(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[194,5,7,8,13],{ /***/ "+ua5": /*!************************************************!*\ !*** ./src/components/monaco-editor/index.css ***! \************************************************/ /*! no static exports found */ /*! ModuleConcatenation bailout: Module is not an ECMAScript module */ /***/ (function(module, exports, __webpack_require__) { // extracted by mini-css-extract-plugin /***/ }), /***/ "+vTd": /*!******************************************************************!*\ !*** ./src/pages/Problemset/components/Topic/index.less?modules ***! \******************************************************************/ /*! no static exports found */ /*! exports used: default */ /*! ModuleConcatenation bailout: Module is not an ECMAScript module */ /***/ (function(module, exports, __webpack_require__) { // extracted by mini-css-extract-plugin module.exports = {"flex_box_center":"flex_box_center___37CPQ","flex_space_between":"flex_space_between___1yzV5","flex_box_vertical_center":"flex_box_vertical_center___2QH_C","flex_box_center_end":"flex_box_center_end___22kLi","flex_box_column":"flex_box_column___1Y3On","line":"line___-rzSr","b1":"b1___1zz_c","b2":"b2___1dAOW","list":"list___1gpez","title":"title___21uOv","tr":"tr___3kTJL","itemDetail":"itemDetail___8QmqJ","answerWrapper":"answerWrapper___3guKO","decoration":"decoration___1rcYW","row":"row___3uQSh","typeRow":"typeRow___ADZSj","type":"type___2pfNZ","typeName":"typeName___8ZhPv","typeIcon":"typeIcon___1Xniv","unpublished":"unpublished___dTXTI","private":"private___XQiDx","public":"public___iIFou","reviewFlag":"reviewFlag___YP4vk","typeRightAction":"typeRightAction___1PQjp","actionLink":"actionLink___2E5q_","actionIcon":"actionIcon___GCvNK","topicTitle":"topicTitle___3fJds","topicTitleContent":"topicTitleContent___35cf9","judgmentContent":"judgmentContent___SU5rV","programContent":"programContent___3G6-D","otherContent":"otherContent___1JHnX","combinationContent":"combinationContent___6ZXO-","con":"con___1_qCl","otherContentItem":"otherContentItem___18WrV","otehrContentHtml":"otehrContentHtml___LW3nV","difficultyRow":"difficultyRow___3HvT0","updateTimeRow":"updateTimeRow___1dNd0","updateTimeWrap":"updateTimeWrap___2PKks","updateTimeContent":"updateTimeContent___1mNBy","programLanguage":"programLanguage___3CnaJ","updateTimeRowAction":"updateTimeRowAction___1DaMt","bottomAction":"bottomAction___Y-BNC","borderColorBlue":"borderColorBlue___2Xd-0","borderColorRed":"borderColorRed___2zA_q","borderColorFFF":"borderColorFFF___2R5-5","borderColorGray":"borderColorGray___nZnDe","selectIcon":"selectIcon___2byLd","colorGreen":"colorGreen___1iOKR","parseAnswerBorder":"parseAnswerBorder___1LTYn","answer":"answer___2L9lv","answerHtml":"answerHtml___3zrOk","parse":"parse___3d3dm","parseText":"parseText___1C_VL","parseAnswer":"parseAnswer___QMVPC","parseAnswerHtml":"parseAnswerHtml___2TCVz","actionBar":"actionBar___2ItMN","know":"know___y8QKK","menu":"menu___SYdg7","bottom":"bottom___2dFIa","textBtn":"textBtn___1y00f"}; /***/ }), /***/ "+z73": /*!*******************************************************************!*\ !*** ./src/pages/Problemset/components/Crumbs/index.less?modules ***! \*******************************************************************/ /*! no static exports found */ /*! exports used: default */ /*! ModuleConcatenation bailout: Module is not an ECMAScript module */ /***/ (function(module, exports, __webpack_require__) { // extracted by mini-css-extract-plugin module.exports = {"flex_box_center":"flex_box_center___3WSrc","flex_space_between":"flex_space_between___1fpCp","flex_box_vertical_center":"flex_box_vertical_center___3Wy8W","flex_box_center_end":"flex_box_center_end___3YIs2","flex_box_column":"flex_box_column___3CNwR","pWrap":"pWrap___2jVbQ","few":"few___3Eebn"}; /***/ }), /***/ "1vnw": /*!**********************************************************************!*\ !*** ./src/pages/Problemset/components/NewFolder/index.less?modules ***! \**********************************************************************/ /*! no static exports found */ /*! exports used: default */ /*! ModuleConcatenation bailout: Module is not an ECMAScript module */ /***/ (function(module, exports, __webpack_require__) { // extracted by mini-css-extract-plugin module.exports = {"list":"list___1dAFk","btns":"btns___1YCLO","name":"name___2XX_F","folderWrapper":"folderWrapper___3sKHr","folderIcon":"folderIcon___Rov4k"}; /***/ }), /***/ "5VLF": /*!**********************************************!*\ !*** ./node_modules/js-beautify/js/index.js ***! \**********************************************/ /*! no static exports found */ /*! exports used: default */ /*! ModuleConcatenation bailout: Module is not an ECMAScript module */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*jshint node:true */ /* globals define */ /* The MIT License (MIT) Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. Permission 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE 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. */ /** The following batches are equivalent: var beautify_js = require('js-beautify'); var beautify_js = require('js-beautify').js; var beautify_js = require('js-beautify').js_beautify; var beautify_css = require('js-beautify').css; var beautify_css = require('js-beautify').css_beautify; var beautify_html = require('js-beautify').html; var beautify_html = require('js-beautify').html_beautify; All methods returned accept two arguments, the source string and an options object. **/ function get_beautify(js_beautify, css_beautify, html_beautify) { // the default is js var beautify = function(src, config) { return js_beautify.js_beautify(src, config); }; // short aliases beautify.js = js_beautify.js_beautify; beautify.css = css_beautify.css_beautify; beautify.html = html_beautify.html_beautify; // legacy aliases beautify.js_beautify = js_beautify.js_beautify; beautify.css_beautify = css_beautify.css_beautify; beautify.html_beautify = html_beautify.html_beautify; return beautify; } if (true) { // Add support for AMD ( https://github.com/amdjs/amdjs-api/wiki/AMD#defineamd-property- ) !(__WEBPACK_AMD_DEFINE_ARRAY__ = [ __webpack_require__(/*! ./lib/beautify */ "6UM0"), __webpack_require__(/*! ./lib/beautify-css */ "TXwP"), __webpack_require__(/*! ./lib/beautify-html */ "psGv") ], __WEBPACK_AMD_DEFINE_RESULT__ = (function(js_beautify, css_beautify, html_beautify) { return get_beautify(js_beautify, css_beautify, html_beautify); }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else {} /***/ }), /***/ "6+eU": /*!************************************************************!*\ !*** ./node_modules/rc-pagination/es/index.js + 4 modules ***! \************************************************************/ /*! exports provided: default */ /*! exports used: default */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/classCallCheck.js */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/createClass.js */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/createSuper.js */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/defineProperty.js */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/extends.js */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/inherits.js */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/objectSpread2.js */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/classnames/index.js (<- Module is not an ECMAScript module) */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-pagination/es/locale/zh_CN.js */ /*! ModuleConcatenation bailout: Cannot concat with external "window.React" (<- Module is not an ECMAScript module) */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; // EXPORTS __webpack_require__.d(__webpack_exports__, "a", function() { return /* reexport */ es_Pagination; }); // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/extends.js var esm_extends = __webpack_require__("wx14"); // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/defineProperty.js var defineProperty = __webpack_require__("rePB"); // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/objectSpread2.js var objectSpread2 = __webpack_require__("VTBJ"); // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/classCallCheck.js var classCallCheck = __webpack_require__("1OyB"); // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/createClass.js var createClass = __webpack_require__("vuIU"); // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/inherits.js var inherits = __webpack_require__("Ji7U"); // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/createSuper.js + 1 modules var createSuper = __webpack_require__("LK+K"); // EXTERNAL MODULE: external "window.React" var external_window_React_ = __webpack_require__("cDcd"); var external_window_React_default = /*#__PURE__*/__webpack_require__.n(external_window_React_); // EXTERNAL MODULE: ./node_modules/classnames/index.js var classnames = __webpack_require__("TSYQ"); var classnames_default = /*#__PURE__*/__webpack_require__.n(classnames); // CONCATENATED MODULE: ./node_modules/rc-pagination/es/Pager.js /* eslint react/prop-types: 0 */ var Pager_Pager = function Pager(props) { var _classNames; var prefixCls = "".concat(props.rootPrefixCls, "-item"); var cls = classnames_default()(prefixCls, "".concat(prefixCls, "-").concat(props.page), (_classNames = {}, Object(defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-active"), props.active), Object(defineProperty["a" /* default */])(_classNames, props.className, !!props.className), Object(defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-disabled"), !props.page), _classNames)); var handleClick = function handleClick() { props.onClick(props.page); }; var handleKeyPress = function handleKeyPress(e) { props.onKeyPress(e, props.onClick, props.page); }; return /*#__PURE__*/external_window_React_default.a.createElement("li", { title: props.showTitle ? props.page : null, className: cls, onClick: handleClick, onKeyPress: handleKeyPress, tabIndex: "0" }, props.itemRender(props.page, 'page', /*#__PURE__*/external_window_React_default.a.createElement("a", { rel: "nofollow" }, props.page))); }; /* harmony default export */ var es_Pager = (Pager_Pager); // CONCATENATED MODULE: ./node_modules/rc-pagination/es/KeyCode.js /* harmony default export */ var KeyCode = ({ ZERO: 48, NINE: 57, NUMPAD_ZERO: 96, NUMPAD_NINE: 105, BACKSPACE: 8, DELETE: 46, ENTER: 13, ARROW_UP: 38, ARROW_DOWN: 40 }); // CONCATENATED MODULE: ./node_modules/rc-pagination/es/Options.js /* eslint react/prop-types: 0 */ var Options_Options = /*#__PURE__*/function (_React$Component) { Object(inherits["a" /* default */])(Options, _React$Component); var _super = Object(createSuper["a" /* default */])(Options); function Options() { var _this; Object(classCallCheck["a" /* default */])(this, Options); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _super.call.apply(_super, [this].concat(args)); _this.state = { goInputText: '' }; _this.buildOptionText = function (value) { return "".concat(value, " ").concat(_this.props.locale.items_per_page); }; _this.changeSize = function (value) { _this.props.changeSize(Number(value)); }; _this.handleChange = function (e) { _this.setState({ goInputText: e.target.value }); }; _this.handleBlur = function (e) { var _this$props = _this.props, goButton = _this$props.goButton, quickGo = _this$props.quickGo, rootPrefixCls = _this$props.rootPrefixCls; var goInputText = _this.state.goInputText; if (goButton || goInputText === '') { return; } if (e.relatedTarget && (e.relatedTarget.className.indexOf("".concat(rootPrefixCls, "-prev")) >= 0 || e.relatedTarget.className.indexOf("".concat(rootPrefixCls, "-next")) >= 0)) { return; } _this.setState({ goInputText: '' }); quickGo(_this.getValidValue()); }; _this.go = function (e) { var goInputText = _this.state.goInputText; if (goInputText === '') { return; } if (e.keyCode === KeyCode.ENTER || e.type === 'click') { _this.setState({ goInputText: '' }); _this.props.quickGo(_this.getValidValue()); } }; return _this; } Object(createClass["a" /* default */])(Options, [{ key: "getValidValue", value: function getValidValue() { var _this$state = this.state, goInputText = _this$state.goInputText, current = _this$state.current; // eslint-disable-next-line no-restricted-globals return !goInputText || isNaN(goInputText) ? current : Number(goInputText); } }, { key: "getPageSizeOptions", value: function getPageSizeOptions() { var _this$props2 = this.props, pageSize = _this$props2.pageSize, pageSizeOptions = _this$props2.pageSizeOptions; if (pageSizeOptions.some(function (option) { return option.toString() === pageSize.toString(); })) { return pageSizeOptions; } return pageSizeOptions.concat([pageSize.toString()]).sort(function (a, b) { // eslint-disable-next-line no-restricted-globals var numberA = isNaN(Number(a)) ? 0 : Number(a); // eslint-disable-next-line no-restricted-globals var numberB = isNaN(Number(b)) ? 0 : Number(b); return numberA - numberB; }); } }, { key: "render", value: function render() { var _this2 = this; var _this$props3 = this.props, pageSize = _this$props3.pageSize, locale = _this$props3.locale, rootPrefixCls = _this$props3.rootPrefixCls, changeSize = _this$props3.changeSize, quickGo = _this$props3.quickGo, goButton = _this$props3.goButton, selectComponentClass = _this$props3.selectComponentClass, buildOptionText = _this$props3.buildOptionText, selectPrefixCls = _this$props3.selectPrefixCls, disabled = _this$props3.disabled; var goInputText = this.state.goInputText; var prefixCls = "".concat(rootPrefixCls, "-options"); var Select = selectComponentClass; var changeSelect = null; var goInput = null; var gotoButton = null; if (!changeSize && !quickGo) { return null; } var pageSizeOptions = this.getPageSizeOptions(); if (changeSize && Select) { var options = pageSizeOptions.map(function (opt, i) { return /*#__PURE__*/external_window_React_default.a.createElement(Select.Option, { key: i, value: opt.toString() }, (buildOptionText || _this2.buildOptionText)(opt)); }); changeSelect = /*#__PURE__*/external_window_React_default.a.createElement(Select, { disabled: disabled, prefixCls: selectPrefixCls, showSearch: false, className: "".concat(prefixCls, "-size-changer"), optionLabelProp: "children", dropdownMatchSelectWidth: false, value: (pageSize || pageSizeOptions[0]).toString(), onChange: this.changeSize, getPopupContainer: function getPopupContainer(triggerNode) { return triggerNode.parentNode; } }, options); } if (quickGo) { if (goButton) { gotoButton = typeof goButton === 'boolean' ? /*#__PURE__*/external_window_React_default.a.createElement("button", { type: "button", onClick: this.go, onKeyUp: this.go, disabled: disabled, className: "".concat(prefixCls, "-quick-jumper-button") }, locale.jump_to_confirm) : /*#__PURE__*/external_window_React_default.a.createElement("span", { onClick: this.go, onKeyUp: this.go }, goButton); } goInput = /*#__PURE__*/external_window_React_default.a.createElement("div", { className: "".concat(prefixCls, "-quick-jumper") }, locale.jump_to, /*#__PURE__*/external_window_React_default.a.createElement("input", { disabled: disabled, type: "text", value: goInputText, onChange: this.handleChange, onKeyUp: this.go, onBlur: this.handleBlur }), locale.page, gotoButton); } return /*#__PURE__*/external_window_React_default.a.createElement("li", { className: "".concat(prefixCls) }, changeSelect, goInput); } }]); return Options; }(external_window_React_default.a.Component); Options_Options.defaultProps = { pageSizeOptions: ['10', '20', '50', '100'] }; /* harmony default export */ var es_Options = (Options_Options); // EXTERNAL MODULE: ./node_modules/rc-pagination/es/locale/zh_CN.js var zh_CN = __webpack_require__("N2Kk"); // CONCATENATED MODULE: ./node_modules/rc-pagination/es/Pagination.js /* eslint react/prop-types: 0 */ function noop() {} function isInteger(value) { return (// eslint-disable-next-line no-restricted-globals typeof value === 'number' && isFinite(value) && Math.floor(value) === value ); } function defaultItemRender(page, type, element) { return element; } function calculatePage(p, state, props) { var pageSize = typeof p === 'undefined' ? state.pageSize : p; return Math.floor((props.total - 1) / pageSize) + 1; } var Pagination_Pagination = /*#__PURE__*/function (_React$Component) { Object(inherits["a" /* default */])(Pagination, _React$Component); var _super = Object(createSuper["a" /* default */])(Pagination); function Pagination(props) { var _this; Object(classCallCheck["a" /* default */])(this, Pagination); _this = _super.call(this, props); _this.getJumpPrevPage = function () { return Math.max(1, _this.state.current - (_this.props.showLessItems ? 3 : 5)); }; _this.getJumpNextPage = function () { return Math.min(calculatePage(undefined, _this.state, _this.props), _this.state.current + (_this.props.showLessItems ? 3 : 5)); }; _this.getItemIcon = function (icon, label) { var prefixCls = _this.props.prefixCls; var iconNode = icon || /*#__PURE__*/external_window_React_default.a.createElement("button", { type: "button", "aria-label": label, className: "".concat(prefixCls, "-item-link") }); if (typeof icon === 'function') { iconNode = external_window_React_default.a.createElement(icon, Object(objectSpread2["a" /* default */])({}, _this.props)); } return iconNode; }; _this.savePaginationNode = function (node) { _this.paginationNode = node; }; _this.isValid = function (page) { return isInteger(page) && page !== _this.state.current; }; _this.shouldDisplayQuickJumper = function () { var _this$props = _this.props, showQuickJumper = _this$props.showQuickJumper, pageSize = _this$props.pageSize, total = _this$props.total; if (total <= pageSize) { return false; } return showQuickJumper; }; _this.handleKeyDown = function (e) { if (e.keyCode === KeyCode.ARROW_UP || e.keyCode === KeyCode.ARROW_DOWN) { e.preventDefault(); } }; _this.handleKeyUp = function (e) { var value = _this.getValidValue(e); var currentInputValue = _this.state.currentInputValue; if (value !== currentInputValue) { _this.setState({ currentInputValue: value }); } if (e.keyCode === KeyCode.ENTER) { _this.handleChange(value); } else if (e.keyCode === KeyCode.ARROW_UP) { _this.handleChange(value - 1); } else if (e.keyCode === KeyCode.ARROW_DOWN) { _this.handleChange(value + 1); } }; _this.changePageSize = function (size) { var current = _this.state.current; var newCurrent = calculatePage(size, _this.state, _this.props); current = current > newCurrent ? newCurrent : current; // fix the issue: // Once 'total' is 0, 'current' in 'onShowSizeChange' is 0, which is not correct. if (newCurrent === 0) { // eslint-disable-next-line prefer-destructuring current = _this.state.current; } if (typeof size === 'number') { if (!('pageSize' in _this.props)) { _this.setState({ pageSize: size }); } if (!('current' in _this.props)) { _this.setState({ current: current, currentInputValue: current }); } } _this.props.onShowSizeChange(current, size); if ('onChange' in _this.props && _this.props.onChange) { _this.props.onChange(current, size); } }; _this.handleChange = function (p) { var disabled = _this.props.disabled; var page = p; if (_this.isValid(page) && !disabled) { var currentPage = calculatePage(undefined, _this.state, _this.props); if (page > currentPage) { page = currentPage; } else if (page < 1) { page = 1; } if (!('current' in _this.props)) { _this.setState({ current: page, currentInputValue: page }); } var pageSize = _this.state.pageSize; _this.props.onChange(page, pageSize); return page; } return _this.state.current; }; _this.prev = function () { if (_this.hasPrev()) { _this.handleChange(_this.state.current - 1); } }; _this.next = function () { if (_this.hasNext()) { _this.handleChange(_this.state.current + 1); } }; _this.jumpPrev = function () { _this.handleChange(_this.getJumpPrevPage()); }; _this.jumpNext = function () { _this.handleChange(_this.getJumpNextPage()); }; _this.hasPrev = function () { return _this.state.current > 1; }; _this.hasNext = function () { return _this.state.current < calculatePage(undefined, _this.state, _this.props); }; _this.runIfEnter = function (event, callback) { if (event.key === 'Enter' || event.charCode === 13) { for (var _len = arguments.length, restParams = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { restParams[_key - 2] = arguments[_key]; } callback.apply(void 0, restParams); } }; _this.runIfEnterPrev = function (e) { _this.runIfEnter(e, _this.prev); }; _this.runIfEnterNext = function (e) { _this.runIfEnter(e, _this.next); }; _this.runIfEnterJumpPrev = function (e) { _this.runIfEnter(e, _this.jumpPrev); }; _this.runIfEnterJumpNext = function (e) { _this.runIfEnter(e, _this.jumpNext); }; _this.handleGoTO = function (e) { if (e.keyCode === KeyCode.ENTER || e.type === 'click') { _this.handleChange(_this.state.currentInputValue); } }; var hasOnChange = props.onChange !== noop; var hasCurrent = ('current' in props); if (hasCurrent && !hasOnChange) { // eslint-disable-next-line no-console console.warn('Warning: You provided a `current` prop to a Pagination component without an `onChange` handler. This will render a read-only component.'); } var _current = props.defaultCurrent; if ('current' in props) { // eslint-disable-next-line prefer-destructuring _current = props.current; } var _pageSize = props.defaultPageSize; if ('pageSize' in props) { // eslint-disable-next-line prefer-destructuring _pageSize = props.pageSize; } _current = Math.min(_current, calculatePage(_pageSize, undefined, props)); _this.state = { current: _current, currentInputValue: _current, pageSize: _pageSize }; return _this; } Object(createClass["a" /* default */])(Pagination, [{ key: "componentDidUpdate", value: function componentDidUpdate(prevProps, prevState) { // When current page change, fix focused style of prev item // A hacky solution of https://github.com/ant-design/ant-design/issues/8948 var prefixCls = this.props.prefixCls; if (prevState.current !== this.state.current && this.paginationNode) { var lastCurrentNode = this.paginationNode.querySelector(".".concat(prefixCls, "-item-").concat(prevState.current)); if (lastCurrentNode && document.activeElement === lastCurrentNode) { lastCurrentNode.blur(); } } } }, { key: "getValidValue", value: function getValidValue(e) { var inputValue = e.target.value; var allPages = calculatePage(undefined, this.state, this.props); var currentInputValue = this.state.currentInputValue; var value; if (inputValue === '') { value = inputValue; // eslint-disable-next-line no-restricted-globals } else if (isNaN(Number(inputValue))) { value = currentInputValue; } else if (inputValue >= allPages) { value = allPages; } else { value = Number(inputValue); } return value; } }, { key: "getShowSizeChanger", value: function getShowSizeChanger() { var _this$props2 = this.props, showSizeChanger = _this$props2.showSizeChanger, total = _this$props2.total, totalBoundaryShowSizeChanger = _this$props2.totalBoundaryShowSizeChanger; if (typeof showSizeChanger !== 'undefined') { return showSizeChanger; } return total > totalBoundaryShowSizeChanger; } }, { key: "renderPrev", value: function renderPrev(prevPage) { var _this$props3 = this.props, prevIcon = _this$props3.prevIcon, itemRender = _this$props3.itemRender; var prevButton = itemRender(prevPage, 'prev', this.getItemIcon(prevIcon, 'prev page')); var disabled = !this.hasPrev(); return Object(external_window_React_["isValidElement"])(prevButton) ? Object(external_window_React_["cloneElement"])(prevButton, { disabled: disabled }) : prevButton; } }, { key: "renderNext", value: function renderNext(nextPage) { var _this$props4 = this.props, nextIcon = _this$props4.nextIcon, itemRender = _this$props4.itemRender; var nextButton = itemRender(nextPage, 'next', this.getItemIcon(nextIcon, 'next page')); var disabled = !this.hasNext(); return Object(external_window_React_["isValidElement"])(nextButton) ? Object(external_window_React_["cloneElement"])(nextButton, { disabled: disabled }) : nextButton; } }, { key: "render", value: function render() { var _this2 = this; var _this$props5 = this.props, prefixCls = _this$props5.prefixCls, className = _this$props5.className, style = _this$props5.style, disabled = _this$props5.disabled, hideOnSinglePage = _this$props5.hideOnSinglePage, total = _this$props5.total, locale = _this$props5.locale, showQuickJumper = _this$props5.showQuickJumper, showLessItems = _this$props5.showLessItems, showTitle = _this$props5.showTitle, showTotal = _this$props5.showTotal, simple = _this$props5.simple, itemRender = _this$props5.itemRender, showPrevNextJumpers = _this$props5.showPrevNextJumpers, jumpPrevIcon = _this$props5.jumpPrevIcon, jumpNextIcon = _this$props5.jumpNextIcon, selectComponentClass = _this$props5.selectComponentClass, selectPrefixCls = _this$props5.selectPrefixCls, pageSizeOptions = _this$props5.pageSizeOptions; var _this$state = this.state, current = _this$state.current, pageSize = _this$state.pageSize, currentInputValue = _this$state.currentInputValue; // When hideOnSinglePage is true and there is only 1 page, hide the pager if (hideOnSinglePage === true && total <= pageSize) { return null; } var allPages = calculatePage(undefined, this.state, this.props); var pagerList = []; var jumpPrev = null; var jumpNext = null; var firstPager = null; var lastPager = null; var gotoButton = null; var goButton = showQuickJumper && showQuickJumper.goButton; var pageBufferSize = showLessItems ? 1 : 2; var prevPage = current - 1 > 0 ? current - 1 : 0; var nextPage = current + 1 < allPages ? current + 1 : allPages; var dataOrAriaAttributeProps = Object.keys(this.props).reduce(function (prev, key) { if (key.substr(0, 5) === 'data-' || key.substr(0, 5) === 'aria-' || key === 'role') { // eslint-disable-next-line no-param-reassign prev[key] = _this2.props[key]; } return prev; }, {}); if (simple) { if (goButton) { if (typeof goButton === 'boolean') { gotoButton = /*#__PURE__*/external_window_React_default.a.createElement("button", { type: "button", onClick: this.handleGoTO, onKeyUp: this.handleGoTO }, locale.jump_to_confirm); } else { gotoButton = /*#__PURE__*/external_window_React_default.a.createElement("span", { onClick: this.handleGoTO, onKeyUp: this.handleGoTO }, goButton); } gotoButton = /*#__PURE__*/external_window_React_default.a.createElement("li", { title: showTitle ? "".concat(locale.jump_to).concat(current, "/").concat(allPages) : null, className: "".concat(prefixCls, "-simple-pager") }, gotoButton); } return /*#__PURE__*/external_window_React_default.a.createElement("ul", Object(esm_extends["a" /* default */])({ className: classnames_default()(prefixCls, "".concat(prefixCls, "-simple"), Object(defineProperty["a" /* default */])({}, "".concat(prefixCls, "-disabled"), disabled), className), style: style, ref: this.savePaginationNode }, dataOrAriaAttributeProps), /*#__PURE__*/external_window_React_default.a.createElement("li", { title: showTitle ? locale.prev_page : null, onClick: this.prev, tabIndex: this.hasPrev() ? 0 : null, onKeyPress: this.runIfEnterPrev, className: classnames_default()("".concat(prefixCls, "-prev"), Object(defineProperty["a" /* default */])({}, "".concat(prefixCls, "-disabled"), !this.hasPrev())), "aria-disabled": !this.hasPrev() }, this.renderPrev(prevPage)), /*#__PURE__*/external_window_React_default.a.createElement("li", { title: showTitle ? "".concat(current, "/").concat(allPages) : null, className: "".concat(prefixCls, "-simple-pager") }, /*#__PURE__*/external_window_React_default.a.createElement("input", { type: "text", value: currentInputValue, disabled: disabled, onKeyDown: this.handleKeyDown, onKeyUp: this.handleKeyUp, onChange: this.handleKeyUp, size: "3" }), /*#__PURE__*/external_window_React_default.a.createElement("span", { className: "".concat(prefixCls, "-slash") }, "/"), allPages), /*#__PURE__*/external_window_React_default.a.createElement("li", { title: showTitle ? locale.next_page : null, onClick: this.next, tabIndex: this.hasPrev() ? 0 : null, onKeyPress: this.runIfEnterNext, className: classnames_default()("".concat(prefixCls, "-next"), Object(defineProperty["a" /* default */])({}, "".concat(prefixCls, "-disabled"), !this.hasNext())), "aria-disabled": !this.hasNext() }, this.renderNext(nextPage)), gotoButton); } if (allPages <= 3 + pageBufferSize * 2) { var pagerProps = { locale: locale, rootPrefixCls: prefixCls, onClick: this.handleChange, onKeyPress: this.runIfEnter, showTitle: showTitle, itemRender: itemRender }; if (!allPages) { pagerList.push( /*#__PURE__*/external_window_React_default.a.createElement(es_Pager, Object(esm_extends["a" /* default */])({}, pagerProps, { key: "noPager", page: allPages, className: "".concat(prefixCls, "-disabled") }))); } for (var i = 1; i <= allPages; i += 1) { var active = current === i; pagerList.push( /*#__PURE__*/external_window_React_default.a.createElement(es_Pager, Object(esm_extends["a" /* default */])({}, pagerProps, { key: i, page: i, active: active }))); } } else { var prevItemTitle = showLessItems ? locale.prev_3 : locale.prev_5; var nextItemTitle = showLessItems ? locale.next_3 : locale.next_5; if (showPrevNextJumpers) { jumpPrev = /*#__PURE__*/external_window_React_default.a.createElement("li", { title: showTitle ? prevItemTitle : null, key: "prev", onClick: this.jumpPrev, tabIndex: "0", onKeyPress: this.runIfEnterJumpPrev, className: classnames_default()("".concat(prefixCls, "-jump-prev"), Object(defineProperty["a" /* default */])({}, "".concat(prefixCls, "-jump-prev-custom-icon"), !!jumpPrevIcon)) }, itemRender(this.getJumpPrevPage(), 'jump-prev', this.getItemIcon(jumpPrevIcon, 'prev page'))); jumpNext = /*#__PURE__*/external_window_React_default.a.createElement("li", { title: showTitle ? nextItemTitle : null, key: "next", tabIndex: "0", onClick: this.jumpNext, onKeyPress: this.runIfEnterJumpNext, className: classnames_default()("".concat(prefixCls, "-jump-next"), Object(defineProperty["a" /* default */])({}, "".concat(prefixCls, "-jump-next-custom-icon"), !!jumpNextIcon)) }, itemRender(this.getJumpNextPage(), 'jump-next', this.getItemIcon(jumpNextIcon, 'next page'))); } lastPager = /*#__PURE__*/external_window_React_default.a.createElement(es_Pager, { locale: locale, last: true, rootPrefixCls: prefixCls, onClick: this.handleChange, onKeyPress: this.runIfEnter, key: allPages, page: allPages, active: false, showTitle: showTitle, itemRender: itemRender }); firstPager = /*#__PURE__*/external_window_React_default.a.createElement(es_Pager, { locale: locale, rootPrefixCls: prefixCls, onClick: this.handleChange, onKeyPress: this.runIfEnter, key: 1, page: 1, active: false, showTitle: showTitle, itemRender: itemRender }); var left = Math.max(1, current - pageBufferSize); var right = Math.min(current + pageBufferSize, allPages); if (current - 1 <= pageBufferSize) { right = 1 + pageBufferSize * 2; } if (allPages - current <= pageBufferSize) { left = allPages - pageBufferSize * 2; } for (var _i = left; _i <= right; _i += 1) { var _active = current === _i; pagerList.push( /*#__PURE__*/external_window_React_default.a.createElement(es_Pager, { locale: locale, rootPrefixCls: prefixCls, onClick: this.handleChange, onKeyPress: this.runIfEnter, key: _i, page: _i, active: _active, showTitle: showTitle, itemRender: itemRender })); } if (current - 1 >= pageBufferSize * 2 && current !== 1 + 2) { pagerList[0] = Object(external_window_React_["cloneElement"])(pagerList[0], { className: "".concat(prefixCls, "-item-after-jump-prev") }); pagerList.unshift(jumpPrev); } if (allPages - current >= pageBufferSize * 2 && current !== allPages - 2) { pagerList[pagerList.length - 1] = Object(external_window_React_["cloneElement"])(pagerList[pagerList.length - 1], { className: "".concat(prefixCls, "-item-before-jump-next") }); pagerList.push(jumpNext); } if (left !== 1) { pagerList.unshift(firstPager); } if (right !== allPages) { pagerList.push(lastPager); } } var totalText = null; if (showTotal) { totalText = /*#__PURE__*/external_window_React_default.a.createElement("li", { className: "".concat(prefixCls, "-total-text") }, showTotal(total, [total === 0 ? 0 : (current - 1) * pageSize + 1, current * pageSize > total ? total : current * pageSize])); } var prevDisabled = !this.hasPrev() || !allPages; var nextDisabled = !this.hasNext() || !allPages; return /*#__PURE__*/external_window_React_default.a.createElement("ul", Object(esm_extends["a" /* default */])({ className: classnames_default()(prefixCls, className, Object(defineProperty["a" /* default */])({}, "".concat(prefixCls, "-disabled"), disabled)), style: style, unselectable: "unselectable", ref: this.savePaginationNode }, dataOrAriaAttributeProps), totalText, /*#__PURE__*/external_window_React_default.a.createElement("li", { title: showTitle ? locale.prev_page : null, onClick: this.prev, tabIndex: prevDisabled ? null : 0, onKeyPress: this.runIfEnterPrev, className: classnames_default()("".concat(prefixCls, "-prev"), Object(defineProperty["a" /* default */])({}, "".concat(prefixCls, "-disabled"), prevDisabled)), "aria-disabled": prevDisabled }, this.renderPrev(prevPage)), pagerList, /*#__PURE__*/external_window_React_default.a.createElement("li", { title: showTitle ? locale.next_page : null, onClick: this.next, tabIndex: nextDisabled ? null : 0, onKeyPress: this.runIfEnterNext, className: classnames_default()("".concat(prefixCls, "-next"), Object(defineProperty["a" /* default */])({}, "".concat(prefixCls, "-disabled"), nextDisabled)), "aria-disabled": nextDisabled }, this.renderNext(nextPage)), /*#__PURE__*/external_window_React_default.a.createElement(es_Options, { disabled: disabled, locale: locale, rootPrefixCls: prefixCls, selectComponentClass: selectComponentClass, selectPrefixCls: selectPrefixCls, changeSize: this.getShowSizeChanger() ? this.changePageSize : null, current: current, pageSize: pageSize, pageSizeOptions: pageSizeOptions, quickGo: this.shouldDisplayQuickJumper() ? this.handleChange : null, goButton: goButton })); } }], [{ key: "getDerivedStateFromProps", value: function getDerivedStateFromProps(props, prevState) { var newState = {}; if ('current' in props) { newState.current = props.current; if (props.current !== prevState.current) { newState.currentInputValue = newState.current; } } if ('pageSize' in props && props.pageSize !== prevState.pageSize) { var current = prevState.current; var newCurrent = calculatePage(props.pageSize, prevState, props); current = current > newCurrent ? newCurrent : current; if (!('current' in props)) { newState.current = current; newState.currentInputValue = current; } newState.pageSize = props.pageSize; } return newState; } }]); return Pagination; }(external_window_React_default.a.Component); Pagination_Pagination.defaultProps = { defaultCurrent: 1, total: 0, defaultPageSize: 10, onChange: noop, className: '', selectPrefixCls: 'rc-select', prefixCls: 'rc-pagination', selectComponentClass: null, hideOnSinglePage: false, showPrevNextJumpers: true, showQuickJumper: false, showLessItems: false, showTitle: true, onShowSizeChange: noop, locale: zh_CN["a" /* default */], style: {}, itemRender: defaultItemRender, totalBoundaryShowSizeChanger: 50 }; /* harmony default export */ var es_Pagination = (Pagination_Pagination); // CONCATENATED MODULE: ./node_modules/rc-pagination/es/index.js /***/ }), /***/ "6UM0": /*!*****************************************************!*\ !*** ./node_modules/js-beautify/js/lib/beautify.js ***! \*****************************************************/ /*! no static exports found */ /*! all exports used */ /*! ModuleConcatenation bailout: Module is not an ECMAScript module */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* AUTO-GENERATED. DO NOT MODIFY. */ /* The MIT License (MIT) Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. Permission 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE 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. JS Beautifier --------------- Written by Einar Lielmanis, https://beautifier.io/ Originally converted to javascript by Vital, "End braces on own line" added by Chris J. Shull, Parsing improvements for brace-less statements by Liam Newman Usage: js_beautify(js_source_text); js_beautify(js_source_text, options); The options are: indent_size (default 4) - indentation size, indent_char (default space) - character to indent with, preserve_newlines (default true) - whether existing line breaks should be preserved, max_preserve_newlines (default unlimited) - maximum number of line breaks to be preserved in one chunk, jslint_happy (default false) - if true, then jslint-stricter mode is enforced. jslint_happy !jslint_happy --------------------------------- function () function() switch () { switch() { case 1: case 1: break; break; } } space_after_anon_function (default false) - should the space before an anonymous function's parens be added, "function()" vs "function ()", NOTE: This option is overriden by jslint_happy (i.e. if jslint_happy is true, space_after_anon_function is true by design) brace_style (default "collapse") - "collapse" | "expand" | "end-expand" | "none" | any of the former + ",preserve-inline" put braces on the same line as control statements (default), or put braces on own line (Allman / ANSI style), or just put end braces on own line, or attempt to keep them where they are. preserve-inline will try to preserve inline blocks of curly braces space_before_conditional (default true) - should the space before conditional statement be added, "if(true)" vs "if (true)", unescape_strings (default false) - should printable characters in strings encoded in \xNN notation be unescaped, "example" vs "\x65\x78\x61\x6d\x70\x6c\x65" wrap_line_length (default unlimited) - lines should wrap at next opportunity after this number of characters. NOTE: This is not a hard limit. Lines will continue until a point where a newline would be preserved if it were present. end_with_newline (default false) - end output with a newline e.g js_beautify(js_source_text, { 'indent_size': 1, 'indent_char': '\t' }); */ (function() { /* GENERATED_BUILD_OUTPUT */ var legacy_beautify_js; /******/ (function() { // webpackBootstrap /******/ "use strict"; /******/ var __webpack_modules__ = ([ /* 0 */ /***/ (function(module, __unused_webpack_exports, __webpack_require__) { /*jshint node:true */ /* The MIT License (MIT) Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. Permission 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE 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. */ var Beautifier = (__webpack_require__(1).Beautifier), Options = (__webpack_require__(5).Options); function js_beautify(js_source_text, options) { var beautifier = new Beautifier(js_source_text, options); return beautifier.beautify(); } module.exports = js_beautify; module.exports.defaultOptions = function() { return new Options(); }; /***/ }), /* 1 */ /***/ (function(module, __unused_webpack_exports, __webpack_require__) { /*jshint node:true */ /* The MIT License (MIT) Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. Permission 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE 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. */ var Output = (__webpack_require__(2).Output); var Token = (__webpack_require__(3).Token); var acorn = __webpack_require__(4); var Options = (__webpack_require__(5).Options); var Tokenizer = (__webpack_require__(7).Tokenizer); var line_starters = (__webpack_require__(7).line_starters); var positionable_operators = (__webpack_require__(7).positionable_operators); var TOKEN = (__webpack_require__(7).TOKEN); function in_array(what, arr) { return arr.indexOf(what) !== -1; } function ltrim(s) { return s.replace(/^\s+/g, ''); } function generateMapFromStrings(list) { var result = {}; for (var x = 0; x < list.length; x++) { // make the mapped names underscored instead of dash result[list[x].replace(/-/g, '_')] = list[x]; } return result; } function reserved_word(token, word) { return token && token.type === TOKEN.RESERVED && token.text === word; } function reserved_array(token, words) { return token && token.type === TOKEN.RESERVED && in_array(token.text, words); } // Unsure of what they mean, but they work. Worth cleaning up in future. var special_words = ['case', 'return', 'do', 'if', 'throw', 'else', 'await', 'break', 'continue', 'async']; var validPositionValues = ['before-newline', 'after-newline', 'preserve-newline']; // Generate map from array var OPERATOR_POSITION = generateMapFromStrings(validPositionValues); var OPERATOR_POSITION_BEFORE_OR_PRESERVE = [OPERATOR_POSITION.before_newline, OPERATOR_POSITION.preserve_newline]; var MODE = { BlockStatement: 'BlockStatement', // 'BLOCK' Statement: 'Statement', // 'STATEMENT' ObjectLiteral: 'ObjectLiteral', // 'OBJECT', ArrayLiteral: 'ArrayLiteral', //'[EXPRESSION]', ForInitializer: 'ForInitializer', //'(FOR-EXPRESSION)', Conditional: 'Conditional', //'(COND-EXPRESSION)', Expression: 'Expression' //'(EXPRESSION)' }; function remove_redundant_indentation(output, frame) { // This implementation is effective but has some issues: // - can cause line wrap to happen too soon due to indent removal // after wrap points are calculated // These issues are minor compared to ugly indentation. if (frame.multiline_frame || frame.mode === MODE.ForInitializer || frame.mode === MODE.Conditional) { return; } // remove one indent from each line inside this section output.remove_indent(frame.start_line_index); } // we could use just string.split, but // IE doesn't like returning empty strings function split_linebreaks(s) { //return s.split(/\x0d\x0a|\x0a/); s = s.replace(acorn.allLineBreaks, '\n'); var out = [], idx = s.indexOf("\n"); while (idx !== -1) { out.push(s.substring(0, idx)); s = s.substring(idx + 1); idx = s.indexOf("\n"); } if (s.length) { out.push(s); } return out; } function is_array(mode) { return mode === MODE.ArrayLiteral; } function is_expression(mode) { return in_array(mode, [MODE.Expression, MODE.ForInitializer, MODE.Conditional]); } function all_lines_start_with(lines, c) { for (var i = 0; i < lines.length; i++) { var line = lines[i].trim(); if (line.charAt(0) !== c) { return false; } } return true; } function each_line_matches_indent(lines, indent) { var i = 0, len = lines.length, line; for (; i < len; i++) { line = lines[i]; // allow empty lines to pass through if (line && line.indexOf(indent) !== 0) { return false; } } return true; } function Beautifier(source_text, options) { options = options || {}; this._source_text = source_text || ''; this._output = null; this._tokens = null; this._last_last_text = null; this._flags = null; this._previous_flags = null; this._flag_store = null; this._options = new Options(options); } Beautifier.prototype.create_flags = function(flags_base, mode) { var next_indent_level = 0; if (flags_base) { next_indent_level = flags_base.indentation_level; if (!this._output.just_added_newline() && flags_base.line_indent_level > next_indent_level) { next_indent_level = flags_base.line_indent_level; } } var next_flags = { mode: mode, parent: flags_base, last_token: flags_base ? flags_base.last_token : new Token(TOKEN.START_BLOCK, ''), // last token text last_word: flags_base ? flags_base.last_word : '', // last TOKEN.WORD passed declaration_statement: false, declaration_assignment: false, multiline_frame: false, inline_frame: false, if_block: false, else_block: false, class_start_block: false, // class A { INSIDE HERE } or class B extends C { INSIDE HERE } do_block: false, do_while: false, import_block: false, in_case_statement: false, // switch(..){ INSIDE HERE } in_case: false, // we're on the exact line with "case 0:" case_body: false, // the indented case-action block case_block: false, // the indented case-action block is wrapped with {} indentation_level: next_indent_level, alignment: 0, line_indent_level: flags_base ? flags_base.line_indent_level : next_indent_level, start_line_index: this._output.get_line_number(), ternary_depth: 0 }; return next_flags; }; Beautifier.prototype._reset = function(source_text) { var baseIndentString = source_text.match(/^[\t ]*/)[0]; this._last_last_text = ''; // pre-last token text this._output = new Output(this._options, baseIndentString); // If testing the ignore directive, start with output disable set to true this._output.raw = this._options.test_output_raw; // Stack of parsing/formatting states, including MODE. // We tokenize, parse, and output in an almost purely a forward-only stream of token input // and formatted output. This makes the beautifier less accurate than full parsers // but also far more tolerant of syntax errors. // // For example, the default mode is MODE.BlockStatement. If we see a '{' we push a new frame of type // MODE.BlockStatement on the the stack, even though it could be object literal. If we later // encounter a ":", we'll switch to to MODE.ObjectLiteral. If we then see a ";", // most full parsers would die, but the beautifier gracefully falls back to // MODE.BlockStatement and continues on. this._flag_store = []; this.set_mode(MODE.BlockStatement); var tokenizer = new Tokenizer(source_text, this._options); this._tokens = tokenizer.tokenize(); return source_text; }; Beautifier.prototype.beautify = function() { // if disabled, return the input unchanged. if (this._options.disabled) { return this._source_text; } var sweet_code; var source_text = this._reset(this._source_text); var eol = this._options.eol; if (this._options.eol === 'auto') { eol = '\n'; if (source_text && acorn.lineBreak.test(source_text || '')) { eol = source_text.match(acorn.lineBreak)[0]; } } var current_token = this._tokens.next(); while (current_token) { this.handle_token(current_token); this._last_last_text = this._flags.last_token.text; this._flags.last_token = current_token; current_token = this._tokens.next(); } sweet_code = this._output.get_code(eol); return sweet_code; }; Beautifier.prototype.handle_token = function(current_token, preserve_statement_flags) { if (current_token.type === TOKEN.START_EXPR) { this.handle_start_expr(current_token); } else if (current_token.type === TOKEN.END_EXPR) { this.handle_end_expr(current_token); } else if (current_token.type === TOKEN.START_BLOCK) { this.handle_start_block(current_token); } else if (current_token.type === TOKEN.END_BLOCK) { this.handle_end_block(current_token); } else if (current_token.type === TOKEN.WORD) { this.handle_word(current_token); } else if (current_token.type === TOKEN.RESERVED) { this.handle_word(current_token); } else if (current_token.type === TOKEN.SEMICOLON) { this.handle_semicolon(current_token); } else if (current_token.type === TOKEN.STRING) { this.handle_string(current_token); } else if (current_token.type === TOKEN.EQUALS) { this.handle_equals(current_token); } else if (current_token.type === TOKEN.OPERATOR) { this.handle_operator(current_token); } else if (current_token.type === TOKEN.COMMA) { this.handle_comma(current_token); } else if (current_token.type === TOKEN.BLOCK_COMMENT) { this.handle_block_comment(current_token, preserve_statement_flags); } else if (current_token.type === TOKEN.COMMENT) { this.handle_comment(current_token, preserve_statement_flags); } else if (current_token.type === TOKEN.DOT) { this.handle_dot(current_token); } else if (current_token.type === TOKEN.EOF) { this.handle_eof(current_token); } else if (current_token.type === TOKEN.UNKNOWN) { this.handle_unknown(current_token, preserve_statement_flags); } else { this.handle_unknown(current_token, preserve_statement_flags); } }; Beautifier.prototype.handle_whitespace_and_comments = function(current_token, preserve_statement_flags) { var newlines = current_token.newlines; var keep_whitespace = this._options.keep_array_indentation && is_array(this._flags.mode); if (current_token.comments_before) { var comment_token = current_token.comments_before.next(); while (comment_token) { // The cleanest handling of inline comments is to treat them as though they aren't there. // Just continue formatting and the behavior should be logical. // Also ignore unknown tokens. Again, this should result in better behavior. this.handle_whitespace_and_comments(comment_token, preserve_statement_flags); this.handle_token(comment_token, preserve_statement_flags); comment_token = current_token.comments_before.next(); } } if (keep_whitespace) { for (var i = 0; i < newlines; i += 1) { this.print_newline(i > 0, preserve_statement_flags); } } else { if (this._options.max_preserve_newlines && newlines > this._options.max_preserve_newlines) { newlines = this._options.max_preserve_newlines; } if (this._options.preserve_newlines) { if (newlines > 1) { this.print_newline(false, preserve_statement_flags); for (var j = 1; j < newlines; j += 1) { this.print_newline(true, preserve_statement_flags); } } } } }; var newline_restricted_tokens = ['async', 'break', 'continue', 'return', 'throw', 'yield']; Beautifier.prototype.allow_wrap_or_preserved_newline = function(current_token, force_linewrap) { force_linewrap = (force_linewrap === undefined) ? false : force_linewrap; // Never wrap the first token on a line if (this._output.just_added_newline()) { return; } var shouldPreserveOrForce = (this._options.preserve_newlines && current_token.newlines) || force_linewrap; var operatorLogicApplies = in_array(this._flags.last_token.text, positionable_operators) || in_array(current_token.text, positionable_operators); if (operatorLogicApplies) { var shouldPrintOperatorNewline = ( in_array(this._flags.last_token.text, positionable_operators) && in_array(this._options.operator_position, OPERATOR_POSITION_BEFORE_OR_PRESERVE) ) || in_array(current_token.text, positionable_operators); shouldPreserveOrForce = shouldPreserveOrForce && shouldPrintOperatorNewline; } if (shouldPreserveOrForce) { this.print_newline(false, true); } else if (this._options.wrap_line_length) { if (reserved_array(this._flags.last_token, newline_restricted_tokens)) { // These tokens should never have a newline inserted // between them and the following expression. return; } this._output.set_wrap_point(); } }; Beautifier.prototype.print_newline = function(force_newline, preserve_statement_flags) { if (!preserve_statement_flags) { if (this._flags.last_token.text !== ';' && this._flags.last_token.text !== ',' && this._flags.last_token.text !== '=' && (this._flags.last_token.type !== TOKEN.OPERATOR || this._flags.last_token.text === '--' || this._flags.last_token.text === '++')) { var next_token = this._tokens.peek(); while (this._flags.mode === MODE.Statement && !(this._flags.if_block && reserved_word(next_token, 'else')) && !this._flags.do_block) { this.restore_mode(); } } } if (this._output.add_new_line(force_newline)) { this._flags.multiline_frame = true; } }; Beautifier.prototype.print_token_line_indentation = function(current_token) { if (this._output.just_added_newline()) { if (this._options.keep_array_indentation && current_token.newlines && (current_token.text === '[' || is_array(this._flags.mode))) { this._output.current_line.set_indent(-1); this._output.current_line.push(current_token.whitespace_before); this._output.space_before_token = false; } else if (this._output.set_indent(this._flags.indentation_level, this._flags.alignment)) { this._flags.line_indent_level = this._flags.indentation_level; } } }; Beautifier.prototype.print_token = function(current_token) { if (this._output.raw) { this._output.add_raw_token(current_token); return; } if (this._options.comma_first && current_token.previous && current_token.previous.type === TOKEN.COMMA && this._output.just_added_newline()) { if (this._output.previous_line.last() === ',') { var popped = this._output.previous_line.pop(); // if the comma was already at the start of the line, // pull back onto that line and reprint the indentation if (this._output.previous_line.is_empty()) { this._output.previous_line.push(popped); this._output.trim(true); this._output.current_line.pop(); this._output.trim(); } // add the comma in front of the next token this.print_token_line_indentation(current_token); this._output.add_token(','); this._output.space_before_token = true; } } this.print_token_line_indentation(current_token); this._output.non_breaking_space = true; this._output.add_token(current_token.text); if (this._output.previous_token_wrapped) { this._flags.multiline_frame = true; } }; Beautifier.prototype.indent = function() { this._flags.indentation_level += 1; this._output.set_indent(this._flags.indentation_level, this._flags.alignment); }; Beautifier.prototype.deindent = function() { if (this._flags.indentation_level > 0 && ((!this._flags.parent) || this._flags.indentation_level > this._flags.parent.indentation_level)) { this._flags.indentation_level -= 1; this._output.set_indent(this._flags.indentation_level, this._flags.alignment); } }; Beautifier.prototype.set_mode = function(mode) { if (this._flags) { this._flag_store.push(this._flags); this._previous_flags = this._flags; } else { this._previous_flags = this.create_flags(null, mode); } this._flags = this.create_flags(this._previous_flags, mode); this._output.set_indent(this._flags.indentation_level, this._flags.alignment); }; Beautifier.prototype.restore_mode = function() { if (this._flag_store.length > 0) { this._previous_flags = this._flags; this._flags = this._flag_store.pop(); if (this._previous_flags.mode === MODE.Statement) { remove_redundant_indentation(this._output, this._previous_flags); } this._output.set_indent(this._flags.indentation_level, this._flags.alignment); } }; Beautifier.prototype.start_of_object_property = function() { return this._flags.parent.mode === MODE.ObjectLiteral && this._flags.mode === MODE.Statement && ( (this._flags.last_token.text === ':' && this._flags.ternary_depth === 0) || (reserved_array(this._flags.last_token, ['get', 'set']))); }; Beautifier.prototype.start_of_statement = function(current_token) { var start = false; start = start || reserved_array(this._flags.last_token, ['var', 'let', 'const']) && current_token.type === TOKEN.WORD; start = start || reserved_word(this._flags.last_token, 'do'); start = start || (!(this._flags.parent.mode === MODE.ObjectLiteral && this._flags.mode === MODE.Statement)) && reserved_array(this._flags.last_token, newline_restricted_tokens) && !current_token.newlines; start = start || reserved_word(this._flags.last_token, 'else') && !(reserved_word(current_token, 'if') && !current_token.comments_before); start = start || (this._flags.last_token.type === TOKEN.END_EXPR && (this._previous_flags.mode === MODE.ForInitializer || this._previous_flags.mode === MODE.Conditional)); start = start || (this._flags.last_token.type === TOKEN.WORD && this._flags.mode === MODE.BlockStatement && !this._flags.in_case && !(current_token.text === '--' || current_token.text === '++') && this._last_last_text !== 'function' && current_token.type !== TOKEN.WORD && current_token.type !== TOKEN.RESERVED); start = start || (this._flags.mode === MODE.ObjectLiteral && ( (this._flags.last_token.text === ':' && this._flags.ternary_depth === 0) || reserved_array(this._flags.last_token, ['get', 'set']))); if (start) { this.set_mode(MODE.Statement); this.indent(); this.handle_whitespace_and_comments(current_token, true); // Issue #276: // If starting a new statement with [if, for, while, do], push to a new line. // if (a) if (b) if(c) d(); else e(); else f(); if (!this.start_of_object_property()) { this.allow_wrap_or_preserved_newline(current_token, reserved_array(current_token, ['do', 'for', 'if', 'while'])); } return true; } return false; }; Beautifier.prototype.handle_start_expr = function(current_token) { // The conditional starts the statement if appropriate. if (!this.start_of_statement(current_token)) { this.handle_whitespace_and_comments(current_token); } var next_mode = MODE.Expression; if (current_token.text === '[') { if (this._flags.last_token.type === TOKEN.WORD || this._flags.last_token.text === ')') { // this is array index specifier, break immediately // a[x], fn()[x] if (reserved_array(this._flags.last_token, line_starters)) { this._output.space_before_token = true; } this.print_token(current_token); this.set_mode(next_mode); this.indent(); if (this._options.space_in_paren) { this._output.space_before_token = true; } return; } next_mode = MODE.ArrayLiteral; if (is_array(this._flags.mode)) { if (this._flags.last_token.text === '[' || (this._flags.last_token.text === ',' && (this._last_last_text === ']' || this._last_last_text === '}'))) { // ], [ goes to new line // }, [ goes to new line if (!this._options.keep_array_indentation) { this.print_newline(); } } } if (!in_array(this._flags.last_token.type, [TOKEN.START_EXPR, TOKEN.END_EXPR, TOKEN.WORD, TOKEN.OPERATOR, TOKEN.DOT])) { this._output.space_before_token = true; } } else { if (this._flags.last_token.type === TOKEN.RESERVED) { if (this._flags.last_token.text === 'for') { this._output.space_before_token = this._options.space_before_conditional; next_mode = MODE.ForInitializer; } else if (in_array(this._flags.last_token.text, ['if', 'while', 'switch'])) { this._output.space_before_token = this._options.space_before_conditional; next_mode = MODE.Conditional; } else if (in_array(this._flags.last_word, ['await', 'async'])) { // Should be a space between await and an IIFE, or async and an arrow function this._output.space_before_token = true; } else if (this._flags.last_token.text === 'import' && current_token.whitespace_before === '') { this._output.space_before_token = false; } else if (in_array(this._flags.last_token.text, line_starters) || this._flags.last_token.text === 'catch') { this._output.space_before_token = true; } } else if (this._flags.last_token.type === TOKEN.EQUALS || this._flags.last_token.type === TOKEN.OPERATOR) { // Support of this kind of newline preservation. // a = (b && // (c || d)); if (!this.start_of_object_property()) { this.allow_wrap_or_preserved_newline(current_token); } } else if (this._flags.last_token.type === TOKEN.WORD) { this._output.space_before_token = false; // function name() vs function name () // function* name() vs function* name () // async name() vs async name () // In ES6, you can also define the method properties of an object // var obj = {a: function() {}} // It can be abbreviated // var obj = {a() {}} // var obj = { a() {}} vs var obj = { a () {}} // var obj = { * a() {}} vs var obj = { * a () {}} var peek_back_two = this._tokens.peek(-3); if (this._options.space_after_named_function && peek_back_two) { // peek starts at next character so -1 is current token var peek_back_three = this._tokens.peek(-4); if (reserved_array(peek_back_two, ['async', 'function']) || (peek_back_two.text === '*' && reserved_array(peek_back_three, ['async', 'function']))) { this._output.space_before_token = true; } else if (this._flags.mode === MODE.ObjectLiteral) { if ((peek_back_two.text === '{' || peek_back_two.text === ',') || (peek_back_two.text === '*' && (peek_back_three.text === '{' || peek_back_three.text === ','))) { this._output.space_before_token = true; } } else if (this._flags.parent && this._flags.parent.class_start_block) { this._output.space_before_token = true; } } } else { // Support preserving wrapped arrow function expressions // a.b('c', // () => d.e // ) this.allow_wrap_or_preserved_newline(current_token); } // function() vs function () // yield*() vs yield* () // function*() vs function* () if ((this._flags.last_token.type === TOKEN.RESERVED && (this._flags.last_word === 'function' || this._flags.last_word === 'typeof')) || (this._flags.last_token.text === '*' && (in_array(this._last_last_text, ['function', 'yield']) || (this._flags.mode === MODE.ObjectLiteral && in_array(this._last_last_text, ['{', ',']))))) { this._output.space_before_token = this._options.space_after_anon_function; } } if (this._flags.last_token.text === ';' || this._flags.last_token.type === TOKEN.START_BLOCK) { this.print_newline(); } else if (this._flags.last_token.type === TOKEN.END_EXPR || this._flags.last_token.type === TOKEN.START_EXPR || this._flags.last_token.type === TOKEN.END_BLOCK || this._flags.last_token.text === '.' || this._flags.last_token.type === TOKEN.COMMA) { // do nothing on (( and )( and ][ and ]( and .( // TODO: Consider whether forcing this is required. Review failing tests when removed. this.allow_wrap_or_preserved_newline(current_token, current_token.newlines); } this.print_token(current_token); this.set_mode(next_mode); if (this._options.space_in_paren) { this._output.space_before_token = true; } // In all cases, if we newline while inside an expression it should be indented. this.indent(); }; Beautifier.prototype.handle_end_expr = function(current_token) { // statements inside expressions are not valid syntax, but... // statements must all be closed when their container closes while (this._flags.mode === MODE.Statement) { this.restore_mode(); } this.handle_whitespace_and_comments(current_token); if (this._flags.multiline_frame) { this.allow_wrap_or_preserved_newline(current_token, current_token.text === ']' && is_array(this._flags.mode) && !this._options.keep_array_indentation); } if (this._options.space_in_paren) { if (this._flags.last_token.type === TOKEN.START_EXPR && !this._options.space_in_empty_paren) { // () [] no inner space in empty parens like these, ever, ref #320 this._output.trim(); this._output.space_before_token = false; } else { this._output.space_before_token = true; } } this.deindent(); this.print_token(current_token); this.restore_mode(); remove_redundant_indentation(this._output, this._previous_flags); // do {} while () // no statement required after if (this._flags.do_while && this._previous_flags.mode === MODE.Conditional) { this._previous_flags.mode = MODE.Expression; this._flags.do_block = false; this._flags.do_while = false; } }; Beautifier.prototype.handle_start_block = function(current_token) { this.handle_whitespace_and_comments(current_token); // Check if this is should be treated as a ObjectLiteral var next_token = this._tokens.peek(); var second_token = this._tokens.peek(1); if (this._flags.last_word === 'switch' && this._flags.last_token.type === TOKEN.END_EXPR) { this.set_mode(MODE.BlockStatement); this._flags.in_case_statement = true; } else if (this._flags.case_body) { this.set_mode(MODE.BlockStatement); } else if (second_token && ( (in_array(second_token.text, [':', ',']) && in_array(next_token.type, [TOKEN.STRING, TOKEN.WORD, TOKEN.RESERVED])) || (in_array(next_token.text, ['get', 'set', '...']) && in_array(second_token.type, [TOKEN.WORD, TOKEN.RESERVED])) )) { // We don't support TypeScript,but we didn't break it for a very long time. // We'll try to keep not breaking it. if (in_array(this._last_last_text, ['class', 'interface']) && !in_array(second_token.text, [':', ','])) { this.set_mode(MODE.BlockStatement); } else { this.set_mode(MODE.ObjectLiteral); } } else if (this._flags.last_token.type === TOKEN.OPERATOR && this._flags.last_token.text === '=>') { // arrow function: (param1, paramN) => { statements } this.set_mode(MODE.BlockStatement); } else if (in_array(this._flags.last_token.type, [TOKEN.EQUALS, TOKEN.START_EXPR, TOKEN.COMMA, TOKEN.OPERATOR]) || reserved_array(this._flags.last_token, ['return', 'throw', 'import', 'default']) ) { // Detecting shorthand function syntax is difficult by scanning forward, // so check the surrounding context. // If the block is being returned, imported, export default, passed as arg, // assigned with = or assigned in a nested object, treat as an ObjectLiteral. this.set_mode(MODE.ObjectLiteral); } else { this.set_mode(MODE.BlockStatement); } if (this._flags.last_token) { if (reserved_array(this._flags.last_token.previous, ['class', 'extends'])) { this._flags.class_start_block = true; } } var empty_braces = !next_token.comments_before && next_token.text === '}'; var empty_anonymous_function = empty_braces && this._flags.last_word === 'function' && this._flags.last_token.type === TOKEN.END_EXPR; if (this._options.brace_preserve_inline) // check for inline, set inline_frame if so { // search forward for a newline wanted inside this block var index = 0; var check_token = null; this._flags.inline_frame = true; do { index += 1; check_token = this._tokens.peek(index - 1); if (check_token.newlines) { this._flags.inline_frame = false; break; } } while (check_token.type !== TOKEN.EOF && !(check_token.type === TOKEN.END_BLOCK && check_token.opened === current_token)); } if ((this._options.brace_style === "expand" || (this._options.brace_style === "none" && current_token.newlines)) && !this._flags.inline_frame) { if (this._flags.last_token.type !== TOKEN.OPERATOR && (empty_anonymous_function || this._flags.last_token.type === TOKEN.EQUALS || (reserved_array(this._flags.last_token, special_words) && this._flags.last_token.text !== 'else'))) { this._output.space_before_token = true; } else { this.print_newline(false, true); } } else { // collapse || inline_frame if (is_array(this._previous_flags.mode) && (this._flags.last_token.type === TOKEN.START_EXPR || this._flags.last_token.type === TOKEN.COMMA)) { if (this._flags.last_token.type === TOKEN.COMMA || this._options.space_in_paren) { this._output.space_before_token = true; } if (this._flags.last_token.type === TOKEN.COMMA || (this._flags.last_token.type === TOKEN.START_EXPR && this._flags.inline_frame)) { this.allow_wrap_or_preserved_newline(current_token); this._previous_flags.multiline_frame = this._previous_flags.multiline_frame || this._flags.multiline_frame; this._flags.multiline_frame = false; } } if (this._flags.last_token.type !== TOKEN.OPERATOR && this._flags.last_token.type !== TOKEN.START_EXPR) { if (this._flags.last_token.type === TOKEN.START_BLOCK && !this._flags.inline_frame) { this.print_newline(); } else { this._output.space_before_token = true; } } } this.print_token(current_token); this.indent(); // Except for specific cases, open braces are followed by a new line. if (!empty_braces && !(this._options.brace_preserve_inline && this._flags.inline_frame)) { this.print_newline(); } }; Beautifier.prototype.handle_end_block = function(current_token) { // statements must all be closed when their container closes this.handle_whitespace_and_comments(current_token); while (this._flags.mode === MODE.Statement) { this.restore_mode(); } var empty_braces = this._flags.last_token.type === TOKEN.START_BLOCK; if (this._flags.inline_frame && !empty_braces) { // try inline_frame (only set if this._options.braces-preserve-inline) first this._output.space_before_token = true; } else if (this._options.brace_style === "expand") { if (!empty_braces) { this.print_newline(); } } else { // skip {} if (!empty_braces) { if (is_array(this._flags.mode) && this._options.keep_array_indentation) { // we REALLY need a newline here, but newliner would skip that this._options.keep_array_indentation = false; this.print_newline(); this._options.keep_array_indentation = true; } else { this.print_newline(); } } } this.restore_mode(); this.print_token(current_token); }; Beautifier.prototype.handle_word = function(current_token) { if (current_token.type === TOKEN.RESERVED) { if (in_array(current_token.text, ['set', 'get']) && this._flags.mode !== MODE.ObjectLiteral) { current_token.type = TOKEN.WORD; } else if (current_token.text === 'import' && in_array(this._tokens.peek().text, ['(', '.'])) { current_token.type = TOKEN.WORD; } else if (in_array(current_token.text, ['as', 'from']) && !this._flags.import_block) { current_token.type = TOKEN.WORD; } else if (this._flags.mode === MODE.ObjectLiteral) { var next_token = this._tokens.peek(); if (next_token.text === ':') { current_token.type = TOKEN.WORD; } } } if (this.start_of_statement(current_token)) { // The conditional starts the statement if appropriate. if (reserved_array(this._flags.last_token, ['var', 'let', 'const']) && current_token.type === TOKEN.WORD) { this._flags.declaration_statement = true; } } else if (current_token.newlines && !is_expression(this._flags.mode) && (this._flags.last_token.type !== TOKEN.OPERATOR || (this._flags.last_token.text === '--' || this._flags.last_token.text === '++')) && this._flags.last_token.type !== TOKEN.EQUALS && (this._options.preserve_newlines || !reserved_array(this._flags.last_token, ['var', 'let', 'const', 'set', 'get']))) { this.handle_whitespace_and_comments(current_token); this.print_newline(); } else { this.handle_whitespace_and_comments(current_token); } if (this._flags.do_block && !this._flags.do_while) { if (reserved_word(current_token, 'while')) { // do {} ## while () this._output.space_before_token = true; this.print_token(current_token); this._output.space_before_token = true; this._flags.do_while = true; return; } else { // do {} should always have while as the next word. // if we don't see the expected while, recover this.print_newline(); this._flags.do_block = false; } } // if may be followed by else, or not // Bare/inline ifs are tricky // Need to unwind the modes correctly: if (a) if (b) c(); else d(); else e(); if (this._flags.if_block) { if (!this._flags.else_block && reserved_word(current_token, 'else')) { this._flags.else_block = true; } else { while (this._flags.mode === MODE.Statement) { this.restore_mode(); } this._flags.if_block = false; this._flags.else_block = false; } } if (this._flags.in_case_statement && reserved_array(current_token, ['case', 'default'])) { this.print_newline(); if (!this._flags.case_block && (this._flags.case_body || this._options.jslint_happy)) { // switch cases following one another this.deindent(); } this._flags.case_body = false; this.print_token(current_token); this._flags.in_case = true; return; } if (this._flags.last_token.type === TOKEN.COMMA || this._flags.last_token.type === TOKEN.START_EXPR || this._flags.last_token.type === TOKEN.EQUALS || this._flags.last_token.type === TOKEN.OPERATOR) { if (!this.start_of_object_property()) { this.allow_wrap_or_preserved_newline(current_token); } } if (reserved_word(current_token, 'function')) { if (in_array(this._flags.last_token.text, ['}', ';']) || (this._output.just_added_newline() && !(in_array(this._flags.last_token.text, ['(', '[', '{', ':', '=', ',']) || this._flags.last_token.type === TOKEN.OPERATOR))) { // make sure there is a nice clean space of at least one blank line // before a new function definition if (!this._output.just_added_blankline() && !current_token.comments_before) { this.print_newline(); this.print_newline(true); } } if (this._flags.last_token.type === TOKEN.RESERVED || this._flags.last_token.type === TOKEN.WORD) { if (reserved_array(this._flags.last_token, ['get', 'set', 'new', 'export']) || reserved_array(this._flags.last_token, newline_restricted_tokens)) { this._output.space_before_token = true; } else if (reserved_word(this._flags.last_token, 'default') && this._last_last_text === 'export') { this._output.space_before_token = true; } else if (this._flags.last_token.text === 'declare') { // accomodates Typescript declare function formatting this._output.space_before_token = true; } else { this.print_newline(); } } else if (this._flags.last_token.type === TOKEN.OPERATOR || this._flags.last_token.text === '=') { // foo = function this._output.space_before_token = true; } else if (!this._flags.multiline_frame && (is_expression(this._flags.mode) || is_array(this._flags.mode))) { // (function } else { this.print_newline(); } this.print_token(current_token); this._flags.last_word = current_token.text; return; } var prefix = 'NONE'; if (this._flags.last_token.type === TOKEN.END_BLOCK) { if (this._previous_flags.inline_frame) { prefix = 'SPACE'; } else if (!reserved_array(current_token, ['else', 'catch', 'finally', 'from'])) { prefix = 'NEWLINE'; } else { if (this._options.brace_style === "expand" || this._options.brace_style === "end-expand" || (this._options.brace_style === "none" && current_token.newlines)) { prefix = 'NEWLINE'; } else { prefix = 'SPACE'; this._output.space_before_token = true; } } } else if (this._flags.last_token.type === TOKEN.SEMICOLON && this._flags.mode === MODE.BlockStatement) { // TODO: Should this be for STATEMENT as well? prefix = 'NEWLINE'; } else if (this._flags.last_token.type === TOKEN.SEMICOLON && is_expression(this._flags.mode)) { prefix = 'SPACE'; } else if (this._flags.last_token.type === TOKEN.STRING) { prefix = 'NEWLINE'; } else if (this._flags.last_token.type === TOKEN.RESERVED || this._flags.last_token.type === TOKEN.WORD || (this._flags.last_token.text === '*' && (in_array(this._last_last_text, ['function', 'yield']) || (this._flags.mode === MODE.ObjectLiteral && in_array(this._last_last_text, ['{', ',']))))) { prefix = 'SPACE'; } else if (this._flags.last_token.type === TOKEN.START_BLOCK) { if (this._flags.inline_frame) { prefix = 'SPACE'; } else { prefix = 'NEWLINE'; } } else if (this._flags.last_token.type === TOKEN.END_EXPR) { this._output.space_before_token = true; prefix = 'NEWLINE'; } if (reserved_array(current_token, line_starters) && this._flags.last_token.text !== ')') { if (this._flags.inline_frame || this._flags.last_token.text === 'else' || this._flags.last_token.text === 'export') { prefix = 'SPACE'; } else { prefix = 'NEWLINE'; } } if (reserved_array(current_token, ['else', 'catch', 'finally'])) { if ((!(this._flags.last_token.type === TOKEN.END_BLOCK && this._previous_flags.mode === MODE.BlockStatement) || this._options.brace_style === "expand" || this._options.brace_style === "end-expand" || (this._options.brace_style === "none" && current_token.newlines)) && !this._flags.inline_frame) { this.print_newline(); } else { this._output.trim(true); var line = this._output.current_line; // If we trimmed and there's something other than a close block before us // put a newline back in. Handles '} // comment' scenario. if (line.last() !== '}') { this.print_newline(); } this._output.space_before_token = true; } } else if (prefix === 'NEWLINE') { if (reserved_array(this._flags.last_token, special_words)) { // no newline between 'return nnn' this._output.space_before_token = true; } else if (this._flags.last_token.text === 'declare' && reserved_array(current_token, ['var', 'let', 'const'])) { // accomodates Typescript declare formatting this._output.space_before_token = true; } else if (this._flags.last_token.type !== TOKEN.END_EXPR) { if ((this._flags.last_token.type !== TOKEN.START_EXPR || !reserved_array(current_token, ['var', 'let', 'const'])) && this._flags.last_token.text !== ':') { // no need to force newline on 'var': for (var x = 0...) if (reserved_word(current_token, 'if') && reserved_word(current_token.previous, 'else')) { // no newline for } else if { this._output.space_before_token = true; } else { this.print_newline(); } } } else if (reserved_array(current_token, line_starters) && this._flags.last_token.text !== ')') { this.print_newline(); } } else if (this._flags.multiline_frame && is_array(this._flags.mode) && this._flags.last_token.text === ',' && this._last_last_text === '}') { this.print_newline(); // }, in lists get a newline treatment } else if (prefix === 'SPACE') { this._output.space_before_token = true; } if (current_token.previous && (current_token.previous.type === TOKEN.WORD || current_token.previous.type === TOKEN.RESERVED)) { this._output.space_before_token = true; } this.print_token(current_token); this._flags.last_word = current_token.text; if (current_token.type === TOKEN.RESERVED) { if (current_token.text === 'do') { this._flags.do_block = true; } else if (current_token.text === 'if') { this._flags.if_block = true; } else if (current_token.text === 'import') { this._flags.import_block = true; } else if (this._flags.import_block && reserved_word(current_token, 'from')) { this._flags.import_block = false; } } }; Beautifier.prototype.handle_semicolon = function(current_token) { if (this.start_of_statement(current_token)) { // The conditional starts the statement if appropriate. // Semicolon can be the start (and end) of a statement this._output.space_before_token = false; } else { this.handle_whitespace_and_comments(current_token); } var next_token = this._tokens.peek(); while (this._flags.mode === MODE.Statement && !(this._flags.if_block && reserved_word(next_token, 'else')) && !this._flags.do_block) { this.restore_mode(); } // hacky but effective for the moment if (this._flags.import_block) { this._flags.import_block = false; } this.print_token(current_token); }; Beautifier.prototype.handle_string = function(current_token) { if (current_token.text.startsWith("`") && current_token.newlines === 0 && current_token.whitespace_before === '' && (current_token.previous.text === ')' || this._flags.last_token.type === TOKEN.WORD)) { //Conditional for detectign backtick strings } else if (this.start_of_statement(current_token)) { // The conditional starts the statement if appropriate. // One difference - strings want at least a space before this._output.space_before_token = true; } else { this.handle_whitespace_and_comments(current_token); if (this._flags.last_token.type === TOKEN.RESERVED || this._flags.last_token.type === TOKEN.WORD || this._flags.inline_frame) { this._output.space_before_token = true; } else if (this._flags.last_token.type === TOKEN.COMMA || this._flags.last_token.type === TOKEN.START_EXPR || this._flags.last_token.type === TOKEN.EQUALS || this._flags.last_token.type === TOKEN.OPERATOR) { if (!this.start_of_object_property()) { this.allow_wrap_or_preserved_newline(current_token); } } else if ((current_token.text.startsWith("`") && this._flags.last_token.type === TOKEN.END_EXPR && (current_token.previous.text === ']' || current_token.previous.text === ')') && current_token.newlines === 0)) { this._output.space_before_token = true; } else { this.print_newline(); } } this.print_token(current_token); }; Beautifier.prototype.handle_equals = function(current_token) { if (this.start_of_statement(current_token)) { // The conditional starts the statement if appropriate. } else { this.handle_whitespace_and_comments(current_token); } if (this._flags.declaration_statement) { // just got an '=' in a var-line, different formatting/line-breaking, etc will now be done this._flags.declaration_assignment = true; } this._output.space_before_token = true; this.print_token(current_token); this._output.space_before_token = true; }; Beautifier.prototype.handle_comma = function(current_token) { this.handle_whitespace_and_comments(current_token, true); this.print_token(current_token); this._output.space_before_token = true; if (this._flags.declaration_statement) { if (is_expression(this._flags.parent.mode)) { // do not break on comma, for(var a = 1, b = 2) this._flags.declaration_assignment = false; } if (this._flags.declaration_assignment) { this._flags.declaration_assignment = false; this.print_newline(false, true); } else if (this._options.comma_first) { // for comma-first, we want to allow a newline before the comma // to turn into a newline after the comma, which we will fixup later this.allow_wrap_or_preserved_newline(current_token); } } else if (this._flags.mode === MODE.ObjectLiteral || (this._flags.mode === MODE.Statement && this._flags.parent.mode === MODE.ObjectLiteral)) { if (this._flags.mode === MODE.Statement) { this.restore_mode(); } if (!this._flags.inline_frame) { this.print_newline(); } } else if (this._options.comma_first) { // EXPR or DO_BLOCK // for comma-first, we want to allow a newline before the comma // to turn into a newline after the comma, which we will fixup later this.allow_wrap_or_preserved_newline(current_token); } }; Beautifier.prototype.handle_operator = function(current_token) { var isGeneratorAsterisk = current_token.text === '*' && (reserved_array(this._flags.last_token, ['function', 'yield']) || (in_array(this._flags.last_token.type, [TOKEN.START_BLOCK, TOKEN.COMMA, TOKEN.END_BLOCK, TOKEN.SEMICOLON])) ); var isUnary = in_array(current_token.text, ['-', '+']) && ( in_array(this._flags.last_token.type, [TOKEN.START_BLOCK, TOKEN.START_EXPR, TOKEN.EQUALS, TOKEN.OPERATOR]) || in_array(this._flags.last_token.text, line_starters) || this._flags.last_token.text === ',' ); if (this.start_of_statement(current_token)) { // The conditional starts the statement if appropriate. } else { var preserve_statement_flags = !isGeneratorAsterisk; this.handle_whitespace_and_comments(current_token, preserve_statement_flags); } // hack for actionscript's import .*; if (current_token.text === '*' && this._flags.last_token.type === TOKEN.DOT) { this.print_token(current_token); return; } if (current_token.text === '::') { // no spaces around exotic namespacing syntax operator this.print_token(current_token); return; } // Allow line wrapping between operators when operator_position is // set to before or preserve if (this._flags.last_token.type === TOKEN.OPERATOR && in_array(this._options.operator_position, OPERATOR_POSITION_BEFORE_OR_PRESERVE)) { this.allow_wrap_or_preserved_newline(current_token); } if (current_token.text === ':' && this._flags.in_case) { this.print_token(current_token); this._flags.in_case = false; this._flags.case_body = true; if (this._tokens.peek().type !== TOKEN.START_BLOCK) { this.indent(); this.print_newline(); this._flags.case_block = false; } else { this._flags.case_block = true; this._output.space_before_token = true; } return; } var space_before = true; var space_after = true; var in_ternary = false; if (current_token.text === ':') { if (this._flags.ternary_depth === 0) { // Colon is invalid javascript outside of ternary and object, but do our best to guess what was meant. space_before = false; } else { this._flags.ternary_depth -= 1; in_ternary = true; } } else if (current_token.text === '?') { this._flags.ternary_depth += 1; } // let's handle the operator_position option prior to any conflicting logic if (!isUnary && !isGeneratorAsterisk && this._options.preserve_newlines && in_array(current_token.text, positionable_operators)) { var isColon = current_token.text === ':'; var isTernaryColon = (isColon && in_ternary); var isOtherColon = (isColon && !in_ternary); switch (this._options.operator_position) { case OPERATOR_POSITION.before_newline: // if the current token is : and it's not a ternary statement then we set space_before to false this._output.space_before_token = !isOtherColon; this.print_token(current_token); if (!isColon || isTernaryColon) { this.allow_wrap_or_preserved_newline(current_token); } this._output.space_before_token = true; return; case OPERATOR_POSITION.after_newline: // if the current token is anything but colon, or (via deduction) it's a colon and in a ternary statement, // then print a newline. this._output.space_before_token = true; if (!isColon || isTernaryColon) { if (this._tokens.peek().newlines) { this.print_newline(false, true); } else { this.allow_wrap_or_preserved_newline(current_token); } } else { this._output.space_before_token = false; } this.print_token(current_token); this._output.space_before_token = true; return; case OPERATOR_POSITION.preserve_newline: if (!isOtherColon) { this.allow_wrap_or_preserved_newline(current_token); } // if we just added a newline, or the current token is : and it's not a ternary statement, // then we set space_before to false space_before = !(this._output.just_added_newline() || isOtherColon); this._output.space_before_token = space_before; this.print_token(current_token); this._output.space_before_token = true; return; } } if (isGeneratorAsterisk) { this.allow_wrap_or_preserved_newline(current_token); space_before = false; var next_token = this._tokens.peek(); space_after = next_token && in_array(next_token.type, [TOKEN.WORD, TOKEN.RESERVED]); } else if (current_token.text === '...') { this.allow_wrap_or_preserved_newline(current_token); space_before = this._flags.last_token.type === TOKEN.START_BLOCK; space_after = false; } else if (in_array(current_token.text, ['--', '++', '!', '~']) || isUnary) { // unary operators (and binary +/- pretending to be unary) special cases if (this._flags.last_token.type === TOKEN.COMMA || this._flags.last_token.type === TOKEN.START_EXPR) { this.allow_wrap_or_preserved_newline(current_token); } space_before = false; space_after = false; // http://www.ecma-international.org/ecma-262/5.1/#sec-7.9.1 // if there is a newline between -- or ++ and anything else we should preserve it. if (current_token.newlines && (current_token.text === '--' || current_token.text === '++' || current_token.text === '~')) { var new_line_needed = reserved_array(this._flags.last_token, special_words) && current_token.newlines; if (new_line_needed && (this._previous_flags.if_block || this._previous_flags.else_block)) { this.restore_mode(); } this.print_newline(new_line_needed, true); } if (this._flags.last_token.text === ';' && is_expression(this._flags.mode)) { // for (;; ++i) // ^^^ space_before = true; } if (this._flags.last_token.type === TOKEN.RESERVED) { space_before = true; } else if (this._flags.last_token.type === TOKEN.END_EXPR) { space_before = !(this._flags.last_token.text === ']' && (current_token.text === '--' || current_token.text === '++')); } else if (this._flags.last_token.type === TOKEN.OPERATOR) { // a++ + ++b; // a - -b space_before = in_array(current_token.text, ['--', '-', '++', '+']) && in_array(this._flags.last_token.text, ['--', '-', '++', '+']); // + and - are not unary when preceeded by -- or ++ operator // a-- + b // a * +b // a - -b if (in_array(current_token.text, ['+', '-']) && in_array(this._flags.last_token.text, ['--', '++'])) { space_after = true; } } if (((this._flags.mode === MODE.BlockStatement && !this._flags.inline_frame) || this._flags.mode === MODE.Statement) && (this._flags.last_token.text === '{' || this._flags.last_token.text === ';')) { // { foo; --i } // foo(); --bar; this.print_newline(); } } this._output.space_before_token = this._output.space_before_token || space_before; this.print_token(current_token); this._output.space_before_token = space_after; }; Beautifier.prototype.handle_block_comment = function(current_token, preserve_statement_flags) { if (this._output.raw) { this._output.add_raw_token(current_token); if (current_token.directives && current_token.directives.preserve === 'end') { // If we're testing the raw output behavior, do not allow a directive to turn it off. this._output.raw = this._options.test_output_raw; } return; } if (current_token.directives) { this.print_newline(false, preserve_statement_flags); this.print_token(current_token); if (current_token.directives.preserve === 'start') { this._output.raw = true; } this.print_newline(false, true); return; } // inline block if (!acorn.newline.test(current_token.text) && !current_token.newlines) { this._output.space_before_token = true; this.print_token(current_token); this._output.space_before_token = true; return; } else { this.print_block_commment(current_token, preserve_statement_flags); } }; Beautifier.prototype.print_block_commment = function(current_token, preserve_statement_flags) { var lines = split_linebreaks(current_token.text); var j; // iterator for this case var javadoc = false; var starless = false; var lastIndent = current_token.whitespace_before; var lastIndentLength = lastIndent.length; // block comment starts with a new line this.print_newline(false, preserve_statement_flags); // first line always indented this.print_token_line_indentation(current_token); this._output.add_token(lines[0]); this.print_newline(false, preserve_statement_flags); if (lines.length > 1) { lines = lines.slice(1); javadoc = all_lines_start_with(lines, '*'); starless = each_line_matches_indent(lines, lastIndent); if (javadoc) { this._flags.alignment = 1; } for (j = 0; j < lines.length; j++) { if (javadoc) { // javadoc: reformat and re-indent this.print_token_line_indentation(current_token); this._output.add_token(ltrim(lines[j])); } else if (starless && lines[j]) { // starless: re-indent non-empty content, avoiding trim this.print_token_line_indentation(current_token); this._output.add_token(lines[j].substring(lastIndentLength)); } else { // normal comments output raw this._output.current_line.set_indent(-1); this._output.add_token(lines[j]); } // for comments on their own line or more than one line, make sure there's a new line after this.print_newline(false, preserve_statement_flags); } this._flags.alignment = 0; } }; Beautifier.prototype.handle_comment = function(current_token, preserve_statement_flags) { if (current_token.newlines) { this.print_newline(false, preserve_statement_flags); } else { this._output.trim(true); } this._output.space_before_token = true; this.print_token(current_token); this.print_newline(false, preserve_statement_flags); }; Beautifier.prototype.handle_dot = function(current_token) { if (this.start_of_statement(current_token)) { // The conditional starts the statement if appropriate. } else { this.handle_whitespace_and_comments(current_token, true); } if (this._flags.last_token.text.match('^[0-9]+$')) { this._output.space_before_token = true; } if (reserved_array(this._flags.last_token, special_words)) { this._output.space_before_token = false; } else { // allow preserved newlines before dots in general // force newlines on dots after close paren when break_chained - for bar().baz() this.allow_wrap_or_preserved_newline(current_token, this._flags.last_token.text === ')' && this._options.break_chained_methods); } // Only unindent chained method dot if this dot starts a new line. // Otherwise the automatic extra indentation removal will handle the over indent if (this._options.unindent_chained_methods && this._output.just_added_newline()) { this.deindent(); } this.print_token(current_token); }; Beautifier.prototype.handle_unknown = function(current_token, preserve_statement_flags) { this.print_token(current_token); if (current_token.text[current_token.text.length - 1] === '\n') { this.print_newline(false, preserve_statement_flags); } }; Beautifier.prototype.handle_eof = function(current_token) { // Unwind any open statements while (this._flags.mode === MODE.Statement) { this.restore_mode(); } this.handle_whitespace_and_comments(current_token); }; module.exports.Beautifier = Beautifier; /***/ }), /* 2 */ /***/ (function(module) { /*jshint node:true */ /* The MIT License (MIT) Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. Permission 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE 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. */ function OutputLine(parent) { this.__parent = parent; this.__character_count = 0; // use indent_count as a marker for this.__lines that have preserved indentation this.__indent_count = -1; this.__alignment_count = 0; this.__wrap_point_index = 0; this.__wrap_point_character_count = 0; this.__wrap_point_indent_count = -1; this.__wrap_point_alignment_count = 0; this.__items = []; } OutputLine.prototype.clone_empty = function() { var line = new OutputLine(this.__parent); line.set_indent(this.__indent_count, this.__alignment_count); return line; }; OutputLine.prototype.item = function(index) { if (index < 0) { return this.__items[this.__items.length + index]; } else { return this.__items[index]; } }; OutputLine.prototype.has_match = function(pattern) { for (var lastCheckedOutput = this.__items.length - 1; lastCheckedOutput >= 0; lastCheckedOutput--) { if (this.__items[lastCheckedOutput].match(pattern)) { return true; } } return false; }; OutputLine.prototype.set_indent = function(indent, alignment) { if (this.is_empty()) { this.__indent_count = indent || 0; this.__alignment_count = alignment || 0; this.__character_count = this.__parent.get_indent_size(this.__indent_count, this.__alignment_count); } }; OutputLine.prototype._set_wrap_point = function() { if (this.__parent.wrap_line_length) { this.__wrap_point_index = this.__items.length; this.__wrap_point_character_count = this.__character_count; this.__wrap_point_indent_count = this.__parent.next_line.__indent_count; this.__wrap_point_alignment_count = this.__parent.next_line.__alignment_count; } }; OutputLine.prototype._should_wrap = function() { return this.__wrap_point_index && this.__character_count > this.__parent.wrap_line_length && this.__wrap_point_character_count > this.__parent.next_line.__character_count; }; OutputLine.prototype._allow_wrap = function() { if (this._should_wrap()) { this.__parent.add_new_line(); var next = this.__parent.current_line; next.set_indent(this.__wrap_point_indent_count, this.__wrap_point_alignment_count); next.__items = this.__items.slice(this.__wrap_point_index); this.__items = this.__items.slice(0, this.__wrap_point_index); next.__character_count += this.__character_count - this.__wrap_point_character_count; this.__character_count = this.__wrap_point_character_count; if (next.__items[0] === " ") { next.__items.splice(0, 1); next.__character_count -= 1; } return true; } return false; }; OutputLine.prototype.is_empty = function() { return this.__items.length === 0; }; OutputLine.prototype.last = function() { if (!this.is_empty()) { return this.__items[this.__items.length - 1]; } else { return null; } }; OutputLine.prototype.push = function(item) { this.__items.push(item); var last_newline_index = item.lastIndexOf('\n'); if (last_newline_index !== -1) { this.__character_count = item.length - last_newline_index; } else { this.__character_count += item.length; } }; OutputLine.prototype.pop = function() { var item = null; if (!this.is_empty()) { item = this.__items.pop(); this.__character_count -= item.length; } return item; }; OutputLine.prototype._remove_indent = function() { if (this.__indent_count > 0) { this.__indent_count -= 1; this.__character_count -= this.__parent.indent_size; } }; OutputLine.prototype._remove_wrap_indent = function() { if (this.__wrap_point_indent_count > 0) { this.__wrap_point_indent_count -= 1; } }; OutputLine.prototype.trim = function() { while (this.last() === ' ') { this.__items.pop(); this.__character_count -= 1; } }; OutputLine.prototype.toString = function() { var result = ''; if (this.is_empty()) { if (this.__parent.indent_empty_lines) { result = this.__parent.get_indent_string(this.__indent_count); } } else { result = this.__parent.get_indent_string(this.__indent_count, this.__alignment_count); result += this.__items.join(''); } return result; }; function IndentStringCache(options, baseIndentString) { this.__cache = ['']; this.__indent_size = options.indent_size; this.__indent_string = options.indent_char; if (!options.indent_with_tabs) { this.__indent_string = new Array(options.indent_size + 1).join(options.indent_char); } // Set to null to continue support for auto detection of base indent baseIndentString = baseIndentString || ''; if (options.indent_level > 0) { baseIndentString = new Array(options.indent_level + 1).join(this.__indent_string); } this.__base_string = baseIndentString; this.__base_string_length = baseIndentString.length; } IndentStringCache.prototype.get_indent_size = function(indent, column) { var result = this.__base_string_length; column = column || 0; if (indent < 0) { result = 0; } result += indent * this.__indent_size; result += column; return result; }; IndentStringCache.prototype.get_indent_string = function(indent_level, column) { var result = this.__base_string; column = column || 0; if (indent_level < 0) { indent_level = 0; result = ''; } column += indent_level * this.__indent_size; this.__ensure_cache(column); result += this.__cache[column]; return result; }; IndentStringCache.prototype.__ensure_cache = function(column) { while (column >= this.__cache.length) { this.__add_column(); } }; IndentStringCache.prototype.__add_column = function() { var column = this.__cache.length; var indent = 0; var result = ''; if (this.__indent_size && column >= this.__indent_size) { indent = Math.floor(column / this.__indent_size); column -= indent * this.__indent_size; result = new Array(indent + 1).join(this.__indent_string); } if (column) { result += new Array(column + 1).join(' '); } this.__cache.push(result); }; function Output(options, baseIndentString) { this.__indent_cache = new IndentStringCache(options, baseIndentString); this.raw = false; this._end_with_newline = options.end_with_newline; this.indent_size = options.indent_size; this.wrap_line_length = options.wrap_line_length; this.indent_empty_lines = options.indent_empty_lines; this.__lines = []; this.previous_line = null; this.current_line = null; this.next_line = new OutputLine(this); this.space_before_token = false; this.non_breaking_space = false; this.previous_token_wrapped = false; // initialize this.__add_outputline(); } Output.prototype.__add_outputline = function() { this.previous_line = this.current_line; this.current_line = this.next_line.clone_empty(); this.__lines.push(this.current_line); }; Output.prototype.get_line_number = function() { return this.__lines.length; }; Output.prototype.get_indent_string = function(indent, column) { return this.__indent_cache.get_indent_string(indent, column); }; Output.prototype.get_indent_size = function(indent, column) { return this.__indent_cache.get_indent_size(indent, column); }; Output.prototype.is_empty = function() { return !this.previous_line && this.current_line.is_empty(); }; Output.prototype.add_new_line = function(force_newline) { // never newline at the start of file // otherwise, newline only if we didn't just add one or we're forced if (this.is_empty() || (!force_newline && this.just_added_newline())) { return false; } // if raw output is enabled, don't print additional newlines, // but still return True as though you had if (!this.raw) { this.__add_outputline(); } return true; }; Output.prototype.get_code = function(eol) { this.trim(true); // handle some edge cases where the last tokens // has text that ends with newline(s) var last_item = this.current_line.pop(); if (last_item) { if (last_item[last_item.length - 1] === '\n') { last_item = last_item.replace(/\n+$/g, ''); } this.current_line.push(last_item); } if (this._end_with_newline) { this.__add_outputline(); } var sweet_code = this.__lines.join('\n'); if (eol !== '\n') { sweet_code = sweet_code.replace(/[\n]/g, eol); } return sweet_code; }; Output.prototype.set_wrap_point = function() { this.current_line._set_wrap_point(); }; Output.prototype.set_indent = function(indent, alignment) { indent = indent || 0; alignment = alignment || 0; // Next line stores alignment values this.next_line.set_indent(indent, alignment); // Never indent your first output indent at the start of the file if (this.__lines.length > 1) { this.current_line.set_indent(indent, alignment); return true; } this.current_line.set_indent(); return false; }; Output.prototype.add_raw_token = function(token) { for (var x = 0; x < token.newlines; x++) { this.__add_outputline(); } this.current_line.set_indent(-1); this.current_line.push(token.whitespace_before); this.current_line.push(token.text); this.space_before_token = false; this.non_breaking_space = false; this.previous_token_wrapped = false; }; Output.prototype.add_token = function(printable_token) { this.__add_space_before_token(); this.current_line.push(printable_token); this.space_before_token = false; this.non_breaking_space = false; this.previous_token_wrapped = this.current_line._allow_wrap(); }; Output.prototype.__add_space_before_token = function() { if (this.space_before_token && !this.just_added_newline()) { if (!this.non_breaking_space) { this.set_wrap_point(); } this.current_line.push(' '); } }; Output.prototype.remove_indent = function(index) { var output_length = this.__lines.length; while (index < output_length) { this.__lines[index]._remove_indent(); index++; } this.current_line._remove_wrap_indent(); }; Output.prototype.trim = function(eat_newlines) { eat_newlines = (eat_newlines === undefined) ? false : eat_newlines; this.current_line.trim(); while (eat_newlines && this.__lines.length > 1 && this.current_line.is_empty()) { this.__lines.pop(); this.current_line = this.__lines[this.__lines.length - 1]; this.current_line.trim(); } this.previous_line = this.__lines.length > 1 ? this.__lines[this.__lines.length - 2] : null; }; Output.prototype.just_added_newline = function() { return this.current_line.is_empty(); }; Output.prototype.just_added_blankline = function() { return this.is_empty() || (this.current_line.is_empty() && this.previous_line.is_empty()); }; Output.prototype.ensure_empty_line_above = function(starts_with, ends_with) { var index = this.__lines.length - 2; while (index >= 0) { var potentialEmptyLine = this.__lines[index]; if (potentialEmptyLine.is_empty()) { break; } else if (potentialEmptyLine.item(0).indexOf(starts_with) !== 0 && potentialEmptyLine.item(-1) !== ends_with) { this.__lines.splice(index + 1, 0, new OutputLine(this)); this.previous_line = this.__lines[this.__lines.length - 2]; break; } index--; } }; module.exports.Output = Output; /***/ }), /* 3 */ /***/ (function(module) { /*jshint node:true */ /* The MIT License (MIT) Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. Permission 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE 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. */ function Token(type, text, newlines, whitespace_before) { this.type = type; this.text = text; // comments_before are // comments that have a new line before them // and may or may not have a newline after // this is a set of comments before this.comments_before = null; /* inline comment*/ // this.comments_after = new TokenStream(); // no new line before and newline after this.newlines = newlines || 0; this.whitespace_before = whitespace_before || ''; this.parent = null; this.next = null; this.previous = null; this.opened = null; this.closed = null; this.directives = null; } module.exports.Token = Token; /***/ }), /* 4 */ /***/ (function(__unused_webpack_module, exports) { /* jshint node: true, curly: false */ // Parts of this section of code is taken from acorn. // // Acorn was written by Marijn Haverbeke and released under an MIT // license. The Unicode regexps (for identifiers and whitespace) were // taken from [Esprima](http://esprima.org) by Ariya Hidayat. // // Git repositories for Acorn are available at // // http://marijnhaverbeke.nl/git/acorn // https://github.com/marijnh/acorn.git // ## Character categories // acorn used char codes to squeeze the last bit of performance out // Beautifier is okay without that, so we're using regex // permit # (23), $ (36), and @ (64). @ is used in ES7 decorators. // 65 through 91 are uppercase letters. // permit _ (95). // 97 through 123 are lowercase letters. var baseASCIIidentifierStartChars = "\\x23\\x24\\x40\\x41-\\x5a\\x5f\\x61-\\x7a"; // inside an identifier @ is not allowed but 0-9 are. var baseASCIIidentifierChars = "\\x24\\x30-\\x39\\x41-\\x5a\\x5f\\x61-\\x7a"; // Big ugly regular expressions that match characters in the // whitespace, identifier, and identifier-start categories. These // are only applied when a character is found to actually have a // code point above 128. var nonASCIIidentifierStartChars = "\\xaa\\xb5\\xba\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u02c1\\u02c6-\\u02d1\\u02e0-\\u02e4\\u02ec\\u02ee\\u0370-\\u0374\\u0376\\u0377\\u037a-\\u037d\\u0386\\u0388-\\u038a\\u038c\\u038e-\\u03a1\\u03a3-\\u03f5\\u03f7-\\u0481\\u048a-\\u0527\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05d0-\\u05ea\\u05f0-\\u05f2\\u0620-\\u064a\\u066e\\u066f\\u0671-\\u06d3\\u06d5\\u06e5\\u06e6\\u06ee\\u06ef\\u06fa-\\u06fc\\u06ff\\u0710\\u0712-\\u072f\\u074d-\\u07a5\\u07b1\\u07ca-\\u07ea\\u07f4\\u07f5\\u07fa\\u0800-\\u0815\\u081a\\u0824\\u0828\\u0840-\\u0858\\u08a0\\u08a2-\\u08ac\\u0904-\\u0939\\u093d\\u0950\\u0958-\\u0961\\u0971-\\u0977\\u0979-\\u097f\\u0985-\\u098c\\u098f\\u0990\\u0993-\\u09a8\\u09aa-\\u09b0\\u09b2\\u09b6-\\u09b9\\u09bd\\u09ce\\u09dc\\u09dd\\u09df-\\u09e1\\u09f0\\u09f1\\u0a05-\\u0a0a\\u0a0f\\u0a10\\u0a13-\\u0a28\\u0a2a-\\u0a30\\u0a32\\u0a33\\u0a35\\u0a36\\u0a38\\u0a39\\u0a59-\\u0a5c\\u0a5e\\u0a72-\\u0a74\\u0a85-\\u0a8d\\u0a8f-\\u0a91\\u0a93-\\u0aa8\\u0aaa-\\u0ab0\\u0ab2\\u0ab3\\u0ab5-\\u0ab9\\u0abd\\u0ad0\\u0ae0\\u0ae1\\u0b05-\\u0b0c\\u0b0f\\u0b10\\u0b13-\\u0b28\\u0b2a-\\u0b30\\u0b32\\u0b33\\u0b35-\\u0b39\\u0b3d\\u0b5c\\u0b5d\\u0b5f-\\u0b61\\u0b71\\u0b83\\u0b85-\\u0b8a\\u0b8e-\\u0b90\\u0b92-\\u0b95\\u0b99\\u0b9a\\u0b9c\\u0b9e\\u0b9f\\u0ba3\\u0ba4\\u0ba8-\\u0baa\\u0bae-\\u0bb9\\u0bd0\\u0c05-\\u0c0c\\u0c0e-\\u0c10\\u0c12-\\u0c28\\u0c2a-\\u0c33\\u0c35-\\u0c39\\u0c3d\\u0c58\\u0c59\\u0c60\\u0c61\\u0c85-\\u0c8c\\u0c8e-\\u0c90\\u0c92-\\u0ca8\\u0caa-\\u0cb3\\u0cb5-\\u0cb9\\u0cbd\\u0cde\\u0ce0\\u0ce1\\u0cf1\\u0cf2\\u0d05-\\u0d0c\\u0d0e-\\u0d10\\u0d12-\\u0d3a\\u0d3d\\u0d4e\\u0d60\\u0d61\\u0d7a-\\u0d7f\\u0d85-\\u0d96\\u0d9a-\\u0db1\\u0db3-\\u0dbb\\u0dbd\\u0dc0-\\u0dc6\\u0e01-\\u0e30\\u0e32\\u0e33\\u0e40-\\u0e46\\u0e81\\u0e82\\u0e84\\u0e87\\u0e88\\u0e8a\\u0e8d\\u0e94-\\u0e97\\u0e99-\\u0e9f\\u0ea1-\\u0ea3\\u0ea5\\u0ea7\\u0eaa\\u0eab\\u0ead-\\u0eb0\\u0eb2\\u0eb3\\u0ebd\\u0ec0-\\u0ec4\\u0ec6\\u0edc-\\u0edf\\u0f00\\u0f40-\\u0f47\\u0f49-\\u0f6c\\u0f88-\\u0f8c\\u1000-\\u102a\\u103f\\u1050-\\u1055\\u105a-\\u105d\\u1061\\u1065\\u1066\\u106e-\\u1070\\u1075-\\u1081\\u108e\\u10a0-\\u10c5\\u10c7\\u10cd\\u10d0-\\u10fa\\u10fc-\\u1248\\u124a-\\u124d\\u1250-\\u1256\\u1258\\u125a-\\u125d\\u1260-\\u1288\\u128a-\\u128d\\u1290-\\u12b0\\u12b2-\\u12b5\\u12b8-\\u12be\\u12c0\\u12c2-\\u12c5\\u12c8-\\u12d6\\u12d8-\\u1310\\u1312-\\u1315\\u1318-\\u135a\\u1380-\\u138f\\u13a0-\\u13f4\\u1401-\\u166c\\u166f-\\u167f\\u1681-\\u169a\\u16a0-\\u16ea\\u16ee-\\u16f0\\u1700-\\u170c\\u170e-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176c\\u176e-\\u1770\\u1780-\\u17b3\\u17d7\\u17dc\\u1820-\\u1877\\u1880-\\u18a8\\u18aa\\u18b0-\\u18f5\\u1900-\\u191c\\u1950-\\u196d\\u1970-\\u1974\\u1980-\\u19ab\\u19c1-\\u19c7\\u1a00-\\u1a16\\u1a20-\\u1a54\\u1aa7\\u1b05-\\u1b33\\u1b45-\\u1b4b\\u1b83-\\u1ba0\\u1bae\\u1baf\\u1bba-\\u1be5\\u1c00-\\u1c23\\u1c4d-\\u1c4f\\u1c5a-\\u1c7d\\u1ce9-\\u1cec\\u1cee-\\u1cf1\\u1cf5\\u1cf6\\u1d00-\\u1dbf\\u1e00-\\u1f15\\u1f18-\\u1f1d\\u1f20-\\u1f45\\u1f48-\\u1f4d\\u1f50-\\u1f57\\u1f59\\u1f5b\\u1f5d\\u1f5f-\\u1f7d\\u1f80-\\u1fb4\\u1fb6-\\u1fbc\\u1fbe\\u1fc2-\\u1fc4\\u1fc6-\\u1fcc\\u1fd0-\\u1fd3\\u1fd6-\\u1fdb\\u1fe0-\\u1fec\\u1ff2-\\u1ff4\\u1ff6-\\u1ffc\\u2071\\u207f\\u2090-\\u209c\\u2102\\u2107\\u210a-\\u2113\\u2115\\u2119-\\u211d\\u2124\\u2126\\u2128\\u212a-\\u212d\\u212f-\\u2139\\u213c-\\u213f\\u2145-\\u2149\\u214e\\u2160-\\u2188\\u2c00-\\u2c2e\\u2c30-\\u2c5e\\u2c60-\\u2ce4\\u2ceb-\\u2cee\\u2cf2\\u2cf3\\u2d00-\\u2d25\\u2d27\\u2d2d\\u2d30-\\u2d67\\u2d6f\\u2d80-\\u2d96\\u2da0-\\u2da6\\u2da8-\\u2dae\\u2db0-\\u2db6\\u2db8-\\u2dbe\\u2dc0-\\u2dc6\\u2dc8-\\u2dce\\u2dd0-\\u2dd6\\u2dd8-\\u2dde\\u2e2f\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303c\\u3041-\\u3096\\u309d-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312d\\u3131-\\u318e\\u31a0-\\u31ba\\u31f0-\\u31ff\\u3400-\\u4db5\\u4e00-\\u9fcc\\ua000-\\ua48c\\ua4d0-\\ua4fd\\ua500-\\ua60c\\ua610-\\ua61f\\ua62a\\ua62b\\ua640-\\ua66e\\ua67f-\\ua697\\ua6a0-\\ua6ef\\ua717-\\ua71f\\ua722-\\ua788\\ua78b-\\ua78e\\ua790-\\ua793\\ua7a0-\\ua7aa\\ua7f8-\\ua801\\ua803-\\ua805\\ua807-\\ua80a\\ua80c-\\ua822\\ua840-\\ua873\\ua882-\\ua8b3\\ua8f2-\\ua8f7\\ua8fb\\ua90a-\\ua925\\ua930-\\ua946\\ua960-\\ua97c\\ua984-\\ua9b2\\ua9cf\\uaa00-\\uaa28\\uaa40-\\uaa42\\uaa44-\\uaa4b\\uaa60-\\uaa76\\uaa7a\\uaa80-\\uaaaf\\uaab1\\uaab5\\uaab6\\uaab9-\\uaabd\\uaac0\\uaac2\\uaadb-\\uaadd\\uaae0-\\uaaea\\uaaf2-\\uaaf4\\uab01-\\uab06\\uab09-\\uab0e\\uab11-\\uab16\\uab20-\\uab26\\uab28-\\uab2e\\uabc0-\\uabe2\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufb00-\\ufb06\\ufb13-\\ufb17\\ufb1d\\ufb1f-\\ufb28\\ufb2a-\\ufb36\\ufb38-\\ufb3c\\ufb3e\\ufb40\\ufb41\\ufb43\\ufb44\\ufb46-\\ufbb1\\ufbd3-\\ufd3d\\ufd50-\\ufd8f\\ufd92-\\ufdc7\\ufdf0-\\ufdfb\\ufe70-\\ufe74\\ufe76-\\ufefc\\uff21-\\uff3a\\uff41-\\uff5a\\uff66-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc"; var nonASCIIidentifierChars = "\\u0300-\\u036f\\u0483-\\u0487\\u0591-\\u05bd\\u05bf\\u05c1\\u05c2\\u05c4\\u05c5\\u05c7\\u0610-\\u061a\\u0620-\\u0649\\u0672-\\u06d3\\u06e7-\\u06e8\\u06fb-\\u06fc\\u0730-\\u074a\\u0800-\\u0814\\u081b-\\u0823\\u0825-\\u0827\\u0829-\\u082d\\u0840-\\u0857\\u08e4-\\u08fe\\u0900-\\u0903\\u093a-\\u093c\\u093e-\\u094f\\u0951-\\u0957\\u0962-\\u0963\\u0966-\\u096f\\u0981-\\u0983\\u09bc\\u09be-\\u09c4\\u09c7\\u09c8\\u09d7\\u09df-\\u09e0\\u0a01-\\u0a03\\u0a3c\\u0a3e-\\u0a42\\u0a47\\u0a48\\u0a4b-\\u0a4d\\u0a51\\u0a66-\\u0a71\\u0a75\\u0a81-\\u0a83\\u0abc\\u0abe-\\u0ac5\\u0ac7-\\u0ac9\\u0acb-\\u0acd\\u0ae2-\\u0ae3\\u0ae6-\\u0aef\\u0b01-\\u0b03\\u0b3c\\u0b3e-\\u0b44\\u0b47\\u0b48\\u0b4b-\\u0b4d\\u0b56\\u0b57\\u0b5f-\\u0b60\\u0b66-\\u0b6f\\u0b82\\u0bbe-\\u0bc2\\u0bc6-\\u0bc8\\u0bca-\\u0bcd\\u0bd7\\u0be6-\\u0bef\\u0c01-\\u0c03\\u0c46-\\u0c48\\u0c4a-\\u0c4d\\u0c55\\u0c56\\u0c62-\\u0c63\\u0c66-\\u0c6f\\u0c82\\u0c83\\u0cbc\\u0cbe-\\u0cc4\\u0cc6-\\u0cc8\\u0cca-\\u0ccd\\u0cd5\\u0cd6\\u0ce2-\\u0ce3\\u0ce6-\\u0cef\\u0d02\\u0d03\\u0d46-\\u0d48\\u0d57\\u0d62-\\u0d63\\u0d66-\\u0d6f\\u0d82\\u0d83\\u0dca\\u0dcf-\\u0dd4\\u0dd6\\u0dd8-\\u0ddf\\u0df2\\u0df3\\u0e34-\\u0e3a\\u0e40-\\u0e45\\u0e50-\\u0e59\\u0eb4-\\u0eb9\\u0ec8-\\u0ecd\\u0ed0-\\u0ed9\\u0f18\\u0f19\\u0f20-\\u0f29\\u0f35\\u0f37\\u0f39\\u0f41-\\u0f47\\u0f71-\\u0f84\\u0f86-\\u0f87\\u0f8d-\\u0f97\\u0f99-\\u0fbc\\u0fc6\\u1000-\\u1029\\u1040-\\u1049\\u1067-\\u106d\\u1071-\\u1074\\u1082-\\u108d\\u108f-\\u109d\\u135d-\\u135f\\u170e-\\u1710\\u1720-\\u1730\\u1740-\\u1750\\u1772\\u1773\\u1780-\\u17b2\\u17dd\\u17e0-\\u17e9\\u180b-\\u180d\\u1810-\\u1819\\u1920-\\u192b\\u1930-\\u193b\\u1951-\\u196d\\u19b0-\\u19c0\\u19c8-\\u19c9\\u19d0-\\u19d9\\u1a00-\\u1a15\\u1a20-\\u1a53\\u1a60-\\u1a7c\\u1a7f-\\u1a89\\u1a90-\\u1a99\\u1b46-\\u1b4b\\u1b50-\\u1b59\\u1b6b-\\u1b73\\u1bb0-\\u1bb9\\u1be6-\\u1bf3\\u1c00-\\u1c22\\u1c40-\\u1c49\\u1c5b-\\u1c7d\\u1cd0-\\u1cd2\\u1d00-\\u1dbe\\u1e01-\\u1f15\\u200c\\u200d\\u203f\\u2040\\u2054\\u20d0-\\u20dc\\u20e1\\u20e5-\\u20f0\\u2d81-\\u2d96\\u2de0-\\u2dff\\u3021-\\u3028\\u3099\\u309a\\ua640-\\ua66d\\ua674-\\ua67d\\ua69f\\ua6f0-\\ua6f1\\ua7f8-\\ua800\\ua806\\ua80b\\ua823-\\ua827\\ua880-\\ua881\\ua8b4-\\ua8c4\\ua8d0-\\ua8d9\\ua8f3-\\ua8f7\\ua900-\\ua909\\ua926-\\ua92d\\ua930-\\ua945\\ua980-\\ua983\\ua9b3-\\ua9c0\\uaa00-\\uaa27\\uaa40-\\uaa41\\uaa4c-\\uaa4d\\uaa50-\\uaa59\\uaa7b\\uaae0-\\uaae9\\uaaf2-\\uaaf3\\uabc0-\\uabe1\\uabec\\uabed\\uabf0-\\uabf9\\ufb20-\\ufb28\\ufe00-\\ufe0f\\ufe20-\\ufe26\\ufe33\\ufe34\\ufe4d-\\ufe4f\\uff10-\\uff19\\uff3f"; //var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); //var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); var identifierStart = "(?:\\\\u[0-9a-fA-F]{4}|[" + baseASCIIidentifierStartChars + nonASCIIidentifierStartChars + "])"; var identifierChars = "(?:\\\\u[0-9a-fA-F]{4}|[" + baseASCIIidentifierChars + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "])*"; exports.identifier = new RegExp(identifierStart + identifierChars, 'g'); exports.identifierStart = new RegExp(identifierStart); exports.identifierMatch = new RegExp("(?:\\\\u[0-9a-fA-F]{4}|[" + baseASCIIidentifierChars + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "])+"); var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/; // jshint ignore:line // Whether a single character denotes a newline. exports.newline = /[\n\r\u2028\u2029]/; // Matches a whole line break (where CRLF is considered a single // line break). Used to count lines. // in javascript, these two differ // in python they are the same, different methods are called on them exports.lineBreak = new RegExp('\r\n|' + exports.newline.source); exports.allLineBreaks = new RegExp(exports.lineBreak.source, 'g'); /***/ }), /* 5 */ /***/ (function(module, __unused_webpack_exports, __webpack_require__) { /*jshint node:true */ /* The MIT License (MIT) Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. Permission 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE 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. */ var BaseOptions = (__webpack_require__(6).Options); var validPositionValues = ['before-newline', 'after-newline', 'preserve-newline']; function Options(options) { BaseOptions.call(this, options, 'js'); // compatibility, re var raw_brace_style = this.raw_options.brace_style || null; if (raw_brace_style === "expand-strict") { //graceful handling of deprecated option this.raw_options.brace_style = "expand"; } else if (raw_brace_style === "collapse-preserve-inline") { //graceful handling of deprecated option this.raw_options.brace_style = "collapse,preserve-inline"; } else if (this.raw_options.braces_on_own_line !== undefined) { //graceful handling of deprecated option this.raw_options.brace_style = this.raw_options.braces_on_own_line ? "expand" : "collapse"; // } else if (!raw_brace_style) { //Nothing exists to set it // raw_brace_style = "collapse"; } //preserve-inline in delimited string will trigger brace_preserve_inline, everything //else is considered a brace_style and the last one only will have an effect var brace_style_split = this._get_selection_list('brace_style', ['collapse', 'expand', 'end-expand', 'none', 'preserve-inline']); this.brace_preserve_inline = false; //Defaults in case one or other was not specified in meta-option this.brace_style = "collapse"; for (var bs = 0; bs < brace_style_split.length; bs++) { if (brace_style_split[bs] === "preserve-inline") { this.brace_preserve_inline = true; } else { this.brace_style = brace_style_split[bs]; } } this.unindent_chained_methods = this._get_boolean('unindent_chained_methods'); this.break_chained_methods = this._get_boolean('break_chained_methods'); this.space_in_paren = this._get_boolean('space_in_paren'); this.space_in_empty_paren = this._get_boolean('space_in_empty_paren'); this.jslint_happy = this._get_boolean('jslint_happy'); this.space_after_anon_function = this._get_boolean('space_after_anon_function'); this.space_after_named_function = this._get_boolean('space_after_named_function'); this.keep_array_indentation = this._get_boolean('keep_array_indentation'); this.space_before_conditional = this._get_boolean('space_before_conditional', true); this.unescape_strings = this._get_boolean('unescape_strings'); this.e4x = this._get_boolean('e4x'); this.comma_first = this._get_boolean('comma_first'); this.operator_position = this._get_selection('operator_position', validPositionValues); // For testing of beautify preserve:start directive this.test_output_raw = this._get_boolean('test_output_raw'); // force this._options.space_after_anon_function to true if this._options.jslint_happy if (this.jslint_happy) { this.space_after_anon_function = true; } } Options.prototype = new BaseOptions(); module.exports.Options = Options; /***/ }), /* 6 */ /***/ (function(module) { /*jshint node:true */ /* The MIT License (MIT) Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. Permission 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE 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. */ function Options(options, merge_child_field) { this.raw_options = _mergeOpts(options, merge_child_field); // Support passing the source text back with no change this.disabled = this._get_boolean('disabled'); this.eol = this._get_characters('eol', 'auto'); this.end_with_newline = this._get_boolean('end_with_newline'); this.indent_size = this._get_number('indent_size', 4); this.indent_char = this._get_characters('indent_char', ' '); this.indent_level = this._get_number('indent_level'); this.preserve_newlines = this._get_boolean('preserve_newlines', true); this.max_preserve_newlines = this._get_number('max_preserve_newlines', 32786); if (!this.preserve_newlines) { this.max_preserve_newlines = 0; } this.indent_with_tabs = this._get_boolean('indent_with_tabs', this.indent_char === '\t'); if (this.indent_with_tabs) { this.indent_char = '\t'; // indent_size behavior changed after 1.8.6 // It used to be that indent_size would be // set to 1 for indent_with_tabs. That is no longer needed and // actually doesn't make sense - why not use spaces? Further, // that might produce unexpected behavior - tabs being used // for single-column alignment. So, when indent_with_tabs is true // and indent_size is 1, reset indent_size to 4. if (this.indent_size === 1) { this.indent_size = 4; } } // Backwards compat with 1.3.x this.wrap_line_length = this._get_number('wrap_line_length', this._get_number('max_char')); this.indent_empty_lines = this._get_boolean('indent_empty_lines'); // valid templating languages ['django', 'erb', 'handlebars', 'php', 'smarty'] // For now, 'auto' = all off for javascript, all on for html (and inline javascript). // other values ignored this.templating = this._get_selection_list('templating', ['auto', 'none', 'django', 'erb', 'handlebars', 'php', 'smarty'], ['auto']); } Options.prototype._get_array = function(name, default_value) { var option_value = this.raw_options[name]; var result = default_value || []; if (typeof option_value === 'object') { if (option_value !== null && typeof option_value.concat === 'function') { result = option_value.concat(); } } else if (typeof option_value === 'string') { result = option_value.split(/[^a-zA-Z0-9_\/\-]+/); } return result; }; Options.prototype._get_boolean = function(name, default_value) { var option_value = this.raw_options[name]; var result = option_value === undefined ? !!default_value : !!option_value; return result; }; Options.prototype._get_characters = function(name, default_value) { var option_value = this.raw_options[name]; var result = default_value || ''; if (typeof option_value === 'string') { result = option_value.replace(/\\r/, '\r').replace(/\\n/, '\n').replace(/\\t/, '\t'); } return result; }; Options.prototype._get_number = function(name, default_value) { var option_value = this.raw_options[name]; default_value = parseInt(default_value, 10); if (isNaN(default_value)) { default_value = 0; } var result = parseInt(option_value, 10); if (isNaN(result)) { result = default_value; } return result; }; Options.prototype._get_selection = function(name, selection_list, default_value) { var result = this._get_selection_list(name, selection_list, default_value); if (result.length !== 1) { throw new Error( "Invalid Option Value: The option '" + name + "' can only be one of the following values:\n" + selection_list + "\nYou passed in: '" + this.raw_options[name] + "'"); } return result[0]; }; Options.prototype._get_selection_list = function(name, selection_list, default_value) { if (!selection_list || selection_list.length === 0) { throw new Error("Selection list cannot be empty."); } default_value = default_value || [selection_list[0]]; if (!this._is_valid_selection(default_value, selection_list)) { throw new Error("Invalid Default Value!"); } var result = this._get_array(name, default_value); if (!this._is_valid_selection(result, selection_list)) { throw new Error( "Invalid Option Value: The option '" + name + "' can contain only the following values:\n" + selection_list + "\nYou passed in: '" + this.raw_options[name] + "'"); } return result; }; Options.prototype._is_valid_selection = function(result, selection_list) { return result.length && selection_list.length && !result.some(function(item) { return selection_list.indexOf(item) === -1; }); }; // merges child options up with the parent options object // Example: obj = {a: 1, b: {a: 2}} // mergeOpts(obj, 'b') // // Returns: {a: 2} function _mergeOpts(allOptions, childFieldName) { var finalOpts = {}; allOptions = _normalizeOpts(allOptions); var name; for (name in allOptions) { if (name !== childFieldName) { finalOpts[name] = allOptions[name]; } } //merge in the per type settings for the childFieldName if (childFieldName && allOptions[childFieldName]) { for (name in allOptions[childFieldName]) { finalOpts[name] = allOptions[childFieldName][name]; } } return finalOpts; } function _normalizeOpts(options) { var convertedOpts = {}; var key; for (key in options) { var newKey = key.replace(/-/g, "_"); convertedOpts[newKey] = options[key]; } return convertedOpts; } module.exports.Options = Options; module.exports.normalizeOpts = _normalizeOpts; module.exports.mergeOpts = _mergeOpts; /***/ }), /* 7 */ /***/ (function(module, __unused_webpack_exports, __webpack_require__) { /*jshint node:true */ /* The MIT License (MIT) Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. Permission 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE 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. */ var InputScanner = (__webpack_require__(8).InputScanner); var BaseTokenizer = (__webpack_require__(9).Tokenizer); var BASETOKEN = (__webpack_require__(9).TOKEN); var Directives = (__webpack_require__(13).Directives); var acorn = __webpack_require__(4); var Pattern = (__webpack_require__(12).Pattern); var TemplatablePattern = (__webpack_require__(14).TemplatablePattern); function in_array(what, arr) { return arr.indexOf(what) !== -1; } var TOKEN = { START_EXPR: 'TK_START_EXPR', END_EXPR: 'TK_END_EXPR', START_BLOCK: 'TK_START_BLOCK', END_BLOCK: 'TK_END_BLOCK', WORD: 'TK_WORD', RESERVED: 'TK_RESERVED', SEMICOLON: 'TK_SEMICOLON', STRING: 'TK_STRING', EQUALS: 'TK_EQUALS', OPERATOR: 'TK_OPERATOR', COMMA: 'TK_COMMA', BLOCK_COMMENT: 'TK_BLOCK_COMMENT', COMMENT: 'TK_COMMENT', DOT: 'TK_DOT', UNKNOWN: 'TK_UNKNOWN', START: BASETOKEN.START, RAW: BASETOKEN.RAW, EOF: BASETOKEN.EOF }; var directives_core = new Directives(/\/\*/, /\*\//); var number_pattern = /0[xX][0123456789abcdefABCDEF_]*n?|0[oO][01234567_]*n?|0[bB][01_]*n?|\d[\d_]*n|(?:\.\d[\d_]*|\d[\d_]*\.?[\d_]*)(?:[eE][+-]?[\d_]+)?/; var digit = /[0-9]/; // Dot "." must be distinguished from "..." and decimal var dot_pattern = /[^\d\.]/; var positionable_operators = ( ">>> === !== &&= ??= ||= " + "<< && >= ** != == <= >> || ?? |> " + "< / - + > : & % ? ^ | *").split(' '); // IMPORTANT: this must be sorted longest to shortest or tokenizing many not work. // Also, you must update possitionable operators separately from punct var punct = ">>>= " + "... >>= <<= === >>> !== **= &&= ??= ||= " + "=> ^= :: /= << <= == && -= >= >> != -- += ** || ?? ++ %= &= *= |= |> " + "= ! ? > < : / ^ - + * & % ~ |"; punct = punct.replace(/[-[\]{}()*+?.,\\^$|#]/g, "\\$&"); // ?. but not if followed by a number punct = '\\?\\.(?!\\d) ' + punct; punct = punct.replace(/ /g, '|'); var punct_pattern = new RegExp(punct); // words which should always start on new line. var line_starters = 'continue,try,throw,return,var,let,const,if,switch,case,default,for,while,break,function,import,export'.split(','); var reserved_words = line_starters.concat(['do', 'in', 'of', 'else', 'get', 'set', 'new', 'catch', 'finally', 'typeof', 'yield', 'async', 'await', 'from', 'as', 'class', 'extends']); var reserved_word_pattern = new RegExp('^(?:' + reserved_words.join('|') + ')$'); // var template_pattern = /(?:(?:<\?php|<\?=)[\s\S]*?\?>)|(?:<%[\s\S]*?%>)/g; var in_html_comment; var Tokenizer = function(input_string, options) { BaseTokenizer.call(this, input_string, options); this._patterns.whitespace = this._patterns.whitespace.matching( /\u00A0\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff/.source, /\u2028\u2029/.source); var pattern_reader = new Pattern(this._input); var templatable = new TemplatablePattern(this._input) .read_options(this._options); this.__patterns = { template: templatable, identifier: templatable.starting_with(acorn.identifier).matching(acorn.identifierMatch), number: pattern_reader.matching(number_pattern), punct: pattern_reader.matching(punct_pattern), // comment ends just before nearest linefeed or end of file comment: pattern_reader.starting_with(/\/\//).until(/[\n\r\u2028\u2029]/), // /* ... */ comment ends with nearest */ or end of file block_comment: pattern_reader.starting_with(/\/\*/).until_after(/\*\//), html_comment_start: pattern_reader.matching(//), include: pattern_reader.starting_with(/#include/).until_after(acorn.lineBreak), shebang: pattern_reader.starting_with(/#!/).until_after(acorn.lineBreak), xml: pattern_reader.matching(/[\s\S]*?<(\/?)([-a-zA-Z:0-9_.]+|{[^}]+?}|!\[CDATA\[[^\]]*?\]\]|)(\s*{[^}]+?}|\s+[-a-zA-Z:0-9_.]+|\s+[-a-zA-Z:0-9_.]+\s*=\s*('[^']*'|"[^"]*"|{([^{}]|{[^}]+?})+?}))*\s*(\/?)\s*>/), single_quote: templatable.until(/['\\\n\r\u2028\u2029]/), double_quote: templatable.until(/["\\\n\r\u2028\u2029]/), template_text: templatable.until(/[`\\$]/), template_expression: templatable.until(/[`}\\]/) }; }; Tokenizer.prototype = new BaseTokenizer(); Tokenizer.prototype._is_comment = function(current_token) { return current_token.type === TOKEN.COMMENT || current_token.type === TOKEN.BLOCK_COMMENT || current_token.type === TOKEN.UNKNOWN; }; Tokenizer.prototype._is_opening = function(current_token) { return current_token.type === TOKEN.START_BLOCK || current_token.type === TOKEN.START_EXPR; }; Tokenizer.prototype._is_closing = function(current_token, open_token) { return (current_token.type === TOKEN.END_BLOCK || current_token.type === TOKEN.END_EXPR) && (open_token && ( (current_token.text === ']' && open_token.text === '[') || (current_token.text === ')' && open_token.text === '(') || (current_token.text === '}' && open_token.text === '{'))); }; Tokenizer.prototype._reset = function() { in_html_comment = false; }; Tokenizer.prototype._get_next_token = function(previous_token, open_token) { // jshint unused:false var token = null; this._readWhitespace(); var c = this._input.peek(); if (c === null) { return this._create_token(TOKEN.EOF, ''); } token = token || this._read_non_javascript(c); token = token || this._read_string(c); token = token || this._read_word(previous_token); token = token || this._read_singles(c); token = token || this._read_comment(c); token = token || this._read_regexp(c, previous_token); token = token || this._read_xml(c, previous_token); token = token || this._read_punctuation(); token = token || this._create_token(TOKEN.UNKNOWN, this._input.next()); return token; }; Tokenizer.prototype._read_word = function(previous_token) { var resulting_string; resulting_string = this.__patterns.identifier.read(); if (resulting_string !== '') { resulting_string = resulting_string.replace(acorn.allLineBreaks, '\n'); if (!(previous_token.type === TOKEN.DOT || (previous_token.type === TOKEN.RESERVED && (previous_token.text === 'set' || previous_token.text === 'get'))) && reserved_word_pattern.test(resulting_string)) { if ((resulting_string === 'in' || resulting_string === 'of') && (previous_token.type === TOKEN.WORD || previous_token.type === TOKEN.STRING)) { // hack for 'in' and 'of' operators return this._create_token(TOKEN.OPERATOR, resulting_string); } return this._create_token(TOKEN.RESERVED, resulting_string); } return this._create_token(TOKEN.WORD, resulting_string); } resulting_string = this.__patterns.number.read(); if (resulting_string !== '') { return this._create_token(TOKEN.WORD, resulting_string); } }; Tokenizer.prototype._read_singles = function(c) { var token = null; if (c === '(' || c === '[') { token = this._create_token(TOKEN.START_EXPR, c); } else if (c === ')' || c === ']') { token = this._create_token(TOKEN.END_EXPR, c); } else if (c === '{') { token = this._create_token(TOKEN.START_BLOCK, c); } else if (c === '}') { token = this._create_token(TOKEN.END_BLOCK, c); } else if (c === ';') { token = this._create_token(TOKEN.SEMICOLON, c); } else if (c === '.' && dot_pattern.test(this._input.peek(1))) { token = this._create_token(TOKEN.DOT, c); } else if (c === ',') { token = this._create_token(TOKEN.COMMA, c); } if (token) { this._input.next(); } return token; }; Tokenizer.prototype._read_punctuation = function() { var resulting_string = this.__patterns.punct.read(); if (resulting_string !== '') { if (resulting_string === '=') { return this._create_token(TOKEN.EQUALS, resulting_string); } else if (resulting_string === '?.') { return this._create_token(TOKEN.DOT, resulting_string); } else { return this._create_token(TOKEN.OPERATOR, resulting_string); } } }; Tokenizer.prototype._read_non_javascript = function(c) { var resulting_string = ''; if (c === '#') { if (this._is_first_token()) { resulting_string = this.__patterns.shebang.read(); if (resulting_string) { return this._create_token(TOKEN.UNKNOWN, resulting_string.trim() + '\n'); } } // handles extendscript #includes resulting_string = this.__patterns.include.read(); if (resulting_string) { return this._create_token(TOKEN.UNKNOWN, resulting_string.trim() + '\n'); } c = this._input.next(); // Spidermonkey-specific sharp variables for circular references. Considered obsolete. var sharp = '#'; if (this._input.hasNext() && this._input.testChar(digit)) { do { c = this._input.next(); sharp += c; } while (this._input.hasNext() && c !== '#' && c !== '='); if (c === '#') { // } else if (this._input.peek() === '[' && this._input.peek(1) === ']') { sharp += '[]'; this._input.next(); this._input.next(); } else if (this._input.peek() === '{' && this._input.peek(1) === '}') { sharp += '{}'; this._input.next(); this._input.next(); } return this._create_token(TOKEN.WORD, sharp); } this._input.back(); } else if (c === '<' && this._is_first_token()) { resulting_string = this.__patterns.html_comment_start.read(); if (resulting_string) { while (this._input.hasNext() && !this._input.testChar(acorn.newline)) { resulting_string += this._input.next(); } in_html_comment = true; return this._create_token(TOKEN.COMMENT, resulting_string); } } else if (in_html_comment && c === '-') { resulting_string = this.__patterns.html_comment_end.read(); if (resulting_string) { in_html_comment = false; return this._create_token(TOKEN.COMMENT, resulting_string); } } return null; }; Tokenizer.prototype._read_comment = function(c) { var token = null; if (c === '/') { var comment = ''; if (this._input.peek(1) === '*') { // peek for comment /* ... */ comment = this.__patterns.block_comment.read(); var directives = directives_core.get_directives(comment); if (directives && directives.ignore === 'start') { comment += directives_core.readIgnored(this._input); } comment = comment.replace(acorn.allLineBreaks, '\n'); token = this._create_token(TOKEN.BLOCK_COMMENT, comment); token.directives = directives; } else if (this._input.peek(1) === '/') { // peek for comment // ... comment = this.__patterns.comment.read(); token = this._create_token(TOKEN.COMMENT, comment); } } return token; }; Tokenizer.prototype._read_string = function(c) { if (c === '`' || c === "'" || c === '"') { var resulting_string = this._input.next(); this.has_char_escapes = false; if (c === '`') { resulting_string += this._read_string_recursive('`', true, '${'); } else { resulting_string += this._read_string_recursive(c); } if (this.has_char_escapes && this._options.unescape_strings) { resulting_string = unescape_string(resulting_string); } if (this._input.peek() === c) { resulting_string += this._input.next(); } resulting_string = resulting_string.replace(acorn.allLineBreaks, '\n'); return this._create_token(TOKEN.STRING, resulting_string); } return null; }; Tokenizer.prototype._allow_regexp_or_xml = function(previous_token) { // regex and xml can only appear in specific locations during parsing return (previous_token.type === TOKEN.RESERVED && in_array(previous_token.text, ['return', 'case', 'throw', 'else', 'do', 'typeof', 'yield'])) || (previous_token.type === TOKEN.END_EXPR && previous_token.text === ')' && previous_token.opened.previous.type === TOKEN.RESERVED && in_array(previous_token.opened.previous.text, ['if', 'while', 'for'])) || (in_array(previous_token.type, [TOKEN.COMMENT, TOKEN.START_EXPR, TOKEN.START_BLOCK, TOKEN.START, TOKEN.END_BLOCK, TOKEN.OPERATOR, TOKEN.EQUALS, TOKEN.EOF, TOKEN.SEMICOLON, TOKEN.COMMA ])); }; Tokenizer.prototype._read_regexp = function(c, previous_token) { if (c === '/' && this._allow_regexp_or_xml(previous_token)) { // handle regexp // var resulting_string = this._input.next(); var esc = false; var in_char_class = false; while (this._input.hasNext() && ((esc || in_char_class || this._input.peek() !== c) && !this._input.testChar(acorn.newline))) { resulting_string += this._input.peek(); if (!esc) { esc = this._input.peek() === '\\'; if (this._input.peek() === '[') { in_char_class = true; } else if (this._input.peek() === ']') { in_char_class = false; } } else { esc = false; } this._input.next(); } if (this._input.peek() === c) { resulting_string += this._input.next(); // regexps may have modifiers /regexp/MOD , so fetch those, too // Only [gim] are valid, but if the user puts in garbage, do what we can to take it. resulting_string += this._input.read(acorn.identifier); } return this._create_token(TOKEN.STRING, resulting_string); } return null; }; Tokenizer.prototype._read_xml = function(c, previous_token) { if (this._options.e4x && c === "<" && this._allow_regexp_or_xml(previous_token)) { var xmlStr = ''; var match = this.__patterns.xml.read_match(); // handle e4x xml literals // if (match) { // Trim root tag to attempt to var rootTag = match[2].replace(/^{\s+/, '{').replace(/\s+}$/, '}'); var isCurlyRoot = rootTag.indexOf('{') === 0; var depth = 0; while (match) { var isEndTag = !!match[1]; var tagName = match[2]; var isSingletonTag = (!!match[match.length - 1]) || (tagName.slice(0, 8) === "![CDATA["); if (!isSingletonTag && (tagName === rootTag || (isCurlyRoot && tagName.replace(/^{\s+/, '{').replace(/\s+}$/, '}')))) { if (isEndTag) { --depth; } else { ++depth; } } xmlStr += match[0]; if (depth <= 0) { break; } match = this.__patterns.xml.read_match(); } // if we didn't close correctly, keep unformatted. if (!match) { xmlStr += this._input.match(/[\s\S]*/g)[0]; } xmlStr = xmlStr.replace(acorn.allLineBreaks, '\n'); return this._create_token(TOKEN.STRING, xmlStr); } } return null; }; function unescape_string(s) { // You think that a regex would work for this // return s.replace(/\\x([0-9a-f]{2})/gi, function(match, val) { // return String.fromCharCode(parseInt(val, 16)); // }) // However, dealing with '\xff', '\\xff', '\\\xff' makes this more fun. var out = '', escaped = 0; var input_scan = new InputScanner(s); var matched = null; while (input_scan.hasNext()) { // Keep any whitespace, non-slash characters // also keep slash pairs. matched = input_scan.match(/([\s]|[^\\]|\\\\)+/g); if (matched) { out += matched[0]; } if (input_scan.peek() === '\\') { input_scan.next(); if (input_scan.peek() === 'x') { matched = input_scan.match(/x([0-9A-Fa-f]{2})/g); } else if (input_scan.peek() === 'u') { matched = input_scan.match(/u([0-9A-Fa-f]{4})/g); } else { out += '\\'; if (input_scan.hasNext()) { out += input_scan.next(); } continue; } // If there's some error decoding, return the original string if (!matched) { return s; } escaped = parseInt(matched[1], 16); if (escaped > 0x7e && escaped <= 0xff && matched[0].indexOf('x') === 0) { // we bail out on \x7f..\xff, // leaving whole string escaped, // as it's probably completely binary return s; } else if (escaped >= 0x00 && escaped < 0x20) { // leave 0x00...0x1f escaped out += '\\' + matched[0]; continue; } else if (escaped === 0x22 || escaped === 0x27 || escaped === 0x5c) { // single-quote, apostrophe, backslash - escape these out += '\\' + String.fromCharCode(escaped); } else { out += String.fromCharCode(escaped); } } } return out; } // handle string // Tokenizer.prototype._read_string_recursive = function(delimiter, allow_unescaped_newlines, start_sub) { var current_char; var pattern; if (delimiter === '\'') { pattern = this.__patterns.single_quote; } else if (delimiter === '"') { pattern = this.__patterns.double_quote; } else if (delimiter === '`') { pattern = this.__patterns.template_text; } else if (delimiter === '}') { pattern = this.__patterns.template_expression; } var resulting_string = pattern.read(); var next = ''; while (this._input.hasNext()) { next = this._input.next(); if (next === delimiter || (!allow_unescaped_newlines && acorn.newline.test(next))) { this._input.back(); break; } else if (next === '\\' && this._input.hasNext()) { current_char = this._input.peek(); if (current_char === 'x' || current_char === 'u') { this.has_char_escapes = true; } else if (current_char === '\r' && this._input.peek(1) === '\n') { this._input.next(); } next += this._input.next(); } else if (start_sub) { if (start_sub === '${' && next === '$' && this._input.peek() === '{') { next += this._input.next(); } if (start_sub === next) { if (delimiter === '`') { next += this._read_string_recursive('}', allow_unescaped_newlines, '`'); } else { next += this._read_string_recursive('`', allow_unescaped_newlines, '${'); } if (this._input.hasNext()) { next += this._input.next(); } } } next += pattern.read(); resulting_string += next; } return resulting_string; }; module.exports.Tokenizer = Tokenizer; module.exports.TOKEN = TOKEN; module.exports.positionable_operators = positionable_operators.slice(); module.exports.line_starters = line_starters.slice(); /***/ }), /* 8 */ /***/ (function(module) { /*jshint node:true */ /* The MIT License (MIT) Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. Permission 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE 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. */ var regexp_has_sticky = RegExp.prototype.hasOwnProperty('sticky'); function InputScanner(input_string) { this.__input = input_string || ''; this.__input_length = this.__input.length; this.__position = 0; } InputScanner.prototype.restart = function() { this.__position = 0; }; InputScanner.prototype.back = function() { if (this.__position > 0) { this.__position -= 1; } }; InputScanner.prototype.hasNext = function() { return this.__position < this.__input_length; }; InputScanner.prototype.next = function() { var val = null; if (this.hasNext()) { val = this.__input.charAt(this.__position); this.__position += 1; } return val; }; InputScanner.prototype.peek = function(index) { var val = null; index = index || 0; index += this.__position; if (index >= 0 && index < this.__input_length) { val = this.__input.charAt(index); } return val; }; // This is a JavaScript only helper function (not in python) // Javascript doesn't have a match method // and not all implementation support "sticky" flag. // If they do not support sticky then both this.match() and this.test() method // must get the match and check the index of the match. // If sticky is supported and set, this method will use it. // Otherwise it will check that global is set, and fall back to the slower method. InputScanner.prototype.__match = function(pattern, index) { pattern.lastIndex = index; var pattern_match = pattern.exec(this.__input); if (pattern_match && !(regexp_has_sticky && pattern.sticky)) { if (pattern_match.index !== index) { pattern_match = null; } } return pattern_match; }; InputScanner.prototype.test = function(pattern, index) { index = index || 0; index += this.__position; if (index >= 0 && index < this.__input_length) { return !!this.__match(pattern, index); } else { return false; } }; InputScanner.prototype.testChar = function(pattern, index) { // test one character regex match var val = this.peek(index); pattern.lastIndex = 0; return val !== null && pattern.test(val); }; InputScanner.prototype.match = function(pattern) { var pattern_match = this.__match(pattern, this.__position); if (pattern_match) { this.__position += pattern_match[0].length; } else { pattern_match = null; } return pattern_match; }; InputScanner.prototype.read = function(starting_pattern, until_pattern, until_after) { var val = ''; var match; if (starting_pattern) { match = this.match(starting_pattern); if (match) { val += match[0]; } } if (until_pattern && (match || !starting_pattern)) { val += this.readUntil(until_pattern, until_after); } return val; }; InputScanner.prototype.readUntil = function(pattern, until_after) { var val = ''; var match_index = this.__position; pattern.lastIndex = this.__position; var pattern_match = pattern.exec(this.__input); if (pattern_match) { match_index = pattern_match.index; if (until_after) { match_index += pattern_match[0].length; } } else { match_index = this.__input_length; } val = this.__input.substring(this.__position, match_index); this.__position = match_index; return val; }; InputScanner.prototype.readUntilAfter = function(pattern) { return this.readUntil(pattern, true); }; InputScanner.prototype.get_regexp = function(pattern, match_from) { var result = null; var flags = 'g'; if (match_from && regexp_has_sticky) { flags = 'y'; } // strings are converted to regexp if (typeof pattern === "string" && pattern !== '') { // result = new RegExp(pattern.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), flags); result = new RegExp(pattern, flags); } else if (pattern) { result = new RegExp(pattern.source, flags); } return result; }; InputScanner.prototype.get_literal_regexp = function(literal_string) { return RegExp(literal_string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')); }; /* css beautifier legacy helpers */ InputScanner.prototype.peekUntilAfter = function(pattern) { var start = this.__position; var val = this.readUntilAfter(pattern); this.__position = start; return val; }; InputScanner.prototype.lookBack = function(testVal) { var start = this.__position - 1; return start >= testVal.length && this.__input.substring(start - testVal.length, start) .toLowerCase() === testVal; }; module.exports.InputScanner = InputScanner; /***/ }), /* 9 */ /***/ (function(module, __unused_webpack_exports, __webpack_require__) { /*jshint node:true */ /* The MIT License (MIT) Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. Permission 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE 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. */ var InputScanner = (__webpack_require__(8).InputScanner); var Token = (__webpack_require__(3).Token); var TokenStream = (__webpack_require__(10).TokenStream); var WhitespacePattern = (__webpack_require__(11).WhitespacePattern); var TOKEN = { START: 'TK_START', RAW: 'TK_RAW', EOF: 'TK_EOF' }; var Tokenizer = function(input_string, options) { this._input = new InputScanner(input_string); this._options = options || {}; this.__tokens = null; this._patterns = {}; this._patterns.whitespace = new WhitespacePattern(this._input); }; Tokenizer.prototype.tokenize = function() { this._input.restart(); this.__tokens = new TokenStream(); this._reset(); var current; var previous = new Token(TOKEN.START, ''); var open_token = null; var open_stack = []; var comments = new TokenStream(); while (previous.type !== TOKEN.EOF) { current = this._get_next_token(previous, open_token); while (this._is_comment(current)) { comments.add(current); current = this._get_next_token(previous, open_token); } if (!comments.isEmpty()) { current.comments_before = comments; comments = new TokenStream(); } current.parent = open_token; if (this._is_opening(current)) { open_stack.push(open_token); open_token = current; } else if (open_token && this._is_closing(current, open_token)) { current.opened = open_token; open_token.closed = current; open_token = open_stack.pop(); current.parent = open_token; } current.previous = previous; previous.next = current; this.__tokens.add(current); previous = current; } return this.__tokens; }; Tokenizer.prototype._is_first_token = function() { return this.__tokens.isEmpty(); }; Tokenizer.prototype._reset = function() {}; Tokenizer.prototype._get_next_token = function(previous_token, open_token) { // jshint unused:false this._readWhitespace(); var resulting_string = this._input.read(/.+/g); if (resulting_string) { return this._create_token(TOKEN.RAW, resulting_string); } else { return this._create_token(TOKEN.EOF, ''); } }; Tokenizer.prototype._is_comment = function(current_token) { // jshint unused:false return false; }; Tokenizer.prototype._is_opening = function(current_token) { // jshint unused:false return false; }; Tokenizer.prototype._is_closing = function(current_token, open_token) { // jshint unused:false return false; }; Tokenizer.prototype._create_token = function(type, text) { var token = new Token(type, text, this._patterns.whitespace.newline_count, this._patterns.whitespace.whitespace_before_token); return token; }; Tokenizer.prototype._readWhitespace = function() { return this._patterns.whitespace.read(); }; module.exports.Tokenizer = Tokenizer; module.exports.TOKEN = TOKEN; /***/ }), /* 10 */ /***/ (function(module) { /*jshint node:true */ /* The MIT License (MIT) Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. Permission 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE 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. */ function TokenStream(parent_token) { // private this.__tokens = []; this.__tokens_length = this.__tokens.length; this.__position = 0; this.__parent_token = parent_token; } TokenStream.prototype.restart = function() { this.__position = 0; }; TokenStream.prototype.isEmpty = function() { return this.__tokens_length === 0; }; TokenStream.prototype.hasNext = function() { return this.__position < this.__tokens_length; }; TokenStream.prototype.next = function() { var val = null; if (this.hasNext()) { val = this.__tokens[this.__position]; this.__position += 1; } return val; }; TokenStream.prototype.peek = function(index) { var val = null; index = index || 0; index += this.__position; if (index >= 0 && index < this.__tokens_length) { val = this.__tokens[index]; } return val; }; TokenStream.prototype.add = function(token) { if (this.__parent_token) { token.parent = this.__parent_token; } this.__tokens.push(token); this.__tokens_length += 1; }; module.exports.TokenStream = TokenStream; /***/ }), /* 11 */ /***/ (function(module, __unused_webpack_exports, __webpack_require__) { /*jshint node:true */ /* The MIT License (MIT) Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. Permission 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE 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. */ var Pattern = (__webpack_require__(12).Pattern); function WhitespacePattern(input_scanner, parent) { Pattern.call(this, input_scanner, parent); if (parent) { this._line_regexp = this._input.get_regexp(parent._line_regexp); } else { this.__set_whitespace_patterns('', ''); } this.newline_count = 0; this.whitespace_before_token = ''; } WhitespacePattern.prototype = new Pattern(); WhitespacePattern.prototype.__set_whitespace_patterns = function(whitespace_chars, newline_chars) { whitespace_chars += '\\t '; newline_chars += '\\n\\r'; this._match_pattern = this._input.get_regexp( '[' + whitespace_chars + newline_chars + ']+', true); this._newline_regexp = this._input.get_regexp( '\\r\\n|[' + newline_chars + ']'); }; WhitespacePattern.prototype.read = function() { this.newline_count = 0; this.whitespace_before_token = ''; var resulting_string = this._input.read(this._match_pattern); if (resulting_string === ' ') { this.whitespace_before_token = ' '; } else if (resulting_string) { var matches = this.__split(this._newline_regexp, resulting_string); this.newline_count = matches.length - 1; this.whitespace_before_token = matches[this.newline_count]; } return resulting_string; }; WhitespacePattern.prototype.matching = function(whitespace_chars, newline_chars) { var result = this._create(); result.__set_whitespace_patterns(whitespace_chars, newline_chars); result._update(); return result; }; WhitespacePattern.prototype._create = function() { return new WhitespacePattern(this._input, this); }; WhitespacePattern.prototype.__split = function(regexp, input_string) { regexp.lastIndex = 0; var start_index = 0; var result = []; var next_match = regexp.exec(input_string); while (next_match) { result.push(input_string.substring(start_index, next_match.index)); start_index = next_match.index + next_match[0].length; next_match = regexp.exec(input_string); } if (start_index < input_string.length) { result.push(input_string.substring(start_index, input_string.length)); } else { result.push(''); } return result; }; module.exports.WhitespacePattern = WhitespacePattern; /***/ }), /* 12 */ /***/ (function(module) { /*jshint node:true */ /* The MIT License (MIT) Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. Permission 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE 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. */ function Pattern(input_scanner, parent) { this._input = input_scanner; this._starting_pattern = null; this._match_pattern = null; this._until_pattern = null; this._until_after = false; if (parent) { this._starting_pattern = this._input.get_regexp(parent._starting_pattern, true); this._match_pattern = this._input.get_regexp(parent._match_pattern, true); this._until_pattern = this._input.get_regexp(parent._until_pattern); this._until_after = parent._until_after; } } Pattern.prototype.read = function() { var result = this._input.read(this._starting_pattern); if (!this._starting_pattern || result) { result += this._input.read(this._match_pattern, this._until_pattern, this._until_after); } return result; }; Pattern.prototype.read_match = function() { return this._input.match(this._match_pattern); }; Pattern.prototype.until_after = function(pattern) { var result = this._create(); result._until_after = true; result._until_pattern = this._input.get_regexp(pattern); result._update(); return result; }; Pattern.prototype.until = function(pattern) { var result = this._create(); result._until_after = false; result._until_pattern = this._input.get_regexp(pattern); result._update(); return result; }; Pattern.prototype.starting_with = function(pattern) { var result = this._create(); result._starting_pattern = this._input.get_regexp(pattern, true); result._update(); return result; }; Pattern.prototype.matching = function(pattern) { var result = this._create(); result._match_pattern = this._input.get_regexp(pattern, true); result._update(); return result; }; Pattern.prototype._create = function() { return new Pattern(this._input, this); }; Pattern.prototype._update = function() {}; module.exports.Pattern = Pattern; /***/ }), /* 13 */ /***/ (function(module) { /*jshint node:true */ /* The MIT License (MIT) Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. Permission 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE 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. */ function Directives(start_block_pattern, end_block_pattern) { start_block_pattern = typeof start_block_pattern === 'string' ? start_block_pattern : start_block_pattern.source; end_block_pattern = typeof end_block_pattern === 'string' ? end_block_pattern : end_block_pattern.source; this.__directives_block_pattern = new RegExp(start_block_pattern + / beautify( \w+[:]\w+)+ /.source + end_block_pattern, 'g'); this.__directive_pattern = / (\w+)[:](\w+)/g; this.__directives_end_ignore_pattern = new RegExp(start_block_pattern + /\sbeautify\signore:end\s/.source + end_block_pattern, 'g'); } Directives.prototype.get_directives = function(text) { if (!text.match(this.__directives_block_pattern)) { return null; } var directives = {}; this.__directive_pattern.lastIndex = 0; var directive_match = this.__directive_pattern.exec(text); while (directive_match) { directives[directive_match[1]] = directive_match[2]; directive_match = this.__directive_pattern.exec(text); } return directives; }; Directives.prototype.readIgnored = function(input) { return input.readUntilAfter(this.__directives_end_ignore_pattern); }; module.exports.Directives = Directives; /***/ }), /* 14 */ /***/ (function(module, __unused_webpack_exports, __webpack_require__) { /*jshint node:true */ /* The MIT License (MIT) Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors. Permission 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE 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. */ var Pattern = (__webpack_require__(12).Pattern); var template_names = { django: false, erb: false, handlebars: false, php: false, smarty: false }; // This lets templates appear anywhere we would do a readUntil // The cost is higher but it is pay to play. function TemplatablePattern(input_scanner, parent) { Pattern.call(this, input_scanner, parent); this.__template_pattern = null; this._disabled = Object.assign({}, template_names); this._excluded = Object.assign({}, template_names); if (parent) { this.__template_pattern = this._input.get_regexp(parent.__template_pattern); this._excluded = Object.assign(this._excluded, parent._excluded); this._disabled = Object.assign(this._disabled, parent._disabled); } var pattern = new Pattern(input_scanner); this.__patterns = { handlebars_comment: pattern.starting_with(/{{!--/).until_after(/--}}/), handlebars_unescaped: pattern.starting_with(/{{{/).until_after(/}}}/), handlebars: pattern.starting_with(/{{/).until_after(/}}/), php: pattern.starting_with(/<\?(?:[= ]|php)/).until_after(/\?>/), erb: pattern.starting_with(/<%[^%]/).until_after(/[^%]%>/), // django coflicts with handlebars a bit. django: pattern.starting_with(/{%/).until_after(/%}/), django_value: pattern.starting_with(/{{/).until_after(/}}/), django_comment: pattern.starting_with(/{#/).until_after(/#}/), smarty: pattern.starting_with(/{(?=[^}{\s\n])/).until_after(/[^\s\n]}/), smarty_comment: pattern.starting_with(/{\*/).until_after(/\*}/), smarty_literal: pattern.starting_with(/{literal}/).until_after(/{\/literal}/) }; } TemplatablePattern.prototype = new Pattern(); TemplatablePattern.prototype._create = function() { return new TemplatablePattern(this._input, this); }; TemplatablePattern.prototype._update = function() { this.__set_templated_pattern(); }; TemplatablePattern.prototype.disable = function(language) { var result = this._create(); result._disabled[language] = true; result._update(); return result; }; TemplatablePattern.prototype.read_options = function(options) { var result = this._create(); for (var language in template_names) { result._disabled[language] = options.templating.indexOf(language) === -1; } result._update(); return result; }; TemplatablePattern.prototype.exclude = function(language) { var result = this._create(); result._excluded[language] = true; result._update(); return result; }; TemplatablePattern.prototype.read = function() { var result = ''; if (this._match_pattern) { result = this._input.read(this._starting_pattern); } else { result = this._input.read(this._starting_pattern, this.__template_pattern); } var next = this._read_template(); while (next) { if (this._match_pattern) { next += this._input.read(this._match_pattern); } else { next += this._input.readUntil(this.__template_pattern); } result += next; next = this._read_template(); } if (this._until_after) { result += this._input.readUntilAfter(this._until_pattern); } return result; }; TemplatablePattern.prototype.__set_templated_pattern = function() { var items = []; if (!this._disabled.php) { items.push(this.__patterns.php._starting_pattern.source); } if (!this._disabled.handlebars) { items.push(this.__patterns.handlebars._starting_pattern.source); } if (!this._disabled.erb) { items.push(this.__patterns.erb._starting_pattern.source); } if (!this._disabled.django) { items.push(this.__patterns.django._starting_pattern.source); // The starting pattern for django is more complex because it has different // patterns for value, comment, and other sections items.push(this.__patterns.django_value._starting_pattern.source); items.push(this.__patterns.django_comment._starting_pattern.source); } if (!this._disabled.smarty) { items.push(this.__patterns.smarty._starting_pattern.source); } if (this._until_pattern) { items.push(this._until_pattern.source); } this.__template_pattern = this._input.get_regexp('(?:' + items.join('|') + ')'); }; TemplatablePattern.prototype._read_template = function() { var resulting_string = ''; var c = this._input.peek(); if (c === '<') { var peek1 = this._input.peek(1); //if we're in a comment, do something special // We treat all comments as literals, even more than preformatted tags // we just look for the appropriate close tag if (!this._disabled.php && !this._excluded.php && peek1 === '?') { resulting_string = resulting_string || this.__patterns.php.read(); } if (!this._disabled.erb && !this._excluded.erb && peek1 === '%') { resulting_string = resulting_string || this.__patterns.erb.read(); } } else if (c === '{') { if (!this._disabled.handlebars && !this._excluded.handlebars) { resulting_string = resulting_string || this.__patterns.handlebars_comment.read(); resulting_string = resulting_string || this.__patterns.handlebars_unescaped.read(); resulting_string = resulting_string || this.__patterns.handlebars.read(); } if (!this._disabled.django) { // django coflicts with handlebars a bit. if (!this._excluded.django && !this._excluded.handlebars) { resulting_string = resulting_string || this.__patterns.django_value.read(); } if (!this._excluded.django) { resulting_string = resulting_string || this.__patterns.django_comment.read(); resulting_string = resulting_string || this.__patterns.django.read(); } } if (!this._disabled.smarty) { // smarty cannot be enabled with django or handlebars enabled if (this._disabled.django && this._disabled.handlebars) { resulting_string = resulting_string || this.__patterns.smarty_comment.read(); resulting_string = resulting_string || this.__patterns.smarty_literal.read(); resulting_string = resulting_string || this.__patterns.smarty.read(); } } } return resulting_string; }; module.exports.TemplatablePattern = TemplatablePattern; /***/ }) /******/ ]); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ /******/ /******/ // startup /******/ // Load entry module and return exports /******/ // This entry module is referenced by other modules so it can't be inlined /******/ var __webpack_exports__ = __webpack_require__(0); /******/ legacy_beautify_js = __webpack_exports__; /******/ /******/ })() ; var js_beautify = legacy_beautify_js; /* Footer */ if (true) { // Add support for AMD ( https://github.com/amdjs/amdjs-api/wiki/AMD#defineamd-property- ) !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function() { return { js_beautify: js_beautify }; }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else {} }()); /***/ }), /***/ "815F": /*!***************************************************!*\ !*** ./node_modules/rc-tree/es/utils/treeUtil.js ***! \***************************************************/ /*! exports provided: getKey, warningWithoutKey, convertTreeToData, flattenTreeData, traverseDataNodes, convertDataToEntities, getTreeNodeProps, convertNodePropsToEventData */ /*! exports used: convertDataToEntities, convertNodePropsToEventData, convertTreeToData, flattenTreeData, getKey, getTreeNodeProps */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return getKey; }); /* unused harmony export warningWithoutKey */ /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return convertTreeToData; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return flattenTreeData; }); /* unused harmony export traverseDataNodes */ /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return convertDataToEntities; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return getTreeNodeProps; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return convertNodePropsToEventData; }); /* harmony import */ var _babel_runtime_helpers_esm_toConsumableArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/esm/toConsumableArray */ "KQm4"); /* harmony import */ var _babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/esm/objectSpread2 */ "VTBJ"); /* harmony import */ var _babel_runtime_helpers_esm_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/esm/objectWithoutProperties */ "Ff2n"); /* harmony import */ var rc_util_es_Children_toArray__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! rc-util/es/Children/toArray */ "Zm9Q"); /* harmony import */ var rc_util_es_warning__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! rc-util/es/warning */ "Kwbf"); /* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util */ "OZM5"); function getKey(key, pos) { if (key !== null && key !== undefined) { return key; } return pos; } /** * Warning if TreeNode do not provides key */ function warningWithoutKey() { var treeData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var keys = new Map(); function dig(list) { var path = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; (list || []).forEach(function (treeNode) { var key = treeNode.key, children = treeNode.children; Object(rc_util_es_warning__WEBPACK_IMPORTED_MODULE_4__[/* default */ "a"])(key !== null && key !== undefined, "Tree node must have a certain key: [".concat(path).concat(key, "]")); var recordKey = String(key); Object(rc_util_es_warning__WEBPACK_IMPORTED_MODULE_4__[/* default */ "a"])(!keys.has(recordKey) || key === null || key === undefined, "Same 'key' exist in the Tree: ".concat(recordKey)); keys.set(recordKey, true); dig(children, "".concat(path).concat(recordKey, " > ")); }); } dig(treeData); } /** * Convert `children` of Tree into `treeData` structure. */ function convertTreeToData(rootNodes) { function dig(node) { var treeNodes = Object(rc_util_es_Children_toArray__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"])(node); return treeNodes.map(function (treeNode) { // Filter invalidate node if (!Object(_util__WEBPACK_IMPORTED_MODULE_5__[/* isTreeNode */ "i"])(treeNode)) { Object(rc_util_es_warning__WEBPACK_IMPORTED_MODULE_4__[/* default */ "a"])(!treeNode, 'Tree/TreeNode can only accept TreeNode as children.'); return null; } var key = treeNode.key; var _treeNode$props = treeNode.props, children = _treeNode$props.children, rest = Object(_babel_runtime_helpers_esm_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"])(_treeNode$props, ["children"]); var dataNode = Object(_babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"])({ key: key }, rest); var parsedChildren = dig(children); if (parsedChildren.length) { dataNode.children = parsedChildren; } return dataNode; }).filter(function (dataNode) { return dataNode; }); } return dig(rootNodes); } /** * Flat nest tree data into flatten list. This is used for virtual list render. * @param treeNodeList Origin data node list * @param expandedKeys * need expanded keys, provides `true` means all expanded (used in `rc-tree-select`). */ function flattenTreeData() { var treeNodeList = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var expandedKeys = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; var expandedKeySet = new Set(expandedKeys === true ? [] : expandedKeys); var flattenList = []; function dig(list) { var parent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; return list.map(function (treeNode, index) { var pos = Object(_util__WEBPACK_IMPORTED_MODULE_5__[/* getPosition */ "h"])(parent ? parent.pos : '0', index); var mergedKey = getKey(treeNode.key, pos); // Add FlattenDataNode into list var flattenNode = Object(_babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"])(Object(_babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"])({}, treeNode), {}, { parent: parent, pos: pos, children: null, data: treeNode, isStart: [].concat(Object(_babel_runtime_helpers_esm_toConsumableArray__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])(parent ? parent.isStart : []), [index === 0]), isEnd: [].concat(Object(_babel_runtime_helpers_esm_toConsumableArray__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])(parent ? parent.isEnd : []), [index === list.length - 1]) }); flattenList.push(flattenNode); // Loop treeNode children if (expandedKeys === true || expandedKeySet.has(mergedKey)) { flattenNode.children = dig(treeNode.children || [], flattenNode); } else { flattenNode.children = []; } return flattenNode; }); } dig(treeNodeList); return flattenList; } /** * Traverse all the data by `treeData`. * Please not use it out of the `rc-tree` since we may refactor this code. */ function traverseDataNodes(dataNodes, callback, externalGetKey) { var syntheticGetKey; if (externalGetKey) { if (typeof externalGetKey === 'string') { syntheticGetKey = function syntheticGetKey(node) { return node[externalGetKey]; }; } else if (typeof externalGetKey === 'function') { syntheticGetKey = function syntheticGetKey(node) { return externalGetKey(node); }; } } else { syntheticGetKey = function syntheticGetKey(node, pos) { return getKey(node.key, pos); }; } function processNode(node, index, parent) { var children = node ? node.children : dataNodes; var pos = node ? Object(_util__WEBPACK_IMPORTED_MODULE_5__[/* getPosition */ "h"])(parent.pos, index) : '0'; // Process node if is not root if (node) { var key = syntheticGetKey(node, pos); var data = { node: node, index: index, pos: pos, key: key, parentPos: parent.node ? parent.pos : null, level: parent.level + 1 }; callback(data); } // Process children node if (children) { children.forEach(function (subNode, subIndex) { processNode(subNode, subIndex, { node: node, pos: pos, level: parent ? parent.level + 1 : -1 }); }); } } processNode(null); } /** * Convert `treeData` into entity records. */ function convertDataToEntities(dataNodes) { var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, initWrapper = _ref.initWrapper, processEntity = _ref.processEntity, onProcessFinished = _ref.onProcessFinished; var externalGetKey = arguments.length > 2 ? arguments[2] : undefined; var posEntities = {}; var keyEntities = {}; var wrapper = { posEntities: posEntities, keyEntities: keyEntities }; if (initWrapper) { wrapper = initWrapper(wrapper) || wrapper; } traverseDataNodes(dataNodes, function (item) { var node = item.node, index = item.index, pos = item.pos, key = item.key, parentPos = item.parentPos, level = item.level; var entity = { node: node, index: index, key: key, pos: pos, level: level }; var mergedKey = getKey(key, pos); posEntities[pos] = entity; keyEntities[mergedKey] = entity; // Fill children entity.parent = posEntities[parentPos]; if (entity.parent) { entity.parent.children = entity.parent.children || []; entity.parent.children.push(entity); } if (processEntity) { processEntity(entity, wrapper); } }, externalGetKey); if (onProcessFinished) { onProcessFinished(wrapper); } return wrapper; } /** * Get TreeNode props with Tree props. */ function getTreeNodeProps(key, _ref2) { var expandedKeys = _ref2.expandedKeys, selectedKeys = _ref2.selectedKeys, loadedKeys = _ref2.loadedKeys, loadingKeys = _ref2.loadingKeys, checkedKeys = _ref2.checkedKeys, halfCheckedKeys = _ref2.halfCheckedKeys, dragOverNodeKey = _ref2.dragOverNodeKey, dropPosition = _ref2.dropPosition, keyEntities = _ref2.keyEntities; var entity = keyEntities[key]; var treeNodeProps = { eventKey: key, expanded: expandedKeys.indexOf(key) !== -1, selected: selectedKeys.indexOf(key) !== -1, loaded: loadedKeys.indexOf(key) !== -1, loading: loadingKeys.indexOf(key) !== -1, checked: checkedKeys.indexOf(key) !== -1, halfChecked: halfCheckedKeys.indexOf(key) !== -1, pos: String(entity ? entity.pos : ''), // [Legacy] Drag props dragOver: dragOverNodeKey === key && dropPosition === 0, dragOverGapTop: dragOverNodeKey === key && dropPosition === -1, dragOverGapBottom: dragOverNodeKey === key && dropPosition === 1 }; return treeNodeProps; } function convertNodePropsToEventData(props) { var data = props.data, expanded = props.expanded, selected = props.selected, checked = props.checked, loaded = props.loaded, loading = props.loading, halfChecked = props.halfChecked, dragOver = props.dragOver, dragOverGapTop = props.dragOverGapTop, dragOverGapBottom = props.dragOverGapBottom, pos = props.pos, active = props.active; var eventData = Object(_babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"])(Object(_babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"])({}, data), {}, { expanded: expanded, selected: selected, checked: checked, loaded: loaded, loading: loading, halfChecked: halfChecked, dragOver: dragOver, dragOverGapTop: dragOverGapTop, dragOverGapBottom: dragOverGapBottom, pos: pos, active: active }); if (!('props' in eventData)) { Object.defineProperty(eventData, 'props', { get: function get() { Object(rc_util_es_warning__WEBPACK_IMPORTED_MODULE_4__[/* default */ "a"])(false, 'Second param return from event is node data instead of TreeNode instance. Please read value directly instead of reading from `props`.'); return props; } }); } return eventData; } /***/ }), /***/ "9Bee": /*!*********************************************************!*\ !*** ./src/components/RenderHtml/index.tsx + 1 modules ***! \*********************************************************/ /*! exports provided: default */ /*! exports used: default */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/objectSpread2.js */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/slicedToArray.js */ /*! ModuleConcatenation bailout: Cannot concat with ./src/components/PreviewAll/index.tsx */ /*! ModuleConcatenation bailout: Cannot concat with ./src/utils/env.ts */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/hls.js/dist/hls.js (<- Module is not an ECMAScript module) */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/katex/dist/katex.js (<- Module is not an ECMAScript module) */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/marked/lib/marked.js (<- Module is not an ECMAScript module) */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/marked/src/helpers.js (<- Module is not an ECMAScript module) */ /*! ModuleConcatenation bailout: Cannot concat with external "window.React" (<- Module is not an ECMAScript module) */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; // EXTERNAL MODULE: ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/objectSpread2.js var objectSpread2 = __webpack_require__("k1fw"); // EXTERNAL MODULE: ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/slicedToArray.js + 1 modules var slicedToArray = __webpack_require__("tJVT"); // EXTERNAL MODULE: external "window.React" var external_window_React_ = __webpack_require__("cDcd"); var external_window_React_default = /*#__PURE__*/__webpack_require__.n(external_window_React_); // EXTERNAL MODULE: ./node_modules/katex/dist/katex.min.css var katex_min = __webpack_require__("vg9a"); // EXTERNAL MODULE: ./node_modules/marked/lib/marked.js var marked = __webpack_require__("DlQD"); var marked_default = /*#__PURE__*/__webpack_require__.n(marked); // EXTERNAL MODULE: ./node_modules/marked/src/helpers.js var helpers = __webpack_require__("rUJ1"); // CONCATENATED MODULE: ./src/utils/marked.ts function indentCodeCompensation(raw, text) { var matchIndentToCode = raw.match(/^(\s+)(?:```)/); if (matchIndentToCode === null) { return text; } var indentToCode = matchIndentToCode[1]; return text.split('\n').map(function (node) { var matchIndentInNode = node.match(/^\s+/); if (matchIndentInNode === null) { return node; } var _matchIndentInNode = Object(slicedToArray["a" /* default */])(matchIndentInNode, 1), indentInNode = _matchIndentInNode[0]; if (indentInNode.length >= indentToCode.length) { return node.slice(indentToCode.length); } return node; }).join('\n'); } //兼容之前的 ##标题式写法 var toc = []; var ctx = ["
    "]; var renderer = new marked_default.a.Renderer(); var headingRegex = /^ *(#{1,6}) *([^\n]+?) *(?:#+ *)?(?:\n+|$)/; function cleanToc() { toc.length = 0; ctx = ["
      "]; } var lines = { overflow: "hidden", WebkitBoxOrient: "vertical", display: "-webkit-box", WebkitLineClamp: 2 }; function buildToc(coll, k, level, ctx) { if (k >= coll.length || coll[k].level <= level) { return k; } var node = coll[k]; ctx.push("
    • " + node.text + ""); k++; var childCtx = []; k = buildToc(coll, k, node.level, childCtx); if (childCtx.length > 0) { ctx.push("
        "); childCtx.forEach(function (idm) { ctx.push(idm); }); ctx.push("
      "); } ctx.push("
    • "); k = buildToc(coll, k, level, ctx); return k; } function getTocContent() { buildToc(toc, 0, 0, ctx); ctx.push("
    "); return ctx.join(""); } var tokenizer = { heading: function heading(src) { var cap = headingRegex.exec(src); if (cap) { return { type: 'heading', raw: cap[0], depth: cap[1].length, text: cap[2] }; } }, fences: function fences(src) { var cap = this.rules.block.fences.exec(src); if (cap) { var raw = cap[0]; var text = indentCodeCompensation(raw, cap[3] || ''); var lang = cap[2] ? cap[2].trim() : cap[2]; if (['latex', 'katex', 'math'].indexOf(lang) >= 0) { var id = next_id(); var expression = text; text = id; marked_math_expressions[id] = { type: 'block', expression: expression }; } return { type: 'code', raw: raw, lang: lang, text: text }; } } }; var latexRegex = /(?:\${2})([^\n`]+?)(?:\${2})/gi; var katex_count = 0; var next_id = function next_id() { return "__special_katext_id_".concat(katex_count++, "__"); }; var marked_math_expressions = {}; function getMathExpressions() { return marked_math_expressions; } function resetMathExpressions() { katex_count = 0; marked_math_expressions = {}; } function replace_math_with_ids(text) { text = text.replace(latexRegex, function (_match, expression) { var id = next_id(); marked_math_expressions[id] = { type: 'inline', expression: expression }; return id; }); return text; } var original_listitem = renderer.listitem; renderer.listitem = function (text) { return original_listitem(replace_math_with_ids(text)); }; var original_paragraph = renderer.paragraph; renderer.paragraph = function (text) { return original_paragraph(replace_math_with_ids(text)); }; var original_tablecell = renderer.tablecell; renderer.tablecell = function (content, flags) { return original_tablecell(replace_math_with_ids(content), flags); }; renderer.code = function (code, infostring, escaped) { var lang = (infostring || '').match(/\S*/)[0]; if (!lang) { return '
    ' + (escaped ? code : Object(helpers["escape"])(code, true)) + '
    '; } if (['latex', 'katex', 'math'].indexOf(lang) >= 0) { return "

    ".concat(code, "

    "); } else { return "
    ").concat(escaped ? code : Object(helpers["escape"])(code, true), "
    \n"); } }; renderer.heading = function (text, level, raw) { var anchor = this.options.headerPrefix + raw.toLowerCase().replace(/[^\w\\u4e00-\\u9fa5]]+/g, '-'); toc.push({ anchor: anchor, level: level, text: text }); return '' + text + ''; }; marked_default.a.setOptions({ silent: true, gfm: true, pedantic: false }); marked_default.a.use({ tokenizer: tokenizer, renderer: renderer }); /* harmony default export */ var utils_marked = (marked_default.a); // EXTERNAL MODULE: ./node_modules/code-prettify/src/prettify.js var prettify = __webpack_require__("SJMd"); // EXTERNAL MODULE: ./node_modules/hls.js/dist/hls.js var dist_hls = __webpack_require__("ulZh"); var hls_default = /*#__PURE__*/__webpack_require__.n(dist_hls); // EXTERNAL MODULE: ./src/utils/env.ts + 1 modules var env = __webpack_require__("m3rI"); // EXTERNAL MODULE: ./node_modules/katex/dist/katex.js var katex = __webpack_require__("Oy/b"); // EXTERNAL MODULE: ./src/components/PreviewAll/index.tsx var PreviewAll = __webpack_require__("p5ED"); // CONCATENATED MODULE: ./src/components/RenderHtml/index.tsx var preRegex = /]*>/g; function _unescape(str) { var div = document.createElement('div'); div.innerHTML = str; return div.childNodes.length === 0 ? '' : div.childNodes[0].nodeValue; } /* harmony default export */ var RenderHtml = __webpack_exports__["a"] = (function (_ref) { var _ref$value = _ref.value, value = _ref$value === void 0 ? '' : _ref$value, className = _ref.className, showTextOnly = _ref.showTextOnly, showLines = _ref.showLines, _ref$style = _ref.style, style = _ref$style === void 0 ? {} : _ref$style, _ref$stylesPrev = _ref.stylesPrev, stylesPrev = _ref$stylesPrev === void 0 ? {} : _ref$stylesPrev; var str = String(value); var _useState = Object(external_window_React_["useState"])(""), _useState2 = Object(slicedToArray["a" /* default */])(_useState, 2), data = _useState2[0], setData = _useState2[1]; var _useState3 = Object(external_window_React_["useState"])("office"), _useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2), type = _useState4[0], setType = _useState4[1]; var html = Object(external_window_React_["useMemo"])(function () { try { var reg = /\(\s+\/api\/attachments\/|\(\/api\/attachments\/|\(\/attachments\/download\//g; var reg2 = /\"\/api\/attachments\/|\"\/attachments\/download\//g; var reg3 = /\(\s+\/files\/uploads\/|\"\/files\/uploads\//g; str = str.replace(reg, "(" + env["a" /* default */].API_SERVER + "/api/attachments/").replace(reg2, '"' + env["a" /* default */].API_SERVER + "/api/attachments/").replace(reg3, '"' + env["a" /* default */].API_SERVER + "/files/uploads/").replaceAll("http://video.educoder", "https://video.educoder").replaceAll("http://www.educoder.net/api", "https://data.educoder.net/api").replaceAll("https://www.educoder.net/api", "https://data.educoder.net/api").replace(/\r\n/g, "\n"); // str = str.replace(new RegExp("(?[TOC]

    ', getTocContent()); cleanToc(); } rs = rs.replace(/(__special_katext_id_\d+__)/g, function (_match, capture) { var _math_expressions$cap = math_expressions[capture], type = _math_expressions$cap.type, expression = _math_expressions$cap.expression; return Object(katex["renderToString"])(_unescape(expression) || '', { displayMode: type === 'block', throwOnError: false, output: 'html' }); }); rs = rs.replace(/▁/g, '▁▁▁'); resetMathExpressions(); // return dompurify.sanitize(rs) if (showTextOnly) { var dom = document.createElement('div'); dom.innerHTML = rs; return dom.innerText; } setTimeout(function () { return onLoad(); }, 500); return rs; }, [str]); var el = Object(external_window_React_["useRef"])(); lines['WebkitLineClamp'] = showLines; if (showLines) { style = Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, style), lines); } function onAncherHandler(e) { var target = e.target; if (target.tagName.toUpperCase() === 'A') { var ancher = target.getAttribute('href'); if (ancher.indexOf("office") > -1) { e.preventDefault(); setData(ancher); setType("office"); } else if (ancher.indexOf("application/pdf") > -1) { e.preventDefault(); setData(ancher); setType("pdf"); } else if (ancher.indexOf("text/html") > -1) { e.preventDefault(); setData(ancher); setType("html"); } else if (ancher.startsWith('#')) { e.preventDefault(); var viewEl = document.getElementById(ancher.replace('#', '')); if (viewEl) { viewEl.scrollIntoView(true); } } } } var onLoad = function onLoad() { var _el$current; var videoElement = (_el$current = el.current) === null || _el$current === void 0 ? void 0 : _el$current.querySelectorAll('video'); videoElement === null || videoElement === void 0 ? void 0 : videoElement.forEach(function (item) { item.oncontextmenu = function () { return false; }; if (item.src.indexOf('.m3u8') > -1) { if (item.canPlayType('application/vnd.apple.mpegurl')) {} else if (hls_default.a.isSupported()) { var hls = new hls_default.a(); hls.loadSource(item.src); hls.attachMedia(item); } } }); }; Object(external_window_React_["useEffect"])(function () { if (el.current && html) { if (html.match(preRegex)) { window.PR.prettyPrint(); } } if (el.current) { el.current.addEventListener('click', onAncherHandler); return function () { el.current.removeEventListener('click', onAncherHandler); resetMathExpressions(); cleanToc(); }; } }, [html, el.current, onAncherHandler]); return /*#__PURE__*/external_window_React_default.a.createElement(external_window_React_default.a.Fragment, null, /*#__PURE__*/external_window_React_default.a.createElement("div", { ref: el, style: Object(objectSpread2["a" /* default */])({}, style), className: "".concat(className ? className : '', " markdown-body "), dangerouslySetInnerHTML: { __html: html } }), /*#__PURE__*/external_window_React_default.a.createElement(PreviewAll["a" /* default */], { close: true, data: data, type: !!(data !== null && data !== void 0 && data.length) ? type : "", style: Object(objectSpread2["a" /* default */])({}, stylesPrev), onClose: function onClose() { return setData(""); } })); }); /***/ }), /***/ "BU3w": /*!***************************************************!*\ !*** ./node_modules/rc-util/es/Dom/dynamicCSS.js ***! \***************************************************/ /*! exports provided: injectCSS, updateCSS */ /*! exports used: updateCSS */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* unused harmony export injectCSS */ /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return updateCSS; }); /* harmony import */ var _canUseDom__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./canUseDom */ "MNnm"); var MARK_KEY = "rc-util-key"; function getContainer(option) { if (option.attachTo) { return option.attachTo; } var head = document.querySelector('head'); return head || document.body; } function injectCSS(css) { var _option$csp; var option = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (!Object(_canUseDom__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])()) { return null; } var styleNode = document.createElement('style'); if ((_option$csp = option.csp) === null || _option$csp === void 0 ? void 0 : _option$csp.nonce) { var _option$csp2; styleNode.nonce = (_option$csp2 = option.csp) === null || _option$csp2 === void 0 ? void 0 : _option$csp2.nonce; } styleNode.innerHTML = css; var container = getContainer(option); var firstChild = container.firstChild; if (option.prepend && container.prepend) { // Use `prepend` first container.prepend(styleNode); } else if (option.prepend && firstChild) { // Fallback to `insertBefore` like IE not support `prepend` container.insertBefore(styleNode, firstChild); } else { container.appendChild(styleNode); } return styleNode; } var containerCache = new Map(); function updateCSS(css, key) { var option = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var container = getContainer(option); // Get real parent if (!containerCache.has(container)) { var placeholderStyle = injectCSS('', option); var parentNode = placeholderStyle.parentNode; containerCache.set(container, parentNode); parentNode.removeChild(placeholderStyle); } var existNode = Array.from(containerCache.get(container).children).find(function (node) { return node.tagName === 'STYLE' && node[MARK_KEY] === key; }); if (existNode) { var _option$csp3, _option$csp4; if (((_option$csp3 = option.csp) === null || _option$csp3 === void 0 ? void 0 : _option$csp3.nonce) && existNode.nonce !== ((_option$csp4 = option.csp) === null || _option$csp4 === void 0 ? void 0 : _option$csp4.nonce)) { var _option$csp5; existNode.nonce = (_option$csp5 = option.csp) === null || _option$csp5 === void 0 ? void 0 : _option$csp5.nonce; } if (existNode.innerHTML !== css) { existNode.innerHTML = css; } return existNode; } var newNode = injectCSS(css, option); newNode[MARK_KEY] = key; return newNode; } /***/ }), /***/ "BdwD": /*!*****************************************!*\ !*** ./src/components/NoData/index.tsx ***! \*****************************************/ /*! exports provided: default */ /*! exports used: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var antd_es_button_style__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! antd/es/button/style */ "+L6B"); /* harmony import */ var antd_es_button__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! antd/es/button */ "2/Rp"); /* harmony import */ var _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/extends */ "0Owb"); /* harmony import */ var _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/objectSpread2 */ "k1fw"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! react */ "cDcd"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_4__); /* harmony import */ var _assets_images_icons_nodata_png__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/assets/images/icons/nodata.png */ "FOrL"); /* harmony import */ var _assets_images_icons_nodata_png__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_assets_images_icons_nodata_png__WEBPACK_IMPORTED_MODULE_5__); var noData = function noData(_ref) { var _ref$buttonProps = _ref.buttonProps, buttonProps = _ref$buttonProps === void 0 ? {} : _ref$buttonProps, _ref$styles = _ref.styles, styles = _ref$styles === void 0 ? {} : _ref$styles, customText = _ref.customText, ButtonText = _ref.ButtonText, ButtonClick = _ref.ButtonClick, Buttonclass = _ref.Buttonclass, ButtonTwo = _ref.ButtonTwo; return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("section", { className: "tc animated fadeIn", style: Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"])(Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"])({}, { color: '#999', margin: '200px auto' }), styles) }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("img", { src: _assets_images_icons_nodata_png__WEBPACK_IMPORTED_MODULE_5___default.a }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("p", { className: "mt20 font14" }, customText || '暂时还没有相关数据哦!'), ButtonText && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(antd_es_button__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"], Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"])({ className: Buttonclass, onClick: ButtonClick }, buttonProps), ButtonText), ButtonTwo && ButtonTwo); }; /* harmony default export */ __webpack_exports__["a"] = (noData); /***/ }), /***/ "DlQD": /*!*******************************************!*\ !*** ./node_modules/marked/lib/marked.js ***! \*******************************************/ /*! no static exports found */ /*! exports used: default */ /*! ModuleConcatenation bailout: Module is not an ECMAScript module */ /***/ (function(module, exports, __webpack_require__) { /** * marked - a markdown parser * Copyright (c) 2011-2020, Christopher Jeffrey. (MIT Licensed) * https://github.com/markedjs/marked */ /** * DO NOT EDIT THIS FILE * The code in this file is generated from files in ./src/ */ (function (global, factory) { true ? module.exports = factory() : undefined; }(this, (function () { 'use strict'; function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } it = o[Symbol.iterator](); return it.next.bind(it); } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var defaults = createCommonjsModule(function (module) { function getDefaults() { return { baseUrl: null, breaks: false, gfm: true, headerIds: true, headerPrefix: '', highlight: null, langPrefix: 'language-', mangle: true, pedantic: false, renderer: null, sanitize: false, sanitizer: null, silent: false, smartLists: false, smartypants: false, tokenizer: null, walkTokens: null, xhtml: false }; } function changeDefaults(newDefaults) { module.exports.defaults = newDefaults; } module.exports = { defaults: getDefaults(), getDefaults: getDefaults, changeDefaults: changeDefaults }; }); var defaults_1 = defaults.defaults; var defaults_2 = defaults.getDefaults; var defaults_3 = defaults.changeDefaults; /** * Helpers */ var escapeTest = /[&<>"']/; var escapeReplace = /[&<>"']/g; var escapeTestNoEncode = /[<>"']|&(?!#?\w+;)/; var escapeReplaceNoEncode = /[<>"']|&(?!#?\w+;)/g; var escapeReplacements = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }; var getEscapeReplacement = function getEscapeReplacement(ch) { return escapeReplacements[ch]; }; function escape(html, encode) { if (encode) { if (escapeTest.test(html)) { return html.replace(escapeReplace, getEscapeReplacement); } } else { if (escapeTestNoEncode.test(html)) { return html.replace(escapeReplaceNoEncode, getEscapeReplacement); } } return html; } var unescapeTest = /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig; function unescape(html) { // explicitly match decimal, hex, and named HTML entities return html.replace(unescapeTest, function (_, n) { n = n.toLowerCase(); if (n === 'colon') return ':'; if (n.charAt(0) === '#') { return n.charAt(1) === 'x' ? String.fromCharCode(parseInt(n.substring(2), 16)) : String.fromCharCode(+n.substring(1)); } return ''; }); } var caret = /(^|[^\[])\^/g; function edit(regex, opt) { regex = regex.source || regex; opt = opt || ''; var obj = { replace: function replace(name, val) { val = val.source || val; val = val.replace(caret, '$1'); regex = regex.replace(name, val); return obj; }, getRegex: function getRegex() { return new RegExp(regex, opt); } }; return obj; } var nonWordAndColonTest = /[^\w:]/g; var originIndependentUrl = /^$|^[a-z][a-z0-9+.-]*:|^[?#]/i; function cleanUrl(sanitize, base, href) { if (sanitize) { var prot; try { prot = decodeURIComponent(unescape(href)).replace(nonWordAndColonTest, '').toLowerCase(); } catch (e) { return null; } if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) { return null; } } if (base && !originIndependentUrl.test(href)) { href = resolveUrl(base, href); } try { href = encodeURI(href).replace(/%25/g, '%'); } catch (e) { return null; } return href; } var baseUrls = {}; var justDomain = /^[^:]+:\/*[^/]*$/; var protocol = /^([^:]+:)[\s\S]*$/; var domain = /^([^:]+:\/*[^/]*)[\s\S]*$/; function resolveUrl(base, href) { if (!baseUrls[' ' + base]) { // we can ignore everything in base after the last slash of its path component, // but we might need to add _that_ // https://tools.ietf.org/html/rfc3986#section-3 if (justDomain.test(base)) { baseUrls[' ' + base] = base + '/'; } else { baseUrls[' ' + base] = rtrim(base, '/', true); } } base = baseUrls[' ' + base]; var relativeBase = base.indexOf(':') === -1; if (href.substring(0, 2) === '//') { if (relativeBase) { return href; } return base.replace(protocol, '$1') + href; } else if (href.charAt(0) === '/') { if (relativeBase) { return href; } return base.replace(domain, '$1') + href; } else { return base + href; } } var noopTest = { exec: function noopTest() {} }; function merge(obj) { var i = 1, target, key; for (; i < arguments.length; i++) { target = arguments[i]; for (key in target) { if (Object.prototype.hasOwnProperty.call(target, key)) { obj[key] = target[key]; } } } return obj; } function splitCells(tableRow, count) { // ensure that every cell-delimiting pipe has a space // before it to distinguish it from an escaped pipe var row = tableRow.replace(/\|/g, function (match, offset, str) { var escaped = false, curr = offset; while (--curr >= 0 && str[curr] === '\\') { escaped = !escaped; } if (escaped) { // odd number of slashes means | is escaped // so we leave it alone return '|'; } else { // add space before unescaped | return ' |'; } }), cells = row.split(/ \|/); var i = 0; if (cells.length > count) { cells.splice(count); } else { while (cells.length < count) { cells.push(''); } } for (; i < cells.length; i++) { // leading or trailing whitespace is ignored per the gfm spec cells[i] = cells[i].trim().replace(/\\\|/g, '|'); } return cells; } // Remove trailing 'c's. Equivalent to str.replace(/c*$/, ''). // /c*$/ is vulnerable to REDOS. // invert: Remove suffix of non-c chars instead. Default falsey. function rtrim(str, c, invert) { var l = str.length; if (l === 0) { return ''; } // Length of suffix matching the invert condition. var suffLen = 0; // Step left until we fail to match the invert condition. while (suffLen < l) { var currChar = str.charAt(l - suffLen - 1); if (currChar === c && !invert) { suffLen++; } else if (currChar !== c && invert) { suffLen++; } else { break; } } return str.substr(0, l - suffLen); } function findClosingBracket(str, b) { if (str.indexOf(b[1]) === -1) { return -1; } var l = str.length; var level = 0, i = 0; for (; i < l; i++) { if (str[i] === '\\') { i++; } else if (str[i] === b[0]) { level++; } else if (str[i] === b[1]) { level--; if (level < 0) { return i; } } } return -1; } function checkSanitizeDeprecation(opt) { if (opt && opt.sanitize && !opt.silent) { console.warn('marked(): sanitize and sanitizer parameters are deprecated since version 0.7.0, should not be used and will be removed in the future. Read more here: https://marked.js.org/#/USING_ADVANCED.md#options'); } } var helpers = { escape: escape, unescape: unescape, edit: edit, cleanUrl: cleanUrl, resolveUrl: resolveUrl, noopTest: noopTest, merge: merge, splitCells: splitCells, rtrim: rtrim, findClosingBracket: findClosingBracket, checkSanitizeDeprecation: checkSanitizeDeprecation }; var defaults$1 = defaults.defaults; var rtrim$1 = helpers.rtrim, splitCells$1 = helpers.splitCells, _escape = helpers.escape, findClosingBracket$1 = helpers.findClosingBracket; function outputLink(cap, link, raw) { var href = link.href; var title = link.title ? _escape(link.title) : null; var text = cap[1].replace(/\\([\[\]])/g, '$1'); if (cap[0].charAt(0) !== '!') { return { type: 'link', raw: raw, href: href, title: title, text: text }; } else { return { type: 'image', raw: raw, href: href, title: title, text: _escape(text) }; } } function indentCodeCompensation(raw, text) { var matchIndentToCode = raw.match(/^(\s+)(?:```)/); if (matchIndentToCode === null) { return text; } var indentToCode = matchIndentToCode[1]; return text.split('\n').map(function (node) { var matchIndentInNode = node.match(/^\s+/); if (matchIndentInNode === null) { return node; } var indentInNode = matchIndentInNode[0]; if (indentInNode.length >= indentToCode.length) { return node.slice(indentToCode.length); } return node; }).join('\n'); } /** * Tokenizer */ var Tokenizer_1 = /*#__PURE__*/function () { function Tokenizer(options) { this.options = options || defaults$1; } var _proto = Tokenizer.prototype; _proto.space = function space(src) { var cap = this.rules.block.newline.exec(src); if (cap) { if (cap[0].length > 1) { return { type: 'space', raw: cap[0] }; } return { raw: '\n' }; } }; _proto.code = function code(src, tokens) { var cap = this.rules.block.code.exec(src); if (cap) { var lastToken = tokens[tokens.length - 1]; // An indented code block cannot interrupt a paragraph. if (lastToken && lastToken.type === 'paragraph') { return { raw: cap[0], text: cap[0].trimRight() }; } var text = cap[0].replace(/^ {4}/gm, ''); return { type: 'code', raw: cap[0], codeBlockStyle: 'indented', text: !this.options.pedantic ? rtrim$1(text, '\n') : text }; } }; _proto.fences = function fences(src) { var cap = this.rules.block.fences.exec(src); if (cap) { var raw = cap[0]; var text = indentCodeCompensation(raw, cap[3] || ''); return { type: 'code', raw: raw, lang: cap[2] ? cap[2].trim() : cap[2], text: text }; } }; _proto.heading = function heading(src) { var cap = this.rules.block.heading.exec(src); if (cap) { return { type: 'heading', raw: cap[0], depth: cap[1].length, text: cap[2] }; } }; _proto.nptable = function nptable(src) { var cap = this.rules.block.nptable.exec(src); if (cap) { var item = { type: 'table', header: splitCells$1(cap[1].replace(/^ *| *\| *$/g, '')), align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */), cells: cap[3] ? cap[3].replace(/\n$/, '').split('\n') : [], raw: cap[0] }; if (item.header.length === item.align.length) { var l = item.align.length; var i; for (i = 0; i < l; i++) { if (/^ *-+: *$/.test(item.align[i])) { item.align[i] = 'right'; } else if (/^ *:-+: *$/.test(item.align[i])) { item.align[i] = 'center'; } else if (/^ *:-+ *$/.test(item.align[i])) { item.align[i] = 'left'; } else { item.align[i] = null; } } l = item.cells.length; for (i = 0; i < l; i++) { item.cells[i] = splitCells$1(item.cells[i], item.header.length); } return item; } } }; _proto.hr = function hr(src) { var cap = this.rules.block.hr.exec(src); if (cap) { return { type: 'hr', raw: cap[0] }; } }; _proto.blockquote = function blockquote(src) { var cap = this.rules.block.blockquote.exec(src); if (cap) { var text = cap[0].replace(/^ *> ?/gm, ''); return { type: 'blockquote', raw: cap[0], text: text }; } }; _proto.list = function list(src) { var cap = this.rules.block.list.exec(src); if (cap) { var raw = cap[0]; var bull = cap[2]; var isordered = bull.length > 1; var isparen = bull[bull.length - 1] === ')'; var list = { type: 'list', raw: raw, ordered: isordered, start: isordered ? +bull.slice(0, -1) : '', loose: false, items: [] }; // Get each top-level item. var itemMatch = cap[0].match(this.rules.block.item); var next = false, item, space, b, addBack, loose, istask, ischecked; var l = itemMatch.length; for (var i = 0; i < l; i++) { item = itemMatch[i]; raw = item; // Remove the list item's bullet // so it is seen as the next token. space = item.length; item = item.replace(/^ *([*+-]|\d+[.)]) */, ''); // Outdent whatever the // list item contains. Hacky. if (~item.indexOf('\n ')) { space -= item.length; item = !this.options.pedantic ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '') : item.replace(/^ {1,4}/gm, ''); } // Determine whether the next list item belongs here. // Backpedal if it does not belong in this list. if (i !== l - 1) { b = this.rules.block.bullet.exec(itemMatch[i + 1])[0]; if (isordered ? b.length === 1 || !isparen && b[b.length - 1] === ')' : b.length > 1 || this.options.smartLists && b !== bull) { addBack = itemMatch.slice(i + 1).join('\n'); list.raw = list.raw.substring(0, list.raw.length - addBack.length); i = l - 1; } } // Determine whether item is loose or not. // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/ // for discount behavior. loose = next || /\n\n(?!\s*$)/.test(item); if (i !== l - 1) { next = item.charAt(item.length - 1) === '\n'; if (!loose) loose = next; } if (loose) { list.loose = true; } // Check for task list items istask = /^\[[ xX]\] /.test(item); ischecked = undefined; if (istask) { ischecked = item[1] !== ' '; item = item.replace(/^\[[ xX]\] +/, ''); } list.items.push({ type: 'list_item', raw: raw, task: istask, checked: ischecked, loose: loose, text: item }); } return list; } }; _proto.html = function html(src) { var cap = this.rules.block.html.exec(src); if (cap) { return { type: this.options.sanitize ? 'paragraph' : 'html', raw: cap[0], pre: !this.options.sanitizer && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'), text: this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : _escape(cap[0]) : cap[0] }; } }; _proto.def = function def(src) { var cap = this.rules.block.def.exec(src); if (cap) { if (cap[3]) cap[3] = cap[3].substring(1, cap[3].length - 1); var tag = cap[1].toLowerCase().replace(/\s+/g, ' '); return { tag: tag, raw: cap[0], href: cap[2], title: cap[3] }; } }; _proto.table = function table(src) { var cap = this.rules.block.table.exec(src); if (cap) { var item = { type: 'table', header: splitCells$1(cap[1].replace(/^ *| *\| *$/g, '')), align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */), cells: cap[3] ? cap[3].replace(/\n$/, '').split('\n') : [] }; if (item.header.length === item.align.length) { item.raw = cap[0]; var l = item.align.length; var i; for (i = 0; i < l; i++) { if (/^ *-+: *$/.test(item.align[i])) { item.align[i] = 'right'; } else if (/^ *:-+: *$/.test(item.align[i])) { item.align[i] = 'center'; } else if (/^ *:-+ *$/.test(item.align[i])) { item.align[i] = 'left'; } else { item.align[i] = null; } } l = item.cells.length; for (i = 0; i < l; i++) { item.cells[i] = splitCells$1(item.cells[i].replace(/^ *\| *| *\| *$/g, ''), item.header.length); } return item; } } }; _proto.lheading = function lheading(src) { var cap = this.rules.block.lheading.exec(src); if (cap) { return { type: 'heading', raw: cap[0], depth: cap[2].charAt(0) === '=' ? 1 : 2, text: cap[1] }; } }; _proto.paragraph = function paragraph(src) { var cap = this.rules.block.paragraph.exec(src); if (cap) { return { type: 'paragraph', raw: cap[0], text: cap[1].charAt(cap[1].length - 1) === '\n' ? cap[1].slice(0, -1) : cap[1] }; } }; _proto.text = function text(src, tokens) { var cap = this.rules.block.text.exec(src); if (cap) { var lastToken = tokens[tokens.length - 1]; if (lastToken && lastToken.type === 'text') { return { raw: cap[0], text: cap[0] }; } return { type: 'text', raw: cap[0], text: cap[0] }; } }; _proto.escape = function escape(src) { var cap = this.rules.inline.escape.exec(src); if (cap) { return { type: 'escape', raw: cap[0], text: _escape(cap[1]) }; } }; _proto.tag = function tag(src, inLink, inRawBlock) { var cap = this.rules.inline.tag.exec(src); if (cap) { if (!inLink && /^/i.test(cap[0])) { inLink = false; } if (!inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(cap[0])) { inRawBlock = true; } else if (inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(cap[0])) { inRawBlock = false; } return { type: this.options.sanitize ? 'text' : 'html', raw: cap[0], inLink: inLink, inRawBlock: inRawBlock, text: this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : _escape(cap[0]) : cap[0] }; } }; _proto.link = function link(src) { var cap = this.rules.inline.link.exec(src); if (cap) { var lastParenIndex = findClosingBracket$1(cap[2], '()'); if (lastParenIndex > -1) { var start = cap[0].indexOf('!') === 0 ? 5 : 4; var linkLen = start + cap[1].length + lastParenIndex; cap[2] = cap[2].substring(0, lastParenIndex); cap[0] = cap[0].substring(0, linkLen).trim(); cap[3] = ''; } var href = cap[2]; var title = ''; if (this.options.pedantic) { var link = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href); if (link) { href = link[1]; title = link[3]; } else { title = ''; } } else { title = cap[3] ? cap[3].slice(1, -1) : ''; } href = href.trim().replace(/^<([\s\S]*)>$/, '$1'); var token = outputLink(cap, { href: href ? href.replace(this.rules.inline._escapes, '$1') : href, title: title ? title.replace(this.rules.inline._escapes, '$1') : title }, cap[0]); return token; } }; _proto.reflink = function reflink(src, links) { var cap; if ((cap = this.rules.inline.reflink.exec(src)) || (cap = this.rules.inline.nolink.exec(src))) { var link = (cap[2] || cap[1]).replace(/\s+/g, ' '); link = links[link.toLowerCase()]; if (!link || !link.href) { var text = cap[0].charAt(0); return { type: 'text', raw: text, text: text }; } var token = outputLink(cap, link, cap[0]); return token; } }; _proto.strong = function strong(src, maskedSrc, prevChar) { if (prevChar === void 0) { prevChar = ''; } var match = this.rules.inline.strong.start.exec(src); if (match && (!match[1] || match[1] && (prevChar === '' || this.rules.inline.punctuation.exec(prevChar)))) { maskedSrc = maskedSrc.slice(-1 * src.length); var endReg = match[0] === '**' ? this.rules.inline.strong.endAst : this.rules.inline.strong.endUnd; endReg.lastIndex = 0; var cap; while ((match = endReg.exec(maskedSrc)) != null) { cap = this.rules.inline.strong.middle.exec(maskedSrc.slice(0, match.index + 3)); if (cap) { return { type: 'strong', raw: src.slice(0, cap[0].length), text: src.slice(2, cap[0].length - 2) }; } } } }; _proto.em = function em(src, maskedSrc, prevChar) { if (prevChar === void 0) { prevChar = ''; } var match = this.rules.inline.em.start.exec(src); if (match && (!match[1] || match[1] && (prevChar === '' || this.rules.inline.punctuation.exec(prevChar)))) { maskedSrc = maskedSrc.slice(-1 * src.length); var endReg = match[0] === '*' ? this.rules.inline.em.endAst : this.rules.inline.em.endUnd; endReg.lastIndex = 0; var cap; while ((match = endReg.exec(maskedSrc)) != null) { cap = this.rules.inline.em.middle.exec(maskedSrc.slice(0, match.index + 2)); if (cap) { return { type: 'em', raw: src.slice(0, cap[0].length), text: src.slice(1, cap[0].length - 1) }; } } } }; _proto.codespan = function codespan(src) { var cap = this.rules.inline.code.exec(src); if (cap) { var text = cap[2].replace(/\n/g, ' '); var hasNonSpaceChars = /[^ ]/.test(text); var hasSpaceCharsOnBothEnds = text.startsWith(' ') && text.endsWith(' '); if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) { text = text.substring(1, text.length - 1); } text = _escape(text, true); return { type: 'codespan', raw: cap[0], text: text }; } }; _proto.br = function br(src) { var cap = this.rules.inline.br.exec(src); if (cap) { return { type: 'br', raw: cap[0] }; } }; _proto.del = function del(src) { var cap = this.rules.inline.del.exec(src); if (cap) { return { type: 'del', raw: cap[0], text: cap[1] }; } }; _proto.autolink = function autolink(src, mangle) { var cap = this.rules.inline.autolink.exec(src); if (cap) { var text, href; if (cap[2] === '@') { text = _escape(this.options.mangle ? mangle(cap[1]) : cap[1]); href = 'mailto:' + text; } else { text = _escape(cap[1]); href = text; } return { type: 'link', raw: cap[0], text: text, href: href, tokens: [{ type: 'text', raw: text, text: text }] }; } }; _proto.url = function url(src, mangle) { var cap; if (cap = this.rules.inline.url.exec(src)) { var text, href; if (cap[2] === '@') { text = _escape(this.options.mangle ? mangle(cap[0]) : cap[0]); href = 'mailto:' + text; } else { // do extended autolink path validation var prevCapZero; do { prevCapZero = cap[0]; cap[0] = this.rules.inline._backpedal.exec(cap[0])[0]; } while (prevCapZero !== cap[0]); text = _escape(cap[0]); if (cap[1] === 'www.') { href = 'http://' + text; } else { href = text; } } return { type: 'link', raw: cap[0], text: text, href: href, tokens: [{ type: 'text', raw: text, text: text }] }; } }; _proto.inlineText = function inlineText(src, inRawBlock, smartypants) { var cap = this.rules.inline.text.exec(src); if (cap) { var text; if (inRawBlock) { text = this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : _escape(cap[0]) : cap[0]; } else { text = _escape(this.options.smartypants ? smartypants(cap[0]) : cap[0]); } return { type: 'text', raw: cap[0], text: text }; } }; return Tokenizer; }(); var noopTest$1 = helpers.noopTest, edit$1 = helpers.edit, merge$1 = helpers.merge; /** * Block-Level Grammar */ var block = { newline: /^\n+/, code: /^( {4}[^\n]+\n*)+/, fences: /^ {0,3}(`{3,}(?=[^`\n]*\n)|~{3,})([^\n]*)\n(?:|([\s\S]*?)\n)(?: {0,3}\1[~`]* *(?:\n+|$)|$)/, hr: /^ {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)/, heading: /^ {0,3}(#{1,6}) +([^\n]*?)(?: +#+)? *(?:\n+|$)/, blockquote: /^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/, list: /^( {0,3})(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/, html: '^ {0,3}(?:' // optional indentation + '<(script|pre|style)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)' // (1) + '|comment[^\\n]*(\\n+|$)' // (2) + '|<\\?[\\s\\S]*?\\?>\\n*' // (3) + '|\\n*' // (4) + '|\\n*' // (5) + '|)[\\s\\S]*?(?:\\n{2,}|$)' // (6) + '|<(?!script|pre|style)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$)' // (7) open tag + '|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$)' // (7) closing tag + ')', def: /^ {0,3}\[(label)\]: *\n? *]+)>?(?:(?: +\n? *| *\n *)(title))? *(?:\n+|$)/, nptable: noopTest$1, table: noopTest$1, lheading: /^([^\n]+)\n {0,3}(=+|-+) *(?:\n+|$)/, // regex template, placeholders will be replaced according to different paragraph // interruption rules of commonmark and the original markdown spec: _paragraph: /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html)[^\n]+)*)/, text: /^[^\n]+/ }; block._label = /(?!\s*\])(?:\\[\[\]]|[^\[\]])+/; block._title = /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/; block.def = edit$1(block.def).replace('label', block._label).replace('title', block._title).getRegex(); block.bullet = /(?:[*+-]|\d{1,9}[.)])/; block.item = /^( *)(bull) ?[^\n]*(?:\n(?!\1bull ?)[^\n]*)*/; block.item = edit$1(block.item, 'gm').replace(/bull/g, block.bullet).getRegex(); block.list = edit$1(block.list).replace(/bull/g, block.bullet).replace('hr', '\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))').replace('def', '\\n+(?=' + block.def.source + ')').getRegex(); block._tag = 'address|article|aside|base|basefont|blockquote|body|caption' + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption' + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe' + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option' + '|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr' + '|track|ul'; block._comment = //; block.html = edit$1(block.html, 'i').replace('comment', block._comment).replace('tag', block._tag).replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(); block.paragraph = edit$1(block._paragraph).replace('hr', block.hr).replace('heading', ' {0,3}#{1,6} ').replace('|lheading', '') // setex headings don't interrupt commonmark paragraphs .replace('blockquote', ' {0,3}>').replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n').replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt .replace('html', ')|<(?:script|pre|style|!--)').replace('tag', block._tag) // pars can be interrupted by type (6) html blocks .getRegex(); block.blockquote = edit$1(block.blockquote).replace('paragraph', block.paragraph).getRegex(); /** * Normal Block Grammar */ block.normal = merge$1({}, block); /** * GFM Block Grammar */ block.gfm = merge$1({}, block.normal, { nptable: '^ *([^|\\n ].*\\|.*)\\n' // Header + ' *([-:]+ *\\|[-| :]*)' // Align + '(?:\\n((?:(?!\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)', // Cells table: '^ *\\|(.+)\\n' // Header + ' *\\|?( *[-:]+[-| :]*)' // Align + '(?:\\n *((?:(?!\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)' // Cells }); block.gfm.nptable = edit$1(block.gfm.nptable).replace('hr', block.hr).replace('heading', ' {0,3}#{1,6} ').replace('blockquote', ' {0,3}>').replace('code', ' {4}[^\\n]').replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n').replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt .replace('html', ')|<(?:script|pre|style|!--)').replace('tag', block._tag) // tables can be interrupted by type (6) html blocks .getRegex(); block.gfm.table = edit$1(block.gfm.table).replace('hr', block.hr).replace('heading', ' {0,3}#{1,6} ').replace('blockquote', ' {0,3}>').replace('code', ' {4}[^\\n]').replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n').replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt .replace('html', ')|<(?:script|pre|style|!--)').replace('tag', block._tag) // tables can be interrupted by type (6) html blocks .getRegex(); /** * Pedantic grammar (original John Gruber's loose markdown specification) */ block.pedantic = merge$1({}, block.normal, { html: edit$1('^ *(?:comment *(?:\\n|\\s*$)' + '|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)' // closed tag + '|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))').replace('comment', block._comment).replace(/tag/g, '(?!(?:' + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub' + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)' + '\\b)\\w+(?!:|[^\\w\\s@]*@)\\b').getRegex(), def: /^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/, heading: /^ *(#{1,6}) *([^\n]+?) *(?:#+ *)?(?:\n+|$)/, fences: noopTest$1, // fences not supported paragraph: edit$1(block.normal._paragraph).replace('hr', block.hr).replace('heading', ' *#{1,6} *[^\n]').replace('lheading', block.lheading).replace('blockquote', ' {0,3}>').replace('|fences', '').replace('|list', '').replace('|html', '').getRegex() }); /** * Inline-Level Grammar */ var inline = { escape: /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/, autolink: /^<(scheme:[^\s\x00-\x1f<>]*|email)>/, url: noopTest$1, tag: '^comment' + '|^' // self-closing tag + '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag + '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. + '|^' // declaration, e.g. + '|^', // CDATA section link: /^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/, reflink: /^!?\[(label)\]\[(?!\s*\])((?:\\[\[\]]?|[^\[\]\\])+)\]/, nolink: /^!?\[(?!\s*\])((?:\[[^\[\]]*\]|\\[\[\]]|[^\[\]])*)\](?:\[\])?/, reflinkSearch: 'reflink|nolink(?!\\()', strong: { start: /^(?:(\*\*(?=[*punctuation]))|\*\*)(?![\s])|__/, // (1) returns if starts w/ punctuation middle: /^\*\*(?:(?:(?!overlapSkip)(?:[^*]|\\\*)|overlapSkip)|\*(?:(?!overlapSkip)(?:[^*]|\\\*)|overlapSkip)*?\*)+?\*\*$|^__(?![\s])((?:(?:(?!overlapSkip)(?:[^_]|\\_)|overlapSkip)|_(?:(?!overlapSkip)(?:[^_]|\\_)|overlapSkip)*?_)+?)__$/, endAst: /[^punctuation\s]\*\*(?!\*)|[punctuation]\*\*(?!\*)(?:(?=[punctuation\s]|$))/, // last char can't be punct, or final * must also be followed by punct (or endline) endUnd: /[^\s]__(?!_)(?:(?=[punctuation\s])|$)/ // last char can't be a space, and final _ must preceed punct or \s (or endline) }, em: { start: /^(?:(\*(?=[punctuation]))|\*)(?![*\s])|_/, // (1) returns if starts w/ punctuation middle: /^\*(?:(?:(?!overlapSkip)(?:[^*]|\\\*)|overlapSkip)|\*(?:(?!overlapSkip)(?:[^*]|\\\*)|overlapSkip)*?\*)+?\*$|^_(?![_\s])(?:(?:(?!overlapSkip)(?:[^_]|\\_)|overlapSkip)|_(?:(?!overlapSkip)(?:[^_]|\\_)|overlapSkip)*?_)+?_$/, endAst: /[^punctuation\s]\*(?!\*)|[punctuation]\*(?!\*)(?:(?=[punctuation\s]|$))/, // last char can't be punct, or final * must also be followed by punct (or endline) endUnd: /[^\s]_(?!_)(?:(?=[punctuation\s])|$)/ // last char can't be a space, and final _ must preceed punct or \s (or endline) }, code: /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/, br: /^( {2,}|\\)\n(?!\s*$)/, del: noopTest$1, text: /^(`+|[^`])(?:[\s\S]*?(?:(?=[\\?@\\[\\]`^{|}~'; inline.punctuation = edit$1(inline.punctuation).replace(/punctuation/g, inline._punctuation).getRegex(); // sequences em should skip over [title](link), `code`, inline._blockSkip = '\\[[^\\]]*?\\]\\([^\\)]*?\\)|`[^`]*?`|<[^>]*?>'; inline._overlapSkip = '__[^_]*?__|\\*\\*\\[^\\*\\]*?\\*\\*'; inline.em.start = edit$1(inline.em.start).replace(/punctuation/g, inline._punctuation).getRegex(); inline.em.middle = edit$1(inline.em.middle).replace(/punctuation/g, inline._punctuation).replace(/overlapSkip/g, inline._overlapSkip).getRegex(); inline.em.endAst = edit$1(inline.em.endAst, 'g').replace(/punctuation/g, inline._punctuation).getRegex(); inline.em.endUnd = edit$1(inline.em.endUnd, 'g').replace(/punctuation/g, inline._punctuation).getRegex(); inline.strong.start = edit$1(inline.strong.start).replace(/punctuation/g, inline._punctuation).getRegex(); inline.strong.middle = edit$1(inline.strong.middle).replace(/punctuation/g, inline._punctuation).replace(/blockSkip/g, inline._blockSkip).getRegex(); inline.strong.endAst = edit$1(inline.strong.endAst, 'g').replace(/punctuation/g, inline._punctuation).getRegex(); inline.strong.endUnd = edit$1(inline.strong.endUnd, 'g').replace(/punctuation/g, inline._punctuation).getRegex(); inline.blockSkip = edit$1(inline._blockSkip, 'g').getRegex(); inline.overlapSkip = edit$1(inline._overlapSkip, 'g').getRegex(); inline._escapes = /\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g; inline._scheme = /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/; inline._email = /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/; inline.autolink = edit$1(inline.autolink).replace('scheme', inline._scheme).replace('email', inline._email).getRegex(); inline._attribute = /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/; inline.tag = edit$1(inline.tag).replace('comment', block._comment).replace('attribute', inline._attribute).getRegex(); inline._label = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/; inline._href = /<(?:\\[<>]?|[^\s<>\\])*>|[^\s\x00-\x1f]*/; inline._title = /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/; inline.link = edit$1(inline.link).replace('label', inline._label).replace('href', inline._href).replace('title', inline._title).getRegex(); inline.reflink = edit$1(inline.reflink).replace('label', inline._label).getRegex(); inline.reflinkSearch = edit$1(inline.reflinkSearch, 'g').replace('reflink', inline.reflink).replace('nolink', inline.nolink).getRegex(); /** * Normal Inline Grammar */ inline.normal = merge$1({}, inline); /** * Pedantic Inline Grammar */ inline.pedantic = merge$1({}, inline.normal, { strong: { start: /^__|\*\*/, middle: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/, endAst: /\*\*(?!\*)/g, endUnd: /__(?!_)/g }, em: { start: /^_|\*/, middle: /^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/, endAst: /\*(?!\*)/g, endUnd: /_(?!_)/g }, link: edit$1(/^!?\[(label)\]\((.*?)\)/).replace('label', inline._label).getRegex(), reflink: edit$1(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace('label', inline._label).getRegex() }); /** * GFM Inline Grammar */ inline.gfm = merge$1({}, inline.normal, { escape: edit$1(inline.escape).replace('])', '~|])').getRegex(), _extended_email: /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/, url: /^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, _backpedal: /(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/, del: /^~+(?=\S)([\s\S]*?\S)~+/, text: /^(`+|[^`])(?:[\s\S]*?(?:(?=[\\ 0.5) { ch = 'x' + ch.toString(16); } out += '&#' + ch + ';'; } return out; } /** * Block Lexer */ var Lexer_1 = /*#__PURE__*/function () { function Lexer(options) { this.tokens = []; this.tokens.links = Object.create(null); this.options = options || defaults$2; this.options.tokenizer = this.options.tokenizer || new Tokenizer_1(); this.tokenizer = this.options.tokenizer; this.tokenizer.options = this.options; var rules = { block: block$1.normal, inline: inline$1.normal }; if (this.options.pedantic) { rules.block = block$1.pedantic; rules.inline = inline$1.pedantic; } else if (this.options.gfm) { rules.block = block$1.gfm; if (this.options.breaks) { rules.inline = inline$1.breaks; } else { rules.inline = inline$1.gfm; } } this.tokenizer.rules = rules; } /** * Expose Rules */ /** * Static Lex Method */ Lexer.lex = function lex(src, options) { var lexer = new Lexer(options); return lexer.lex(src); } /** * Preprocessing */ ; var _proto = Lexer.prototype; _proto.lex = function lex(src) { src = src.replace(/\r\n|\r/g, '\n').replace(/\t/g, ' '); this.blockTokens(src, this.tokens, true); this.inline(this.tokens); return this.tokens; } /** * Lexing */ ; _proto.blockTokens = function blockTokens(src, tokens, top) { if (tokens === void 0) { tokens = []; } if (top === void 0) { top = true; } src = src.replace(/^ +$/gm, ''); var token, i, l, lastToken; while (src) { // newline if (token = this.tokenizer.space(src)) { src = src.substring(token.raw.length); if (token.type) { tokens.push(token); } continue; } // code if (token = this.tokenizer.code(src, tokens)) { src = src.substring(token.raw.length); if (token.type) { tokens.push(token); } else { lastToken = tokens[tokens.length - 1]; lastToken.raw += '\n' + token.raw; lastToken.text += '\n' + token.text; } continue; } // fences if (token = this.tokenizer.fences(src)) { src = src.substring(token.raw.length); tokens.push(token); continue; } // heading if (token = this.tokenizer.heading(src)) { src = src.substring(token.raw.length); tokens.push(token); continue; } // table no leading pipe (gfm) if (token = this.tokenizer.nptable(src)) { src = src.substring(token.raw.length); tokens.push(token); continue; } // hr if (token = this.tokenizer.hr(src)) { src = src.substring(token.raw.length); tokens.push(token); continue; } // blockquote if (token = this.tokenizer.blockquote(src)) { src = src.substring(token.raw.length); token.tokens = this.blockTokens(token.text, [], top); tokens.push(token); continue; } // list if (token = this.tokenizer.list(src)) { src = src.substring(token.raw.length); l = token.items.length; for (i = 0; i < l; i++) { token.items[i].tokens = this.blockTokens(token.items[i].text, [], false); } tokens.push(token); continue; } // html if (token = this.tokenizer.html(src)) { src = src.substring(token.raw.length); tokens.push(token); continue; } // def if (top && (token = this.tokenizer.def(src))) { src = src.substring(token.raw.length); if (!this.tokens.links[token.tag]) { this.tokens.links[token.tag] = { href: token.href, title: token.title }; } continue; } // table (gfm) if (token = this.tokenizer.table(src)) { src = src.substring(token.raw.length); tokens.push(token); continue; } // lheading if (token = this.tokenizer.lheading(src)) { src = src.substring(token.raw.length); tokens.push(token); continue; } // top-level paragraph if (top && (token = this.tokenizer.paragraph(src))) { src = src.substring(token.raw.length); tokens.push(token); continue; } // text if (token = this.tokenizer.text(src, tokens)) { src = src.substring(token.raw.length); if (token.type) { tokens.push(token); } else { lastToken = tokens[tokens.length - 1]; lastToken.raw += '\n' + token.raw; lastToken.text += '\n' + token.text; } continue; } if (src) { var errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0); if (this.options.silent) { console.error(errMsg); break; } else { throw new Error(errMsg); } } } return tokens; }; _proto.inline = function inline(tokens) { var i, j, k, l2, row, token; var l = tokens.length; for (i = 0; i < l; i++) { token = tokens[i]; switch (token.type) { case 'paragraph': case 'text': case 'heading': { token.tokens = []; this.inlineTokens(token.text, token.tokens); break; } case 'table': { token.tokens = { header: [], cells: [] }; // header l2 = token.header.length; for (j = 0; j < l2; j++) { token.tokens.header[j] = []; this.inlineTokens(token.header[j], token.tokens.header[j]); } // cells l2 = token.cells.length; for (j = 0; j < l2; j++) { row = token.cells[j]; token.tokens.cells[j] = []; for (k = 0; k < row.length; k++) { token.tokens.cells[j][k] = []; this.inlineTokens(row[k], token.tokens.cells[j][k]); } } break; } case 'blockquote': { this.inline(token.tokens); break; } case 'list': { l2 = token.items.length; for (j = 0; j < l2; j++) { this.inline(token.items[j].tokens); } break; } } } return tokens; } /** * Lexing/Compiling */ ; _proto.inlineTokens = function inlineTokens(src, tokens, inLink, inRawBlock, prevChar) { if (tokens === void 0) { tokens = []; } if (inLink === void 0) { inLink = false; } if (inRawBlock === void 0) { inRawBlock = false; } if (prevChar === void 0) { prevChar = ''; } var token; // String with links masked to avoid interference with em and strong var maskedSrc = src; var match; // Mask out reflinks if (this.tokens.links) { var links = Object.keys(this.tokens.links); if (links.length > 0) { while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) { if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) { maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex); } } } } // Mask out other blocks while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) { maskedSrc = maskedSrc.slice(0, match.index) + '[' + 'a'.repeat(match[0].length - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex); } while (src) { // escape if (token = this.tokenizer.escape(src)) { src = src.substring(token.raw.length); tokens.push(token); continue; } // tag if (token = this.tokenizer.tag(src, inLink, inRawBlock)) { src = src.substring(token.raw.length); inLink = token.inLink; inRawBlock = token.inRawBlock; tokens.push(token); continue; } // link if (token = this.tokenizer.link(src)) { src = src.substring(token.raw.length); if (token.type === 'link') { token.tokens = this.inlineTokens(token.text, [], true, inRawBlock); } tokens.push(token); continue; } // reflink, nolink if (token = this.tokenizer.reflink(src, this.tokens.links)) { src = src.substring(token.raw.length); if (token.type === 'link') { token.tokens = this.inlineTokens(token.text, [], true, inRawBlock); } tokens.push(token); continue; } // strong if (token = this.tokenizer.strong(src, maskedSrc, prevChar)) { src = src.substring(token.raw.length); token.tokens = this.inlineTokens(token.text, [], inLink, inRawBlock); tokens.push(token); continue; } // em if (token = this.tokenizer.em(src, maskedSrc, prevChar)) { src = src.substring(token.raw.length); token.tokens = this.inlineTokens(token.text, [], inLink, inRawBlock); tokens.push(token); continue; } // code if (token = this.tokenizer.codespan(src)) { src = src.substring(token.raw.length); tokens.push(token); continue; } // br if (token = this.tokenizer.br(src)) { src = src.substring(token.raw.length); tokens.push(token); continue; } // del (gfm) if (token = this.tokenizer.del(src)) { src = src.substring(token.raw.length); token.tokens = this.inlineTokens(token.text, [], inLink, inRawBlock); tokens.push(token); continue; } // autolink if (token = this.tokenizer.autolink(src, mangle)) { src = src.substring(token.raw.length); tokens.push(token); continue; } // url (gfm) if (!inLink && (token = this.tokenizer.url(src, mangle))) { src = src.substring(token.raw.length); tokens.push(token); continue; } // text if (token = this.tokenizer.inlineText(src, inRawBlock, smartypants)) { src = src.substring(token.raw.length); prevChar = token.raw.slice(-1); tokens.push(token); continue; } if (src) { var errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0); if (this.options.silent) { console.error(errMsg); break; } else { throw new Error(errMsg); } } } return tokens; }; _createClass(Lexer, null, [{ key: "rules", get: function get() { return { block: block$1, inline: inline$1 }; } }]); return Lexer; }(); var defaults$3 = defaults.defaults; var cleanUrl$1 = helpers.cleanUrl, escape$1 = helpers.escape; /** * Renderer */ var Renderer_1 = /*#__PURE__*/function () { function Renderer(options) { this.options = options || defaults$3; } var _proto = Renderer.prototype; _proto.code = function code(_code, infostring, escaped) { var lang = (infostring || '').match(/\S*/)[0]; if (this.options.highlight) { var out = this.options.highlight(_code, lang); if (out != null && out !== _code) { escaped = true; _code = out; } } if (!lang) { return '
    ' + (escaped ? _code : escape$1(_code, true)) + '
    \n'; } return '
    ' + (escaped ? _code : escape$1(_code, true)) + '
    \n'; }; _proto.blockquote = function blockquote(quote) { return '
    \n' + quote + '
    \n'; }; _proto.html = function html(_html) { return _html; }; _proto.heading = function heading(text, level, raw, slugger) { if (this.options.headerIds) { return '' + text + '\n'; } // ignore IDs return '' + text + '\n'; }; _proto.hr = function hr() { return this.options.xhtml ? '
    \n' : '
    \n'; }; _proto.list = function list(body, ordered, start) { var type = ordered ? 'ol' : 'ul', startatt = ordered && start !== 1 ? ' start="' + start + '"' : ''; return '<' + type + startatt + '>\n' + body + '\n'; }; _proto.listitem = function listitem(text) { return '
  • ' + text + '
  • \n'; }; _proto.checkbox = function checkbox(checked) { return ' '; }; _proto.paragraph = function paragraph(text) { return '

    ' + text + '

    \n'; }; _proto.table = function table(header, body) { if (body) body = '' + body + ''; return '\n' + '\n' + header + '\n' + body + '
    \n'; }; _proto.tablerow = function tablerow(content) { return '\n' + content + '\n'; }; _proto.tablecell = function tablecell(content, flags) { var type = flags.header ? 'th' : 'td'; var tag = flags.align ? '<' + type + ' align="' + flags.align + '">' : '<' + type + '>'; return tag + content + '\n'; } // span level renderer ; _proto.strong = function strong(text) { return '' + text + ''; }; _proto.em = function em(text) { return '' + text + ''; }; _proto.codespan = function codespan(text) { return '' + text + ''; }; _proto.br = function br() { return this.options.xhtml ? '
    ' : '
    '; }; _proto.del = function del(text) { return '' + text + ''; }; _proto.link = function link(href, title, text) { href = cleanUrl$1(this.options.sanitize, this.options.baseUrl, href); if (href === null) { return text; } var out = '
    '; return out; }; _proto.image = function image(href, title, text) { href = cleanUrl$1(this.options.sanitize, this.options.baseUrl, href); if (href === null) { return text; } var out = '' + text + '' : '>'; return out; }; _proto.text = function text(_text) { return _text; }; return Renderer; }(); /** * TextRenderer * returns only the textual part of the token */ var TextRenderer_1 = /*#__PURE__*/function () { function TextRenderer() {} var _proto = TextRenderer.prototype; // no need for block level renderers _proto.strong = function strong(text) { return text; }; _proto.em = function em(text) { return text; }; _proto.codespan = function codespan(text) { return text; }; _proto.del = function del(text) { return text; }; _proto.html = function html(text) { return text; }; _proto.text = function text(_text) { return _text; }; _proto.link = function link(href, title, text) { return '' + text; }; _proto.image = function image(href, title, text) { return '' + text; }; _proto.br = function br() { return ''; }; return TextRenderer; }(); /** * Slugger generates header id */ var Slugger_1 = /*#__PURE__*/function () { function Slugger() { this.seen = {}; } /** * Convert string to unique id */ var _proto = Slugger.prototype; _proto.slug = function slug(value) { var slug = value.toLowerCase().trim() // remove html tags .replace(/<[!\/a-z].*?>/ig, '') // remove unwanted chars .replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g, '').replace(/\s/g, '-'); if (this.seen.hasOwnProperty(slug)) { var originalSlug = slug; do { this.seen[originalSlug]++; slug = originalSlug + '-' + this.seen[originalSlug]; } while (this.seen.hasOwnProperty(slug)); } this.seen[slug] = 0; return slug; }; return Slugger; }(); var defaults$4 = defaults.defaults; var unescape$1 = helpers.unescape; /** * Parsing & Compiling */ var Parser_1 = /*#__PURE__*/function () { function Parser(options) { this.options = options || defaults$4; this.options.renderer = this.options.renderer || new Renderer_1(); this.renderer = this.options.renderer; this.renderer.options = this.options; this.textRenderer = new TextRenderer_1(); this.slugger = new Slugger_1(); } /** * Static Parse Method */ Parser.parse = function parse(tokens, options) { var parser = new Parser(options); return parser.parse(tokens); } /** * Parse Loop */ ; var _proto = Parser.prototype; _proto.parse = function parse(tokens, top) { if (top === void 0) { top = true; } var out = '', i, j, k, l2, l3, row, cell, header, body, token, ordered, start, loose, itemBody, item, checked, task, checkbox; var l = tokens.length; for (i = 0; i < l; i++) { token = tokens[i]; switch (token.type) { case 'space': { continue; } case 'hr': { out += this.renderer.hr(); continue; } case 'heading': { out += this.renderer.heading(this.parseInline(token.tokens), token.depth, unescape$1(this.parseInline(token.tokens, this.textRenderer)), this.slugger); continue; } case 'code': { out += this.renderer.code(token.text, token.lang, token.escaped); continue; } case 'table': { header = ''; // header cell = ''; l2 = token.header.length; for (j = 0; j < l2; j++) { cell += this.renderer.tablecell(this.parseInline(token.tokens.header[j]), { header: true, align: token.align[j] }); } header += this.renderer.tablerow(cell); body = ''; l2 = token.cells.length; for (j = 0; j < l2; j++) { row = token.tokens.cells[j]; cell = ''; l3 = row.length; for (k = 0; k < l3; k++) { cell += this.renderer.tablecell(this.parseInline(row[k]), { header: false, align: token.align[k] }); } body += this.renderer.tablerow(cell); } out += this.renderer.table(header, body); continue; } case 'blockquote': { body = this.parse(token.tokens); out += this.renderer.blockquote(body); continue; } case 'list': { ordered = token.ordered; start = token.start; loose = token.loose; l2 = token.items.length; body = ''; for (j = 0; j < l2; j++) { item = token.items[j]; checked = item.checked; task = item.task; itemBody = ''; if (item.task) { checkbox = this.renderer.checkbox(checked); if (loose) { if (item.tokens.length > 0 && item.tokens[0].type === 'text') { item.tokens[0].text = checkbox + ' ' + item.tokens[0].text; if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') { item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text; } } else { item.tokens.unshift({ type: 'text', text: checkbox }); } } else { itemBody += checkbox; } } itemBody += this.parse(item.tokens, loose); body += this.renderer.listitem(itemBody, task, checked); } out += this.renderer.list(body, ordered, start); continue; } case 'html': { // TODO parse inline content if parameter markdown=1 out += this.renderer.html(token.text); continue; } case 'paragraph': { out += this.renderer.paragraph(this.parseInline(token.tokens)); continue; } case 'text': { body = token.tokens ? this.parseInline(token.tokens) : token.text; while (i + 1 < l && tokens[i + 1].type === 'text') { token = tokens[++i]; body += '\n' + (token.tokens ? this.parseInline(token.tokens) : token.text); } out += top ? this.renderer.paragraph(body) : body; continue; } default: { var errMsg = 'Token with "' + token.type + '" type was not found.'; if (this.options.silent) { console.error(errMsg); return; } else { throw new Error(errMsg); } } } } return out; } /** * Parse Inline Tokens */ ; _proto.parseInline = function parseInline(tokens, renderer) { renderer = renderer || this.renderer; var out = '', i, token; var l = tokens.length; for (i = 0; i < l; i++) { token = tokens[i]; switch (token.type) { case 'escape': { out += renderer.text(token.text); break; } case 'html': { out += renderer.html(token.text); break; } case 'link': { out += renderer.link(token.href, token.title, this.parseInline(token.tokens, renderer)); break; } case 'image': { out += renderer.image(token.href, token.title, token.text); break; } case 'strong': { out += renderer.strong(this.parseInline(token.tokens, renderer)); break; } case 'em': { out += renderer.em(this.parseInline(token.tokens, renderer)); break; } case 'codespan': { out += renderer.codespan(token.text); break; } case 'br': { out += renderer.br(); break; } case 'del': { out += renderer.del(this.parseInline(token.tokens, renderer)); break; } case 'text': { out += renderer.text(token.text); break; } default: { var errMsg = 'Token with "' + token.type + '" type was not found.'; if (this.options.silent) { console.error(errMsg); return; } else { throw new Error(errMsg); } } } } return out; }; return Parser; }(); var merge$2 = helpers.merge, checkSanitizeDeprecation$1 = helpers.checkSanitizeDeprecation, escape$2 = helpers.escape; var getDefaults = defaults.getDefaults, changeDefaults = defaults.changeDefaults, defaults$5 = defaults.defaults; /** * Marked */ function marked(src, opt, callback) { // throw error in case of non string input if (typeof src === 'undefined' || src === null) { throw new Error('marked(): input parameter is undefined or null'); } if (typeof src !== 'string') { throw new Error('marked(): input parameter is of type ' + Object.prototype.toString.call(src) + ', string expected'); } if (typeof opt === 'function') { callback = opt; opt = null; } opt = merge$2({}, marked.defaults, opt || {}); checkSanitizeDeprecation$1(opt); if (callback) { var highlight = opt.highlight; var tokens; try { tokens = Lexer_1.lex(src, opt); } catch (e) { return callback(e); } var done = function done(err) { var out; if (!err) { try { out = Parser_1.parse(tokens, opt); } catch (e) { err = e; } } opt.highlight = highlight; return err ? callback(err) : callback(null, out); }; if (!highlight || highlight.length < 3) { return done(); } delete opt.highlight; if (!tokens.length) return done(); var pending = 0; marked.walkTokens(tokens, function (token) { if (token.type === 'code') { pending++; setTimeout(function () { highlight(token.text, token.lang, function (err, code) { if (err) { return done(err); } if (code != null && code !== token.text) { token.text = code; token.escaped = true; } pending--; if (pending === 0) { done(); } }); }, 0); } }); if (pending === 0) { done(); } return; } try { var _tokens = Lexer_1.lex(src, opt); if (opt.walkTokens) { marked.walkTokens(_tokens, opt.walkTokens); } return Parser_1.parse(_tokens, opt); } catch (e) { e.message += '\nPlease report this to https://github.com/markedjs/marked.'; if (opt.silent) { return '

    An error occurred:

    ' + escape$2(e.message + '', true) + '
    '; } throw e; } } /** * Options */ marked.options = marked.setOptions = function (opt) { merge$2(marked.defaults, opt); changeDefaults(marked.defaults); return marked; }; marked.getDefaults = getDefaults; marked.defaults = defaults$5; /** * Use Extension */ marked.use = function (extension) { var opts = merge$2({}, extension); if (extension.renderer) { (function () { var renderer = marked.defaults.renderer || new Renderer_1(); var _loop = function _loop(prop) { var prevRenderer = renderer[prop]; renderer[prop] = function () { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var ret = extension.renderer[prop].apply(renderer, args); if (ret === false) { ret = prevRenderer.apply(renderer, args); } return ret; }; }; for (var prop in extension.renderer) { _loop(prop); } opts.renderer = renderer; })(); } if (extension.tokenizer) { (function () { var tokenizer = marked.defaults.tokenizer || new Tokenizer_1(); var _loop2 = function _loop2(prop) { var prevTokenizer = tokenizer[prop]; tokenizer[prop] = function () { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } var ret = extension.tokenizer[prop].apply(tokenizer, args); if (ret === false) { ret = prevTokenizer.apply(tokenizer, args); } return ret; }; }; for (var prop in extension.tokenizer) { _loop2(prop); } opts.tokenizer = tokenizer; })(); } if (extension.walkTokens) { var walkTokens = marked.defaults.walkTokens; opts.walkTokens = function (token) { extension.walkTokens(token); if (walkTokens) { walkTokens(token); } }; } marked.setOptions(opts); }; /** * Run callback for every token */ marked.walkTokens = function (tokens, callback) { for (var _iterator = _createForOfIteratorHelperLoose(tokens), _step; !(_step = _iterator()).done;) { var token = _step.value; callback(token); switch (token.type) { case 'table': { for (var _iterator2 = _createForOfIteratorHelperLoose(token.tokens.header), _step2; !(_step2 = _iterator2()).done;) { var cell = _step2.value; marked.walkTokens(cell, callback); } for (var _iterator3 = _createForOfIteratorHelperLoose(token.tokens.cells), _step3; !(_step3 = _iterator3()).done;) { var row = _step3.value; for (var _iterator4 = _createForOfIteratorHelperLoose(row), _step4; !(_step4 = _iterator4()).done;) { var _cell = _step4.value; marked.walkTokens(_cell, callback); } } break; } case 'list': { marked.walkTokens(token.items, callback); break; } default: { if (token.tokens) { marked.walkTokens(token.tokens, callback); } } } } }; /** * Expose */ marked.Parser = Parser_1; marked.parser = Parser_1.parse; marked.Renderer = Renderer_1; marked.TextRenderer = TextRenderer_1; marked.Lexer = Lexer_1; marked.lexer = Lexer_1.lex; marked.Tokenizer = Tokenizer_1; marked.Slugger = Slugger_1; marked.parse = marked; var marked_1 = marked; return marked_1; }))); /***/ }), /***/ "EJTS": /*!*********************************************************!*\ !*** ./src/pages/Problemset/components/Topic/index.tsx ***! \*********************************************************/ /*! exports provided: MenuMore, default */ /*! exports used: MenuMore, default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return MenuMore; }); /* harmony import */ var antd_es_dropdown_style__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! antd/es/dropdown/style */ "qVdP"); /* harmony import */ var antd_es_dropdown__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! antd/es/dropdown */ "jsC+"); /* harmony import */ var antd_es_menu_style__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! antd/es/menu/style */ "lUTK"); /* harmony import */ var antd_es_menu__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! antd/es/menu */ "BvKs"); /* harmony import */ var antd_es_checkbox_style__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! antd/es/checkbox/style */ "sRBo"); /* harmony import */ var antd_es_checkbox__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! antd/es/checkbox */ "kaz8"); /* harmony import */ var _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_toConsumableArray__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/toConsumableArray */ "oBTY"); /* harmony import */ var antd_es_radio_style__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! antd/es/radio/style */ "7Kak"); /* harmony import */ var antd_es_radio__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! antd/es/radio */ "9yH6"); /* harmony import */ var _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/slicedToArray */ "tJVT"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! react */ "cDcd"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_10__); /* harmony import */ var _components_RenderHtml__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @/components/RenderHtml */ "9Bee"); /* harmony import */ var _index_less_modules__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./index.less?modules */ "+vTd"); /* harmony import */ var _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_index_less_modules__WEBPACK_IMPORTED_MODULE_12__); /* harmony import */ var _utils_authority__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! @/utils/authority */ "xKgJ"); /* harmony import */ var _assets_images_problemset_answer_decoration_png__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! @/assets/images/problemset/answer-decoration.png */ "Is5a"); /* harmony import */ var _assets_images_problemset_answer_decoration_png__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_assets_images_problemset_answer_decoration_png__WEBPACK_IMPORTED_MODULE_14__); var tagDotData = ['A.', 'B.', 'C.', 'D.', 'E.', 'F.', 'G.', 'H.', 'I.', 'J.', 'K.', 'L.', 'M.', 'N.', 'O.', 'P.', 'Q.', 'R.', 'S.', 'T.', 'U.', 'V.', 'W.', 'X.', 'Y.', 'Z.']; var tagData = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']; var List = function List(_ref) { var _data$program_attr2; var data = _ref.data, selectIds = _ref.selectIds, _ref$onSelectCheckBox = _ref.onSelectCheckBox, onSelectCheckBox = _ref$onSelectCheckBox === void 0 ? function () {} : _ref$onSelectCheckBox, _ref$showCheckbox = _ref.showCheckbox, showCheckbox = _ref$showCheckbox === void 0 ? true : _ref$showCheckbox; var _useState = Object(react__WEBPACK_IMPORTED_MODULE_10__["useState"])(false), _useState2 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_9__[/* default */ "a"])(_useState, 2), visible = _useState2[0], setVisible = _useState2[1]; var renderContent = function renderContent() { if (data.item_type === "JUDGMENT") { return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.judgmentContent }, data.choices.map(function (item, key) { return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(antd_es_radio__WEBPACK_IMPORTED_MODULE_8__[/* default */ "a"], { key: key, disabled: true }, item.choice_text); })); } if (data.item_type === "PROGRAM") { var _data$program_attr; return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.programContent }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(_components_RenderHtml__WEBPACK_IMPORTED_MODULE_11__[/* default */ "a"], { value: (_data$program_attr = data.program_attr) === null || _data$program_attr === void 0 ? void 0 : _data$program_attr.description })); } if (data.item_type === "COMBINATION") { var _data$sub_item_banks; return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.combinationContent }, data === null || data === void 0 ? void 0 : (_data$sub_item_banks = data.sub_item_banks) === null || _data$sub_item_banks === void 0 ? void 0 : _data$sub_item_banks.map(function (e, i) { var _e$choices; var str = "(\u9898\u76EE".concat(i + 1, "-\u5355\u9009\u9898) "); return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_10__["Fragment"], null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("div", { style: { marginTop: 10, marginBottom: 10 } }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(_components_RenderHtml__WEBPACK_IMPORTED_MODULE_11__[/* default */ "a"], { value: str + e.name })), e.choices.map(function (item, key) { return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("div", { key: key, className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.otherContentItem }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("p", null, tagDotData[key]), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(_components_RenderHtml__WEBPACK_IMPORTED_MODULE_11__[/* default */ "a"], { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.otehrContentHtml, value: item.choice_text })); }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.con }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("b", { className: "c-grey-333 font14" }, " \u7B54\u6848\uFF1A", tagData === null || tagData === void 0 ? void 0 : tagData[e === null || e === void 0 ? void 0 : (_e$choices = e.choices) === null || _e$choices === void 0 ? void 0 : _e$choices.findIndex(function (k) { return k === null || k === void 0 ? void 0 : k.is_answer; })], " "), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("div", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("span", null, "\u89E3\u6790\uFF1A"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(_components_RenderHtml__WEBPACK_IMPORTED_MODULE_11__[/* default */ "a"], { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.parseAnswerHtml, value: e.analysis || '暂无解析' })))); })); } return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.otherContent }, data.choices.map(function (item, key) { return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("div", { key: key, className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.otherContentItem }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("p", null, tagDotData[key]), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(_components_RenderHtml__WEBPACK_IMPORTED_MODULE_11__[/* default */ "a"], { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.otehrContentHtml, value: item.choice_text })); })); }; var renderCompletionAnswer = function renderCompletionAnswer() { var _data$standard_answer; return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("div", null, (_data$standard_answer = data.standard_answer) === null || _data$standard_answer === void 0 ? void 0 : _data$standard_answer.map(function (item, key) { return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(_components_RenderHtml__WEBPACK_IMPORTED_MODULE_11__[/* default */ "a"], { key: key, className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.answerHtml, value: "\u7B54\u6848\uFF08\u586B\u7A7A".concat(item.position, "\uFF09\uFF1A").concat(item.answer_text.join('、')) }); })); }; var renderAnswer = function renderAnswer() { var _data$answer_texts, _data$choices, _data$choices$find; var rightKeyMapping = { "SUBJECTIVE": (_data$answer_texts = data.answer_texts) === null || _data$answer_texts === void 0 ? void 0 : _data$answer_texts[0], "JUDGMENT": (_data$choices = data.choices) === null || _data$choices === void 0 ? void 0 : (_data$choices$find = _data$choices.find(function (item) { return item.is_answer; })) === null || _data$choices$find === void 0 ? void 0 : _data$choices$find.choice_text }; var singleIndex = data.choices.map(function (item) { return item.is_answer; }).findIndex(function (item) { return item; }); var singleAnswer = singleIndex > -1 ? tagData[singleIndex] : ''; var multipleAnswer = ''; data.choices.map(function (item, index) { if (item.is_answer) { multipleAnswer += tagData[index]; } }); var otherAnswer = rightKeyMapping[data.item_type]; var answerMapping = { "SINGLE": /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(_components_RenderHtml__WEBPACK_IMPORTED_MODULE_11__[/* default */ "a"], { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.answerHtml, value: "\u7B54\u6848\uFF1A".concat(singleAnswer || '无') }), "MULTIPLE": /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(_components_RenderHtml__WEBPACK_IMPORTED_MODULE_11__[/* default */ "a"], { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.answerHtml, value: "\u7B54\u6848\uFF1A".concat(multipleAnswer || '无') }), "COMPLETION": renderCompletionAnswer() }; var otherAnswerElement = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(_components_RenderHtml__WEBPACK_IMPORTED_MODULE_11__[/* default */ "a"], { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.answerHtml, value: "\u7B54\u6848\uFF1A".concat(otherAnswer || '无') }); return answerMapping[data.item_type] || otherAnswerElement; }; var handleSelectCheck = function handleSelectCheck(e) { var ids = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_toConsumableArray__WEBPACK_IMPORTED_MODULE_6__[/* default */ "a"])(selectIds); if (e.target.checked) { ids.push(data.id); } else { ids = ids.filter(function (k) { return k !== data.id; }); } onSelectCheckBox(ids); }; return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.itemWrap }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.list }, showCheckbox && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(antd_es_checkbox__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"], { className: "mr10", onChange: handleSelectCheck, checked: selectIds.includes(data.id) }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.title }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(_components_RenderHtml__WEBPACK_IMPORTED_MODULE_11__[/* default */ "a"], { key: 1, showLines: 1, showTextOnly: true, className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.topicTitleContent, value: data.name })), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.line }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("b", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.b1 }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("b", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.b2 })), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("div", { onClick: function onClick() { return setVisible(!visible); }, className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.tr }, visible ? '收起' : '展开', /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("i", { style: { transform: visible ? 'scale(0.5) rotate(-180deg)' : 'scale(0.5) rotate(0deg)' }, className: "iconfont icon-zhankai4" }))), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("aside", { style: visible ? { display: 'block' } : { display: 'none' }, className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.itemDetail }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("div", { style: { marginBottom: 44 } }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(_components_RenderHtml__WEBPACK_IMPORTED_MODULE_11__[/* default */ "a"], { key: 2, className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.topicTitleContent, value: data.name }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("div", { className: "".concat(_index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.row, " mt15") }, renderContent()), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.row }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.updateTimeRow }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.updateTimeWrap }, data.item_type === "PROGRAM" && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("p", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.programLanguage }, "\u7F16\u7A0B\u8BED\u8A00\uFF1A", (_data$program_attr2 = data.program_attr) === null || _data$program_attr2 === void 0 ? void 0 : _data$program_attr2.language))))), data.item_type !== "PROGRAM" && data.item_type !== "COMBINATION" && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.answerWrapper }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("img", { src: _assets_images_problemset_answer_decoration_png__WEBPACK_IMPORTED_MODULE_14___default.a, alt: "", className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.decoration }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.answer }, renderAnswer()), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.parse }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.parseText }, "\u89E3\u6790\uFF1A"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.parseAnswer }, data.analysis ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(_components_RenderHtml__WEBPACK_IMPORTED_MODULE_11__[/* default */ "a"], { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.parseAnswerHtml, value: data.analysis }) : "暂无解析"))))); }; var MenuMore = function MenuMore(_ref2) { var _data$program_attr3, _data$program_attr4, _data$program_attr5, _data$author, _user$userInfo, _data$author2, _user$userInfo2, _data$author3, _user$userInfo3, _data$program_attr7, _data$author4, _user$userInfo4, _data$author5, _user$userInfo5, _data$author6, _user$userInfo6; var isProblemset = _ref2.isProblemset, data = _ref2.data, user = _ref2.user, activeTabsKey = _ref2.activeTabsKey, _ref2$onPublicReview = _ref2.onPublicReview, onPublicReview = _ref2$onPublicReview === void 0 ? function () {} : _ref2$onPublicReview, _ref2$onStartExperien = _ref2.onStartExperience, onStartExperience = _ref2$onStartExperien === void 0 ? function () {} : _ref2$onStartExperien, _ref2$onSetPrivate = _ref2.onSetPrivate, onSetPrivate = _ref2$onSetPrivate === void 0 ? function () {} : _ref2$onSetPrivate, _ref2$onCorrection = _ref2.onCorrection, onCorrection = _ref2$onCorrection === void 0 ? function () {} : _ref2$onCorrection, _ref2$onCollect = _ref2.onCollect, onCollect = _ref2$onCollect === void 0 ? function () {} : _ref2$onCollect, _ref2$onSetPublic = _ref2.onSetPublic, onSetPublic = _ref2$onSetPublic === void 0 ? function () {} : _ref2$onSetPublic, _ref2$onDelete = _ref2.onDelete, onDelete = _ref2$onDelete === void 0 ? function () {} : _ref2$onDelete, _ref2$onCancel = _ref2.onCancel, onCancel = _ref2$onCancel === void 0 ? function () {} : _ref2$onCancel, _ref2$onSelect = _ref2.onSelect, onSelect = _ref2$onSelect === void 0 ? function () {} : _ref2$onSelect, _ref2$onMoveTo = _ref2.onMoveTo, onMoveTo = _ref2$onMoveTo === void 0 ? function () {} : _ref2$onMoveTo, _ref2$onSetShare = _ref2.onSetShare, onSetShare = _ref2$onSetShare === void 0 ? function () {} : _ref2$onSetShare, _ref2$onCancelShare = _ref2.onCancelShare, onCancelShare = _ref2$onCancelShare === void 0 ? function () {} : _ref2$onCancelShare, _ref2$onPublish = _ref2.onPublish, onPublish = _ref2$onPublish === void 0 ? function () {} : _ref2$onPublish, _ref2$onCancelPublish = _ref2.onCancelPublish, onCancelPublish = _ref2$onCancelPublish === void 0 ? function () {} : _ref2$onCancelPublish; var editUrl = data.item_type === "PROGRAM" ? "/problems/".concat((_data$program_attr3 = data.program_attr) === null || _data$program_attr3 === void 0 ? void 0 : _data$program_attr3.identifier, "/edit") : "/problemset/edit/".concat(data.id); var showPrivateFlag = activeTabsKey === "0" && !data.public && !data.apply && (data.item_type === "PROGRAM" && ((_data$program_attr4 = data.program_attr) === null || _data$program_attr4 === void 0 ? void 0 : _data$program_attr4.status) !== 0 || data.item_type !== "PROGRAM"); var menu = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(antd_es_menu__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"], { forceSubMenuRender: true, className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.menu }, activeTabsKey === "0" && !data.public && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(antd_es_menu__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].Item, { key: "-1" }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("a", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.actionLink, target: "_blank", href: editUrl }, "\u7F16\u8F91")), (activeTabsKey === "0" || activeTabsKey === "3") && data.item_type === "PROGRAM" && ((_data$program_attr5 = data.program_attr) === null || _data$program_attr5 === void 0 ? void 0 : _data$program_attr5.status) !== 0 && !data.public && ((_data$author = data.author) === null || _data$author === void 0 ? void 0 : _data$author.login) === ((_user$userInfo = user.userInfo) === null || _user$userInfo === void 0 ? void 0 : _user$userInfo.login) && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(antd_es_menu__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].Item, { key: "0" }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("a", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.actionLink, onClick: function onClick() { var _data$program_attr6; return onCancelPublish(data === null || data === void 0 ? void 0 : (_data$program_attr6 = data.program_attr) === null || _data$program_attr6 === void 0 ? void 0 : _data$program_attr6.identifier); } }, "\u64A4\u9500\u53D1\u5E03")), activeTabsKey === "0" && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(antd_es_menu__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].Item, { key: "1" }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("a", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.actionLink, onClick: function onClick() { return onMoveTo(data.id); } }, "\u79FB\u52A8\u5230")), activeTabsKey === "0" && !(data !== null && data !== void 0 && data.is_share) && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(antd_es_menu__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].Item, { key: "3" }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("a", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.actionLink, onClick: function onClick() { return onSetShare(data.id); } }, "\u5171\u4EAB")), (activeTabsKey === "0" && (data === null || data === void 0 ? void 0 : data.is_share) || activeTabsKey === "3" && ((_data$author2 = data.author) === null || _data$author2 === void 0 ? void 0 : _data$author2.login) === ((_user$userInfo2 = user.userInfo) === null || _user$userInfo2 === void 0 ? void 0 : _user$userInfo2.login)) && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(antd_es_menu__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].Item, { key: "3" }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("a", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.actionLink, onClick: function onClick() { return onCancelShare(data.id); } }, "\u64A4\u9500\u5171\u4EAB")), showPrivateFlag && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(antd_es_menu__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].Item, { key: "4" }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("a", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.actionLink, onClick: function onClick() { return onSetPublic(data.id); } }, "\u516C\u5F00")), activeTabsKey === "0" && !data.public && data.apply && (data.item_type === "PROGRAM" && data.program_attr.status !== 0 || data.item_type !== "PROGRAM") && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(antd_es_menu__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].Item, { key: "5" }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("a", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.reviewFlag, onClick: onPublicReview }, "\u5BA1\u6838\u4E2D")), (activeTabsKey === "0" || activeTabsKey === "1") && data.public && ((_data$author3 = data.author) === null || _data$author3 === void 0 ? void 0 : _data$author3.login) === ((_user$userInfo3 = user.userInfo) === null || _user$userInfo3 === void 0 ? void 0 : _user$userInfo3.login) && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(antd_es_menu__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].Item, { key: "6" }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("a", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.actionLink, onClick: function onClick() { return onSetPrivate(data.id); } }, "\u64A4\u9500\u516C\u5F00")), activeTabsKey === "2" && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(antd_es_menu__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].Item, { key: "7" }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("a", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.actionLink, onClick: function onClick() { return onCollect(data.id, data.is_collected); } }, "\u53D6\u6D88\u6536\u85CF")), (activeTabsKey === "0" || activeTabsKey === "3") && data.item_type === "PROGRAM" && ((_data$program_attr7 = data.program_attr) === null || _data$program_attr7 === void 0 ? void 0 : _data$program_attr7.status) === 0 && !data.public && ((_data$author4 = data.author) === null || _data$author4 === void 0 ? void 0 : _data$author4.login) === ((_user$userInfo4 = user.userInfo) === null || _user$userInfo4 === void 0 ? void 0 : _user$userInfo4.login) && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(antd_es_menu__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].Item, { key: "8" }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("a", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.actionLink, onClick: function onClick() { var _data$program_attr8; return onPublish(data === null || data === void 0 ? void 0 : (_data$program_attr8 = data.program_attr) === null || _data$program_attr8 === void 0 ? void 0 : _data$program_attr8.identifier); } }, "\u53D1\u5E03")), (activeTabsKey === "1" || activeTabsKey === "3") && !Object(_utils_authority__WEBPACK_IMPORTED_MODULE_13__[/* isCommonSuperAdminOrOperation */ "o"])() && !Object(_utils_authority__WEBPACK_IMPORTED_MODULE_13__[/* isCommonStudent */ "m"])() && ((_data$author5 = data.author) === null || _data$author5 === void 0 ? void 0 : _data$author5.login) !== ((_user$userInfo5 = user.userInfo) === null || _user$userInfo5 === void 0 ? void 0 : _user$userInfo5.login) && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(antd_es_menu__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].Item, { key: "9" }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("a", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.actionLink, onClick: function onClick() { return onCollect(data.id, data.is_collected); } }, data.is_collected ? '取消收藏' : '收藏')), activeTabsKey !== "0" && !Object(_utils_authority__WEBPACK_IMPORTED_MODULE_13__[/* isCommonSuperAdminOrOperation */ "o"])() && !Object(_utils_authority__WEBPACK_IMPORTED_MODULE_13__[/* isCommonStudent */ "m"])() && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(antd_es_menu__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].Item, { key: "10" }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("a", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.actionLink, onClick: function onClick() { return onCorrection(data.id); } }, "\u7EA0\u9519")), (activeTabsKey === "0" && !data.public || activeTabsKey === "1" && Object(_utils_authority__WEBPACK_IMPORTED_MODULE_13__[/* isCommonSuperAdminOrOperation */ "o"])() && ((_data$author6 = data.author) === null || _data$author6 === void 0 ? void 0 : _data$author6.login) !== ((_user$userInfo6 = user.userInfo) === null || _user$userInfo6 === void 0 ? void 0 : _user$userInfo6.login)) && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(antd_es_menu__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].Item, { key: "11" }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("a", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.actionLink, onClick: function onClick() { return onDelete(data.id); } }, "\u5220\u9664"))); var smMenu = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(antd_es_menu__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"], { forceSubMenuRender: true, className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.menu }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(antd_es_menu__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].Item, { key: "10" }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("a", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.actionLink, onClick: function onClick() { return onCorrection(data.id); } }, "\u7EA0\u9519"))); var showMore = activeTabsKey !== "0" && !Object(_utils_authority__WEBPACK_IMPORTED_MODULE_13__[/* isCommonSuperAdminOrOperation */ "o"])() && !Object(_utils_authority__WEBPACK_IMPORTED_MODULE_13__[/* isCommonStudent */ "m"])(); return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_10___default.a.Fragment, null, isProblemset ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_10___default.a.Fragment, null, data.item_type !== "SUBJECTIVE" && data.item_type !== "COMBINATION" && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("span", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.textBtn, style: { cursor: 'pointer' }, onClick: function onClick() { return onStartExperience(data); } }, "\u4F53\u9A8C"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(antd_es_dropdown__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"], { overlay: menu }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("span", { style: { cursor: "default" }, onClick: function onClick(e) { return e.preventDefault(); } }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("span", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_12___default.a.textBtn }, "\u66F4\u591A")))) : showMore ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement(antd_es_dropdown__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"], { className: "ml40", overlay: smMenu }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("span", { style: { cursor: "default" }, onClick: function onClick(e) { return e.preventDefault(); } }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("span", null, "\u66F4\u591A"))) : /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_10___default.a.createElement("span", null)); }; /* harmony default export */ __webpack_exports__["b"] = (List); /***/ }), /***/ "FKdj": /*!*********************************************************************************!*\ !*** ./src/pages/Paperlibrary/Random/ExchangeFromProblemSet/index.less?modules ***! \*********************************************************************************/ /*! no static exports found */ /*! exports used: default */ /*! ModuleConcatenation bailout: Module is not an ECMAScript module */ /***/ (function(module, exports, __webpack_require__) { // extracted by mini-css-extract-plugin module.exports = {"flex_box_center":"flex_box_center___3uXpC","flex_space_between":"flex_space_between___1R5l3","flex_box_vertical_center":"flex_box_vertical_center___2whw-","flex_box_center_end":"flex_box_center_end___Jni7d","flex_box_column":"flex_box_column___bQWh0","page":"page___2wqIC","wrap":"wrap___3ThhU","title":"title___3BwkD","select":"select___2Ozsr","contentWrap":"contentWrap___3srp0","pngIcon":"pngIcon___2ckkq","tabsWrap":"tabsWrap___2Y959","searchWrap":"searchWrap___H9GsL","addQuestionBtn":"addQuestionBtn___1b8s_","search":"search___3d1EJ","searchIcon":"searchIcon___1mrzV","batchWrap":"batchWrap___j1Er3","contentListWrap":"contentListWrap___3pty2","li":"li___2UOPB","bottom":"bottom___I7MVG","actionLeftItem":"actionLeftItem___3bGeH","questionTypeName":"questionTypeName___Aiyux","more":"more___YExtS","btnAdd":"btnAdd___2RrWf","treeWrapper":"treeWrapper___U0OPC","treeHeader":"treeHeader___1LB2p","treeContent":"treeContent___Ckfqx","action":"action___Xn5RP","headerWrapper":"headerWrapper___3ECJD","exportBtn":"exportBtn___35cZE"}; /***/ }), /***/ "FOrL": /*!********************************************!*\ !*** ./src/assets/images/icons/nodata.png ***! \********************************************/ /*! no static exports found */ /*! exports used: default */ /*! ModuleConcatenation bailout: Module is not an ECMAScript module */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__.p + "static/nodata.a6b3f948.png"; /***/ }), /***/ "Is5a": /*!************************************************************!*\ !*** ./src/assets/images/problemset/answer-decoration.png ***! \************************************************************/ /*! no static exports found */ /*! exports used: default */ /*! ModuleConcatenation bailout: Module is not an ECMAScript module */ /***/ (function(module, exports) { module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAACMgAAAA6CAYAAABPwffJAAAAAXNSR0IArs4c6QAAH35JREFUeF7t3Q2MZWV9x/H/c849d17uzL6y7K4M76xLNIAKoiBQak0oRgsiYKyxUEq0LwZLYmqa0hqtpi8xodam1daKRFtbRITYBmlspRBBAXmRaHddsCyO7Bsssztzd2buveec5jl37jC7bN155l7OL7P3ewmZfTnn+Z37+f9nsjn3n+c4W8JrfHx8bGam9ZfNZutif3q1Wrl3YKDyB2NjY+NLWC74FHV+8AVzQlcC6nqr87vC4+RgAXW91fnBYJyAAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACpr6/r86nBcoVUNdbnV+uNmnqevcy34WW84knto0513giz22NWef03P9qb27Vs846a9MrOiSjzg/14vjuBNT1Vud3p8fZoQLqeqvzQ704HgEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBMzU9/fV+fRAuQLqeqvzy9UmTV3vXucHD8g88shj/2zm3ttoNOa7wZmzJEnMnPvqOeec9euvZJuo81/J98baLxdQ11udT0+UK6Cutzq/XG3SEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBA4OgTU9/fV+UdHFZfPu1DXW52/fCp1dFyput69zg8ekLnvvu8+l+e28XDldM52XHTRW171SpZanf9KvjfWfrmAut7qfHqiXAF1vdX55WqThgACCCCAAAIIIIAAAggggAACCCCAAAIIIIDA0SGgvr+vzj86qrh83oW63ur85VOpo+NK1fXudX7wgMy3v31vnue5NZtNc84sz9sPWkqq1aLCb3vbxcFrhrSGOj/kWjm2ewF1vdX53QuyQoiAut7q/BArjkUAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAIG2gPr+vjqfPihXQF1vdX652qSp693r/OBhlrvu+ve8PRiTmx+N6QzJtFsjt8sue0fwmiFtpc4PuVaO7V5AXW91fveCrBAioK63Oj/EimMRQAABBBBAAAEEEEAAAQQQQAABBBBAAAEEEECgLaC+v6/Opw/KFVDXW51frjZp6nr3Oj94mOX22+/0kzHWbDaK3WP8yw/JJElSDMxceeXlwWuGtJU6P+RaObZ7AXW91fndC7JCiIC63ur8ECuORQABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAgbaA+v6+Op8+KFdAXW91frnapKnr3ev84GGWW2/9Smcsptgx5qVdZNq/vuaa9wWvGdJW6vyQa+XY7gXU9Vbndy/ICiEC6nqr80OsOBYBBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQTaAur7++p8+qBcAXW91fnlapOmrnev84OHWb7whVvyZrN5UCf4xy055yxJqnb99dcGrxnSVur8kGvl2O4F1PVW53cvyAohAup6q/NDrDgWAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEE2gLq+/vqfPqgXAF1vdX55WqTpq53r/ODh1k+85m/yZ05y4vdY/zjldpLFEMy5uyGD/9e8JohbaXOD7lWju1eQF1vdX73gqwQIqCutzo/xIpjEUAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAoC2gvr+vzqcPyhVQ11udX642aep69zo/eJjl05+++ZAdZNqPVvKvJEnsIx+5MXjNkLZS54dcK8d2L6Cutzq/e0FWCBFQ11udH2LFsQgggAACCCCAAAIIIIAAAggggAACCCCAAAIIINAWUN/fV+fTB+UKqOutzi9XmzR1vXudHzzM8olPfCrvPFKp/dXvHtNuDL/Yn3zspuA1Q9pKnR9yrRzbvYC63ur87gVZIURAXW91fogVxyKAAAIIIIAAAggggAACCCCAAAIIIIAAAggggEBbQH1/X51PH5QroK63Or9cbdLU9e51fvAwy003fSxvNhsLOuGlJfwOMp/85MeD1wxpK3V+yLVybPcC6nqr87sXZIUQAXW91fkhVhyLAAIIIIAAAggggAACCCCAAAIIIIAAAggggAACbQH1/X11Pn1QroC63ur8crVJU9e71/nBwyw33viR3O8a03nN7x4zt5PMzTd/OnjNkLZS54dcK8d2L6Cutzq/e0FWCBFQ11udH2LFsQgggAACCCCAAAIIIIAAAggggAACCCCAAAIIINAWUN/fV+fTB+UKqOutzi9XmzR1vXudHzzM8qEP3ZC3mi3Lbe65SvM94axaTeyzn/1M8JohbaXOD7lWju1eQF1vdX73gqwQIqCutzo/xIpjEUAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAoC2gvr+vzqcPyhVQ11udX642aep69zo/eJjluuuuf2kyxv/KrzD3Nc9zu+WWfwxeM6St1Pkh18qx3Quo663O716QFUIE1PVW54dYcSwCCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAgi0BdT399X59EG5Aup6q/PL1SZNXe9e5wcPs7z//dfkzUbjoP1j/COX/KOWqtWqffnLtwavGdJW6vyQa+XY7gXU9Vbndy/ICiEC6nqr80OsOBYBBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQTaAur7++p8+qBcAXW91fnlapOmrnev84OHWa644sp8fsuY+X7obCrj7I47bg9eM6St1Pkh18qx3Quo663O716QFUIE1PVW54dYcSwCCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAgi0BdT399X59EG5Aup6q/PL1SZNXe9e5wcPs7zjHb+Wt1rNYseY9is359z8DjLf/OZdwWuGtJU6P+RaObZ7AXW91fndC7JCiIC63ur8ECuORQABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAgbaA+v6+Op8+KFdAXW91frnapKnr3ev84GGWSy65NG82m0UnNJuN4muSJMVX/4ilb33r7uA1Q9pKnR9yrRzbvYC63ur87gVZIURAXW91fogVxyKAAAIIIIAAAggggAACCCCAAAIIIIAAAggggEBbQH1/X51PH5QroK63Or9cbdLU9e51fvAwy4UXXpT73WP8kIxzZv43fgeZJKkWu8ncf/99wWuGtJU6P+RaObZ7AXW91fndC7JCiIC63ur8ECuORQABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAgbaA+v6+Op8+KFdAXW91frnapKnr3ev84GGWN73pzXmr1SoGYzo7yfgdZPyQTKVSse9//3vBa4a0lTo/5Fo5tnsBdb3V+d0LskKIgLre6vwQK45FAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQACBtoD6/r46nz4oV0Bdb3V+udqkqevd6/zgYZazzz4nbzQaxXBMsXuM74liB5mk2EXm0UcfCV4zpK3U+SHXyrHdC6jrrc7vXpAVQgTU9Vbnh1hxLAIIIIAAAggggAACCCCAAAIIIIAAAggggAACCLQF1Pf31fn0QbkC6nqr88vVJk1d717nBw+zbN58et7ZOabZbPjpGKtWE/OPXapWq7Zly/8ErxnSVur8kGvl2O4F1PVW53cvyAohAup6q/NDrDgWAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEE2gLq+/vqfPqgXAF1vdX55WqTpq53r/ODh1lOOeXUYkCmMyRjls8Px/gBmaeffip4zZC2UueHXCvHdi+grrc6v3tBVggRUNdbnR9ixbEIIIAAAggggAACCCCAAAIIIIAAAggggAACCCDQFlDf31fn0wflCqjrrc4vV5s0db17nR88zOIv4MCBujUafkimYa7zeKVKYsO1mv30p08HrxnSVur8kGvl2O4F1PVW53cvyAohAup6q/NDrDgWAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEE2gLq+/vqfPqgXAF1vdX55WqTpq53r/MXNcyS57m75557Vq9atfbCq656951+95h6fWp+F5kkqVqtVrMkSexrX/v65RMTL9x/ySWXvOicy3vRMur8XrwH1li8gLre6vzFS3FkLwTU9Vbn98KQNRBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQ6DcB9f19dX6/1Vv9ftX1Vuer/fstX13vVzL//x2Q8aG+0HfffXd1zbp1v3rssSe8rzay4opzXrc5rtfr1mo1bWpqqthBZnh42DpDMo88vjWtT+2/Y/fuZ/9p754937r00ksbfp3QYRl1fr81ufr9quutzlf791u+ut7q/H6rN+8XAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAIFeCKjv76vze2HIGosXUNdbnb94KY7shYC63mXlH3ZAphN+7733Dqw5ZsONGzae9Ie55aMe9o2vP714tJIfkvE7yZi5YueYzg4yDz+2pfB35iZ37njmz/ZPPP+5Cy64YKL4s0XuKKPO70UDscbiBdT1VucvXoojeyGgrrc6vxeGrIEAAggggAACCCCAAAIIIIAAAggggAACCCCAQL8JqO/vq/P7rd7q96uutzpf7d9v+ep6l5n/sgGZuXD34IMPrhpZsfrP12886beyLI98Ezhndv65ZxSDMX5Ixn/NcysGZKrVavH1gYeeLP7Mv6LIZbuf2/7Fycm9N5x33nmzZpYfaUhGnd9vza5+v+p6q/PV/v2Wr663Or/f6s37RQABBBBAAAEEEEAAAQQQQAABBBBAAAEEEECgFwLq+/vq/F4YssbiBdT1VucvXoojeyGgrnfZ+QcNyCwIHxhdufbGdRtO+NPcD8f4o+amXi6+4Ozi8UqNRntAxr/845Wq1aT4+p37H2nXwU/T5GYuctmenc/+8eS+F24+0pCMOr8XDcQaixdQ11udv3gpjuyFgLre6vxeGLIGAggggAACCCCAAAIIIIAAAggggAACCCCAAAL9JqC+v6/O77d6q9+vut7qfLV/v+Wr663Inx+Q6YT70ZaHH330shNPfM2X8jwfzf2Ui5k1m6nd9i+32q23/MNBu8c45yzP8/kBmWuv+4Bd9Z7fsCSJi/Oc/8+5ye3bf3ztG9/whrv8qM3hdpJR5/dbs6vfr7re6ny1f7/lq+utzu+3evN+EUAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBDohYD6/r46vxeGrLF4AXW91fmLl+LIXgio663KP3RAJnrggQfWbjjutL+t1Ubf7Ydj/MYxrVbLPv93N9vT27batm3bit1j/JxLs9kqvvqdY/zLP2Zp06ZNduqmzfbB37nRKpVKsZGMH5Kp1ye/vvPnT/3u+eef/4KZZYc+amkOQJbfiyZijcULqOutzl+8FEf2QkBdb3V+LwxZAwEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQACBfhNQ399X5/dbvdXvV11vdb7av9/y1fVW5RcDMgumc6IfPP7ku44/YdNXsyyL/XCMP+CuO2+zhx96wOIoth/+8Ilixxj/eCW/e8zc+ZYkSfH7M888y9IstTeee75ddvnVxXYx/rAoitKfPbvtvWe/7oxv+AGZhbvIqPP7rdnV71ddb3W+2r/f8tX1Vuf3W715vwgggAACCCCAAAIIIIAAAggggAACCCCAAAII9EJAfX9fnd8LQ9ZYvIC63ur8xUtxZC8E1PVW5i8ckInMLN761M/+YuWqtb/fGY7ZvXunfeHzf21xHFujMWNbtmwthmOKV95+XtLcnIxVk6q9evMmGxgYsjRN7foP3mDHHrth/ph9Ey/81ebTjv+omaULd5HpTAep8nvRRKyxeAF1vdX5i5fiyF4IqOutzu+FIWsggAACCCCAAAIIIIAAAggggAACCCCAAAIIINBvAur7++r8fqu3+v2q663OV/v3W7663sp8t2A6J37ooR+OverEE2+pxMkv5Zkffsnt3v+6x3705GOWZZkdODBlW7duKwZiGg0/JFOMx8w/Zsn/+aZNp1mtNup3jLHXnvF6u/itlxSPWHKRWStt/vdz27f/5rnnnjk+NyTjF/Avv4gk/9BHPfVb85f9fuk31+n5sun7Mo9+o9/6svF50wgggAACCCCAAAIIIIAAAggggAACCCCAAAJdCfD5Ap8vdNVAgSfTb/RbYMt0dXjf99vC6Zz77ntw8+mvOesbae5OzX0fZpnd/q9ftqmpSZua2metZtOeeeZZm56ents1xhWPW2rvIONscHDQTjrpBKskiY2MrLSRkVG78j3v989XMpc7i13+9JYfP/Guiy46b2tnF5m56hW71yjyGZDp6vsn+GT6jR/wwU3TxQn0G/3WRftwKgIIIIAAAggggAACCCCAAAIIIIAAAggggECfCvD5Ap8vlNn69Bv9Rr+VN5/S2UEmesYs2fPw4284/uTN/2FZXsssszxzdvttXzLnnL3w/K5iGGbHjp02NVW3RmN2buMXX67cqtWqjYyM2MaNG4rdY9asPbb483dfda25KLfIIrPI1Z956keXbHjzOT84ycxvQZN1BmRU+QzIlPntZr6H/DgV/VYue9+m0W/8g6Jvm583jgACCCCAAAIIIIAAAggggAACCCCAAAIIILBkAT5f4POFJTfPEk6k3+i3JbTNkk/p+36bA4jHxy3Z/txD55x2ypl3Z3lWy/PMbyBjd//bbRZFse3e9VzxmKVWq1XsIpOmaTEw419+gMYPxZx88olWqVSK36/fcFxxzNvfebXfQMaciyxyUX3rTx59+yknnP/w2FgxIJPOVU6Wz4DMkr93lnQi/cYP+CU1zhJPot/otyW2DqchgAACCCCAAAIIIIAAAggggAACCCCAAAII9LEAny/w+UKZ7U+/0W/0W3nzKZ0dZCo7dlgyPv74a4874dW35VF+kmX+8Umpfe+737FGs1HsINOYnSlq44dkdu7cbfV6vRiGGR4etg0bjrU4jou/HxgcsrXHrLdqUrU3v+WXzbnYLMrNZe6Znz/7k6vHxl73o40biwGZ1lyxZfkMyJT57Ta/g4ys3vRbufVWp839g4J+UxeCfAQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEElpEAny8wsFBmu9Jv9Bv9Vt58ih+Qicws3rXLqnv2bD111THHfi6Kquf53WP8DjH/+/SWYjhmdna6+LqY19q16606MGjHrNtgJ596+twOM2ZZ1nhw4vndv71u3ean16+3xsIdZFT5zrnOY54W89Y4pksB+o1+67KFgk6n3+i3oIbhYAQQQAABBBBAAAEEEEAAAQQQQAABBBBAAAEErPiMlM9P6YTSBOg3Ps8qrdn4+ZYeNCATxwdW7Hlx7ydXrlx1XZ47y7LcpqcP2LatT1ilUrXndz9n09P1X1ifoaGarVt/nDWbs7Zp81k2NDRsUeTMudz27Zv44rrVa25K0+H9hxuQUeQzIFPmt9vB/6BQ1Hvu3RYDYYp8+o1+K/PnK/1Wbr+RhgACCCCAAAIIIIAAAggggAACCCCAAAIIIHB0CCwcWFB8nsTnWUdHHy32XdBvDMgstld6cVzf99uhAOPj41esHxv7TJbmsR+Q8bvI7Nr5M5ua3GfORfbC8zts+sDUYe2Hhkds7TEb/dyR1UZW2PoNx8/tHuMsil26a3z8w2NjY3f8ogGZsvP5ALkX30aLX4N+4wf84rul+yPpN/qt+y5iBQQQQAABBBBAAAEEEEAAAQQQQAABBBBAAIF+E+DzBT5fKLPn6Tf6jX4rbz7loB1koqg+umfixROHhoY+lVQGf8UPx3T+f37XuDVbTYvjxOr1/Ta5f681ZmeKWvnHKY2uWGO12grLspbFccXWrR8rhmM6/zdbM/85PT39R+tWrd6eZbXJw+0go8hnQKbMb7eDd5BR1Hvu3RY7yCjy6Tf6rcyfr/Rbuf1GGgIIIIAAAggggAACCCCAAAIIIIAAAggggMDRIbBwYEHxeRKfZx0dfbTYd0G/MSCz2F7pxXF932+5f5aSWWXHDkucm6q14mTV3r3PXX7MqvUfz/J0KM/NMj8ok5pNTu61VnPGXBSbs8hc5E8tNoyxLE8tz1JLqoM2MrLGXGwWFQMy/ms8/fzEro+tWfOqOytpcyLPR+obN1rTzFpzRZTlO//sJ16lCdBv9FtpzdZ+hh4/38oEJwsBBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAgaNAgM8X+DyrzDam3+g3+q28+RS/g4z/ADkeH7fErZwcbh1IVuStxvqZ6ckPrBhddU2aZ1GemWV+CiY1a6Uta7WmLW2llvupGTNzLra4ElulMmSVuGLmh2PMmYvMYhdl+ycnbh0cGv17V6nuqgw39+f7Rg+MjRUDMu0FhPkMyJT57TY/sEC/lcvet2n8fOMfFH3b/LxxBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAgSUL8PkCny8suXmWcCL9Rr8toW2WfErf99scQPSMWbJqwgbr2fRIVk9X5XG64cDU1EdXrFz11jTLoixr7xRTPHLJ/6LYnaHt7neJKb76//xv/K4xfjgmirJ9ExPfGRiMb06ike1RLZ6oRUNTE6ts5iQrBmT8qv4ly2dAZsnfO0s6kX7jB/ySGmeJJ9Fv9NsSW4fTEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBPpYgM8X+HyhzPan3+g3+q28+ZTODjKR38Vlzx6r5nm95lxtdDI9sDprzJyYNqavHhlZ/c4sSwczPyDj+7MzLDPXq85vQuOHZCIz/2v/5KUoimempl78Zjww8JUoGd4xGg+/mOf1Sedq9XXrrDG3e8z8gIwqnwGZMr/d5neQod/KZe/btM4/KFQ/X+bgZf3Oz7e+bX3eOAIIIIAAAggggAACCCCAAAIIIIAAAggggEAXAny+wMBCF+0TfCr9Rr8FN00XJ/R9v80BFI9Z2rHDkrRmg1FrutaaSkctydfMTmfr09bkxQNDtQuTJDkjy/Ko2EEmd/M7yfidY8zlxQ4yUeSyZrP55Ox0/f64MnrvwFC0y5pub2UknswqQ/W4bjMbN84/XmluD5pivEaSzwfIXXz3LOFU+o0f8EtomyWfQr/Rb0tuHk5EAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQ6FsBPl/g84Uym59+o9/ot/LmU4qHIx06JZSmU0OzrjJSaaUrGlm+Mk3z1ZY1jsvy1utdxZ1eTQbGnEUrnYtq7fOzem7ZvkZzdjxv5VsiV3nMourP49i9WI3cvlYl3j+Qt6bieGR64e4xneEUdX6ZDUcW/UYPlCug/vmizi9XmzQEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBI4OAfX9fXX+0VHF5fMu1PVW5y+fSh0dV6qutzJ/4YBM8ZCkcbOk9qJVm8364OxsZSSKWiNplI3mLh7Nm80VeWYjqbXWZ62sluX5kG+ByLnpqBLVY6vscpFNuSTZ7/J0Ms6iySyrTA0MtKaSpDZTX22NMSt2jyke0nTIgIws/+ho4+XzLhZMQdJvy6dsy/ZK6bdlWzouHAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABmQCfL8jo+zKYfuvLssvedD/3WzEg418LpnQi/6ilwUFL/JDMdB4Pu9nWUKsa1aJWo+Yq1SFrpYNZ5hLnsrh9bpRGUd60SjyTtxrTWaVarzSyej5QmR5y6QE/HDMzY825Ryv54Zjs0EcbqfNl3denwep6q/P7tOyyt62utzpfBk8wAggggAACCCCAAAIIIIAAAggggAACCCCAAALLWEB9f1+dv4xLtywvXV1vdf6yLNoyvmh1vVX5hw7I+N/7/+MdO6zih2RmZ6eqWTUeTNKhgZmZqcHKUDRQn02r1SiJs3SmGJCJ4sG0kTXT2kDcaE1ns4ODIzPNeHo2aqQzAwMjjbnhmJaZpX6eZuHuMZ2eWTClJMlfxr27LC9dXW91/rIs2jK+aHW91fnLuHRcOgIIIIAAAggggAACCCCAAAIIIIAAAggggAACMgH1/X11vgy+T4PV9Vbn92nZZW9bXW9V/vyAjJc/5CL8428qA3ssnh2wanWmnjQrUdJqumQ4GozrrcmKa7j2I5qqeV6rjLYOZDNpJcmbSStrNgZrzYFZa8yus3TMzA/HFI9VOtxwTKfq6nxZ9/VpsLre6vw+Lbvsbavrrc6XwROMAAIIIIAAAggggAACCCCAAAIIIIAAAggggMAyFlDf31fnL+PSLctLV9dbnb8si7aML1pdb0X+QQMyvnaHXIT/e//IpUqlYlGSWKUeT8Zx3UVx7IrdYzqvNM3TtJZntXQ0bTat1WpZtnHjwYMxv2g4prOOOn8Z9++yvHR1vdX5y7Joy/ii1fVW5y/j0nHpCCCAAAIIIIAAAggggAACCCCAAAIIIIAAAgjIBNT399X5Mvg+DVbXW53fp2WXvW11vcvOf9mAjJefuwj/y84jl6LOr8fHLYpjc1FU/N38K8ssT1PLx8Ze2ilm4a4xxWLO+R1kjvhS5x/xAjmgpwLqeqvze4rJYkcUUNdbnX9EIA5AAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQACBlwmo7++r82mJcgXU9Vbnl6tNmrreZeYfdkDGt8CCi/C/7QzKHPrrQ7uleITS3B8u/PWih2M6C6rz+TYoV0Bdb3V+udqkqeutzqcDEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBBBAIFxAfX9fnR8uxhndCKjrrc7vxo5zwwXU9S4r//8dkFlIdsjFdP7q0HNftjvMYneMOVJ51PlHuj7+vrcC6nqr83uryWpHElDXW51/JB/+HgEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABBF4uoL6/r86nJ8oVUNdbnV+uNmnqer+S+f8HabRiLm3R4IUAAAAASUVORK5CYII=" /***/ }), /***/ "Ix/O": /*!********************************************************!*\ !*** ./src/assets/images/problemset/folder-closed.png ***! \********************************************************/ /*! no static exports found */ /*! exports used: default */ /*! ModuleConcatenation bailout: Module is not an ECMAScript module */ /***/ (function(module, exports) { module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACEAAAAgCAYAAACcuBHKAAAACXBIWXMAAAsSAAALEgHS3X78AAAAAXNSR0IArs4c6QAAAhNJREFUWEftlztLA0EQx/97Z2LAF1ooKhZaCClsVARFLAQbbQTBVFY2NjZiI4KFINjo51DBD2BhI4IQfKAIikJAg48oKD4Kk3usbDabXHSTu1yCucJp5pL5z+zvZm4XllBKVZTZSBriaLIV9HMdBIOoJE22XHEaA8U+zMc19B2HbfV5BByCAeAzDMPB4rJiCt0uBoZDHI5uIv4xUczbFJQbqOFdJNVz6Nm64xB7wVtQf0tBhUohJol7VHX1c4jddr0UNV3VIMoGh9hpKB+EakazIer7gc5FwN/o6qUcJyWegKsV4PUgmZINEVwGfHXyWoQAlALMy0zEmHdi2htwsWSBeFnNjIPVYOuIWuJZrG0XtwOQ5PNOPC+U75tIjyM27wGIu1kdFZXyRupxJGPMMxPPQp8vbo3l0fNxMAhmpgYovt8+15yF3u47EPEceg4RnfHAOG6mPQARmSoeQvUDRsLpYLJ0fBylgBAAAoZ5mTGdFVj1p07M65CzThhxQM2xi6QLOtPzTlyOO4Nw1Wz7pN8QugZU+ACZT54Tlhj7bdXJ4j81LN9qupYax/lY6pxIAIpklmaO/+1fUq4Q9VKed+JsxAPjOB32AMTJkAcgjgY8ABHu/YfI3DtU4+/vHWwDG+o9hwh39+HrYR8Uitut7yqPwESgeTBzIWYg75FNEK3NVcFCk6gvitqOELtMZyAKLVJC/TfVWC6c92hknAAAAABJRU5ErkJggg==" /***/ }), /***/ "KMxT": /*!************************************************************************!*\ !*** ./src/pages/Paperlibrary/Random/ExchangeFromProblemSet/index.tsx ***! \************************************************************************/ /*! exports provided: default */ /*! all exports used */ /*! ModuleConcatenation bailout: Module is referenced from these modules with unsupported syntax: ./src/.umi-production/core/routes.ts (referenced with import()) */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var antd_es_pagination_style__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! antd/es/pagination/style */ "DjyN"); /* harmony import */ var antd_es_pagination__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! antd/es/pagination */ "NUBc"); /* harmony import */ var antd_es_dropdown_style__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! antd/es/dropdown/style */ "qVdP"); /* harmony import */ var antd_es_dropdown__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! antd/es/dropdown */ "jsC+"); /* harmony import */ var antd_es_menu_style__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! antd/es/menu/style */ "lUTK"); /* harmony import */ var antd_es_menu__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! antd/es/menu */ "BvKs"); /* harmony import */ var antd_es_spin_style__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! antd/es/spin/style */ "T2oS"); /* harmony import */ var antd_es_spin__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! antd/es/spin */ "W9HT"); /* harmony import */ var antd_es_button_style__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! antd/es/button/style */ "+L6B"); /* harmony import */ var antd_es_button__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! antd/es/button */ "2/Rp"); /* harmony import */ var _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/objectSpread2 */ "k1fw"); /* harmony import */ var _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_asyncToGenerator__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/asyncToGenerator */ "9og8"); /* harmony import */ var _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/slicedToArray */ "tJVT"); /* harmony import */ var _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties */ "PpiC"); /* harmony import */ var antd_es_input_style__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! antd/es/input/style */ "5NDa"); /* harmony import */ var antd_es_input__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! antd/es/input */ "5rEg"); /* harmony import */ var antd_es_tabs_style__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! antd/es/tabs/style */ "Znn+"); /* harmony import */ var antd_es_tabs__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! antd/es/tabs */ "ZTPi"); /* harmony import */ var _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/regenerator */ "WmNS"); /* harmony import */ var _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_18__); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! react */ "cDcd"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_19__); /* harmony import */ var umi__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! umi */ "9kvl"); /* harmony import */ var _components_LanguageSelect__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! @/components/LanguageSelect */ "iris"); /* harmony import */ var _pages_Problemset_components_AddModal__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! @/pages/Problemset/components/AddModal */ "jcZT"); /* harmony import */ var _components_NoData__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! @/components/NoData */ "BdwD"); /* harmony import */ var _pages_Problemset_components_Crumbs__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! @/pages/Problemset/components/Crumbs */ "SAoR"); /* harmony import */ var _index_less_modules__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./index.less?modules */ "FKdj"); /* harmony import */ var _index_less_modules__WEBPACK_IMPORTED_MODULE_25___default = /*#__PURE__*/__webpack_require__.n(_index_less_modules__WEBPACK_IMPORTED_MODULE_25__); /* harmony import */ var _pages_Problemset_components_Topic__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! @/pages/Problemset/components/Topic */ "EJTS"); /* harmony import */ var _pages_Problemset_components_NewFolder__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! @/pages/Problemset/components/NewFolder */ "LE3n"); /* harmony import */ var _utils_authority__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! @/utils/authority */ "xKgJ"); /* harmony import */ var _service_global__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! @/service/global */ "SVaM"); /* harmony import */ var _assets_images_problemset_folder_opened_png__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! @/assets/images/problemset/folder-opened.png */ "xTzM"); /* harmony import */ var _assets_images_problemset_folder_opened_png__WEBPACK_IMPORTED_MODULE_30___default = /*#__PURE__*/__webpack_require__.n(_assets_images_problemset_folder_opened_png__WEBPACK_IMPORTED_MODULE_30__); /* harmony import */ var _utils_util__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! @/utils/util */ "1vsH"); /* harmony import */ var _utils_fetch__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! @/utils/fetch */ "ErOA"); var TabPane = antd_es_tabs__WEBPACK_IMPORTED_MODULE_17__[/* default */ "a"].TabPane; var Search = antd_es_input__WEBPACK_IMPORTED_MODULE_15__[/* default */ "a"].Search; var TabType; (function (TabType) { TabType["Mine"] = "0"; TabType["Public"] = "1"; TabType["Collection"] = "2"; TabType["TeachGroupShare"] = "3"; })(TabType || (TabType = {})); var ProblemsetPage = function ProblemsetPage(_ref) { var _props$location, _props$location$query, _match$params, _match$params2, _problemset$teachGrou, _problemset$teachGrou2, _problemset$disciplin, _problemset$teachGrou3; var classroomList = _ref.classroomList, problemset = _ref.problemset, user = _ref.user, globalSetting = _ref.globalSetting, loading = _ref.loading, dispatch = _ref.dispatch, match = _ref.match, shixunHomeworks = _ref.shixunHomeworks, props = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_13__[/* default */ "a"])(_ref, ["classroomList", "problemset", "user", "globalSetting", "loading", "dispatch", "match", "shixunHomeworks"]); var queryParams = Object(_utils_util__WEBPACK_IMPORTED_MODULE_31__[/* getJsonFromUrl */ "J"])(); var _useState = Object(react__WEBPACK_IMPORTED_MODULE_19__["useState"])({ discipline_id: null, sub_discipline_id: null, tag_discipline_id: null, group_id: null, type: '0', item_type: queryParams.qtype, difficulty: null, keyword: null, page: 1, per_page: 20, sort_by: 'updated_at', sort_direction: 'desc', id: ((_props$location = props.location) === null || _props$location === void 0 ? void 0 : (_props$location$query = _props$location.query) === null || _props$location$query === void 0 ? void 0 : _props$location$query.id) || null, exam_id: (match === null || match === void 0 ? void 0 : (_match$params = match.params) === null || _match$params === void 0 ? void 0 : _match$params.id) || null, exercise_id: (match === null || match === void 0 ? void 0 : (_match$params2 = match.params) === null || _match$params2 === void 0 ? void 0 : _match$params2.categoryId) || null }), _useState2 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_12__[/* default */ "a"])(_useState, 2), params = _useState2[0], setParams = _useState2[1]; var _useState3 = Object(react__WEBPACK_IMPORTED_MODULE_19__["useState"])(0), _useState4 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_12__[/* default */ "a"])(_useState3, 2), problemsetCount = _useState4[0], setProblemsetCount = _useState4[1]; var _useState5 = Object(react__WEBPACK_IMPORTED_MODULE_19__["useState"])([]), _useState6 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_12__[/* default */ "a"])(_useState5, 2), problemsetList = _useState6[0], setProblemsetList = _useState6[1]; var _useState7 = Object(react__WEBPACK_IMPORTED_MODULE_19__["useState"])(TabType.Mine), _useState8 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_12__[/* default */ "a"])(_useState7, 2), activeTabsKey = _useState8[0], setActiveTabsKey = _useState8[1]; var _useState9 = Object(react__WEBPACK_IMPORTED_MODULE_19__["useState"])(-1), _useState10 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_12__[/* default */ "a"])(_useState9, 2), knowledgeValue = _useState10[0], setKnowledgeValue = _useState10[1]; var _useState11 = Object(react__WEBPACK_IMPORTED_MODULE_19__["useState"])([]), _useState12 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_12__[/* default */ "a"])(_useState11, 2), knowledgeData = _useState12[0], setKnowledgeData = _useState12[1]; var _useState13 = Object(react__WEBPACK_IMPORTED_MODULE_19__["useState"])([]), _useState14 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_12__[/* default */ "a"])(_useState13, 2), navigation = _useState14[0], setNavigation = _useState14[1]; var _useState15 = Object(react__WEBPACK_IMPORTED_MODULE_19__["useState"])(false), _useState16 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_12__[/* default */ "a"])(_useState15, 2), backIcon = _useState16[0], setBackIcon = _useState16[1]; var unpublishedAll = Object(react__WEBPACK_IMPORTED_MODULE_19__["useRef"])(false); var _useState17 = Object(react__WEBPACK_IMPORTED_MODULE_19__["useState"])([]), _useState18 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_12__[/* default */ "a"])(_useState17, 2), selectIds = _useState18[0], setSelectIds = _useState18[1]; var _useState19 = Object(react__WEBPACK_IMPORTED_MODULE_19__["useState"])('按更新时间降序'), _useState20 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_12__[/* default */ "a"])(_useState19, 2), SortMenuName = _useState20[0], setSortMenuName = _useState20[1]; var _useState21 = Object(react__WEBPACK_IMPORTED_MODULE_19__["useState"])([]), _useState22 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_12__[/* default */ "a"])(_useState21, 2), treeData = _useState22[0], setTreeData = _useState22[1]; var treeDataWarp = Object(react__WEBPACK_IMPORTED_MODULE_19__["useRef"])(null); var _useState23 = Object(react__WEBPACK_IMPORTED_MODULE_19__["useState"])(false), _useState24 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_12__[/* default */ "a"])(_useState23, 2), folderLoading = _useState24[0], setFolderLoading = _useState24[1]; var _useState25 = Object(react__WEBPACK_IMPORTED_MODULE_19__["useState"])(''), _useState26 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_12__[/* default */ "a"])(_useState25, 2), name = _useState26[0], setname = _useState26[1]; var SortMenus = [{ name: '按更新时间升序', type: 'updated_at', direction: 'asc' }, { name: '按更新时间降序', type: 'updated_at', direction: 'desc' }, { name: '按使用次数升序', type: 'quotes', direction: 'asc' }, { name: '按使用次数降序', type: 'quotes', direction: 'desc' }]; Object(react__WEBPACK_IMPORTED_MODULE_19__["useEffect"])(function () { document.body.setAttribute('data-custom', 'initial'); return function () { document.body.removeAttribute('data-custom'); }; }, []); Object(react__WEBPACK_IMPORTED_MODULE_19__["useEffect"])(function () { var _query; dispatch({ type: 'problemset/getDisciplines', payload: { source: 'question' } }); var group_id = ((_query = props.location.query) === null || _query === void 0 ? void 0 : _query.group_id) || 0; params.group_id = Number(group_id); setParams(params); getItemBanks(params).then(function (res) { if (!(res !== null && res !== void 0 && res.status)) { setTreeData(res === null || res === void 0 ? void 0 : res.item_banks_group); } setFolderLoading(false); }); getBasketList(); handleGetTeachGroupData(); }, []); //出现页面右侧悬浮按钮 Object(react__WEBPACK_IMPORTED_MODULE_19__["useEffect"])(function () { dispatch({ type: 'globalSetting/onlyShowBackTopToggle', payload: false }); dispatch({ type: 'globalSetting/onlyShowBackTopIconToggle', payload: false }); return function () { dispatch({ type: 'globalSetting/onlyShowBackTopToggle', payload: true }); dispatch({ type: 'globalSetting/onlyShowBackTopIconToggle', payload: true }); }; }, []); Object(react__WEBPACK_IMPORTED_MODULE_19__["useEffect"])(function () { dispatch({ type: 'globalSetting/headerFixedToggle', payload: true }); return function () { dispatch({ type: 'globalSetting/headerFixedToggle', payload: false }); }; }, []); Object(react__WEBPACK_IMPORTED_MODULE_19__["useEffect"])(function () { dispatch({ type: 'globalSetting/headerFooterToggle', payload: false }); return function () { dispatch({ type: 'globalSetting/headerFooterToggle', payload: true }); }; }, []); var handleGetTeachGroupData = /*#__PURE__*/function () { var _ref2 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_asyncToGenerator__WEBPACK_IMPORTED_MODULE_11__[/* default */ "a"])( /*#__PURE__*/_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_18___default.a.mark(function _callee() { return _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_18___default.a.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: dispatch({ type: 'problemset/getTeachGroupData' }); case 1: case "end": return _context.stop(); } } }, _callee); })); return function handleGetTeachGroupData() { return _ref2.apply(this, arguments); }; }(); var getItemBanks = /*#__PURE__*/function () { var _ref3 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_asyncToGenerator__WEBPACK_IMPORTED_MODULE_11__[/* default */ "a"])( /*#__PURE__*/_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_18___default.a.mark(function _callee2(query) { var res; return _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_18___default.a.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: query.item_type = query.item_type; setFolderLoading(true); _context2.next = 4; return dispatch({ type: 'problemset/getItemBanks', payload: query }); case 4: res = _context2.sent; if (!(res && res.status !== 403 && res.status !== 401 && res.status !== 500)) { _context2.next = 14; break; } setProblemsetCount(res.items_count || 0); setProblemsetList(res.items || []); setKnowledgeData(res.tag_disciplines || []); // setUseShixunIds(res.used_shixun_ids || []); handleData(res.items || []); setSelectIds([]); setNavigation((res === null || res === void 0 ? void 0 : res.navigation) || []); setFolderLoading(false); return _context2.abrupt("return", res); case 14: case "end": return _context2.stop(); } } }, _callee2); })); return function getItemBanks(_x) { return _ref3.apply(this, arguments); }; }(); var getBasketList = function getBasketList() { dispatch({ type: 'problemset/getBasketList', payload: {} }); }; var handleData = function handleData(problemsetData) { // 1. 过滤掉编程题中的未发布的情况 // 2. 再判断剩下的数据中是否都选中了 var unpublished = problemsetData.every(function (item) { var _item$program_attr; return ((_item$program_attr = item.program_attr) === null || _item$program_attr === void 0 ? void 0 : _item$program_attr.status) === 0; }); unpublishedAll.current = unpublished; }; var handleDirectionChange = function handleDirectionChange(id, subId) { params.discipline_id = id || ''; params.sub_discipline_id = subId || ''; params.tag_discipline_id = ''; params.page = 1; params.per_page = 20; delete params.id; setKnowledgeValue(id === null ? -1 : null); setParams(params); getItemBanks(params); if (id === null) { return; } }; var handleDifficultyChange = function handleDifficultyChange(value) { params.difficulty = value || ''; params.page = 1; params.per_page = 20; delete params.id; setParams(params); getItemBanks(params); }; var handleKnowledgeChange = function handleKnowledgeChange(value) { params.tag_discipline_id = value; params.page = 1; params.per_page = 20; delete params.id; if (value === -1) { params.discipline_id = ''; params.sub_discipline_id = ''; params.tag_discipline_id = ''; } setKnowledgeValue(value); setParams(params); getItemBanks(params); }; var _useState27 = Object(react__WEBPACK_IMPORTED_MODULE_19__["useState"])(false), _useState28 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_12__[/* default */ "a"])(_useState27, 2), showTeachGroup = _useState28[0], setShowTeachGroup = _useState28[1]; var handleTabsChange = function handleTabsChange(activeKey) { dispatch({ type: 'problemset/getDisciplines', payload: { source: 'question', group_id: 0, group_type: activeKey } }); params.discipline_id = ''; params.sub_discipline_id = ''; params.tag_discipline_id = ''; params.difficulty = null; params.type = activeKey; if (activeKey === '0') { params.group_id = 0; } else { params.group_id = null; } // if (activeKey === '3' && isprogram_homework) { // params.only_published = true; // } else { // params.only_published = null; // } if (activeKey === '3') { setShowTeachGroup(true); } else { setShowTeachGroup(false); } params.page = 1; params.per_page = 20; delete params.id; setKnowledgeValue(-1); setActiveTabsKey(activeKey); setParams(params); getItemBanks(params); }; var handleChangePage = function handleChangePage(page, pagesize) { params.page = page; params.per_page = pagesize; setParams(params); getItemBanks(params); }; var handleSearch = function handleSearch(value) { params.discipline_id = ''; params.sub_discipline_id = ''; params.tag_discipline_id = ''; params.difficulty = null; params.page = 1; params.keyword = value; delete params.id; if (value) { setBackIcon(true); Object(_service_global__WEBPACK_IMPORTED_MODULE_29__[/* addSearchRecord */ "a"])({ name: value, copywriting: value, position: 'ItemBank' }); } else { setBackIcon(false); } setKnowledgeValue(-1); setParams(params); getItemBanks(params); }; var handleReloadData = function handleReloadData() { params.per_page = 20; setParams(params); getItemBanks(params); }; var handleOpen = /*#__PURE__*/function () { var _ref4 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_asyncToGenerator__WEBPACK_IMPORTED_MODULE_11__[/* default */ "a"])( /*#__PURE__*/_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_18___default.a.mark(function _callee3(id) { return _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_18___default.a.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: dispatch({ type: 'problemset/getDisciplines', payload: { source: 'question', group_id: Math.abs(id), group_type: TabType.Mine } }); params.page = 1; params.per_page = 20; params.group_id = Math.abs(id); setParams(params); getItemBanks(params).then(function (res) { return setTreeData(res === null || res === void 0 ? void 0 : res.item_banks_group); }); case 6: case "end": return _context3.stop(); } } }, _callee3); })); return function handleOpen(_x2) { return _ref4.apply(this, arguments); }; }(); var handleNewGroup = function handleNewGroup() { dispatch({ type: 'problemset/setActionTabs', payload: { key: '新建文件夹', params: params } }); return; }; var handleShixunChange = function handleShixunChange() { dispatch({ type: 'classroomList/setActionTabs', payload: { key: '选用实践项目' } }); }; var handleChangeTeachGroup = /*#__PURE__*/function () { var _ref5 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_asyncToGenerator__WEBPACK_IMPORTED_MODULE_11__[/* default */ "a"])( /*#__PURE__*/_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_18___default.a.mark(function _callee4(id) { return _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_18___default.a.wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: dispatch({ type: 'problemset/getDisciplines', payload: { source: 'question', group_id: id, group_type: TabType.TeachGroupShare } }); params.page = 1; params.group_id = id || null; delete params.id; setParams(Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_10__[/* default */ "a"])({}, params)); getItemBanks(params); case 6: case "end": return _context4.stop(); } } }, _callee4); })); return function handleChangeTeachGroup(_x3) { return _ref5.apply(this, arguments); }; }(); var handleMenuChange = function handleMenuChange(item) { params.sort_by = item.type; params.sort_direction = item.direction; params.page = 1; params.per_page = 20; setSortMenuName(item.name); setParams(params); getItemBanks(params); }; var handleAddOk = function handleAddOk(id) { params.discipline_id = ''; params.sub_discipline_id = ''; params.tag_discipline_id = ''; params.difficulty = null; params.page = 1; params.per_page = 20; params.group_id = id; setKnowledgeValue(-1); setParams(params); getItemBanks(params).then(function (res) { return setTreeData(res === null || res === void 0 ? void 0 : res.item_banks_group); }); }; var onSelectChange = function onSelectChange(keys) { setSelectIds(keys); }; var questionType = [{ type: 'SINGLE', name: '单选题' }, { type: 'MULTIPLE', name: '多选题' }, { type: 'JUDGMENT', name: '判断题' }, { type: 'PROGRAM', name: '编程题' }, { type: 'SUBJECTIVE', name: '简答题' }, { type: 'COMPLETION', name: '填空题' }, { type: 'COMBINATION', name: '组合题' }]; var difficultyMapping = { 1: '简单', 2: '适中', 3: '困难' }; var handleReplace = /*#__PURE__*/function () { var _ref6 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_asyncToGenerator__WEBPACK_IMPORTED_MODULE_11__[/* default */ "a"])( /*#__PURE__*/_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_18___default.a.mark(function _callee5(itemBankId) { var res; return _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_18___default.a.wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: if (!(queryParams.type === 'exercise')) { _context5.next = 6; break; } _context5.next = 3; return Object(_utils_fetch__WEBPACK_IMPORTED_MODULE_32__[/* default */ "a"])("/api/exercises/".concat(queryParams.exerciseid, "/toggle_random_question.json"), { method: 'post', body: { question_id: queryParams.qid, item_bank_id: itemBankId } }); case 3: res = _context5.sent; if (!(res !== null && res !== void 0 && res.status)) { umi__WEBPACK_IMPORTED_MODULE_20__[/* history */ "d"].push(queryParams.from); } return _context5.abrupt("return"); case 6: case "end": return _context5.stop(); } } }, _callee5); })); return function handleReplace(_x4) { return _ref6.apply(this, arguments); }; }(); return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_25___default.a.page }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("section", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_25___default.a.wrap }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_25___default.a.title }, "\u8BD5\u9898\u5E93"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_25___default.a.headerWrapper }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_25___default.a.tabsWrap }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement(antd_es_tabs__WEBPACK_IMPORTED_MODULE_17__[/* default */ "a"], { activeKey: activeTabsKey, onChange: handleTabsChange, tabBarExtraContent: /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_25___default.a.searchWrap }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement(Search, { allowClear: true, suffix: /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("i", { className: "iconfont icon-sousuo9 font14 ".concat(_index_less_modules__WEBPACK_IMPORTED_MODULE_25___default.a.searchIcon), onClick: function onClick() { return handleSearch(params.keyword); } }), className: _index_less_modules__WEBPACK_IMPORTED_MODULE_25___default.a.search, placeholder: "\u8BF7\u8F93\u5165\u5173\u952E\u8BCD\u641C\u7D22", size: "large", value: params.keyword, onChange: function onChange(e) { params.keyword = e.target.value; setParams(Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_10__[/* default */ "a"])({}, params)); }, onSearch: handleSearch })) }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement(TabPane, { tab: "\u516C\u5171", key: "1" }), ((_problemset$teachGrou = problemset.teachGroupData) === null || _problemset$teachGrou === void 0 ? void 0 : (_problemset$teachGrou2 = _problemset$teachGrou.groups) === null || _problemset$teachGrou2 === void 0 ? void 0 : _problemset$teachGrou2.length) && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement(TabPane, { tab: "\u6211\u7684\u7FA4\u7EC4", key: "3" }), !Object(_utils_authority__WEBPACK_IMPORTED_MODULE_28__[/* isCommonSuperAdminOrOperation */ "o"])() && !Object(_utils_authority__WEBPACK_IMPORTED_MODULE_28__[/* isCommonStudent */ "m"])() && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement(TabPane, { tab: "\u6536\u85CF\u5939", key: "2" }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement(TabPane, { tab: "\u6211\u521B\u5EFA\u7684", key: "0" }))), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement(_components_LanguageSelect__WEBPACK_IMPORTED_MODULE_21__[/* LanguageSelect */ "a"], { showSelectAll: false, className: _index_less_modules__WEBPACK_IMPORTED_MODULE_25___default.a.select, disciplinesData: (_problemset$disciplin = problemset.disciplinesData) === null || _problemset$disciplin === void 0 ? void 0 : _problemset$disciplin.disciplines, knowledgeData: knowledgeData, directionValue: params.discipline_id, subDisciplineValue: params.sub_discipline_id, typeValue: params.item_type, isprogram_homework: false, showItemType: false //换一题功能页面,不展示题型筛选项 , showKnowledge: true, name: name, setname: setname, difficultyValue: params.difficulty, showShixun: false, onShixunChange: handleShixunChange, onDirectionChange: handleDirectionChange, onTypeChange: function onTypeChange() {}, onDifficultyChange: handleDifficultyChange, knowledgeValue: knowledgeValue, onKnowledgeChange: handleKnowledgeChange, teachGroupData: (_problemset$teachGrou3 = problemset.teachGroupData) === null || _problemset$teachGrou3 === void 0 ? void 0 : _problemset$teachGrou3.groups, onTeachGroupChange: handleChangeTeachGroup, teachGroupValue: params.group_id, showTeachGroup: showTeachGroup })), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_25___default.a.treeWrapper, style: { display: activeTabsKey === TabType.Mine ? 'block' : 'none' } }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_25___default.a.treeHeader }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement(_pages_Problemset_components_Crumbs__WEBPACK_IMPORTED_MODULE_24__[/* default */ "a"], { data: navigation, onClick: handleOpen }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement(antd_es_button__WEBPACK_IMPORTED_MODULE_9__[/* default */ "a"], { type: "link", onClick: handleNewGroup, className: _index_less_modules__WEBPACK_IMPORTED_MODULE_25___default.a.exportBtn }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("img", { src: _assets_images_problemset_folder_opened_png__WEBPACK_IMPORTED_MODULE_30___default.a, alt: "", className: _index_less_modules__WEBPACK_IMPORTED_MODULE_25___default.a.pngIcon }), "\u65B0\u5EFA\u6587\u4EF6\u5939")), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement(antd_es_spin__WEBPACK_IMPORTED_MODULE_7__[/* default */ "a"], { spinning: folderLoading }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("div", { ref: treeDataWarp, className: _index_less_modules__WEBPACK_IMPORTED_MODULE_25___default.a.treeContent }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement(_pages_Problemset_components_NewFolder__WEBPACK_IMPORTED_MODULE_27__[/* default */ "a"], { isProblemset: false, reloadData: handleReloadData, data: treeData, onShare: function onShare() {}, onOpen: handleOpen })))), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_25___default.a.contentWrap }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_25___default.a.batchWrap }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("div", { style: { flex: 1, display: 'flex', alignItems: 'center' } }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("div", { className: "font14" }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement(antd_es_dropdown__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"], { overlay: /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement(antd_es_menu__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"], { selectedKeys: [SortMenuName] }, SortMenus === null || SortMenus === void 0 ? void 0 : SortMenus.map(function (item, index) { return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement(antd_es_menu__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].Item, { key: item.name, onClick: function onClick() { return handleMenuChange(item); } }, item.name); })) }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("span", { style: { color: '#464F66' } }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("i", { className: "iconfont icon-paixu font14 mr5 c-light-primary" }), SortMenuName))))), backIcon ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("div", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement(antd_es_button__WEBPACK_IMPORTED_MODULE_9__[/* default */ "a"], { style: { paddingLeft: 0 }, onClick: function onClick() { params.page = 1; params.keyword = null; delete params.id; setParams(params); setBackIcon(false); getItemBanks(params); }, type: "link" }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("i", { className: "iconfont icon-fanhui2 font14" }), "\u8FD4\u56DE"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("span", { className: "font14 mr20 c-grey-333" }, "\u641C\u7D22\u201C", params.keyword, "\u201D")) : null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_25___default.a.contentListWrap }, problemsetCount !== 0 ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement(antd_es_spin__WEBPACK_IMPORTED_MODULE_7__[/* default */ "a"], { size: "large", spinning: loading['problemset/getItemBanks'] }, problemsetList.map(function (v, index) { var _questionType$find, _v$author; return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_25___default.a.li, key: v.id }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_25___default.a.top }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement(_pages_Problemset_components_Topic__WEBPACK_IMPORTED_MODULE_26__[/* default */ "b"], { showCheckbox: false, data: v, selectIds: selectIds, onSelectCheckBox: onSelectChange })), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_25___default.a.bottom }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("p", { className: "".concat(_index_less_modules__WEBPACK_IMPORTED_MODULE_25___default.a.actionLeftItem, " ").concat(_index_less_modules__WEBPACK_IMPORTED_MODULE_25___default.a.questionTypeName) }, (_questionType$find = questionType.find(function (item) { return item.type === v.item_type; })) === null || _questionType$find === void 0 ? void 0 : _questionType$find.name), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("p", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_25___default.a.actionLeftItem }, difficultyMapping[v.difficulty]), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("p", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_25___default.a.actionLeftItem }, "\u521B\u5EFA\u8005", /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("span", { className: "c-grey-333" }, v === null || v === void 0 ? void 0 : (_v$author = v.author) === null || _v$author === void 0 ? void 0 : _v$author.name)), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("p", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_25___default.a.actionLeftItem }, "\u66F4\u65B0", /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("span", { className: "c-grey-333" }, v === null || v === void 0 ? void 0 : v.updated_at)), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("p", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_25___default.a.actionLeftItem }, "\u4F7F\u7528\u6B21\u6570", /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("span", { className: "c-grey-333" }, v === null || v === void 0 ? void 0 : v.quotes)), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_25___default.a.more }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("span", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_25___default.a.btnAdd, onClick: function onClick() { return handleReplace(v.id); } }, "\u66FF\u6362")))); })) : /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement(antd_es_spin__WEBPACK_IMPORTED_MODULE_7__[/* default */ "a"], { size: "large", spinning: loading['problemset/getItemBanks'] }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement(_components_NoData__WEBPACK_IMPORTED_MODULE_23__[/* default */ "a"], null))), problemsetCount !== 0 && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement(antd_es_pagination__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"], { // showSizeChanger={false} showQuickJumper: true, onChange: handleChangePage, defaultCurrent: 1, pageSize: params === null || params === void 0 ? void 0 : params.per_page, current: params.page || 1, total: problemsetCount, showTotal: function showTotal(total) { return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("span", { className: "mr10" }, "\u5171", /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement("span", { className: "c-light-primary" }, total), "\u6761\u6570\u636E"); } }))), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_19___default.a.createElement(_pages_Problemset_components_AddModal__WEBPACK_IMPORTED_MODULE_22__[/* default */ "a"], { onOk: handleAddOk }))); }; /* harmony default export */ __webpack_exports__["default"] = (Object(umi__WEBPACK_IMPORTED_MODULE_20__[/* connect */ "a"])(function (_ref7) { var classroomList = _ref7.classroomList, problemset = _ref7.problemset, user = _ref7.user, loading = _ref7.loading, globalSetting = _ref7.globalSetting, shixunHomeworks = _ref7.shixunHomeworks; return { classroomList: classroomList, problemset: problemset, user: user, globalSetting: globalSetting, loading: loading.effects, shixunHomeworks: shixunHomeworks }; })(ProblemsetPage)); /***/ }), /***/ "LE3n": /*!*************************************************************!*\ !*** ./src/pages/Problemset/components/NewFolder/index.tsx ***! \*************************************************************/ /*! exports provided: default */ /*! exports used: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var antd_es_tree_style__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! antd/es/tree/style */ "ozfa"); /* harmony import */ var antd_es_tree__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! antd/es/tree */ "MJZm"); /* harmony import */ var _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/objectSpread2 */ "k1fw"); /* harmony import */ var antd_es_button_style__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! antd/es/button/style */ "+L6B"); /* harmony import */ var antd_es_button__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! antd/es/button */ "2/Rp"); /* harmony import */ var antd_es_input_style__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! antd/es/input/style */ "5NDa"); /* harmony import */ var antd_es_input__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! antd/es/input */ "5rEg"); /* harmony import */ var antd_es_modal_style__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! antd/es/modal/style */ "2qtc"); /* harmony import */ var antd_es_modal__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! antd/es/modal */ "kLXV"); /* harmony import */ var antd_es_message_style__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! antd/es/message/style */ "miYZ"); /* harmony import */ var antd_es_message__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! antd/es/message */ "tsqr"); /* harmony import */ var _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_asyncToGenerator__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/asyncToGenerator */ "9og8"); /* harmony import */ var _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/slicedToArray */ "tJVT"); /* harmony import */ var _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/regenerator */ "WmNS"); /* harmony import */ var _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_13__); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! react */ "cDcd"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_14__); /* harmony import */ var _index_less_modules__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./index.less?modules */ "1vnw"); /* harmony import */ var _index_less_modules__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_index_less_modules__WEBPACK_IMPORTED_MODULE_15__); /* harmony import */ var _utils_fetch__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! @/utils/fetch */ "ErOA"); /* harmony import */ var _assets_images_problemset_folder_closed_png__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! @/assets/images/problemset/folder-closed.png */ "Ix/O"); /* harmony import */ var _assets_images_problemset_folder_closed_png__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_assets_images_problemset_folder_closed_png__WEBPACK_IMPORTED_MODULE_17__); /* harmony import */ var _assets_images_problemset_folder_opened_png__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! @/assets/images/problemset/folder-opened.png */ "xTzM"); /* harmony import */ var _assets_images_problemset_folder_opened_png__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_assets_images_problemset_folder_opened_png__WEBPACK_IMPORTED_MODULE_18__); /* harmony import */ var _service_problemset__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! @/service/problemset */ "WCUW"); /* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! lodash */ "LvDl"); /* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_20___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_20__); var FolderItems = function FolderItems(_ref) { var isProblemset = _ref.isProblemset, name = _ref.name, id = _ref.id, itemBanksCount = _ref.itemBanksCount, _ref$onOpen = _ref.onOpen, onOpen = _ref$onOpen === void 0 ? function () {} : _ref$onOpen, _ref$onShare = _ref.onShare, onShare = _ref$onShare === void 0 ? function () {} : _ref$onShare, _ref$onMove = _ref.onMove, onMove = _ref$onMove === void 0 ? function () {} : _ref$onMove, _ref$onDeleteOk = _ref.onDeleteOk, onDeleteOk = _ref$onDeleteOk === void 0 ? function () {} : _ref$onDeleteOk; var _useState = Object(react__WEBPACK_IMPORTED_MODULE_14__["useState"])(false), _useState2 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_12__[/* default */ "a"])(_useState, 2), visible = _useState2[0], setVisible = _useState2[1]; var _useState3 = Object(react__WEBPACK_IMPORTED_MODULE_14__["useState"])(name), _useState4 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_12__[/* default */ "a"])(_useState3, 2), folderName = _useState4[0], setFolderName = _useState4[1]; var _useState5 = Object(react__WEBPACK_IMPORTED_MODULE_14__["useState"])(name), _useState6 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_12__[/* default */ "a"])(_useState5, 2), inputValue = _useState6[0], setInputValue = _useState6[1]; var onRename = /*#__PURE__*/function () { var _ref2 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_asyncToGenerator__WEBPACK_IMPORTED_MODULE_11__[/* default */ "a"])( /*#__PURE__*/_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_13___default.a.mark(function _callee(id) { var array, i, res; return _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_13___default.a.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: array = ['?', '、', '/', '╲', '*', '<', '>', '|']; if (inputValue.trim()) { _context.next = 4; break; } antd_es_message__WEBPACK_IMPORTED_MODULE_10__[/* default */ "b"].warn('请输入文件夹名称'); return _context.abrupt("return"); case 4: if (!(inputValue.charAt(0) === ' ')) { _context.next = 7; break; } antd_es_message__WEBPACK_IMPORTED_MODULE_10__[/* default */ "b"].warn('首字符不能为空格'); return _context.abrupt("return"); case 7: i = 0; case 8: if (!(i < inputValue.length)) { _context.next = 15; break; } if (!array.includes(inputValue.charAt(i))) { _context.next = 12; break; } antd_es_message__WEBPACK_IMPORTED_MODULE_10__[/* default */ "b"].warn('文件夹名称包含特殊字符'); return _context.abrupt("return", false); case 12: i++; _context.next = 8; break; case 15: _context.next = 17; return Object(_utils_fetch__WEBPACK_IMPORTED_MODULE_16__[/* default */ "a"])("/api/item_banks_groups/".concat(Math.abs(id), ".json"), { method: 'put', body: { name: inputValue } }); case 17: res = _context.sent; if (res.status === 0) { setVisible(false); setFolderName(inputValue); } case 19: case "end": return _context.stop(); } } }, _callee); })); return function onRename(_x) { return _ref2.apply(this, arguments); }; }(); var onDelete = function onDelete(id) { antd_es_modal__WEBPACK_IMPORTED_MODULE_8__[/* default */ "a"].confirm({ title: '提示', okText: '确认删除', className: 'custom-modal-divider ', icon: null, content: /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_14___default.a.createElement("div", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_14___default.a.createElement("p", null, "\u672C\u6B21\u5220\u9664\u64CD\u4F5C\u786E\u5B9A\u540E\u5185\u5BB9\u5C06\u65E0\u6CD5\u6062\u590D\uFF0C\u662F\u5426\u7EE7\u7EED\uFF1F"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_14___default.a.createElement("p", null, "\u5220\u9664\u6587\u4EF6\u5939\uFF0C\u5C06\u540C\u6B65\u5220\u9664\u5176\u6240\u5305\u542B\u7684\u5168\u90E8\u5B50\u6587\u4EF6\u5939\u548C\u8BD5\u9898\uFF0C\u8BF7\u614E\u91CD\u64CD\u4F5C\uFF01")), cancelText: '取消', onOk: function () { var _onOk = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_asyncToGenerator__WEBPACK_IMPORTED_MODULE_11__[/* default */ "a"])( /*#__PURE__*/_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_13___default.a.mark(function _callee2() { var res; return _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_13___default.a.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _context2.next = 2; return Object(_utils_fetch__WEBPACK_IMPORTED_MODULE_16__[/* default */ "a"])("/api/item_banks_groups/".concat(Math.abs(id), ".json"), { method: 'delete', body: {} }); case 2: res = _context2.sent; if (res.status === 0) { onDeleteOk(id); } case 4: case "end": return _context2.stop(); } } }, _callee2); })); function onOk() { return _onOk.apply(this, arguments); } return onOk; }() }); }; return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_14___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_15___default.a.list }, visible ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_14___default.a.createElement(antd_es_input__WEBPACK_IMPORTED_MODULE_6__[/* default */ "a"], { style: { maxWidth: 780 }, value: inputValue, onChange: function onChange(e) { return setInputValue(e.target.value); } }) : /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_14___default.a.createElement("div", { title: folderName, onClick: function onClick() { return onOpen(id); }, className: _index_less_modules__WEBPACK_IMPORTED_MODULE_15___default.a.name }, folderName), isProblemset && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_14___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_15___default.a.btns }, visible ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_14___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_14___default.a.Fragment, null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_14___default.a.createElement("div", { style: { height: 16 }, onClick: function onClick() { return onRename(id); }, className: "ml0" }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_14___default.a.createElement("i", { className: "iconfont icon-chenggong1", style: { color: '#33BD8C' } })), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_14___default.a.createElement("div", { style: { height: 16 }, onClick: function onClick() { setInputValue(folderName); setVisible(false); }, className: "ml10" }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_14___default.a.createElement("i", { className: "iconfont icon-qingchu" }))) : /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_14___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_14___default.a.Fragment, null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_14___default.a.createElement("div", { onClick: function onClick() { return onMove(id, 'up'); }, className: "ml0" }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_14___default.a.createElement("i", { className: "iconfont icon-shangyi3", style: { transform: 'translateY(2px)' } })), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_14___default.a.createElement("div", { onClick: function onClick() { return onMove(id, 'down'); }, className: "ml10", style: { transform: 'rotate(180deg) translateY(1px)' } }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_14___default.a.createElement("i", { className: "iconfont icon-shangyi3" }))), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_14___default.a.createElement(antd_es_button__WEBPACK_IMPORTED_MODULE_4__[/* default */ "a"], { className: "ml10", onClick: function onClick() { if (!itemBanksCount) { antd_es_message__WEBPACK_IMPORTED_MODULE_10__[/* default */ "b"].warn('该目录下没有试题'); return; } onShare(Math.abs(id)); }, type: "link" }, "\u5171\u4EAB\u5168\u90E8\u8BD5\u9898"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_14___default.a.createElement(antd_es_button__WEBPACK_IMPORTED_MODULE_4__[/* default */ "a"], { className: "ml10", onClick: function onClick() { return setVisible(true); }, type: "link" }, "\u91CD\u547D\u540D"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_14___default.a.createElement(antd_es_button__WEBPACK_IMPORTED_MODULE_4__[/* default */ "a"], { onClick: function onClick() { return onDelete(id); }, type: "link", danger: true }, "\u5220\u9664"))); }; var NewFolder = function NewFolder(_ref3) { var isProblemset = _ref3.isProblemset, data = _ref3.data, _ref3$onOpen = _ref3.onOpen, onOpen = _ref3$onOpen === void 0 ? function () {} : _ref3$onOpen, _ref3$onShare = _ref3.onShare, onShare = _ref3$onShare === void 0 ? function () {} : _ref3$onShare, reloadData = _ref3.reloadData; var _useState7 = Object(react__WEBPACK_IMPORTED_MODULE_14__["useState"])(), _useState8 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_12__[/* default */ "a"])(_useState7, 2), treeData = _useState8[0], setTreeData = _useState8[1]; Object(react__WEBPACK_IMPORTED_MODULE_14__["useEffect"])(function () { setTreeData(data === null || data === void 0 ? void 0 : data.map(function (item) { return { title: /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_14___default.a.createElement(FolderItems, { isProblemset: isProblemset, name: item.name, id: item.id, itemBanksCount: item.item_banks_count, onMove: handleMove, onOpen: onOpen, onShare: onShare, onDeleteOk: handleDelete }), key: item.id, icon: /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_14___default.a.createElement("img", { src: _assets_images_problemset_folder_closed_png__WEBPACK_IMPORTED_MODULE_17___default.a, className: _index_less_modules__WEBPACK_IMPORTED_MODULE_15___default.a.folderIcon }), isLeaf: false }; })); }, [data]); var moveTreeNode = function moveTreeNode(list, key, direction) { //最顶部和最底部的边界条件后端会处理 var listCopy = Object(lodash__WEBPACK_IMPORTED_MODULE_20__["cloneDeep"])(list); for (var i = 0; i < listCopy.length; i++) { if (listCopy[i].key === key) { if (direction === 'up') { var _ref4 = [listCopy[i], listCopy[i - 1]]; listCopy[i - 1] = _ref4[0]; listCopy[i] = _ref4[1]; } else { var _ref5 = [listCopy[i + 1], listCopy[i]]; listCopy[i] = _ref5[0]; listCopy[i + 1] = _ref5[1]; } break; } if (listCopy[i].children) { listCopy[i].children = moveTreeNode(listCopy[i].children, key, direction); } } return listCopy; }; var handleMove = /*#__PURE__*/function () { var _ref6 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_asyncToGenerator__WEBPACK_IMPORTED_MODULE_11__[/* default */ "a"])( /*#__PURE__*/_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_13___default.a.mark(function _callee3(id, direction) { var res; return _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_13___default.a.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: if (!(direction === 'up')) { _context3.next = 6; break; } _context3.next = 3; return Object(_service_problemset__WEBPACK_IMPORTED_MODULE_19__[/* moveUp */ "I"])({ id: Math.abs(id) }); case 3: _context3.t0 = _context3.sent; _context3.next = 9; break; case 6: _context3.next = 8; return Object(_service_problemset__WEBPACK_IMPORTED_MODULE_19__[/* moveDown */ "H"])({ id: Math.abs(id) }); case 8: _context3.t0 = _context3.sent; case 9: res = _context3.t0; if (res.status === 0) { setTreeData(function (originData) { return moveTreeNode(originData, id, direction); }); } case 11: case "end": return _context3.stop(); } } }, _callee3); })); return function handleMove(_x2, _x3) { return _ref6.apply(this, arguments); }; }(); var deleteTreeNode = function deleteTreeNode(list, key) { return list.filter(function (node) { if (node.key === key) { return false; } if (node.children) { node.children = deleteTreeNode(node.children, key); } return true; }); }; var handleDelete = function handleDelete(id) { setTreeData(function (originData) { return deleteTreeNode(originData, id); }); reloadData(); }; //更新treeNode的统一方法 var updateTreeData = function updateTreeData(list, key, changePart) { return list.map(function (node) { if (node.key === key) { return Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"])(Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"])({}, node), changePart); } if (node.children) { return Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"])(Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"])({}, node), {}, { children: updateTreeData(node.children, key, changePart) }); } return node; }); }; var onLoadData = /*#__PURE__*/function () { var _ref7 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_asyncToGenerator__WEBPACK_IMPORTED_MODULE_11__[/* default */ "a"])( /*#__PURE__*/_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_13___default.a.mark(function _callee4(nodeData) { var key, res, _ref8, item_banks_group, item_banks_group_count; return _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_13___default.a.wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: key = nodeData.key; _context4.next = 3; return Object(_service_problemset__WEBPACK_IMPORTED_MODULE_19__[/* getSubdirectory */ "B"])({ group_id: Math.abs(key) }); case 3: res = _context4.sent; _ref8 = res || {}, item_banks_group = _ref8.item_banks_group, item_banks_group_count = _ref8.item_banks_group_count; if (item_banks_group_count > 0) { setTreeData(function (originData) { return updateTreeData(originData, key, { children: item_banks_group.map(function (item) { return { title: /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_14___default.a.createElement(FolderItems, { isProblemset: isProblemset, name: item.name, id: item.id, itemBanksCount: item.item_banks_count, onMove: handleMove, onOpen: onOpen, onShare: onShare, onDeleteOk: handleDelete }), key: item.id, icon: /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_14___default.a.createElement("img", { src: _assets_images_problemset_folder_closed_png__WEBPACK_IMPORTED_MODULE_17___default.a, className: _index_less_modules__WEBPACK_IMPORTED_MODULE_15___default.a.folderIcon }), isLeaf: false }; }) }); }); } else { setTreeData(function (originData) { return updateTreeData(originData, key, { isLeaf: true }); }); } case 6: case "end": return _context4.stop(); } } }, _callee4); })); return function onLoadData(_x4) { return _ref7.apply(this, arguments); }; }(); var onExpand = function onExpand(expandedKeys, info) { var node = info.node, expanded = info.expanded; setTreeData(function (originData) { return updateTreeData(originData, node.key, { icon: expanded ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_14___default.a.createElement("img", { src: _assets_images_problemset_folder_opened_png__WEBPACK_IMPORTED_MODULE_18___default.a, className: _index_less_modules__WEBPACK_IMPORTED_MODULE_15___default.a.folderIcon }) : /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_14___default.a.createElement("img", { src: _assets_images_problemset_folder_closed_png__WEBPACK_IMPORTED_MODULE_17___default.a, className: _index_less_modules__WEBPACK_IMPORTED_MODULE_15___default.a.folderIcon }) }); }); }; return (treeData === null || treeData === void 0 ? void 0 : treeData.length) > 0 && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_14___default.a.createElement(antd_es_tree__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"], { showLine: { showLeafIcon: false }, showIcon: true, treeData: treeData, loadData: onLoadData, onExpand: onExpand, className: _index_less_modules__WEBPACK_IMPORTED_MODULE_15___default.a.folderWrapper, selectable: false }); }; /* harmony default export */ __webpack_exports__["a"] = (NewFolder); /***/ }), /***/ "LdHM": /*!********************************************************!*\ !*** ./node_modules/rc-select/es/index.js + 6 modules ***! \********************************************************/ /*! exports provided: Option, OptGroup, default */ /*! exports used: OptGroup, Option, default */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/classCallCheck.js */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/createClass.js */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/createSuper.js */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/defineProperty.js */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/inherits.js */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/objectSpread2.js */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/slicedToArray.js */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/typeof.js */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/classnames/index.js (<- Module is not an ECMAScript module) */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-select/es/TransBtn.js */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-select/es/generate.js */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-select/es/utils/commonUtil.js */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-select/es/utils/valueUtil.js */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/Children/toArray.js */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/KeyCode.js */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/hooks/useMemo.js */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/pickAttrs.js */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/warning.js */ /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-virtual-list/es/index.js */ /*! ModuleConcatenation bailout: Cannot concat with external "window.React" (<- Module is not an ECMAScript module) */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; // EXPORTS __webpack_require__.d(__webpack_exports__, "b", function() { return /* reexport */ es_Option; }); __webpack_require__.d(__webpack_exports__, "a", function() { return /* reexport */ es_OptGroup; }); // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/classCallCheck.js var classCallCheck = __webpack_require__("1OyB"); // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/createClass.js var createClass = __webpack_require__("vuIU"); // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/inherits.js var inherits = __webpack_require__("Ji7U"); // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/createSuper.js + 1 modules var createSuper = __webpack_require__("LK+K"); // EXTERNAL MODULE: external "window.React" var external_window_React_ = __webpack_require__("cDcd"); // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/defineProperty.js var defineProperty = __webpack_require__("rePB"); // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js var objectWithoutProperties = __webpack_require__("Ff2n"); // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/slicedToArray.js + 1 modules var slicedToArray = __webpack_require__("ODXe"); // EXTERNAL MODULE: ./node_modules/rc-util/es/KeyCode.js var KeyCode = __webpack_require__("4IlW"); // EXTERNAL MODULE: ./node_modules/rc-util/es/pickAttrs.js var pickAttrs = __webpack_require__("bX4T"); // EXTERNAL MODULE: ./node_modules/rc-util/es/hooks/useMemo.js var useMemo = __webpack_require__("YrtM"); // EXTERNAL MODULE: ./node_modules/classnames/index.js var classnames = __webpack_require__("TSYQ"); var classnames_default = /*#__PURE__*/__webpack_require__.n(classnames); // EXTERNAL MODULE: ./node_modules/rc-virtual-list/es/index.js + 19 modules var es = __webpack_require__("+nKL"); // EXTERNAL MODULE: ./node_modules/rc-select/es/TransBtn.js var TransBtn = __webpack_require__("8OUc"); // CONCATENATED MODULE: ./node_modules/rc-select/es/OptionList.js /** * Using virtual list of option display. * Will fallback to dom if use customize render. */ var OptionList_OptionList = function OptionList(_ref, ref) { var prefixCls = _ref.prefixCls, id = _ref.id, flattenOptions = _ref.flattenOptions, childrenAsData = _ref.childrenAsData, values = _ref.values, searchValue = _ref.searchValue, multiple = _ref.multiple, defaultActiveFirstOption = _ref.defaultActiveFirstOption, height = _ref.height, itemHeight = _ref.itemHeight, notFoundContent = _ref.notFoundContent, open = _ref.open, menuItemSelectedIcon = _ref.menuItemSelectedIcon, virtual = _ref.virtual, onSelect = _ref.onSelect, onToggleOpen = _ref.onToggleOpen, onActiveValue = _ref.onActiveValue, onScroll = _ref.onScroll, onMouseEnter = _ref.onMouseEnter; var itemPrefixCls = "".concat(prefixCls, "-item"); var memoFlattenOptions = Object(useMemo["a" /* default */])(function () { return flattenOptions; }, [open, flattenOptions], function (prev, next) { return next[0] && prev[1] !== next[1]; }); // =========================== List =========================== var listRef = external_window_React_["useRef"](null); var onListMouseDown = function onListMouseDown(event) { event.preventDefault(); }; var scrollIntoView = function scrollIntoView(index) { if (listRef.current) { listRef.current.scrollTo({ index: index }); } }; // ========================== Active ========================== var getEnabledActiveIndex = function getEnabledActiveIndex(index) { var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; var len = memoFlattenOptions.length; for (var i = 0; i < len; i += 1) { var current = (index + i * offset + len) % len; var _memoFlattenOptions$c = memoFlattenOptions[current], group = _memoFlattenOptions$c.group, data = _memoFlattenOptions$c.data; if (!group && !data.disabled) { return current; } } return -1; }; var _React$useState = external_window_React_["useState"](function () { return getEnabledActiveIndex(0); }), _React$useState2 = Object(slicedToArray["a" /* default */])(_React$useState, 2), activeIndex = _React$useState2[0], setActiveIndex = _React$useState2[1]; var setActive = function setActive(index) { setActiveIndex(index); // Trigger active event var flattenItem = memoFlattenOptions[index]; if (!flattenItem) { onActiveValue(null, -1); return; } onActiveValue(flattenItem.data.value, index); }; // Auto active first item when list length or searchValue changed external_window_React_["useEffect"](function () { setActive(defaultActiveFirstOption !== false ? getEnabledActiveIndex(0) : -1); }, [memoFlattenOptions.length, searchValue]); // Auto scroll to item position in single mode external_window_React_["useEffect"](function () { /** * React will skip `onChange` when component update. * `setActive` function will call root accessibility state update which makes re-render. * So we need to delay to let Input component trigger onChange first. */ var timeoutId = setTimeout(function () { if (!multiple && open && values.size === 1) { var value = Array.from(values)[0]; var index = memoFlattenOptions.findIndex(function (_ref2) { var data = _ref2.data; return data.value === value; }); setActive(index); scrollIntoView(index); } }); return function () { return clearTimeout(timeoutId); }; }, [open]); // ========================== Values ========================== var onSelectValue = function onSelectValue(value) { if (value !== undefined) { onSelect(value, { selected: !values.has(value) }); } // Single mode should always close by select if (!multiple) { onToggleOpen(false); } }; // ========================= Keyboard ========================= external_window_React_["useImperativeHandle"](ref, function () { return { onKeyDown: function onKeyDown(event) { var which = event.which; switch (which) { // >>> Arrow keys case KeyCode["a" /* default */].UP: case KeyCode["a" /* default */].DOWN: { var offset = 0; if (which === KeyCode["a" /* default */].UP) { offset = -1; } else if (which === KeyCode["a" /* default */].DOWN) { offset = 1; } if (offset !== 0) { var nextActiveIndex = getEnabledActiveIndex(activeIndex + offset, offset); scrollIntoView(nextActiveIndex); setActive(nextActiveIndex); } break; } // >>> Select case KeyCode["a" /* default */].ENTER: { // value var item = memoFlattenOptions[activeIndex]; if (item && !item.data.disabled) { onSelectValue(item.data.value); } else { onSelectValue(undefined); } if (open) { event.preventDefault(); } break; } // >>> Close case KeyCode["a" /* default */].ESC: { onToggleOpen(false); } } }, onKeyUp: function onKeyUp() {}, scrollTo: function scrollTo(index) { scrollIntoView(index); } }; }); // ========================== Render ========================== if (memoFlattenOptions.length === 0) { return external_window_React_["createElement"]("div", { role: "listbox", id: "".concat(id, "_list"), className: "".concat(itemPrefixCls, "-empty"), onMouseDown: onListMouseDown }, notFoundContent); } function renderItem(index) { var item = memoFlattenOptions[index]; if (!item) return null; var itemData = item.data || {}; var value = itemData.value, label = itemData.label, children = itemData.children; var attrs = Object(pickAttrs["a" /* default */])(itemData, true); var mergedLabel = childrenAsData ? children : label; return item ? external_window_React_["createElement"]("div", Object.assign({ "aria-label": typeof mergedLabel === 'string' ? mergedLabel : null }, attrs, { key: index, role: "option", id: "".concat(id, "_list_").concat(index), "aria-selected": values.has(value) }), value) : null; } return external_window_React_["createElement"](external_window_React_["Fragment"], null, external_window_React_["createElement"]("div", { role: "listbox", id: "".concat(id, "_list"), style: { height: 0, width: 0, overflow: 'hidden' } }, renderItem(activeIndex - 1), renderItem(activeIndex), renderItem(activeIndex + 1)), external_window_React_["createElement"](es["a" /* default */], { itemKey: "key", ref: listRef, data: memoFlattenOptions, height: height, itemHeight: itemHeight, fullHeight: false, onMouseDown: onListMouseDown, onScroll: onScroll, virtual: virtual, onMouseEnter: onMouseEnter }, function (_ref3, itemIndex) { var _classNames; var group = _ref3.group, groupOption = _ref3.groupOption, data = _ref3.data; var label = data.label, key = data.key; // Group if (group) { return external_window_React_["createElement"]("div", { className: classnames_default()(itemPrefixCls, "".concat(itemPrefixCls, "-group")) }, label !== undefined ? label : key); } var disabled = data.disabled, value = data.value, title = data.title, children = data.children, style = data.style, className = data.className, otherProps = Object(objectWithoutProperties["a" /* default */])(data, ["disabled", "value", "title", "children", "style", "className"]); // Option var selected = values.has(value); var optionPrefixCls = "".concat(itemPrefixCls, "-option"); var optionClassName = classnames_default()(itemPrefixCls, optionPrefixCls, className, (_classNames = {}, Object(defineProperty["a" /* default */])(_classNames, "".concat(optionPrefixCls, "-grouped"), groupOption), Object(defineProperty["a" /* default */])(_classNames, "".concat(optionPrefixCls, "-active"), activeIndex === itemIndex && !disabled), Object(defineProperty["a" /* default */])(_classNames, "".concat(optionPrefixCls, "-disabled"), disabled), Object(defineProperty["a" /* default */])(_classNames, "".concat(optionPrefixCls, "-selected"), selected), _classNames)); var mergedLabel = childrenAsData ? children : label; var iconVisible = !menuItemSelectedIcon || typeof menuItemSelectedIcon === 'function' || selected; return external_window_React_["createElement"]("div", Object.assign({}, otherProps, { "aria-selected": selected, className: optionClassName, title: title, onMouseMove: function onMouseMove() { if (activeIndex === itemIndex || disabled) { return; } setActive(itemIndex); }, onClick: function onClick() { if (!disabled) { onSelectValue(value); } }, style: style }), external_window_React_["createElement"]("div", { className: "".concat(optionPrefixCls, "-content") }, mergedLabel || value), external_window_React_["isValidElement"](menuItemSelectedIcon) || selected, iconVisible && external_window_React_["createElement"](TransBtn["a" /* default */], { className: "".concat(itemPrefixCls, "-option-state"), customizeIcon: menuItemSelectedIcon, customizeIconProps: { isSelected: selected } }, selected ? '✓' : null)); })); }; var RefOptionList = external_window_React_["forwardRef"](OptionList_OptionList); RefOptionList.displayName = 'OptionList'; /* harmony default export */ var es_OptionList = (RefOptionList); // CONCATENATED MODULE: ./node_modules/rc-select/es/Option.js /** This is a placeholder, not real render in dom */ var Option = function Option() { return null; }; Option.isSelectOption = true; /* harmony default export */ var es_Option = (Option); // CONCATENATED MODULE: ./node_modules/rc-select/es/OptGroup.js /** This is a placeholder, not real render in dom */ var OptGroup = function OptGroup() { return null; }; OptGroup.isSelectOptGroup = true; /* harmony default export */ var es_OptGroup = (OptGroup); // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/objectSpread2.js var objectSpread2 = __webpack_require__("VTBJ"); // EXTERNAL MODULE: ./node_modules/rc-util/es/Children/toArray.js var toArray = __webpack_require__("Zm9Q"); // CONCATENATED MODULE: ./node_modules/rc-select/es/utils/legacyUtil.js function convertNodeToOption(node) { var key = node.key, _node$props = node.props, children = _node$props.children, value = _node$props.value, restProps = Object(objectWithoutProperties["a" /* default */])(_node$props, ["children", "value"]); return Object(objectSpread2["a" /* default */])({ key: key, value: value !== undefined ? value : key, children: children }, restProps); } function convertChildrenToData(nodes) { var optionOnly = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; return Object(toArray["a" /* default */])(nodes).map(function (node, index) { if (!external_window_React_["isValidElement"](node) || !node.type) { return null; } var isSelectOptGroup = node.type.isSelectOptGroup, key = node.key, _node$props2 = node.props, children = _node$props2.children, restProps = Object(objectWithoutProperties["a" /* default */])(_node$props2, ["children"]); if (optionOnly || !isSelectOptGroup) { return convertNodeToOption(node); } return Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({ key: "__RC_SELECT_GRP__".concat(key === null ? index : key, "__"), label: key }, restProps), {}, { options: convertChildrenToData(children) }); }).filter(function (data) { return data; }); } // EXTERNAL MODULE: ./node_modules/rc-select/es/utils/valueUtil.js var valueUtil = __webpack_require__("2Qr1"); // EXTERNAL MODULE: ./node_modules/rc-select/es/generate.js + 11 modules var generate = __webpack_require__("qNPg"); // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/typeof.js var esm_typeof = __webpack_require__("U8pU"); // EXTERNAL MODULE: ./node_modules/rc-util/es/warning.js var warning = __webpack_require__("Kwbf"); // EXTERNAL MODULE: ./node_modules/rc-select/es/utils/commonUtil.js var commonUtil = __webpack_require__("WKfj"); // CONCATENATED MODULE: ./node_modules/rc-select/es/utils/warningPropsUtil.js function warningProps(props) { var mode = props.mode, options = props.options, children = props.children, backfill = props.backfill, allowClear = props.allowClear, placeholder = props.placeholder, getInputElement = props.getInputElement, showSearch = props.showSearch, onSearch = props.onSearch, defaultOpen = props.defaultOpen, autoFocus = props.autoFocus, labelInValue = props.labelInValue, value = props.value, inputValue = props.inputValue, optionLabelProp = props.optionLabelProp; var multiple = mode === 'multiple' || mode === 'tags'; var mergedShowSearch = showSearch !== undefined ? showSearch : multiple || mode === 'combobox'; var mergedOptions = options || convertChildrenToData(children); // `tags` should not set option as disabled Object(warning["a" /* default */])(mode !== 'tags' || mergedOptions.every(function (opt) { return !opt.disabled; }), 'Please avoid setting option to disabled in tags mode since user can always type text as tag.'); // `combobox` & `tags` should option be `string` type if (mode === 'tags' || mode === 'combobox') { var hasNumberValue = mergedOptions.some(function (item) { if (item.options) { return item.options.some(function (opt) { return typeof ('value' in opt ? opt.value : opt.key) === 'number'; }); } return typeof ('value' in item ? item.value : item.key) === 'number'; }); Object(warning["a" /* default */])(!hasNumberValue, '`value` of Option should not use number type when `mode` is `tags` or `combobox`.'); } // `combobox` should not use `optionLabelProp` Object(warning["a" /* default */])(mode !== 'combobox' || !optionLabelProp, '`combobox` mode not support `optionLabelProp`. Please set `value` on Option directly.'); // Only `combobox` support `backfill` Object(warning["a" /* default */])(mode === 'combobox' || !backfill, '`backfill` only works with `combobox` mode.'); // Only `combobox` support `getInputElement` Object(warning["a" /* default */])(mode === 'combobox' || !getInputElement, '`getInputElement` only work with `combobox` mode.'); // Customize `getInputElement` should not use `allowClear` & `placeholder` Object(warning["b" /* noteOnce */])(mode !== 'combobox' || !getInputElement || !allowClear || !placeholder, 'Customize `getInputElement` should customize clear and placeholder logic instead of configuring `allowClear` and `placeholder`.'); // `onSearch` should use in `combobox` or `showSearch` if (onSearch && !mergedShowSearch && mode !== 'combobox' && mode !== 'tags') { Object(warning["a" /* default */])(false, '`onSearch` should work with `showSearch` instead of use alone.'); } Object(warning["b" /* noteOnce */])(!defaultOpen || autoFocus, '`defaultOpen` makes Select open without focus which means it will not close by click outside. You can set `autoFocus` if needed.'); if (value !== undefined && value !== null) { var values = Object(commonUtil["d" /* toArray */])(value); Object(warning["a" /* default */])(!labelInValue || values.every(function (val) { return Object(esm_typeof["a" /* default */])(val) === 'object' && ('key' in val || 'value' in val); }), '`value` should in shape of `{ value: string | number, label?: ReactNode }` when you set `labelInValue` to `true`'); Object(warning["a" /* default */])(!multiple || Array.isArray(value), '`value` should be array when `mode` is `multiple` or `tags`'); } // Syntactic sugar should use correct children type if (children) { var invalidateChildType = null; Object(toArray["a" /* default */])(children).some(function (node) { if (!external_window_React_["isValidElement"](node) || !node.type) { return false; } var type = node.type; if (type.isSelectOption) { return false; } if (type.isSelectOptGroup) { var allChildrenValid = Object(toArray["a" /* default */])(node.props.children).every(function (subNode) { if (!external_window_React_["isValidElement"](subNode) || !node.type || subNode.type.isSelectOption) { return true; } invalidateChildType = subNode.type; return false; }); if (allChildrenValid) { return false; } return true; } invalidateChildType = type; return true; }); if (invalidateChildType) { Object(warning["a" /* default */])(false, "`children` should be `Select.Option` or `Select.OptGroup` instead of `".concat(invalidateChildType.displayName || invalidateChildType.name || invalidateChildType, "`.")); } Object(warning["a" /* default */])(inputValue === undefined, '`inputValue` is deprecated, please use `searchValue` instead.'); } } /* harmony default export */ var warningPropsUtil = (warningProps); // CONCATENATED MODULE: ./node_modules/rc-select/es/Select.js /** * To match accessibility requirement, we always provide an input in the component. * Other element will not set `tabIndex` to avoid `onBlur` sequence problem. * For focused select, we set `aria-live="polite"` to update the accessibility content. * * ref: * - keyboard: https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/listbox_role#Keyboard_interactions * * New api: * - listHeight * - listItemHeight * - component * * Remove deprecated api: * - multiple * - tags * - combobox * - firstActiveValue * - dropdownMenuStyle * - openClassName (Not list in api) * * Update: * - `backfill` only support `combobox` mode * - `combobox` mode not support `labelInValue` since it's meaningless * - `getInputElement` only support `combobox` mode * - `onChange` return OptionData instead of ReactNode * - `filterOption` `onChange` `onSelect` accept OptionData instead of ReactNode * - `combobox` mode trigger `onChange` will get `undefined` if no `value` match in Option * - `combobox` mode not support `optionLabelProp` */ var RefSelect = Object(generate["a" /* default */])({ prefixCls: 'rc-select', components: { optionList: es_OptionList }, convertChildrenToData: convertChildrenToData, flattenOptions: valueUtil["d" /* flattenOptions */], getLabeledValue: valueUtil["e" /* getLabeledValue */], filterOptions: valueUtil["b" /* filterOptions */], isValueDisabled: valueUtil["g" /* isValueDisabled */], findValueOption: valueUtil["c" /* findValueOption */], warningProps: warningPropsUtil, fillOptionsWithMissingValue: valueUtil["a" /* fillOptionsWithMissingValue */] }); /** * Typescript not support generic with function component, * we have to wrap an class component to handle this. */ var Select_Select = /*#__PURE__*/function (_React$Component) { Object(inherits["a" /* default */])(Select, _React$Component); var _super = Object(createSuper["a" /* default */])(Select); function Select() { var _this; Object(classCallCheck["a" /* default */])(this, Select); _this = _super.apply(this, arguments); _this.selectRef = external_window_React_["createRef"](); _this.focus = function () { _this.selectRef.current.focus(); }; _this.blur = function () { _this.selectRef.current.blur(); }; return _this; } Object(createClass["a" /* default */])(Select, [{ key: "render", value: function render() { return external_window_React_["createElement"](RefSelect, Object.assign({ ref: this.selectRef }, this.props)); } }]); return Select; }(external_window_React_["Component"]); Select_Select.Option = es_Option; Select_Select.OptGroup = es_OptGroup; /* harmony default export */ var es_Select = (Select_Select); // CONCATENATED MODULE: ./node_modules/rc-select/es/index.js /* harmony default export */ var rc_select_es = __webpack_exports__["c"] = (es_Select); /***/ }), /***/ "NvD2": /*!******************************************************!*\ !*** ./node_modules/rc-tree/es/utils/conductUtil.js ***! \******************************************************/ /*! exports provided: isCheckDisabled, conductCheck */ /*! exports used: conductCheck */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* unused harmony export isCheckDisabled */ /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return conductCheck; }); /* harmony import */ var rc_util_es_warning__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rc-util/es/warning */ "Kwbf"); function removeFromCheckedKeys(halfCheckedKeys, checkedKeys) { var filteredKeys = new Set(); halfCheckedKeys.forEach(function (key) { if (!checkedKeys.has(key)) { filteredKeys.add(key); } }); return filteredKeys; } function isCheckDisabled(node) { var _ref = node || {}, disabled = _ref.disabled, disableCheckbox = _ref.disableCheckbox, checkable = _ref.checkable; return !!(disabled || disableCheckbox) || checkable === false; } // Fill miss keys function fillConductCheck(keys, levelEntities, maxLevel, syntheticGetCheckDisabled) { var checkedKeys = new Set(keys); var halfCheckedKeys = new Set(); // Add checked keys top to bottom for (var level = 0; level <= maxLevel; level += 1) { var entities = levelEntities.get(level) || new Set(); entities.forEach(function (entity) { var key = entity.key, node = entity.node, _entity$children = entity.children, children = _entity$children === void 0 ? [] : _entity$children; if (checkedKeys.has(key) && !syntheticGetCheckDisabled(node)) { children.filter(function (childEntity) { return !syntheticGetCheckDisabled(childEntity.node); }).forEach(function (childEntity) { checkedKeys.add(childEntity.key); }); } }); } // Add checked keys from bottom to top var visitedKeys = new Set(); for (var _level = maxLevel; _level >= 0; _level -= 1) { var _entities = levelEntities.get(_level) || new Set(); _entities.forEach(function (entity) { var parent = entity.parent, node = entity.node; // Skip if no need to check if (syntheticGetCheckDisabled(node) || !entity.parent || visitedKeys.has(entity.parent.key)) { return; } // Skip if parent is disabled if (syntheticGetCheckDisabled(entity.parent.node)) { visitedKeys.add(parent.key); return; } var allChecked = true; var partialChecked = false; (parent.children || []).filter(function (childEntity) { return !syntheticGetCheckDisabled(childEntity.node); }).forEach(function (_ref2) { var key = _ref2.key; var checked = checkedKeys.has(key); if (allChecked && !checked) { allChecked = false; } if (!partialChecked && (checked || halfCheckedKeys.has(key))) { partialChecked = true; } }); if (allChecked) { checkedKeys.add(parent.key); } if (partialChecked) { halfCheckedKeys.add(parent.key); } visitedKeys.add(parent.key); }); } return { checkedKeys: Array.from(checkedKeys), halfCheckedKeys: Array.from(removeFromCheckedKeys(halfCheckedKeys, checkedKeys)) }; } // Remove useless key function cleanConductCheck(keys, halfKeys, levelEntities, maxLevel, syntheticGetCheckDisabled) { var checkedKeys = new Set(keys); var halfCheckedKeys = new Set(halfKeys); // Remove checked keys from top to bottom for (var level = 0; level <= maxLevel; level += 1) { var entities = levelEntities.get(level) || new Set(); entities.forEach(function (entity) { var key = entity.key, node = entity.node, _entity$children2 = entity.children, children = _entity$children2 === void 0 ? [] : _entity$children2; if (!checkedKeys.has(key) && !halfCheckedKeys.has(key) && !syntheticGetCheckDisabled(node)) { children.filter(function (childEntity) { return !syntheticGetCheckDisabled(childEntity.node); }).forEach(function (childEntity) { checkedKeys.delete(childEntity.key); }); } }); } // Remove checked keys form bottom to top halfCheckedKeys = new Set(); var visitedKeys = new Set(); for (var _level2 = maxLevel; _level2 >= 0; _level2 -= 1) { var _entities2 = levelEntities.get(_level2) || new Set(); _entities2.forEach(function (entity) { var parent = entity.parent, node = entity.node; // Skip if no need to check if (syntheticGetCheckDisabled(node) || !entity.parent || visitedKeys.has(entity.parent.key)) { return; } // Skip if parent is disabled if (syntheticGetCheckDisabled(entity.parent.node)) { visitedKeys.add(parent.key); return; } var allChecked = true; var partialChecked = false; (parent.children || []).filter(function (childEntity) { return !syntheticGetCheckDisabled(childEntity.node); }).forEach(function (_ref3) { var key = _ref3.key; var checked = checkedKeys.has(key); if (allChecked && !checked) { allChecked = false; } if (!partialChecked && (checked || halfCheckedKeys.has(key))) { partialChecked = true; } }); if (!allChecked) { checkedKeys.delete(parent.key); } if (partialChecked) { halfCheckedKeys.add(parent.key); } visitedKeys.add(parent.key); }); } return { checkedKeys: Array.from(checkedKeys), halfCheckedKeys: Array.from(removeFromCheckedKeys(halfCheckedKeys, checkedKeys)) }; } /** * Conduct with keys. * @param keyList current key list * @param keyEntities key - dataEntity map * @param mode `fill` to fill missing key, `clean` to remove useless key */ function conductCheck(keyList, checked, keyEntities, getCheckDisabled) { var warningMissKeys = []; var syntheticGetCheckDisabled; if (getCheckDisabled) { syntheticGetCheckDisabled = getCheckDisabled; } else { syntheticGetCheckDisabled = isCheckDisabled; } // We only handle exist keys var keys = new Set(keyList.filter(function (key) { var hasEntity = !!keyEntities[key]; if (!hasEntity) { warningMissKeys.push(key); } return hasEntity; })); var levelEntities = new Map(); var maxLevel = 0; // Convert entities by level for calculation Object.keys(keyEntities).forEach(function (key) { var entity = keyEntities[key]; var level = entity.level; var levelSet = levelEntities.get(level); if (!levelSet) { levelSet = new Set(); levelEntities.set(level, levelSet); } levelSet.add(entity); maxLevel = Math.max(maxLevel, level); }); Object(rc_util_es_warning__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])(!warningMissKeys.length, "Tree missing follow keys: ".concat(warningMissKeys.slice(0, 100).map(function (key) { return "'".concat(key, "'"); }).join(', '))); var result; if (checked === true) { result = fillConductCheck(keys, levelEntities, maxLevel, syntheticGetCheckDisabled); } else { result = cleanConductCheck(keys, checked.halfCheckedKeys, levelEntities, maxLevel, syntheticGetCheckDisabled); } return result; } /***/ }), /***/ "OZM5": /*!*****************************************!*\ !*** ./node_modules/rc-tree/es/util.js ***! \*****************************************/ /*! exports provided: arrDel, arrAdd, posToArr, getPosition, isTreeNode, getDragNodesKeys, calcDropPosition, calcSelectedKeys, convertDataToTree, parseCheckedKeys, conductExpandParent, getDataAndAria */ /*! exports used: arrAdd, arrDel, calcDropPosition, calcSelectedKeys, conductExpandParent, getDataAndAria, getDragNodesKeys, getPosition, isTreeNode, parseCheckedKeys, posToArr */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return arrDel; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return arrAdd; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return posToArr; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return getPosition; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return isTreeNode; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return getDragNodesKeys; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return calcDropPosition; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return calcSelectedKeys; }); /* unused harmony export convertDataToTree */ /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return parseCheckedKeys; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return conductExpandParent; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return getDataAndAria; }); /* harmony import */ var _babel_runtime_helpers_esm_toConsumableArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/esm/toConsumableArray */ "KQm4"); /* harmony import */ var _babel_runtime_helpers_esm_typeof__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/esm/typeof */ "U8pU"); /* harmony import */ var _babel_runtime_helpers_esm_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/esm/objectWithoutProperties */ "Ff2n"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! react */ "cDcd"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_3__); /* harmony import */ var rc_util_es_warning__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! rc-util/es/warning */ "Kwbf"); /* harmony import */ var _TreeNode__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./TreeNode */ "WaYH"); /** * Legacy code. Should avoid to use if you are new to import these code. */ var DRAG_SIDE_RANGE = 0.25; var DRAG_MIN_GAP = 2; function arrDel(list, value) { var clone = list.slice(); var index = clone.indexOf(value); if (index >= 0) { clone.splice(index, 1); } return clone; } function arrAdd(list, value) { var clone = list.slice(); if (clone.indexOf(value) === -1) { clone.push(value); } return clone; } function posToArr(pos) { return pos.split('-'); } function getPosition(level, index) { return "".concat(level, "-").concat(index); } function isTreeNode(node) { return node && node.type && node.type.isTreeNode; } function getDragNodesKeys(dragNodeKey, keyEntities) { var dragNodesKeys = [dragNodeKey]; var entity = keyEntities[dragNodeKey]; function dig() { var list = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; list.forEach(function (_ref) { var key = _ref.key, children = _ref.children; dragNodesKeys.push(key); dig(children); }); } dig(entity.children); return dragNodesKeys; } // Only used when drag, not affect SSR. function calcDropPosition(event, treeNode) { var clientY = event.clientY; var _treeNode$selectHandl = treeNode.selectHandle.getBoundingClientRect(), top = _treeNode$selectHandl.top, bottom = _treeNode$selectHandl.bottom, height = _treeNode$selectHandl.height; var des = Math.max(height * DRAG_SIDE_RANGE, DRAG_MIN_GAP); if (clientY <= top + des) { return -1; } if (clientY >= bottom - des) { return 1; } return 0; } /** * Return selectedKeys according with multiple prop * @param selectedKeys * @param props * @returns [string] */ function calcSelectedKeys(selectedKeys, props) { if (!selectedKeys) return undefined; var multiple = props.multiple; if (multiple) { return selectedKeys.slice(); } if (selectedKeys.length) { return [selectedKeys[0]]; } return selectedKeys; } var internalProcessProps = function internalProcessProps(props) { return props; }; function convertDataToTree(treeData, processor) { if (!treeData) return []; var _ref2 = processor || {}, _ref2$processProps = _ref2.processProps, processProps = _ref2$processProps === void 0 ? internalProcessProps : _ref2$processProps; var list = Array.isArray(treeData) ? treeData : [treeData]; return list.map(function (_ref3) { var children = _ref3.children, props = Object(_babel_runtime_helpers_esm_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"])(_ref3, ["children"]); var childrenNodes = convertDataToTree(children, processor); return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(_TreeNode__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"], Object.assign({}, processProps(props)), childrenNodes); }); } /** * Parse `checkedKeys` to { checkedKeys, halfCheckedKeys } style */ function parseCheckedKeys(keys) { if (!keys) { return null; } // Convert keys to object format var keyProps; if (Array.isArray(keys)) { // [Legacy] Follow the api doc keyProps = { checkedKeys: keys, halfCheckedKeys: undefined }; } else if (Object(_babel_runtime_helpers_esm_typeof__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"])(keys) === 'object') { keyProps = { checkedKeys: keys.checked || undefined, halfCheckedKeys: keys.halfChecked || undefined }; } else { Object(rc_util_es_warning__WEBPACK_IMPORTED_MODULE_4__[/* default */ "a"])(false, '`checkedKeys` is not an array or an object'); return null; } return keyProps; } /** * If user use `autoExpandParent` we should get the list of parent node * @param keyList * @param keyEntities */ function conductExpandParent(keyList, keyEntities) { var expandedKeys = new Set(); function conductUp(key) { if (expandedKeys.has(key)) return; var entity = keyEntities[key]; if (!entity) return; expandedKeys.add(key); var parent = entity.parent, node = entity.node; if (node.disabled) return; if (parent) { conductUp(parent.key); } } (keyList || []).forEach(function (key) { conductUp(key); }); return Object(_babel_runtime_helpers_esm_toConsumableArray__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])(expandedKeys); } /** * Returns only the data- and aria- key/value pairs */ function getDataAndAria(props) { var omitProps = {}; Object.keys(props).forEach(function (key) { if (key.startsWith('data-') || key.startsWith('aria-')) { omitProps[key] = props[key]; } }); return omitProps; } /***/ }), /***/ "P/tu": /*!*********************************************!*\ !*** ./src/components/CustomTree/index.tsx ***! \*********************************************/ /*! exports provided: default */ /*! exports used: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var antd_es_tree_style__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! antd/es/tree/style */ "ozfa"); /* harmony import */ var antd_es_tree__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! antd/es/tree */ "MJZm"); /* harmony import */ var _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/extends */ "0Owb"); /* harmony import */ var _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_asyncToGenerator__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/asyncToGenerator */ "9og8"); /* harmony import */ var _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/slicedToArray */ "tJVT"); /* harmony import */ var _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties */ "PpiC"); /* harmony import */ var _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/regenerator */ "WmNS"); /* harmony import */ var _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_6__); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! react */ "cDcd"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_7__); /* harmony import */ var _service_problemset__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/service/problemset */ "WCUW"); /* harmony import */ var _index_less_modules__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./index.less?modules */ "spXi"); /* harmony import */ var _index_less_modules__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_index_less_modules__WEBPACK_IMPORTED_MODULE_9__); var CustomTree = function CustomTree(_ref) { var value = _ref.value, onChange = _ref.onChange, defaultValue = _ref.defaultValue, disabled = _ref.disabled, props = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"])(_ref, ["value", "onChange", "defaultValue", "disabled"]); var _useState = Object(react__WEBPACK_IMPORTED_MODULE_7__["useState"])([]), _useState2 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_4__[/* default */ "a"])(_useState, 2), treeData = _useState2[0], setTreeData = _useState2[1]; var _useState3 = Object(react__WEBPACK_IMPORTED_MODULE_7__["useState"])('1'), _useState4 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_4__[/* default */ "a"])(_useState3, 2), keyIndex = _useState4[0], setKeyIndex = _useState4[1]; // const sign = useRef(true) Object(react__WEBPACK_IMPORTED_MODULE_7__["useEffect"])(function () { getData(); }, []); var getData = /*#__PURE__*/function () { var _ref2 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_asyncToGenerator__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"])( /*#__PURE__*/_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_6___default.a.mark(function _callee() { var res, item; return _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_6___default.a.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return Object(_service_problemset__WEBPACK_IMPORTED_MODULE_8__[/* getPaperList */ "A"])({}); case 2: res = _context.sent; if (res !== null && res !== void 0 && res.data) { item = [{ title: /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("div", { title: '根目录', className: _index_less_modules__WEBPACK_IMPORTED_MODULE_9___default.a.name }, "\u6839\u76EE\u5F55"), value: 0, key: 0, icon: /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("i", { className: "iconfont icon-wenjianjia2 c-light-primary mr10", style: { lineHeight: '19px' } }), children: transformTreeKey(res.data || []) }]; setTreeData(item); setKeyIndex('2'); } case 4: case "end": return _context.stop(); } } }, _callee); })); return function getData() { return _ref2.apply(this, arguments); }; }(); var transformTreeKey = function transformTreeKey(items) { function mapTree(org) { var realChildren = org.children; var haveChildren = Array.isArray(realChildren) && realChildren.length > 0; var key = org === null || org === void 0 ? void 0 : org.group_id; return { //分别将我们查询出来的值做出改变他的key title: /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("div", { title: org === null || org === void 0 ? void 0 : org.name, className: _index_less_modules__WEBPACK_IMPORTED_MODULE_9___default.a.name }, org === null || org === void 0 ? void 0 : org.name), value: key, key: key, icon: /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("i", { className: "iconfont icon-wenjianjia2 c-light-primary mr10", style: { lineHeight: '19px' } }), //判断它是否存在子集,若果存在就进行再次进行遍历操作,知道不存在子集便对其他的元素进行操作 children: haveChildren ? realChildren === null || realChildren === void 0 ? void 0 : realChildren.map(function (e) { return mapTree(e); }) : [] }; } return items === null || items === void 0 ? void 0 : items.map(function (org) { return mapTree(org); }); }; var param = defaultValue ? { defaultExpandedKeys: [0] } : { selectedKeys: value, defaultExpandedKeys: value }; return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_9___default.a.customTree }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement(antd_es_tree__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"], Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"])({ key: keyIndex }, param, { showIcon: true, treeData: treeData, onSelect: onChange, disabled: disabled }, props))); }; /* harmony default export */ __webpack_exports__["a"] = (CustomTree); /***/ }), /***/ "Q0Vu": /*!**********************************************************!*\ !*** ./src/components/LanguageSelect/index.less?modules ***! \**********************************************************/ /*! no static exports found */ /*! exports used: default */ /*! ModuleConcatenation bailout: Module is not an ECMAScript module */ /***/ (function(module, exports, __webpack_require__) { // extracted by mini-css-extract-plugin module.exports = {"flex_box_center":"flex_box_center___3fHaw","flex_space_between":"flex_space_between___1tu3K","flex_box_vertical_center":"flex_box_vertical_center___3kmTT","flex_box_center_end":"flex_box_center_end___19OcD","flex_box_column":"flex_box_column___1aMoy","main":"main___JkLSb","wrap":"wrap___1k_Ib","content":"content___1by-P","programName":"programName___1mMSD","name":"name___2mlTd","directionContentWrap":"directionContentWrap___3qsxQ","directionItem":"directionItem___2aAvu","active":"active___ACZqb","subActive":"subActive___2RkoB","subItem":"subItem___3tJgX","subMenu":"subMenu___Y_7S_","action":"action___xqgFs"}; /***/ }), /***/ "SAoR": /*!**********************************************************!*\ !*** ./src/pages/Problemset/components/Crumbs/index.tsx ***! \**********************************************************/ /*! exports provided: default */ /*! exports used: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var antd_es_popover_style__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! antd/es/popover/style */ "Q9mQ"); /* harmony import */ var antd_es_popover__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! antd/es/popover */ "diRs"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react */ "cDcd"); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_2__); /* harmony import */ var _index_less_modules__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./index.less?modules */ "+z73"); /* harmony import */ var _index_less_modules__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_index_less_modules__WEBPACK_IMPORTED_MODULE_3__); var Crumbs = function Crumbs(_ref) { var _ref$data = _ref.data, data = _ref$data === void 0 ? [] : _ref$data, _onClick = _ref.onClick; // const [value, setValue] = useState(''); var renderFew = function renderFew() { return data.map(function (e, i) { return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("div", { key: i, className: _index_less_modules__WEBPACK_IMPORTED_MODULE_3___default.a.few }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("b", { title: e.name, style: { color: i === 0 ? '#333333' : '#999999' }, onClick: function onClick() { return _onClick(e.id); } }, e.name), i < data.length - 1 && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("span", null, "/")); }); }; var renderMuch = function renderMuch() { var bool = true; var items = data.slice(2, -2); var content = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("div", { className: _index_less_modules__WEBPACK_IMPORTED_MODULE_3___default.a.pWrap }, items.map(function (e) { return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("span", { title: e.name, onClick: function onClick() { return _onClick(e.id); }, key: e.id }, e.name); })); return data.map(function (e, i) { var dom = null; if (i > 1 && i < data.length - 2) { if (bool) { dom = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(antd_es_popover__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"], { key: i, placement: "bottom", content: content }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("span", { style: { color: "#999", cursor: 'pointer' } }, ".../")); bool = false; } } else { dom = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("div", { key: i, className: _index_less_modules__WEBPACK_IMPORTED_MODULE_3___default.a.few }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("b", { title: e.name, style: { color: i === 0 ? '#333333' : '#999999' }, onClick: function onClick() { return _onClick(e.id); } }, e.name), i < data.length - 1 && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("span", null, "/")); } return dom; }); }; return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("aside", { style: { overflowX: 'auto' } }, (data === null || data === void 0 ? void 0 : data.length) > 5 ? renderMuch() : renderFew()); }; /* harmony default export */ __webpack_exports__["a"] = (Crumbs); /***/ }), /***/ "SJMd": /*!****************************************************!*\ !*** ./node_modules/code-prettify/src/prettify.js ***! \****************************************************/ /*! no static exports found */ /*! ModuleConcatenation bailout: Module is not an ECMAScript module */ /***/ (function(module, exports) { /** * @license * Copyright (C) 2006 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview * some functions for browser-side pretty printing of code contained in html. * *

    * For a fairly comprehensive set of languages see the * README * file that came with this source. At a minimum, the lexer should work on a * number of languages including C and friends, Java, Python, Bash, SQL, HTML, * XML, CSS, Javascript, and Makefiles. It works passably on Ruby, PHP and Awk * and a subset of Perl, but, because of commenting conventions, doesn't work on * Smalltalk, Lisp-like, or CAML-like languages without an explicit lang class. *

    * Usage:

      *
    1. include this source file in an html page via * {@code } *
    2. define style rules. See the example page for examples. *
    3. mark the {@code
      } and {@code } tags in your source with
       *    {@code class=prettyprint.}
       *    You can also use the (html deprecated) {@code } tag, but the pretty
       *    printer needs to do more substantial DOM manipulations to support that, so
       *    some css styles may not be preserved.
       * </ol>
       * That's it.  I wanted to keep the API as simple as possible, so there's no
       * need to specify which language the code is in, but if you wish, you can add
       * another class to the {@code <pre>} or {@code <code>} element to specify the
       * language, as in {@code <pre class="prettyprint lang-java">}.  Any class that
       * starts with "lang-" followed by a file extension, specifies the file type.
       * See the "lang-*.js" files in this directory for code that implements
       * per-language file handlers.
       * <p>
       * Change log:<br>
       * cbeust, 2006/08/22
       * <blockquote>
       *   Java annotations (start with "@") are now captured as literals ("lit")
       * </blockquote>
       * @requires console
       */
      
      // JSLint declarations
      /*global console, document, navigator, setTimeout, window, define */
      
      
      /**
      * @typedef {!Array.<number|string>}
      * Alternating indices and the decorations that should be inserted there.
      * The indices are monotonically increasing.
      */
      var DecorationsT;
      
      /**
      * @typedef {!{
      *   sourceNode: !Element,
      *   pre: !(number|boolean),
      *   langExtension: ?string,
      *   numberLines: ?(number|boolean),
      *   sourceCode: ?string,
      *   spans: ?(Array.<number|Node>),
      *   basePos: ?number,
      *   decorations: ?DecorationsT
      * }}
      * <dl>
      *  <dt>sourceNode<dd>the element containing the source
      *  <dt>sourceCode<dd>source as plain text
      *  <dt>pre<dd>truthy if white-space in text nodes
      *     should be considered significant.
      *  <dt>spans<dd> alternating span start indices into source
      *     and the text node or element (e.g. {@code <BR>}) corresponding to that
      *     span.
      *  <dt>decorations<dd>an array of style classes preceded
      *     by the position at which they start in job.sourceCode in order
      *  <dt>basePos<dd>integer position of this.sourceCode in the larger chunk of
      *     source.
      * </dl>
      */
      var JobT;
      
      /**
      * @typedef {!{
      *   sourceCode: string,
      *   spans: !(Array.<number|Node>)
      * }}
      * <dl>
      *  <dt>sourceCode<dd>source as plain text
      *  <dt>spans<dd> alternating span start indices into source
      *     and the text node or element (e.g. {@code <BR>}) corresponding to that
      *     span.
      * </dl>
      */
      var SourceSpansT;
      
      /** @define {boolean} */
      var IN_GLOBAL_SCOPE = false;
      
      var HACK_TO_FIX_JS_INCLUDE_PL;
      
      /**
       * {@type !{
       *   'createSimpleLexer': function (Array, Array): (function (JobT)),
       *   'registerLangHandler': function (function (JobT), Array.<string>),
       *   'PR_ATTRIB_NAME': string,
       *   'PR_ATTRIB_NAME': string,
       *   'PR_ATTRIB_VALUE': string,
       *   'PR_COMMENT': string,
       *   'PR_DECLARATION': string,
       *   'PR_KEYWORD': string,
       *   'PR_LITERAL': string,
       *   'PR_NOCODE': string,
       *   'PR_PLAIN': string,
       *   'PR_PUNCTUATION': string,
       *   'PR_SOURCE': string,
       *   'PR_STRING': string,
       *   'PR_TAG': string,
       *   'PR_TYPE': string,
       *   'prettyPrintOne': function (string, string, number|boolean),
       *   'prettyPrint': function (?function, ?(HTMLElement|HTMLDocument))
       * }}
       * @const
       */
      var PR;
      
      /**
       * Split {@code prettyPrint} into multiple timeouts so as not to interfere with
       * UI events.
       * If set to {@code false}, {@code prettyPrint()} is synchronous.
       */
      window['PR_SHOULD_USE_CONTINUATION'] = true;
      
      /**
       * Pretty print a chunk of code.
       * @param {string} sourceCodeHtml The HTML to pretty print.
       * @param {string} opt_langExtension The language name to use.
       *     Typically, a filename extension like 'cpp' or 'java'.
       * @param {number|boolean} opt_numberLines True to number lines,
       *     or the 1-indexed number of the first line in sourceCodeHtml.
       * @return {string} code as html, but prettier
       */
      var prettyPrintOne;
      /**
       * Find all the {@code <pre>} and {@code <code>} tags in the DOM with
       * {@code class=prettyprint} and prettify them.
       *
       * @param {Function} opt_whenDone called when prettifying is done.
       * @param {HTMLElement|HTMLDocument} opt_root an element or document
       *   containing all the elements to pretty print.
       *   Defaults to {@code document.body}.
       */
      var prettyPrint;
      
      
      (function () {
        var win = window;
        // Keyword lists for various languages.
        // We use things that coerce to strings to make them compact when minified
        // and to defeat aggressive optimizers that fold large string constants.
        var FLOW_CONTROL_KEYWORDS = ["break,continue,do,else,for,if,return,while"];
        var C_KEYWORDS = [FLOW_CONTROL_KEYWORDS,"auto,case,char,const,default," +
            "double,enum,extern,float,goto,inline,int,long,register,restrict,short,signed," +
            "sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"];
        var COMMON_KEYWORDS = [C_KEYWORDS,"catch,class,delete,false,import," +
            "new,operator,private,protected,public,this,throw,true,try,typeof"];
        var CPP_KEYWORDS = [COMMON_KEYWORDS,"alignas,alignof,align_union,asm,axiom,bool," +
            "concept,concept_map,const_cast,constexpr,decltype,delegate," +
            "dynamic_cast,explicit,export,friend,generic,late_check," +
            "mutable,namespace,noexcept,noreturn,nullptr,property,reinterpret_cast,static_assert," +
            "static_cast,template,typeid,typename,using,virtual,where"];
        var JAVA_KEYWORDS = [COMMON_KEYWORDS,
            "abstract,assert,boolean,byte,extends,finally,final,implements,import," +
            "instanceof,interface,null,native,package,strictfp,super,synchronized," +
            "throws,transient"];
        var CSHARP_KEYWORDS = [COMMON_KEYWORDS,
            "abstract,add,alias,as,ascending,async,await,base,bool,by,byte,checked,decimal,delegate,descending," +
            "dynamic,event,finally,fixed,foreach,from,get,global,group,implicit,in,interface," +
            "internal,into,is,join,let,lock,null,object,out,override,orderby,params," +
            "partial,readonly,ref,remove,sbyte,sealed,select,set,stackalloc,string,select,uint,ulong," +
            "unchecked,unsafe,ushort,value,var,virtual,where,yield"];
        var COFFEE_KEYWORDS = "all,and,by,catch,class,else,extends,false,finally," +
            "for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then," +
            "throw,true,try,unless,until,when,while,yes";
        var JSCRIPT_KEYWORDS = [COMMON_KEYWORDS,
            "abstract,async,await,constructor,debugger,enum,eval,export,function," +
            "get,implements,instanceof,interface,let,null,set,undefined,var,with," +
            "yield,Infinity,NaN"];
        var PERL_KEYWORDS = "caller,delete,die,do,dump,elsif,eval,exit,foreach,for," +
            "goto,if,import,last,local,my,next,no,our,print,package,redo,require," +
            "sub,undef,unless,until,use,wantarray,while,BEGIN,END";
        var PYTHON_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "and,as,assert,class,def,del," +
            "elif,except,exec,finally,from,global,import,in,is,lambda," +
            "nonlocal,not,or,pass,print,raise,try,with,yield," +
            "False,True,None"];
        var RUBY_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "alias,and,begin,case,class," +
            "def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo," +
            "rescue,retry,self,super,then,true,undef,unless,until,when,yield," +
            "BEGIN,END"];
        var SH_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "case,done,elif,esac,eval,fi," +
            "function,in,local,set,then,until"];
        var ALL_KEYWORDS = [
            CPP_KEYWORDS, CSHARP_KEYWORDS, JAVA_KEYWORDS, JSCRIPT_KEYWORDS,
            PERL_KEYWORDS, PYTHON_KEYWORDS, RUBY_KEYWORDS, SH_KEYWORDS];
        var C_TYPES = /^(DIR|FILE|array|vector|(de|priority_)?queue|(forward_)?list|stack|(const_)?(reverse_)?iterator|(unordered_)?(multi)?(set|map)|bitset|u?(int|float)\d*)\b/;
      
        // token style names.  correspond to css classes
        /**
         * token style for a string literal
         * @const
         */
        var PR_STRING = 'str';
        /**
         * token style for a keyword
         * @const
         */
        var PR_KEYWORD = 'kwd';
        /**
         * token style for a comment
         * @const
         */
        var PR_COMMENT = 'com';
        /**
         * token style for a type
         * @const
         */
        var PR_TYPE = 'typ';
        /**
         * token style for a literal value.  e.g. 1, null, true.
         * @const
         */
        var PR_LITERAL = 'lit';
        /**
         * token style for a punctuation string.
         * @const
         */
        var PR_PUNCTUATION = 'pun';
        /**
         * token style for plain text.
         * @const
         */
        var PR_PLAIN = 'pln';
      
        /**
         * token style for an sgml tag.
         * @const
         */
        var PR_TAG = 'tag';
        /**
         * token style for a markup declaration such as a DOCTYPE.
         * @const
         */
        var PR_DECLARATION = 'dec';
        /**
         * token style for embedded source.
         * @const
         */
        var PR_SOURCE = 'src';
        /**
         * token style for an sgml attribute name.
         * @const
         */
        var PR_ATTRIB_NAME = 'atn';
        /**
         * token style for an sgml attribute value.
         * @const
         */
        var PR_ATTRIB_VALUE = 'atv';
      
        /**
         * A class that indicates a section of markup that is not code, e.g. to allow
         * embedding of line numbers within code listings.
         * @const
         */
        var PR_NOCODE = 'nocode';
      
        
        
        /**
         * A set of tokens that can precede a regular expression literal in
         * javascript
         * http://web.archive.org/web/20070717142515/http://www.mozilla.org/js/language/js20/rationale/syntax.html
         * has the full list, but I've removed ones that might be problematic when
         * seen in languages that don't support regular expression literals.
         *
         * <p>Specifically, I've removed any keywords that can't precede a regexp
         * literal in a syntactically legal javascript program, and I've removed the
         * "in" keyword since it's not a keyword in many languages, and might be used
         * as a count of inches.
         *
         * <p>The link above does not accurately describe EcmaScript rules since
         * it fails to distinguish between (a=++/b/i) and (a++/b/i) but it works
         * very well in practice.
         *
         * @private
         * @const
         */
        var REGEXP_PRECEDER_PATTERN = '(?:^^\\.?|[+-]|[!=]=?=?|\\#|%=?|&&?=?|\\(|\\*=?|[+\\-]=|->|\\/=?|::?|<<?=?|>>?>?=?|,|;|\\?|@|\\[|~|{|\\^\\^?=?|\\|\\|?=?|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*';
        
        // CAVEAT: this does not properly handle the case where a regular
        // expression immediately follows another since a regular expression may
        // have flags for case-sensitivity and the like.  Having regexp tokens
        // adjacent is not valid in any language I'm aware of, so I'm punting.
        // TODO: maybe style special characters inside a regexp as punctuation.
      
        /**
         * Given a group of {@link RegExp}s, returns a {@code RegExp} that globally
         * matches the union of the sets of strings matched by the input RegExp.
         * Since it matches globally, if the input strings have a start-of-input
         * anchor (/^.../), it is ignored for the purposes of unioning.
         * @param {Array.<RegExp>} regexs non multiline, non-global regexs.
         * @return {RegExp} a global regex.
         */
        function combinePrefixPatterns(regexs) {
          var capturedGroupIndex = 0;
        
          var needToFoldCase = false;
          var ignoreCase = false;
          for (var i = 0, n = regexs.length; i < n; ++i) {
            var regex = regexs[i];
            if (regex.ignoreCase) {
              ignoreCase = true;
            } else if (/[a-z]/i.test(regex.source.replace(
                           /\\u[0-9a-f]{4}|\\x[0-9a-f]{2}|\\[^ux]/gi, ''))) {
              needToFoldCase = true;
              ignoreCase = false;
              break;
            }
          }
        
          var escapeCharToCodeUnit = {
            'b': 8,
            't': 9,
            'n': 0xa,
            'v': 0xb,
            'f': 0xc,
            'r': 0xd
          };
        
          function decodeEscape(charsetPart) {
            var cc0 = charsetPart.charCodeAt(0);
            if (cc0 !== 92 /* \\ */) {
              return cc0;
            }
            var c1 = charsetPart.charAt(1);
            cc0 = escapeCharToCodeUnit[c1];
            if (cc0) {
              return cc0;
            } else if ('0' <= c1 && c1 <= '7') {
              return parseInt(charsetPart.substring(1), 8);
            } else if (c1 === 'u' || c1 === 'x') {
              return parseInt(charsetPart.substring(2), 16);
            } else {
              return charsetPart.charCodeAt(1);
            }
          }
        
          function encodeEscape(charCode) {
            if (charCode < 0x20) {
              return (charCode < 0x10 ? '\\x0' : '\\x') + charCode.toString(16);
            }
            var ch = String.fromCharCode(charCode);
            return (ch === '\\' || ch === '-' || ch === ']' || ch === '^')
                ? "\\" + ch : ch;
          }
        
          function caseFoldCharset(charSet) {
            var charsetParts = charSet.substring(1, charSet.length - 1).match(
                new RegExp(
                    '\\\\u[0-9A-Fa-f]{4}'
                    + '|\\\\x[0-9A-Fa-f]{2}'
                    + '|\\\\[0-3][0-7]{0,2}'
                    + '|\\\\[0-7]{1,2}'
                    + '|\\\\[\\s\\S]'
                    + '|-'
                    + '|[^-\\\\]',
                    'g'));
            var ranges = [];
            var inverse = charsetParts[0] === '^';
        
            var out = ['['];
            if (inverse) { out.push('^'); }
        
            for (var i = inverse ? 1 : 0, n = charsetParts.length; i < n; ++i) {
              var p = charsetParts[i];
              if (/\\[bdsw]/i.test(p)) {  // Don't muck with named groups.
                out.push(p);
              } else {
                var start = decodeEscape(p);
                var end;
                if (i + 2 < n && '-' === charsetParts[i + 1]) {
                  end = decodeEscape(charsetParts[i + 2]);
                  i += 2;
                } else {
                  end = start;
                }
                ranges.push([start, end]);
                // If the range might intersect letters, then expand it.
                // This case handling is too simplistic.
                // It does not deal with non-latin case folding.
                // It works for latin source code identifiers though.
                if (!(end < 65 || start > 122)) {
                  if (!(end < 65 || start > 90)) {
                    ranges.push([Math.max(65, start) | 32, Math.min(end, 90) | 32]);
                  }
                  if (!(end < 97 || start > 122)) {
                    ranges.push([Math.max(97, start) & ~32, Math.min(end, 122) & ~32]);
                  }
                }
              }
            }
        
            // [[1, 10], [3, 4], [8, 12], [14, 14], [16, 16], [17, 17]]
            // -> [[1, 12], [14, 14], [16, 17]]
            ranges.sort(function (a, b) { return (a[0] - b[0]) || (b[1]  - a[1]); });
            var consolidatedRanges = [];
            var lastRange = [];
            for (var i = 0; i < ranges.length; ++i) {
              var range = ranges[i];
              if (range[0] <= lastRange[1] + 1) {
                lastRange[1] = Math.max(lastRange[1], range[1]);
              } else {
                consolidatedRanges.push(lastRange = range);
              }
            }
        
            for (var i = 0; i < consolidatedRanges.length; ++i) {
              var range = consolidatedRanges[i];
              out.push(encodeEscape(range[0]));
              if (range[1] > range[0]) {
                if (range[1] + 1 > range[0]) { out.push('-'); }
                out.push(encodeEscape(range[1]));
              }
            }
            out.push(']');
            return out.join('');
          }
        
          function allowAnywhereFoldCaseAndRenumberGroups(regex) {
            // Split into character sets, escape sequences, punctuation strings
            // like ('(', '(?:', ')', '^'), and runs of characters that do not
            // include any of the above.
            var parts = regex.source.match(
                new RegExp(
                    '(?:'
                    + '\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]'  // a character set
                    + '|\\\\u[A-Fa-f0-9]{4}'  // a unicode escape
                    + '|\\\\x[A-Fa-f0-9]{2}'  // a hex escape
                    + '|\\\\[0-9]+'  // a back-reference or octal escape
                    + '|\\\\[^ux0-9]'  // other escape sequence
                    + '|\\(\\?[:!=]'  // start of a non-capturing group
                    + '|[\\(\\)\\^]'  // start/end of a group, or line start
                    + '|[^\\x5B\\x5C\\(\\)\\^]+'  // run of other characters
                    + ')',
                    'g'));
            var n = parts.length;
        
            // Maps captured group numbers to the number they will occupy in
            // the output or to -1 if that has not been determined, or to
            // undefined if they need not be capturing in the output.
            var capturedGroups = [];
        
            // Walk over and identify back references to build the capturedGroups
            // mapping.
            for (var i = 0, groupIndex = 0; i < n; ++i) {
              var p = parts[i];
              if (p === '(') {
                // groups are 1-indexed, so max group index is count of '('
                ++groupIndex;
              } else if ('\\' === p.charAt(0)) {
                var decimalValue = +p.substring(1);
                if (decimalValue) {
                  if (decimalValue <= groupIndex) {
                    capturedGroups[decimalValue] = -1;
                  } else {
                    // Replace with an unambiguous escape sequence so that
                    // an octal escape sequence does not turn into a backreference
                    // to a capturing group from an earlier regex.
                    parts[i] = encodeEscape(decimalValue);
                  }
                }
              }
            }
        
            // Renumber groups and reduce capturing groups to non-capturing groups
            // where possible.
            for (var i = 1; i < capturedGroups.length; ++i) {
              if (-1 === capturedGroups[i]) {
                capturedGroups[i] = ++capturedGroupIndex;
              }
            }
            for (var i = 0, groupIndex = 0; i < n; ++i) {
              var p = parts[i];
              if (p === '(') {
                ++groupIndex;
                if (!capturedGroups[groupIndex]) {
                  parts[i] = '(?:';
                }
              } else if ('\\' === p.charAt(0)) {
                var decimalValue = +p.substring(1);
                if (decimalValue && decimalValue <= groupIndex) {
                  parts[i] = '\\' + capturedGroups[decimalValue];
                }
              }
            }
        
            // Remove any prefix anchors so that the output will match anywhere.
            // ^^ really does mean an anchored match though.
            for (var i = 0; i < n; ++i) {
              if ('^' === parts[i] && '^' !== parts[i + 1]) { parts[i] = ''; }
            }
        
            // Expand letters to groups to handle mixing of case-sensitive and
            // case-insensitive patterns if necessary.
            if (regex.ignoreCase && needToFoldCase) {
              for (var i = 0; i < n; ++i) {
                var p = parts[i];
                var ch0 = p.charAt(0);
                if (p.length >= 2 && ch0 === '[') {
                  parts[i] = caseFoldCharset(p);
                } else if (ch0 !== '\\') {
                  // TODO: handle letters in numeric escapes.
                  parts[i] = p.replace(
                      /[a-zA-Z]/g,
                      function (ch) {
                        var cc = ch.charCodeAt(0);
                        return '[' + String.fromCharCode(cc & ~32, cc | 32) + ']';
                      });
                }
              }
            }
        
            return parts.join('');
          }
        
          var rewritten = [];
          for (var i = 0, n = regexs.length; i < n; ++i) {
            var regex = regexs[i];
            if (regex.global || regex.multiline) { throw new Error('' + regex); }
            rewritten.push(
                '(?:' + allowAnywhereFoldCaseAndRenumberGroups(regex) + ')');
          }
        
          return new RegExp(rewritten.join('|'), ignoreCase ? 'gi' : 'g');
        }
      
        /**
         * Split markup into a string of source code and an array mapping ranges in
         * that string to the text nodes in which they appear.
         *
         * <p>
         * The HTML DOM structure:</p>
         * <pre>
         * (Element   "p"
         *   (Element "b"
         *     (Text  "print "))       ; #1
         *   (Text    "'Hello '")      ; #2
         *   (Element "br")            ; #3
         *   (Text    "  + 'World';")) ; #4
         * </pre>
         * <p>
         * corresponds to the HTML
         * {@code <p><b>print </b>'Hello '<br>  + 'World';</p>}.</p>
         *
         * <p>
         * It will produce the output:</p>
         * <pre>
         * {
         *   sourceCode: "print 'Hello '\n  + 'World';",
         *   //                     1          2
         *   //           012345678901234 5678901234567
         *   spans: [0, #1, 6, #2, 14, #3, 15, #4]
         * }
         * </pre>
         * <p>
         * where #1 is a reference to the {@code "print "} text node above, and so
         * on for the other text nodes.
         * </p>
         *
         * <p>
         * The {@code} spans array is an array of pairs.  Even elements are the start
         * indices of substrings, and odd elements are the text nodes (or BR elements)
         * that contain the text for those substrings.
         * Substrings continue until the next index or the end of the source.
         * </p>
         *
         * @param {Node} node an HTML DOM subtree containing source-code.
         * @param {boolean|number} isPreformatted truthy if white-space in
         *    text nodes should be considered significant.
         * @return {SourceSpansT} source code and the nodes in which they occur.
         */
        function extractSourceSpans(node, isPreformatted) {
          var nocode = /(?:^|\s)nocode(?:\s|$)/;
        
          var chunks = [];
          var length = 0;
          var spans = [];
          var k = 0;
        
          function walk(node) {
            var type = node.nodeType;
            if (type == 1) {  // Element
              if (nocode.test(node.className)) { return; }
              for (var child = node.firstChild; child; child = child.nextSibling) {
                walk(child);
              }
              var nodeName = node.nodeName.toLowerCase();
              if ('br' === nodeName || 'li' === nodeName) {
                chunks[k] = '\n';
                spans[k << 1] = length++;
                spans[(k++ << 1) | 1] = node;
              }
            } else if (type == 3 || type == 4) {  // Text
              var text = node.nodeValue;
              if (text.length) {
                if (!isPreformatted) {
                  text = text.replace(/[ \t\r\n]+/g, ' ');
                } else {
                  text = text.replace(/\r\n?/g, '\n');  // Normalize newlines.
                }
                // TODO: handle tabs here?
                chunks[k] = text;
                spans[k << 1] = length;
                length += text.length;
                spans[(k++ << 1) | 1] = node;
              }
            }
          }
        
          walk(node);
        
          return {
            sourceCode: chunks.join('').replace(/\n$/, ''),
            spans: spans
          };
        }
      
        /**
         * Apply the given language handler to sourceCode and add the resulting
         * decorations to out.
         * @param {!Element} sourceNode
         * @param {number} basePos the index of sourceCode within the chunk of source
         *    whose decorations are already present on out.
         * @param {string} sourceCode
         * @param {function(JobT)} langHandler
         * @param {DecorationsT} out
         */
        function appendDecorations(
            sourceNode, basePos, sourceCode, langHandler, out) {
          if (!sourceCode) { return; }
          /** @type {JobT} */
          var job = {
            sourceNode: sourceNode,
            pre: 1,
            langExtension: null,
            numberLines: null,
            sourceCode: sourceCode,
            spans: null,
            basePos: basePos,
            decorations: null
          };
          langHandler(job);
          out.push.apply(out, job.decorations);
        }
      
        var notWs = /\S/;
      
        /**
         * Given an element, if it contains only one child element and any text nodes
         * it contains contain only space characters, return the sole child element.
         * Otherwise returns undefined.
         * <p>
         * This is meant to return the CODE element in {@code <pre><code ...>} when
         * there is a single child element that contains all the non-space textual
         * content, but not to return anything where there are multiple child elements
         * as in {@code <pre><code>...</code><code>...</code></pre>} or when there
         * is textual content.
         */
        function childContentWrapper(element) {
          var wrapper = undefined;
          for (var c = element.firstChild; c; c = c.nextSibling) {
            var type = c.nodeType;
            wrapper = (type === 1)  // Element Node
                ? (wrapper ? element : c)
                : (type === 3)  // Text Node
                ? (notWs.test(c.nodeValue) ? element : wrapper)
                : wrapper;
          }
          return wrapper === element ? undefined : wrapper;
        }
      
        /** Given triples of [style, pattern, context] returns a lexing function,
          * The lexing function interprets the patterns to find token boundaries and
          * returns a decoration list of the form
          * [index_0, style_0, index_1, style_1, ..., index_n, style_n]
          * where index_n is an index into the sourceCode, and style_n is a style
          * constant like PR_PLAIN.  index_n-1 <= index_n, and style_n-1 applies to
          * all characters in sourceCode[index_n-1:index_n].
          *
          * The stylePatterns is a list whose elements have the form
          * [style : string, pattern : RegExp, DEPRECATED, shortcut : string].
          *
          * Style is a style constant like PR_PLAIN, or can be a string of the
          * form 'lang-FOO', where FOO is a language extension describing the
          * language of the portion of the token in $1 after pattern executes.
          * E.g., if style is 'lang-lisp', and group 1 contains the text
          * '(hello (world))', then that portion of the token will be passed to the
          * registered lisp handler for formatting.
          * The text before and after group 1 will be restyled using this decorator
          * so decorators should take care that this doesn't result in infinite
          * recursion.  For example, the HTML lexer rule for SCRIPT elements looks
          * something like ['lang-js', /<[s]cript>(.+?)<\/script>/].  This may match
          * '<script>foo()<\/script>', which would cause the current decorator to
          * be called with '<script>' which would not match the same rule since
          * group 1 must not be empty, so it would be instead styled as PR_TAG by
          * the generic tag rule.  The handler registered for the 'js' extension would
          * then be called with 'foo()', and finally, the current decorator would
          * be called with '<\/script>' which would not match the original rule and
          * so the generic tag rule would identify it as a tag.
          *
          * Pattern must only match prefixes, and if it matches a prefix, then that
          * match is considered a token with the same style.
          *
          * Context is applied to the last non-whitespace, non-comment token
          * recognized.
          *
          * Shortcut is an optional string of characters, any of which, if the first
          * character, gurantee that this pattern and only this pattern matches.
          *
          * @param {Array} shortcutStylePatterns patterns that always start with
          *   a known character.  Must have a shortcut string.
          * @param {Array} fallthroughStylePatterns patterns that will be tried in
          *   order if the shortcut ones fail.  May have shortcuts.
          *
          * @return {function (JobT)} a function that takes an undecorated job and
          *   attaches a list of decorations.
          */
        function createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns) {
          var shortcuts = {};
          var tokenizer;
          (function () {
            var allPatterns = shortcutStylePatterns.concat(fallthroughStylePatterns);
            var allRegexs = [];
            var regexKeys = {};
            for (var i = 0, n = allPatterns.length; i < n; ++i) {
              var patternParts = allPatterns[i];
              var shortcutChars = patternParts[3];
              if (shortcutChars) {
                for (var c = shortcutChars.length; --c >= 0;) {
                  shortcuts[shortcutChars.charAt(c)] = patternParts;
                }
              }
              var regex = patternParts[1];
              var k = '' + regex;
              if (!regexKeys.hasOwnProperty(k)) {
                allRegexs.push(regex);
                regexKeys[k] = null;
              }
            }
            allRegexs.push(/[\0-\uffff]/);
            tokenizer = combinePrefixPatterns(allRegexs);
          })();
      
          var nPatterns = fallthroughStylePatterns.length;
      
          /**
           * Lexes job.sourceCode and attaches an output array job.decorations of
           * style classes preceded by the position at which they start in
           * job.sourceCode in order.
           *
           * @type{function (JobT)}
           */
          var decorate = function (job) {
            var sourceCode = job.sourceCode, basePos = job.basePos;
            var sourceNode = job.sourceNode;
            /** Even entries are positions in source in ascending order.  Odd enties
              * are style markers (e.g., PR_COMMENT) that run from that position until
              * the end.
              * @type {DecorationsT}
              */
            var decorations = [basePos, PR_PLAIN];
            var pos = 0;  // index into sourceCode
            var tokens = sourceCode.match(tokenizer) || [];
            var styleCache = {};
      
            for (var ti = 0, nTokens = tokens.length; ti < nTokens; ++ti) {
              var token = tokens[ti];
              var style = styleCache[token];
              var match = void 0;
      
              var isEmbedded;
              if (typeof style === 'string') {
                isEmbedded = false;
              } else {
                var patternParts = shortcuts[token.charAt(0)];
                if (patternParts) {
                  match = token.match(patternParts[1]);
                  style = patternParts[0];
                } else {
                  for (var i = 0; i < nPatterns; ++i) {
                    patternParts = fallthroughStylePatterns[i];
                    match = token.match(patternParts[1]);
                    if (match) {
                      style = patternParts[0];
                      break;
                    }
                  }
      
                  if (!match) {  // make sure that we make progress
                    style = PR_PLAIN;
                  }
                }
      
                isEmbedded = style.length >= 5 && 'lang-' === style.substring(0, 5);
                if (isEmbedded && !(match && typeof match[1] === 'string')) {
                  isEmbedded = false;
                  style = PR_SOURCE;
                }
      
                if (!isEmbedded) { styleCache[token] = style; }
              }
      
              var tokenStart = pos;
              pos += token.length;
      
              if (!isEmbedded) {
                decorations.push(basePos + tokenStart, style);
              } else {  // Treat group 1 as an embedded block of source code.
                var embeddedSource = match[1];
                var embeddedSourceStart = token.indexOf(embeddedSource);
                var embeddedSourceEnd = embeddedSourceStart + embeddedSource.length;
                if (match[2]) {
                  // If embeddedSource can be blank, then it would match at the
                  // beginning which would cause us to infinitely recurse on the
                  // entire token, so we catch the right context in match[2].
                  embeddedSourceEnd = token.length - match[2].length;
                  embeddedSourceStart = embeddedSourceEnd - embeddedSource.length;
                }
                var lang = style.substring(5);
                // Decorate the left of the embedded source
                appendDecorations(
                    sourceNode,
                    basePos + tokenStart,
                    token.substring(0, embeddedSourceStart),
                    decorate, decorations);
                // Decorate the embedded source
                appendDecorations(
                    sourceNode,
                    basePos + tokenStart + embeddedSourceStart,
                    embeddedSource,
                    langHandlerForExtension(lang, embeddedSource),
                    decorations);
                // Decorate the right of the embedded section
                appendDecorations(
                    sourceNode,
                    basePos + tokenStart + embeddedSourceEnd,
                    token.substring(embeddedSourceEnd),
                    decorate, decorations);
              }
            }
            job.decorations = decorations;
          };
          return decorate;
        }
      
        /** returns a function that produces a list of decorations from source text.
          *
          * This code treats ", ', and ` as string delimiters, and \ as a string
          * escape.  It does not recognize perl's qq() style strings.
          * It has no special handling for double delimiter escapes as in basic, or
          * the tripled delimiters used in python, but should work on those regardless
          * although in those cases a single string literal may be broken up into
          * multiple adjacent string literals.
          *
          * It recognizes C, C++, and shell style comments.
          *
          * @param {Object} options a set of optional parameters.
          * @return {function (JobT)} a function that examines the source code
          *     in the input job and builds a decoration list which it attaches to
          *     the job.
          */
        function sourceDecorator(options) {
          var shortcutStylePatterns = [], fallthroughStylePatterns = [];
          if (options['tripleQuotedStrings']) {
            // '''multi-line-string''', 'single-line-string', and double-quoted
            shortcutStylePatterns.push(
                [PR_STRING,  /^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,
                 null, '\'"']);
          } else if (options['multiLineStrings']) {
            // 'multi-line-string', "multi-line-string"
            shortcutStylePatterns.push(
                [PR_STRING,  /^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,
                 null, '\'"`']);
          } else {
            // 'single-line-string', "single-line-string"
            shortcutStylePatterns.push(
                [PR_STRING,
                 /^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,
                 null, '"\'']);
          }
          if (options['verbatimStrings']) {
            // verbatim-string-literal production from the C# grammar.  See issue 93.
            fallthroughStylePatterns.push(
                [PR_STRING, /^@\"(?:[^\"]|\"\")*(?:\"|$)/, null]);
          }
          var hc = options['hashComments'];
          if (hc) {
            if (options['cStyleComments']) {
              if (hc > 1) {  // multiline hash comments
                shortcutStylePatterns.push(
                    [PR_COMMENT, /^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/, null, '#']);
              } else {
                // Stop C preprocessor declarations at an unclosed open comment
                shortcutStylePatterns.push(
                    [PR_COMMENT, /^#(?:(?:define|e(?:l|nd)if|else|error|ifn?def|include|line|pragma|undef|warning)\b|[^\r\n]*)/,
                     null, '#']);
              }
              // #include <stdio.h>
              fallthroughStylePatterns.push(
                  [PR_STRING,
                   /^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h(?:h|pp|\+\+)?|[a-z]\w*)>/,
                   null]);
            } else {
              shortcutStylePatterns.push([PR_COMMENT, /^#[^\r\n]*/, null, '#']);
            }
          }
          if (options['cStyleComments']) {
            fallthroughStylePatterns.push([PR_COMMENT, /^\/\/[^\r\n]*/, null]);
            fallthroughStylePatterns.push(
                [PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/, null]);
          }
          var regexLiterals = options['regexLiterals'];
          if (regexLiterals) {
            /**
             * @const
             */
            var regexExcls = regexLiterals > 1
              ? ''  // Multiline regex literals
              : '\n\r';
            /**
             * @const
             */
            var regexAny = regexExcls ? '.' : '[\\S\\s]';
            /**
             * @const
             */
            var REGEX_LITERAL = (
                // A regular expression literal starts with a slash that is
                // not followed by * or / so that it is not confused with
                // comments.
                '/(?=[^/*' + regexExcls + '])'
                // and then contains any number of raw characters,
                + '(?:[^/\\x5B\\x5C' + regexExcls + ']'
                // escape sequences (\x5C),
                +    '|\\x5C' + regexAny
                // or non-nesting character sets (\x5B\x5D);
                +    '|\\x5B(?:[^\\x5C\\x5D' + regexExcls + ']'
                +             '|\\x5C' + regexAny + ')*(?:\\x5D|$))+'
                // finally closed by a /.
                + '/');
            fallthroughStylePatterns.push(
                ['lang-regex',
                 RegExp('^' + REGEXP_PRECEDER_PATTERN + '(' + REGEX_LITERAL + ')')
                 ]);
          }
      
          var types = options['types'];
          if (types) {
            fallthroughStylePatterns.push([PR_TYPE, types]);
          }
      
          var keywords = ("" + options['keywords']).replace(/^ | $/g, '');
          if (keywords.length) {
            fallthroughStylePatterns.push(
                [PR_KEYWORD,
                 new RegExp('^(?:' + keywords.replace(/[\s,]+/g, '|') + ')\\b'),
                 null]);
          }
      
          shortcutStylePatterns.push([PR_PLAIN,       /^\s+/, null, ' \r\n\t\xA0']);
      
          var punctuation =
            // The Bash man page says
      
            // A word is a sequence of characters considered as a single
            // unit by GRUB. Words are separated by metacharacters,
            // which are the following plus space, tab, and newline: { }
            // | & $ ; < >
            // ...
      
            // A word beginning with # causes that word and all remaining
            // characters on that line to be ignored.
      
            // which means that only a '#' after /(?:^|[{}|&$;<>\s])/ starts a
            // comment but empirically
            // $ echo {#}
            // {#}
            // $ echo \$#
            // $#
            // $ echo }#
            // }#
      
            // so /(?:^|[|&;<>\s])/ is more appropriate.
      
            // http://gcc.gnu.org/onlinedocs/gcc-2.95.3/cpp_1.html#SEC3
            // suggests that this definition is compatible with a
            // default mode that tries to use a single token definition
            // to recognize both bash/python style comments and C
            // preprocessor directives.
      
            // This definition of punctuation does not include # in the list of
            // follow-on exclusions, so # will not be broken before if preceeded
            // by a punctuation character.  We could try to exclude # after
            // [|&;<>] but that doesn't seem to cause many major problems.
            // If that does turn out to be a problem, we should change the below
            // when hc is truthy to include # in the run of punctuation characters
            // only when not followint [|&;<>].
            '^.[^\\s\\w.$@\'"`/\\\\]*';
          if (options['regexLiterals']) {
            punctuation += '(?!\s*\/)';
          }
      
          fallthroughStylePatterns.push(
              // TODO(mikesamuel): recognize non-latin letters and numerals in idents
              [PR_LITERAL,     /^@[a-z_$][a-z_$@0-9]*/i, null],
              [PR_TYPE,        /^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/, null],
              [PR_PLAIN,       /^[a-z_$][a-z_$@0-9]*/i, null],
              [PR_LITERAL,
               new RegExp(
                   '^(?:'
                   // A hex number
                   + '0x[a-f0-9]+'
                   // or an octal or decimal number,
                   + '|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)'
                   // possibly in scientific notation
                   + '(?:e[+\\-]?\\d+)?'
                   + ')'
                   // with an optional modifier like UL for unsigned long
                   + '[a-z]*', 'i'),
               null, '0123456789'],
              // Don't treat escaped quotes in bash as starting strings.
              // See issue 144.
              [PR_PLAIN,       /^\\[\s\S]?/, null],
              [PR_PUNCTUATION, new RegExp(punctuation), null]);
      
          return createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns);
        }
      
        var decorateSource = sourceDecorator({
              'keywords': ALL_KEYWORDS,
              'hashComments': true,
              'cStyleComments': true,
              'multiLineStrings': true,
              'regexLiterals': true
            });
      
        /**
         * Given a DOM subtree, wraps it in a list, and puts each line into its own
         * list item.
         *
         * @param {Node} node modified in place.  Its content is pulled into an
         *     HTMLOListElement, and each line is moved into a separate list item.
         *     This requires cloning elements, so the input might not have unique
         *     IDs after numbering.
         * @param {number|null|boolean} startLineNum
         *     If truthy, coerced to an integer which is the 1-indexed line number
         *     of the first line of code.  The number of the first line will be
         *     attached to the list.
         * @param {boolean} isPreformatted true iff white-space in text nodes should
         *     be treated as significant.
         */
        function numberLines(node, startLineNum, isPreformatted) {
          var nocode = /(?:^|\s)nocode(?:\s|$)/;
          var lineBreak = /\r\n?|\n/;
        
          var document = node.ownerDocument;
        
          var li = document.createElement('li');
          while (node.firstChild) {
            li.appendChild(node.firstChild);
          }
          // An array of lines.  We split below, so this is initialized to one
          // un-split line.
          var listItems = [li];
        
          function walk(node) {
            var type = node.nodeType;
            if (type == 1 && !nocode.test(node.className)) {  // Element
              if ('br' === node.nodeName) {
                breakAfter(node);
                // Discard the <BR> since it is now flush against a </LI>.
                if (node.parentNode) {
                  node.parentNode.removeChild(node);
                }
              } else {
                for (var child = node.firstChild; child; child = child.nextSibling) {
                  walk(child);
                }
              }
            } else if ((type == 3 || type == 4) && isPreformatted) {  // Text
              var text = node.nodeValue;
              var match = text.match(lineBreak);
              if (match) {
                var firstLine = text.substring(0, match.index);
                node.nodeValue = firstLine;
                var tail = text.substring(match.index + match[0].length);
                if (tail) {
                  var parent = node.parentNode;
                  parent.insertBefore(
                    document.createTextNode(tail), node.nextSibling);
                }
                breakAfter(node);
                if (!firstLine) {
                  // Don't leave blank text nodes in the DOM.
                  node.parentNode.removeChild(node);
                }
              }
            }
          }
        
          // Split a line after the given node.
          function breakAfter(lineEndNode) {
            // If there's nothing to the right, then we can skip ending the line
            // here, and move root-wards since splitting just before an end-tag
            // would require us to create a bunch of empty copies.
            while (!lineEndNode.nextSibling) {
              lineEndNode = lineEndNode.parentNode;
              if (!lineEndNode) { return; }
            }
        
            function breakLeftOf(limit, copy) {
              // Clone shallowly if this node needs to be on both sides of the break.
              var rightSide = copy ? limit.cloneNode(false) : limit;
              var parent = limit.parentNode;
              if (parent) {
                // We clone the parent chain.
                // This helps us resurrect important styling elements that cross lines.
                // E.g. in <i>Foo<br>Bar</i>
                // should be rewritten to <li><i>Foo</i></li><li><i>Bar</i></li>.
                var parentClone = breakLeftOf(parent, 1);
                // Move the clone and everything to the right of the original
                // onto the cloned parent.
                var next = limit.nextSibling;
                parentClone.appendChild(rightSide);
                for (var sibling = next; sibling; sibling = next) {
                  next = sibling.nextSibling;
                  parentClone.appendChild(sibling);
                }
              }
              return rightSide;
            }
        
            var copiedListItem = breakLeftOf(lineEndNode.nextSibling, 0);
        
            // Walk the parent chain until we reach an unattached LI.
            for (var parent;
                 // Check nodeType since IE invents document fragments.
                 (parent = copiedListItem.parentNode) && parent.nodeType === 1;) {
              copiedListItem = parent;
            }
            // Put it on the list of lines for later processing.
            listItems.push(copiedListItem);
          }
        
          // Split lines while there are lines left to split.
          for (var i = 0;  // Number of lines that have been split so far.
               i < listItems.length;  // length updated by breakAfter calls.
               ++i) {
            walk(listItems[i]);
          }
        
          // Make sure numeric indices show correctly.
          if (startLineNum === (startLineNum|0)) {
            listItems[0].setAttribute('value', startLineNum);
          }
        
          var ol = document.createElement('ol');
          ol.className = 'linenums';
          var offset = Math.max(0, ((startLineNum - 1 /* zero index */)) | 0) || 0;
          for (var i = 0, n = listItems.length; i < n; ++i) {
            li = listItems[i];
            // Stick a class on the LIs so that stylesheets can
            // color odd/even rows, or any other row pattern that
            // is co-prime with 10.
            li.className = 'L' + ((i + offset) % 10);
            if (!li.firstChild) {
              li.appendChild(document.createTextNode('\xA0'));
            }
            ol.appendChild(li);
          }
        
          node.appendChild(ol);
        }
      
        /**
         * Breaks {@code job.sourceCode} around style boundaries in
         * {@code job.decorations} and modifies {@code job.sourceNode} in place.
         * @param {JobT} job
         * @private
         */
        function recombineTagsAndDecorations(job) {
          var isIE8OrEarlier = /\bMSIE\s(\d+)/.exec(navigator.userAgent);
          isIE8OrEarlier = isIE8OrEarlier && +isIE8OrEarlier[1] <= 8;
          var newlineRe = /\n/g;
        
          var source = job.sourceCode;
          var sourceLength = source.length;
          // Index into source after the last code-unit recombined.
          var sourceIndex = 0;
        
          var spans = job.spans;
          var nSpans = spans.length;
          // Index into spans after the last span which ends at or before sourceIndex.
          var spanIndex = 0;
        
          var decorations = job.decorations;
          var nDecorations = decorations.length;
          // Index into decorations after the last decoration which ends at or before
          // sourceIndex.
          var decorationIndex = 0;
        
          // Remove all zero-length decorations.
          decorations[nDecorations] = sourceLength;
          var decPos, i;
          for (i = decPos = 0; i < nDecorations;) {
            if (decorations[i] !== decorations[i + 2]) {
              decorations[decPos++] = decorations[i++];
              decorations[decPos++] = decorations[i++];
            } else {
              i += 2;
            }
          }
          nDecorations = decPos;
        
          // Simplify decorations.
          for (i = decPos = 0; i < nDecorations;) {
            var startPos = decorations[i];
            // Conflate all adjacent decorations that use the same style.
            var startDec = decorations[i + 1];
            var end = i + 2;
            while (end + 2 <= nDecorations && decorations[end + 1] === startDec) {
              end += 2;
            }
            decorations[decPos++] = startPos;
            decorations[decPos++] = startDec;
            i = end;
          }
        
          nDecorations = decorations.length = decPos;
        
          var sourceNode = job.sourceNode;
          var oldDisplay = "";
          if (sourceNode) {
            oldDisplay = sourceNode.style.display;
            sourceNode.style.display = 'none';
          }
          try {
            var decoration = null;
            while (spanIndex < nSpans) {
              var spanStart = spans[spanIndex];
              var spanEnd = /** @type{number} */ (spans[spanIndex + 2])
                  || sourceLength;
        
              var decEnd = decorations[decorationIndex + 2] || sourceLength;
        
              var end = Math.min(spanEnd, decEnd);
        
              var textNode = /** @type{Node} */ (spans[spanIndex + 1]);
              var styledText;
              if (textNode.nodeType !== 1  // Don't muck with <BR>s or <LI>s
                  // Don't introduce spans around empty text nodes.
                  && (styledText = source.substring(sourceIndex, end))) {
                // This may seem bizarre, and it is.  Emitting LF on IE causes the
                // code to display with spaces instead of line breaks.
                // Emitting Windows standard issue linebreaks (CRLF) causes a blank
                // space to appear at the beginning of every line but the first.
                // Emitting an old Mac OS 9 line separator makes everything spiffy.
                if (isIE8OrEarlier) {
                  styledText = styledText.replace(newlineRe, '\r');
                }
                textNode.nodeValue = styledText;
                var document = textNode.ownerDocument;
                var span = document.createElement('span');
                span.className = decorations[decorationIndex + 1];
                var parentNode = textNode.parentNode;
                parentNode.replaceChild(span, textNode);
                span.appendChild(textNode);
                if (sourceIndex < spanEnd) {  // Split off a text node.
                  spans[spanIndex + 1] = textNode
                      // TODO: Possibly optimize by using '' if there's no flicker.
                      = document.createTextNode(source.substring(end, spanEnd));
                  parentNode.insertBefore(textNode, span.nextSibling);
                }
              }
        
              sourceIndex = end;
        
              if (sourceIndex >= spanEnd) {
                spanIndex += 2;
              }
              if (sourceIndex >= decEnd) {
                decorationIndex += 2;
              }
            }
          } finally {
            if (sourceNode) {
              sourceNode.style.display = oldDisplay;
            }
          }
        }
      
        /** Maps language-specific file extensions to handlers. */
        var langHandlerRegistry = {};
        /** Register a language handler for the given file extensions.
          * @param {function (JobT)} handler a function from source code to a list
          *      of decorations.  Takes a single argument job which describes the
          *      state of the computation and attaches the decorations to it.
          * @param {Array.<string>} fileExtensions
          */
        function registerLangHandler(handler, fileExtensions) {
          for (var i = fileExtensions.length; --i >= 0;) {
            var ext = fileExtensions[i];
            if (!langHandlerRegistry.hasOwnProperty(ext)) {
              langHandlerRegistry[ext] = handler;
            } else if (win['console']) {
              console['warn']('cannot override language handler %s', ext);
            }
          }
        }
        function langHandlerForExtension(extension, source) {
          if (!(extension && langHandlerRegistry.hasOwnProperty(extension))) {
            // Treat it as markup if the first non whitespace character is a < and
            // the last non-whitespace character is a >.
            extension = /^\s*</.test(source)
                ? 'default-markup'
                : 'default-code';
          }
          return langHandlerRegistry[extension];
        }
        registerLangHandler(decorateSource, ['default-code']);
        registerLangHandler(
            createSimpleLexer(
                [],
                [
                 [PR_PLAIN,       /^[^<?]+/],
                 [PR_DECLARATION, /^<!\w[^>]*(?:>|$)/],
                 [PR_COMMENT,     /^<\!--[\s\S]*?(?:-\->|$)/],
                 // Unescaped content in an unknown language
                 ['lang-',        /^<\?([\s\S]+?)(?:\?>|$)/],
                 ['lang-',        /^<%([\s\S]+?)(?:%>|$)/],
                 [PR_PUNCTUATION, /^(?:<[%?]|[%?]>)/],
                 ['lang-',        /^<xmp\b[^>]*>([\s\S]+?)<\/xmp\b[^>]*>/i],
                 // Unescaped content in javascript.  (Or possibly vbscript).
                 ['lang-js',      /^<script\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],
                 // Contains unescaped stylesheet content
                 ['lang-css',     /^<style\b[^>]*>([\s\S]*?)(<\/style\b[^>]*>)/i],
                 ['lang-in.tag',  /^(<\/?[a-z][^<>]*>)/i]
                ]),
            ['default-markup', 'htm', 'html', 'mxml', 'xhtml', 'xml', 'xsl']);
        registerLangHandler(
            createSimpleLexer(
                [
                 [PR_PLAIN,        /^[\s]+/, null, ' \t\r\n'],
                 [PR_ATTRIB_VALUE, /^(?:\"[^\"]*\"?|\'[^\']*\'?)/, null, '\"\'']
                 ],
                [
                 [PR_TAG,          /^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],
                 [PR_ATTRIB_NAME,  /^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],
                 ['lang-uq.val',   /^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/],
                 [PR_PUNCTUATION,  /^[=<>\/]+/],
                 ['lang-js',       /^on\w+\s*=\s*\"([^\"]+)\"/i],
                 ['lang-js',       /^on\w+\s*=\s*\'([^\']+)\'/i],
                 ['lang-js',       /^on\w+\s*=\s*([^\"\'>\s]+)/i],
                 ['lang-css',      /^style\s*=\s*\"([^\"]+)\"/i],
                 ['lang-css',      /^style\s*=\s*\'([^\']+)\'/i],
                 ['lang-css',      /^style\s*=\s*([^\"\'>\s]+)/i]
                 ]),
            ['in.tag']);
        registerLangHandler(
            createSimpleLexer([], [[PR_ATTRIB_VALUE, /^[\s\S]+/]]), ['uq.val']);
        registerLangHandler(sourceDecorator({
                'keywords': CPP_KEYWORDS,
                'hashComments': true,
                'cStyleComments': true,
                'types': C_TYPES
              }), ['c', 'cc', 'cpp', 'cxx', 'cyc', 'm']);
        registerLangHandler(sourceDecorator({
                'keywords': 'null,true,false'
              }), ['json']);
        registerLangHandler(sourceDecorator({
                'keywords': CSHARP_KEYWORDS,
                'hashComments': true,
                'cStyleComments': true,
                'verbatimStrings': true,
                'types': C_TYPES
              }), ['cs']);
        registerLangHandler(sourceDecorator({
                'keywords': JAVA_KEYWORDS,
                'cStyleComments': true
              }), ['java']);
        registerLangHandler(sourceDecorator({
                'keywords': SH_KEYWORDS,
                'hashComments': true,
                'multiLineStrings': true
              }), ['bash', 'bsh', 'csh', 'sh']);
        registerLangHandler(sourceDecorator({
                'keywords': PYTHON_KEYWORDS,
                'hashComments': true,
                'multiLineStrings': true,
                'tripleQuotedStrings': true
              }), ['cv', 'py', 'python']);
        registerLangHandler(sourceDecorator({
                'keywords': PERL_KEYWORDS,
                'hashComments': true,
                'multiLineStrings': true,
                'regexLiterals': 2  // multiline regex literals
              }), ['perl', 'pl', 'pm']);
        registerLangHandler(sourceDecorator({
                'keywords': RUBY_KEYWORDS,
                'hashComments': true,
                'multiLineStrings': true,
                'regexLiterals': true
              }), ['rb', 'ruby']);
        registerLangHandler(sourceDecorator({
                'keywords': JSCRIPT_KEYWORDS,
                'cStyleComments': true,
                'regexLiterals': true
              }), ['javascript', 'js', 'ts', 'typescript']);
        registerLangHandler(sourceDecorator({
                'keywords': COFFEE_KEYWORDS,
                'hashComments': 3,  // ### style block comments
                'cStyleComments': true,
                'multilineStrings': true,
                'tripleQuotedStrings': true,
                'regexLiterals': true
              }), ['coffee']);
        registerLangHandler(
            createSimpleLexer([], [[PR_STRING, /^[\s\S]+/]]), ['regex']);
      
        /** @param {JobT} job */
        function applyDecorator(job) {
          var opt_langExtension = job.langExtension;
      
          try {
            // Extract tags, and convert the source code to plain text.
            var sourceAndSpans = extractSourceSpans(job.sourceNode, job.pre);
            /** Plain text. @type {string} */
            var source = sourceAndSpans.sourceCode;
            job.sourceCode = source;
            job.spans = sourceAndSpans.spans;
            job.basePos = 0;
      
            // Apply the appropriate language handler
            langHandlerForExtension(opt_langExtension, source)(job);
      
            // Integrate the decorations and tags back into the source code,
            // modifying the sourceNode in place.
            recombineTagsAndDecorations(job);
          } catch (e) {
            if (win['console']) {
              console['log'](e && e['stack'] || e);
            }
          }
        }
      
        /**
         * Pretty print a chunk of code.
         * @param sourceCodeHtml {string} The HTML to pretty print.
         * @param opt_langExtension {string} The language name to use.
         *     Typically, a filename extension like 'cpp' or 'java'.
         * @param opt_numberLines {number|boolean} True to number lines,
         *     or the 1-indexed number of the first line in sourceCodeHtml.
         */
        function $prettyPrintOne(sourceCodeHtml, opt_langExtension, opt_numberLines) {
          /** @type{number|boolean} */
          var nl = opt_numberLines || false;
          /** @type{string|null} */
          var langExtension = opt_langExtension || null;
          /** @type{!Element} */
          var container = document.createElement('div');
          // This could cause images to load and onload listeners to fire.
          // E.g. <img onerror="alert(1337)" src="nosuchimage.png">.
          // We assume that the inner HTML is from a trusted source.
          // The pre-tag is required for IE8 which strips newlines from innerHTML
          // when it is injected into a <pre> tag.
          // http://stackoverflow.com/questions/451486/pre-tag-loses-line-breaks-when-setting-innerhtml-in-ie
          // http://stackoverflow.com/questions/195363/inserting-a-newline-into-a-pre-tag-ie-javascript
          container.innerHTML = '<pre>' + sourceCodeHtml + '</pre>';
          container = /** @type{!Element} */(container.firstChild);
          if (nl) {
            numberLines(container, nl, true);
          }
      
          /** @type{JobT} */
          var job = {
            langExtension: langExtension,
            numberLines: nl,
            sourceNode: container,
            pre: 1,
            sourceCode: null,
            basePos: null,
            spans: null,
            decorations: null
          };
          applyDecorator(job);
          return container.innerHTML;
        }
      
         /**
          * Find all the {@code <pre>} and {@code <code>} tags in the DOM with
          * {@code class=prettyprint} and prettify them.
          *
          * @param {Function} opt_whenDone called when prettifying is done.
          * @param {HTMLElement|HTMLDocument} opt_root an element or document
          *   containing all the elements to pretty print.
          *   Defaults to {@code document.body}.
          */
        function $prettyPrint(opt_whenDone, opt_root) {
          var root = opt_root || document.body;
          var doc = root.ownerDocument || document;
          function byTagName(tn) { return root.getElementsByTagName(tn); }
          // fetch a list of nodes to rewrite
          var codeSegments = [byTagName('pre'), byTagName('code'), byTagName('xmp')];
          var elements = [];
          for (var i = 0; i < codeSegments.length; ++i) {
            for (var j = 0, n = codeSegments[i].length; j < n; ++j) {
              elements.push(codeSegments[i][j]);
            }
          }
          codeSegments = null;
      
          var clock = Date;
          if (!clock['now']) {
            clock = { 'now': function () { return +(new Date); } };
          }
      
          // The loop is broken into a series of continuations to make sure that we
          // don't make the browser unresponsive when rewriting a large page.
          var k = 0;
      
          var langExtensionRe = /\blang(?:uage)?-([\w.]+)(?!\S)/;
          var prettyPrintRe = /\bprettyprint\b/;
          var prettyPrintedRe = /\bprettyprinted\b/;
          var preformattedTagNameRe = /pre|xmp/i;
          var codeRe = /^code$/i;
          var preCodeXmpRe = /^(?:pre|code|xmp)$/i;
          var EMPTY = {};
      
          function doWork() {
            var endTime = (win['PR_SHOULD_USE_CONTINUATION'] ?
                           clock['now']() + 250 /* ms */ :
                           Infinity);
            for (; k < elements.length && clock['now']() < endTime; k++) {
              var cs = elements[k];
      
              // Look for a preceding comment like
              // <?prettify lang="..." linenums="..."?>
              var attrs = EMPTY;
              {
                for (var preceder = cs; (preceder = preceder.previousSibling);) {
                  var nt = preceder.nodeType;
                  // <?foo?> is parsed by HTML 5 to a comment node (8)
                  // like <!--?foo?-->, but in XML is a processing instruction
                  var value = (nt === 7 || nt === 8) && preceder.nodeValue;
                  if (value
                      ? !/^\??prettify\b/.test(value)
                      : (nt !== 3 || /\S/.test(preceder.nodeValue))) {
                    // Skip over white-space text nodes but not others.
                    break;
                  }
                  if (value) {
                    attrs = {};
                    value.replace(
                        /\b(\w+)=([\w:.%+-]+)/g,
                      function (_, name, value) { attrs[name] = value; });
                    break;
                  }
                }
              }
      
              var className = cs.className;
              if ((attrs !== EMPTY || prettyPrintRe.test(className))
                  // Don't redo this if we've already done it.
                  // This allows recalling pretty print to just prettyprint elements
                  // that have been added to the page since last call.
                  && !prettyPrintedRe.test(className)) {
      
                // make sure this is not nested in an already prettified element
                var nested = false;
                for (var p = cs.parentNode; p; p = p.parentNode) {
                  var tn = p.tagName;
                  if (preCodeXmpRe.test(tn)
                      && p.className && prettyPrintRe.test(p.className)) {
                    nested = true;
                    break;
                  }
                }
                if (!nested) {
                  // Mark done.  If we fail to prettyprint for whatever reason,
                  // we shouldn't try again.
                  cs.className += ' prettyprinted';
      
                  // If the classes includes a language extensions, use it.
                  // Language extensions can be specified like
                  //     <pre class="prettyprint lang-cpp">
                  // the language extension "cpp" is used to find a language handler
                  // as passed to PR.registerLangHandler.
                  // HTML5 recommends that a language be specified using "language-"
                  // as the prefix instead.  Google Code Prettify supports both.
                  // http://dev.w3.org/html5/spec-author-view/the-code-element.html
                  var langExtension = attrs['lang'];
                  if (!langExtension) {
                    langExtension = className.match(langExtensionRe);
                    // Support <pre class="prettyprint"><code class="language-c">
                    var wrapper;
                    if (!langExtension && (wrapper = childContentWrapper(cs))
                        && codeRe.test(wrapper.tagName)) {
                      langExtension = wrapper.className.match(langExtensionRe);
                    }
      
                    if (langExtension) { langExtension = langExtension[1]; }
                  }
      
                  var preformatted;
                  if (preformattedTagNameRe.test(cs.tagName)) {
                    preformatted = 1;
                  } else {
                    var currentStyle = cs['currentStyle'];
                    var defaultView = doc.defaultView;
                    var whitespace = (
                        currentStyle
                        ? currentStyle['whiteSpace']
                        : (defaultView
                           && defaultView.getComputedStyle)
                        ? defaultView.getComputedStyle(cs, null)
                        .getPropertyValue('white-space')
                        : 0);
                    preformatted = whitespace
                        && 'pre' === whitespace.substring(0, 3);
                  }
      
                  // Look for a class like linenums or linenums:<n> where <n> is the
                  // 1-indexed number of the first line.
                  var lineNums = attrs['linenums'];
                  if (!(lineNums = lineNums === 'true' || +lineNums)) {
                    lineNums = className.match(/\blinenums\b(?::(\d+))?/);
                    lineNums =
                      lineNums
                      ? lineNums[1] && lineNums[1].length
                        ? +lineNums[1] : true
                      : false;
                  }
                  if (lineNums) { numberLines(cs, lineNums, preformatted); }
      
                  // do the pretty printing
                  var prettyPrintingJob = {
                    langExtension: langExtension,
                    sourceNode: cs,
                    numberLines: lineNums,
                    pre: preformatted,
                    sourceCode: null,
                    basePos: null,
                    spans: null,
                    decorations: null
                  };
                  applyDecorator(prettyPrintingJob);
                }
              }
            }
            if (k < elements.length) {
              // finish up in a continuation
              win.setTimeout(doWork, 250);
            } else if ('function' === typeof opt_whenDone) {
              opt_whenDone();
            }
          }
      
          doWork();
        }
      
        /**
         * Contains functions for creating and registering new language handlers.
         * @type {Object}
         */
        var PR = win['PR'] = {
              'createSimpleLexer': createSimpleLexer,
              'registerLangHandler': registerLangHandler,
              'sourceDecorator': sourceDecorator,
              'PR_ATTRIB_NAME': PR_ATTRIB_NAME,
              'PR_ATTRIB_VALUE': PR_ATTRIB_VALUE,
              'PR_COMMENT': PR_COMMENT,
              'PR_DECLARATION': PR_DECLARATION,
              'PR_KEYWORD': PR_KEYWORD,
              'PR_LITERAL': PR_LITERAL,
              'PR_NOCODE': PR_NOCODE,
              'PR_PLAIN': PR_PLAIN,
              'PR_PUNCTUATION': PR_PUNCTUATION,
              'PR_SOURCE': PR_SOURCE,
              'PR_STRING': PR_STRING,
              'PR_TAG': PR_TAG,
              'PR_TYPE': PR_TYPE,
              'prettyPrintOne':
                 IN_GLOBAL_SCOPE
                   ? (win['prettyPrintOne'] = $prettyPrintOne)
                   : (prettyPrintOne = $prettyPrintOne),
              'prettyPrint': prettyPrint =
                 IN_GLOBAL_SCOPE
                   ? (win['prettyPrint'] = $prettyPrint)
                   : (prettyPrint = $prettyPrint)
            };
      
        // Make PR available via the Asynchronous Module Definition (AMD) API.
        // Per https://github.com/amdjs/amdjs-api/wiki/AMD:
        // The Asynchronous Module Definition (AMD) API specifies a
        // mechanism for defining modules such that the module and its
        // dependencies can be asynchronously loaded.
        // ...
        // To allow a clear indicator that a global define function (as
        // needed for script src browser loading) conforms to the AMD API,
        // any global define function SHOULD have a property called "amd"
        // whose value is an object. This helps avoid conflict with any
        // other existing JavaScript code that could have defined a define()
        // function that does not conform to the AMD API.
        var define = win['define'];
        if (typeof define === "function" && define['amd']) {
          define("google-code-prettify", [], function () {
            return PR;
          });
        }
      })();
      
      
      /***/ }),
      
      /***/ "TXwP":
      /*!*********************************************************!*\
        !*** ./node_modules/js-beautify/js/lib/beautify-css.js ***!
        \*********************************************************/
      /*! no static exports found */
      /*! all exports used */
      /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
      /***/ (function(module, exports, __webpack_require__) {
      
      var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* AUTO-GENERATED. DO NOT MODIFY. */
      /*
      
        The MIT License (MIT)
      
        Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
      
        Permission 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:
      
        The above copyright notice and this permission notice shall be
        included in all copies or substantial portions of the Software.
      
        THE 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.
      
      
       CSS Beautifier
      ---------------
      
          Written by Harutyun Amirjanyan, (amirjanyan@gmail.com)
      
          Based on code initially developed by: Einar Lielmanis, <einar@beautifier.io>
              https://beautifier.io/
      
          Usage:
              css_beautify(source_text);
              css_beautify(source_text, options);
      
          The options are (default in brackets):
              indent_size (4)                         — indentation size,
              indent_char (space)                     — character to indent with,
              selector_separator_newline (true)       - separate selectors with newline or
                                                        not (e.g. "a,\nbr" or "a, br")
              end_with_newline (false)                - end with a newline
              newline_between_rules (true)            - add a new line after every css rule
              space_around_selector_separator (false) - ensure space around selector separators:
                                                        '>', '+', '~' (e.g. "a>b" -> "a > b")
          e.g
      
          css_beautify(css_source_text, {
            'indent_size': 1,
            'indent_char': '\t',
            'selector_separator': ' ',
            'end_with_newline': false,
            'newline_between_rules': true,
            'space_around_selector_separator': true
          });
      */
      
      // http://www.w3.org/TR/CSS21/syndata.html#tokenization
      // http://www.w3.org/TR/css3-syntax/
      
      (function() {
      
      /* GENERATED_BUILD_OUTPUT */
      var legacy_beautify_css;
      /******/ (function() { // webpackBootstrap
      /******/ 	"use strict";
      /******/ 	var __webpack_modules__ = ([
      /* 0 */,
      /* 1 */,
      /* 2 */
      /***/ (function(module) {
      
      /*jshint node:true */
      /*
        The MIT License (MIT)
      
        Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
      
        Permission 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:
      
        The above copyright notice and this permission notice shall be
        included in all copies or substantial portions of the Software.
      
        THE 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.
      */
      
      
      
      function OutputLine(parent) {
        this.__parent = parent;
        this.__character_count = 0;
        // use indent_count as a marker for this.__lines that have preserved indentation
        this.__indent_count = -1;
        this.__alignment_count = 0;
        this.__wrap_point_index = 0;
        this.__wrap_point_character_count = 0;
        this.__wrap_point_indent_count = -1;
        this.__wrap_point_alignment_count = 0;
      
        this.__items = [];
      }
      
      OutputLine.prototype.clone_empty = function() {
        var line = new OutputLine(this.__parent);
        line.set_indent(this.__indent_count, this.__alignment_count);
        return line;
      };
      
      OutputLine.prototype.item = function(index) {
        if (index < 0) {
          return this.__items[this.__items.length + index];
        } else {
          return this.__items[index];
        }
      };
      
      OutputLine.prototype.has_match = function(pattern) {
        for (var lastCheckedOutput = this.__items.length - 1; lastCheckedOutput >= 0; lastCheckedOutput--) {
          if (this.__items[lastCheckedOutput].match(pattern)) {
            return true;
          }
        }
        return false;
      };
      
      OutputLine.prototype.set_indent = function(indent, alignment) {
        if (this.is_empty()) {
          this.__indent_count = indent || 0;
          this.__alignment_count = alignment || 0;
          this.__character_count = this.__parent.get_indent_size(this.__indent_count, this.__alignment_count);
        }
      };
      
      OutputLine.prototype._set_wrap_point = function() {
        if (this.__parent.wrap_line_length) {
          this.__wrap_point_index = this.__items.length;
          this.__wrap_point_character_count = this.__character_count;
          this.__wrap_point_indent_count = this.__parent.next_line.__indent_count;
          this.__wrap_point_alignment_count = this.__parent.next_line.__alignment_count;
        }
      };
      
      OutputLine.prototype._should_wrap = function() {
        return this.__wrap_point_index &&
          this.__character_count > this.__parent.wrap_line_length &&
          this.__wrap_point_character_count > this.__parent.next_line.__character_count;
      };
      
      OutputLine.prototype._allow_wrap = function() {
        if (this._should_wrap()) {
          this.__parent.add_new_line();
          var next = this.__parent.current_line;
          next.set_indent(this.__wrap_point_indent_count, this.__wrap_point_alignment_count);
          next.__items = this.__items.slice(this.__wrap_point_index);
          this.__items = this.__items.slice(0, this.__wrap_point_index);
      
          next.__character_count += this.__character_count - this.__wrap_point_character_count;
          this.__character_count = this.__wrap_point_character_count;
      
          if (next.__items[0] === " ") {
            next.__items.splice(0, 1);
            next.__character_count -= 1;
          }
          return true;
        }
        return false;
      };
      
      OutputLine.prototype.is_empty = function() {
        return this.__items.length === 0;
      };
      
      OutputLine.prototype.last = function() {
        if (!this.is_empty()) {
          return this.__items[this.__items.length - 1];
        } else {
          return null;
        }
      };
      
      OutputLine.prototype.push = function(item) {
        this.__items.push(item);
        var last_newline_index = item.lastIndexOf('\n');
        if (last_newline_index !== -1) {
          this.__character_count = item.length - last_newline_index;
        } else {
          this.__character_count += item.length;
        }
      };
      
      OutputLine.prototype.pop = function() {
        var item = null;
        if (!this.is_empty()) {
          item = this.__items.pop();
          this.__character_count -= item.length;
        }
        return item;
      };
      
      
      OutputLine.prototype._remove_indent = function() {
        if (this.__indent_count > 0) {
          this.__indent_count -= 1;
          this.__character_count -= this.__parent.indent_size;
        }
      };
      
      OutputLine.prototype._remove_wrap_indent = function() {
        if (this.__wrap_point_indent_count > 0) {
          this.__wrap_point_indent_count -= 1;
        }
      };
      OutputLine.prototype.trim = function() {
        while (this.last() === ' ') {
          this.__items.pop();
          this.__character_count -= 1;
        }
      };
      
      OutputLine.prototype.toString = function() {
        var result = '';
        if (this.is_empty()) {
          if (this.__parent.indent_empty_lines) {
            result = this.__parent.get_indent_string(this.__indent_count);
          }
        } else {
          result = this.__parent.get_indent_string(this.__indent_count, this.__alignment_count);
          result += this.__items.join('');
        }
        return result;
      };
      
      function IndentStringCache(options, baseIndentString) {
        this.__cache = [''];
        this.__indent_size = options.indent_size;
        this.__indent_string = options.indent_char;
        if (!options.indent_with_tabs) {
          this.__indent_string = new Array(options.indent_size + 1).join(options.indent_char);
        }
      
        // Set to null to continue support for auto detection of base indent
        baseIndentString = baseIndentString || '';
        if (options.indent_level > 0) {
          baseIndentString = new Array(options.indent_level + 1).join(this.__indent_string);
        }
      
        this.__base_string = baseIndentString;
        this.__base_string_length = baseIndentString.length;
      }
      
      IndentStringCache.prototype.get_indent_size = function(indent, column) {
        var result = this.__base_string_length;
        column = column || 0;
        if (indent < 0) {
          result = 0;
        }
        result += indent * this.__indent_size;
        result += column;
        return result;
      };
      
      IndentStringCache.prototype.get_indent_string = function(indent_level, column) {
        var result = this.__base_string;
        column = column || 0;
        if (indent_level < 0) {
          indent_level = 0;
          result = '';
        }
        column += indent_level * this.__indent_size;
        this.__ensure_cache(column);
        result += this.__cache[column];
        return result;
      };
      
      IndentStringCache.prototype.__ensure_cache = function(column) {
        while (column >= this.__cache.length) {
          this.__add_column();
        }
      };
      
      IndentStringCache.prototype.__add_column = function() {
        var column = this.__cache.length;
        var indent = 0;
        var result = '';
        if (this.__indent_size && column >= this.__indent_size) {
          indent = Math.floor(column / this.__indent_size);
          column -= indent * this.__indent_size;
          result = new Array(indent + 1).join(this.__indent_string);
        }
        if (column) {
          result += new Array(column + 1).join(' ');
        }
      
        this.__cache.push(result);
      };
      
      function Output(options, baseIndentString) {
        this.__indent_cache = new IndentStringCache(options, baseIndentString);
        this.raw = false;
        this._end_with_newline = options.end_with_newline;
        this.indent_size = options.indent_size;
        this.wrap_line_length = options.wrap_line_length;
        this.indent_empty_lines = options.indent_empty_lines;
        this.__lines = [];
        this.previous_line = null;
        this.current_line = null;
        this.next_line = new OutputLine(this);
        this.space_before_token = false;
        this.non_breaking_space = false;
        this.previous_token_wrapped = false;
        // initialize
        this.__add_outputline();
      }
      
      Output.prototype.__add_outputline = function() {
        this.previous_line = this.current_line;
        this.current_line = this.next_line.clone_empty();
        this.__lines.push(this.current_line);
      };
      
      Output.prototype.get_line_number = function() {
        return this.__lines.length;
      };
      
      Output.prototype.get_indent_string = function(indent, column) {
        return this.__indent_cache.get_indent_string(indent, column);
      };
      
      Output.prototype.get_indent_size = function(indent, column) {
        return this.__indent_cache.get_indent_size(indent, column);
      };
      
      Output.prototype.is_empty = function() {
        return !this.previous_line && this.current_line.is_empty();
      };
      
      Output.prototype.add_new_line = function(force_newline) {
        // never newline at the start of file
        // otherwise, newline only if we didn't just add one or we're forced
        if (this.is_empty() ||
          (!force_newline && this.just_added_newline())) {
          return false;
        }
      
        // if raw output is enabled, don't print additional newlines,
        // but still return True as though you had
        if (!this.raw) {
          this.__add_outputline();
        }
        return true;
      };
      
      Output.prototype.get_code = function(eol) {
        this.trim(true);
      
        // handle some edge cases where the last tokens
        // has text that ends with newline(s)
        var last_item = this.current_line.pop();
        if (last_item) {
          if (last_item[last_item.length - 1] === '\n') {
            last_item = last_item.replace(/\n+$/g, '');
          }
          this.current_line.push(last_item);
        }
      
        if (this._end_with_newline) {
          this.__add_outputline();
        }
      
        var sweet_code = this.__lines.join('\n');
      
        if (eol !== '\n') {
          sweet_code = sweet_code.replace(/[\n]/g, eol);
        }
        return sweet_code;
      };
      
      Output.prototype.set_wrap_point = function() {
        this.current_line._set_wrap_point();
      };
      
      Output.prototype.set_indent = function(indent, alignment) {
        indent = indent || 0;
        alignment = alignment || 0;
      
        // Next line stores alignment values
        this.next_line.set_indent(indent, alignment);
      
        // Never indent your first output indent at the start of the file
        if (this.__lines.length > 1) {
          this.current_line.set_indent(indent, alignment);
          return true;
        }
      
        this.current_line.set_indent();
        return false;
      };
      
      Output.prototype.add_raw_token = function(token) {
        for (var x = 0; x < token.newlines; x++) {
          this.__add_outputline();
        }
        this.current_line.set_indent(-1);
        this.current_line.push(token.whitespace_before);
        this.current_line.push(token.text);
        this.space_before_token = false;
        this.non_breaking_space = false;
        this.previous_token_wrapped = false;
      };
      
      Output.prototype.add_token = function(printable_token) {
        this.__add_space_before_token();
        this.current_line.push(printable_token);
        this.space_before_token = false;
        this.non_breaking_space = false;
        this.previous_token_wrapped = this.current_line._allow_wrap();
      };
      
      Output.prototype.__add_space_before_token = function() {
        if (this.space_before_token && !this.just_added_newline()) {
          if (!this.non_breaking_space) {
            this.set_wrap_point();
          }
          this.current_line.push(' ');
        }
      };
      
      Output.prototype.remove_indent = function(index) {
        var output_length = this.__lines.length;
        while (index < output_length) {
          this.__lines[index]._remove_indent();
          index++;
        }
        this.current_line._remove_wrap_indent();
      };
      
      Output.prototype.trim = function(eat_newlines) {
        eat_newlines = (eat_newlines === undefined) ? false : eat_newlines;
      
        this.current_line.trim();
      
        while (eat_newlines && this.__lines.length > 1 &&
          this.current_line.is_empty()) {
          this.__lines.pop();
          this.current_line = this.__lines[this.__lines.length - 1];
          this.current_line.trim();
        }
      
        this.previous_line = this.__lines.length > 1 ?
          this.__lines[this.__lines.length - 2] : null;
      };
      
      Output.prototype.just_added_newline = function() {
        return this.current_line.is_empty();
      };
      
      Output.prototype.just_added_blankline = function() {
        return this.is_empty() ||
          (this.current_line.is_empty() && this.previous_line.is_empty());
      };
      
      Output.prototype.ensure_empty_line_above = function(starts_with, ends_with) {
        var index = this.__lines.length - 2;
        while (index >= 0) {
          var potentialEmptyLine = this.__lines[index];
          if (potentialEmptyLine.is_empty()) {
            break;
          } else if (potentialEmptyLine.item(0).indexOf(starts_with) !== 0 &&
            potentialEmptyLine.item(-1) !== ends_with) {
            this.__lines.splice(index + 1, 0, new OutputLine(this));
            this.previous_line = this.__lines[this.__lines.length - 2];
            break;
          }
          index--;
        }
      };
      
      module.exports.Output = Output;
      
      
      /***/ }),
      /* 3 */,
      /* 4 */,
      /* 5 */,
      /* 6 */
      /***/ (function(module) {
      
      /*jshint node:true */
      /*
      
        The MIT License (MIT)
      
        Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
      
        Permission 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:
      
        The above copyright notice and this permission notice shall be
        included in all copies or substantial portions of the Software.
      
        THE 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.
      */
      
      
      
      function Options(options, merge_child_field) {
        this.raw_options = _mergeOpts(options, merge_child_field);
      
        // Support passing the source text back with no change
        this.disabled = this._get_boolean('disabled');
      
        this.eol = this._get_characters('eol', 'auto');
        this.end_with_newline = this._get_boolean('end_with_newline');
        this.indent_size = this._get_number('indent_size', 4);
        this.indent_char = this._get_characters('indent_char', ' ');
        this.indent_level = this._get_number('indent_level');
      
        this.preserve_newlines = this._get_boolean('preserve_newlines', true);
        this.max_preserve_newlines = this._get_number('max_preserve_newlines', 32786);
        if (!this.preserve_newlines) {
          this.max_preserve_newlines = 0;
        }
      
        this.indent_with_tabs = this._get_boolean('indent_with_tabs', this.indent_char === '\t');
        if (this.indent_with_tabs) {
          this.indent_char = '\t';
      
          // indent_size behavior changed after 1.8.6
          // It used to be that indent_size would be
          // set to 1 for indent_with_tabs. That is no longer needed and
          // actually doesn't make sense - why not use spaces? Further,
          // that might produce unexpected behavior - tabs being used
          // for single-column alignment. So, when indent_with_tabs is true
          // and indent_size is 1, reset indent_size to 4.
          if (this.indent_size === 1) {
            this.indent_size = 4;
          }
        }
      
        // Backwards compat with 1.3.x
        this.wrap_line_length = this._get_number('wrap_line_length', this._get_number('max_char'));
      
        this.indent_empty_lines = this._get_boolean('indent_empty_lines');
      
        // valid templating languages ['django', 'erb', 'handlebars', 'php', 'smarty']
        // For now, 'auto' = all off for javascript, all on for html (and inline javascript).
        // other values ignored
        this.templating = this._get_selection_list('templating', ['auto', 'none', 'django', 'erb', 'handlebars', 'php', 'smarty'], ['auto']);
      }
      
      Options.prototype._get_array = function(name, default_value) {
        var option_value = this.raw_options[name];
        var result = default_value || [];
        if (typeof option_value === 'object') {
          if (option_value !== null && typeof option_value.concat === 'function') {
            result = option_value.concat();
          }
        } else if (typeof option_value === 'string') {
          result = option_value.split(/[^a-zA-Z0-9_\/\-]+/);
        }
        return result;
      };
      
      Options.prototype._get_boolean = function(name, default_value) {
        var option_value = this.raw_options[name];
        var result = option_value === undefined ? !!default_value : !!option_value;
        return result;
      };
      
      Options.prototype._get_characters = function(name, default_value) {
        var option_value = this.raw_options[name];
        var result = default_value || '';
        if (typeof option_value === 'string') {
          result = option_value.replace(/\\r/, '\r').replace(/\\n/, '\n').replace(/\\t/, '\t');
        }
        return result;
      };
      
      Options.prototype._get_number = function(name, default_value) {
        var option_value = this.raw_options[name];
        default_value = parseInt(default_value, 10);
        if (isNaN(default_value)) {
          default_value = 0;
        }
        var result = parseInt(option_value, 10);
        if (isNaN(result)) {
          result = default_value;
        }
        return result;
      };
      
      Options.prototype._get_selection = function(name, selection_list, default_value) {
        var result = this._get_selection_list(name, selection_list, default_value);
        if (result.length !== 1) {
          throw new Error(
            "Invalid Option Value: The option '" + name + "' can only be one of the following values:\n" +
            selection_list + "\nYou passed in: '" + this.raw_options[name] + "'");
        }
      
        return result[0];
      };
      
      
      Options.prototype._get_selection_list = function(name, selection_list, default_value) {
        if (!selection_list || selection_list.length === 0) {
          throw new Error("Selection list cannot be empty.");
        }
      
        default_value = default_value || [selection_list[0]];
        if (!this._is_valid_selection(default_value, selection_list)) {
          throw new Error("Invalid Default Value!");
        }
      
        var result = this._get_array(name, default_value);
        if (!this._is_valid_selection(result, selection_list)) {
          throw new Error(
            "Invalid Option Value: The option '" + name + "' can contain only the following values:\n" +
            selection_list + "\nYou passed in: '" + this.raw_options[name] + "'");
        }
      
        return result;
      };
      
      Options.prototype._is_valid_selection = function(result, selection_list) {
        return result.length && selection_list.length &&
          !result.some(function(item) { return selection_list.indexOf(item) === -1; });
      };
      
      
      // merges child options up with the parent options object
      // Example: obj = {a: 1, b: {a: 2}}
      //          mergeOpts(obj, 'b')
      //
      //          Returns: {a: 2}
      function _mergeOpts(allOptions, childFieldName) {
        var finalOpts = {};
        allOptions = _normalizeOpts(allOptions);
        var name;
      
        for (name in allOptions) {
          if (name !== childFieldName) {
            finalOpts[name] = allOptions[name];
          }
        }
      
        //merge in the per type settings for the childFieldName
        if (childFieldName && allOptions[childFieldName]) {
          for (name in allOptions[childFieldName]) {
            finalOpts[name] = allOptions[childFieldName][name];
          }
        }
        return finalOpts;
      }
      
      function _normalizeOpts(options) {
        var convertedOpts = {};
        var key;
      
        for (key in options) {
          var newKey = key.replace(/-/g, "_");
          convertedOpts[newKey] = options[key];
        }
        return convertedOpts;
      }
      
      module.exports.Options = Options;
      module.exports.normalizeOpts = _normalizeOpts;
      module.exports.mergeOpts = _mergeOpts;
      
      
      /***/ }),
      /* 7 */,
      /* 8 */
      /***/ (function(module) {
      
      /*jshint node:true */
      /*
      
        The MIT License (MIT)
      
        Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
      
        Permission 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:
      
        The above copyright notice and this permission notice shall be
        included in all copies or substantial portions of the Software.
      
        THE 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.
      */
      
      
      
      var regexp_has_sticky = RegExp.prototype.hasOwnProperty('sticky');
      
      function InputScanner(input_string) {
        this.__input = input_string || '';
        this.__input_length = this.__input.length;
        this.__position = 0;
      }
      
      InputScanner.prototype.restart = function() {
        this.__position = 0;
      };
      
      InputScanner.prototype.back = function() {
        if (this.__position > 0) {
          this.__position -= 1;
        }
      };
      
      InputScanner.prototype.hasNext = function() {
        return this.__position < this.__input_length;
      };
      
      InputScanner.prototype.next = function() {
        var val = null;
        if (this.hasNext()) {
          val = this.__input.charAt(this.__position);
          this.__position += 1;
        }
        return val;
      };
      
      InputScanner.prototype.peek = function(index) {
        var val = null;
        index = index || 0;
        index += this.__position;
        if (index >= 0 && index < this.__input_length) {
          val = this.__input.charAt(index);
        }
        return val;
      };
      
      // This is a JavaScript only helper function (not in python)
      // Javascript doesn't have a match method
      // and not all implementation support "sticky" flag.
      // If they do not support sticky then both this.match() and this.test() method
      // must get the match and check the index of the match.
      // If sticky is supported and set, this method will use it.
      // Otherwise it will check that global is set, and fall back to the slower method.
      InputScanner.prototype.__match = function(pattern, index) {
        pattern.lastIndex = index;
        var pattern_match = pattern.exec(this.__input);
      
        if (pattern_match && !(regexp_has_sticky && pattern.sticky)) {
          if (pattern_match.index !== index) {
            pattern_match = null;
          }
        }
      
        return pattern_match;
      };
      
      InputScanner.prototype.test = function(pattern, index) {
        index = index || 0;
        index += this.__position;
      
        if (index >= 0 && index < this.__input_length) {
          return !!this.__match(pattern, index);
        } else {
          return false;
        }
      };
      
      InputScanner.prototype.testChar = function(pattern, index) {
        // test one character regex match
        var val = this.peek(index);
        pattern.lastIndex = 0;
        return val !== null && pattern.test(val);
      };
      
      InputScanner.prototype.match = function(pattern) {
        var pattern_match = this.__match(pattern, this.__position);
        if (pattern_match) {
          this.__position += pattern_match[0].length;
        } else {
          pattern_match = null;
        }
        return pattern_match;
      };
      
      InputScanner.prototype.read = function(starting_pattern, until_pattern, until_after) {
        var val = '';
        var match;
        if (starting_pattern) {
          match = this.match(starting_pattern);
          if (match) {
            val += match[0];
          }
        }
        if (until_pattern && (match || !starting_pattern)) {
          val += this.readUntil(until_pattern, until_after);
        }
        return val;
      };
      
      InputScanner.prototype.readUntil = function(pattern, until_after) {
        var val = '';
        var match_index = this.__position;
        pattern.lastIndex = this.__position;
        var pattern_match = pattern.exec(this.__input);
        if (pattern_match) {
          match_index = pattern_match.index;
          if (until_after) {
            match_index += pattern_match[0].length;
          }
        } else {
          match_index = this.__input_length;
        }
      
        val = this.__input.substring(this.__position, match_index);
        this.__position = match_index;
        return val;
      };
      
      InputScanner.prototype.readUntilAfter = function(pattern) {
        return this.readUntil(pattern, true);
      };
      
      InputScanner.prototype.get_regexp = function(pattern, match_from) {
        var result = null;
        var flags = 'g';
        if (match_from && regexp_has_sticky) {
          flags = 'y';
        }
        // strings are converted to regexp
        if (typeof pattern === "string" && pattern !== '') {
          // result = new RegExp(pattern.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), flags);
          result = new RegExp(pattern, flags);
        } else if (pattern) {
          result = new RegExp(pattern.source, flags);
        }
        return result;
      };
      
      InputScanner.prototype.get_literal_regexp = function(literal_string) {
        return RegExp(literal_string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'));
      };
      
      /* css beautifier legacy helpers */
      InputScanner.prototype.peekUntilAfter = function(pattern) {
        var start = this.__position;
        var val = this.readUntilAfter(pattern);
        this.__position = start;
        return val;
      };
      
      InputScanner.prototype.lookBack = function(testVal) {
        var start = this.__position - 1;
        return start >= testVal.length && this.__input.substring(start - testVal.length, start)
          .toLowerCase() === testVal;
      };
      
      module.exports.InputScanner = InputScanner;
      
      
      /***/ }),
      /* 9 */,
      /* 10 */,
      /* 11 */,
      /* 12 */,
      /* 13 */
      /***/ (function(module) {
      
      /*jshint node:true */
      /*
      
        The MIT License (MIT)
      
        Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
      
        Permission 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:
      
        The above copyright notice and this permission notice shall be
        included in all copies or substantial portions of the Software.
      
        THE 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.
      */
      
      
      
      function Directives(start_block_pattern, end_block_pattern) {
        start_block_pattern = typeof start_block_pattern === 'string' ? start_block_pattern : start_block_pattern.source;
        end_block_pattern = typeof end_block_pattern === 'string' ? end_block_pattern : end_block_pattern.source;
        this.__directives_block_pattern = new RegExp(start_block_pattern + / beautify( \w+[:]\w+)+ /.source + end_block_pattern, 'g');
        this.__directive_pattern = / (\w+)[:](\w+)/g;
      
        this.__directives_end_ignore_pattern = new RegExp(start_block_pattern + /\sbeautify\signore:end\s/.source + end_block_pattern, 'g');
      }
      
      Directives.prototype.get_directives = function(text) {
        if (!text.match(this.__directives_block_pattern)) {
          return null;
        }
      
        var directives = {};
        this.__directive_pattern.lastIndex = 0;
        var directive_match = this.__directive_pattern.exec(text);
      
        while (directive_match) {
          directives[directive_match[1]] = directive_match[2];
          directive_match = this.__directive_pattern.exec(text);
        }
      
        return directives;
      };
      
      Directives.prototype.readIgnored = function(input) {
        return input.readUntilAfter(this.__directives_end_ignore_pattern);
      };
      
      
      module.exports.Directives = Directives;
      
      
      /***/ }),
      /* 14 */,
      /* 15 */
      /***/ (function(module, __unused_webpack_exports, __webpack_require__) {
      
      /*jshint node:true */
      /*
      
        The MIT License (MIT)
      
        Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
      
        Permission 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:
      
        The above copyright notice and this permission notice shall be
        included in all copies or substantial portions of the Software.
      
        THE 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.
      */
      
      
      
      var Beautifier = (__webpack_require__(16).Beautifier),
        Options = (__webpack_require__(17).Options);
      
      function css_beautify(source_text, options) {
        var beautifier = new Beautifier(source_text, options);
        return beautifier.beautify();
      }
      
      module.exports = css_beautify;
      module.exports.defaultOptions = function() {
        return new Options();
      };
      
      
      /***/ }),
      /* 16 */
      /***/ (function(module, __unused_webpack_exports, __webpack_require__) {
      
      /*jshint node:true */
      /*
      
        The MIT License (MIT)
      
        Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
      
        Permission 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:
      
        The above copyright notice and this permission notice shall be
        included in all copies or substantial portions of the Software.
      
        THE 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.
      */
      
      
      
      var Options = (__webpack_require__(17).Options);
      var Output = (__webpack_require__(2).Output);
      var InputScanner = (__webpack_require__(8).InputScanner);
      var Directives = (__webpack_require__(13).Directives);
      
      var directives_core = new Directives(/\/\*/, /\*\//);
      
      var lineBreak = /\r\n|[\r\n]/;
      var allLineBreaks = /\r\n|[\r\n]/g;
      
      // tokenizer
      var whitespaceChar = /\s/;
      var whitespacePattern = /(?:\s|\n)+/g;
      var block_comment_pattern = /\/\*(?:[\s\S]*?)((?:\*\/)|$)/g;
      var comment_pattern = /\/\/(?:[^\n\r\u2028\u2029]*)/g;
      
      function Beautifier(source_text, options) {
        this._source_text = source_text || '';
        // Allow the setting of language/file-type specific options
        // with inheritance of overall settings
        this._options = new Options(options);
        this._ch = null;
        this._input = null;
      
        // https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule
        this.NESTED_AT_RULE = {
          "@page": true,
          "@font-face": true,
          "@keyframes": true,
          // also in CONDITIONAL_GROUP_RULE below
          "@media": true,
          "@supports": true,
          "@document": true
        };
        this.CONDITIONAL_GROUP_RULE = {
          "@media": true,
          "@supports": true,
          "@document": true
        };
        this.NON_SEMICOLON_NEWLINE_PROPERTY = [
          "grid-template-areas",
          "grid-template"
        ];
      
      }
      
      Beautifier.prototype.eatString = function(endChars) {
        var result = '';
        this._ch = this._input.next();
        while (this._ch) {
          result += this._ch;
          if (this._ch === "\\") {
            result += this._input.next();
          } else if (endChars.indexOf(this._ch) !== -1 || this._ch === "\n") {
            break;
          }
          this._ch = this._input.next();
        }
        return result;
      };
      
      // Skips any white space in the source text from the current position.
      // When allowAtLeastOneNewLine is true, will output new lines for each
      // newline character found; if the user has preserve_newlines off, only
      // the first newline will be output
      Beautifier.prototype.eatWhitespace = function(allowAtLeastOneNewLine) {
        var result = whitespaceChar.test(this._input.peek());
        var newline_count = 0;
        while (whitespaceChar.test(this._input.peek())) {
          this._ch = this._input.next();
          if (allowAtLeastOneNewLine && this._ch === '\n') {
            if (newline_count === 0 || newline_count < this._options.max_preserve_newlines) {
              newline_count++;
              this._output.add_new_line(true);
            }
          }
        }
        return result;
      };
      
      // Nested pseudo-class if we are insideRule
      // and the next special character found opens
      // a new block
      Beautifier.prototype.foundNestedPseudoClass = function() {
        var openParen = 0;
        var i = 1;
        var ch = this._input.peek(i);
        while (ch) {
          if (ch === "{") {
            return true;
          } else if (ch === '(') {
            // pseudoclasses can contain ()
            openParen += 1;
          } else if (ch === ')') {
            if (openParen === 0) {
              return false;
            }
            openParen -= 1;
          } else if (ch === ";" || ch === "}") {
            return false;
          }
          i++;
          ch = this._input.peek(i);
        }
        return false;
      };
      
      Beautifier.prototype.print_string = function(output_string) {
        this._output.set_indent(this._indentLevel);
        this._output.non_breaking_space = true;
        this._output.add_token(output_string);
      };
      
      Beautifier.prototype.preserveSingleSpace = function(isAfterSpace) {
        if (isAfterSpace) {
          this._output.space_before_token = true;
        }
      };
      
      Beautifier.prototype.indent = function() {
        this._indentLevel++;
      };
      
      Beautifier.prototype.outdent = function() {
        if (this._indentLevel > 0) {
          this._indentLevel--;
        }
      };
      
      /*_____________________--------------------_____________________*/
      
      Beautifier.prototype.beautify = function() {
        if (this._options.disabled) {
          return this._source_text;
        }
      
        var source_text = this._source_text;
        var eol = this._options.eol;
        if (eol === 'auto') {
          eol = '\n';
          if (source_text && lineBreak.test(source_text || '')) {
            eol = source_text.match(lineBreak)[0];
          }
        }
      
      
        // HACK: newline parsing inconsistent. This brute force normalizes the this._input.
        source_text = source_text.replace(allLineBreaks, '\n');
      
        // reset
        var baseIndentString = source_text.match(/^[\t ]*/)[0];
      
        this._output = new Output(this._options, baseIndentString);
        this._input = new InputScanner(source_text);
        this._indentLevel = 0;
        this._nestedLevel = 0;
      
        this._ch = null;
        var parenLevel = 0;
      
        var insideRule = false;
        // This is the value side of a property value pair (blue in the following ex)
        // label { content: blue }
        var insidePropertyValue = false;
        var enteringConditionalGroup = false;
        var insideAtExtend = false;
        var insideAtImport = false;
        var insideScssMap = false;
        var topCharacter = this._ch;
        var insideNonSemiColonValues = false;
        var whitespace;
        var isAfterSpace;
        var previous_ch;
      
        while (true) {
          whitespace = this._input.read(whitespacePattern);
          isAfterSpace = whitespace !== '';
          previous_ch = topCharacter;
          this._ch = this._input.next();
          if (this._ch === '\\' && this._input.hasNext()) {
            this._ch += this._input.next();
          }
          topCharacter = this._ch;
      
          if (!this._ch) {
            break;
          } else if (this._ch === '/' && this._input.peek() === '*') {
            // /* css comment */
            // Always start block comments on a new line.
            // This handles scenarios where a block comment immediately
            // follows a property definition on the same line or where
            // minified code is being beautified.
            this._output.add_new_line();
            this._input.back();
      
            var comment = this._input.read(block_comment_pattern);
      
            // Handle ignore directive
            var directives = directives_core.get_directives(comment);
            if (directives && directives.ignore === 'start') {
              comment += directives_core.readIgnored(this._input);
            }
      
            this.print_string(comment);
      
            // Ensures any new lines following the comment are preserved
            this.eatWhitespace(true);
      
            // Block comments are followed by a new line so they don't
            // share a line with other properties
            this._output.add_new_line();
          } else if (this._ch === '/' && this._input.peek() === '/') {
            // // single line comment
            // Preserves the space before a comment
            // on the same line as a rule
            this._output.space_before_token = true;
            this._input.back();
            this.print_string(this._input.read(comment_pattern));
      
            // Ensures any new lines following the comment are preserved
            this.eatWhitespace(true);
          } else if (this._ch === '@' || this._ch === '$') {
            this.preserveSingleSpace(isAfterSpace);
      
            // deal with less propery mixins @{...}
            if (this._input.peek() === '{') {
              this.print_string(this._ch + this.eatString('}'));
            } else {
              this.print_string(this._ch);
      
              // strip trailing space, if present, for hash property checks
              var variableOrRule = this._input.peekUntilAfter(/[: ,;{}()[\]\/='"]/g);
      
              if (variableOrRule.match(/[ :]$/)) {
                // we have a variable or pseudo-class, add it and insert one space before continuing
                variableOrRule = this.eatString(": ").replace(/\s$/, '');
                this.print_string(variableOrRule);
                this._output.space_before_token = true;
              }
      
              variableOrRule = variableOrRule.replace(/\s$/, '');
      
              if (variableOrRule === 'extend') {
                insideAtExtend = true;
              } else if (variableOrRule === 'import') {
                insideAtImport = true;
              }
      
              // might be a nesting at-rule
              if (variableOrRule in this.NESTED_AT_RULE) {
                this._nestedLevel += 1;
                if (variableOrRule in this.CONDITIONAL_GROUP_RULE) {
                  enteringConditionalGroup = true;
                }
                // might be less variable
              } else if (!insideRule && parenLevel === 0 && variableOrRule.indexOf(':') !== -1) {
                insidePropertyValue = true;
                this.indent();
              }
            }
          } else if (this._ch === '#' && this._input.peek() === '{') {
            this.preserveSingleSpace(isAfterSpace);
            this.print_string(this._ch + this.eatString('}'));
          } else if (this._ch === '{') {
            if (insidePropertyValue) {
              insidePropertyValue = false;
              this.outdent();
            }
      
            // when entering conditional groups, only rulesets are allowed
            if (enteringConditionalGroup) {
              enteringConditionalGroup = false;
              insideRule = (this._indentLevel >= this._nestedLevel);
            } else {
              // otherwise, declarations are also allowed
              insideRule = (this._indentLevel >= this._nestedLevel - 1);
            }
            if (this._options.newline_between_rules && insideRule) {
              if (this._output.previous_line && this._output.previous_line.item(-1) !== '{') {
                this._output.ensure_empty_line_above('/', ',');
              }
            }
      
            this._output.space_before_token = true;
      
            // The difference in print_string and indent order is necessary to indent the '{' correctly
            if (this._options.brace_style === 'expand') {
              this._output.add_new_line();
              this.print_string(this._ch);
              this.indent();
              this._output.set_indent(this._indentLevel);
            } else {
              // inside mixin and first param is object
              if (previous_ch === '(') {
                this._output.space_before_token = false;
              } else if (previous_ch !== ',') {
                this.indent();
              }
              this.print_string(this._ch);
            }
      
            this.eatWhitespace(true);
            this._output.add_new_line();
          } else if (this._ch === '}') {
            this.outdent();
            this._output.add_new_line();
            if (previous_ch === '{') {
              this._output.trim(true);
            }
            insideAtImport = false;
            insideAtExtend = false;
            if (insidePropertyValue) {
              this.outdent();
              insidePropertyValue = false;
            }
            this.print_string(this._ch);
            insideRule = false;
            if (this._nestedLevel) {
              this._nestedLevel--;
            }
      
            this.eatWhitespace(true);
            this._output.add_new_line();
      
            if (this._options.newline_between_rules && !this._output.just_added_blankline()) {
              if (this._input.peek() !== '}') {
                this._output.add_new_line(true);
              }
            }
            if (this._input.peek() === ')') {
              this._output.trim(true);
              if (this._options.brace_style === "expand") {
                this._output.add_new_line(true);
              }
            }
          } else if (this._ch === ":") {
      
            for (var i = 0; i < this.NON_SEMICOLON_NEWLINE_PROPERTY.length; i++) {
              if (this._input.lookBack(this.NON_SEMICOLON_NEWLINE_PROPERTY[i])) {
                insideNonSemiColonValues = true;
                break;
              }
            }
      
            if ((insideRule || enteringConditionalGroup) && !(this._input.lookBack("&") || this.foundNestedPseudoClass()) && !this._input.lookBack("(") && !insideAtExtend && parenLevel === 0) {
              // 'property: value' delimiter
              // which could be in a conditional group query
              this.print_string(':');
              if (!insidePropertyValue) {
                insidePropertyValue = true;
                this._output.space_before_token = true;
                this.eatWhitespace(true);
                this.indent();
              }
            } else {
              // sass/less parent reference don't use a space
              // sass nested pseudo-class don't use a space
      
              // preserve space before pseudoclasses/pseudoelements, as it means "in any child"
              if (this._input.lookBack(" ")) {
                this._output.space_before_token = true;
              }
              if (this._input.peek() === ":") {
                // pseudo-element
                this._ch = this._input.next();
                this.print_string("::");
              } else {
                // pseudo-class
                this.print_string(':');
              }
            }
          } else if (this._ch === '"' || this._ch === '\'') {
            var preserveQuoteSpace = previous_ch === '"' || previous_ch === '\'';
            this.preserveSingleSpace(preserveQuoteSpace || isAfterSpace);
            this.print_string(this._ch + this.eatString(this._ch));
            this.eatWhitespace(true);
          } else if (this._ch === ';') {
            insideNonSemiColonValues = false;
            if (parenLevel === 0) {
              if (insidePropertyValue) {
                this.outdent();
                insidePropertyValue = false;
              }
              insideAtExtend = false;
              insideAtImport = false;
              this.print_string(this._ch);
              this.eatWhitespace(true);
      
              // This maintains single line comments on the same
              // line. Block comments are also affected, but
              // a new line is always output before one inside
              // that section
              if (this._input.peek() !== '/') {
                this._output.add_new_line();
              }
            } else {
              this.print_string(this._ch);
              this.eatWhitespace(true);
              this._output.space_before_token = true;
            }
          } else if (this._ch === '(') { // may be a url
            if (this._input.lookBack("url")) {
              this.print_string(this._ch);
              this.eatWhitespace();
              parenLevel++;
              this.indent();
              this._ch = this._input.next();
              if (this._ch === ')' || this._ch === '"' || this._ch === '\'') {
                this._input.back();
              } else if (this._ch) {
                this.print_string(this._ch + this.eatString(')'));
                if (parenLevel) {
                  parenLevel--;
                  this.outdent();
                }
              }
            } else {
              var space_needed = false;
              if (this._input.lookBack("with")) {
                // look back is not an accurate solution, we need tokens to confirm without whitespaces
                space_needed = true;
              }
              this.preserveSingleSpace(isAfterSpace || space_needed);
              this.print_string(this._ch);
      
              // handle scss/sass map
              if (insidePropertyValue && previous_ch === "$" && this._options.selector_separator_newline) {
                this._output.add_new_line();
                insideScssMap = true;
              } else {
                this.eatWhitespace();
                parenLevel++;
                this.indent();
              }
            }
          } else if (this._ch === ')') {
            if (parenLevel) {
              parenLevel--;
              this.outdent();
            }
            if (insideScssMap && this._input.peek() === ";" && this._options.selector_separator_newline) {
              insideScssMap = false;
              this.outdent();
              this._output.add_new_line();
            }
            this.print_string(this._ch);
          } else if (this._ch === ',') {
            this.print_string(this._ch);
            this.eatWhitespace(true);
            if (this._options.selector_separator_newline && (!insidePropertyValue || insideScssMap) && parenLevel === 0 && !insideAtImport && !insideAtExtend) {
              this._output.add_new_line();
            } else {
              this._output.space_before_token = true;
            }
          } else if ((this._ch === '>' || this._ch === '+' || this._ch === '~') && !insidePropertyValue && parenLevel === 0) {
            //handle combinator spacing
            if (this._options.space_around_combinator) {
              this._output.space_before_token = true;
              this.print_string(this._ch);
              this._output.space_before_token = true;
            } else {
              this.print_string(this._ch);
              this.eatWhitespace();
              // squash extra whitespace
              if (this._ch && whitespaceChar.test(this._ch)) {
                this._ch = '';
              }
            }
          } else if (this._ch === ']') {
            this.print_string(this._ch);
          } else if (this._ch === '[') {
            this.preserveSingleSpace(isAfterSpace);
            this.print_string(this._ch);
          } else if (this._ch === '=') { // no whitespace before or after
            this.eatWhitespace();
            this.print_string('=');
            if (whitespaceChar.test(this._ch)) {
              this._ch = '';
            }
          } else if (this._ch === '!' && !this._input.lookBack("\\")) { // !important
            this._output.space_before_token = true;
            this.print_string(this._ch);
          } else {
            var preserveAfterSpace = previous_ch === '"' || previous_ch === '\'';
            this.preserveSingleSpace(preserveAfterSpace || isAfterSpace);
            this.print_string(this._ch);
      
            if (!this._output.just_added_newline() && this._input.peek() === '\n' && insideNonSemiColonValues) {
              this._output.add_new_line();
            }
          }
        }
      
        var sweetCode = this._output.get_code(eol);
      
        return sweetCode;
      };
      
      module.exports.Beautifier = Beautifier;
      
      
      /***/ }),
      /* 17 */
      /***/ (function(module, __unused_webpack_exports, __webpack_require__) {
      
      /*jshint node:true */
      /*
      
        The MIT License (MIT)
      
        Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
      
        Permission 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:
      
        The above copyright notice and this permission notice shall be
        included in all copies or substantial portions of the Software.
      
        THE 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.
      */
      
      
      
      var BaseOptions = (__webpack_require__(6).Options);
      
      function Options(options) {
        BaseOptions.call(this, options, 'css');
      
        this.selector_separator_newline = this._get_boolean('selector_separator_newline', true);
        this.newline_between_rules = this._get_boolean('newline_between_rules', true);
        var space_around_selector_separator = this._get_boolean('space_around_selector_separator');
        this.space_around_combinator = this._get_boolean('space_around_combinator') || space_around_selector_separator;
      
        var brace_style_split = this._get_selection_list('brace_style', ['collapse', 'expand', 'end-expand', 'none', 'preserve-inline']);
        this.brace_style = 'collapse';
        for (var bs = 0; bs < brace_style_split.length; bs++) {
          if (brace_style_split[bs] !== 'expand') {
            // default to collapse, as only collapse|expand is implemented for now
            this.brace_style = 'collapse';
          } else {
            this.brace_style = brace_style_split[bs];
          }
        }
      }
      Options.prototype = new BaseOptions();
      
      
      
      module.exports.Options = Options;
      
      
      /***/ })
      /******/ 	]);
      /************************************************************************/
      /******/ 	// The module cache
      /******/ 	var __webpack_module_cache__ = {};
      /******/ 	
      /******/ 	// The require function
      /******/ 	function __webpack_require__(moduleId) {
      /******/ 		// Check if module is in cache
      /******/ 		var cachedModule = __webpack_module_cache__[moduleId];
      /******/ 		if (cachedModule !== undefined) {
      /******/ 			return cachedModule.exports;
      /******/ 		}
      /******/ 		// Create a new module (and put it into the cache)
      /******/ 		var module = __webpack_module_cache__[moduleId] = {
      /******/ 			// no module.id needed
      /******/ 			// no module.loaded needed
      /******/ 			exports: {}
      /******/ 		};
      /******/ 	
      /******/ 		// Execute the module function
      /******/ 		__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
      /******/ 	
      /******/ 		// Return the exports of the module
      /******/ 		return module.exports;
      /******/ 	}
      /******/ 	
      /************************************************************************/
      /******/ 	
      /******/ 	// startup
      /******/ 	// Load entry module and return exports
      /******/ 	// This entry module is referenced by other modules so it can't be inlined
      /******/ 	var __webpack_exports__ = __webpack_require__(15);
      /******/ 	legacy_beautify_css = __webpack_exports__;
      /******/ 	
      /******/ })()
      ;
      var css_beautify = legacy_beautify_css;
      /* Footer */
      if (true) {
          // Add support for AMD ( https://github.com/amdjs/amdjs-api/wiki/AMD#defineamd-property- )
          !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function() {
              return {
                  css_beautify: css_beautify
              };
          }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
      				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
      } else {}
      
      }());
      
      
      /***/ }),
      
      /***/ "WaYH":
      /*!*********************************************************!*\
        !*** ./node_modules/rc-tree/es/TreeNode.js + 1 modules ***!
        \*********************************************************/
      /*! exports provided: InternalTreeNode, default */
      /*! exports used: default */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/classCallCheck.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/createClass.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/createSuper.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/defineProperty.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/inherits.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/objectSpread2.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/classnames/index.js (<- Module is not an ECMAScript module) */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-tree/es/contextTypes.js because of ./node_modules/rc-tree/es/Tree.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-tree/es/util.js because of ./node_modules/antd/es/table/hooks/useSelection.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-tree/es/utils/treeUtil.js because of ./node_modules/antd/es/table/hooks/useSelection.js */
      /*! ModuleConcatenation bailout: Cannot concat with external "window.React" (<- Module is not an ECMAScript module) */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      
      // UNUSED EXPORTS: InternalTreeNode
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/defineProperty.js
      var defineProperty = __webpack_require__("rePB");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js
      var objectWithoutProperties = __webpack_require__("Ff2n");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/objectSpread2.js
      var objectSpread2 = __webpack_require__("VTBJ");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/classCallCheck.js
      var classCallCheck = __webpack_require__("1OyB");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/createClass.js
      var createClass = __webpack_require__("vuIU");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js
      var assertThisInitialized = __webpack_require__("JX7q");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/inherits.js
      var inherits = __webpack_require__("Ji7U");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/createSuper.js + 1 modules
      var createSuper = __webpack_require__("LK+K");
      
      // EXTERNAL MODULE: external "window.React"
      var external_window_React_ = __webpack_require__("cDcd");
      
      // EXTERNAL MODULE: ./node_modules/classnames/index.js
      var classnames = __webpack_require__("TSYQ");
      var classnames_default = /*#__PURE__*/__webpack_require__.n(classnames);
      
      // EXTERNAL MODULE: ./node_modules/rc-tree/es/contextTypes.js
      var contextTypes = __webpack_require__("sboe");
      
      // EXTERNAL MODULE: ./node_modules/rc-tree/es/util.js
      var util = __webpack_require__("OZM5");
      
      // CONCATENATED MODULE: ./node_modules/rc-tree/es/Indent.js
      
      
      
      
      var Indent_Indent = function Indent(_ref) {
        var prefixCls = _ref.prefixCls,
            level = _ref.level,
            isStart = _ref.isStart,
            isEnd = _ref.isEnd;
      
        if (!level) {
          return null;
        }
      
        var baseClassName = "".concat(prefixCls, "-indent-unit");
        var list = [];
      
        for (var i = 0; i < level; i += 1) {
          var _classNames;
      
          list.push(external_window_React_["createElement"]("span", {
            key: i,
            className: classnames_default()(baseClassName, (_classNames = {}, Object(defineProperty["a" /* default */])(_classNames, "".concat(baseClassName, "-start"), isStart[i + 1]), Object(defineProperty["a" /* default */])(_classNames, "".concat(baseClassName, "-end"), isEnd[i + 1]), Object(defineProperty["a" /* default */])(_classNames, "".concat(baseClassName, "-end-first-level"), !i && isEnd[0]), _classNames))
          }));
        }
      
        return external_window_React_["createElement"]("span", {
          "aria-hidden": "true",
          className: "".concat(prefixCls, "-indent")
        }, list);
      };
      
      /* harmony default export */ var es_Indent = (Indent_Indent);
      // EXTERNAL MODULE: ./node_modules/rc-tree/es/utils/treeUtil.js
      var treeUtil = __webpack_require__("815F");
      
      // CONCATENATED MODULE: ./node_modules/rc-tree/es/TreeNode.js
      
      
      
      
      
      
      
      
      
       // @ts-ignore
      
      
      
      
      
      var ICON_OPEN = 'open';
      var ICON_CLOSE = 'close';
      var defaultTitle = '---';
      
      var TreeNode_InternalTreeNode = /*#__PURE__*/function (_React$Component) {
        Object(inherits["a" /* default */])(InternalTreeNode, _React$Component);
      
        var _super = Object(createSuper["a" /* default */])(InternalTreeNode);
      
        function InternalTreeNode() {
          var _this;
      
          Object(classCallCheck["a" /* default */])(this, InternalTreeNode);
      
          _this = _super.apply(this, arguments);
          _this.state = {
            dragNodeHighlight: false
          };
      
          _this.onSelectorClick = function (e) {
            // Click trigger before select/check operation
            var onNodeClick = _this.props.context.onNodeClick;
            onNodeClick(e, Object(treeUtil["b" /* convertNodePropsToEventData */])(_this.props));
      
            if (_this.isSelectable()) {
              _this.onSelect(e);
            } else {
              _this.onCheck(e);
            }
          };
      
          _this.onSelectorDoubleClick = function (e) {
            var onNodeDoubleClick = _this.props.context.onNodeDoubleClick;
            onNodeDoubleClick(e, Object(treeUtil["b" /* convertNodePropsToEventData */])(_this.props));
          };
      
          _this.onSelect = function (e) {
            if (_this.isDisabled()) return;
            var onNodeSelect = _this.props.context.onNodeSelect;
            e.preventDefault();
            onNodeSelect(e, Object(treeUtil["b" /* convertNodePropsToEventData */])(_this.props));
          };
      
          _this.onCheck = function (e) {
            if (_this.isDisabled()) return;
            var _this$props = _this.props,
                disableCheckbox = _this$props.disableCheckbox,
                checked = _this$props.checked;
            var onNodeCheck = _this.props.context.onNodeCheck;
            if (!_this.isCheckable() || disableCheckbox) return;
            e.preventDefault();
            var targetChecked = !checked;
            onNodeCheck(e, Object(treeUtil["b" /* convertNodePropsToEventData */])(_this.props), targetChecked);
          };
      
          _this.onMouseEnter = function (e) {
            var onNodeMouseEnter = _this.props.context.onNodeMouseEnter;
            onNodeMouseEnter(e, Object(treeUtil["b" /* convertNodePropsToEventData */])(_this.props));
          };
      
          _this.onMouseLeave = function (e) {
            var onNodeMouseLeave = _this.props.context.onNodeMouseLeave;
            onNodeMouseLeave(e, Object(treeUtil["b" /* convertNodePropsToEventData */])(_this.props));
          };
      
          _this.onContextMenu = function (e) {
            var onNodeContextMenu = _this.props.context.onNodeContextMenu;
            onNodeContextMenu(e, Object(treeUtil["b" /* convertNodePropsToEventData */])(_this.props));
          };
      
          _this.onDragStart = function (e) {
            var onNodeDragStart = _this.props.context.onNodeDragStart;
            e.stopPropagation();
      
            _this.setState({
              dragNodeHighlight: true
            });
      
            onNodeDragStart(e, Object(assertThisInitialized["a" /* default */])(_this));
      
            try {
              // ie throw error
              // firefox-need-it
              e.dataTransfer.setData('text/plain', '');
            } catch (error) {// empty
            }
          };
      
          _this.onDragEnter = function (e) {
            var onNodeDragEnter = _this.props.context.onNodeDragEnter;
            e.preventDefault();
            e.stopPropagation();
            onNodeDragEnter(e, Object(assertThisInitialized["a" /* default */])(_this));
          };
      
          _this.onDragOver = function (e) {
            var onNodeDragOver = _this.props.context.onNodeDragOver;
            e.preventDefault();
            e.stopPropagation();
            onNodeDragOver(e, Object(assertThisInitialized["a" /* default */])(_this));
          };
      
          _this.onDragLeave = function (e) {
            var onNodeDragLeave = _this.props.context.onNodeDragLeave;
            e.stopPropagation();
            onNodeDragLeave(e, Object(assertThisInitialized["a" /* default */])(_this));
          };
      
          _this.onDragEnd = function (e) {
            var onNodeDragEnd = _this.props.context.onNodeDragEnd;
            e.stopPropagation();
      
            _this.setState({
              dragNodeHighlight: false
            });
      
            onNodeDragEnd(e, Object(assertThisInitialized["a" /* default */])(_this));
          };
      
          _this.onDrop = function (e) {
            var onNodeDrop = _this.props.context.onNodeDrop;
            e.preventDefault();
            e.stopPropagation();
      
            _this.setState({
              dragNodeHighlight: false
            });
      
            onNodeDrop(e, Object(assertThisInitialized["a" /* default */])(_this));
          }; // Disabled item still can be switch
      
      
          _this.onExpand = function (e) {
            var onNodeExpand = _this.props.context.onNodeExpand;
            onNodeExpand(e, Object(treeUtil["b" /* convertNodePropsToEventData */])(_this.props));
          }; // Drag usage
      
      
          _this.setSelectHandle = function (node) {
            _this.selectHandle = node;
          };
      
          _this.getNodeState = function () {
            var expanded = _this.props.expanded;
      
            if (_this.isLeaf()) {
              return null;
            }
      
            return expanded ? ICON_OPEN : ICON_CLOSE;
          };
      
          _this.hasChildren = function () {
            var eventKey = _this.props.eventKey;
            var keyEntities = _this.props.context.keyEntities;
      
            var _ref = keyEntities[eventKey] || {},
                children = _ref.children;
      
            return !!(children || []).length;
          };
      
          _this.isLeaf = function () {
            var _this$props2 = _this.props,
                isLeaf = _this$props2.isLeaf,
                loaded = _this$props2.loaded;
            var loadData = _this.props.context.loadData;
      
            var hasChildren = _this.hasChildren();
      
            if (isLeaf === false) {
              return false;
            }
      
            return isLeaf || !loadData && !hasChildren || loadData && loaded && !hasChildren;
          };
      
          _this.isDisabled = function () {
            var disabled = _this.props.disabled;
            var treeDisabled = _this.props.context.disabled;
            return !!(treeDisabled || disabled);
          };
      
          _this.isCheckable = function () {
            var checkable = _this.props.checkable;
            var treeCheckable = _this.props.context.checkable; // Return false if tree or treeNode is not checkable
      
            if (!treeCheckable || checkable === false) return false;
            return treeCheckable;
          }; // Load data to avoid default expanded tree without data
      
      
          _this.syncLoadData = function (props) {
            var expanded = props.expanded,
                loading = props.loading,
                loaded = props.loaded;
            var _this$props$context = _this.props.context,
                loadData = _this$props$context.loadData,
                onNodeLoad = _this$props$context.onNodeLoad;
            if (loading) return; // read from state to avoid loadData at same time
      
            if (loadData && expanded && !_this.isLeaf()) {
              // We needn't reload data when has children in sync logic
              // It's only needed in node expanded
              if (!_this.hasChildren() && !loaded) {
                onNodeLoad(Object(treeUtil["b" /* convertNodePropsToEventData */])(_this.props));
              }
            }
          }; // Switcher
      
      
          _this.renderSwitcher = function () {
            var _this$props3 = _this.props,
                expanded = _this$props3.expanded,
                switcherIconFromProps = _this$props3.switcherIcon;
            var _this$props$context2 = _this.props.context,
                prefixCls = _this$props$context2.prefixCls,
                switcherIconFromCtx = _this$props$context2.switcherIcon;
            var switcherIcon = switcherIconFromProps || switcherIconFromCtx;
      
            if (_this.isLeaf()) {
              return external_window_React_["createElement"]("span", {
                className: classnames_default()("".concat(prefixCls, "-switcher"), "".concat(prefixCls, "-switcher-noop"))
              }, typeof switcherIcon === 'function' ? switcherIcon(Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, _this.props), {}, {
                isLeaf: true
              })) : switcherIcon);
            }
      
            var switcherCls = classnames_default()("".concat(prefixCls, "-switcher"), "".concat(prefixCls, "-switcher_").concat(expanded ? ICON_OPEN : ICON_CLOSE));
            return external_window_React_["createElement"]("span", {
              onClick: _this.onExpand,
              className: switcherCls
            }, typeof switcherIcon === 'function' ? switcherIcon(Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, _this.props), {}, {
              isLeaf: false
            })) : switcherIcon);
          }; // Checkbox
      
      
          _this.renderCheckbox = function () {
            var _this$props4 = _this.props,
                checked = _this$props4.checked,
                halfChecked = _this$props4.halfChecked,
                disableCheckbox = _this$props4.disableCheckbox;
            var prefixCls = _this.props.context.prefixCls;
      
            var disabled = _this.isDisabled();
      
            var checkable = _this.isCheckable();
      
            if (!checkable) return null; // [Legacy] Custom element should be separate with `checkable` in future
      
            var $custom = typeof checkable !== 'boolean' ? checkable : null;
            return external_window_React_["createElement"]("span", {
              className: classnames_default()("".concat(prefixCls, "-checkbox"), checked && "".concat(prefixCls, "-checkbox-checked"), !checked && halfChecked && "".concat(prefixCls, "-checkbox-indeterminate"), (disabled || disableCheckbox) && "".concat(prefixCls, "-checkbox-disabled")),
              onClick: _this.onCheck
            }, $custom);
          };
      
          _this.renderIcon = function () {
            var loading = _this.props.loading;
            var prefixCls = _this.props.context.prefixCls;
            return external_window_React_["createElement"]("span", {
              className: classnames_default()("".concat(prefixCls, "-iconEle"), "".concat(prefixCls, "-icon__").concat(_this.getNodeState() || 'docu'), loading && "".concat(prefixCls, "-icon_loading"))
            });
          }; // Icon + Title
      
      
          _this.renderSelector = function () {
            var dragNodeHighlight = _this.state.dragNodeHighlight;
            var _this$props5 = _this.props,
                title = _this$props5.title,
                selected = _this$props5.selected,
                icon = _this$props5.icon,
                loading = _this$props5.loading,
                data = _this$props5.data;
            var _this$props$context3 = _this.props.context,
                prefixCls = _this$props$context3.prefixCls,
                showIcon = _this$props$context3.showIcon,
                treeIcon = _this$props$context3.icon,
                draggable = _this$props$context3.draggable,
                loadData = _this$props$context3.loadData,
                titleRender = _this$props$context3.titleRender;
      
            var disabled = _this.isDisabled();
      
            var wrapClass = "".concat(prefixCls, "-node-content-wrapper"); // Icon - Still show loading icon when loading without showIcon
      
            var $icon;
      
            if (showIcon) {
              var currentIcon = icon || treeIcon;
              $icon = currentIcon ? external_window_React_["createElement"]("span", {
                className: classnames_default()("".concat(prefixCls, "-iconEle"), "".concat(prefixCls, "-icon__customize"))
              }, typeof currentIcon === 'function' ? currentIcon(_this.props) : currentIcon) : _this.renderIcon();
            } else if (loadData && loading) {
              $icon = _this.renderIcon();
            } // Title
      
      
            var titleNode;
      
            if (typeof title === 'function') {
              titleNode = title(data);
            } else if (titleRender) {
              titleNode = titleRender(data);
            } else {
              titleNode = title;
            }
      
            var $title = external_window_React_["createElement"]("span", {
              className: "".concat(prefixCls, "-title")
            }, titleNode);
            return external_window_React_["createElement"]("span", {
              ref: _this.setSelectHandle,
              title: typeof title === 'string' ? title : '',
              className: classnames_default()("".concat(wrapClass), "".concat(wrapClass, "-").concat(_this.getNodeState() || 'normal'), !disabled && (selected || dragNodeHighlight) && "".concat(prefixCls, "-node-selected"), !disabled && draggable && 'draggable'),
              draggable: !disabled && draggable || undefined,
              "aria-grabbed": !disabled && draggable || undefined,
              onMouseEnter: _this.onMouseEnter,
              onMouseLeave: _this.onMouseLeave,
              onContextMenu: _this.onContextMenu,
              onClick: _this.onSelectorClick,
              onDoubleClick: _this.onSelectorDoubleClick,
              onDragStart: draggable ? _this.onDragStart : undefined
            }, $icon, $title);
          };
      
          return _this;
        } // Isomorphic needn't load data in server side
      
      
        Object(createClass["a" /* default */])(InternalTreeNode, [{
          key: "componentDidMount",
          value: function componentDidMount() {
            this.syncLoadData(this.props);
          }
        }, {
          key: "componentDidUpdate",
          value: function componentDidUpdate() {
            this.syncLoadData(this.props);
          }
        }, {
          key: "isSelectable",
          value: function isSelectable() {
            var selectable = this.props.selectable;
            var treeSelectable = this.props.context.selectable; // Ignore when selectable is undefined or null
      
            if (typeof selectable === 'boolean') {
              return selectable;
            }
      
            return treeSelectable;
          }
        }, {
          key: "render",
          value: function render() {
            var _classNames;
      
            var _this$props6 = this.props,
                eventKey = _this$props6.eventKey,
                className = _this$props6.className,
                style = _this$props6.style,
                dragOver = _this$props6.dragOver,
                dragOverGapTop = _this$props6.dragOverGapTop,
                dragOverGapBottom = _this$props6.dragOverGapBottom,
                isLeaf = _this$props6.isLeaf,
                isStart = _this$props6.isStart,
                isEnd = _this$props6.isEnd,
                expanded = _this$props6.expanded,
                selected = _this$props6.selected,
                checked = _this$props6.checked,
                halfChecked = _this$props6.halfChecked,
                loading = _this$props6.loading,
                domRef = _this$props6.domRef,
                active = _this$props6.active,
                onMouseMove = _this$props6.onMouseMove,
                otherProps = Object(objectWithoutProperties["a" /* default */])(_this$props6, ["eventKey", "className", "style", "dragOver", "dragOverGapTop", "dragOverGapBottom", "isLeaf", "isStart", "isEnd", "expanded", "selected", "checked", "halfChecked", "loading", "domRef", "active", "onMouseMove"]);
      
            var _this$props$context4 = this.props.context,
                prefixCls = _this$props$context4.prefixCls,
                filterTreeNode = _this$props$context4.filterTreeNode,
                draggable = _this$props$context4.draggable,
                keyEntities = _this$props$context4.keyEntities;
            var disabled = this.isDisabled();
            var dataOrAriaAttributeProps = Object(util["f" /* getDataAndAria */])(otherProps);
      
            var _ref2 = keyEntities[eventKey] || {},
                level = _ref2.level;
      
            var isEndNode = isEnd[isEnd.length - 1];
            return external_window_React_["createElement"]("div", Object.assign({
              ref: domRef,
              className: classnames_default()(className, "".concat(prefixCls, "-treenode"), (_classNames = {}, Object(defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-treenode-disabled"), disabled), Object(defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-treenode-switcher-").concat(expanded ? 'open' : 'close'), !isLeaf), Object(defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-treenode-checkbox-checked"), checked), Object(defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-treenode-checkbox-indeterminate"), halfChecked), Object(defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-treenode-selected"), selected), Object(defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-treenode-loading"), loading), Object(defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-treenode-active"), active), Object(defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-treenode-leaf-last"), isEndNode), Object(defineProperty["a" /* default */])(_classNames, 'drag-over', !disabled && dragOver), Object(defineProperty["a" /* default */])(_classNames, 'drag-over-gap-top', !disabled && dragOverGapTop), Object(defineProperty["a" /* default */])(_classNames, 'drag-over-gap-bottom', !disabled && dragOverGapBottom), Object(defineProperty["a" /* default */])(_classNames, 'filter-node', filterTreeNode && filterTreeNode(Object(treeUtil["b" /* convertNodePropsToEventData */])(this.props))), _classNames)),
              style: style,
              onDragEnter: draggable ? this.onDragEnter : undefined,
              onDragOver: draggable ? this.onDragOver : undefined,
              onDragLeave: draggable ? this.onDragLeave : undefined,
              onDrop: draggable ? this.onDrop : undefined,
              onDragEnd: draggable ? this.onDragEnd : undefined,
              onMouseMove: onMouseMove
            }, dataOrAriaAttributeProps), external_window_React_["createElement"](es_Indent, {
              prefixCls: prefixCls,
              level: level,
              isStart: isStart,
              isEnd: isEnd
            }), this.renderSwitcher(), this.renderCheckbox(), this.renderSelector());
          }
        }]);
      
        return InternalTreeNode;
      }(external_window_React_["Component"]);
      
      var TreeNode_ContextTreeNode = function ContextTreeNode(props) {
        return external_window_React_["createElement"](contextTypes["a" /* TreeContext */].Consumer, null, function (context) {
          return external_window_React_["createElement"](TreeNode_InternalTreeNode, Object.assign({}, props, {
            context: context
          }));
        });
      };
      
      TreeNode_ContextTreeNode.displayName = 'TreeNode';
      TreeNode_ContextTreeNode.defaultProps = {
        title: defaultTitle
      };
      TreeNode_ContextTreeNode.isTreeNode = 1;
      
      /* harmony default export */ var TreeNode = __webpack_exports__["a"] = (TreeNode_ContextTreeNode);
      
      /***/ }),
      
      /***/ "Y1PL":
      /*!**********************************************************!*\
        !*** ./node_modules/rc-textarea/es/index.js + 7 modules ***!
        \**********************************************************/
      /*! exports provided: ResizableTextArea, default */
      /*! all exports used */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/classCallCheck.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/createClass.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/createSuper.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/defineProperty.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/extends.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/inherits.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/objectSpread2.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/classnames/index.js (<- Module is not an ECMAScript module) */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/Children/toArray.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/Dom/findDOMNode.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/omit.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/ref.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/warning.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/resize-observer-polyfill/dist/ResizeObserver.es.js (<- Module uses injected variables (global)) */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/shallowequal/index.js (<- Module is not an ECMAScript module) */
      /*! ModuleConcatenation bailout: Cannot concat with external "window.React" (<- Module is not an ECMAScript module) */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      // ESM COMPAT FLAG
      __webpack_require__.r(__webpack_exports__);
      
      // EXPORTS
      __webpack_require__.d(__webpack_exports__, "ResizableTextArea", function() { return /* reexport */ es_ResizableTextArea; });
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/extends.js
      var esm_extends = __webpack_require__("wx14");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/classCallCheck.js
      var classCallCheck = __webpack_require__("1OyB");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/createClass.js
      var createClass = __webpack_require__("vuIU");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/inherits.js
      var inherits = __webpack_require__("Ji7U");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/createSuper.js + 1 modules
      var createSuper = __webpack_require__("LK+K");
      
      // EXTERNAL MODULE: external "window.React"
      var external_window_React_ = __webpack_require__("cDcd");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/objectSpread2.js
      var objectSpread2 = __webpack_require__("VTBJ");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/defineProperty.js
      var defineProperty = __webpack_require__("rePB");
      
      // EXTERNAL MODULE: ./node_modules/rc-util/es/Children/toArray.js
      var toArray = __webpack_require__("Zm9Q");
      
      // EXTERNAL MODULE: ./node_modules/rc-util/es/warning.js
      var warning = __webpack_require__("Kwbf");
      
      // EXTERNAL MODULE: ./node_modules/rc-util/es/ref.js
      var ref = __webpack_require__("c+Xe");
      
      // EXTERNAL MODULE: ./node_modules/rc-util/es/Dom/findDOMNode.js
      var findDOMNode = __webpack_require__("m+aA");
      
      // EXTERNAL MODULE: ./node_modules/resize-observer-polyfill/dist/ResizeObserver.es.js
      var ResizeObserver_es = __webpack_require__("bdgK");
      
      // CONCATENATED MODULE: ./node_modules/rc-textarea/node_modules/rc-resize-observer/es/utils/observerUtil.js
       // =============================== Const ===============================
      
      var elementListeners = new Map();
      
      function observerUtil_onResize(entities) {
        entities.forEach(function (entity) {
          var _elementListeners$get;
      
          var target = entity.target;
          (_elementListeners$get = elementListeners.get(target)) === null || _elementListeners$get === void 0 ? void 0 : _elementListeners$get.forEach(function (listener) {
            return listener(target);
          });
        });
      } // Note: ResizeObserver polyfill not support option to measure border-box resize
      
      
      var resizeObserver = new ResizeObserver_es["default"](observerUtil_onResize); // Dev env only
      
      var _el =  false ? undefined : null; // eslint-disable-line
      
      var _rs =  false ? undefined : null; // eslint-disable-line
      // ============================== Observe ==============================
      
      function observe(element, callback) {
        if (!elementListeners.has(element)) {
          elementListeners.set(element, new Set());
          resizeObserver.observe(element);
        }
      
        elementListeners.get(element).add(callback);
      }
      function unobserve(element, callback) {
        if (elementListeners.has(element)) {
          elementListeners.get(element).delete(callback);
      
          if (!elementListeners.get(element).size) {
            resizeObserver.unobserve(element);
            elementListeners.delete(element);
          }
        }
      }
      // CONCATENATED MODULE: ./node_modules/rc-textarea/node_modules/rc-resize-observer/es/SingleObserver/DomWrapper.js
      
      
      
      
      
      /**
       * Fallback to findDOMNode if origin ref do not provide any dom element
       */
      
      var DomWrapper_DomWrapper = /*#__PURE__*/function (_React$Component) {
        Object(inherits["a" /* default */])(DomWrapper, _React$Component);
      
        var _super = Object(createSuper["a" /* default */])(DomWrapper);
      
        function DomWrapper() {
          Object(classCallCheck["a" /* default */])(this, DomWrapper);
      
          return _super.apply(this, arguments);
        }
      
        Object(createClass["a" /* default */])(DomWrapper, [{
          key: "render",
          value: function render() {
            return this.props.children;
          }
        }]);
      
        return DomWrapper;
      }(external_window_React_["Component"]);
      
      
      // CONCATENATED MODULE: ./node_modules/rc-textarea/node_modules/rc-resize-observer/es/Collection.js
      
      var CollectionContext = /*#__PURE__*/external_window_React_["createContext"](null);
      /**
       * Collect all the resize event from children ResizeObserver
       */
      
      function Collection(_ref) {
        var children = _ref.children,
            onBatchResize = _ref.onBatchResize;
        var resizeIdRef = external_window_React_["useRef"](0);
        var resizeInfosRef = external_window_React_["useRef"]([]);
        var onCollectionResize = external_window_React_["useContext"](CollectionContext);
        var onResize = external_window_React_["useCallback"](function (size, element, data) {
          resizeIdRef.current += 1;
          var currentId = resizeIdRef.current;
          resizeInfosRef.current.push({
            size: size,
            element: element,
            data: data
          });
          Promise.resolve().then(function () {
            if (currentId === resizeIdRef.current) {
              onBatchResize === null || onBatchResize === void 0 ? void 0 : onBatchResize(resizeInfosRef.current);
              resizeInfosRef.current = [];
            }
          }); // Continue bubbling if parent exist
      
          onCollectionResize === null || onCollectionResize === void 0 ? void 0 : onCollectionResize(size, element, data);
        }, [onBatchResize, onCollectionResize]);
        return /*#__PURE__*/external_window_React_["createElement"](CollectionContext.Provider, {
          value: onResize
        }, children);
      }
      // CONCATENATED MODULE: ./node_modules/rc-textarea/node_modules/rc-resize-observer/es/SingleObserver/index.js
      
      
      
      
      
      
      
      function SingleObserver(props) {
        var children = props.children,
            disabled = props.disabled;
        var elementRef = external_window_React_["useRef"](null);
        var wrapperRef = external_window_React_["useRef"](null);
        var onCollectionResize = external_window_React_["useContext"](CollectionContext); // ============================= Size =============================
      
        var sizeRef = external_window_React_["useRef"]({
          width: -1,
          height: -1,
          offsetWidth: -1,
          offsetHeight: -1
        }); // ============================= Ref ==============================
      
        var canRef = /*#__PURE__*/external_window_React_["isValidElement"](children) && Object(ref["c" /* supportRef */])(children);
        var originRef = canRef ? children.ref : null;
        var mergedRef = external_window_React_["useMemo"](function () {
          return Object(ref["a" /* composeRef */])(originRef, elementRef);
        }, [originRef, elementRef]); // =========================== Observe ============================
      
        var propsRef = external_window_React_["useRef"](props);
        propsRef.current = props; // Handler
      
        var onInternalResize = external_window_React_["useCallback"](function (target) {
          var _propsRef$current = propsRef.current,
              onResize = _propsRef$current.onResize,
              data = _propsRef$current.data;
      
          var _target$getBoundingCl = target.getBoundingClientRect(),
              width = _target$getBoundingCl.width,
              height = _target$getBoundingCl.height;
      
          var offsetWidth = target.offsetWidth,
              offsetHeight = target.offsetHeight;
          /**
           * Resize observer trigger when content size changed.
           * In most case we just care about element size,
           * let's use `boundary` instead of `contentRect` here to avoid shaking.
           */
      
          var fixedWidth = Math.floor(width);
          var fixedHeight = Math.floor(height);
      
          if (sizeRef.current.width !== fixedWidth || sizeRef.current.height !== fixedHeight || sizeRef.current.offsetWidth !== offsetWidth || sizeRef.current.offsetHeight !== offsetHeight) {
            var size = {
              width: fixedWidth,
              height: fixedHeight,
              offsetWidth: offsetWidth,
              offsetHeight: offsetHeight
            };
            sizeRef.current = size; // IE is strange, right?
      
            var mergedOffsetWidth = offsetWidth === Math.round(width) ? width : offsetWidth;
            var mergedOffsetHeight = offsetHeight === Math.round(height) ? height : offsetHeight;
      
            var sizeInfo = Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, size), {}, {
              offsetWidth: mergedOffsetWidth,
              offsetHeight: mergedOffsetHeight
            }); // Let collection know what happened
      
      
            onCollectionResize === null || onCollectionResize === void 0 ? void 0 : onCollectionResize(sizeInfo, target, data);
      
            if (onResize) {
              // defer the callback but not defer to next frame
              Promise.resolve().then(function () {
                onResize(sizeInfo, target);
              });
            }
          }
        }, []); // Dynamic observe
      
        external_window_React_["useEffect"](function () {
          var currentElement = Object(findDOMNode["a" /* default */])(elementRef.current) || Object(findDOMNode["a" /* default */])(wrapperRef.current);
      
          if (currentElement && !disabled) {
            observe(currentElement, onInternalResize);
          }
      
          return function () {
            return unobserve(currentElement, onInternalResize);
          };
        }, [elementRef.current, disabled]); // ============================ Render ============================
      
        return /*#__PURE__*/external_window_React_["createElement"](DomWrapper_DomWrapper, {
          ref: wrapperRef
        }, canRef ? /*#__PURE__*/external_window_React_["cloneElement"](children, {
          ref: mergedRef
        }) : children);
      }
      // CONCATENATED MODULE: ./node_modules/rc-textarea/node_modules/rc-resize-observer/es/index.js
      
      
      
      
      
      
      var INTERNAL_PREFIX_KEY = 'rc-observer-key';
      
      function ResizeObserver(props) {
        var children = props.children;
        var childNodes = Object(toArray["a" /* default */])(children);
      
        if (false) {}
      
        return childNodes.map(function (child, index) {
          var key = (child === null || child === void 0 ? void 0 : child.key) || "".concat(INTERNAL_PREFIX_KEY, "-").concat(index);
          return /*#__PURE__*/external_window_React_["createElement"](SingleObserver, Object(esm_extends["a" /* default */])({}, props, {
            key: key
          }), child);
        });
      }
      
      ResizeObserver.Collection = Collection;
      /* harmony default export */ var es = (ResizeObserver);
      // EXTERNAL MODULE: ./node_modules/rc-util/es/omit.js
      var omit = __webpack_require__("bT9E");
      
      // EXTERNAL MODULE: ./node_modules/classnames/index.js
      var classnames = __webpack_require__("TSYQ");
      var classnames_default = /*#__PURE__*/__webpack_require__.n(classnames);
      
      // CONCATENATED MODULE: ./node_modules/rc-textarea/es/calculateNodeHeight.js
      // Thanks to https://github.com/andreypopp/react-textarea-autosize/
      
      /**
       * calculateNodeHeight(uiTextNode, useCache = false)
       */
      var HIDDEN_TEXTAREA_STYLE = "\n  min-height:0 !important;\n  max-height:none !important;\n  height:0 !important;\n  visibility:hidden !important;\n  overflow:hidden !important;\n  position:absolute !important;\n  z-index:-1000 !important;\n  top:0 !important;\n  right:0 !important\n";
      var SIZING_STYLE = ['letter-spacing', 'line-height', 'padding-top', 'padding-bottom', 'font-family', 'font-weight', 'font-size', 'font-variant', 'text-rendering', 'text-transform', 'width', 'text-indent', 'padding-left', 'padding-right', 'border-width', 'box-sizing', 'word-break'];
      var computedStyleCache = {};
      var hiddenTextarea;
      function calculateNodeStyling(node) {
        var useCache = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
        var nodeRef = node.getAttribute('id') || node.getAttribute('data-reactid') || node.getAttribute('name');
      
        if (useCache && computedStyleCache[nodeRef]) {
          return computedStyleCache[nodeRef];
        }
      
        var style = window.getComputedStyle(node);
        var boxSizing = style.getPropertyValue('box-sizing') || style.getPropertyValue('-moz-box-sizing') || style.getPropertyValue('-webkit-box-sizing');
        var paddingSize = parseFloat(style.getPropertyValue('padding-bottom')) + parseFloat(style.getPropertyValue('padding-top'));
        var borderSize = parseFloat(style.getPropertyValue('border-bottom-width')) + parseFloat(style.getPropertyValue('border-top-width'));
        var sizingStyle = SIZING_STYLE.map(function (name) {
          return "".concat(name, ":").concat(style.getPropertyValue(name));
        }).join(';');
        var nodeInfo = {
          sizingStyle: sizingStyle,
          paddingSize: paddingSize,
          borderSize: borderSize,
          boxSizing: boxSizing
        };
      
        if (useCache && nodeRef) {
          computedStyleCache[nodeRef] = nodeInfo;
        }
      
        return nodeInfo;
      }
      function calculateNodeHeight(uiTextNode) {
        var useCache = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
        var minRows = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
        var maxRows = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
      
        if (!hiddenTextarea) {
          hiddenTextarea = document.createElement('textarea');
          hiddenTextarea.setAttribute('tab-index', '-1');
          hiddenTextarea.setAttribute('aria-hidden', 'true');
          document.body.appendChild(hiddenTextarea);
        } // Fix wrap="off" issue
        // https://github.com/ant-design/ant-design/issues/6577
      
      
        if (uiTextNode.getAttribute('wrap')) {
          hiddenTextarea.setAttribute('wrap', uiTextNode.getAttribute('wrap'));
        } else {
          hiddenTextarea.removeAttribute('wrap');
        } // Copy all CSS properties that have an impact on the height of the content in
        // the textbox
      
      
        var _calculateNodeStyling = calculateNodeStyling(uiTextNode, useCache),
            paddingSize = _calculateNodeStyling.paddingSize,
            borderSize = _calculateNodeStyling.borderSize,
            boxSizing = _calculateNodeStyling.boxSizing,
            sizingStyle = _calculateNodeStyling.sizingStyle; // Need to have the overflow attribute to hide the scrollbar otherwise
        // text-lines will not calculated properly as the shadow will technically be
        // narrower for content
      
      
        hiddenTextarea.setAttribute('style', "".concat(sizingStyle, ";").concat(HIDDEN_TEXTAREA_STYLE));
        hiddenTextarea.value = uiTextNode.value || uiTextNode.placeholder || '';
        var minHeight = Number.MIN_SAFE_INTEGER;
        var maxHeight = Number.MAX_SAFE_INTEGER;
        var height = hiddenTextarea.scrollHeight;
        var overflowY;
      
        if (boxSizing === 'border-box') {
          // border-box: add border, since height = content + padding + border
          height += borderSize;
        } else if (boxSizing === 'content-box') {
          // remove padding, since height = content
          height -= paddingSize;
        }
      
        if (minRows !== null || maxRows !== null) {
          // measure height of a textarea with a single row
          hiddenTextarea.value = ' ';
          var singleRowHeight = hiddenTextarea.scrollHeight - paddingSize;
      
          if (minRows !== null) {
            minHeight = singleRowHeight * minRows;
      
            if (boxSizing === 'border-box') {
              minHeight = minHeight + paddingSize + borderSize;
            }
      
            height = Math.max(minHeight, height);
          }
      
          if (maxRows !== null) {
            maxHeight = singleRowHeight * maxRows;
      
            if (boxSizing === 'border-box') {
              maxHeight = maxHeight + paddingSize + borderSize;
            }
      
            overflowY = height > maxHeight ? '' : 'hidden';
            height = Math.min(maxHeight, height);
          }
        }
      
        return {
          height: height,
          minHeight: minHeight,
          maxHeight: maxHeight,
          overflowY: overflowY,
          resize: 'none'
        };
      }
      // EXTERNAL MODULE: ./node_modules/shallowequal/index.js
      var shallowequal = __webpack_require__("Gytx");
      var shallowequal_default = /*#__PURE__*/__webpack_require__.n(shallowequal);
      
      // CONCATENATED MODULE: ./node_modules/rc-textarea/es/ResizableTextArea.js
      
      
      
      
      
      
      
      
      
      
      
      
       // eslint-disable-next-line @typescript-eslint/naming-convention
      
      var RESIZE_STATUS;
      
      (function (RESIZE_STATUS) {
        RESIZE_STATUS[RESIZE_STATUS["NONE"] = 0] = "NONE";
        RESIZE_STATUS[RESIZE_STATUS["RESIZING"] = 1] = "RESIZING";
        RESIZE_STATUS[RESIZE_STATUS["RESIZED"] = 2] = "RESIZED";
      })(RESIZE_STATUS || (RESIZE_STATUS = {}));
      
      var ResizableTextArea_ResizableTextArea = /*#__PURE__*/function (_React$Component) {
        Object(inherits["a" /* default */])(ResizableTextArea, _React$Component);
      
        var _super = Object(createSuper["a" /* default */])(ResizableTextArea);
      
        function ResizableTextArea(props) {
          var _this;
      
          Object(classCallCheck["a" /* default */])(this, ResizableTextArea);
      
          _this = _super.call(this, props);
          _this.nextFrameActionId = void 0;
          _this.resizeFrameId = void 0;
          _this.textArea = void 0;
      
          _this.saveTextArea = function (textArea) {
            _this.textArea = textArea;
          };
      
          _this.handleResize = function (size) {
            var resizeStatus = _this.state.resizeStatus;
            var _this$props = _this.props,
                autoSize = _this$props.autoSize,
                onResize = _this$props.onResize;
      
            if (resizeStatus !== RESIZE_STATUS.NONE) {
              return;
            }
      
            if (typeof onResize === 'function') {
              onResize(size);
            }
      
            if (autoSize) {
              _this.resizeOnNextFrame();
            }
          };
      
          _this.resizeOnNextFrame = function () {
            cancelAnimationFrame(_this.nextFrameActionId);
            _this.nextFrameActionId = requestAnimationFrame(_this.resizeTextarea);
          };
      
          _this.resizeTextarea = function () {
            var autoSize = _this.props.autoSize;
      
            if (!autoSize || !_this.textArea) {
              return;
            }
      
            var minRows = autoSize.minRows,
                maxRows = autoSize.maxRows;
            var textareaStyles = calculateNodeHeight(_this.textArea, false, minRows, maxRows);
      
            _this.setState({
              textareaStyles: textareaStyles,
              resizeStatus: RESIZE_STATUS.RESIZING
            }, function () {
              cancelAnimationFrame(_this.resizeFrameId);
              _this.resizeFrameId = requestAnimationFrame(function () {
                _this.setState({
                  resizeStatus: RESIZE_STATUS.RESIZED
                }, function () {
                  _this.resizeFrameId = requestAnimationFrame(function () {
                    _this.setState({
                      resizeStatus: RESIZE_STATUS.NONE
                    });
      
                    _this.fixFirefoxAutoScroll();
                  });
                });
              });
            });
          };
      
          _this.renderTextArea = function () {
            var _this$props2 = _this.props,
                _this$props2$prefixCl = _this$props2.prefixCls,
                prefixCls = _this$props2$prefixCl === void 0 ? 'rc-textarea' : _this$props2$prefixCl,
                autoSize = _this$props2.autoSize,
                onResize = _this$props2.onResize,
                className = _this$props2.className,
                disabled = _this$props2.disabled;
            var _this$state = _this.state,
                textareaStyles = _this$state.textareaStyles,
                resizeStatus = _this$state.resizeStatus;
            var otherProps = Object(omit["a" /* default */])(_this.props, ['prefixCls', 'onPressEnter', 'autoSize', 'defaultValue', 'onResize']);
            var cls = classnames_default()(prefixCls, className, Object(defineProperty["a" /* default */])({}, "".concat(prefixCls, "-disabled"), disabled)); // Fix https://github.com/ant-design/ant-design/issues/6776
            // Make sure it could be reset when using form.getFieldDecorator
      
            if ('value' in otherProps) {
              otherProps.value = otherProps.value || '';
            }
      
            var style = Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, _this.props.style), textareaStyles), resizeStatus === RESIZE_STATUS.RESIZING ? // React will warning when mix `overflow` & `overflowY`.
            // We need to define this separately.
            {
              overflowX: 'hidden',
              overflowY: 'hidden'
            } : null);
      
            return /*#__PURE__*/external_window_React_["createElement"](es, {
              onResize: _this.handleResize,
              disabled: !(autoSize || onResize)
            }, /*#__PURE__*/external_window_React_["createElement"]("textarea", Object(esm_extends["a" /* default */])({}, otherProps, {
              className: cls,
              style: style,
              ref: _this.saveTextArea
            })));
          };
      
          _this.state = {
            textareaStyles: {},
            resizeStatus: RESIZE_STATUS.NONE
          };
          return _this;
        }
      
        Object(createClass["a" /* default */])(ResizableTextArea, [{
          key: "componentDidUpdate",
          value: function componentDidUpdate(prevProps) {
            // Re-render with the new content or new autoSize property then recalculate the height as required.
            if (prevProps.value !== this.props.value || !shallowequal_default()(prevProps.autoSize, this.props.autoSize)) {
              this.resizeTextarea();
            }
          }
        }, {
          key: "componentWillUnmount",
          value: function componentWillUnmount() {
            cancelAnimationFrame(this.nextFrameActionId);
            cancelAnimationFrame(this.resizeFrameId);
          } // https://github.com/ant-design/ant-design/issues/21870
      
        }, {
          key: "fixFirefoxAutoScroll",
          value: function fixFirefoxAutoScroll() {
            try {
              if (document.activeElement === this.textArea) {
                var currentStart = this.textArea.selectionStart;
                var currentEnd = this.textArea.selectionEnd;
                this.textArea.setSelectionRange(currentStart, currentEnd);
              }
            } catch (e) {// Fix error in Chrome:
              // Failed to read the 'selectionStart' property from 'HTMLInputElement'
              // http://stackoverflow.com/q/21177489/3040605
            }
          }
        }, {
          key: "render",
          value: function render() {
            return this.renderTextArea();
          }
        }]);
      
        return ResizableTextArea;
      }(external_window_React_["Component"]);
      
      /* harmony default export */ var es_ResizableTextArea = (ResizableTextArea_ResizableTextArea);
      // CONCATENATED MODULE: ./node_modules/rc-textarea/es/index.js
      
      
      
      
      
      
      
      
      var es_TextArea = /*#__PURE__*/function (_React$Component) {
        Object(inherits["a" /* default */])(TextArea, _React$Component);
      
        var _super = Object(createSuper["a" /* default */])(TextArea);
      
        function TextArea(props) {
          var _this;
      
          Object(classCallCheck["a" /* default */])(this, TextArea);
      
          _this = _super.call(this, props);
          _this.resizableTextArea = void 0;
      
          _this.focus = function () {
            _this.resizableTextArea.textArea.focus();
          };
      
          _this.saveTextArea = function (resizableTextArea) {
            _this.resizableTextArea = resizableTextArea;
          };
      
          _this.handleChange = function (e) {
            var onChange = _this.props.onChange;
      
            _this.setValue(e.target.value, function () {
              _this.resizableTextArea.resizeTextarea();
            });
      
            if (onChange) {
              onChange(e);
            }
          };
      
          _this.handleKeyDown = function (e) {
            var _this$props = _this.props,
                onPressEnter = _this$props.onPressEnter,
                onKeyDown = _this$props.onKeyDown;
      
            if (e.keyCode === 13 && onPressEnter) {
              onPressEnter(e);
            }
      
            if (onKeyDown) {
              onKeyDown(e);
            }
          };
      
          var value = typeof props.value === 'undefined' || props.value === null ? props.defaultValue : props.value;
          _this.state = {
            value: value
          };
          return _this;
        }
      
        Object(createClass["a" /* default */])(TextArea, [{
          key: "setValue",
          value: function setValue(value, callback) {
            if (!('value' in this.props)) {
              this.setState({
                value: value
              }, callback);
            }
          }
        }, {
          key: "blur",
          value: function blur() {
            this.resizableTextArea.textArea.blur();
          }
        }, {
          key: "render",
          value: function render() {
            return /*#__PURE__*/external_window_React_["createElement"](es_ResizableTextArea, Object(esm_extends["a" /* default */])({}, this.props, {
              value: this.state.value,
              onKeyDown: this.handleKeyDown,
              onChange: this.handleChange,
              ref: this.saveTextArea
            }));
          }
        }], [{
          key: "getDerivedStateFromProps",
          value: function getDerivedStateFromProps(nextProps) {
            if ('value' in nextProps) {
              return {
                value: nextProps.value
              };
            }
      
            return null;
          }
        }]);
      
        return TextArea;
      }(external_window_React_["Component"]);
      
      
      /* harmony default export */ var rc_textarea_es = __webpack_exports__["default"] = (es_TextArea);
      
      /***/ }),
      
      /***/ "ZW9T":
      /*!************************************************************!*\
        !*** ./src/components/monaco-editor/index.jsx + 2 modules ***!
        \************************************************************/
      /*! exports provided: getLanguageByMirrorName, default, DiffEditor */
      /*! exports used: DiffEditor, default */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelper.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/objectSpread2.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/slicedToArray.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/toConsumableArray.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/regenerator/index.js (<- Module is not an ECMAScript module) */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/message/index.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/message/style/index.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/js-beautify/js/index.js (<- Module is not an ECMAScript module) */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/resize-observer-polyfill/dist/ResizeObserver.es.js (<- Module uses injected variables (global)) */
      /*! ModuleConcatenation bailout: Cannot concat with external "window.React" (<- Module is not an ECMAScript module) */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      
      // EXPORTS
      __webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ DiffEditor; });
      
      // UNUSED EXPORTS: getLanguageByMirrorName
      
      // EXTERNAL MODULE: ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/objectSpread2.js
      var objectSpread2 = __webpack_require__("k1fw");
      
      // EXTERNAL MODULE: ./node_modules/antd/es/message/style/index.js
      var message_style = __webpack_require__("miYZ");
      
      // EXTERNAL MODULE: ./node_modules/antd/es/message/index.js + 1 modules
      var message = __webpack_require__("tsqr");
      
      // EXTERNAL MODULE: ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelper.js
      var createForOfIteratorHelper = __webpack_require__("rAM+");
      
      // EXTERNAL MODULE: ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/slicedToArray.js + 1 modules
      var slicedToArray = __webpack_require__("tJVT");
      
      // EXTERNAL MODULE: ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js + 1 modules
      var objectWithoutProperties = __webpack_require__("PpiC");
      
      // EXTERNAL MODULE: external "window.React"
      var external_window_React_ = __webpack_require__("cDcd");
      var external_window_React_default = /*#__PURE__*/__webpack_require__.n(external_window_React_);
      
      // EXTERNAL MODULE: ./node_modules/resize-observer-polyfill/dist/ResizeObserver.es.js
      var ResizeObserver_es = __webpack_require__("bdgK");
      
      // EXTERNAL MODULE: ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/toConsumableArray.js + 2 modules
      var toConsumableArray = __webpack_require__("oBTY");
      
      // EXTERNAL MODULE: ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js
      var asyncToGenerator = __webpack_require__("9og8");
      
      // EXTERNAL MODULE: ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/regenerator/index.js
      var regenerator = __webpack_require__("WmNS");
      var regenerator_default = /*#__PURE__*/__webpack_require__.n(regenerator);
      
      // CONCATENATED MODULE: ./src/components/monaco-editor/keywords.tsx
      var cLangage = {
        keywords: ['print', 'auto', 'break', 'case', 'char', 'const', 'continue', 'default', 'do', 'double', 'else', 'enum', 'extern', 'float', 'for', 'goto', 'if', 'int', 'long', 'register', 'return', 'short', 'signed', 'sizeof', 'static', 'struct', 'switch', 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while']
      };
      var javaLangage = {
        quickKey: [{
          label: "main",
          content: ['public static void main(String[] args) {', '\t$0', '}'].join('\n')
        }, {
          label: "System.out.println",
          content: ['System.out.println($0)'].join('\n')
        }, {
          label: "System.out.print",
          content: ['System.out.print($0)'].join('\n')
        }],
        keywords: ['abstract', 'continue', 'for', 'new', 'switch', 'assert', 'default', 'goto', 'package', 'synchronized', 'boolean', 'do', 'if', 'private', 'this', 'break', 'double', 'implements', 'protected', 'throw', 'byte', 'else', 'import', 'public', 'throws', 'case', 'enum', 'instanceof', 'return', 'transient', 'catch', 'extends', 'int', 'short', 'try', 'char', 'final', 'interface', 'static', 'void', 'class', 'finally', 'long', 'strictfp', 'volatile', 'const', 'float', 'native', 'super', 'while', 'true', 'false']
      };
      var cppLangage = {
        keywords: ['abstract', 'amp', 'array', 'auto', 'bool', 'break', 'case', 'catch', 'char', 'class', 'const', 'constexpr', 'const_cast', 'continue', 'cpu', 'decltype', 'default', 'delegate', 'delete', 'do', 'double', 'dynamic_cast', 'each', 'else', 'enum', 'event', 'explicit', 'export', 'extern', 'false', 'final', 'finally', 'float', 'for', 'friend', 'gcnew', 'generic', 'goto', 'if', 'in', 'initonly', 'inline', 'int', 'interface', 'interior_ptr', 'internal', 'literal', 'long', 'mutable', 'namespace', 'new', 'noexcept', 'nullptr', '__nullptr', 'operator', 'override', 'partial', 'pascal', 'pin_ptr', 'private', 'property', 'protected', 'public', 'ref', 'register', 'reinterpret_cast', 'restrict', 'return', 'safe_cast', 'sealed', 'short', 'signed', 'sizeof', 'static', 'static_assert', 'static_cast', 'struct', 'switch', 'template', 'this', 'thread_local', 'throw', 'tile_static', 'true', 'try', 'typedef', 'typeid', 'typename', 'union', 'unsigned', 'using', 'virtual', 'void', 'volatile', 'wchar_t', 'where', 'while', '_asm', '_based', '_cdecl', '_declspec', '_fastcall', '_if_exists', '_if_not_exists', '_inline', '_multiple_inheritance', '_pascal', '_single_inheritance', '_stdcall', '_virtual_inheritance', '_w64', '__abstract', '__alignof', '__asm', '__assume', '__based', '__box', '__builtin_alignof', '__cdecl', '__clrcall', '__declspec', '__delegate', '__event', '__except', '__fastcall', '__finally', '__forceinline', '__gc', '__hook', '__identifier', '__if_exists', '__if_not_exists', '__inline', '__int128', '__int16', '__int32', '__int64', '__int8', '__interface', '__leave', '__m128', '__m128d', '__m128i', '__m256', '__m256d', '__m256i', '__m64', '__multiple_inheritance', '__newslot', '__nogc', '__noop', '__nounwind', '__novtordisp', '__pascal', '__pin', '__pragma', '__property', '__ptr32', '__ptr64', '__raise', '__restrict', '__resume', '__sealed', '__single_inheritance', '__stdcall', '__super', '__thiscall', '__try', '__try_cast', '__typeof', '__unaligned', '__unhook', '__uuidof', '__value', '__virtual_inheritance', '__w64', '__wchar_t'],
        operators: ['=', '>', '<', '!', '~', '?', ':', '==', '<=', '>=', '!=', '&&', '||', '++', '--', '+', '-', '*', '/', '&', '|', '^', '%', '<<', '>>', '>>>', '+=', '-=', '*=', '/=', '&=', '|=', '^=', '%=', '<<=', '>>=', '>>>='],
        quickKey: [{
          label: "ifelse",
          content: ['if (${1:condition}) {', '\t$0', '} else {', '\t', '}'].join('\n')
        }, {
          label: "#include",
          content: 'include "$0"'
        }, {
          label: "printf",
          content: 'printf($0)'
        }, {
          label: "main",
          content: ['int main () {', '\t$0', '}'].join('\n')
        }, {
          label: "for",
          content: ['for( ; ; ){', '\t$0', '}'].join('\n')
        }, {
          label: "trycatch",
          content: ['try{', '\t$0', '}catch(ExceptionName e){', '}'].join('\n')
        }, {
          label: "using namespace std;",
          content: ['using namespace std;'].join('\n')
        }, {
          label: "#include <iostream>",
          content: ['#include <iostream>'].join('\n')
        }, {
          label: "#include <vector>",
          content: ['#include <vector>'].join('\n')
        }, {
          label: "#include <sstream>",
          content: ['#include <sstream>'].join('\n')
        }, {
          label: "#include <string>",
          content: ['#include <string>'].join('\n')
        }, {
          label: "#include <cmath>",
          content: ['#include <cmath>'].join('\n')
        }]
      };
      var pythonLangage = {
        keywords: ['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'None', 'not', 'or', 'pass', 'raise', 'return', 'self', 'try', 'while', 'with', 'yield', 'int', 'float', 'long', 'complex', 'hex', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'file', 'filter', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'id', 'input', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'locals', 'list', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'reversed', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip', 'True', 'False', '__dict__', '__methods__', '__members__', '__class__', '__bases__', '__name__', '__mro__', '__subclasses__', '__init__', '__import__'],
        quickKey: [{
          label: "print",
          content: ['print($0)'].join('\n')
        } // { label: "#include", content: '#include ""' },
        // { label: "printf", content: 'printf("")' },
        ]
      };
      // EXTERNAL MODULE: ./node_modules/js-beautify/js/index.js
      var js = __webpack_require__("5VLF");
      var js_default = /*#__PURE__*/__webpack_require__.n(js);
      
      // CONCATENATED MODULE: ./src/components/monaco-editor/monaco-suggest-config.tsx
      
      
      
      
      
      
      var baseConfig = {
        languages: ['c', 'abap', 'apex', 'azcli', 'bat', 'cameligo', 'clojure', 'coffee', 'cpp', 'csharp', 'csp', 'css', 'dockerfile', 'fsharp', 'go', 'graphql', 'handlebars', 'html', 'ini', 'java', 'javascript', 'json', 'kotlin', 'less', 'lua', 'markdown', 'mips', 'msdax', 'mysql', 'objective-c', 'pascal', 'pascaligo', 'perl', 'pgsql', 'php', 'postiats', 'powerquery', 'powershell', 'pug', 'python', 'r', 'razor', 'redis', 'redshift', 'restructuredtext', 'ruby', 'rust', 'sb', 'scheme', 'scss', 'shell', 'solidity', 'sophia', 'sql', 'st', 'swift', 'tcl', 'twig', 'vb', 'xml', "yaml'"],
        tables: {
          users: ["name", "id", "email", "phone", "password"],
          roles: ["id", "name", "order", "created_at", "updated_at", "deleted_at"]
        }
      };
      
      var getKeywordsSuggest = function getKeywordsSuggest(monaco, keywords) {
        return keywords.map(function (key) {
          return {
            label: key,
            // 显示的名称
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: key // 真实补全的值
      
          };
        });
      };
      
      var getTableSuggest = function getTableSuggest(monaco) {
        return Object.keys(baseConfig.tables).map(function (key) {
          return {
            label: key,
            // 显示的名称
            kind: monaco.languages.CompletionItemKind.Variable,
            insertText: key // 真实补全的值
      
          };
        });
      };
      
      var getFieldsSuggest = function getFieldsSuggest(tableName, monaco) {
        var fields = baseConfig.tables[tableName];
      
        if (!fields) {
          return [];
        }
      
        return fields.map(function (name) {
          return {
            label: name,
            kind: monaco.languages.CompletionItemKind.Field,
            insertText: name
          };
        });
      };
      
      function getSuggestions(monaco, model, position, keywords, snippts) {
        var word = model.getWordUntilPosition(position);
        var range = {
          startLineNumber: position.lineNumber,
          endLineNumber: position.lineNumber,
          startColumn: word.startColumn,
          endColumn: word.endColumn
        };
        var rs = keywords.map(function (item) {
          return {
            label: item,
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: item,
            insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            range: range
          };
        });
        snippts.map(function (item) {
          rs.push(Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, item), {}, {
            range: range
          }));
        });
        return rs;
      }
      
      /* harmony default export */ var monaco_suggest_config = (function (monaco) {
        baseConfig.languages.map(function (item) {
          monaco.languages.registerDocumentFormattingEditProvider(item, {
            provideDocumentFormattingEdits: function provideDocumentFormattingEdits(model, options, token) {
              return Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee() {
                var formattedText;
                return regenerator_default.a.wrap(function _callee$(_context) {
                  while (1) {
                    switch (_context.prev = _context.next) {
                      case 0:
                        formattedText = js_default()(model.getValue(), {
                          "indent_size": "2",
                          "indent_char": " ",
                          "max_preserve_newlines": "2",
                          "preserve_newlines": true,
                          "keep_array_indentation": true,
                          "break_chained_methods": false,
                          "indent_scripts": "normal",
                          "brace_style": "collapse",
                          "space_before_conditional": true,
                          "unescape_strings": false,
                          "jslint_happy": false,
                          "end_with_newline": true,
                          "wrap_line_length": "0",
                          "indent_inner_html": false,
                          "comma_first": false,
                          "e4x": false,
                          "indent_empty_lines": false
                        });
                        return _context.abrupt("return", [{
                          range: model.getFullModelRange(),
                          text: formattedText
                        }]);
      
                      case 2:
                      case "end":
                        return _context.stop();
                    }
                  }
                }, _callee);
              }))();
            }
          });
          return item;
        });
        var cppKeyPrompt = cppLangage.quickKey.map(function (item) {
          return {
            label: item.label,
            kind: monaco.languages.CompletionItemKind.Method,
            insertText: item.content,
            insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet
          };
        });
        var pythonKeyPrompt = pythonLangage.quickKey.map(function (item) {
          return {
            label: item.label,
            kind: monaco.languages.CompletionItemKind.Method,
            insertText: item.content,
            insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet
          };
        });
        var javaKeyPrompt = javaLangage.quickKey.map(function (item) {
          return {
            label: item.label,
            kind: monaco.languages.CompletionItemKind.Method,
            insertText: item.content,
            insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet
          };
        });
        monaco.languages.registerCompletionItemProvider("cpp", {
          triggerCharacters: [".", " ", "#"].concat(Object(toConsumableArray["a" /* default */])(cppLangage.keywords), Object(toConsumableArray["a" /* default */])(cppLangage.quickKey.map(function (item) {
            return item.label;
          }))),
          provideCompletionItems: function provideCompletionItems(model, position) {
            var textUntilPosition = model.getValueInRange({
              startLineNumber: position.lineNumber,
              startColumn: 1,
              endLineNumber: position.lineNumber,
              endColumn: position.column
            });
            var match = textUntilPosition.match(/cu/gim);
            console.log("match:", match, position, textUntilPosition, model);
            var suggestions = [];
            var lineNumber = position.lineNumber,
                column = position.column;
            var textBeforePointer = model.getValueInRange({
              startLineNumber: lineNumber,
              startColumn: 0,
              endLineNumber: lineNumber,
              endColumn: column
            });
            var words = textBeforePointer.trim().split(/\s+/);
            var lastWord = words[words.length - 1];
      
            if (lastWord.endsWith(".")) {
              // 如果这个词以 . 结尾,那么认为是希望补全表的字段
              var tableName = lastWord.slice(0, lastWord.length - 1);
      
              if (Object.keys(baseConfig.tables).includes(tableName)) {
                suggestions = Object(toConsumableArray["a" /* default */])(getFieldsSuggest(tableName, monaco));
              }
            } else if (lastWord === ".") {
              suggestions = [];
            } else {
              suggestions = [].concat(Object(toConsumableArray["a" /* default */])(getTableSuggest(monaco)), Object(toConsumableArray["a" /* default */])(getKeywordsSuggest(monaco, cppLangage.keywords)), Object(toConsumableArray["a" /* default */])(cppKeyPrompt));
            }
      
            return {
              suggestions: suggestions
            };
          }
        });
        monaco.languages.registerCompletionItemProvider("c", {
          triggerCharacters: [".", " ", "#"].concat(Object(toConsumableArray["a" /* default */])(cLangage.keywords)),
          provideCompletionItems: function provideCompletionItems(model, position) {
            var textUntilPosition = model.getValueInRange({
              startLineNumber: position.lineNumber,
              startColumn: 1,
              endLineNumber: position.lineNumber,
              endColumn: position.column
            });
            var match = textUntilPosition.match(/cu/gim);
            console.log("match:", match, position, textUntilPosition, model);
            var suggestions = [];
            var lineNumber = position.lineNumber,
                column = position.column;
            var textBeforePointer = model.getValueInRange({
              startLineNumber: lineNumber,
              startColumn: 0,
              endLineNumber: lineNumber,
              endColumn: column
            });
            var words = textBeforePointer.trim().split(/\s+/);
            var lastWord = words[words.length - 1];
      
            if (lastWord.endsWith(".")) {
              // 如果这个词以 . 结尾,那么认为是希望补全表的字段
              var tableName = lastWord.slice(0, lastWord.length - 1);
      
              if (Object.keys(baseConfig.tables).includes(tableName)) {
                suggestions = Object(toConsumableArray["a" /* default */])(getFieldsSuggest(tableName, monaco));
              }
            } else if (lastWord === ".") {
              suggestions = [];
            } else {
              suggestions = [].concat(Object(toConsumableArray["a" /* default */])(getTableSuggest(monaco)), Object(toConsumableArray["a" /* default */])(getKeywordsSuggest(monaco, cLangage.keywords)));
            }
      
            return {
              suggestions: suggestions
            };
          }
        });
        monaco.languages.registerCompletionItemProvider("java", {
          triggerCharacters: [".", " "].concat(Object(toConsumableArray["a" /* default */])(javaLangage.keywords)),
          provideCompletionItems: function provideCompletionItems(model, position) {
            var suggestions = [];
            var lineNumber = position.lineNumber,
                column = position.column;
            var textBeforePointer = model.getValueInRange({
              startLineNumber: lineNumber,
              startColumn: 0,
              endLineNumber: lineNumber,
              endColumn: column
            });
            var words = textBeforePointer.trim().split(/\s+/);
            var lastWord = words[words.length - 1];
      
            if (lastWord.endsWith(".")) {
              // 如果这个词以 . 结尾,那么认为是希望补全表的字段
              var tableName = lastWord.slice(0, lastWord.length - 1);
      
              if (Object.keys(baseConfig.tables).includes(tableName)) {
                suggestions = Object(toConsumableArray["a" /* default */])(getFieldsSuggest(tableName, monaco));
              }
            } else if (lastWord === ".") {
              suggestions = [];
            } else {
              suggestions = [].concat(Object(toConsumableArray["a" /* default */])(getTableSuggest(monaco)), Object(toConsumableArray["a" /* default */])(getKeywordsSuggest(monaco, javaLangage.keywords)), Object(toConsumableArray["a" /* default */])(javaKeyPrompt));
            }
      
            return {
              suggestions: suggestions
            };
          }
        });
        monaco.languages.registerCompletionItemProvider("python", {
          triggerCharacters: [".", " "].concat(Object(toConsumableArray["a" /* default */])(pythonLangage.keywords)),
          provideCompletionItems: function provideCompletionItems(model, position) {
            var suggestions = [];
            var lineNumber = position.lineNumber,
                column = position.column;
            var textBeforePointer = model.getValueInRange({
              startLineNumber: lineNumber,
              startColumn: 0,
              endLineNumber: lineNumber,
              endColumn: column
            });
            var words = textBeforePointer.trim().split(/\s+/);
            var lastWord = words[words.length - 1];
      
            if (lastWord.endsWith(".")) {
              // 如果这个词以 . 结尾,那么认为是希望补全表的字段
              var tableName = lastWord.slice(0, lastWord.length - 1);
      
              if (Object.keys(baseConfig.tables).includes(tableName)) {
                suggestions = Object(toConsumableArray["a" /* default */])(getFieldsSuggest(tableName, monaco));
              }
            } else if (lastWord === ".") {
              suggestions = [];
            } else {
              suggestions = [].concat(Object(toConsumableArray["a" /* default */])(getTableSuggest(monaco)), Object(toConsumableArray["a" /* default */])(getKeywordsSuggest(monaco, pythonLangage.keywords)), Object(toConsumableArray["a" /* default */])(pythonKeyPrompt));
            }
      
            return {
              suggestions: suggestions
            };
          }
        });
      });
      var tipTxt = '该任务关卡设置了禁止复制粘贴,请手动输入代码。';
      // EXTERNAL MODULE: ./node_modules/lodash/lodash.js
      var lodash = __webpack_require__("LvDl");
      
      // EXTERNAL MODULE: ./src/components/monaco-editor/index.css
      var monaco_editor = __webpack_require__("+ua5");
      
      // CONCATENATED MODULE: ./src/components/monaco-editor/index.jsx
      
      
      
      
      
      
      
      
      
      
      
      
      
      function processSize(size) {
        return !/^\d+$/.test(size) ? size : "".concat(size, "px");
      }
      
      function noop() {}
      
      var __prevent_trigger_change_event = false;
      var DICT = {
        'Python3.6': 'python',
        'Python2.7': 'python',
        Dynamips: 'cpp',
        Java: 'java',
        Web: 'php',
        Html: 'html',
        Hive: 'sql',
        Hadoop: 'java',
        SDL: 'cpp',
        PHP: 'php',
        Matlab: 'python',
        Git: 'python',
        Python: 'python',
        'C/C++': 'cpp',
        'C++': 'cpp',
        C: 'cpp',
        Ruby: 'ruby',
        Shell: 'shell',
        JavaScript: 'javascript',
        Perl6: 'perl',
        Kotlin: 'kotlin',
        Elixir: 'elixir',
        Android: 'java',
        JavaWeb: 'java',
        Go: 'go',
        Spark: 'sql',
        MachineLearning: 'python',
        Verilog: 'xml',
        'Verilog/VNC': 'xml',
        Docker: 'dockerfile',
        'C#': 'csharp',
        SQLite3: 'sql',
        Oracle: 'sql',
        Vhdl: 'vhdl',
        R: 'r',
        Swift: 'swift',
        SQLServer: 'mysql',
        MySQL: 'mysql',
        Mongo: 'sql',
        PostgreSql: 'pgsql',
        Hbase: 'powershell',
        Sqoop: 'sql',
        Nasm: 'cpp',
        Kafka: 'java',
        Flink: 'java',
        Sml: 'javascript',
        OpenGL: 'cpp',
        Perl5: 'perl',
        Orange: 'python'
      };
      function getLanguageByMirrorName() {
        var mirror_name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
        var lang = mirror_name;
      
        if (Array.isArray(mirror_name)) {
          for (var i = 0; i < mirror_name.length; i++) {
            var languageVal = DICT[mirror_name[i]];
      
            if (languageVal) {
              return languageVal;
            }
          }
      
          return lang[0];
        }
      
        return DICT[lang] || lang;
      } //onCodeChange 必须是幂等的,因为只会注册一次,如果有变化,会响应旧的,产生脏数据
      
      var monaco_editor_monaco = null;
      /* harmony default export */ var components_monaco_editor = __webpack_exports__["b"] = (function (_ref) {
        var _ref$width = _ref.width,
            width = _ref$width === void 0 ? '100%' : _ref$width,
            _ref$height = _ref.height,
            height = _ref$height === void 0 ? '100%' : _ref$height,
            value = _ref.value,
            _ref$language = _ref.language,
            language = _ref$language === void 0 ? 'javascript' : _ref$language,
            _ref$style = _ref.style,
            style = _ref$style === void 0 ? {} : _ref$style,
            _ref$options = _ref.options,
            options = _ref$options === void 0 ? {} : _ref$options,
            _ref$overrideServices = _ref.overrideServices,
            overrideServices = _ref$overrideServices === void 0 ? {} : _ref$overrideServices,
            _ref$theme = _ref.theme,
            theme = _ref$theme === void 0 ? 'vs-dark' : _ref$theme,
            onEditBlur = _ref.onEditBlur,
            onSave = _ref.onSave,
            _ref$autoHeight = _ref.autoHeight,
            autoHeight = _ref$autoHeight === void 0 ? false : _ref$autoHeight,
            _ref$forbidCopy = _ref.forbidCopy,
            forbidCopy = _ref$forbidCopy === void 0 ? false : _ref$forbidCopy,
            _ref$onChange = _ref.onChange,
            onChange = _ref$onChange === void 0 ? noop : _ref$onChange,
            _ref$editorDidMount = _ref.editorDidMount,
            editorDidMount = _ref$editorDidMount === void 0 ? noop : _ref$editorDidMount,
            _ref$onFocus = _ref.onFocus,
            onFocus = _ref$onFocus === void 0 ? noop : _ref$onFocus,
            _ref$filename = _ref.filename,
            filename = _ref$filename === void 0 ? 'educoder.txt' : _ref$filename,
            errorLine = _ref.errorLine,
            _ref$errorContent = _ref.errorContent,
            errorContent = _ref$errorContent === void 0 ? '' : _ref$errorContent,
            props = Object(objectWithoutProperties["a" /* default */])(_ref, ["width", "height", "value", "language", "style", "options", "overrideServices", "theme", "onEditBlur", "onSave", "autoHeight", "forbidCopy", "onChange", "editorDidMount", "onFocus", "filename", "errorLine", "errorContent"]);
      
        var editorEl = Object(external_window_React_["useRef"])();
        var editor = Object(external_window_React_["useRef"])({});
        var optionsRef = Object(external_window_React_["useRef"])();
        var timeRef = Object(external_window_React_["useRef"])();
        var inputLock = Object(external_window_React_["useRef"])(false);
        var inputLockTime = Object(external_window_React_["useRef"])();
      
        var _useState = Object(external_window_React_["useState"])(false),
            _useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
            init = _useState2[0],
            setInit = _useState2[1];
      
        function onLayout() {
          var ro;
      
          if (editorEl.current) {
            ro = new ResizeObserver_es["default"](function (entries) {
              var _iterator = Object(createForOfIteratorHelper["a" /* default */])(entries),
                  _step;
      
              try {
                for (_iterator.s(); !(_step = _iterator.n()).done;) {
                  var entry = _step.value;
      
                  if (entry.target.offsetHeight > 0 || entry.target.offsetWidth > 0) {
                    editor.current.instance.layout();
                  }
                }
              } catch (err) {
                _iterator.e(err);
              } finally {
                _iterator.f();
              }
            });
            ro.observe(editorEl.current);
          }
      
          return ro;
        }
      
        function tipWarn() {
          message["b" /* default */].warn(decodeURIComponent(tipTxt));
        }
      
        var setCodeValue = function setCodeValue() {
          var instance = editor.current.instance;
      
          if (value != null && instance && init) {
            var model = instance.getModel();
      
            if (model && value !== model.getValue()) {
              __prevent_trigger_change_event = true;
              model.setValue(value);
              instance.layout();
              __prevent_trigger_change_event = false;
            }
          }
        };
      
        Object(external_window_React_["useEffect"])(function () {
          if (timeRef.current) clearTimeout(timeRef.current);
          timeRef.current = setTimeout(function () {
            setCodeValue();
          }, 500);
        }, [value, init, editor.current]);
        Object(external_window_React_["useEffect"])(function () {
          if (errorLine && editor.current && editor.current.instance) {
            var _instance = editor.current.instance;
      
            _instance.changeViewZones(function (changeAccessor) {
              var domNode = document.createElement('div');
              domNode.style.padding = '10px 20px';
              domNode.style.width = 'calc(100% - 20px)';
              domNode.className = 'my-error-line-wrp';
              domNode.innerHTML = errorContent;
              changeAccessor.addZone({
                afterLineNumber: errorLine || 11,
                heightInLines: 3,
                domNode: domNode
              });
            });
      
            var overlayWidget = {
              domNode: null,
              getId: function getId() {
                return 'my.overlay.widget';
              },
              getDomNode: function getDomNode() {
                if (!this.domNode) {
                  this.domNode = document.createElement('div');
                  this.domNode.innerHTML = '';
                  this.domNode.style.width = '100%';
                  this.domNode.style.padding = '20px 100px';
                  this.domNode.style.right = '0px';
                  this.domNode.style.top = '50px';
                  this.domNode.style.position = 'relative';
                  this.domNode.style.color = '#333';
                }
      
                return this.domNode;
              },
              getPosition: function getPosition() {
                return null;
              }
            };
      
            _instance.addOverlayWidget(overlayWidget); // instance.revealPositionInCenter(11,1);
      
      
            _instance.revealPositionInCenter({
              lineNumber: 20,
              column: 1
            });
          }
        }, [errorLine, editor.current, init]);
      
        function onPaste() {
          var instance = editor.current.instance;
      
          if (instance) {
            var selection = instance.getSelection();
            var pastePos = editor.current.pastePos || {};
            var range = new monaco_editor_monaco.Range(pastePos.startLineNumber || selection.endLineNumber, pastePos.startColumn || selection.endColumn, pastePos.endLineNumber || selection.endLineNumber, pastePos.endColumn || selection.endColumn);
            setTimeout(function () {
              instance.executeEdits('', [{
                range: range,
                text: ''
              }]);
            }, 300);
          }
        }
      
        function onSaveHandler(e) {
          if ((window.navigator.platform.match('Mac') ? e.metaKey : e.ctrlKey) && e.keyCode == 83) {
            e.preventDefault();
            onSave();
          }
        }
      
        var autoCalcHeight = function autoCalcHeight() {
          if (autoHeight && editor.current.instance) {
            var _height = editor.current.instance.getContentHeight();
      
            setFixedHeight(_height < height ? height : _height);
          } else {
            setFixedHeight(height);
          }
        };
      
        function fakeClick(obj) {
          var ev = document.createEvent('MouseEvents');
          ev.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
          obj.dispatchEvent(ev);
        }
      
        function exportRaw(name, data) {
          var urlObject = window.URL || window.webkitURL || window;
          var export_blob = new Blob([data]);
          var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
          save_link.href = urlObject.createObjectURL(export_blob);
          save_link.download = name;
          fakeClick(save_link);
        }
      
        function FormatDoc() {
          instance.getAction('editor.action.formatDocument').run();
        }
      
        Object(external_window_React_["useEffect"])(function () {
          autoCalcHeight();
        }, [autoCalcHeight]);
        Object(external_window_React_["useEffect"])(function () {
          if (editorEl.current && !init) {
            undefined;
      
            undefined;
      
            __webpack_require__.e(/*! import() | monaco-editor */ 26).then(__webpack_require__.t.bind(null, /*! monaco-editor/esm/vs/editor/editor.api.js */ "M/lh", 7)).then(function (mod) {
              try {
                monaco_editor_monaco = mod;
                editor.current.instance = monaco_editor_monaco.editor.create(editorEl.current, {
                  value: value,
                  language: getLanguageByMirrorName(language),
                  theme: theme,
                  requireConfig: {
                    'vs/nls': {
                      availableLanguages: {
                        '*': 'zh-cn'
                      }
                    }
                  },
                  wordWrap: true,
                  autoIndent: true,
                  formatOnPaste: true,
                  formatOnType: true
                }, overrideServices);
                var _instance2 = editor.current.instance;
                editorDidMount(_instance2, monaco_editor_monaco);
                setTimeout(function () {
                  autoCalcHeight();
                  editor.current.instance.addAction({
                    id: 'd123123',
                    label: 'Download File',
                    contextMenuGroupId: '9_cutcopypaste',
                    run: function run() {
                      exportRaw(filename || 'educoder.txt', _instance2.getValue());
                    }
                  });
      
                  _instance2.getDomNode().addEventListener('input', function () {
                    if (optionsRef.current.autoFormat) FormatDoc();
                  });
                }, 500);
                editor.current.subscription = _instance2.onDidChangeModelContent(function (event) {
                  if (!inputLock.current) {
                    autoCalcHeight();
                    onChange(_instance2.getValue(), event);
                  } else {
                    clearTimeout(inputLockTime.current);
                  }
      
                  inputLockTime.current = setTimeout(function () {
                    inputLock.current = false;
                  }, 500);
                });
                editor.current.instance.addAction({
                  id: 'formatdoc',
                  label: 'Format Document',
                  contextMenuGroupId: 'formatdocs',
                  run: function run() {
                    FormatDoc();
                  }
                });
                if (!window.Monaco) monaco_suggest_config(monaco_editor_monaco, getLanguageByMirrorName(language));
      
                if (forbidCopy) {
                  _instance2.addCommand(monaco_editor_monaco.KeyMod.CtrlCmd | monaco_editor_monaco.KeyMod.Shift | monaco_editor_monaco.KeyCode.KEY_V, function () {
                    tipWarn();
                    return null;
                  });
      
                  _instance2.addCommand(monaco_editor_monaco.KeyMod.CtrlCmd | monaco_editor_monaco.KeyCode.KEY_C, function () {
                    tipWarn();
                    return null;
                  });
                }
      
                window.Monaco = monaco_editor_monaco;
      
                if (onEditBlur) {
                  _instance2.onDidBlurEditorWidget(function () {
                    onEditBlur(_instance2.getValue());
                  });
                }
      
                if (onFocus) {
                  _instance2.onDidFocusEditorText(function () {
                    onFocus(_instance2.getValue());
                  });
                }
      
                if (forbidCopy) {
                  _instance2.addCommand(monaco_editor_monaco.KeyMod.CtrlCmd | monaco_editor_monaco.KeyCode.KEY_V, function () {
                    tipWarn();
                    return null;
                  });
      
                  _instance2.onDidPaste(function (pos) {
                    editor.current.pastePos = pos;
                  });
      
                  try {
                    window.addEventListener('paste', onPaste);
                  } catch (e) {}
                }
      
                var ro = onLayout();
                setInit(true);
                return function () {
                  var el = editor.current.instance;
                  el.dispose();
                  var model = el.getModel();
      
                  if (model) {
                    model.dispose();
                  }
      
                  if (editor.current.subscription) {
                    editor.current.subscription.dispose();
                  }
      
                  if (forbidCopy) {
                    window.removeEventListener('paste', onPaste);
                  }
      
                  ro.unobserve(editorEl.current);
                };
              } catch (e) {//  ;
              }
            });
          }
        }, []);
        Object(external_window_React_["useEffect"])(function () {
          var instance = editor.current.instance;
      
          if (instance && init) {
            document.addEventListener('keydown', onSaveHandler, false);
            return function () {
              document.removeEventListener('keydown', onSaveHandler);
            };
          }
        }, [onSave, init]);
        Object(external_window_React_["useEffect"])(function () {
          var instance = editor.current.instance;
      
          if (instance && init) {
            var lang = getLanguageByMirrorName(language);
            monaco_editor_monaco.editor.setModelLanguage(instance.getModel(), lang);
          }
        }, [language, init]);
        Object(external_window_React_["useEffect"])(function () {
          var instance = editor.current.instance;
      
          if (instance && init) {
            monaco_editor_monaco.editor.setTheme(theme);
          }
        }, [theme, init]);
        Object(external_window_React_["useEffect"])(function () {
          var instance = editor.current.instance;
          optionsRef.current = options;
      
          if (instance && init) {
            instance.updateOptions(Object(objectSpread2["a" /* default */])({}, options));
            setTimeout(function () {
              instance.getModel().updateOptions(Object(objectSpread2["a" /* default */])({}, options));
            }, 200);
          }
        }, [JSON.stringify(options), init]);
        Object(external_window_React_["useEffect"])(function () {
          var instance = editor.current.instance;
      
          if (instance && init) {
            instance.layout();
          }
        }, [width, height, init]); // const fixedWidth = processSize(width);
        // const fixedHeight = processSize(height);
      
        var _useState3 = Object(external_window_React_["useState"])(processSize(width)),
            _useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
            fixedWidth = _useState4[0],
            setFixedWidth = _useState4[1];
      
        var _useState5 = Object(external_window_React_["useState"])(processSize(height)),
            _useState6 = Object(slicedToArray["a" /* default */])(_useState5, 2),
            fixedHeight = _useState6[0],
            setFixedHeight = _useState6[1];
      
        var mergeStyle = Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, style), {}, {
          width: fixedWidth,
          height: fixedHeight
        });
      
        return /*#__PURE__*/external_window_React_default.a.createElement("div", {
          className: "my-monaco-editor",
          ref: editorEl,
          style: mergeStyle
        });
      });
      function DiffEditor(_ref2) {
        var _ref2$width = _ref2.width,
            width = _ref2$width === void 0 ? '100%' : _ref2$width,
            _ref2$height = _ref2.height,
            height = _ref2$height === void 0 ? '100%' : _ref2$height,
            original = _ref2.original,
            modified = _ref2.modified,
            language = _ref2.language,
            _ref2$options = _ref2.options,
            options = _ref2$options === void 0 ? {} : _ref2$options;
        var editorEl = Object(external_window_React_["useRef"])();
      
        var _useState7 = Object(external_window_React_["useState"])(null),
            _useState8 = Object(slicedToArray["a" /* default */])(_useState7, 2),
            instance = _useState8[0],
            setInstance = _useState8[1];
      
        function onLayout(instance) {
          var ro;
      
          if (editorEl.current) {
            ro = new ResizeObserver_es["default"](function (entries) {
              var _iterator2 = Object(createForOfIteratorHelper["a" /* default */])(entries),
                  _step2;
      
              try {
                for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
                  var entry = _step2.value;
      
                  if (entry.target.offsetHeight > 0 || entry.target.offsetWidth > 0) {
                    instance.layout();
                  }
                }
              } catch (err) {
                _iterator2.e(err);
              } finally {
                _iterator2.f();
              }
            });
            ro.observe(editorEl.current);
          }
      
          return ro;
        }
      
        Object(external_window_React_["useEffect"])(function () {
          if (editorEl.current) {
            __webpack_require__.e(/*! import() | monaco-editor */ 26).then(__webpack_require__.t.bind(null, /*! monaco-editor/esm/vs/editor/editor.api.js */ "M/lh", 7)).then(function (mod) {
              monaco_editor_monaco = mod;
              var instance = monaco_editor_monaco.editor.createDiffEditor(editorEl.current, Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({
                enableSplitViewResizing: false,
                scrollBeyondLastLine: false,
                roundedSelection: false,
                renderIndicators: false,
                useShadows: false,
                horizontal: 'hidden',
                lineNumbers: 'off',
                ignoreTrimWhitespace: false,
                'semanticHighlighting.enabled': true,
                followsCaret: true,
                // resets the navigator state when the user selects something in the editor
                ignoreCharChanges: true,
                // jump from line to line,
                minimap: {
                  enabled: false
                },
                readOnly: true
              }, options), {}, {
                wordWrap: true
              }));
              setInstance(instance);
              var ro = onLayout(instance);
              return function () {
                instance.dispose();
                var model = instance.getModel();
      
                if (model) {
                  model.dispose();
                }
      
                ro.unobserve(editorEl.current);
              };
            });
          }
        }, []);
        Object(external_window_React_["useEffect"])(function () {
          if (instance) {
            instance.setModel({
              original: monaco_editor_monaco.editor.createModel(original, language),
              modified: monaco_editor_monaco.editor.createModel(modified, language)
            });
          }
        }, [original, modified, language, instance]);
        var fixedWidth = processSize(width);
        var fixedHeight = processSize(height);
        var style = {
          width: fixedWidth,
          height: fixedHeight
        };
        return /*#__PURE__*/external_window_React_default.a.createElement("div", {
          className: "my-diff-editor",
          ref: editorEl,
          style: style
        });
      }
      
      /***/ }),
      
      /***/ "bT9E":
      /*!*****************************************!*\
        !*** ./node_modules/rc-util/es/omit.js ***!
        \*****************************************/
      /*! exports provided: default */
      /*! exports used: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return omit; });
      /* harmony import */ var _babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/esm/objectSpread2 */ "VTBJ");
      
      function omit(obj, fields) {
        var clone = Object(_babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])({}, obj);
      
        if (Array.isArray(fields)) {
          fields.forEach(function (key) {
            delete clone[key];
          });
        }
      
        return clone;
      }
      
      /***/ }),
      
      /***/ "d5o6":
      /*!*********************************************************************!*\
        !*** ./src/pages/Problemset/components/AddModal/index.less?modules ***!
        \*********************************************************************/
      /*! no static exports found */
      /*! exports used: default */
      /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
      /***/ (function(module, exports, __webpack_require__) {
      
      // extracted by mini-css-extract-plugin
      module.exports = {"flex_box_center":"flex_box_center___2-Tej","flex_space_between":"flex_space_between___1Q3vH","flex_box_vertical_center":"flex_box_vertical_center___2x9ha","flex_box_center_end":"flex_box_center_end___1fvRI","flex_box_column":"flex_box_column___2RmOE","addModal":"addModal___2Pv06","row":"row___2XmSi","label":"label___1L8pt"};
      
      /***/ }),
      
      /***/ "fAei":
      /*!******************************************************!*\
        !*** ./node_modules/rc-tree/es/index.js + 4 modules ***!
        \******************************************************/
      /*! exports provided: TreeNode, default */
      /*! exports used: TreeNode, default */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/classCallCheck.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/createClass.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/createSuper.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/defineProperty.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/inherits.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/objectSpread2.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/slicedToArray.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/toConsumableArray.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/classnames/index.js (<- Module is not an ECMAScript module) */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-motion/es/index.js (<- Module is referenced from these modules with unsupported syntax: ./node_modules/antd/lib/button/LoadingIcon.js (referenced with cjs require)) */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-tree/es/TreeNode.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-tree/es/contextTypes.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-tree/es/util.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-tree/es/utils/conductUtil.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-tree/es/utils/treeUtil.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/KeyCode.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/warning.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-virtual-list/es/index.js */
      /*! ModuleConcatenation bailout: Cannot concat with external "window.React" (<- Module is not an ECMAScript module) */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      
      // EXPORTS
      __webpack_require__.d(__webpack_exports__, "a", function() { return /* reexport */ TreeNode["a" /* default */]; });
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/defineProperty.js
      var defineProperty = __webpack_require__("rePB");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/objectSpread2.js
      var objectSpread2 = __webpack_require__("VTBJ");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/toConsumableArray.js + 2 modules
      var toConsumableArray = __webpack_require__("KQm4");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/classCallCheck.js
      var classCallCheck = __webpack_require__("1OyB");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/createClass.js
      var createClass = __webpack_require__("vuIU");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/inherits.js
      var inherits = __webpack_require__("Ji7U");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/createSuper.js + 1 modules
      var createSuper = __webpack_require__("LK+K");
      
      // EXTERNAL MODULE: external "window.React"
      var external_window_React_ = __webpack_require__("cDcd");
      
      // EXTERNAL MODULE: ./node_modules/rc-util/es/KeyCode.js
      var KeyCode = __webpack_require__("4IlW");
      
      // EXTERNAL MODULE: ./node_modules/rc-util/es/warning.js
      var warning = __webpack_require__("Kwbf");
      
      // EXTERNAL MODULE: ./node_modules/classnames/index.js
      var classnames = __webpack_require__("TSYQ");
      var classnames_default = /*#__PURE__*/__webpack_require__.n(classnames);
      
      // EXTERNAL MODULE: ./node_modules/rc-tree/es/contextTypes.js
      var contextTypes = __webpack_require__("sboe");
      
      // EXTERNAL MODULE: ./node_modules/rc-tree/es/util.js
      var util = __webpack_require__("OZM5");
      
      // EXTERNAL MODULE: ./node_modules/rc-tree/es/utils/treeUtil.js
      var treeUtil = __webpack_require__("815F");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/slicedToArray.js + 1 modules
      var slicedToArray = __webpack_require__("ODXe");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js
      var objectWithoutProperties = __webpack_require__("Ff2n");
      
      // EXTERNAL MODULE: ./node_modules/rc-virtual-list/es/index.js + 19 modules
      var es = __webpack_require__("+nKL");
      
      // EXTERNAL MODULE: ./node_modules/rc-motion/es/index.js + 5 modules
      var rc_motion_es = __webpack_require__("8XRh");
      
      // EXTERNAL MODULE: ./node_modules/rc-tree/es/TreeNode.js + 1 modules
      var TreeNode = __webpack_require__("WaYH");
      
      // CONCATENATED MODULE: ./node_modules/rc-tree/es/MotionTreeNode.js
      
      
      
      
      
      
      
      
      
      
      var MotionTreeNode_MotionTreeNode = function MotionTreeNode(_ref, ref) {
        var className = _ref.className,
            style = _ref.style,
            motion = _ref.motion,
            motionNodes = _ref.motionNodes,
            motionType = _ref.motionType,
            onOriginMotionStart = _ref.onMotionStart,
            onOriginMotionEnd = _ref.onMotionEnd,
            active = _ref.active,
            treeNodeRequiredProps = _ref.treeNodeRequiredProps,
            props = Object(objectWithoutProperties["a" /* default */])(_ref, ["className", "style", "motion", "motionNodes", "motionType", "onMotionStart", "onMotionEnd", "active", "treeNodeRequiredProps"]);
      
        var _React$useState = external_window_React_["useState"](true),
            _React$useState2 = Object(slicedToArray["a" /* default */])(_React$useState, 2),
            visible = _React$useState2[0],
            setVisible = _React$useState2[1];
      
        var _React$useContext = external_window_React_["useContext"](contextTypes["a" /* TreeContext */]),
            prefixCls = _React$useContext.prefixCls;
      
        var motionedRef = external_window_React_["useRef"](false);
      
        var onMotionEnd = function onMotionEnd() {
          if (!motionedRef.current) {
            onOriginMotionEnd();
          }
      
          motionedRef.current = true;
        };
      
        Object(external_window_React_["useEffect"])(function () {
          if (motionNodes && motionType === 'hide' && visible) {
            setVisible(false);
          }
        }, [motionNodes]);
        Object(external_window_React_["useEffect"])(function () {
          // Trigger motion only when patched
          if (motionNodes) {
            onOriginMotionStart();
          }
      
          return function () {
            if (motionNodes) {
              onMotionEnd();
            }
          };
        }, []);
      
        if (motionNodes) {
          return external_window_React_["createElement"](rc_motion_es["default"], Object.assign({
            ref: ref,
            visible: visible
          }, motion, {
            motionAppear: motionType === 'show',
            onAppearEnd: onMotionEnd,
            onLeaveEnd: onMotionEnd
          }), function (_ref2, motionRef) {
            var motionClassName = _ref2.className,
                motionStyle = _ref2.style;
            return external_window_React_["createElement"]("div", {
              ref: motionRef,
              className: classnames_default()("".concat(prefixCls, "-treenode-motion"), motionClassName),
              style: motionStyle
            }, motionNodes.map(function (treeNode) {
              var _treeNode$data = treeNode.data,
                  key = _treeNode$data.key,
                  restProps = Object(objectWithoutProperties["a" /* default */])(_treeNode$data, ["key"]),
                  isStart = treeNode.isStart,
                  isEnd = treeNode.isEnd;
      
              delete restProps.children;
              var treeNodeProps = Object(treeUtil["f" /* getTreeNodeProps */])(key, treeNodeRequiredProps);
              return external_window_React_["createElement"](TreeNode["a" /* default */], Object.assign({}, restProps, treeNodeProps, {
                active: active,
                data: treeNode.data,
                key: key,
                isStart: isStart,
                isEnd: isEnd
              }));
            }));
          });
        }
      
        return external_window_React_["createElement"](TreeNode["a" /* default */], Object.assign({
          domRef: ref,
          className: className,
          style: style
        }, props, {
          active: active
        }));
      };
      
      MotionTreeNode_MotionTreeNode.displayName = 'MotionTreeNode';
      var RefMotionTreeNode = external_window_React_["forwardRef"](MotionTreeNode_MotionTreeNode);
      /* harmony default export */ var es_MotionTreeNode = (RefMotionTreeNode);
      // CONCATENATED MODULE: ./node_modules/rc-tree/es/utils/diffUtil.js
      function findExpandedKeys() {
        var prev = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
        var next = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
        var prevLen = prev.length;
        var nextLen = next.length;
      
        if (Math.abs(prevLen - nextLen) !== 1) {
          return {
            add: false,
            key: null
          };
        }
      
        function find(shorter, longer) {
          var cache = new Map();
          shorter.forEach(function (key) {
            cache.set(key, true);
          });
          var keys = longer.filter(function (key) {
            return !cache.has(key);
          });
          return keys.length === 1 ? keys[0] : null;
        }
      
        if (prevLen < nextLen) {
          return {
            add: true,
            key: find(prev, next)
          };
        }
      
        return {
          add: false,
          key: find(next, prev)
        };
      }
      function getExpandRange(shorter, longer, key) {
        var shorterStartIndex = shorter.findIndex(function (_ref) {
          var data = _ref.data;
          return data.key === key;
        });
        var shorterEndNode = shorter[shorterStartIndex + 1];
        var longerStartIndex = longer.findIndex(function (_ref2) {
          var data = _ref2.data;
          return data.key === key;
        });
      
        if (shorterEndNode) {
          var longerEndIndex = longer.findIndex(function (_ref3) {
            var data = _ref3.data;
            return data.key === shorterEndNode.data.key;
          });
          return longer.slice(longerStartIndex + 1, longerEndIndex);
        }
      
        return longer.slice(longerStartIndex + 1);
      }
      // CONCATENATED MODULE: ./node_modules/rc-tree/es/NodeList.js
      
      
      
      /**
       * Handle virtual list of the TreeNodes.
       */
      
      
      
      
      
      var HIDDEN_STYLE = {
        width: 0,
        height: 0,
        display: 'flex',
        overflow: 'hidden',
        opacity: 0,
        border: 0,
        padding: 0,
        margin: 0
      };
      
      var noop = function noop() {};
      
      var MOTION_KEY = "RC_TREE_MOTION_".concat(Math.random());
      var MotionNode = {
        key: MOTION_KEY
      };
      var MotionEntity = {
        key: MOTION_KEY,
        level: 0,
        index: 0,
        pos: '0',
        node: MotionNode
      };
      var MotionFlattenData = {
        parent: null,
        children: [],
        pos: MotionEntity.pos,
        data: MotionNode,
      
        /** Hold empty list here since we do not use it */
        isStart: [],
        isEnd: []
      };
      /**
       * We only need get visible content items to play the animation.
       */
      
      function getMinimumRangeTransitionRange(list, virtual, height, itemHeight) {
        if (virtual === false || !height) {
          return list;
        }
      
        return list.slice(0, Math.ceil(height / itemHeight) + 1);
      }
      
      function itemKey(item) {
        var key = item.data.key,
            pos = item.pos;
        return Object(treeUtil["e" /* getKey */])(key, pos);
      }
      
      function getAccessibilityPath(item) {
        var path = String(item.data.key);
        var current = item;
      
        while (current.parent) {
          current = current.parent;
          path = "".concat(current.data.key, " > ").concat(path);
        }
      
        return path;
      }
      
      var NodeList_RefNodeList = function RefNodeList(props, ref) {
        var prefixCls = props.prefixCls,
            data = props.data,
            selectable = props.selectable,
            checkable = props.checkable,
            expandedKeys = props.expandedKeys,
            selectedKeys = props.selectedKeys,
            checkedKeys = props.checkedKeys,
            loadedKeys = props.loadedKeys,
            loadingKeys = props.loadingKeys,
            halfCheckedKeys = props.halfCheckedKeys,
            keyEntities = props.keyEntities,
            disabled = props.disabled,
            dragging = props.dragging,
            dragOverNodeKey = props.dragOverNodeKey,
            dropPosition = props.dropPosition,
            motion = props.motion,
            height = props.height,
            itemHeight = props.itemHeight,
            virtual = props.virtual,
            focusable = props.focusable,
            activeItem = props.activeItem,
            focused = props.focused,
            tabIndex = props.tabIndex,
            onKeyDown = props.onKeyDown,
            onFocus = props.onFocus,
            onBlur = props.onBlur,
            onActiveChange = props.onActiveChange,
            onListChangeStart = props.onListChangeStart,
            onListChangeEnd = props.onListChangeEnd,
            domProps = Object(objectWithoutProperties["a" /* default */])(props, ["prefixCls", "data", "selectable", "checkable", "expandedKeys", "selectedKeys", "checkedKeys", "loadedKeys", "loadingKeys", "halfCheckedKeys", "keyEntities", "disabled", "dragging", "dragOverNodeKey", "dropPosition", "motion", "height", "itemHeight", "virtual", "focusable", "activeItem", "focused", "tabIndex", "onKeyDown", "onFocus", "onBlur", "onActiveChange", "onListChangeStart", "onListChangeEnd"]); // =============================== Ref ================================
      
      
        var listRef = external_window_React_["useRef"](null);
        external_window_React_["useImperativeHandle"](ref, function () {
          return {
            scrollTo: function scrollTo(scroll) {
              listRef.current.scrollTo(scroll);
            }
          };
        }); // ============================== Motion ==============================
      
        var _React$useState = external_window_React_["useState"](expandedKeys),
            _React$useState2 = Object(slicedToArray["a" /* default */])(_React$useState, 2),
            prevExpandedKeys = _React$useState2[0],
            setPrevExpandedKeys = _React$useState2[1];
      
        var _React$useState3 = external_window_React_["useState"](data),
            _React$useState4 = Object(slicedToArray["a" /* default */])(_React$useState3, 2),
            prevData = _React$useState4[0],
            setPrevData = _React$useState4[1];
      
        var _React$useState5 = external_window_React_["useState"](data),
            _React$useState6 = Object(slicedToArray["a" /* default */])(_React$useState5, 2),
            transitionData = _React$useState6[0],
            setTransitionData = _React$useState6[1];
      
        var _React$useState7 = external_window_React_["useState"]([]),
            _React$useState8 = Object(slicedToArray["a" /* default */])(_React$useState7, 2),
            transitionRange = _React$useState8[0],
            setTransitionRange = _React$useState8[1];
      
        var _React$useState9 = external_window_React_["useState"](null),
            _React$useState10 = Object(slicedToArray["a" /* default */])(_React$useState9, 2),
            motionType = _React$useState10[0],
            setMotionType = _React$useState10[1];
      
        function onMotionEnd() {
          setPrevData(data);
          setTransitionData(data);
          setTransitionRange([]);
          setMotionType(null);
          onListChangeEnd();
        } // Do animation if expanded keys changed
      
      
        external_window_React_["useEffect"](function () {
          setPrevExpandedKeys(expandedKeys);
          var diffExpanded = findExpandedKeys(prevExpandedKeys, expandedKeys);
      
          if (diffExpanded.key !== null) {
            if (diffExpanded.add) {
              var keyIndex = prevData.findIndex(function (_ref) {
                var key = _ref.data.key;
                return key === diffExpanded.key;
              });
              var rangeNodes = getMinimumRangeTransitionRange(getExpandRange(prevData, data, diffExpanded.key), virtual, height, itemHeight);
              var newTransitionData = prevData.slice();
              newTransitionData.splice(keyIndex + 1, 0, MotionFlattenData);
              setTransitionData(newTransitionData);
              setTransitionRange(rangeNodes);
              setMotionType('show');
            } else {
              var _keyIndex = data.findIndex(function (_ref2) {
                var key = _ref2.data.key;
                return key === diffExpanded.key;
              });
      
              var _rangeNodes = getMinimumRangeTransitionRange(getExpandRange(data, prevData, diffExpanded.key), virtual, height, itemHeight);
      
              var _newTransitionData = data.slice();
      
              _newTransitionData.splice(_keyIndex + 1, 0, MotionFlattenData);
      
              setTransitionData(_newTransitionData);
              setTransitionRange(_rangeNodes);
              setMotionType('hide');
            }
          } else if (prevData !== data) {
            // If whole data changed, we just refresh the list
            setPrevData(data);
            setTransitionData(data);
          }
        }, [expandedKeys, data]); // We should clean up motion if is changed by dragging
      
        external_window_React_["useEffect"](function () {
          if (!dragging) {
            onMotionEnd();
          }
        }, [dragging]);
        var mergedData = motion ? transitionData : data;
        var treeNodeRequiredProps = {
          expandedKeys: expandedKeys,
          selectedKeys: selectedKeys,
          loadedKeys: loadedKeys,
          loadingKeys: loadingKeys,
          checkedKeys: checkedKeys,
          halfCheckedKeys: halfCheckedKeys,
          dragOverNodeKey: dragOverNodeKey,
          dropPosition: dropPosition,
          keyEntities: keyEntities
        };
        return external_window_React_["createElement"](external_window_React_["Fragment"], null, focused && activeItem && external_window_React_["createElement"]("span", {
          style: HIDDEN_STYLE,
          "aria-live": "assertive"
        }, getAccessibilityPath(activeItem)), external_window_React_["createElement"]("div", {
          role: "tree"
        }, external_window_React_["createElement"]("input", {
          style: HIDDEN_STYLE,
          disabled: focusable === false || disabled,
          tabIndex: focusable !== false ? tabIndex : null,
          onKeyDown: onKeyDown,
          onFocus: onFocus,
          onBlur: onBlur,
          value: "",
          onChange: noop
        })), external_window_React_["createElement"](es["a" /* default */], Object.assign({}, domProps, {
          data: mergedData,
          itemKey: itemKey,
          height: height,
          fullHeight: false,
          virtual: virtual,
          itemHeight: itemHeight,
          prefixCls: "".concat(prefixCls, "-list"),
          ref: listRef
        }), function (treeNode) {
          var pos = treeNode.pos,
              _treeNode$data = treeNode.data,
              key = _treeNode$data.key,
              restProps = Object(objectWithoutProperties["a" /* default */])(_treeNode$data, ["key"]),
              isStart = treeNode.isStart,
              isEnd = treeNode.isEnd;
      
          var mergedKey = Object(treeUtil["e" /* getKey */])(key, pos);
          delete restProps.children;
          var treeNodeProps = Object(treeUtil["f" /* getTreeNodeProps */])(mergedKey, treeNodeRequiredProps);
          return external_window_React_["createElement"](es_MotionTreeNode, Object.assign({}, restProps, treeNodeProps, {
            active: activeItem && key === activeItem.data.key,
            pos: pos,
            data: treeNode.data,
            isStart: isStart,
            isEnd: isEnd,
            motion: motion,
            motionNodes: key === MOTION_KEY ? transitionRange : null,
            motionType: motionType,
            onMotionStart: onListChangeStart,
            onMotionEnd: onMotionEnd,
            treeNodeRequiredProps: treeNodeRequiredProps,
            onMouseMove: function onMouseMove() {
              onActiveChange(null);
            }
          }));
        }));
      };
      
      var NodeList = external_window_React_["forwardRef"](NodeList_RefNodeList);
      NodeList.displayName = 'NodeList';
      /* harmony default export */ var es_NodeList = (NodeList);
      // EXTERNAL MODULE: ./node_modules/rc-tree/es/utils/conductUtil.js
      var conductUtil = __webpack_require__("NvD2");
      
      // CONCATENATED MODULE: ./node_modules/rc-tree/es/Tree.js
      
      
      
      
      
      
      
      // TODO: https://www.w3.org/TR/2017/NOTE-wai-aria-practices-1.1-20171214/examples/treeview/treeview-2/treeview-2a.html
      // Fully accessibility support
      
      
      
      
      
      
      
      
      
      
      
      var Tree_Tree = /*#__PURE__*/function (_React$Component) {
        Object(inherits["a" /* default */])(Tree, _React$Component);
      
        var _super = Object(createSuper["a" /* default */])(Tree);
      
        function Tree() {
          var _this;
      
          Object(classCallCheck["a" /* default */])(this, Tree);
      
          _this = _super.apply(this, arguments);
          _this.destroyed = false;
          _this.state = {
            keyEntities: {},
            selectedKeys: [],
            checkedKeys: [],
            halfCheckedKeys: [],
            loadedKeys: [],
            loadingKeys: [],
            expandedKeys: [],
            dragging: false,
            dragNodesKeys: [],
            dragOverNodeKey: null,
            dropPosition: null,
            treeData: [],
            flattenNodes: [],
            focused: false,
            activeKey: null,
            listChanging: false,
            prevProps: null
          };
          _this.listRef = external_window_React_["createRef"]();
      
          _this.onNodeDragStart = function (event, node) {
            var _this$state = _this.state,
                expandedKeys = _this$state.expandedKeys,
                keyEntities = _this$state.keyEntities;
            var onDragStart = _this.props.onDragStart;
            var eventKey = node.props.eventKey;
            _this.dragNode = node;
            var newExpandedKeys = Object(util["b" /* arrDel */])(expandedKeys, eventKey);
      
            _this.setState({
              dragging: true,
              dragNodesKeys: Object(util["g" /* getDragNodesKeys */])(eventKey, keyEntities)
            });
      
            _this.setExpandedKeys(newExpandedKeys);
      
            if (onDragStart) {
              onDragStart({
                event: event,
                node: Object(treeUtil["b" /* convertNodePropsToEventData */])(node.props)
              });
            }
          };
          /**
           * [Legacy] Select handler is less small than node,
           * so that this will trigger when drag enter node or select handler.
           * This is a little tricky if customize css without padding.
           * Better for use mouse move event to refresh drag state.
           * But let's just keep it to avoid event trigger logic change.
           */
      
      
          _this.onNodeDragEnter = function (event, node) {
            var _this$state2 = _this.state,
                expandedKeys = _this$state2.expandedKeys,
                keyEntities = _this$state2.keyEntities,
                dragNodesKeys = _this$state2.dragNodesKeys;
            var onDragEnter = _this.props.onDragEnter;
            var _node$props = node.props,
                pos = _node$props.pos,
                eventKey = _node$props.eventKey;
            if (!_this.dragNode || dragNodesKeys.indexOf(eventKey) !== -1) return;
            var dropPosition = Object(util["c" /* calcDropPosition */])(event, node); // Skip if drag node is self
      
            if (_this.dragNode.props.eventKey === eventKey && dropPosition === 0) {
              _this.setState({
                dragOverNodeKey: '',
                dropPosition: null
              });
      
              return;
            } // Ref: https://github.com/react-component/tree/issues/132
            // Add timeout to let onDragLevel fire before onDragEnter,
            // so that we can clean drag props for onDragLeave node.
            // Macro task for this:
            // https://html.spec.whatwg.org/multipage/webappapis.html#clean-up-after-running-script
      
      
            setTimeout(function () {
              // Update drag over node
              _this.setState({
                dragOverNodeKey: eventKey,
                dropPosition: dropPosition
              }); // Side effect for delay drag
      
      
              if (!_this.delayedDragEnterLogic) {
                _this.delayedDragEnterLogic = {};
              }
      
              Object.keys(_this.delayedDragEnterLogic).forEach(function (key) {
                clearTimeout(_this.delayedDragEnterLogic[key]);
              });
              _this.delayedDragEnterLogic[pos] = window.setTimeout(function () {
                if (!_this.state.dragging) return;
      
                var newExpandedKeys = Object(toConsumableArray["a" /* default */])(expandedKeys);
      
                var entity = keyEntities[eventKey];
      
                if (entity && (entity.children || []).length) {
                  newExpandedKeys = Object(util["a" /* arrAdd */])(expandedKeys, eventKey);
                }
      
                if (!('expandedKeys' in _this.props)) {
                  _this.setExpandedKeys(newExpandedKeys);
                }
      
                if (onDragEnter) {
                  onDragEnter({
                    event: event,
                    node: Object(treeUtil["b" /* convertNodePropsToEventData */])(node.props),
                    expandedKeys: newExpandedKeys
                  });
                }
              }, 400);
            }, 0);
          };
      
          _this.onNodeDragOver = function (event, node) {
            var dragNodesKeys = _this.state.dragNodesKeys;
            var onDragOver = _this.props.onDragOver;
            var eventKey = node.props.eventKey;
      
            if (dragNodesKeys.indexOf(eventKey) !== -1) {
              return;
            } // Update drag position
      
      
            if (_this.dragNode && eventKey === _this.state.dragOverNodeKey) {
              var dropPosition = Object(util["c" /* calcDropPosition */])(event, node);
              if (dropPosition === _this.state.dropPosition) return;
      
              _this.setState({
                dropPosition: dropPosition
              });
            }
      
            if (onDragOver) {
              onDragOver({
                event: event,
                node: Object(treeUtil["b" /* convertNodePropsToEventData */])(node.props)
              });
            }
          };
      
          _this.onNodeDragLeave = function (event, node) {
            var onDragLeave = _this.props.onDragLeave;
      
            _this.setState({
              dragOverNodeKey: ''
            });
      
            if (onDragLeave) {
              onDragLeave({
                event: event,
                node: Object(treeUtil["b" /* convertNodePropsToEventData */])(node.props)
              });
            }
          };
      
          _this.onNodeDragEnd = function (event, node) {
            var onDragEnd = _this.props.onDragEnd;
      
            _this.setState({
              dragOverNodeKey: ''
            });
      
            _this.cleanDragState();
      
            if (onDragEnd) {
              onDragEnd({
                event: event,
                node: Object(treeUtil["b" /* convertNodePropsToEventData */])(node.props)
              });
            }
      
            _this.dragNode = null;
          };
      
          _this.onNodeDrop = function (event, node) {
            var _this$state3 = _this.state,
                _this$state3$dragNode = _this$state3.dragNodesKeys,
                dragNodesKeys = _this$state3$dragNode === void 0 ? [] : _this$state3$dragNode,
                dropPosition = _this$state3.dropPosition;
            var onDrop = _this.props.onDrop;
            var _node$props2 = node.props,
                eventKey = _node$props2.eventKey,
                pos = _node$props2.pos;
      
            _this.setState({
              dragOverNodeKey: ''
            });
      
            _this.cleanDragState();
      
            if (dragNodesKeys.indexOf(eventKey) !== -1) {
              Object(warning["a" /* default */])(false, "Can not drop to dragNode(include it's children node)");
              return;
            }
      
            var posArr = Object(util["k" /* posToArr */])(pos);
            var dropResult = {
              event: event,
              node: Object(treeUtil["b" /* convertNodePropsToEventData */])(node.props),
              dragNode: _this.dragNode ? Object(treeUtil["b" /* convertNodePropsToEventData */])(_this.dragNode.props) : null,
              dragNodesKeys: dragNodesKeys.slice(),
              dropPosition: dropPosition + Number(posArr[posArr.length - 1]),
              dropToGap: false
            };
      
            if (dropPosition !== 0) {
              dropResult.dropToGap = true;
            }
      
            if (onDrop) {
              onDrop(dropResult);
            }
      
            _this.dragNode = null;
          };
      
          _this.cleanDragState = function () {
            var dragging = _this.state.dragging;
      
            if (dragging) {
              _this.setState({
                dragging: false
              });
            }
          };
      
          _this.onNodeClick = function (e, treeNode) {
            var onClick = _this.props.onClick;
      
            if (onClick) {
              onClick(e, treeNode);
            }
          };
      
          _this.onNodeDoubleClick = function (e, treeNode) {
            var onDoubleClick = _this.props.onDoubleClick;
      
            if (onDoubleClick) {
              onDoubleClick(e, treeNode);
            }
          };
      
          _this.onNodeSelect = function (e, treeNode) {
            var selectedKeys = _this.state.selectedKeys;
            var keyEntities = _this.state.keyEntities;
            var _this$props = _this.props,
                onSelect = _this$props.onSelect,
                multiple = _this$props.multiple;
            var selected = treeNode.selected,
                key = treeNode.key;
            var targetSelected = !selected; // Update selected keys
      
            if (!targetSelected) {
              selectedKeys = Object(util["b" /* arrDel */])(selectedKeys, key);
            } else if (!multiple) {
              selectedKeys = [key];
            } else {
              selectedKeys = Object(util["a" /* arrAdd */])(selectedKeys, key);
            } // [Legacy] Not found related usage in doc or upper libs
      
      
            var selectedNodes = selectedKeys.map(function (selectedKey) {
              var entity = keyEntities[selectedKey];
              if (!entity) return null;
              return entity.node;
            }).filter(function (node) {
              return node;
            });
      
            _this.setUncontrolledState({
              selectedKeys: selectedKeys
            });
      
            if (onSelect) {
              onSelect(selectedKeys, {
                event: 'select',
                selected: targetSelected,
                node: treeNode,
                selectedNodes: selectedNodes,
                nativeEvent: e.nativeEvent
              });
            }
          };
      
          _this.onNodeCheck = function (e, treeNode, checked) {
            var _this$state4 = _this.state,
                keyEntities = _this$state4.keyEntities,
                oriCheckedKeys = _this$state4.checkedKeys,
                oriHalfCheckedKeys = _this$state4.halfCheckedKeys;
            var _this$props2 = _this.props,
                checkStrictly = _this$props2.checkStrictly,
                onCheck = _this$props2.onCheck;
            var key = treeNode.key; // Prepare trigger arguments
      
            var checkedObj;
            var eventObj = {
              event: 'check',
              node: treeNode,
              checked: checked,
              nativeEvent: e.nativeEvent
            };
      
            if (checkStrictly) {
              var checkedKeys = checked ? Object(util["a" /* arrAdd */])(oriCheckedKeys, key) : Object(util["b" /* arrDel */])(oriCheckedKeys, key);
              var halfCheckedKeys = Object(util["b" /* arrDel */])(oriHalfCheckedKeys, key);
              checkedObj = {
                checked: checkedKeys,
                halfChecked: halfCheckedKeys
              };
              eventObj.checkedNodes = checkedKeys.map(function (checkedKey) {
                return keyEntities[checkedKey];
              }).filter(function (entity) {
                return entity;
              }).map(function (entity) {
                return entity.node;
              });
      
              _this.setUncontrolledState({
                checkedKeys: checkedKeys
              });
            } else {
              // Always fill first
              var _conductCheck = Object(conductUtil["a" /* conductCheck */])([].concat(Object(toConsumableArray["a" /* default */])(oriCheckedKeys), [key]), true, keyEntities),
                  _checkedKeys = _conductCheck.checkedKeys,
                  _halfCheckedKeys = _conductCheck.halfCheckedKeys; // If remove, we do it again to correction
      
      
              if (!checked) {
                var keySet = new Set(_checkedKeys);
                keySet.delete(key);
      
                var _conductCheck2 = Object(conductUtil["a" /* conductCheck */])(Array.from(keySet), {
                  checked: false,
                  halfCheckedKeys: _halfCheckedKeys
                }, keyEntities);
      
                _checkedKeys = _conductCheck2.checkedKeys;
                _halfCheckedKeys = _conductCheck2.halfCheckedKeys;
              }
      
              checkedObj = _checkedKeys; // [Legacy] This is used for `rc-tree-select`
      
              eventObj.checkedNodes = [];
              eventObj.checkedNodesPositions = [];
              eventObj.halfCheckedKeys = _halfCheckedKeys;
      
              _checkedKeys.forEach(function (checkedKey) {
                var entity = keyEntities[checkedKey];
                if (!entity) return;
                var node = entity.node,
                    pos = entity.pos;
                eventObj.checkedNodes.push(node);
                eventObj.checkedNodesPositions.push({
                  node: node,
                  pos: pos
                });
              });
      
              _this.setUncontrolledState({
                checkedKeys: _checkedKeys
              }, false, {
                halfCheckedKeys: _halfCheckedKeys
              });
            }
      
            if (onCheck) {
              onCheck(checkedObj, eventObj);
            }
          };
      
          _this.onNodeLoad = function (treeNode) {
            return new Promise(function (resolve) {
              // We need to get the latest state of loading/loaded keys
              _this.setState(function (_ref) {
                var _ref$loadedKeys = _ref.loadedKeys,
                    loadedKeys = _ref$loadedKeys === void 0 ? [] : _ref$loadedKeys,
                    _ref$loadingKeys = _ref.loadingKeys,
                    loadingKeys = _ref$loadingKeys === void 0 ? [] : _ref$loadingKeys;
                var _this$props3 = _this.props,
                    loadData = _this$props3.loadData,
                    onLoad = _this$props3.onLoad;
                var key = treeNode.key;
      
                if (!loadData || loadedKeys.indexOf(key) !== -1 || loadingKeys.indexOf(key) !== -1) {
                  // react 15 will warn if return null
                  return {};
                } // Process load data
      
      
                var promise = loadData(treeNode);
                promise.then(function () {
                  var _this$state5 = _this.state,
                      currentLoadedKeys = _this$state5.loadedKeys,
                      currentLoadingKeys = _this$state5.loadingKeys;
                  var newLoadedKeys = Object(util["a" /* arrAdd */])(currentLoadedKeys, key);
                  var newLoadingKeys = Object(util["b" /* arrDel */])(currentLoadingKeys, key); // onLoad should trigger before internal setState to avoid `loadData` trigger twice.
                  // https://github.com/ant-design/ant-design/issues/12464
      
                  if (onLoad) {
                    onLoad(newLoadedKeys, {
                      event: 'load',
                      node: treeNode
                    });
                  }
      
                  _this.setUncontrolledState({
                    loadedKeys: newLoadedKeys
                  });
      
                  _this.setState({
                    loadingKeys: newLoadingKeys
                  });
      
                  resolve();
                });
                return {
                  loadingKeys: Object(util["a" /* arrAdd */])(loadingKeys, key)
                };
              });
            });
          };
      
          _this.onNodeMouseEnter = function (event, node) {
            var onMouseEnter = _this.props.onMouseEnter;
      
            if (onMouseEnter) {
              onMouseEnter({
                event: event,
                node: node
              });
            }
          };
      
          _this.onNodeMouseLeave = function (event, node) {
            var onMouseLeave = _this.props.onMouseLeave;
      
            if (onMouseLeave) {
              onMouseLeave({
                event: event,
                node: node
              });
            }
          };
      
          _this.onNodeContextMenu = function (event, node) {
            var onRightClick = _this.props.onRightClick;
      
            if (onRightClick) {
              event.preventDefault();
              onRightClick({
                event: event,
                node: node
              });
            }
          };
      
          _this.onFocus = function () {
            var onFocus = _this.props.onFocus;
      
            _this.setState({
              focused: true
            });
      
            if (onFocus) {
              onFocus.apply(void 0, arguments);
            }
          };
      
          _this.onBlur = function () {
            var onBlur = _this.props.onBlur;
      
            _this.setState({
              focused: false
            });
      
            _this.onActiveChange(null);
      
            if (onBlur) {
              onBlur.apply(void 0, arguments);
            }
          };
      
          _this.getTreeNodeRequiredProps = function () {
            var _this$state6 = _this.state,
                expandedKeys = _this$state6.expandedKeys,
                selectedKeys = _this$state6.selectedKeys,
                loadedKeys = _this$state6.loadedKeys,
                loadingKeys = _this$state6.loadingKeys,
                checkedKeys = _this$state6.checkedKeys,
                halfCheckedKeys = _this$state6.halfCheckedKeys,
                dragOverNodeKey = _this$state6.dragOverNodeKey,
                dropPosition = _this$state6.dropPosition,
                keyEntities = _this$state6.keyEntities;
            return {
              expandedKeys: expandedKeys || [],
              selectedKeys: selectedKeys || [],
              loadedKeys: loadedKeys || [],
              loadingKeys: loadingKeys || [],
              checkedKeys: checkedKeys || [],
              halfCheckedKeys: halfCheckedKeys || [],
              dragOverNodeKey: dragOverNodeKey,
              dropPosition: dropPosition,
              keyEntities: keyEntities
            };
          }; // =========================== Expanded ===========================
      
          /** Set uncontrolled `expandedKeys`. This will also auto update `flattenNodes`. */
      
      
          _this.setExpandedKeys = function (expandedKeys) {
            var treeData = _this.state.treeData;
            var flattenNodes = Object(treeUtil["d" /* flattenTreeData */])(treeData, expandedKeys);
      
            _this.setUncontrolledState({
              expandedKeys: expandedKeys,
              flattenNodes: flattenNodes
            }, true);
          };
      
          _this.onNodeExpand = function (e, treeNode) {
            var expandedKeys = _this.state.expandedKeys;
            var listChanging = _this.state.listChanging;
            var _this$props4 = _this.props,
                onExpand = _this$props4.onExpand,
                loadData = _this$props4.loadData;
            var key = treeNode.key,
                expanded = treeNode.expanded; // Do nothing when motion is in progress
      
            if (listChanging) {
              return;
            } // Update selected keys
      
      
            var index = expandedKeys.indexOf(key);
            var targetExpanded = !expanded;
            Object(warning["a" /* default */])(expanded && index !== -1 || !expanded && index === -1, 'Expand state not sync with index check');
      
            if (targetExpanded) {
              expandedKeys = Object(util["a" /* arrAdd */])(expandedKeys, key);
            } else {
              expandedKeys = Object(util["b" /* arrDel */])(expandedKeys, key);
            }
      
            _this.setExpandedKeys(expandedKeys);
      
            if (onExpand) {
              onExpand(expandedKeys, {
                node: treeNode,
                expanded: targetExpanded,
                nativeEvent: e.nativeEvent
              });
            } // Async Load data
      
      
            if (targetExpanded && loadData) {
              var loadPromise = _this.onNodeLoad(treeNode);
      
              if (loadPromise) {
                loadPromise.then(function () {
                  // [Legacy] Refresh logic
                  var newFlattenTreeData = Object(treeUtil["d" /* flattenTreeData */])(_this.state.treeData, expandedKeys);
      
                  _this.setUncontrolledState({
                    flattenNodes: newFlattenTreeData
                  });
                });
              }
            }
          };
      
          _this.onListChangeStart = function () {
            _this.setUncontrolledState({
              listChanging: true
            });
          };
      
          _this.onListChangeEnd = function () {
            setTimeout(function () {
              _this.setUncontrolledState({
                listChanging: false
              });
            });
          }; // =========================== Keyboard ===========================
      
      
          _this.onActiveChange = function (newActiveKey) {
            var activeKey = _this.state.activeKey;
            var onActiveChange = _this.props.onActiveChange;
      
            if (activeKey === newActiveKey) {
              return;
            }
      
            _this.setState({
              activeKey: newActiveKey
            });
      
            if (newActiveKey !== null) {
              _this.scrollTo({
                key: newActiveKey
              });
            }
      
            if (onActiveChange) {
              onActiveChange(newActiveKey);
            }
          };
      
          _this.getActiveItem = function () {
            var _this$state7 = _this.state,
                activeKey = _this$state7.activeKey,
                flattenNodes = _this$state7.flattenNodes;
      
            if (activeKey === null) {
              return null;
            }
      
            return flattenNodes.find(function (_ref2) {
              var key = _ref2.data.key;
              return key === activeKey;
            }) || null;
          };
      
          _this.offsetActiveKey = function (offset) {
            var _this$state8 = _this.state,
                flattenNodes = _this$state8.flattenNodes,
                activeKey = _this$state8.activeKey;
            var index = flattenNodes.findIndex(function (_ref3) {
              var key = _ref3.data.key;
              return key === activeKey;
            }); // Align with index
      
            if (index === -1 && offset < 0) {
              index = flattenNodes.length;
            }
      
            index = (index + offset + flattenNodes.length) % flattenNodes.length;
            var item = flattenNodes[index];
      
            if (item) {
              var key = item.data.key;
      
              _this.onActiveChange(key);
            } else {
              _this.onActiveChange(null);
            }
          };
      
          _this.onKeyDown = function (event) {
            var _this$state9 = _this.state,
                activeKey = _this$state9.activeKey,
                expandedKeys = _this$state9.expandedKeys,
                checkedKeys = _this$state9.checkedKeys;
            var _this$props5 = _this.props,
                onKeyDown = _this$props5.onKeyDown,
                checkable = _this$props5.checkable,
                selectable = _this$props5.selectable; // >>>>>>>>>> Direction
      
            switch (event.which) {
              case KeyCode["a" /* default */].UP:
                {
                  _this.offsetActiveKey(-1);
      
                  event.preventDefault();
                  break;
                }
      
              case KeyCode["a" /* default */].DOWN:
                {
                  _this.offsetActiveKey(1);
      
                  event.preventDefault();
                  break;
                }
            } // >>>>>>>>>> Expand & Selection
      
      
            var activeItem = _this.getActiveItem();
      
            if (activeItem && activeItem.data) {
              var treeNodeRequiredProps = _this.getTreeNodeRequiredProps();
      
              var expandable = activeItem.data.isLeaf === false || !!(activeItem.data.children || []).length;
              var eventNode = Object(treeUtil["b" /* convertNodePropsToEventData */])(Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, Object(treeUtil["f" /* getTreeNodeProps */])(activeKey, treeNodeRequiredProps)), {}, {
                data: activeItem.data,
                active: true
              }));
      
              switch (event.which) {
                // >>> Expand
                case KeyCode["a" /* default */].LEFT:
                  {
                    // Collapse if possible
                    if (expandable && expandedKeys.includes(activeKey)) {
                      _this.onNodeExpand({}, eventNode);
                    } else if (activeItem.parent) {
                      _this.onActiveChange(activeItem.parent.data.key);
                    }
      
                    event.preventDefault();
                    break;
                  }
      
                case KeyCode["a" /* default */].RIGHT:
                  {
                    // Expand if possible
                    if (expandable && !expandedKeys.includes(activeKey)) {
                      _this.onNodeExpand({}, eventNode);
                    } else if (activeItem.children && activeItem.children.length) {
                      _this.onActiveChange(activeItem.children[0].data.key);
                    }
      
                    event.preventDefault();
                    break;
                  }
                // Selection
      
                case KeyCode["a" /* default */].ENTER:
                case KeyCode["a" /* default */].SPACE:
                  {
                    if (checkable && !eventNode.disabled && eventNode.checkable !== false && !eventNode.disableCheckbox) {
                      _this.onNodeCheck({}, eventNode, !checkedKeys.includes(activeKey));
                    } else if (!checkable && selectable && !eventNode.disabled && eventNode.selectable !== false) {
                      _this.onNodeSelect({}, eventNode);
                    }
      
                    break;
                  }
              }
            }
      
            if (onKeyDown) {
              onKeyDown(event);
            }
          };
          /**
           * Only update the value which is not in props
           */
      
      
          _this.setUncontrolledState = function (state) {
            var atomic = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
            var forceState = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
      
            if (_this.destroyed) {
              return;
            }
      
            var needSync = false;
            var allPassed = true;
            var newState = {};
            Object.keys(state).forEach(function (name) {
              if (name in _this.props) {
                allPassed = false;
                return;
              }
      
              needSync = true;
              newState[name] = state[name];
            });
      
            if (needSync && (!atomic || allPassed)) {
              _this.setState(Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, newState), forceState));
            }
          };
      
          _this.scrollTo = function (scroll) {
            _this.listRef.current.scrollTo(scroll);
          };
      
          return _this;
        }
      
        Object(createClass["a" /* default */])(Tree, [{
          key: "componentWillUnmount",
          value: function componentWillUnmount() {
            this.destroyed = true;
          }
        }, {
          key: "render",
          value: function render() {
            var _classNames;
      
            var _this$state10 = this.state,
                focused = _this$state10.focused,
                flattenNodes = _this$state10.flattenNodes,
                keyEntities = _this$state10.keyEntities,
                dragging = _this$state10.dragging,
                activeKey = _this$state10.activeKey;
            var _this$props6 = this.props,
                prefixCls = _this$props6.prefixCls,
                className = _this$props6.className,
                style = _this$props6.style,
                showLine = _this$props6.showLine,
                focusable = _this$props6.focusable,
                _this$props6$tabIndex = _this$props6.tabIndex,
                tabIndex = _this$props6$tabIndex === void 0 ? 0 : _this$props6$tabIndex,
                selectable = _this$props6.selectable,
                showIcon = _this$props6.showIcon,
                icon = _this$props6.icon,
                switcherIcon = _this$props6.switcherIcon,
                draggable = _this$props6.draggable,
                checkable = _this$props6.checkable,
                checkStrictly = _this$props6.checkStrictly,
                disabled = _this$props6.disabled,
                motion = _this$props6.motion,
                loadData = _this$props6.loadData,
                filterTreeNode = _this$props6.filterTreeNode,
                height = _this$props6.height,
                itemHeight = _this$props6.itemHeight,
                virtual = _this$props6.virtual,
                titleRender = _this$props6.titleRender,
                onContextMenu = _this$props6.onContextMenu;
            var domProps = Object(util["f" /* getDataAndAria */])(this.props);
            return external_window_React_["createElement"](contextTypes["a" /* TreeContext */].Provider, {
              value: {
                prefixCls: prefixCls,
                selectable: selectable,
                showIcon: showIcon,
                icon: icon,
                switcherIcon: switcherIcon,
                draggable: draggable,
                checkable: checkable,
                checkStrictly: checkStrictly,
                disabled: disabled,
                keyEntities: keyEntities,
                loadData: loadData,
                filterTreeNode: filterTreeNode,
                titleRender: titleRender,
                onNodeClick: this.onNodeClick,
                onNodeDoubleClick: this.onNodeDoubleClick,
                onNodeExpand: this.onNodeExpand,
                onNodeSelect: this.onNodeSelect,
                onNodeCheck: this.onNodeCheck,
                onNodeLoad: this.onNodeLoad,
                onNodeMouseEnter: this.onNodeMouseEnter,
                onNodeMouseLeave: this.onNodeMouseLeave,
                onNodeContextMenu: this.onNodeContextMenu,
                onNodeDragStart: this.onNodeDragStart,
                onNodeDragEnter: this.onNodeDragEnter,
                onNodeDragOver: this.onNodeDragOver,
                onNodeDragLeave: this.onNodeDragLeave,
                onNodeDragEnd: this.onNodeDragEnd,
                onNodeDrop: this.onNodeDrop
              }
            }, external_window_React_["createElement"]("div", {
              className: classnames_default()(prefixCls, className, (_classNames = {}, Object(defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-show-line"), showLine), Object(defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-focused"), focused), Object(defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-active-focused"), activeKey !== null), _classNames))
            }, external_window_React_["createElement"](es_NodeList, Object.assign({
              ref: this.listRef,
              prefixCls: prefixCls,
              style: style,
              data: flattenNodes,
              disabled: disabled,
              selectable: selectable,
              checkable: !!checkable,
              motion: motion,
              dragging: dragging,
              height: height,
              itemHeight: itemHeight,
              virtual: virtual,
              focusable: focusable,
              focused: focused,
              tabIndex: tabIndex,
              activeItem: this.getActiveItem(),
              onFocus: this.onFocus,
              onBlur: this.onBlur,
              onKeyDown: this.onKeyDown,
              onActiveChange: this.onActiveChange,
              onListChangeStart: this.onListChangeStart,
              onListChangeEnd: this.onListChangeEnd,
              onContextMenu: onContextMenu
            }, this.getTreeNodeRequiredProps(), domProps))));
          }
        }], [{
          key: "getDerivedStateFromProps",
          value: function getDerivedStateFromProps(props, prevState) {
            var prevProps = prevState.prevProps;
            var newState = {
              prevProps: props
            };
      
            function needSync(name) {
              return !prevProps && name in props || prevProps && prevProps[name] !== props[name];
            } // ================== Tree Node ==================
      
      
            var treeData; // Check if `treeData` or `children` changed and save into the state.
      
            if (needSync('treeData')) {
              treeData = props.treeData;
            } else if (needSync('children')) {
              Object(warning["a" /* default */])(false, '`children` of Tree is deprecated. Please use `treeData` instead.');
              treeData = Object(treeUtil["c" /* convertTreeToData */])(props.children);
            } // Save flatten nodes info and convert `treeData` into keyEntities
      
      
            if (treeData) {
              newState.treeData = treeData;
              var entitiesMap = Object(treeUtil["a" /* convertDataToEntities */])(treeData);
              newState.keyEntities = Object(objectSpread2["a" /* default */])(Object(defineProperty["a" /* default */])({}, MOTION_KEY, MotionEntity), entitiesMap.keyEntities); // Warning if treeNode not provide key
      
              if (false) {}
            }
      
            var keyEntities = newState.keyEntities || prevState.keyEntities; // ================ expandedKeys =================
      
            if (needSync('expandedKeys') || prevProps && needSync('autoExpandParent')) {
              newState.expandedKeys = props.autoExpandParent || !prevProps && props.defaultExpandParent ? Object(util["e" /* conductExpandParent */])(props.expandedKeys, keyEntities) : props.expandedKeys;
            } else if (!prevProps && props.defaultExpandAll) {
              var cloneKeyEntities = Object(objectSpread2["a" /* default */])({}, keyEntities);
      
              delete cloneKeyEntities[MOTION_KEY];
              newState.expandedKeys = Object.keys(cloneKeyEntities).map(function (key) {
                return cloneKeyEntities[key].key;
              });
            } else if (!prevProps && props.defaultExpandedKeys) {
              newState.expandedKeys = props.autoExpandParent || props.defaultExpandParent ? Object(util["e" /* conductExpandParent */])(props.defaultExpandedKeys, keyEntities) : props.defaultExpandedKeys;
            }
      
            if (!newState.expandedKeys) {
              delete newState.expandedKeys;
            } // ================ flattenNodes =================
      
      
            if (treeData || newState.expandedKeys) {
              var flattenNodes = Object(treeUtil["d" /* flattenTreeData */])(treeData || prevState.treeData, newState.expandedKeys || prevState.expandedKeys);
              newState.flattenNodes = flattenNodes;
            } // ================ selectedKeys =================
      
      
            if (props.selectable) {
              if (needSync('selectedKeys')) {
                newState.selectedKeys = Object(util["d" /* calcSelectedKeys */])(props.selectedKeys, props);
              } else if (!prevProps && props.defaultSelectedKeys) {
                newState.selectedKeys = Object(util["d" /* calcSelectedKeys */])(props.defaultSelectedKeys, props);
              }
            } // ================= checkedKeys =================
      
      
            if (props.checkable) {
              var checkedKeyEntity;
      
              if (needSync('checkedKeys')) {
                checkedKeyEntity = Object(util["j" /* parseCheckedKeys */])(props.checkedKeys) || {};
              } else if (!prevProps && props.defaultCheckedKeys) {
                checkedKeyEntity = Object(util["j" /* parseCheckedKeys */])(props.defaultCheckedKeys) || {};
              } else if (treeData) {
                // If `treeData` changed, we also need check it
                checkedKeyEntity = Object(util["j" /* parseCheckedKeys */])(props.checkedKeys) || {
                  checkedKeys: prevState.checkedKeys,
                  halfCheckedKeys: prevState.halfCheckedKeys
                };
              }
      
              if (checkedKeyEntity) {
                var _checkedKeyEntity = checkedKeyEntity,
                    _checkedKeyEntity$che = _checkedKeyEntity.checkedKeys,
                    checkedKeys = _checkedKeyEntity$che === void 0 ? [] : _checkedKeyEntity$che,
                    _checkedKeyEntity$hal = _checkedKeyEntity.halfCheckedKeys,
                    halfCheckedKeys = _checkedKeyEntity$hal === void 0 ? [] : _checkedKeyEntity$hal;
      
                if (!props.checkStrictly) {
                  var conductKeys = Object(conductUtil["a" /* conductCheck */])(checkedKeys, true, keyEntities);
                  checkedKeys = conductKeys.checkedKeys;
                  halfCheckedKeys = conductKeys.halfCheckedKeys;
                }
      
                newState.checkedKeys = checkedKeys;
                newState.halfCheckedKeys = halfCheckedKeys;
              }
            } // ================= loadedKeys ==================
      
      
            if (needSync('loadedKeys')) {
              newState.loadedKeys = props.loadedKeys;
            }
      
            return newState;
          }
        }]);
      
        return Tree;
      }(external_window_React_["Component"]);
      
      Tree_Tree.defaultProps = {
        prefixCls: 'rc-tree',
        showLine: false,
        showIcon: true,
        selectable: true,
        multiple: false,
        checkable: false,
        disabled: false,
        checkStrictly: false,
        draggable: false,
        defaultExpandParent: true,
        autoExpandParent: false,
        defaultExpandAll: false,
        defaultExpandedKeys: [],
        defaultCheckedKeys: [],
        defaultSelectedKeys: []
      };
      Tree_Tree.TreeNode = TreeNode["a" /* default */];
      /* harmony default export */ var es_Tree = (Tree_Tree);
      // CONCATENATED MODULE: ./node_modules/rc-tree/es/index.js
      
      
      
      /* harmony default export */ var rc_tree_es = __webpack_exports__["b"] = (es_Tree);
      
      /***/ }),
      
      /***/ "iris":
      /*!*************************************************!*\
        !*** ./src/components/LanguageSelect/index.tsx ***!
        \*************************************************/
      /*! exports provided: LanguageSelect */
      /*! exports used: LanguageSelect */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return LanguageSelect; });
      /* harmony import */ var antd_es_dropdown_style__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! antd/es/dropdown/style */ "qVdP");
      /* harmony import */ var antd_es_dropdown__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! antd/es/dropdown */ "jsC+");
      /* harmony import */ var antd_es_menu_style__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! antd/es/menu/style */ "lUTK");
      /* harmony import */ var antd_es_menu__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! antd/es/menu */ "BvKs");
      /* harmony import */ var _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/slicedToArray */ "tJVT");
      /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! react */ "cDcd");
      /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_5__);
      /* harmony import */ var _index_less_modules__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./index.less?modules */ "Q0Vu");
      /* harmony import */ var _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_index_less_modules__WEBPACK_IMPORTED_MODULE_6__);
      
      
      
      
      
      
      
      var typeData = [{
        name: "编程题",
        value: "PROGRAM"
      }, {
        name: "单选题",
        value: "SINGLE"
      }, {
        name: "多选题",
        value: "MULTIPLE"
      }, {
        name: "判断题",
        value: "JUDGMENT"
      }, {
        name: "填空题",
        value: "COMPLETION"
      }, {
        name: "简答题",
        value: "SUBJECTIVE"
      }, {
        name: "组合题",
        value: "COMBINATION"
      }];
      var difficultyData = [{
        name: "简单",
        value: 1
      }, {
        name: "适中",
        value: 2
      }, {
        name: "困难",
        value: 3
      }];
      var randomData = [{
        name: "随机组卷",
        value: 1
      }, {
        name: "人工组卷",
        value: 2
      }];
      var LanguageSelect = function LanguageSelect(_ref) {
        var _ref$showSelectAll = _ref.showSelectAll,
            showSelectAll = _ref$showSelectAll === void 0 ? false : _ref$showSelectAll,
            _ref$disciplinesData = _ref.disciplinesData,
            disciplinesData = _ref$disciplinesData === void 0 ? [] : _ref$disciplinesData,
            _ref$knowledgeData = _ref.knowledgeData,
            knowledgeData = _ref$knowledgeData === void 0 ? [] : _ref$knowledgeData,
            directionValue = _ref.directionValue,
            subDisciplineValue = _ref.subDisciplineValue,
            typeValue = _ref.typeValue,
            knowledgeValue = _ref.knowledgeValue,
            _ref$showKnowledge = _ref.showKnowledge,
            showKnowledge = _ref$showKnowledge === void 0 ? false : _ref$showKnowledge,
            _ref$showRandomType = _ref.showRandomType,
            showRandomType = _ref$showRandomType === void 0 ? false : _ref$showRandomType,
            difficultyValue = _ref.difficultyValue,
            randomValue = _ref.randomValue,
            selectAll = _ref.selectAll,
            languagesvalue = _ref.languagesvalue,
            className = _ref.className,
            _ref$languages = _ref.languages,
            languages = _ref$languages === void 0 ? [] : _ref$languages,
            isprogram_homework = _ref.isprogram_homework,
            _ref$showShixun = _ref.showShixun,
            showShixun = _ref$showShixun === void 0 ? false : _ref$showShixun,
            _ref$showItemType = _ref.showItemType,
            showItemType = _ref$showItemType === void 0 ? true : _ref$showItemType,
            _ref$onShixunChange = _ref.onShixunChange,
            onShixunChange = _ref$onShixunChange === void 0 ? function () {} : _ref$onShixunChange,
            _ref$onDirectionChang = _ref.onDirectionChange,
            onDirectionChange = _ref$onDirectionChang === void 0 ? function () {} : _ref$onDirectionChang,
            _ref$onTypeChange = _ref.onTypeChange,
            onTypeChange = _ref$onTypeChange === void 0 ? function () {} : _ref$onTypeChange,
            _ref$onDifficultyChan = _ref.onDifficultyChange,
            onDifficultyChange = _ref$onDifficultyChan === void 0 ? function () {} : _ref$onDifficultyChan,
            _ref$handlelanguagesC = _ref.handlelanguagesChange,
            handlelanguagesChange = _ref$handlelanguagesC === void 0 ? function () {} : _ref$handlelanguagesC,
            _ref$onKnowledgeChang = _ref.onKnowledgeChange,
            onKnowledgeChange = _ref$onKnowledgeChang === void 0 ? function () {} : _ref$onKnowledgeChang,
            _ref$onRandomChange = _ref.onRandomChange,
            onRandomChange = _ref$onRandomChange === void 0 ? function () {} : _ref$onRandomChange,
            _ref$showTeachGroup = _ref.showTeachGroup,
            showTeachGroup = _ref$showTeachGroup === void 0 ? false : _ref$showTeachGroup,
            _ref$teachGroupData = _ref.teachGroupData,
            teachGroupData = _ref$teachGroupData === void 0 ? [] : _ref$teachGroupData,
            _ref$onTeachGroupChan = _ref.onTeachGroupChange,
            onTeachGroupChange = _ref$onTeachGroupChan === void 0 ? function () {} : _ref$onTeachGroupChan,
            teachGroupValue = _ref.teachGroupValue;
      
        var _useState = Object(react__WEBPACK_IMPORTED_MODULE_5__["useState"])(0),
            _useState2 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_4__[/* default */ "a"])(_useState, 2),
            directionShow = _useState2[0],
            setDirectionShow = _useState2[1];
      
        var directionWarp = Object(react__WEBPACK_IMPORTED_MODULE_5__["useRef"])(null);
      
        var _useState3 = Object(react__WEBPACK_IMPORTED_MODULE_5__["useState"])(0),
            _useState4 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_4__[/* default */ "a"])(_useState3, 2),
            knowledgeShow = _useState4[0],
            setKnowledgeShow = _useState4[1];
      
        var knowledgeWarp = Object(react__WEBPACK_IMPORTED_MODULE_5__["useRef"])(null);
        Object(react__WEBPACK_IMPORTED_MODULE_5__["useEffect"])(function () {
          if (disciplinesData.length !== 0) {
            var _directionWarp$curren;
      
            if ((directionWarp === null || directionWarp === void 0 ? void 0 : (_directionWarp$curren = directionWarp.current) === null || _directionWarp$curren === void 0 ? void 0 : _directionWarp$curren.clientHeight) > 108) {
              setDirectionShow(1);
            } else {
              setDirectionShow(0);
            }
          }
      
          if (disciplinesData.length === 0) {
            setDirectionShow(0);
          }
        }, [disciplinesData]);
        Object(react__WEBPACK_IMPORTED_MODULE_5__["useEffect"])(function () {
          console.log(knowledgeData.length === 0, '数量');
      
          if (knowledgeData.length !== 0) {
            var _knowledgeWarp$curren, _knowledgeWarp$curren2;
      
            console.log(knowledgeWarp === null || knowledgeWarp === void 0 ? void 0 : (_knowledgeWarp$curren = knowledgeWarp.current) === null || _knowledgeWarp$curren === void 0 ? void 0 : _knowledgeWarp$curren.clientHeight, '高度'); //两个像素的偏差106+2
      
            if ((knowledgeWarp === null || knowledgeWarp === void 0 ? void 0 : (_knowledgeWarp$curren2 = knowledgeWarp.current) === null || _knowledgeWarp$curren2 === void 0 ? void 0 : _knowledgeWarp$curren2.clientHeight) > 108) {
              setKnowledgeShow(1);
            } else {
              setKnowledgeShow(0);
            }
          }
      
          if (knowledgeData.length === 0) {
            setKnowledgeShow(0);
          }
        }, [knowledgeData]);
      
        var renderMenu = function renderMenu() {
          var sub_disciplines = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
          var id = arguments.length > 1 ? arguments[1] : undefined;
          return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement(antd_es_menu__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"], {
            className: _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.subMenu
          }, sub_disciplines.map(function (item) {
            return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement(antd_es_menu__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].Item, {
              key: item.id
            }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("a", {
              className: "".concat(_index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.subItem, " ").concat(subDisciplineValue === item.id ? _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.subActive : ''),
              onClick: function onClick() {
                return onDirectionChange(id, item.id);
              }
            }, item.name));
          }));
        };
      
        return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("aside", {
          className: className ? "".concat(_index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.main, " ").concat(className) : _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.main
        }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.wrap
        }, isprogram_homework && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.programName
        }, "\u8BD5\u9898\u5E93-\u7F16\u7A0B\u9898"), showTeachGroup && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.content
        }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("span", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.name
        }, "\u56E2\u961F"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.directionContentWrap
        }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("li", {
          className: "".concat(_index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.directionItem, " ").concat(!teachGroupValue ? _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.active : '', " "),
          onClick: function onClick() {
            return onTeachGroupChange(null);
          }
        }, "\u5168\u90E8"), teachGroupData === null || teachGroupData === void 0 ? void 0 : teachGroupData.map(function (item) {
          return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("li", {
            key: item.group_id,
            className: "".concat(_index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.directionItem, " ").concat(teachGroupValue === item.group_id ? _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.active : '', " "),
            onClick: function onClick() {
              return onTeachGroupChange(item.group_id);
            }
          }, item.name);
        }))), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.content
        }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("span", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.name
        }, "\u65B9\u5411"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("span", null), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.directionContentWrap,
          style: {
            overflow: 'hidden',
            height: directionShow === 1 ? 88 : 'auto'
          }
        }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("li", {
          className: "".concat(_index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.directionItem, " ").concat(!directionValue ? _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.active : '', " "),
          onClick: function onClick() {
            return onDirectionChange(null);
          }
        }, "\u5168\u90E8"), disciplinesData.map(function (item) {
          var _item$sub_disciplines;
      
          return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_5___default.a.Fragment, {
            key: item.id
          }, ((_item$sub_disciplines = item.sub_disciplines) === null || _item$sub_disciplines === void 0 ? void 0 : _item$sub_disciplines.length) > 0 ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement(antd_es_dropdown__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"], {
            placement: "bottomLeft",
            overlayStyle: {
              width: 600
            },
            getPopupContainer: function getPopupContainer(trigger) {
              return trigger.parentNode;
            },
            overlay: function overlay() {
              return renderMenu(item.sub_disciplines, item.id);
            }
          }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("li", {
            className: "".concat(_index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.directionItem, " ").concat(directionValue === item.id ? _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.active : '', " "),
            onClick: function onClick() {
              return onDirectionChange(item.id);
            }
          }, item.name)) : /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("li", {
            className: "".concat(_index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.directionItem, " ").concat(directionValue === item.id ? _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.active : '', " "),
            onClick: function onClick() {
              return onDirectionChange(item.id);
            }
          }, item.name));
        })), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.directionContentWrap,
          ref: directionWarp,
          style: {
            height: 'auto',
            position: 'fixed',
            left: 0,
            top: 0,
            width: 1024,
            visibility: 'hidden'
          }
        }, disciplinesData.map(function (item) {
          var _item$sub_disciplines2;
      
          return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_5___default.a.Fragment, {
            key: item.id
          }, ((_item$sub_disciplines2 = item.sub_disciplines) === null || _item$sub_disciplines2 === void 0 ? void 0 : _item$sub_disciplines2.length) > 0 ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement(antd_es_dropdown__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"], {
            placement: "bottomLeft",
            overlayStyle: {
              width: 600
            },
            getPopupContainer: function getPopupContainer(trigger) {
              return trigger.parentNode;
            },
            overlay: function overlay() {
              return renderMenu(item.sub_disciplines, item.id);
            }
          }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("li", {
            className: "".concat(_index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.directionItem, " ").concat(directionValue === item.id ? _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.active : '', " "),
            onClick: function onClick() {
              return onDirectionChange(item.id);
            }
          }, item.name)) : /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("li", {
            className: "".concat(_index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.directionItem, " ").concat(directionValue === item.id ? _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.active : '', " "),
            onClick: function onClick() {
              return onDirectionChange(item.id);
            }
          }, item.name));
        })), !!directionShow && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.action
        }, directionShow === 1 && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("span", {
          onClick: function onClick() {
            return setDirectionShow(2);
          }
        }, "\u5C55\u5F00", /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("i", {
          className: "iconfont icon-xiala"
        })), directionShow === 2 && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("span", {
          onClick: function onClick() {
            return setDirectionShow(1);
          }
        }, "\u6536\u8D77", /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("i", {
          style: {
            transform: 'scale(0.5) rotate(180deg) translateY(2px)'
          },
          className: "iconfont icon-xiala"
        })))), showKnowledge && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.content
        }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("span", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.name
        }, "\u77E5\u8BC6\u70B9"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.directionContentWrap,
          style: {
            overflow: 'hidden',
            height: knowledgeShow === 1 ? 106 : 'auto'
          }
        }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("li", {
          className: "".concat(_index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.directionItem, " ").concat(knowledgeValue === -1 ? _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.active : '', " "),
          onClick: function onClick() {
            return onKnowledgeChange(-1);
          }
        }, "\u5168\u90E8"), knowledgeData.map(function (item) {
          return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("li", {
            key: item.id,
            className: "".concat(_index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.directionItem, " ").concat(knowledgeValue === item.id ? _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.active : '', " "),
            onClick: function onClick() {
              return onKnowledgeChange(item.id);
            }
          }, item.name);
        })), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
          ref: knowledgeWarp,
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.directionContentWrap,
          style: {
            height: 'auto',
            position: 'fixed',
            left: 0,
            top: 0,
            width: 1010,
            visibility: 'hidden'
          }
        }, knowledgeData.map(function (item) {
          return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("li", {
            key: item.id,
            className: "".concat(_index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.directionItem, " ").concat(knowledgeValue === item.id ? _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.active : '', " "),
            onClick: function onClick() {
              return onKnowledgeChange(item.id);
            }
          }, item.name);
        })), !!knowledgeShow && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.action
        }, knowledgeShow === 1 && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("span", {
          onClick: function onClick() {
            return setKnowledgeShow(2);
          }
        }, "\u5C55\u5F00", /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("i", {
          className: "iconfont icon-xiala"
        })), knowledgeShow === 2 && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("span", {
          onClick: function onClick() {
            return setKnowledgeShow(1);
          }
        }, "\u6536\u8D77", /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("i", {
          style: {
            transform: 'scale(0.5) rotate(180deg) translateY(2px)'
          },
          className: "iconfont icon-xiala"
        })))), showItemType && !isprogram_homework && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.content
        }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("span", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.name
        }, "\u9898\u578B"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("li", {
          className: "".concat(_index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.directionItem, " ").concat(!typeValue ? _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.active : '', " "),
          onClick: function onClick() {
            return onTypeChange(null);
          }
        }, "\u5168\u90E8"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.directionContentWrap
        }, typeData.map(function (item) {
          return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("li", {
            key: item.name,
            className: "".concat(_index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.directionItem, " ").concat(typeValue === item.value ? _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.active : '', " "),
            onClick: function onClick() {
              return onTypeChange(item.value);
            }
          }, item.name);
        }), showShixun && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("li", {
          key: "\u5B9E\u8BAD\u9898",
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.directionItem,
          onClick: function onClick() {
            return onShixunChange();
          }
        }, "\u5B9E\u8BAD\u9898"))), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.content
        }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("span", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.name
        }, "\u96BE\u5EA6"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("li", {
          className: "".concat(_index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.directionItem, " ").concat(!difficultyValue ? _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.active : '', " "),
          onClick: function onClick() {
            return onDifficultyChange(null);
          }
        }, "\u5168\u90E8"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.directionContentWrap
        }, difficultyData.map(function (item) {
          return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("li", {
            key: item.name,
            className: "".concat(_index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.directionItem, " ").concat(difficultyValue === item.value ? _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.active : '', " "),
            onClick: function onClick() {
              return onDifficultyChange(item.value);
            }
          }, item.name);
        }))), showRandomType && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.content
        }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("span", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.name
        }, "\u7C7B\u578B"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("li", {
          className: "".concat(_index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.directionItem, " ").concat(!randomValue ? _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.active : '', " "),
          onClick: function onClick() {
            return onRandomChange(null);
          }
        }, "\u5168\u90E8"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.directionContentWrap
        }, randomData.map(function (item) {
          return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("li", {
            key: item.name,
            className: "".concat(_index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.directionItem, " ").concat(randomValue === item.value ? _index_less_modules__WEBPACK_IMPORTED_MODULE_6___default.a.active : '', " "),
            onClick: function onClick() {
              return onRandomChange(item.value);
            }
          }, item.name);
        })))));
      };
      
      /***/ }),
      
      /***/ "jcZT":
      /*!************************************************************!*\
        !*** ./src/pages/Problemset/components/AddModal/index.tsx ***!
        \************************************************************/
      /*! exports provided: default */
      /*! exports used: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      /* harmony import */ var antd_es_modal_style__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! antd/es/modal/style */ "2qtc");
      /* harmony import */ var antd_es_modal__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! antd/es/modal */ "kLXV");
      /* harmony import */ var antd_es_input_style__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! antd/es/input/style */ "5NDa");
      /* harmony import */ var antd_es_input__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! antd/es/input */ "5rEg");
      /* harmony import */ var antd_es_message_style__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! antd/es/message/style */ "miYZ");
      /* harmony import */ var antd_es_message__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! antd/es/message */ "tsqr");
      /* harmony import */ var _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_asyncToGenerator__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/asyncToGenerator */ "9og8");
      /* harmony import */ var _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/slicedToArray */ "tJVT");
      /* harmony import */ var _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/regenerator */ "WmNS");
      /* harmony import */ var _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_8__);
      /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! react */ "cDcd");
      /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_9__);
      /* harmony import */ var _index_less_modules__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./index.less?modules */ "d5o6");
      /* harmony import */ var _index_less_modules__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_index_less_modules__WEBPACK_IMPORTED_MODULE_10__);
      /* harmony import */ var _components_CustomTree__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @/components/CustomTree */ "P/tu");
      /* harmony import */ var _service_problemset__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @/service/problemset */ "WCUW");
      /* harmony import */ var umi__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! umi */ "9kvl");
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      var ShareModal = function ShareModal(_ref) {
        var problemset = _ref.problemset,
            dispatch = _ref.dispatch,
            onOk = _ref.onOk;
      
        var _useState = Object(react__WEBPACK_IMPORTED_MODULE_9__["useState"])(''),
            _useState2 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_7__[/* default */ "a"])(_useState, 2),
            value = _useState2[0],
            setValue = _useState2[1];
      
        var _useState3 = Object(react__WEBPACK_IMPORTED_MODULE_9__["useState"])([0]),
            _useState4 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_7__[/* default */ "a"])(_useState3, 2),
            selectedKeys = _useState4[0],
            setSelectedKeys = _useState4[1];
      
        var handleCancel = function handleCancel() {
          dispatch({
            type: 'problemset/setActionTabs',
            payload: {}
          });
        };
      
        Object(react__WEBPACK_IMPORTED_MODULE_9__["useEffect"])(function () {
          if (problemset.actionTabs.key === '新建文件夹') {
            var _problemset$actionTab, _problemset$actionTab2;
      
            setSelectedKeys([(_problemset$actionTab = problemset.actionTabs) === null || _problemset$actionTab === void 0 ? void 0 : (_problemset$actionTab2 = _problemset$actionTab.params) === null || _problemset$actionTab2 === void 0 ? void 0 : _problemset$actionTab2.group_id]);
            setValue('');
          }
        }, [problemset.actionTabs.key]);
      
        var handleOk = /*#__PURE__*/function () {
          var _ref2 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_asyncToGenerator__WEBPACK_IMPORTED_MODULE_6__[/* default */ "a"])( /*#__PURE__*/_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_8___default.a.mark(function _callee() {
            var array, i, res;
            return _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_8___default.a.wrap(function _callee$(_context) {
              while (1) {
                switch (_context.prev = _context.next) {
                  case 0:
                    array = ['?', '、', '/', '╲', '*', '<', '>', '|'];
      
                    if (value.trim()) {
                      _context.next = 4;
                      break;
                    }
      
                    antd_es_message__WEBPACK_IMPORTED_MODULE_5__[/* default */ "b"].warn('请输入文件夹名称');
      
                    return _context.abrupt("return");
      
                  case 4:
                    if (!(value.charAt(0) === ' ')) {
                      _context.next = 7;
                      break;
                    }
      
                    antd_es_message__WEBPACK_IMPORTED_MODULE_5__[/* default */ "b"].warn('首字符不能为空格');
      
                    return _context.abrupt("return");
      
                  case 7:
                    i = 0;
      
                  case 8:
                    if (!(i < value.length)) {
                      _context.next = 15;
                      break;
                    }
      
                    if (!array.includes(value.charAt(i))) {
                      _context.next = 12;
                      break;
                    }
      
                    antd_es_message__WEBPACK_IMPORTED_MODULE_5__[/* default */ "b"].warn('文件夹名称包含特殊字符');
      
                    return _context.abrupt("return", false);
      
                  case 12:
                    i++;
                    _context.next = 8;
                    break;
      
                  case 15:
                    _context.next = 17;
                    return Object(_service_problemset__WEBPACK_IMPORTED_MODULE_12__[/* createGroup */ "p"])({
                      parent_id: selectedKeys.length > 0 ? selectedKeys[0] : 0,
                      name: value
                    });
      
                  case 17:
                    res = _context.sent;
      
                    if (res.status === 0) {
                      handleCancel();
                      onOk(res === null || res === void 0 ? void 0 : res.id);
                    }
      
                  case 19:
                  case "end":
                    return _context.stop();
                }
              }
            }, _callee);
          }));
      
          return function handleOk() {
            return _ref2.apply(this, arguments);
          };
        }();
      
        return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_9___default.a.createElement(antd_es_modal__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"], {
          centered: true,
          title: "\u65B0\u5EFA\u6587\u4EF6\u5939",
          visible: problemset.actionTabs.key === '新建文件夹' ? true : false // visible
          ,
          width: 500,
          onCancel: handleCancel,
          onOk: handleOk,
          destroyOnClose: true
        }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_9___default.a.createElement("div", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_10___default.a.addModal
        }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_9___default.a.createElement("div", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_10___default.a.row
        }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_9___default.a.createElement("span", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_10___default.a.label
        }, "\u6587\u4EF6\u5939\u540D\u79F0: "), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_9___default.a.createElement(antd_es_input__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"], {
          placeholder: "\u8BF7\u8F93\u5165\u6587\u4EF6\u5939\u540D\u79F0",
          value: value,
          onChange: function onChange(e) {
            return setValue(e.target.value);
          }
        })), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_9___default.a.createElement("div", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_10___default.a.row,
          style: {
            alignItems: 'start',
            maxHeight: 500,
            overflow: 'auto'
          }
        }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_9___default.a.createElement("span", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_10___default.a.label
        }, "\u6587\u4EF6\u5939\u4F4D\u7F6E: "), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_9___default.a.createElement(_components_CustomTree__WEBPACK_IMPORTED_MODULE_11__[/* default */ "a"], {
          value: selectedKeys,
          onChange: function onChange(e) {
            return setSelectedKeys(e);
          }
        }))));
      };
      
      /* harmony default export */ __webpack_exports__["a"] = (Object(umi__WEBPACK_IMPORTED_MODULE_13__[/* connect */ "a"])(function (_ref3) {
        var problemset = _ref3.problemset;
        return {
          problemset: problemset
        };
      })(ShareModal));
      
      /***/ }),
      
      /***/ "k3GJ":
      /*!*******************************************************!*\
        !*** ./node_modules/rc-tabs/es/index.js + 50 modules ***!
        \*******************************************************/
      /*! exports provided: TabPane, default */
      /*! exports used: TabPane, default */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/classCallCheck.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/createClass.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/createSuper.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/defineProperty.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/extends.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/inherits.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/objectSpread2.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/slicedToArray.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/toConsumableArray.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/typeof.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/regenerator/index.js (<- Module is not an ECMAScript module) */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/classnames/index.js (<- Module is not an ECMAScript module) */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/mini-store/esm/index.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/raf/index.js (<- Module is not an ECMAScript module) */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-align/es/index.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-dropdown/es/index.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-resize-observer/es/index.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/Children/toArray.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/Dom/addEventListener.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/Dom/canUseDom.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/Dom/contains.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/Dom/findDOMNode.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/KeyCode.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/Portal.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/createChainedFunction.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/hooks/useMergedState.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/omit.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/raf.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/ref.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/warning.js */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/resize-observer-polyfill/dist/ResizeObserver.es.js (<- Module uses injected variables (global)) */
      /*! ModuleConcatenation bailout: Cannot concat with ./node_modules/shallowequal/index.js (<- Module is not an ECMAScript module) */
      /*! ModuleConcatenation bailout: Cannot concat with external "window.React" (<- Module is not an ECMAScript module) */
      /*! ModuleConcatenation bailout: Cannot concat with external "window.ReactDOM" (<- Module is not an ECMAScript module) */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      
      // EXPORTS
      __webpack_require__.d(__webpack_exports__, "a", function() { return /* reexport */ TabPane; });
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/defineProperty.js
      var defineProperty = __webpack_require__("rePB");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/slicedToArray.js + 1 modules
      var slicedToArray = __webpack_require__("ODXe");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js
      var objectWithoutProperties = __webpack_require__("Ff2n");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/objectSpread2.js
      var objectSpread2 = __webpack_require__("VTBJ");
      
      // EXTERNAL MODULE: external "window.React"
      var external_window_React_ = __webpack_require__("cDcd");
      
      // EXTERNAL MODULE: ./node_modules/classnames/index.js
      var classnames = __webpack_require__("TSYQ");
      var classnames_default = /*#__PURE__*/__webpack_require__.n(classnames);
      
      // EXTERNAL MODULE: ./node_modules/rc-util/es/Children/toArray.js
      var toArray = __webpack_require__("Zm9Q");
      
      // EXTERNAL MODULE: ./node_modules/rc-util/es/hooks/useMergedState.js
      var useMergedState = __webpack_require__("6cGi");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/toConsumableArray.js + 2 modules
      var toConsumableArray = __webpack_require__("KQm4");
      
      // EXTERNAL MODULE: ./node_modules/raf/index.js
      var raf = __webpack_require__("xEkU");
      var raf_default = /*#__PURE__*/__webpack_require__.n(raf);
      
      // EXTERNAL MODULE: ./node_modules/rc-resize-observer/es/index.js
      var es = __webpack_require__("t23M");
      
      // CONCATENATED MODULE: ./node_modules/rc-tabs/es/hooks/useRaf.js
      
      
      
      function useRaf(callback) {
        var rafRef = Object(external_window_React_["useRef"])();
        var removedRef = Object(external_window_React_["useRef"])(false);
      
        function trigger() {
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
      
          if (!removedRef.current) {
            raf_default.a.cancel(rafRef.current);
            rafRef.current = raf_default()(function () {
              callback.apply(void 0, args);
            });
          }
        }
      
        Object(external_window_React_["useEffect"])(function () {
          return function () {
            removedRef.current = true;
            raf_default.a.cancel(rafRef.current);
          };
        }, []);
        return trigger;
      }
      function useRafState(defaultState) {
        var batchRef = Object(external_window_React_["useRef"])([]);
      
        var _useState = Object(external_window_React_["useState"])({}),
            _useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
            forceUpdate = _useState2[1];
      
        var state = Object(external_window_React_["useRef"])(typeof defaultState === 'function' ? defaultState() : defaultState);
        var flushUpdate = useRaf(function () {
          var current = state.current;
          batchRef.current.forEach(function (callback) {
            current = callback(current);
          });
          batchRef.current = [];
          state.current = current;
          forceUpdate({});
        });
      
        function updater(callback) {
          batchRef.current.push(callback);
          flushUpdate();
        }
      
        return [state.current, updater];
      }
      // EXTERNAL MODULE: ./node_modules/rc-util/es/KeyCode.js
      var KeyCode = __webpack_require__("4IlW");
      
      // CONCATENATED MODULE: ./node_modules/rc-tabs/es/TabNavList/TabNode.js
      
      
      
      
      
      function TabNode(_ref, ref) {
        var _classNames;
      
        var prefixCls = _ref.prefixCls,
            id = _ref.id,
            active = _ref.active,
            rtl = _ref.rtl,
            _ref$tab = _ref.tab,
            key = _ref$tab.key,
            tab = _ref$tab.tab,
            disabled = _ref$tab.disabled,
            closeIcon = _ref$tab.closeIcon,
            tabBarGutter = _ref.tabBarGutter,
            tabPosition = _ref.tabPosition,
            closable = _ref.closable,
            renderWrapper = _ref.renderWrapper,
            removeAriaLabel = _ref.removeAriaLabel,
            editable = _ref.editable,
            onClick = _ref.onClick,
            onRemove = _ref.onRemove,
            onFocus = _ref.onFocus;
        var tabPrefix = "".concat(prefixCls, "-tab");
        external_window_React_["useEffect"](function () {
          return onRemove;
        }, []);
        var nodeStyle = {};
      
        if (tabPosition === 'top' || tabPosition === 'bottom') {
          nodeStyle[rtl ? 'marginLeft' : 'marginRight'] = tabBarGutter;
        } else {
          nodeStyle.marginBottom = tabBarGutter;
        }
      
        var removable = editable && closable !== false && !disabled;
      
        function onInternalClick(e) {
          if (disabled) return;
          onClick(e);
        }
      
        function onRemoveTab(event) {
          event.preventDefault();
          event.stopPropagation();
          editable.onEdit('remove', {
            key: key,
            event: event
          });
        }
      
        var node = external_window_React_["createElement"]("div", {
          key: key,
          ref: ref,
          className: classnames_default()(tabPrefix, (_classNames = {}, Object(defineProperty["a" /* default */])(_classNames, "".concat(tabPrefix, "-with-remove"), removable), Object(defineProperty["a" /* default */])(_classNames, "".concat(tabPrefix, "-active"), active), Object(defineProperty["a" /* default */])(_classNames, "".concat(tabPrefix, "-disabled"), disabled), _classNames)),
          style: nodeStyle,
          onClick: onInternalClick
        }, external_window_React_["createElement"]("div", {
          role: "tab",
          "aria-selected": active,
          id: id && "".concat(id, "-tab-").concat(key),
          className: "".concat(tabPrefix, "-btn"),
          "aria-controls": id && "".concat(id, "-panel-").concat(key),
          "aria-disabled": disabled,
          tabIndex: disabled ? null : 0,
          onClick: function onClick(e) {
            e.stopPropagation();
            onInternalClick(e);
          },
          onKeyDown: function onKeyDown(e) {
            if ([KeyCode["a" /* default */].SPACE, KeyCode["a" /* default */].ENTER].includes(e.which)) {
              e.preventDefault();
              onInternalClick(e);
            }
          },
          onFocus: onFocus
        }, tab), removable && external_window_React_["createElement"]("button", {
          type: "button",
          "aria-label": removeAriaLabel || 'remove',
          tabIndex: 0,
          className: "".concat(tabPrefix, "-remove"),
          onClick: function onClick(e) {
            e.stopPropagation();
            onRemoveTab(e);
          }
        }, closeIcon || editable.removeIcon || '×'));
      
        if (renderWrapper) {
          node = renderWrapper(node);
        }
      
        return node;
      }
      
      /* harmony default export */ var TabNavList_TabNode = (external_window_React_["forwardRef"](TabNode));
      // CONCATENATED MODULE: ./node_modules/rc-tabs/es/hooks/useOffsets.js
      
      
      var DEFAULT_SIZE = {
        width: 0,
        height: 0,
        left: 0,
        top: 0
      };
      function useOffsets(tabs, tabSizes, holderScrollWidth) {
        return Object(external_window_React_["useMemo"])(function () {
          var _tabs$;
      
          var map = new Map();
          var lastOffset = tabSizes.get((_tabs$ = tabs[0]) === null || _tabs$ === void 0 ? void 0 : _tabs$.key) || DEFAULT_SIZE;
          var rightOffset = lastOffset.left + lastOffset.width;
      
          for (var i = 0; i < tabs.length; i += 1) {
            var key = tabs[i].key;
            var data = tabSizes.get(key); // Reuse last one when not exist yet
      
            if (!data) {
              var _tabs;
      
              data = tabSizes.get((_tabs = tabs[i - 1]) === null || _tabs === void 0 ? void 0 : _tabs.key) || DEFAULT_SIZE;
            }
      
            var entity = map.get(key) || Object(objectSpread2["a" /* default */])({}, data); // Right
      
      
            entity.right = rightOffset - entity.left - entity.width; // Update entity
      
            map.set(key, entity);
          }
      
          return map;
        }, [tabs.map(function (tab) {
          return tab.key;
        }).join('_'), tabSizes, holderScrollWidth]);
      }
      // CONCATENATED MODULE: ./node_modules/rc-tabs/es/hooks/useVisibleRange.js
      
      var useVisibleRange_DEFAULT_SIZE = {
        width: 0,
        height: 0,
        left: 0,
        top: 0,
        right: 0
      };
      function useVisibleRange(tabOffsets, containerSize, tabContentNodeSize, addNodeSize, _ref) {
        var tabs = _ref.tabs,
            tabPosition = _ref.tabPosition,
            rtl = _ref.rtl;
        var unit;
        var position;
        var transformSize;
      
        if (['top', 'bottom'].includes(tabPosition)) {
          unit = 'width';
          position = rtl ? 'right' : 'left';
          transformSize = Math.abs(containerSize.left);
        } else {
          unit = 'height';
          position = 'top';
          transformSize = -containerSize.top;
        }
      
        var basicSize = containerSize[unit];
        var tabContentSize = tabContentNodeSize[unit];
        var addSize = addNodeSize[unit];
        var mergedBasicSize = basicSize;
      
        if (tabContentSize + addSize > basicSize) {
          mergedBasicSize = basicSize - addSize;
        }
      
        return Object(external_window_React_["useMemo"])(function () {
          if (!tabs.length) {
            return [0, 0];
          }
      
          var len = tabs.length;
          var endIndex = len;
      
          for (var i = 0; i < len; i += 1) {
            var offset = tabOffsets.get(tabs[i].key) || useVisibleRange_DEFAULT_SIZE;
      
            if (offset[position] + offset[unit] > transformSize + mergedBasicSize) {
              endIndex = i - 1;
              break;
            }
          }
      
          var startIndex = 0;
      
          for (var _i = len - 1; _i >= 0; _i -= 1) {
            var _offset = tabOffsets.get(tabs[_i].key) || useVisibleRange_DEFAULT_SIZE;
      
            if (_offset[position] < transformSize) {
              startIndex = _i + 1;
              break;
            }
          }
      
          return [startIndex, endIndex];
        }, [tabOffsets, transformSize, mergedBasicSize, tabPosition, tabs.map(function (tab) {
          return tab.key;
        }).join('_'), rtl]);
      }
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/extends.js
      var esm_extends = __webpack_require__("wx14");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/classCallCheck.js
      var classCallCheck = __webpack_require__("1OyB");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/createClass.js
      var createClass = __webpack_require__("vuIU");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js
      var assertThisInitialized = __webpack_require__("JX7q");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/inherits.js
      var inherits = __webpack_require__("Ji7U");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/createSuper.js + 1 modules
      var createSuper = __webpack_require__("LK+K");
      
      // EXTERNAL MODULE: ./node_modules/mini-store/esm/index.js + 3 modules
      var esm = __webpack_require__("I8Z2");
      
      // EXTERNAL MODULE: ./node_modules/rc-util/es/omit.js
      var omit = __webpack_require__("bT9E");
      
      // EXTERNAL MODULE: ./node_modules/rc-util/es/createChainedFunction.js
      var createChainedFunction = __webpack_require__("2GS6");
      
      // EXTERNAL MODULE: ./node_modules/shallowequal/index.js
      var shallowequal = __webpack_require__("Gytx");
      var shallowequal_default = /*#__PURE__*/__webpack_require__.n(shallowequal);
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/typeof.js
      var esm_typeof = __webpack_require__("U8pU");
      
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-menu/es/utils/isMobile.js
      
      
      // MIT License from https://github.com/kaimallea/isMobile
      var applePhone = /iPhone/i;
      var appleIpod = /iPod/i;
      var appleTablet = /iPad/i;
      var androidPhone = /\bAndroid(?:.+)Mobile\b/i; // Match 'Android' AND 'Mobile'
      
      var androidTablet = /Android/i;
      var amazonPhone = /\bAndroid(?:.+)SD4930UR\b/i;
      var amazonTablet = /\bAndroid(?:.+)(?:KF[A-Z]{2,4})\b/i;
      var windowsPhone = /Windows Phone/i;
      var windowsTablet = /\bWindows(?:.+)ARM\b/i; // Match 'Windows' AND 'ARM'
      
      var otherBlackberry = /BlackBerry/i;
      var otherBlackberry10 = /BB10/i;
      var otherOpera = /Opera Mini/i;
      var otherChrome = /\b(CriOS|Chrome)(?:.+)Mobile/i;
      var otherFirefox = /Mobile(?:.+)Firefox\b/i; // Match 'Mobile' AND 'Firefox'
      
      function match(regex, userAgent) {
        return regex.test(userAgent);
      }
      
      function isMobile(userAgent) {
        var ua = userAgent || (typeof navigator !== 'undefined' ? navigator.userAgent : ''); // Facebook mobile app's integrated browser adds a bunch of strings that
        // match everything. Strip it out if it exists.
      
        var tmp = (ua || '').split('[FBAN');
      
        if (typeof tmp[1] !== 'undefined') {
          var _tmp = tmp;
      
          var _tmp2 = Object(slicedToArray["a" /* default */])(_tmp, 1);
      
          ua = _tmp2[0];
        } // Twitter mobile app's integrated browser on iPad adds a "Twitter for
        // iPhone" string. Same probably happens on other tablet platforms.
        // This will confuse detection so strip it out if it exists.
      
      
        tmp = ua.split('Twitter');
      
        if (typeof tmp[1] !== 'undefined') {
          var _tmp3 = tmp;
      
          var _tmp4 = Object(slicedToArray["a" /* default */])(_tmp3, 1);
      
          ua = _tmp4[0];
        }
      
        var result = {
          apple: {
            phone: match(applePhone, ua) && !match(windowsPhone, ua),
            ipod: match(appleIpod, ua),
            tablet: !match(applePhone, ua) && match(appleTablet, ua) && !match(windowsPhone, ua),
            device: (match(applePhone, ua) || match(appleIpod, ua) || match(appleTablet, ua)) && !match(windowsPhone, ua)
          },
          amazon: {
            phone: match(amazonPhone, ua),
            tablet: !match(amazonPhone, ua) && match(amazonTablet, ua),
            device: match(amazonPhone, ua) || match(amazonTablet, ua)
          },
          android: {
            phone: !match(windowsPhone, ua) && match(amazonPhone, ua) || !match(windowsPhone, ua) && match(androidPhone, ua),
            tablet: !match(windowsPhone, ua) && !match(amazonPhone, ua) && !match(androidPhone, ua) && (match(amazonTablet, ua) || match(androidTablet, ua)),
            device: !match(windowsPhone, ua) && (match(amazonPhone, ua) || match(amazonTablet, ua) || match(androidPhone, ua) || match(androidTablet, ua)) || match(/\bokhttp\b/i, ua)
          },
          windows: {
            phone: match(windowsPhone, ua),
            tablet: match(windowsTablet, ua),
            device: match(windowsPhone, ua) || match(windowsTablet, ua)
          },
          other: {
            blackberry: match(otherBlackberry, ua),
            blackberry10: match(otherBlackberry10, ua),
            opera: match(otherOpera, ua),
            firefox: match(otherFirefox, ua),
            chrome: match(otherChrome, ua),
            device: match(otherBlackberry, ua) || match(otherBlackberry10, ua) || match(otherOpera, ua) || match(otherFirefox, ua) || match(otherChrome, ua)
          },
          // Additional
          any: null,
          phone: null,
          tablet: null
        };
        result.any = result.apple.device || result.android.device || result.windows.device || result.other.device; // excludes 'other' devices and ipods, targeting touchscreen phones
      
        result.phone = result.apple.phone || result.android.phone || result.windows.phone;
        result.tablet = result.apple.tablet || result.android.tablet || result.windows.tablet;
        return result;
      }
      
      var defaultResult = Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, isMobile()), {}, {
        isMobile: isMobile
      });
      
      /* harmony default export */ var utils_isMobile = (defaultResult);
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-menu/es/util.js
      
      
      
      function noop() {}
      function getKeyFromChildrenIndex(child, menuEventKey, index) {
        var prefix = menuEventKey || '';
        return child.key || "".concat(prefix, "item_").concat(index);
      }
      function getMenuIdFromSubMenuEventKey(eventKey) {
        return "".concat(eventKey, "-menu-");
      }
      function loopMenuItem(children, cb) {
        var index = -1;
        external_window_React_["Children"].forEach(children, function (c) {
          index += 1;
      
          if (c && c.type && c.type.isMenuItemGroup) {
            external_window_React_["Children"].forEach(c.props.children, function (c2) {
              index += 1;
              cb(c2, index);
            });
          } else {
            cb(c, index);
          }
        });
      }
      function loopMenuItemRecursively(children, keys, ret) {
        /* istanbul ignore if */
        if (!children || ret.find) {
          return;
        }
      
        external_window_React_["Children"].forEach(children, function (c) {
          if (c) {
            var construct = c.type;
      
            if (!construct || !(construct.isSubMenu || construct.isMenuItem || construct.isMenuItemGroup)) {
              return;
            }
      
            if (keys.indexOf(c.key) !== -1) {
              // eslint-disable-next-line no-param-reassign
              ret.find = true;
            } else if (c.props.children) {
              loopMenuItemRecursively(c.props.children, keys, ret);
            }
          }
        });
      }
      var menuAllProps = ['defaultSelectedKeys', 'selectedKeys', 'defaultOpenKeys', 'openKeys', 'mode', 'getPopupContainer', 'onSelect', 'onDeselect', 'onDestroy', 'openTransitionName', 'openAnimation', 'subMenuOpenDelay', 'subMenuCloseDelay', 'forceSubMenuRender', 'triggerSubMenuAction', 'level', 'selectable', 'multiple', 'onOpenChange', 'visible', 'focusable', 'defaultActiveFirst', 'prefixCls', 'inlineIndent', 'parentMenu', 'title', 'rootPrefixCls', 'eventKey', 'active', 'onItemHover', 'onTitleMouseEnter', 'onTitleMouseLeave', 'onTitleClick', 'popupAlign', 'popupOffset', 'isOpen', 'renderMenuItem', 'manualRef', 'subMenuKey', 'disabled', 'index', 'isSelected', 'store', 'activeKey', 'builtinPlacements', 'overflowedIndicator', 'motion', // the following keys found need to be removed from test regression
      'attribute', 'value', 'popupClassName', 'inlineCollapsed', 'menu', 'theme', 'itemIcon', 'expandIcon']; // ref: https://github.com/ant-design/ant-design/issues/14007
      // ref: https://bugs.chromium.org/p/chromium/issues/detail?id=360889
      // getBoundingClientRect return the full precision value, which is
      // not the same behavior as on chrome. Set the precision to 6 to
      // unify their behavior
      
      var getWidth = function getWidth(elem) {
        var includeMargin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
        var width = elem && typeof elem.getBoundingClientRect === 'function' && elem.getBoundingClientRect().width;
      
        if (width) {
          if (includeMargin) {
            var _getComputedStyle = getComputedStyle(elem),
                marginLeft = _getComputedStyle.marginLeft,
                marginRight = _getComputedStyle.marginRight;
      
            width += +marginLeft.replace('px', '') + +marginRight.replace('px', '');
          }
      
          width = +width.toFixed(6);
        }
      
        return width || 0;
      };
      var util_setStyle = function setStyle(elem, styleProperty, value) {
        if (elem && Object(esm_typeof["a" /* default */])(elem.style) === 'object') {
          // eslint-disable-next-line no-param-reassign
          elem.style[styleProperty] = value;
        }
      };
      var util_isMobileDevice = function isMobileDevice() {
        return utils_isMobile.any;
      };
      // EXTERNAL MODULE: ./node_modules/resize-observer-polyfill/dist/ResizeObserver.es.js
      var ResizeObserver_es = __webpack_require__("bdgK");
      
      // EXTERNAL MODULE: external "window.ReactDOM"
      var external_window_ReactDOM_ = __webpack_require__("faye");
      var external_window_ReactDOM_default = /*#__PURE__*/__webpack_require__.n(external_window_ReactDOM_);
      
      // EXTERNAL MODULE: ./node_modules/rc-util/es/raf.js
      var es_raf = __webpack_require__("wgJM");
      
      // EXTERNAL MODULE: ./node_modules/rc-util/es/Dom/contains.js
      var contains = __webpack_require__("l4aY");
      
      // EXTERNAL MODULE: ./node_modules/rc-util/es/Dom/findDOMNode.js
      var findDOMNode = __webpack_require__("m+aA");
      
      // EXTERNAL MODULE: ./node_modules/rc-util/es/ref.js
      var es_ref = __webpack_require__("c+Xe");
      
      // EXTERNAL MODULE: ./node_modules/rc-util/es/Dom/addEventListener.js
      var addEventListener = __webpack_require__("zT1h");
      
      // EXTERNAL MODULE: ./node_modules/rc-util/es/Portal.js
      var Portal = __webpack_require__("QC+M");
      
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-trigger/es/utils/alignUtil.js
      
      
      function isPointsEq(a1, a2, isAlignPoint) {
        if (isAlignPoint) {
          return a1[0] === a2[0];
        }
      
        return a1[0] === a2[0] && a1[1] === a2[1];
      }
      
      function getAlignFromPlacement(builtinPlacements, placementStr, align) {
        var baseAlign = builtinPlacements[placementStr] || {};
        return Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, baseAlign), align);
      }
      function getAlignPopupClassName(builtinPlacements, prefixCls, align, isAlignPoint) {
        var points = align.points;
        var placements = Object.keys(builtinPlacements);
      
        for (var i = 0; i < placements.length; i += 1) {
          var placement = placements[i];
      
          if (isPointsEq(builtinPlacements[placement].points, points, isAlignPoint)) {
            return "".concat(prefixCls, "-placement-").concat(placement);
          }
        }
      
        return '';
      }
      // CONCATENATED MODULE: ./node_modules/rc-util/es/isMobile.js
      /* harmony default export */ var es_isMobile = (function () {
        if (typeof navigator === 'undefined' || typeof window === 'undefined') {
          return false;
        }
      
        var agent = navigator.userAgent || navigator.vendor || window.opera;
      
        if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(agent) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test(agent === null || agent === void 0 ? void 0 : agent.substr(0, 4))) {
          return true;
        }
      
        return false;
      });
      // EXTERNAL MODULE: ./node_modules/rc-util/es/Dom/canUseDom.js
      var canUseDom = __webpack_require__("MNnm");
      
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-motion/es/util/motion.js
      
       // ================= Transition =================
      // Event wrapper. Copy from react source code
      
      function makePrefixMap(styleProp, eventName) {
        var prefixes = {};
        prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
        prefixes["Webkit".concat(styleProp)] = "webkit".concat(eventName);
        prefixes["Moz".concat(styleProp)] = "moz".concat(eventName);
        prefixes["ms".concat(styleProp)] = "MS".concat(eventName);
        prefixes["O".concat(styleProp)] = "o".concat(eventName.toLowerCase());
        return prefixes;
      }
      
      function getVendorPrefixes(domSupport, win) {
        var prefixes = {
          animationend: makePrefixMap('Animation', 'AnimationEnd'),
          transitionend: makePrefixMap('Transition', 'TransitionEnd')
        };
      
        if (domSupport) {
          if (!('AnimationEvent' in win)) {
            delete prefixes.animationend.animation;
          }
      
          if (!('TransitionEvent' in win)) {
            delete prefixes.transitionend.transition;
          }
        }
      
        return prefixes;
      }
      var vendorPrefixes = getVendorPrefixes(Object(canUseDom["a" /* default */])(), typeof window !== 'undefined' ? window : {});
      var motion_style = {};
      
      if (Object(canUseDom["a" /* default */])()) {
        var _document$createEleme = document.createElement('div');
      
        motion_style = _document$createEleme.style;
      }
      
      var prefixedEventNames = {};
      function getVendorPrefixedEventName(eventName) {
        if (prefixedEventNames[eventName]) {
          return prefixedEventNames[eventName];
        }
      
        var prefixMap = vendorPrefixes[eventName];
      
        if (prefixMap) {
          var stylePropList = Object.keys(prefixMap);
          var len = stylePropList.length;
      
          for (var i = 0; i < len; i += 1) {
            var styleProp = stylePropList[i];
      
            if (Object.prototype.hasOwnProperty.call(prefixMap, styleProp) && styleProp in motion_style) {
              prefixedEventNames[eventName] = prefixMap[styleProp];
              return prefixedEventNames[eventName];
            }
          }
        }
      
        return '';
      }
      var internalAnimationEndName = getVendorPrefixedEventName('animationend');
      var internalTransitionEndName = getVendorPrefixedEventName('transitionend');
      var supportTransition = !!(internalAnimationEndName && internalTransitionEndName);
      var animationEndName = internalAnimationEndName || 'animationend';
      var transitionEndName = internalTransitionEndName || 'transitionend';
      function getTransitionName(transitionName, transitionType) {
        if (!transitionName) return null;
      
        if (Object(esm_typeof["a" /* default */])(transitionName) === 'object') {
          var type = transitionType.replace(/-\w/g, function (match) {
            return match[1].toUpperCase();
          });
          return transitionName[type];
        }
      
        return "".concat(transitionName, "-").concat(transitionType);
      }
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-motion/es/interface.js
      var STATUS_NONE = 'none';
      var STATUS_APPEAR = 'appear';
      var STATUS_ENTER = 'enter';
      var STATUS_LEAVE = 'leave';
      var STEP_NONE = 'none';
      var STEP_PREPARE = 'prepare';
      var STEP_START = 'start';
      var STEP_ACTIVE = 'active';
      var STEP_ACTIVATED = 'end';
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-motion/es/hooks/useState.js
      
      
      function useMountStatus(defaultValue) {
        var destroyRef = Object(external_window_React_["useRef"])(false);
      
        var _useState = Object(external_window_React_["useState"])(defaultValue),
            _useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
            val = _useState2[0],
            setVal = _useState2[1];
      
        function setValue(next) {
          if (!destroyRef.current) {
            setVal(next);
          }
        }
      
        Object(external_window_React_["useEffect"])(function () {
          return function () {
            destroyRef.current = true;
          };
        }, []);
        return [val, setValue];
      }
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-motion/es/hooks/useIsomorphicLayoutEffect.js
      
       // It's safe to use `useLayoutEffect` but the warning is annoying
      
      var useIsomorphicLayoutEffect = Object(canUseDom["a" /* default */])() ? external_window_React_["useLayoutEffect"] : external_window_React_["useEffect"];
      /* harmony default export */ var hooks_useIsomorphicLayoutEffect = (useIsomorphicLayoutEffect);
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-motion/es/hooks/useNextFrame.js
      
      
      /* harmony default export */ var useNextFrame = (function () {
        var nextFrameRef = external_window_React_["useRef"](null);
      
        function cancelNextFrame() {
          es_raf["a" /* default */].cancel(nextFrameRef.current);
        }
      
        function nextFrame(callback) {
          var delay = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
          cancelNextFrame();
          var nextFrameId = Object(es_raf["a" /* default */])(function () {
            if (delay <= 1) {
              callback({
                isCanceled: function isCanceled() {
                  return nextFrameId !== nextFrameRef.current;
                }
              });
            } else {
              nextFrame(callback, delay - 1);
            }
          });
          nextFrameRef.current = nextFrameId;
        }
      
        external_window_React_["useEffect"](function () {
          return function () {
            cancelNextFrame();
          };
        }, []);
        return [nextFrame, cancelNextFrame];
      });
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-motion/es/hooks/useStepQueue.js
      
      
      
      
      
      var STEP_QUEUE = [STEP_PREPARE, STEP_START, STEP_ACTIVE, STEP_ACTIVATED];
      /** Skip current step */
      
      var SkipStep = false;
      /** Current step should be update in */
      
      var DoStep = true;
      function useStepQueue_isActive(step) {
        return step === STEP_ACTIVE || step === STEP_ACTIVATED;
      }
      /* harmony default export */ var useStepQueue = (function (status, callback) {
        var _React$useState = external_window_React_["useState"](STEP_NONE),
            _React$useState2 = Object(slicedToArray["a" /* default */])(_React$useState, 2),
            step = _React$useState2[0],
            setStep = _React$useState2[1];
      
        var _useNextFrame = useNextFrame(),
            _useNextFrame2 = Object(slicedToArray["a" /* default */])(_useNextFrame, 2),
            nextFrame = _useNextFrame2[0],
            cancelNextFrame = _useNextFrame2[1];
      
        function startQueue() {
          setStep(STEP_PREPARE);
        }
      
        hooks_useIsomorphicLayoutEffect(function () {
          if (step !== STEP_NONE && step !== STEP_ACTIVATED) {
            var index = STEP_QUEUE.indexOf(step);
            var nextStep = STEP_QUEUE[index + 1];
            var result = callback(step);
      
            if (result === SkipStep) {
              // Skip when no needed
              setStep(nextStep);
            } else {
              // Do as frame for step update
              nextFrame(function (info) {
                function doNext() {
                  // Skip since current queue is ood
                  if (info.isCanceled()) return;
                  setStep(nextStep);
                }
      
                if (result === true) {
                  doNext();
                } else {
                  // Only promise should be async
                  Promise.resolve(result).then(doNext);
                }
              });
            }
          }
        }, [status, step]);
        external_window_React_["useEffect"](function () {
          return function () {
            cancelNextFrame();
          };
        }, []);
        return [startQueue, step];
      });
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-motion/es/hooks/useDomMotionEvents.js
      
      
      
      /* harmony default export */ var useDomMotionEvents = (function (callback) {
        var cacheElementRef = Object(external_window_React_["useRef"])(); // Cache callback
      
        var callbackRef = Object(external_window_React_["useRef"])(callback);
        callbackRef.current = callback; // Internal motion event handler
      
        var onInternalMotionEnd = external_window_React_["useCallback"](function (event) {
          callbackRef.current(event);
        }, []); // Remove events
      
        function removeMotionEvents(element) {
          if (element) {
            element.removeEventListener(transitionEndName, onInternalMotionEnd);
            element.removeEventListener(animationEndName, onInternalMotionEnd);
          }
        } // Patch events
      
      
        function patchMotionEvents(element) {
          if (cacheElementRef.current && cacheElementRef.current !== element) {
            removeMotionEvents(cacheElementRef.current);
          }
      
          if (element && element !== cacheElementRef.current) {
            element.addEventListener(transitionEndName, onInternalMotionEnd);
            element.addEventListener(animationEndName, onInternalMotionEnd); // Save as cache in case dom removed trigger by `motionDeadline`
      
            cacheElementRef.current = element;
          }
        } // Clean up when removed
      
      
        external_window_React_["useEffect"](function () {
          return function () {
            removeMotionEvents(cacheElementRef.current);
          };
        }, []);
        return [patchMotionEvents, removeMotionEvents];
      });
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-motion/es/hooks/useStatus.js
      
      
      
      
      
      
      
      
      
      
      function useStatus(supportMotion, visible, getElement, _ref) {
        var _ref$motionEnter = _ref.motionEnter,
            motionEnter = _ref$motionEnter === void 0 ? true : _ref$motionEnter,
            _ref$motionAppear = _ref.motionAppear,
            motionAppear = _ref$motionAppear === void 0 ? true : _ref$motionAppear,
            _ref$motionLeave = _ref.motionLeave,
            motionLeave = _ref$motionLeave === void 0 ? true : _ref$motionLeave,
            motionDeadline = _ref.motionDeadline,
            motionLeaveImmediately = _ref.motionLeaveImmediately,
            onAppearPrepare = _ref.onAppearPrepare,
            onEnterPrepare = _ref.onEnterPrepare,
            onLeavePrepare = _ref.onLeavePrepare,
            onAppearStart = _ref.onAppearStart,
            onEnterStart = _ref.onEnterStart,
            onLeaveStart = _ref.onLeaveStart,
            onAppearActive = _ref.onAppearActive,
            onEnterActive = _ref.onEnterActive,
            onLeaveActive = _ref.onLeaveActive,
            onAppearEnd = _ref.onAppearEnd,
            onEnterEnd = _ref.onEnterEnd,
            onLeaveEnd = _ref.onLeaveEnd,
            onVisibleChanged = _ref.onVisibleChanged;
      
        // Used for outer render usage to avoid `visible: false & status: none` to render nothing
        var _useState = useMountStatus(),
            _useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
            asyncVisible = _useState2[0],
            setAsyncVisible = _useState2[1];
      
        var _useState3 = useMountStatus(STATUS_NONE),
            _useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
            status = _useState4[0],
            setStatus = _useState4[1];
      
        var _useState5 = useMountStatus(null),
            _useState6 = Object(slicedToArray["a" /* default */])(_useState5, 2),
            style = _useState6[0],
            setStyle = _useState6[1];
      
        var mountedRef = Object(external_window_React_["useRef"])(false);
        var deadlineRef = Object(external_window_React_["useRef"])(null);
        var destroyedRef = Object(external_window_React_["useRef"])(false); // =========================== Dom Node ===========================
      
        var cacheElementRef = Object(external_window_React_["useRef"])(null);
      
        function getDomElement() {
          var element = getElement();
          return element || cacheElementRef.current;
        } // ========================== Motion End ==========================
      
      
        var activeRef = Object(external_window_React_["useRef"])(false);
      
        function onInternalMotionEnd(event) {
          var element = getDomElement();
      
          if (event && !event.deadline && event.target !== element) {
            // event exists
            // not initiated by deadline
            // transitionEnd not fired by inner elements
            return;
          }
      
          var canEnd;
      
          if (status === STATUS_APPEAR && activeRef.current) {
            canEnd = onAppearEnd === null || onAppearEnd === void 0 ? void 0 : onAppearEnd(element, event);
          } else if (status === STATUS_ENTER && activeRef.current) {
            canEnd = onEnterEnd === null || onEnterEnd === void 0 ? void 0 : onEnterEnd(element, event);
          } else if (status === STATUS_LEAVE && activeRef.current) {
            canEnd = onLeaveEnd === null || onLeaveEnd === void 0 ? void 0 : onLeaveEnd(element, event);
          } // Only update status when `canEnd` and not destroyed
      
      
          if (canEnd !== false && !destroyedRef.current) {
            setStatus(STATUS_NONE);
            setStyle(null);
          }
        }
      
        var _useDomMotionEvents = useDomMotionEvents(onInternalMotionEnd),
            _useDomMotionEvents2 = Object(slicedToArray["a" /* default */])(_useDomMotionEvents, 1),
            patchMotionEvents = _useDomMotionEvents2[0]; // ============================= Step =============================
      
      
        var eventHandlers = external_window_React_["useMemo"](function () {
          var _ref2, _ref3, _ref4;
      
          switch (status) {
            case 'appear':
              return _ref2 = {}, Object(defineProperty["a" /* default */])(_ref2, STEP_PREPARE, onAppearPrepare), Object(defineProperty["a" /* default */])(_ref2, STEP_START, onAppearStart), Object(defineProperty["a" /* default */])(_ref2, STEP_ACTIVE, onAppearActive), _ref2;
      
            case 'enter':
              return _ref3 = {}, Object(defineProperty["a" /* default */])(_ref3, STEP_PREPARE, onEnterPrepare), Object(defineProperty["a" /* default */])(_ref3, STEP_START, onEnterStart), Object(defineProperty["a" /* default */])(_ref3, STEP_ACTIVE, onEnterActive), _ref3;
      
            case 'leave':
              return _ref4 = {}, Object(defineProperty["a" /* default */])(_ref4, STEP_PREPARE, onLeavePrepare), Object(defineProperty["a" /* default */])(_ref4, STEP_START, onLeaveStart), Object(defineProperty["a" /* default */])(_ref4, STEP_ACTIVE, onLeaveActive), _ref4;
      
            default:
              return {};
          }
        }, [status]);
      
        var _useStepQueue = useStepQueue(status, function (newStep) {
          // Only prepare step can be skip
          if (newStep === STEP_PREPARE) {
            var onPrepare = eventHandlers[STEP_PREPARE];
      
            if (!onPrepare) {
              return SkipStep;
            }
      
            return onPrepare(getDomElement());
          } // Rest step is sync update
      
      
          // Rest step is sync update
          if (step in eventHandlers) {
            var _eventHandlers$step;
      
            setStyle(((_eventHandlers$step = eventHandlers[step]) === null || _eventHandlers$step === void 0 ? void 0 : _eventHandlers$step.call(eventHandlers, getDomElement(), null)) || null);
          }
      
          if (step === STEP_ACTIVE) {
            // Patch events when motion needed
            patchMotionEvents(getDomElement());
      
            if (motionDeadline > 0) {
              clearTimeout(deadlineRef.current);
              deadlineRef.current = setTimeout(function () {
                onInternalMotionEnd({
                  deadline: true
                });
              }, motionDeadline);
            }
          }
      
          return DoStep;
        }),
            _useStepQueue2 = Object(slicedToArray["a" /* default */])(_useStepQueue, 2),
            startStep = _useStepQueue2[0],
            step = _useStepQueue2[1];
      
        var active = useStepQueue_isActive(step);
        activeRef.current = active; // ============================ Status ============================
        // Update with new status
      
        hooks_useIsomorphicLayoutEffect(function () {
          setAsyncVisible(visible);
          var isMounted = mountedRef.current;
          mountedRef.current = true;
      
          if (!supportMotion) {
            return;
          }
      
          var nextStatus; // Appear
      
          if (!isMounted && visible && motionAppear) {
            nextStatus = STATUS_APPEAR;
          } // Enter
      
      
          if (isMounted && visible && motionEnter) {
            nextStatus = STATUS_ENTER;
          } // Leave
      
      
          if (isMounted && !visible && motionLeave || !isMounted && motionLeaveImmediately && !visible && motionLeave) {
            nextStatus = STATUS_LEAVE;
          } // Update to next status
      
      
          if (nextStatus) {
            setStatus(nextStatus);
            startStep();
          }
        }, [visible]); // ============================ Effect ============================
        // Reset when motion changed
      
        Object(external_window_React_["useEffect"])(function () {
          if ( // Cancel appear
          status === STATUS_APPEAR && !motionAppear || // Cancel enter
          status === STATUS_ENTER && !motionEnter || // Cancel leave
          status === STATUS_LEAVE && !motionLeave) {
            setStatus(STATUS_NONE);
          }
        }, [motionAppear, motionEnter, motionLeave]);
        Object(external_window_React_["useEffect"])(function () {
          return function () {
            clearTimeout(deadlineRef.current);
            destroyedRef.current = true;
          };
        }, []); // Trigger `onVisibleChanged`
      
        Object(external_window_React_["useEffect"])(function () {
          if (asyncVisible !== undefined && status === STATUS_NONE) {
            onVisibleChanged === null || onVisibleChanged === void 0 ? void 0 : onVisibleChanged(asyncVisible);
          }
        }, [asyncVisible, status]); // ============================ Styles ============================
      
        var mergedStyle = style;
      
        if (eventHandlers[STEP_PREPARE] && step === STEP_START) {
          mergedStyle = Object(objectSpread2["a" /* default */])({
            transition: 'none'
          }, mergedStyle);
        }
      
        return [status, step, mergedStyle, asyncVisible !== null && asyncVisible !== void 0 ? asyncVisible : visible];
      }
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-motion/es/DomWrapper.js
      
      
      
      
      
      
      var DomWrapper_DomWrapper = /*#__PURE__*/function (_React$Component) {
        Object(inherits["a" /* default */])(DomWrapper, _React$Component);
      
        var _super = Object(createSuper["a" /* default */])(DomWrapper);
      
        function DomWrapper() {
          Object(classCallCheck["a" /* default */])(this, DomWrapper);
      
          return _super.apply(this, arguments);
        }
      
        Object(createClass["a" /* default */])(DomWrapper, [{
          key: "render",
          value: function render() {
            return this.props.children;
          }
        }]);
      
        return DomWrapper;
      }(external_window_React_["Component"]);
      
      /* harmony default export */ var es_DomWrapper = (DomWrapper_DomWrapper);
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-motion/es/CSSMotion.js
      
      
      
      
      
      /* eslint-disable react/default-props-match-prop-types, react/no-multi-comp, react/prop-types */
      
      
      
      
      
      
      
      
      
      
      /**
       * `transitionSupport` is used for none transition test case.
       * Default we use browser transition event support check.
       */
      
      function genCSSMotion(config) {
        var transitionSupport = config;
      
        if (Object(esm_typeof["a" /* default */])(config) === 'object') {
          transitionSupport = config.transitionSupport;
        }
      
        function isSupportTransition(props) {
          return !!(props.motionName && transitionSupport);
        }
      
        var CSSMotion = /*#__PURE__*/external_window_React_["forwardRef"](function (props, ref) {
          var _props$visible = props.visible,
              visible = _props$visible === void 0 ? true : _props$visible,
              _props$removeOnLeave = props.removeOnLeave,
              removeOnLeave = _props$removeOnLeave === void 0 ? true : _props$removeOnLeave,
              forceRender = props.forceRender,
              children = props.children,
              motionName = props.motionName,
              leavedClassName = props.leavedClassName,
              eventProps = props.eventProps;
          var supportMotion = isSupportTransition(props); // Ref to the react node, it may be a HTMLElement
      
          var nodeRef = Object(external_window_React_["useRef"])(); // Ref to the dom wrapper in case ref can not pass to HTMLElement
      
          var wrapperNodeRef = Object(external_window_React_["useRef"])();
      
          function getDomElement() {
            try {
              return Object(findDOMNode["a" /* default */])(nodeRef.current || wrapperNodeRef.current);
            } catch (e) {
              // Only happen when `motionDeadline` trigger but element removed.
              return null;
            }
          }
      
          var _useStatus = useStatus(supportMotion, visible, getDomElement, props),
              _useStatus2 = Object(slicedToArray["a" /* default */])(_useStatus, 4),
              status = _useStatus2[0],
              statusStep = _useStatus2[1],
              statusStyle = _useStatus2[2],
              mergedVisible = _useStatus2[3]; // Record whether content has rended
          // Will return null for un-rendered even when `removeOnLeave={false}`
      
      
          var renderedRef = external_window_React_["useRef"](mergedVisible);
      
          if (mergedVisible) {
            renderedRef.current = true;
          } // ====================== Refs ======================
      
      
          var originRef = Object(external_window_React_["useRef"])(ref);
          originRef.current = ref;
          var setNodeRef = external_window_React_["useCallback"](function (node) {
            nodeRef.current = node;
            Object(es_ref["b" /* fillRef */])(originRef.current, node);
          }, []); // ===================== Render =====================
      
          var motionChildren;
      
          var mergedProps = Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, eventProps), {}, {
            visible: visible
          });
      
          if (!children) {
            // No children
            motionChildren = null;
          } else if (status === STATUS_NONE || !isSupportTransition(props)) {
            // Stable children
            if (mergedVisible) {
              motionChildren = children(Object(objectSpread2["a" /* default */])({}, mergedProps), setNodeRef);
            } else if (!removeOnLeave && renderedRef.current) {
              motionChildren = children(Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, mergedProps), {}, {
                className: leavedClassName
              }), setNodeRef);
            } else if (forceRender) {
              motionChildren = children(Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, mergedProps), {}, {
                style: {
                  display: 'none'
                }
              }), setNodeRef);
            } else {
              motionChildren = null;
            }
          } else {
            var _classNames;
      
            // In motion
            var statusSuffix;
      
            if (statusStep === STEP_PREPARE) {
              statusSuffix = 'prepare';
            } else if (useStepQueue_isActive(statusStep)) {
              statusSuffix = 'active';
            } else if (statusStep === STEP_START) {
              statusSuffix = 'start';
            }
      
            motionChildren = children(Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, mergedProps), {}, {
              className: classnames_default()(getTransitionName(motionName, status), (_classNames = {}, Object(defineProperty["a" /* default */])(_classNames, getTransitionName(motionName, "".concat(status, "-").concat(statusSuffix)), statusSuffix), Object(defineProperty["a" /* default */])(_classNames, motionName, typeof motionName === 'string'), _classNames)),
              style: statusStyle
            }), setNodeRef);
          }
      
          return /*#__PURE__*/external_window_React_["createElement"](es_DomWrapper, {
            ref: wrapperNodeRef
          }, motionChildren);
        });
        CSSMotion.displayName = 'CSSMotion';
        return CSSMotion;
      }
      /* harmony default export */ var es_CSSMotion = (genCSSMotion(supportTransition));
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-motion/es/util/diff.js
      
      
      var STATUS_ADD = 'add';
      var STATUS_KEEP = 'keep';
      var STATUS_REMOVE = 'remove';
      var STATUS_REMOVED = 'removed';
      function wrapKeyToObject(key) {
        var keyObj;
      
        if (key && Object(esm_typeof["a" /* default */])(key) === 'object' && 'key' in key) {
          keyObj = key;
        } else {
          keyObj = {
            key: key
          };
        }
      
        return Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, keyObj), {}, {
          key: String(keyObj.key)
        });
      }
      function parseKeys() {
        var keys = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
        return keys.map(wrapKeyToObject);
      }
      function diffKeys() {
        var prevKeys = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
        var currentKeys = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
        var list = [];
        var currentIndex = 0;
        var currentLen = currentKeys.length;
        var prevKeyObjects = parseKeys(prevKeys);
        var currentKeyObjects = parseKeys(currentKeys); // Check prev keys to insert or keep
      
        prevKeyObjects.forEach(function (keyObj) {
          var hit = false;
      
          for (var i = currentIndex; i < currentLen; i += 1) {
            var currentKeyObj = currentKeyObjects[i];
      
            if (currentKeyObj.key === keyObj.key) {
              // New added keys should add before current key
              if (currentIndex < i) {
                list = list.concat(currentKeyObjects.slice(currentIndex, i).map(function (obj) {
                  return Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, obj), {}, {
                    status: STATUS_ADD
                  });
                }));
                currentIndex = i;
              }
      
              list.push(Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, currentKeyObj), {}, {
                status: STATUS_KEEP
              }));
              currentIndex += 1;
              hit = true;
              break;
            }
          } // If not hit, it means key is removed
      
      
          if (!hit) {
            list.push(Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, keyObj), {}, {
              status: STATUS_REMOVE
            }));
          }
        }); // Add rest to the list
      
        if (currentIndex < currentLen) {
          list = list.concat(currentKeyObjects.slice(currentIndex).map(function (obj) {
            return Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, obj), {}, {
              status: STATUS_ADD
            });
          }));
        }
        /**
         * Merge same key when it remove and add again:
         *    [1 - add, 2 - keep, 1 - remove] -> [1 - keep, 2 - keep]
         */
      
      
        var keys = {};
        list.forEach(function (_ref) {
          var key = _ref.key;
          keys[key] = (keys[key] || 0) + 1;
        });
        var duplicatedKeys = Object.keys(keys).filter(function (key) {
          return keys[key] > 1;
        });
        duplicatedKeys.forEach(function (matchKey) {
          // Remove `STATUS_REMOVE` node.
          list = list.filter(function (_ref2) {
            var key = _ref2.key,
                status = _ref2.status;
            return key !== matchKey || status !== STATUS_REMOVE;
          }); // Update `STATUS_ADD` to `STATUS_KEEP`
      
          list.forEach(function (node) {
            if (node.key === matchKey) {
              // eslint-disable-next-line no-param-reassign
              node.status = STATUS_KEEP;
            }
          });
        });
        return list;
      }
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-motion/es/CSSMotionList.js
      
      
      
      
      
      
      
      
      /* eslint react/prop-types: 0 */
      
      
      
      
      var MOTION_PROP_NAMES = ['eventProps', 'visible', 'children', 'motionName', 'motionAppear', 'motionEnter', 'motionLeave', 'motionLeaveImmediately', 'motionDeadline', 'removeOnLeave', 'leavedClassName', 'onAppearStart', 'onAppearActive', 'onAppearEnd', 'onEnterStart', 'onEnterActive', 'onEnterEnd', 'onLeaveStart', 'onLeaveActive', 'onLeaveEnd'];
      /**
       * Generate a CSSMotionList component with config
       * @param transitionSupport No need since CSSMotionList no longer depends on transition support
       * @param CSSMotion CSSMotion component
       */
      
      function genCSSMotionList(transitionSupport) {
        var CSSMotion = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : es_CSSMotion;
      
        var CSSMotionList = /*#__PURE__*/function (_React$Component) {
          Object(inherits["a" /* default */])(CSSMotionList, _React$Component);
      
          var _super = Object(createSuper["a" /* default */])(CSSMotionList);
      
          function CSSMotionList() {
            var _this;
      
            Object(classCallCheck["a" /* default */])(this, CSSMotionList);
      
            _this = _super.apply(this, arguments);
            _this.state = {
              keyEntities: []
            };
      
            _this.removeKey = function (removeKey) {
              _this.setState(function (_ref) {
                var keyEntities = _ref.keyEntities;
                return {
                  keyEntities: keyEntities.map(function (entity) {
                    if (entity.key !== removeKey) return entity;
                    return Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, entity), {}, {
                      status: STATUS_REMOVED
                    });
                  })
                };
              });
            };
      
            return _this;
          }
      
          Object(createClass["a" /* default */])(CSSMotionList, [{
            key: "render",
            value: function render() {
              var _this2 = this;
      
              var keyEntities = this.state.keyEntities;
      
              var _this$props = this.props,
                  component = _this$props.component,
                  children = _this$props.children,
                  _onVisibleChanged = _this$props.onVisibleChanged,
                  restProps = Object(objectWithoutProperties["a" /* default */])(_this$props, ["component", "children", "onVisibleChanged"]);
      
              var Component = component || external_window_React_["Fragment"];
              var motionProps = {};
              MOTION_PROP_NAMES.forEach(function (prop) {
                motionProps[prop] = restProps[prop];
                delete restProps[prop];
              });
              delete restProps.keys;
              return /*#__PURE__*/external_window_React_["createElement"](Component, restProps, keyEntities.map(function (_ref2) {
                var status = _ref2.status,
                    eventProps = Object(objectWithoutProperties["a" /* default */])(_ref2, ["status"]);
      
                var visible = status === STATUS_ADD || status === STATUS_KEEP;
                return /*#__PURE__*/external_window_React_["createElement"](CSSMotion, Object(esm_extends["a" /* default */])({}, motionProps, {
                  key: eventProps.key,
                  visible: visible,
                  eventProps: eventProps,
                  onVisibleChanged: function onVisibleChanged(changedVisible) {
                    _onVisibleChanged === null || _onVisibleChanged === void 0 ? void 0 : _onVisibleChanged(changedVisible, {
                      key: eventProps.key
                    });
      
                    if (!changedVisible) {
                      _this2.removeKey(eventProps.key);
                    }
                  }
                }), children);
              }));
            }
          }], [{
            key: "getDerivedStateFromProps",
            value: function getDerivedStateFromProps(_ref3, _ref4) {
              var keys = _ref3.keys;
              var keyEntities = _ref4.keyEntities;
              var parsedKeyObjects = parseKeys(keys);
              var mixedKeyEntities = diffKeys(keyEntities, parsedKeyObjects);
              return {
                keyEntities: mixedKeyEntities.filter(function (entity) {
                  var prevEntity = keyEntities.find(function (_ref5) {
                    var key = _ref5.key;
                    return entity.key === key;
                  }); // Remove if already mark as removed
      
                  if (prevEntity && prevEntity.status === STATUS_REMOVED && entity.status === STATUS_REMOVE) {
                    return false;
                  }
      
                  return true;
                })
              };
            }
          }]);
      
          return CSSMotionList;
        }(external_window_React_["Component"]);
      
        CSSMotionList.defaultProps = {
          component: 'div'
        };
        return CSSMotionList;
      }
      /* harmony default export */ var es_CSSMotionList = (genCSSMotionList(supportTransition));
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-motion/es/index.js
      
      
      
      /* harmony default export */ var rc_motion_es = (es_CSSMotion);
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-trigger/es/utils/legacyUtil.js
      function getMotion(_ref) {
        var prefixCls = _ref.prefixCls,
            motion = _ref.motion,
            animation = _ref.animation,
            transitionName = _ref.transitionName;
      
        if (motion) {
          return motion;
        }
      
        if (animation) {
          return {
            motionName: "".concat(prefixCls, "-").concat(animation)
          };
        }
      
        if (transitionName) {
          return {
            motionName: transitionName
          };
        }
      
        return null;
      }
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-trigger/es/Popup/Mask.js
      
      
      
      
      
      
      function Mask(props) {
        var prefixCls = props.prefixCls,
            visible = props.visible,
            zIndex = props.zIndex,
            mask = props.mask,
            maskMotion = props.maskMotion,
            maskAnimation = props.maskAnimation,
            maskTransitionName = props.maskTransitionName;
      
        if (!mask) {
          return null;
        }
      
        var motion = {};
      
        if (maskMotion || maskTransitionName || maskAnimation) {
          motion = Object(objectSpread2["a" /* default */])({
            motionAppear: true
          }, getMotion({
            motion: maskMotion,
            prefixCls: prefixCls,
            transitionName: maskTransitionName,
            animation: maskAnimation
          }));
        }
      
        return /*#__PURE__*/external_window_React_["createElement"](rc_motion_es, Object(esm_extends["a" /* default */])({}, motion, {
          visible: visible,
          removeOnLeave: true
        }), function (_ref) {
          var className = _ref.className;
          return /*#__PURE__*/external_window_React_["createElement"]("div", {
            style: {
              zIndex: zIndex
            },
            className: classnames_default()("".concat(prefixCls, "-mask"), className)
          });
        });
      }
      // EXTERNAL MODULE: ./node_modules/rc-align/es/index.js + 5 modules
      var rc_align_es = __webpack_require__("9mu1");
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/regenerator/index.js
      var regenerator = __webpack_require__("o0o1");
      var regenerator_default = /*#__PURE__*/__webpack_require__.n(regenerator);
      
      // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js
      var asyncToGenerator = __webpack_require__("HaE+");
      
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-trigger/es/Popup/useVisibleStatus.js
      
      
      
      
      
      var StatusQueue = ['measure', 'align', null, 'motion'];
      /* harmony default export */ var useVisibleStatus = (function (visible, doMeasure) {
        var _useState = Object(external_window_React_["useState"])(null),
            _useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
            status = _useState2[0],
            setInternalStatus = _useState2[1];
      
        var rafRef = Object(external_window_React_["useRef"])();
        var destroyRef = Object(external_window_React_["useRef"])(false);
      
        function setStatus(nextStatus) {
          if (!destroyRef.current) {
            setInternalStatus(nextStatus);
          }
        }
      
        function cancelRaf() {
          es_raf["a" /* default */].cancel(rafRef.current);
        }
      
        function goNextStatus(callback) {
          cancelRaf();
          rafRef.current = Object(es_raf["a" /* default */])(function () {
            // Only align should be manually trigger
            setStatus(function (prev) {
              switch (status) {
                case 'align':
                  return 'motion';
      
                case 'motion':
                  return 'stable';
      
                default:
              }
      
              return prev;
            });
            callback === null || callback === void 0 ? void 0 : callback();
          });
        } // Init status
      
      
        Object(external_window_React_["useEffect"])(function () {
          setStatus('measure');
        }, [visible]); // Go next status
      
        Object(external_window_React_["useEffect"])(function () {
          switch (status) {
            case 'measure':
              doMeasure();
              break;
      
            default:
          }
      
          if (status) {
            rafRef.current = Object(es_raf["a" /* default */])( /*#__PURE__*/Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee() {
              var index, nextStatus;
              return regenerator_default.a.wrap(function _callee$(_context) {
                while (1) {
                  switch (_context.prev = _context.next) {
                    case 0:
                      index = StatusQueue.indexOf(status);
                      nextStatus = StatusQueue[index + 1];
      
                      if (nextStatus && index !== -1) {
                        setStatus(nextStatus);
                      }
      
                    case 3:
                    case "end":
                      return _context.stop();
                  }
                }
              }, _callee);
            })));
          }
        }, [status]);
        Object(external_window_React_["useEffect"])(function () {
          return function () {
            destroyRef.current = true;
            cancelRaf();
          };
        }, []);
        return [status, goNextStatus];
      });
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-trigger/es/Popup/useStretchStyle.js
      
      
      /* harmony default export */ var useStretchStyle = (function (stretch) {
        var _React$useState = external_window_React_["useState"]({
          width: 0,
          height: 0
        }),
            _React$useState2 = Object(slicedToArray["a" /* default */])(_React$useState, 2),
            targetSize = _React$useState2[0],
            setTargetSize = _React$useState2[1];
      
        function measureStretch(element) {
          setTargetSize({
            width: element.offsetWidth,
            height: element.offsetHeight
          });
        } // Merge stretch style
      
      
        var style = external_window_React_["useMemo"](function () {
          var sizeStyle = {};
      
          if (stretch) {
            var width = targetSize.width,
                height = targetSize.height; // Stretch with target
      
            if (stretch.indexOf('height') !== -1 && height) {
              sizeStyle.height = height;
            } else if (stretch.indexOf('minHeight') !== -1 && height) {
              sizeStyle.minHeight = height;
            }
      
            if (stretch.indexOf('width') !== -1 && width) {
              sizeStyle.width = width;
            } else if (stretch.indexOf('minWidth') !== -1 && width) {
              sizeStyle.minWidth = width;
            }
          }
      
          return sizeStyle;
        }, [stretch, targetSize]);
        return [style, measureStretch];
      });
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-trigger/es/Popup/PopupInner.js
      
      
      
      
      
      
      
      
      
      
      
      var PopupInner = /*#__PURE__*/external_window_React_["forwardRef"](function (props, ref) {
        var visible = props.visible,
            prefixCls = props.prefixCls,
            className = props.className,
            style = props.style,
            children = props.children,
            zIndex = props.zIndex,
            stretch = props.stretch,
            destroyPopupOnHide = props.destroyPopupOnHide,
            forceRender = props.forceRender,
            align = props.align,
            point = props.point,
            getRootDomNode = props.getRootDomNode,
            getClassNameFromAlign = props.getClassNameFromAlign,
            onAlign = props.onAlign,
            onMouseEnter = props.onMouseEnter,
            onMouseLeave = props.onMouseLeave,
            onMouseDown = props.onMouseDown,
            onTouchStart = props.onTouchStart;
        var alignRef = Object(external_window_React_["useRef"])();
        var elementRef = Object(external_window_React_["useRef"])();
      
        var _useState = Object(external_window_React_["useState"])(),
            _useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
            alignedClassName = _useState2[0],
            setAlignedClassName = _useState2[1]; // ======================= Measure ========================
      
      
        var _useStretchStyle = useStretchStyle(stretch),
            _useStretchStyle2 = Object(slicedToArray["a" /* default */])(_useStretchStyle, 2),
            stretchStyle = _useStretchStyle2[0],
            measureStretchStyle = _useStretchStyle2[1];
      
        function doMeasure() {
          if (stretch) {
            measureStretchStyle(getRootDomNode());
          }
        } // ======================== Status ========================
      
      
        var _useVisibleStatus = useVisibleStatus(visible, doMeasure),
            _useVisibleStatus2 = Object(slicedToArray["a" /* default */])(_useVisibleStatus, 2),
            status = _useVisibleStatus2[0],
            goNextStatus = _useVisibleStatus2[1]; // ======================== Aligns ========================
      
      
        var prepareResolveRef = Object(external_window_React_["useRef"])(); // `target` on `rc-align` can accept as a function to get the bind element or a point.
        // ref: https://www.npmjs.com/package/rc-align
      
        function getAlignTarget() {
          if (point) {
            return point;
          }
      
          return getRootDomNode;
        }
      
        function forceAlign() {
          var _alignRef$current;
      
          (_alignRef$current = alignRef.current) === null || _alignRef$current === void 0 ? void 0 : _alignRef$current.forceAlign();
        }
      
        function onInternalAlign(popupDomNode, matchAlign) {
          var nextAlignedClassName = getClassNameFromAlign(matchAlign);
      
          if (alignedClassName !== nextAlignedClassName) {
            setAlignedClassName(nextAlignedClassName);
          }
      
          if (status === 'align') {
            // Repeat until not more align needed
            if (alignedClassName !== nextAlignedClassName) {
              Promise.resolve().then(function () {
                forceAlign();
              });
            } else {
              goNextStatus(function () {
                var _prepareResolveRef$cu;
      
                (_prepareResolveRef$cu = prepareResolveRef.current) === null || _prepareResolveRef$cu === void 0 ? void 0 : _prepareResolveRef$cu.call(prepareResolveRef);
              });
            }
      
            onAlign === null || onAlign === void 0 ? void 0 : onAlign(popupDomNode, matchAlign);
          }
        } // ======================== Motion ========================
      
      
        var motion = Object(objectSpread2["a" /* default */])({}, getMotion(props));
      
        ['onAppearEnd', 'onEnterEnd', 'onLeaveEnd'].forEach(function (eventName) {
          var originHandler = motion[eventName];
      
          motion[eventName] = function (element, event) {
            goNextStatus();
            return originHandler === null || originHandler === void 0 ? void 0 : originHandler(element, event);
          };
        });
      
        function onShowPrepare() {
          return new Promise(function (resolve) {
            prepareResolveRef.current = resolve;
          });
        } // Go to stable directly when motion not provided
      
      
        external_window_React_["useEffect"](function () {
          if (!motion.motionName && status === 'motion') {
            goNextStatus();
          }
        }, [motion.motionName, status]); // ========================= Refs =========================
      
        external_window_React_["useImperativeHandle"](ref, function () {
          return {
            forceAlign: forceAlign,
            getElement: function getElement() {
              return elementRef.current;
            }
          };
        }); // ======================== Render ========================
      
        var mergedStyle = Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, stretchStyle), {}, {
          zIndex: zIndex,
          opacity: status === 'motion' || status === 'stable' || !visible ? undefined : 0,
          pointerEvents: status === 'stable' ? undefined : 'none'
        }, style); // Align status
      
      
        var alignDisabled = true;
      
        if ((align === null || align === void 0 ? void 0 : align.points) && (status === 'align' || status === 'stable')) {
          alignDisabled = false;
        }
      
        var childNode = children; // Wrapper when multiple children
      
        if (external_window_React_["Children"].count(children) > 1) {
          childNode = /*#__PURE__*/external_window_React_["createElement"]("div", {
            className: "".concat(prefixCls, "-content")
          }, children);
        }
      
        return /*#__PURE__*/external_window_React_["createElement"](rc_motion_es, Object(esm_extends["a" /* default */])({
          visible: visible,
          ref: elementRef,
          leavedClassName: "".concat(prefixCls, "-hidden")
        }, motion, {
          onAppearPrepare: onShowPrepare,
          onEnterPrepare: onShowPrepare,
          removeOnLeave: destroyPopupOnHide,
          forceRender: forceRender
        }), function (_ref, motionRef) {
          var motionClassName = _ref.className,
              motionStyle = _ref.style;
          var mergedClassName = classnames_default()(prefixCls, className, alignedClassName, motionClassName);
          return /*#__PURE__*/external_window_React_["createElement"](rc_align_es["a" /* default */], {
            target: getAlignTarget(),
            key: "popup",
            ref: alignRef,
            monitorWindowResize: true,
            disabled: alignDisabled,
            align: align,
            onAlign: onInternalAlign
          }, /*#__PURE__*/external_window_React_["createElement"]("div", {
            ref: motionRef,
            className: mergedClassName,
            onMouseEnter: onMouseEnter,
            onMouseLeave: onMouseLeave,
            onMouseDownCapture: onMouseDown,
            onTouchStartCapture: onTouchStart,
            style: Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, motionStyle), mergedStyle)
          }, childNode));
        });
      });
      PopupInner.displayName = 'PopupInner';
      /* harmony default export */ var Popup_PopupInner = (PopupInner);
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-trigger/es/Popup/MobilePopupInner.js
      
      
      
      
      
      var MobilePopupInner = /*#__PURE__*/external_window_React_["forwardRef"](function (props, ref) {
        var prefixCls = props.prefixCls,
            visible = props.visible,
            zIndex = props.zIndex,
            children = props.children,
            _props$mobile = props.mobile;
        _props$mobile = _props$mobile === void 0 ? {} : _props$mobile;
        var popupClassName = _props$mobile.popupClassName,
            popupStyle = _props$mobile.popupStyle,
            _props$mobile$popupMo = _props$mobile.popupMotion,
            popupMotion = _props$mobile$popupMo === void 0 ? {} : _props$mobile$popupMo,
            popupRender = _props$mobile.popupRender;
        var elementRef = external_window_React_["useRef"](); // ========================= Refs =========================
      
        external_window_React_["useImperativeHandle"](ref, function () {
          return {
            forceAlign: function forceAlign() {},
            getElement: function getElement() {
              return elementRef.current;
            }
          };
        }); // ======================== Render ========================
      
        var mergedStyle = Object(objectSpread2["a" /* default */])({
          zIndex: zIndex
        }, popupStyle);
      
        var childNode = children; // Wrapper when multiple children
      
        if (external_window_React_["Children"].count(children) > 1) {
          childNode = /*#__PURE__*/external_window_React_["createElement"]("div", {
            className: "".concat(prefixCls, "-content")
          }, children);
        } // Mobile support additional render
      
      
        if (popupRender) {
          childNode = popupRender(childNode);
        }
      
        return /*#__PURE__*/external_window_React_["createElement"](rc_motion_es, Object(esm_extends["a" /* default */])({
          visible: visible,
          ref: elementRef,
          removeOnLeave: true
        }, popupMotion), function (_ref, motionRef) {
          var motionClassName = _ref.className,
              motionStyle = _ref.style;
          var mergedClassName = classnames_default()(prefixCls, popupClassName, motionClassName);
          return /*#__PURE__*/external_window_React_["createElement"]("div", {
            ref: motionRef,
            className: mergedClassName,
            style: Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, motionStyle), mergedStyle)
          }, childNode);
        });
      });
      MobilePopupInner.displayName = 'MobilePopupInner';
      /* harmony default export */ var Popup_MobilePopupInner = (MobilePopupInner);
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-trigger/es/Popup/index.js
      
      
      
      
      var _excluded = ["visible", "mobile"];
      
      
      
      
      
      
      var Popup = /*#__PURE__*/external_window_React_["forwardRef"](function (_ref, ref) {
        var visible = _ref.visible,
            mobile = _ref.mobile,
            props = Object(objectWithoutProperties["a" /* default */])(_ref, _excluded);
      
        var _useState = Object(external_window_React_["useState"])(visible),
            _useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
            innerVisible = _useState2[0],
            serInnerVisible = _useState2[1];
      
        var _useState3 = Object(external_window_React_["useState"])(false),
            _useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
            inMobile = _useState4[0],
            setInMobile = _useState4[1];
      
        var cloneProps = Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, props), {}, {
          visible: innerVisible
        }); // We check mobile in visible changed here.
        // And this also delay set `innerVisible` to avoid popup component render flash
      
      
        Object(external_window_React_["useEffect"])(function () {
          serInnerVisible(visible);
      
          if (visible && mobile) {
            setInMobile(es_isMobile());
          }
        }, [visible, mobile]);
        var popupNode = inMobile ? /*#__PURE__*/external_window_React_["createElement"](Popup_MobilePopupInner, Object(esm_extends["a" /* default */])({}, cloneProps, {
          mobile: mobile,
          ref: ref
        })) : /*#__PURE__*/external_window_React_["createElement"](Popup_PopupInner, Object(esm_extends["a" /* default */])({}, cloneProps, {
          ref: ref
        })); // We can use fragment directly but this may failed some selector usage. Keep as origin logic
      
        return /*#__PURE__*/external_window_React_["createElement"]("div", null, /*#__PURE__*/external_window_React_["createElement"](Mask, cloneProps), popupNode);
      });
      Popup.displayName = 'Popup';
      /* harmony default export */ var es_Popup = (Popup);
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-trigger/es/context.js
      
      var TriggerContext = /*#__PURE__*/external_window_React_["createContext"](null);
      /* harmony default export */ var context = (TriggerContext);
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-trigger/es/index.js
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      function es_noop() {}
      
      function returnEmptyString() {
        return '';
      }
      
      function returnDocument(element) {
        if (element) {
          return element.ownerDocument;
        }
      
        return window.document;
      }
      
      var ALL_HANDLERS = ['onClick', 'onMouseDown', 'onTouchStart', 'onMouseEnter', 'onMouseLeave', 'onFocus', 'onBlur', 'onContextMenu'];
      /**
       * Internal usage. Do not use in your code since this will be removed.
       */
      
      function generateTrigger(PortalComponent) {
        var Trigger = /*#__PURE__*/function (_React$Component) {
          Object(inherits["a" /* default */])(Trigger, _React$Component);
      
          var _super = Object(createSuper["a" /* default */])(Trigger);
      
          function Trigger(props) {
            var _this;
      
            Object(classCallCheck["a" /* default */])(this, Trigger);
      
            _this = _super.call(this, props);
            _this.popupRef = /*#__PURE__*/external_window_React_["createRef"]();
            _this.triggerRef = /*#__PURE__*/external_window_React_["createRef"]();
            _this.attachId = void 0;
            _this.clickOutsideHandler = void 0;
            _this.touchOutsideHandler = void 0;
            _this.contextMenuOutsideHandler1 = void 0;
            _this.contextMenuOutsideHandler2 = void 0;
            _this.mouseDownTimeout = void 0;
            _this.focusTime = void 0;
            _this.preClickTime = void 0;
            _this.preTouchTime = void 0;
            _this.delayTimer = void 0;
            _this.hasPopupMouseDown = void 0;
      
            _this.onMouseEnter = function (e) {
              var mouseEnterDelay = _this.props.mouseEnterDelay;
      
              _this.fireEvents('onMouseEnter', e);
      
              _this.delaySetPopupVisible(true, mouseEnterDelay, mouseEnterDelay ? null : e);
            };
      
            _this.onMouseMove = function (e) {
              _this.fireEvents('onMouseMove', e);
      
              _this.setPoint(e);
            };
      
            _this.onMouseLeave = function (e) {
              _this.fireEvents('onMouseLeave', e);
      
              _this.delaySetPopupVisible(false, _this.props.mouseLeaveDelay);
            };
      
            _this.onPopupMouseEnter = function () {
              _this.clearDelayTimer();
            };
      
            _this.onPopupMouseLeave = function (e) {
              var _this$popupRef$curren;
      
              // https://github.com/react-component/trigger/pull/13
              // react bug?
              if (e.relatedTarget && !e.relatedTarget.setTimeout && Object(contains["a" /* default */])((_this$popupRef$curren = _this.popupRef.current) === null || _this$popupRef$curren === void 0 ? void 0 : _this$popupRef$curren.getElement(), e.relatedTarget)) {
                return;
              }
      
              _this.delaySetPopupVisible(false, _this.props.mouseLeaveDelay);
            };
      
            _this.onFocus = function (e) {
              _this.fireEvents('onFocus', e); // incase focusin and focusout
      
      
              _this.clearDelayTimer();
      
              if (_this.isFocusToShow()) {
                _this.focusTime = Date.now();
      
                _this.delaySetPopupVisible(true, _this.props.focusDelay);
              }
            };
      
            _this.onMouseDown = function (e) {
              _this.fireEvents('onMouseDown', e);
      
              _this.preClickTime = Date.now();
            };
      
            _this.onTouchStart = function (e) {
              _this.fireEvents('onTouchStart', e);
      
              _this.preTouchTime = Date.now();
            };
      
            _this.onBlur = function (e) {
              _this.fireEvents('onBlur', e);
      
              _this.clearDelayTimer();
      
              if (_this.isBlurToHide()) {
                _this.delaySetPopupVisible(false, _this.props.blurDelay);
              }
            };
      
            _this.onContextMenu = function (e) {
              e.preventDefault();
      
              _this.fireEvents('onContextMenu', e);
      
              _this.setPopupVisible(true, e);
            };
      
            _this.onContextMenuClose = function () {
              if (_this.isContextMenuToShow()) {
                _this.close();
              }
            };
      
            _this.onClick = function (event) {
              _this.fireEvents('onClick', event); // focus will trigger click
      
      
              if (_this.focusTime) {
                var preTime;
      
                if (_this.preClickTime && _this.preTouchTime) {
                  preTime = Math.min(_this.preClickTime, _this.preTouchTime);
                } else if (_this.preClickTime) {
                  preTime = _this.preClickTime;
                } else if (_this.preTouchTime) {
                  preTime = _this.preTouchTime;
                }
      
                if (Math.abs(preTime - _this.focusTime) < 20) {
                  return;
                }
      
                _this.focusTime = 0;
              }
      
              _this.preClickTime = 0;
              _this.preTouchTime = 0; // Only prevent default when all the action is click.
              // https://github.com/ant-design/ant-design/issues/17043
              // https://github.com/ant-design/ant-design/issues/17291
      
              if (_this.isClickToShow() && (_this.isClickToHide() || _this.isBlurToHide()) && event && event.preventDefault) {
                event.preventDefault();
              }
      
              var nextVisible = !_this.state.popupVisible;
      
              if (_this.isClickToHide() && !nextVisible || nextVisible && _this.isClickToShow()) {
                _this.setPopupVisible(!_this.state.popupVisible, event);
              }
            };
      
            _this.onPopupMouseDown = function () {
              _this.hasPopupMouseDown = true;
              clearTimeout(_this.mouseDownTimeout);
              _this.mouseDownTimeout = window.setTimeout(function () {
                _this.hasPopupMouseDown = false;
              }, 0);
      
              if (_this.context) {
                var _this$context;
      
                (_this$context = _this.context).onPopupMouseDown.apply(_this$context, arguments);
              }
            };
      
            _this.onDocumentClick = function (event) {
              if (_this.props.mask && !_this.props.maskClosable) {
                return;
              }
      
              var target = event.target;
      
              var root = _this.getRootDomNode();
      
              var popupNode = _this.getPopupDomNode();
      
              if ( // mousedown on the target should also close popup when action is contextMenu.
              // https://github.com/ant-design/ant-design/issues/29853
              (!Object(contains["a" /* default */])(root, target) || _this.isContextMenuOnly()) && !Object(contains["a" /* default */])(popupNode, target) && !_this.hasPopupMouseDown) {
                _this.close();
              }
            };
      
            _this.getRootDomNode = function () {
              var getTriggerDOMNode = _this.props.getTriggerDOMNode;
      
              if (getTriggerDOMNode) {
                return getTriggerDOMNode(_this.triggerRef.current);
              }
      
              try {
                var domNode = Object(findDOMNode["a" /* default */])(_this.triggerRef.current);
      
                if (domNode) {
                  return domNode;
                }
              } catch (err) {// Do nothing
              }
      
              return external_window_ReactDOM_default.a.findDOMNode(Object(assertThisInitialized["a" /* default */])(_this));
            };
      
            _this.getPopupClassNameFromAlign = function (align) {
              var className = [];
              var _this$props = _this.props,
                  popupPlacement = _this$props.popupPlacement,
                  builtinPlacements = _this$props.builtinPlacements,
                  prefixCls = _this$props.prefixCls,
                  alignPoint = _this$props.alignPoint,
                  getPopupClassNameFromAlign = _this$props.getPopupClassNameFromAlign;
      
              if (popupPlacement && builtinPlacements) {
                className.push(getAlignPopupClassName(builtinPlacements, prefixCls, align, alignPoint));
              }
      
              if (getPopupClassNameFromAlign) {
                className.push(getPopupClassNameFromAlign(align));
              }
      
              return className.join(' ');
            };
      
            _this.getComponent = function () {
              var _this$props2 = _this.props,
                  prefixCls = _this$props2.prefixCls,
                  destroyPopupOnHide = _this$props2.destroyPopupOnHide,
                  popupClassName = _this$props2.popupClassName,
                  onPopupAlign = _this$props2.onPopupAlign,
                  popupMotion = _this$props2.popupMotion,
                  popupAnimation = _this$props2.popupAnimation,
                  popupTransitionName = _this$props2.popupTransitionName,
                  popupStyle = _this$props2.popupStyle,
                  mask = _this$props2.mask,
                  maskAnimation = _this$props2.maskAnimation,
                  maskTransitionName = _this$props2.maskTransitionName,
                  maskMotion = _this$props2.maskMotion,
                  zIndex = _this$props2.zIndex,
                  popup = _this$props2.popup,
                  stretch = _this$props2.stretch,
                  alignPoint = _this$props2.alignPoint,
                  mobile = _this$props2.mobile,
                  forceRender = _this$props2.forceRender;
              var _this$state = _this.state,
                  popupVisible = _this$state.popupVisible,
                  point = _this$state.point;
      
              var align = _this.getPopupAlign();
      
              var mouseProps = {};
      
              if (_this.isMouseEnterToShow()) {
                mouseProps.onMouseEnter = _this.onPopupMouseEnter;
              }
      
              if (_this.isMouseLeaveToHide()) {
                mouseProps.onMouseLeave = _this.onPopupMouseLeave;
              }
      
              mouseProps.onMouseDown = _this.onPopupMouseDown;
              mouseProps.onTouchStart = _this.onPopupMouseDown;
              return /*#__PURE__*/external_window_React_["createElement"](es_Popup, Object(esm_extends["a" /* default */])({
                prefixCls: prefixCls,
                destroyPopupOnHide: destroyPopupOnHide,
                visible: popupVisible,
                point: alignPoint && point,
                className: popupClassName,
                align: align,
                onAlign: onPopupAlign,
                animation: popupAnimation,
                getClassNameFromAlign: _this.getPopupClassNameFromAlign
              }, mouseProps, {
                stretch: stretch,
                getRootDomNode: _this.getRootDomNode,
                style: popupStyle,
                mask: mask,
                zIndex: zIndex,
                transitionName: popupTransitionName,
                maskAnimation: maskAnimation,
                maskTransitionName: maskTransitionName,
                maskMotion: maskMotion,
                ref: _this.popupRef,
                motion: popupMotion,
                mobile: mobile,
                forceRender: forceRender
              }), typeof popup === 'function' ? popup() : popup);
            };
      
            _this.attachParent = function (popupContainer) {
              es_raf["a" /* default */].cancel(_this.attachId);
              var _this$props3 = _this.props,
                  getPopupContainer = _this$props3.getPopupContainer,
                  getDocument = _this$props3.getDocument;
      
              var domNode = _this.getRootDomNode();
      
              var mountNode;
      
              if (!getPopupContainer) {
                mountNode = getDocument(_this.getRootDomNode()).body;
              } else if (domNode || getPopupContainer.length === 0) {
                // Compatible for legacy getPopupContainer with domNode argument.
                // If no need `domNode` argument, will call directly.
                // https://codesandbox.io/s/eloquent-mclean-ss93m?file=/src/App.js
                mountNode = getPopupContainer(domNode);
              }
      
              if (mountNode) {
                mountNode.appendChild(popupContainer);
              } else {
                // Retry after frame render in case parent not ready
                _this.attachId = Object(es_raf["a" /* default */])(function () {
                  _this.attachParent(popupContainer);
                });
              }
            };
      
            _this.getContainer = function () {
              var getDocument = _this.props.getDocument;
              var popupContainer = getDocument(_this.getRootDomNode()).createElement('div'); // Make sure default popup container will never cause scrollbar appearing
              // https://github.com/react-component/trigger/issues/41
      
              popupContainer.style.position = 'absolute';
              popupContainer.style.top = '0';
              popupContainer.style.left = '0';
              popupContainer.style.width = '100%';
      
              _this.attachParent(popupContainer);
      
              return popupContainer;
            };
      
            _this.setPoint = function (point) {
              var alignPoint = _this.props.alignPoint;
              if (!alignPoint || !point) return;
      
              _this.setState({
                point: {
                  pageX: point.pageX,
                  pageY: point.pageY
                }
              });
            };
      
            _this.handlePortalUpdate = function () {
              if (_this.state.prevPopupVisible !== _this.state.popupVisible) {
                _this.props.afterPopupVisibleChange(_this.state.popupVisible);
              }
            };
      
            _this.triggerContextValue = {
              onPopupMouseDown: _this.onPopupMouseDown
            };
      
            var _popupVisible;
      
            if ('popupVisible' in props) {
              _popupVisible = !!props.popupVisible;
            } else {
              _popupVisible = !!props.defaultPopupVisible;
            }
      
            _this.state = {
              prevPopupVisible: _popupVisible,
              popupVisible: _popupVisible
            };
            ALL_HANDLERS.forEach(function (h) {
              _this["fire".concat(h)] = function (e) {
                _this.fireEvents(h, e);
              };
            });
            return _this;
          }
      
          Object(createClass["a" /* default */])(Trigger, [{
            key: "componentDidMount",
            value: function componentDidMount() {
              this.componentDidUpdate();
            }
          }, {
            key: "componentDidUpdate",
            value: function componentDidUpdate() {
              var props = this.props;
              var state = this.state; // We must listen to `mousedown` or `touchstart`, edge case:
              // https://github.com/ant-design/ant-design/issues/5804
              // https://github.com/react-component/calendar/issues/250
              // https://github.com/react-component/trigger/issues/50
      
              if (state.popupVisible) {
                var currentDocument;
      
                if (!this.clickOutsideHandler && (this.isClickToHide() || this.isContextMenuToShow())) {
                  currentDocument = props.getDocument(this.getRootDomNode());
                  this.clickOutsideHandler = Object(addEventListener["a" /* default */])(currentDocument, 'mousedown', this.onDocumentClick);
                } // always hide on mobile
      
      
                if (!this.touchOutsideHandler) {
                  currentDocument = currentDocument || props.getDocument(this.getRootDomNode());
                  this.touchOutsideHandler = Object(addEventListener["a" /* default */])(currentDocument, 'touchstart', this.onDocumentClick);
                } // close popup when trigger type contains 'onContextMenu' and document is scrolling.
      
      
                if (!this.contextMenuOutsideHandler1 && this.isContextMenuToShow()) {
                  currentDocument = currentDocument || props.getDocument(this.getRootDomNode());
                  this.contextMenuOutsideHandler1 = Object(addEventListener["a" /* default */])(currentDocument, 'scroll', this.onContextMenuClose);
                } // close popup when trigger type contains 'onContextMenu' and window is blur.
      
      
                if (!this.contextMenuOutsideHandler2 && this.isContextMenuToShow()) {
                  this.contextMenuOutsideHandler2 = Object(addEventListener["a" /* default */])(window, 'blur', this.onContextMenuClose);
                }
      
                return;
              }
      
              this.clearOutsideHandler();
            }
          }, {
            key: "componentWillUnmount",
            value: function componentWillUnmount() {
              this.clearDelayTimer();
              this.clearOutsideHandler();
              clearTimeout(this.mouseDownTimeout);
              es_raf["a" /* default */].cancel(this.attachId);
            }
          }, {
            key: "getPopupDomNode",
            value: function getPopupDomNode() {
              var _this$popupRef$curren2;
      
              // for test
              return ((_this$popupRef$curren2 = this.popupRef.current) === null || _this$popupRef$curren2 === void 0 ? void 0 : _this$popupRef$curren2.getElement()) || null;
            }
          }, {
            key: "getPopupAlign",
            value: function getPopupAlign() {
              var props = this.props;
              var popupPlacement = props.popupPlacement,
                  popupAlign = props.popupAlign,
                  builtinPlacements = props.builtinPlacements;
      
              if (popupPlacement && builtinPlacements) {
                return getAlignFromPlacement(builtinPlacements, popupPlacement, popupAlign);
              }
      
              return popupAlign;
            }
          }, {
            key: "setPopupVisible",
            value:
            /**
             * @param popupVisible    Show or not the popup element
             * @param event           SyntheticEvent, used for `pointAlign`
             */
            function setPopupVisible(popupVisible, event) {
              var alignPoint = this.props.alignPoint;
              var prevPopupVisible = this.state.popupVisible;
              this.clearDelayTimer();
      
              if (prevPopupVisible !== popupVisible) {
                if (!('popupVisible' in this.props)) {
                  this.setState({
                    popupVisible: popupVisible,
                    prevPopupVisible: prevPopupVisible
                  });
                }
      
                this.props.onPopupVisibleChange(popupVisible);
              } // Always record the point position since mouseEnterDelay will delay the show
      
      
              if (alignPoint && event && popupVisible) {
                this.setPoint(event);
              }
            }
          }, {
            key: "delaySetPopupVisible",
            value: function delaySetPopupVisible(visible, delayS, event) {
              var _this2 = this;
      
              var delay = delayS * 1000;
              this.clearDelayTimer();
      
              if (delay) {
                var point = event ? {
                  pageX: event.pageX,
                  pageY: event.pageY
                } : null;
                this.delayTimer = window.setTimeout(function () {
                  _this2.setPopupVisible(visible, point);
      
                  _this2.clearDelayTimer();
                }, delay);
              } else {
                this.setPopupVisible(visible, event);
              }
            }
          }, {
            key: "clearDelayTimer",
            value: function clearDelayTimer() {
              if (this.delayTimer) {
                clearTimeout(this.delayTimer);
                this.delayTimer = null;
              }
            }
          }, {
            key: "clearOutsideHandler",
            value: function clearOutsideHandler() {
              if (this.clickOutsideHandler) {
                this.clickOutsideHandler.remove();
                this.clickOutsideHandler = null;
              }
      
              if (this.contextMenuOutsideHandler1) {
                this.contextMenuOutsideHandler1.remove();
                this.contextMenuOutsideHandler1 = null;
              }
      
              if (this.contextMenuOutsideHandler2) {
                this.contextMenuOutsideHandler2.remove();
                this.contextMenuOutsideHandler2 = null;
              }
      
              if (this.touchOutsideHandler) {
                this.touchOutsideHandler.remove();
                this.touchOutsideHandler = null;
              }
            }
          }, {
            key: "createTwoChains",
            value: function createTwoChains(event) {
              var childPros = this.props.children.props;
              var props = this.props;
      
              if (childPros[event] && props[event]) {
                return this["fire".concat(event)];
              }
      
              return childPros[event] || props[event];
            }
          }, {
            key: "isClickToShow",
            value: function isClickToShow() {
              var _this$props4 = this.props,
                  action = _this$props4.action,
                  showAction = _this$props4.showAction;
              return action.indexOf('click') !== -1 || showAction.indexOf('click') !== -1;
            }
          }, {
            key: "isContextMenuOnly",
            value: function isContextMenuOnly() {
              var action = this.props.action;
              return action === 'contextMenu' || action.length === 1 && action[0] === 'contextMenu';
            }
          }, {
            key: "isContextMenuToShow",
            value: function isContextMenuToShow() {
              var _this$props5 = this.props,
                  action = _this$props5.action,
                  showAction = _this$props5.showAction;
              return action.indexOf('contextMenu') !== -1 || showAction.indexOf('contextMenu') !== -1;
            }
          }, {
            key: "isClickToHide",
            value: function isClickToHide() {
              var _this$props6 = this.props,
                  action = _this$props6.action,
                  hideAction = _this$props6.hideAction;
              return action.indexOf('click') !== -1 || hideAction.indexOf('click') !== -1;
            }
          }, {
            key: "isMouseEnterToShow",
            value: function isMouseEnterToShow() {
              var _this$props7 = this.props,
                  action = _this$props7.action,
                  showAction = _this$props7.showAction;
              return action.indexOf('hover') !== -1 || showAction.indexOf('mouseEnter') !== -1;
            }
          }, {
            key: "isMouseLeaveToHide",
            value: function isMouseLeaveToHide() {
              var _this$props8 = this.props,
                  action = _this$props8.action,
                  hideAction = _this$props8.hideAction;
              return action.indexOf('hover') !== -1 || hideAction.indexOf('mouseLeave') !== -1;
            }
          }, {
            key: "isFocusToShow",
            value: function isFocusToShow() {
              var _this$props9 = this.props,
                  action = _this$props9.action,
                  showAction = _this$props9.showAction;
              return action.indexOf('focus') !== -1 || showAction.indexOf('focus') !== -1;
            }
          }, {
            key: "isBlurToHide",
            value: function isBlurToHide() {
              var _this$props10 = this.props,
                  action = _this$props10.action,
                  hideAction = _this$props10.hideAction;
              return action.indexOf('focus') !== -1 || hideAction.indexOf('blur') !== -1;
            }
          }, {
            key: "forcePopupAlign",
            value: function forcePopupAlign() {
              if (this.state.popupVisible) {
                var _this$popupRef$curren3;
      
                (_this$popupRef$curren3 = this.popupRef.current) === null || _this$popupRef$curren3 === void 0 ? void 0 : _this$popupRef$curren3.forceAlign();
              }
            }
          }, {
            key: "fireEvents",
            value: function fireEvents(type, e) {
              var childCallback = this.props.children.props[type];
      
              if (childCallback) {
                childCallback(e);
              }
      
              var callback = this.props[type];
      
              if (callback) {
                callback(e);
              }
            }
          }, {
            key: "close",
            value: function close() {
              this.setPopupVisible(false);
            }
          }, {
            key: "render",
            value: function render() {
              var popupVisible = this.state.popupVisible;
              var _this$props11 = this.props,
                  children = _this$props11.children,
                  forceRender = _this$props11.forceRender,
                  alignPoint = _this$props11.alignPoint,
                  className = _this$props11.className,
                  autoDestroy = _this$props11.autoDestroy;
              var child = external_window_React_["Children"].only(children);
              var newChildProps = {
                key: 'trigger'
              }; // ============================== Visible Handlers ==============================
              // >>> ContextMenu
      
              if (this.isContextMenuToShow()) {
                newChildProps.onContextMenu = this.onContextMenu;
              } else {
                newChildProps.onContextMenu = this.createTwoChains('onContextMenu');
              } // >>> Click
      
      
              if (this.isClickToHide() || this.isClickToShow()) {
                newChildProps.onClick = this.onClick;
                newChildProps.onMouseDown = this.onMouseDown;
                newChildProps.onTouchStart = this.onTouchStart;
              } else {
                newChildProps.onClick = this.createTwoChains('onClick');
                newChildProps.onMouseDown = this.createTwoChains('onMouseDown');
                newChildProps.onTouchStart = this.createTwoChains('onTouchStart');
              } // >>> Hover(enter)
      
      
              if (this.isMouseEnterToShow()) {
                newChildProps.onMouseEnter = this.onMouseEnter; // Point align
      
                if (alignPoint) {
                  newChildProps.onMouseMove = this.onMouseMove;
                }
              } else {
                newChildProps.onMouseEnter = this.createTwoChains('onMouseEnter');
              } // >>> Hover(leave)
      
      
              if (this.isMouseLeaveToHide()) {
                newChildProps.onMouseLeave = this.onMouseLeave;
              } else {
                newChildProps.onMouseLeave = this.createTwoChains('onMouseLeave');
              } // >>> Focus
      
      
              if (this.isFocusToShow() || this.isBlurToHide()) {
                newChildProps.onFocus = this.onFocus;
                newChildProps.onBlur = this.onBlur;
              } else {
                newChildProps.onFocus = this.createTwoChains('onFocus');
                newChildProps.onBlur = this.createTwoChains('onBlur');
              } // =================================== Render ===================================
      
      
              var childrenClassName = classnames_default()(child && child.props && child.props.className, className);
      
              if (childrenClassName) {
                newChildProps.className = childrenClassName;
              }
      
              var cloneProps = Object(objectSpread2["a" /* default */])({}, newChildProps);
      
              if (Object(es_ref["c" /* supportRef */])(child)) {
                cloneProps.ref = Object(es_ref["a" /* composeRef */])(this.triggerRef, child.ref);
              }
      
              var trigger = /*#__PURE__*/external_window_React_["cloneElement"](child, cloneProps);
              var portal; // prevent unmounting after it's rendered
      
              if (popupVisible || this.popupRef.current || forceRender) {
                portal = /*#__PURE__*/external_window_React_["createElement"](PortalComponent, {
                  key: "portal",
                  getContainer: this.getContainer,
                  didUpdate: this.handlePortalUpdate
                }, this.getComponent());
              }
      
              if (!popupVisible && autoDestroy) {
                portal = null;
              }
      
              return /*#__PURE__*/external_window_React_["createElement"](context.Provider, {
                value: this.triggerContextValue
              }, trigger, portal);
            }
          }], [{
            key: "getDerivedStateFromProps",
            value: function getDerivedStateFromProps(_ref, prevState) {
              var popupVisible = _ref.popupVisible;
              var newState = {};
      
              if (popupVisible !== undefined && prevState.popupVisible !== popupVisible) {
                newState.popupVisible = popupVisible;
                newState.prevPopupVisible = prevState.popupVisible;
              }
      
              return newState;
            }
          }]);
      
          return Trigger;
        }(external_window_React_["Component"]);
      
        Trigger.contextType = context;
        Trigger.defaultProps = {
          prefixCls: 'rc-trigger-popup',
          getPopupClassNameFromAlign: returnEmptyString,
          getDocument: returnDocument,
          onPopupVisibleChange: es_noop,
          afterPopupVisibleChange: es_noop,
          onPopupAlign: es_noop,
          popupClassName: '',
          mouseEnterDelay: 0,
          mouseLeaveDelay: 0.1,
          focusDelay: 0,
          blurDelay: 0.15,
          popupStyle: {},
          destroyPopupOnHide: false,
          popupAlign: {},
          defaultPopupVisible: false,
          mask: false,
          maskClosable: true,
          action: [],
          showAction: [],
          hideAction: [],
          autoDestroy: false
        };
        return Trigger;
      }
      /* harmony default export */ var rc_trigger_es = (generateTrigger(Portal["a" /* default */]));
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-menu/es/placements.js
      var autoAdjustOverflow = {
        adjustX: 1,
        adjustY: 1
      };
      var placements = {
        topLeft: {
          points: ['bl', 'tl'],
          overflow: autoAdjustOverflow,
          offset: [0, -7]
        },
        bottomLeft: {
          points: ['tl', 'bl'],
          overflow: autoAdjustOverflow,
          offset: [0, 7]
        },
        leftTop: {
          points: ['tr', 'tl'],
          overflow: autoAdjustOverflow,
          offset: [-4, 0]
        },
        rightTop: {
          points: ['tl', 'tr'],
          overflow: autoAdjustOverflow,
          offset: [4, 0]
        }
      };
      var placementsRtl = {
        topLeft: {
          points: ['bl', 'tl'],
          overflow: autoAdjustOverflow,
          offset: [0, -7]
        },
        bottomLeft: {
          points: ['tl', 'bl'],
          overflow: autoAdjustOverflow,
          offset: [0, 7]
        },
        rightTop: {
          points: ['tr', 'tl'],
          overflow: autoAdjustOverflow,
          offset: [-4, 0]
        },
        leftTop: {
          points: ['tl', 'tr'],
          overflow: autoAdjustOverflow,
          offset: [4, 0]
        }
      };
      /* harmony default export */ var es_placements = (placements);
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-menu/es/SubMenu.js
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      var guid = 0;
      var popupPlacementMap = {
        horizontal: 'bottomLeft',
        vertical: 'rightTop',
        'vertical-left': 'rightTop',
        'vertical-right': 'leftTop'
      };
      
      var SubMenu_updateDefaultActiveFirst = function updateDefaultActiveFirst(store, eventKey, defaultActiveFirst) {
        var menuId = getMenuIdFromSubMenuEventKey(eventKey);
        var state = store.getState();
        store.setState({
          defaultActiveFirst: Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, state.defaultActiveFirst), {}, Object(defineProperty["a" /* default */])({}, menuId, defaultActiveFirst))
        });
      };
      
      var SubMenu_SubMenu = /*#__PURE__*/function (_React$Component) {
        Object(inherits["a" /* default */])(SubMenu, _React$Component);
      
        var _super = Object(createSuper["a" /* default */])(SubMenu);
      
        function SubMenu(props) {
          var _this;
      
          Object(classCallCheck["a" /* default */])(this, SubMenu);
      
          _this = _super.call(this, props);
      
          _this.onDestroy = function (key) {
            _this.props.onDestroy(key);
          };
          /**
           * note:
           *  This legacy code that `onKeyDown` is called by parent instead of dom self.
           *  which need return code to check if this event is handled
           */
      
      
          _this.onKeyDown = function (e) {
            var keyCode = e.keyCode;
            var menu = _this.menuInstance;
            var store = _this.props.store;
      
            var visible = _this.getVisible();
      
            if (keyCode === KeyCode["a" /* default */].ENTER) {
              _this.onTitleClick(e);
      
              SubMenu_updateDefaultActiveFirst(store, _this.props.eventKey, true);
              return true;
            }
      
            if (keyCode === KeyCode["a" /* default */].RIGHT) {
              if (visible) {
                menu.onKeyDown(e);
              } else {
                _this.triggerOpenChange(true); // need to update current menu's defaultActiveFirst value
      
      
                SubMenu_updateDefaultActiveFirst(store, _this.props.eventKey, true);
              }
      
              return true;
            }
      
            if (keyCode === KeyCode["a" /* default */].LEFT) {
              var handled;
      
              if (visible) {
                handled = menu.onKeyDown(e);
              } else {
                return undefined;
              }
      
              if (!handled) {
                _this.triggerOpenChange(false);
      
                handled = true;
              }
      
              return handled;
            }
      
            if (visible && (keyCode === KeyCode["a" /* default */].UP || keyCode === KeyCode["a" /* default */].DOWN)) {
              return menu.onKeyDown(e);
            }
      
            return undefined;
          };
      
          _this.onOpenChange = function (e) {
            _this.props.onOpenChange(e);
          };
      
          _this.onPopupVisibleChange = function (visible) {
            _this.triggerOpenChange(visible, visible ? 'mouseenter' : 'mouseleave');
          };
      
          _this.onMouseEnter = function (e) {
            var _this$props = _this.props,
                key = _this$props.eventKey,
                onMouseEnter = _this$props.onMouseEnter,
                store = _this$props.store;
            SubMenu_updateDefaultActiveFirst(store, _this.props.eventKey, false);
            onMouseEnter({
              key: key,
              domEvent: e
            });
          };
      
          _this.onMouseLeave = function (e) {
            var _this$props2 = _this.props,
                parentMenu = _this$props2.parentMenu,
                eventKey = _this$props2.eventKey,
                onMouseLeave = _this$props2.onMouseLeave;
            parentMenu.subMenuInstance = Object(assertThisInitialized["a" /* default */])(_this);
            onMouseLeave({
              key: eventKey,
              domEvent: e
            });
          };
      
          _this.onTitleMouseEnter = function (domEvent) {
            var _this$props3 = _this.props,
                key = _this$props3.eventKey,
                onItemHover = _this$props3.onItemHover,
                onTitleMouseEnter = _this$props3.onTitleMouseEnter;
            onItemHover({
              key: key,
              hover: true
            });
            onTitleMouseEnter({
              key: key,
              domEvent: domEvent
            });
          };
      
          _this.onTitleMouseLeave = function (e) {
            var _this$props4 = _this.props,
                parentMenu = _this$props4.parentMenu,
                eventKey = _this$props4.eventKey,
                onItemHover = _this$props4.onItemHover,
                onTitleMouseLeave = _this$props4.onTitleMouseLeave;
            parentMenu.subMenuInstance = Object(assertThisInitialized["a" /* default */])(_this);
            onItemHover({
              key: eventKey,
              hover: false
            });
            onTitleMouseLeave({
              key: eventKey,
              domEvent: e
            });
          };
      
          _this.onTitleClick = function (e) {
            var _assertThisInitialize = Object(assertThisInitialized["a" /* default */])(_this),
                props = _assertThisInitialize.props;
      
            props.onTitleClick({
              key: props.eventKey,
              domEvent: e
            });
      
            if (props.triggerSubMenuAction === 'hover') {
              return;
            }
      
            _this.triggerOpenChange(!_this.getVisible(), 'click');
      
            SubMenu_updateDefaultActiveFirst(props.store, _this.props.eventKey, false);
          };
      
          _this.onSubMenuClick = function (info) {
            // in the case of overflowed submenu
            // onClick is not copied over
            if (typeof _this.props.onClick === 'function') {
              _this.props.onClick(_this.addKeyPath(info));
            }
          };
      
          _this.onSelect = function (info) {
            _this.props.onSelect(info);
          };
      
          _this.onDeselect = function (info) {
            _this.props.onDeselect(info);
          };
      
          _this.getPrefixCls = function () {
            return "".concat(_this.props.rootPrefixCls, "-submenu");
          };
      
          _this.getActiveClassName = function () {
            return "".concat(_this.getPrefixCls(), "-active");
          };
      
          _this.getDisabledClassName = function () {
            return "".concat(_this.getPrefixCls(), "-disabled");
          };
      
          _this.getSelectedClassName = function () {
            return "".concat(_this.getPrefixCls(), "-selected");
          };
      
          _this.getOpenClassName = function () {
            return "".concat(_this.props.rootPrefixCls, "-submenu-open");
          };
      
          _this.getVisible = function () {
            return _this.state.isOpen;
          };
      
          _this.getMode = function () {
            return _this.state.mode;
          };
      
          _this.saveMenuInstance = function (c) {
            // children menu instance
            _this.menuInstance = c;
          };
      
          _this.addKeyPath = function (info) {
            return Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, info), {}, {
              keyPath: (info.keyPath || []).concat(_this.props.eventKey)
            });
          };
      
          _this.triggerOpenChange = function (open, type) {
            var key = _this.props.eventKey;
      
            var openChange = function openChange() {
              _this.onOpenChange({
                key: key,
                item: Object(assertThisInitialized["a" /* default */])(_this),
                trigger: type,
                open: open
              });
            };
      
            if (type === 'mouseenter') {
              // make sure mouseenter happen after other menu item's mouseleave
              _this.mouseenterTimeout = setTimeout(function () {
                openChange();
              }, 0);
            } else {
              openChange();
            }
          };
      
          _this.isChildrenSelected = function () {
            var ret = {
              find: false
            };
            loopMenuItemRecursively(_this.props.children, _this.props.selectedKeys, ret);
            return ret.find;
          };
      
          _this.isInlineMode = function () {
            return _this.getMode() === 'inline';
          };
      
          _this.adjustWidth = function () {
            /* istanbul ignore if */
            if (!_this.subMenuTitle || !_this.menuInstance) {
              return;
            }
      
            var popupMenu = external_window_ReactDOM_["findDOMNode"](_this.menuInstance);
      
            if (popupMenu.offsetWidth >= _this.subMenuTitle.offsetWidth) {
              return;
            }
            /* istanbul ignore next */
      
      
            popupMenu.style.minWidth = "".concat(_this.subMenuTitle.offsetWidth, "px");
          };
      
          _this.saveSubMenuTitle = function (subMenuTitle) {
            _this.subMenuTitle = subMenuTitle;
          };
      
          _this.getBaseProps = function () {
            var _assertThisInitialize2 = Object(assertThisInitialized["a" /* default */])(_this),
                props = _assertThisInitialize2.props;
      
            var mergedMode = _this.getMode();
      
            return {
              mode: mergedMode === 'horizontal' ? 'vertical' : mergedMode,
              visible: _this.getVisible(),
              level: props.level + 1,
              inlineIndent: props.inlineIndent,
              focusable: false,
              onClick: _this.onSubMenuClick,
              onSelect: _this.onSelect,
              onDeselect: _this.onDeselect,
              onDestroy: _this.onDestroy,
              selectedKeys: props.selectedKeys,
              eventKey: "".concat(props.eventKey, "-menu-"),
              openKeys: props.openKeys,
              motion: props.motion,
              onOpenChange: _this.onOpenChange,
              subMenuOpenDelay: props.subMenuOpenDelay,
              parentMenu: Object(assertThisInitialized["a" /* default */])(_this),
              subMenuCloseDelay: props.subMenuCloseDelay,
              forceSubMenuRender: props.forceSubMenuRender,
              triggerSubMenuAction: props.triggerSubMenuAction,
              builtinPlacements: props.builtinPlacements,
              defaultActiveFirst: props.store.getState().defaultActiveFirst[getMenuIdFromSubMenuEventKey(props.eventKey)],
              multiple: props.multiple,
              prefixCls: props.rootPrefixCls,
              id: _this.internalMenuId,
              manualRef: _this.saveMenuInstance,
              itemIcon: props.itemIcon,
              expandIcon: props.expandIcon,
              direction: props.direction
            };
          };
      
          _this.getMotion = function (mode, visible) {
            var _assertThisInitialize3 = Object(assertThisInitialized["a" /* default */])(_this),
                haveRendered = _assertThisInitialize3.haveRendered;
      
            var _this$props5 = _this.props,
                motion = _this$props5.motion,
                rootPrefixCls = _this$props5.rootPrefixCls; // don't show transition on first rendering (no animation for opened menu)
            // show appear transition if it's not visible (not sure why)
            // show appear transition if it's not inline mode
      
            var mergedMotion = Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, motion), {}, {
              leavedClassName: "".concat(rootPrefixCls, "-hidden"),
              removeOnLeave: false,
              motionAppear: haveRendered || !visible || mode !== 'inline'
            });
      
            return mergedMotion;
          };
      
          var store = props.store,
              eventKey = props.eventKey;
      
          var _store$getState = store.getState(),
              defaultActiveFirst = _store$getState.defaultActiveFirst;
      
          _this.isRootMenu = false;
          var value = false;
      
          if (defaultActiveFirst) {
            value = defaultActiveFirst[eventKey];
          }
      
          SubMenu_updateDefaultActiveFirst(store, eventKey, value);
          _this.state = {
            mode: props.mode,
            isOpen: props.isOpen
          };
          return _this;
        }
      
        Object(createClass["a" /* default */])(SubMenu, [{
          key: "componentDidMount",
          value: function componentDidMount() {
            this.componentDidUpdate();
          }
        }, {
          key: "componentDidUpdate",
          value: function componentDidUpdate() {
            var _this2 = this;
      
            var _this$props6 = this.props,
                mode = _this$props6.mode,
                parentMenu = _this$props6.parentMenu,
                manualRef = _this$props6.manualRef,
                isOpen = _this$props6.isOpen;
      
            var updateState = function updateState() {
              _this2.setState({
                mode: mode,
                isOpen: isOpen
              });
            }; // Delay sync when mode changed in case openKeys change not sync
      
      
            var isOpenChanged = isOpen !== this.state.isOpen;
            var isModeChanged = mode !== this.state.mode;
      
            if (isModeChanged || isOpenChanged) {
              es_raf["a" /* default */].cancel(this.updateStateRaf);
      
              if (isModeChanged) {
                this.updateStateRaf = Object(es_raf["a" /* default */])(updateState);
              } else {
                updateState();
              }
            } // invoke customized ref to expose component to mixin
      
      
            if (manualRef) {
              manualRef(this);
            }
      
            if (mode !== 'horizontal' || !(parentMenu === null || parentMenu === void 0 ? void 0 : parentMenu.isRootMenu) || !isOpen) {
              return;
            }
      
            this.minWidthTimeout = setTimeout(function () {
              return _this2.adjustWidth();
            }, 0);
          }
        }, {
          key: "componentWillUnmount",
          value: function componentWillUnmount() {
            var _this$props7 = this.props,
                onDestroy = _this$props7.onDestroy,
                eventKey = _this$props7.eventKey;
      
            if (onDestroy) {
              onDestroy(eventKey);
            }
            /* istanbul ignore if */
      
      
            if (this.minWidthTimeout) {
              clearTimeout(this.minWidthTimeout);
            }
            /* istanbul ignore if */
      
      
            if (this.mouseenterTimeout) {
              clearTimeout(this.mouseenterTimeout);
            }
      
            es_raf["a" /* default */].cancel(this.updateStateRaf);
          }
        }, {
          key: "renderPopupMenu",
          value: function renderPopupMenu(className, style) {
            var baseProps = this.getBaseProps();
            /**
             * zombiej: Why SubPopupMenu here?
             * Seems whatever popup or inline mode both will render SubPopupMenu.
             * It's controlled by Trigger for popup or not.
             */
      
            return /*#__PURE__*/external_window_React_["createElement"](es_SubPopupMenu, Object(esm_extends["a" /* default */])({}, baseProps, {
              id: this.internalMenuId,
              className: className,
              style: style
            }), this.props.children);
          }
        }, {
          key: "renderChildren",
          value: function renderChildren() {
            var _this3 = this;
      
            var baseProps = this.getBaseProps();
            var mode = baseProps.mode,
                visible = baseProps.visible,
                forceSubMenuRender = baseProps.forceSubMenuRender,
                direction = baseProps.direction; // [Legacy] getMotion must be called before `haveRendered`
      
            var mergedMotion = this.getMotion(mode, visible);
            this.haveRendered = true;
            this.haveOpened = this.haveOpened || visible || forceSubMenuRender; // never rendered not planning to, don't render
      
            if (!this.haveOpened) {
              return /*#__PURE__*/external_window_React_["createElement"]("div", null);
            }
      
            var sharedClassName = classnames_default()("".concat(baseProps.prefixCls, "-sub"), Object(defineProperty["a" /* default */])({}, "".concat(baseProps.prefixCls, "-rtl"), direction === 'rtl'));
      
            if (!this.isInlineMode()) {
              return this.renderPopupMenu(sharedClassName);
            }
      
            return /*#__PURE__*/external_window_React_["createElement"](rc_motion_es, Object(esm_extends["a" /* default */])({
              visible: baseProps.visible,
              forceRender: forceSubMenuRender
            }, mergedMotion), function (_ref) {
              var className = _ref.className,
                  style = _ref.style;
              var mergedClassName = classnames_default()(sharedClassName, className);
              return _this3.renderPopupMenu(mergedClassName, style);
            });
          }
        }, {
          key: "render",
          value: function render() {
            var _classNames2, _props$parentMenu, _classNames3;
      
            var props = Object(objectSpread2["a" /* default */])({}, this.props);
      
            var visible = this.getVisible();
            var prefixCls = this.getPrefixCls();
            var inline = this.isInlineMode();
            var mergedMode = this.getMode();
            var className = classnames_default()(prefixCls, "".concat(prefixCls, "-").concat(mergedMode), (_classNames2 = {}, Object(defineProperty["a" /* default */])(_classNames2, props.className, !!props.className), Object(defineProperty["a" /* default */])(_classNames2, this.getOpenClassName(), visible), Object(defineProperty["a" /* default */])(_classNames2, this.getActiveClassName(), props.active || visible && !inline), Object(defineProperty["a" /* default */])(_classNames2, this.getDisabledClassName(), props.disabled), Object(defineProperty["a" /* default */])(_classNames2, this.getSelectedClassName(), this.isChildrenSelected()), _classNames2));
      
            if (!this.internalMenuId) {
              if (props.eventKey) {
                this.internalMenuId = "".concat(props.eventKey, "$Menu");
              } else {
                guid += 1;
                this.internalMenuId = "$__$".concat(guid, "$Menu");
              }
            }
      
            var mouseEvents = {};
            var titleClickEvents = {};
            var titleMouseEvents = {};
      
            if (!props.disabled) {
              mouseEvents = {
                onMouseLeave: this.onMouseLeave,
                onMouseEnter: this.onMouseEnter
              }; // only works in title, not outer li
      
              titleClickEvents = {
                onClick: this.onTitleClick
              };
              titleMouseEvents = {
                onMouseEnter: this.onTitleMouseEnter,
                onMouseLeave: this.onTitleMouseLeave
              };
            }
      
            var style = {};
            var direction = props.direction;
            var isRTL = direction === 'rtl';
      
            if (inline) {
              if (isRTL) {
                style.paddingRight = props.inlineIndent * props.level;
              } else {
                style.paddingLeft = props.inlineIndent * props.level;
              }
            }
      
            var ariaOwns = {}; // only set aria-owns when menu is open
            // otherwise it would be an invalid aria-owns value
            // since corresponding node cannot be found
      
            if (this.getVisible()) {
              ariaOwns = {
                'aria-owns': this.internalMenuId
              };
            } // expand custom icon should NOT be displayed in menu with horizontal mode.
      
      
            var icon = null;
      
            if (mergedMode !== 'horizontal') {
              icon = this.props.expandIcon; // ReactNode
      
              if (typeof this.props.expandIcon === 'function') {
                icon = /*#__PURE__*/external_window_React_["createElement"](this.props.expandIcon, Object(objectSpread2["a" /* default */])({}, this.props));
              }
            }
      
            var title = /*#__PURE__*/external_window_React_["createElement"]("div", Object(esm_extends["a" /* default */])({
              ref: this.saveSubMenuTitle,
              style: style,
              className: "".concat(prefixCls, "-title"),
              role: "button"
            }, titleMouseEvents, titleClickEvents, {
              "aria-expanded": visible
            }, ariaOwns, {
              "aria-haspopup": "true",
              title: typeof props.title === 'string' ? props.title : undefined
            }), props.title, icon || /*#__PURE__*/external_window_React_["createElement"]("i", {
              className: "".concat(prefixCls, "-arrow")
            }));
            var children = this.renderChildren();
            var getPopupContainer = ((_props$parentMenu = props.parentMenu) === null || _props$parentMenu === void 0 ? void 0 : _props$parentMenu.isRootMenu) ? props.parentMenu.props.getPopupContainer : function (triggerNode) {
              return triggerNode.parentNode;
            };
            var popupPlacement = popupPlacementMap[mergedMode];
            var popupAlign = props.popupOffset ? {
              offset: props.popupOffset
            } : {};
            var popupClassName = classnames_default()((_classNames3 = {}, Object(defineProperty["a" /* default */])(_classNames3, props.popupClassName, props.popupClassName && !inline), Object(defineProperty["a" /* default */])(_classNames3, "".concat(prefixCls, "-rtl"), isRTL), _classNames3));
            var disabled = props.disabled,
                triggerSubMenuAction = props.triggerSubMenuAction,
                subMenuOpenDelay = props.subMenuOpenDelay,
                forceSubMenuRender = props.forceSubMenuRender,
                subMenuCloseDelay = props.subMenuCloseDelay,
                builtinPlacements = props.builtinPlacements;
            menuAllProps.forEach(function (key) {
              return delete props[key];
            }); // Set onClick to null, to ignore propagated onClick event
      
            delete props.onClick;
            var placement = isRTL ? Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, placementsRtl), builtinPlacements) : Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, placements), builtinPlacements);
            delete props.direction; // [Legacy] It's a fast fix,
            // but we should check if we can refactor this to make code more easy to understand
      
            var baseProps = this.getBaseProps();
            var mergedMotion = inline ? null : this.getMotion(baseProps.mode, baseProps.visible);
            return /*#__PURE__*/external_window_React_["createElement"]("li", Object(esm_extends["a" /* default */])({}, props, mouseEvents, {
              className: className,
              role: "menuitem"
            }), /*#__PURE__*/external_window_React_["createElement"](rc_trigger_es, {
              prefixCls: prefixCls,
              popupClassName: classnames_default()("".concat(prefixCls, "-popup"), popupClassName),
              getPopupContainer: getPopupContainer,
              builtinPlacements: placement,
              popupPlacement: popupPlacement,
              popupVisible: inline ? false : visible,
              popupAlign: popupAlign,
              popup: inline ? null : children,
              action: disabled || inline ? [] : [triggerSubMenuAction],
              mouseEnterDelay: subMenuOpenDelay,
              mouseLeaveDelay: subMenuCloseDelay,
              onPopupVisibleChange: this.onPopupVisibleChange,
              forceRender: forceSubMenuRender,
              popupMotion: mergedMotion
            }, title), inline ? children : null);
          }
        }]);
      
        return SubMenu;
      }(external_window_React_["Component"]);
      SubMenu_SubMenu.defaultProps = {
        onMouseEnter: noop,
        onMouseLeave: noop,
        onTitleMouseEnter: noop,
        onTitleMouseLeave: noop,
        onTitleClick: noop,
        manualRef: noop,
        mode: 'vertical',
        title: ''
      };
      var connected = Object(esm["b" /* connect */])(function (_ref2, _ref3) {
        var openKeys = _ref2.openKeys,
            activeKey = _ref2.activeKey,
            selectedKeys = _ref2.selectedKeys;
        var eventKey = _ref3.eventKey,
            subMenuKey = _ref3.subMenuKey;
        return {
          isOpen: openKeys.indexOf(eventKey) > -1,
          active: activeKey[subMenuKey] === eventKey,
          selectedKeys: selectedKeys
        };
      })(SubMenu_SubMenu);
      connected.isSubMenu = true;
      /* harmony default export */ var es_SubMenu = (connected);
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-menu/es/DOMWrap.js
      
      
      
      
      
      
      
      
      
      
      
      
      var MENUITEM_OVERFLOWED_CLASSNAME = 'menuitem-overflowed';
      var FLOAT_PRECISION_ADJUST = 0.5;
      
      var DOMWrap_DOMWrap = /*#__PURE__*/function (_React$Component) {
        Object(inherits["a" /* default */])(DOMWrap, _React$Component);
      
        var _super = Object(createSuper["a" /* default */])(DOMWrap);
      
        function DOMWrap() {
          var _this;
      
          Object(classCallCheck["a" /* default */])(this, DOMWrap);
      
          _this = _super.apply(this, arguments);
          _this.resizeObserver = null;
          _this.mutationObserver = null; // original scroll size of the list
      
          _this.originalTotalWidth = 0; // copy of overflowed items
      
          _this.overflowedItems = []; // cache item of the original items (so we can track the size and order)
      
          _this.menuItemSizes = [];
          _this.cancelFrameId = null;
          _this.state = {
            lastVisibleIndex: undefined
          };
          _this.childRef = /*#__PURE__*/external_window_React_["createRef"](); // get all valid menuItem nodes
      
          _this.getMenuItemNodes = function () {
            var prefixCls = _this.props.prefixCls;
            var ul = _this.childRef.current;
      
            if (!ul) {
              return [];
            } // filter out all overflowed indicator placeholder
      
      
            return [].slice.call(ul.children).filter(function (node) {
              return node.className.split(' ').indexOf("".concat(prefixCls, "-overflowed-submenu")) < 0;
            });
          };
      
          _this.getOverflowedSubMenuItem = function (keyPrefix, overflowedItems, renderPlaceholder) {
            var _this$props = _this.props,
                overflowedIndicator = _this$props.overflowedIndicator,
                level = _this$props.level,
                mode = _this$props.mode,
                prefixCls = _this$props.prefixCls,
                theme = _this$props.theme;
      
            if (level !== 1 || mode !== 'horizontal') {
              return null;
            } // put all the overflowed item inside a submenu
            // with a title of overflow indicator ('...')
      
      
            var copy = _this.props.children[0];
      
            var _copy$props = copy.props,
                throwAway = _copy$props.children,
                title = _copy$props.title,
                propStyle = _copy$props.style,
                rest = Object(objectWithoutProperties["a" /* default */])(_copy$props, ["children", "title", "style"]);
      
            var style = Object(objectSpread2["a" /* default */])({}, propStyle);
      
            var key = "".concat(keyPrefix, "-overflowed-indicator");
            var eventKey = "".concat(keyPrefix, "-overflowed-indicator");
      
            if (overflowedItems.length === 0 && renderPlaceholder !== true) {
              style = Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, style), {}, {
                display: 'none'
              });
            } else if (renderPlaceholder) {
              style = Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, style), {}, {
                visibility: 'hidden',
                // prevent from taking normal dom space
                position: 'absolute'
              });
              key = "".concat(key, "-placeholder");
              eventKey = "".concat(eventKey, "-placeholder");
            }
      
            var popupClassName = theme ? "".concat(prefixCls, "-").concat(theme) : '';
            var props = {};
            menuAllProps.forEach(function (k) {
              if (rest[k] !== undefined) {
                props[k] = rest[k];
              }
            });
            return /*#__PURE__*/external_window_React_["createElement"](es_SubMenu, Object(esm_extends["a" /* default */])({
              title: overflowedIndicator,
              className: "".concat(prefixCls, "-overflowed-submenu"),
              popupClassName: popupClassName
            }, props, {
              key: key,
              eventKey: eventKey,
              disabled: false,
              style: style
            }), overflowedItems);
          }; // memorize rendered menuSize
      
      
          _this.setChildrenWidthAndResize = function () {
            if (_this.props.mode !== 'horizontal') {
              return;
            }
      
            var ul = _this.childRef.current;
      
            if (!ul) {
              return;
            }
      
            var ulChildrenNodes = ul.children;
      
            if (!ulChildrenNodes || ulChildrenNodes.length === 0) {
              return;
            }
      
            var lastOverflowedIndicatorPlaceholder = ul.children[ulChildrenNodes.length - 1]; // need last overflowed indicator for calculating length;
      
            util_setStyle(lastOverflowedIndicatorPlaceholder, 'display', 'inline-block');
      
            var menuItemNodes = _this.getMenuItemNodes(); // reset display attribute for all hidden elements caused by overflow to calculate updated width
            // and then reset to original state after width calculation
      
      
            var overflowedItems = menuItemNodes.filter(function (c) {
              return c.className.split(' ').indexOf(MENUITEM_OVERFLOWED_CLASSNAME) >= 0;
            });
            overflowedItems.forEach(function (c) {
              util_setStyle(c, 'display', 'inline-block');
            });
            _this.menuItemSizes = menuItemNodes.map(function (c) {
              return getWidth(c, true);
            });
            overflowedItems.forEach(function (c) {
              util_setStyle(c, 'display', 'none');
            });
            _this.overflowedIndicatorWidth = getWidth(ul.children[ul.children.length - 1], true);
            _this.originalTotalWidth = _this.menuItemSizes.reduce(function (acc, cur) {
              return acc + cur;
            }, 0);
      
            _this.handleResize(); // prevent the overflowed indicator from taking space;
      
      
            util_setStyle(lastOverflowedIndicatorPlaceholder, 'display', 'none');
          };
      
          _this.handleResize = function () {
            if (_this.props.mode !== 'horizontal') {
              return;
            }
      
            var ul = _this.childRef.current;
      
            if (!ul) {
              return;
            }
      
            var width = getWidth(ul);
            _this.overflowedItems = [];
            var currentSumWidth = 0; // index for last visible child in horizontal mode
      
            var lastVisibleIndex; // float number comparison could be problematic
            // e.g. 0.1 + 0.2 > 0.3 =====> true
            // thus using FLOAT_PRECISION_ADJUST as buffer to help the situation
      
            if (_this.originalTotalWidth > width + FLOAT_PRECISION_ADJUST) {
              lastVisibleIndex = -1;
      
              _this.menuItemSizes.forEach(function (liWidth) {
                currentSumWidth += liWidth;
      
                if (currentSumWidth + _this.overflowedIndicatorWidth <= width) {
                  lastVisibleIndex += 1;
                }
              });
            }
      
            _this.setState({
              lastVisibleIndex: lastVisibleIndex
            });
          };
      
          return _this;
        }
      
        Object(createClass["a" /* default */])(DOMWrap, [{
          key: "componentDidMount",
          value: function componentDidMount() {
            var _this2 = this;
      
            this.setChildrenWidthAndResize();
      
            if (this.props.level === 1 && this.props.mode === 'horizontal') {
              var menuUl = this.childRef.current;
      
              if (!menuUl) {
                return;
              }
      
              this.resizeObserver = new ResizeObserver_es["default"](function (entries) {
                entries.forEach(function () {
                  var cancelFrameId = _this2.cancelFrameId;
                  cancelAnimationFrame(cancelFrameId);
                  _this2.cancelFrameId = requestAnimationFrame(_this2.setChildrenWidthAndResize);
                });
              });
              [].slice.call(menuUl.children).concat(menuUl).forEach(function (el) {
                _this2.resizeObserver.observe(el);
              });
      
              if (typeof MutationObserver !== 'undefined') {
                this.mutationObserver = new MutationObserver(function () {
                  _this2.resizeObserver.disconnect();
      
                  [].slice.call(menuUl.children).concat(menuUl).forEach(function (el) {
                    _this2.resizeObserver.observe(el);
                  });
      
                  _this2.setChildrenWidthAndResize();
                });
                this.mutationObserver.observe(menuUl, {
                  attributes: false,
                  childList: true,
                  subTree: false
                });
              }
            }
          }
        }, {
          key: "componentWillUnmount",
          value: function componentWillUnmount() {
            if (this.resizeObserver) {
              this.resizeObserver.disconnect();
            }
      
            if (this.mutationObserver) {
              this.mutationObserver.disconnect();
            }
      
            cancelAnimationFrame(this.cancelFrameId);
          }
        }, {
          key: "renderChildren",
          value: function renderChildren(children) {
            var _this3 = this;
      
            // need to take care of overflowed items in horizontal mode
            var lastVisibleIndex = this.state.lastVisibleIndex;
            return (children || []).reduce(function (acc, childNode, index) {
              var item = childNode;
      
              if (_this3.props.mode === 'horizontal') {
                var overflowed = _this3.getOverflowedSubMenuItem(childNode.props.eventKey, []);
      
                if (lastVisibleIndex !== undefined && _this3.props.className.indexOf("".concat(_this3.props.prefixCls, "-root")) !== -1) {
                  if (index > lastVisibleIndex) {
                    item = /*#__PURE__*/external_window_React_["cloneElement"](childNode, // 这里修改 eventKey 是为了防止隐藏状态下还会触发 openkeys 事件
                    {
                      style: {
                        display: 'none'
                      },
                      eventKey: "".concat(childNode.props.eventKey, "-hidden"),
      
                      /**
                       * Legacy code. Here `className` never used:
                       * https://github.com/react-component/menu/commit/4cd6b49fce9d116726f4ea00dda85325d6f26500#diff-e2fa48f75c2dd2318295cde428556a76R240
                       */
                      className: "".concat(MENUITEM_OVERFLOWED_CLASSNAME)
                    });
                  }
      
                  if (index === lastVisibleIndex + 1) {
                    _this3.overflowedItems = children.slice(lastVisibleIndex + 1).map(function (c) {
                      return /*#__PURE__*/external_window_React_["cloneElement"](c, // children[index].key will become '.$key' in clone by default,
                      // we have to overwrite with the correct key explicitly
                      {
                        key: c.props.eventKey,
                        mode: 'vertical-left'
                      });
                    });
                    overflowed = _this3.getOverflowedSubMenuItem(childNode.props.eventKey, _this3.overflowedItems);
                  }
                }
      
                var ret = [].concat(Object(toConsumableArray["a" /* default */])(acc), [overflowed, item]);
      
                if (index === children.length - 1) {
                  // need a placeholder for calculating overflowed indicator width
                  ret.push(_this3.getOverflowedSubMenuItem(childNode.props.eventKey, [], true));
                }
      
                return ret;
              }
      
              return [].concat(Object(toConsumableArray["a" /* default */])(acc), [item]);
            }, []);
          }
        }, {
          key: "render",
          value: function render() {
            var _this$props2 = this.props,
                visible = _this$props2.visible,
                prefixCls = _this$props2.prefixCls,
                overflowedIndicator = _this$props2.overflowedIndicator,
                mode = _this$props2.mode,
                level = _this$props2.level,
                tag = _this$props2.tag,
                children = _this$props2.children,
                theme = _this$props2.theme,
                rest = Object(objectWithoutProperties["a" /* default */])(_this$props2, ["visible", "prefixCls", "overflowedIndicator", "mode", "level", "tag", "children", "theme"]);
      
            var Tag = tag;
            return /*#__PURE__*/external_window_React_["createElement"](Tag, Object(esm_extends["a" /* default */])({
              ref: this.childRef
            }, rest), this.renderChildren(children));
          }
        }]);
      
        return DOMWrap;
      }(external_window_React_["Component"]);
      
      DOMWrap_DOMWrap.defaultProps = {
        tag: 'div',
        className: ''
      };
      /* harmony default export */ var es_DOMWrap = (DOMWrap_DOMWrap);
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-menu/es/SubPopupMenu.js
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      function allDisabled(arr) {
        if (!arr.length) {
          return true;
        }
      
        return arr.every(function (c) {
          return !!c.props.disabled;
        });
      }
      
      function updateActiveKey(store, menuId, activeKey) {
        var state = store.getState();
        store.setState({
          activeKey: Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, state.activeKey), {}, Object(defineProperty["a" /* default */])({}, menuId, activeKey))
        });
      }
      
      function getEventKey(props) {
        // when eventKey not available ,it's menu and return menu id '0-menu-'
        return props.eventKey || '0-menu-';
      }
      
      function getActiveKey(props, originalActiveKey) {
        var activeKey = originalActiveKey;
        var children = props.children,
            eventKey = props.eventKey;
      
        if (activeKey) {
          var found;
          loopMenuItem(children, function (c, i) {
            if (c && c.props && !c.props.disabled && activeKey === getKeyFromChildrenIndex(c, eventKey, i)) {
              found = true;
            }
          });
      
          if (found) {
            return activeKey;
          }
        }
      
        activeKey = null;
      
        if (props.defaultActiveFirst) {
          loopMenuItem(children, function (c, i) {
            if (!activeKey && c && !c.props.disabled) {
              activeKey = getKeyFromChildrenIndex(c, eventKey, i);
            }
          });
          return activeKey;
        }
      
        return activeKey;
      }
      function saveRef(c) {
        if (!c) {
          return;
        }
        /* eslint-disable @typescript-eslint/no-invalid-this */
      
      
        var index = this.instanceArray.indexOf(c);
      
        if (index !== -1) {
          // update component if it's already inside instanceArray
          this.instanceArray[index] = c;
        } else {
          // add component if it's not in instanceArray yet;
          this.instanceArray.push(c);
        }
        /* eslint-enable @typescript-eslint/no-invalid-this */
      
      }
      var SubPopupMenu_SubPopupMenu = /*#__PURE__*/function (_React$Component) {
        Object(inherits["a" /* default */])(SubPopupMenu, _React$Component);
      
        var _super = Object(createSuper["a" /* default */])(SubPopupMenu);
      
        function SubPopupMenu(props) {
          var _this;
      
          Object(classCallCheck["a" /* default */])(this, SubPopupMenu);
      
          _this = _super.call(this, props);
          /**
           * all keyboard events callbacks run from here at first
           *
           * note:
           *  This legacy code that `onKeyDown` is called by parent instead of dom self.
           *  which need return code to check if this event is handled
           */
      
          _this.onKeyDown = function (e, callback) {
            var keyCode = e.keyCode;
            var handled;
      
            _this.getFlatInstanceArray().forEach(function (obj) {
              if (obj && obj.props.active && obj.onKeyDown) {
                handled = obj.onKeyDown(e);
              }
            });
      
            if (handled) {
              return 1;
            }
      
            var activeItem = null;
      
            if (keyCode === KeyCode["a" /* default */].UP || keyCode === KeyCode["a" /* default */].DOWN) {
              activeItem = _this.step(keyCode === KeyCode["a" /* default */].UP ? -1 : 1);
            }
      
            if (activeItem) {
              e.preventDefault();
              updateActiveKey(_this.props.store, getEventKey(_this.props), activeItem.props.eventKey);
      
              if (typeof callback === 'function') {
                callback(activeItem);
              }
      
              return 1;
            }
      
            return undefined;
          };
      
          _this.onItemHover = function (e) {
            var key = e.key,
                hover = e.hover;
            updateActiveKey(_this.props.store, getEventKey(_this.props), hover ? key : null);
          };
      
          _this.onDeselect = function (selectInfo) {
            _this.props.onDeselect(selectInfo);
          };
      
          _this.onSelect = function (selectInfo) {
            _this.props.onSelect(selectInfo);
          };
      
          _this.onClick = function (e) {
            _this.props.onClick(e);
          };
      
          _this.onOpenChange = function (e) {
            _this.props.onOpenChange(e);
          };
      
          _this.onDestroy = function (key) {
            /* istanbul ignore next */
            _this.props.onDestroy(key);
          };
      
          _this.getFlatInstanceArray = function () {
            return _this.instanceArray;
          };
      
          _this.step = function (direction) {
            var children = _this.getFlatInstanceArray();
      
            var activeKey = _this.props.store.getState().activeKey[getEventKey(_this.props)];
      
            var len = children.length;
      
            if (!len) {
              return null;
            }
      
            if (direction < 0) {
              children = children.concat().reverse();
            } // find current activeIndex
      
      
            var activeIndex = -1;
            children.every(function (c, ci) {
              if (c && c.props.eventKey === activeKey) {
                activeIndex = ci;
                return false;
              }
      
              return true;
            });
      
            if (!_this.props.defaultActiveFirst && activeIndex !== -1 && allDisabled(children.slice(activeIndex, len - 1))) {
              return undefined;
            }
      
            var start = (activeIndex + 1) % len;
            var i = start;
      
            do {
              var child = children[i];
      
              if (!child || child.props.disabled) {
                i = (i + 1) % len;
              } else {
                return child;
              }
            } while (i !== start);
      
            return null;
          };
      
          _this.renderCommonMenuItem = function (child, i, extraProps) {
            var state = _this.props.store.getState();
      
            var _assertThisInitialize = Object(assertThisInitialized["a" /* default */])(_this),
                props = _assertThisInitialize.props;
      
            var key = getKeyFromChildrenIndex(child, props.eventKey, i);
            var childProps = child.props; // https://github.com/ant-design/ant-design/issues/11517#issuecomment-477403055
      
            if (!childProps || typeof child.type === 'string') {
              return child;
            }
      
            var isActive = key === state.activeKey;
      
            var newChildProps = Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({
              mode: childProps.mode || props.mode,
              level: props.level,
              inlineIndent: props.inlineIndent,
              renderMenuItem: _this.renderMenuItem,
              rootPrefixCls: props.prefixCls,
              index: i,
              parentMenu: props.parentMenu,
              // customized ref function, need to be invoked manually in child's componentDidMount
              manualRef: childProps.disabled ? undefined : Object(createChainedFunction["a" /* default */])(child.ref, saveRef.bind(Object(assertThisInitialized["a" /* default */])(_this))),
              eventKey: key,
              active: !childProps.disabled && isActive,
              multiple: props.multiple,
              onClick: function onClick(e) {
                (childProps.onClick || noop)(e);
      
                _this.onClick(e);
              },
              onItemHover: _this.onItemHover,
              motion: props.motion,
              subMenuOpenDelay: props.subMenuOpenDelay,
              subMenuCloseDelay: props.subMenuCloseDelay,
              forceSubMenuRender: props.forceSubMenuRender,
              onOpenChange: _this.onOpenChange,
              onDeselect: _this.onDeselect,
              onSelect: _this.onSelect,
              builtinPlacements: props.builtinPlacements,
              itemIcon: childProps.itemIcon || _this.props.itemIcon,
              expandIcon: childProps.expandIcon || _this.props.expandIcon
            }, extraProps), {}, {
              direction: props.direction
            }); // ref: https://github.com/ant-design/ant-design/issues/13943
      
      
            if (props.mode === 'inline' || util_isMobileDevice()) {
              newChildProps.triggerSubMenuAction = 'click';
            }
      
            return /*#__PURE__*/external_window_React_["cloneElement"](child, Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, newChildProps), {}, {
              key: key || i
            }));
          };
      
          _this.renderMenuItem = function (c, i, subMenuKey) {
            /* istanbul ignore if */
            if (!c) {
              return null;
            }
      
            var state = _this.props.store.getState();
      
            var extraProps = {
              openKeys: state.openKeys,
              selectedKeys: state.selectedKeys,
              triggerSubMenuAction: _this.props.triggerSubMenuAction,
              subMenuKey: subMenuKey
            };
            return _this.renderCommonMenuItem(c, i, extraProps);
          };
      
          props.store.setState({
            activeKey: Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, props.store.getState().activeKey), {}, Object(defineProperty["a" /* default */])({}, props.eventKey, getActiveKey(props, props.activeKey)))
          });
          _this.instanceArray = [];
          return _this;
        }
      
        Object(createClass["a" /* default */])(SubPopupMenu, [{
          key: "componentDidMount",
          value: function componentDidMount() {
            // invoke customized ref to expose component to mixin
            if (this.props.manualRef) {
              this.props.manualRef(this);
            }
          }
        }, {
          key: "shouldComponentUpdate",
          value: function shouldComponentUpdate(nextProps) {
            return this.props.visible || nextProps.visible || this.props.className !== nextProps.className || !shallowequal_default()(this.props.style, nextProps.style);
          }
        }, {
          key: "componentDidUpdate",
          value: function componentDidUpdate(prevProps) {
            var props = this.props;
            var originalActiveKey = 'activeKey' in props ? props.activeKey : props.store.getState().activeKey[getEventKey(props)];
            var activeKey = getActiveKey(props, originalActiveKey);
      
            if (activeKey !== originalActiveKey) {
              updateActiveKey(props.store, getEventKey(props), activeKey);
            } else if ('activeKey' in prevProps) {
              // If prev activeKey is not same as current activeKey,
              // we should set it.
              var prevActiveKey = getActiveKey(prevProps, prevProps.activeKey);
      
              if (activeKey !== prevActiveKey) {
                updateActiveKey(props.store, getEventKey(props), activeKey);
              }
            }
          }
        }, {
          key: "render",
          value: function render() {
            var _this2 = this;
      
            var props = Object(esm_extends["a" /* default */])({}, this.props);
      
            this.instanceArray = [];
            var className = classnames_default()(props.prefixCls, props.className, "".concat(props.prefixCls, "-").concat(props.mode));
            var domProps = {
              className: className,
              // role could be 'select' and by default set to menu
              role: props.role || 'menu'
            };
      
            if (props.id) {
              domProps.id = props.id;
            }
      
            if (props.focusable) {
              domProps.tabIndex = 0;
              domProps.onKeyDown = this.onKeyDown;
            }
      
            var prefixCls = props.prefixCls,
                eventKey = props.eventKey,
                visible = props.visible,
                level = props.level,
                mode = props.mode,
                overflowedIndicator = props.overflowedIndicator,
                theme = props.theme;
            menuAllProps.forEach(function (key) {
              return delete props[key];
            }); // Otherwise, the propagated click event will trigger another onClick
      
            delete props.onClick;
            return /*#__PURE__*/external_window_React_["createElement"](es_DOMWrap, Object(esm_extends["a" /* default */])({}, props, {
              prefixCls: prefixCls,
              mode: mode,
              tag: "ul",
              level: level,
              theme: theme,
              visible: visible,
              overflowedIndicator: overflowedIndicator
            }, domProps), Object(toArray["a" /* default */])(props.children).map(function (c, i) {
              return _this2.renderMenuItem(c, i, eventKey || '0-menu-');
            }));
          }
        }]);
      
        return SubPopupMenu;
      }(external_window_React_["Component"]);
      SubPopupMenu_SubPopupMenu.defaultProps = {
        prefixCls: 'rc-menu',
        className: '',
        mode: 'vertical',
        level: 1,
        inlineIndent: 24,
        visible: true,
        focusable: true,
        style: {},
        manualRef: noop
      };
      var SubPopupMenu_connected = Object(esm["b" /* connect */])()(SubPopupMenu_SubPopupMenu);
      /* harmony default export */ var es_SubPopupMenu = (SubPopupMenu_connected);
      // EXTERNAL MODULE: ./node_modules/rc-util/es/warning.js
      var warning = __webpack_require__("Kwbf");
      
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-menu/es/utils/legacyUtil.js
      
      
      function legacyUtil_getMotion(_ref, _ref2, menuMode) {
        var prefixCls = _ref.prefixCls,
            motion = _ref.motion,
            _ref$defaultMotions = _ref.defaultMotions,
            defaultMotions = _ref$defaultMotions === void 0 ? {} : _ref$defaultMotions,
            openAnimation = _ref.openAnimation,
            openTransitionName = _ref.openTransitionName;
        var switchingModeFromInline = _ref2.switchingModeFromInline;
      
        if (motion) {
          return motion;
        }
      
        if (Object(esm_typeof["a" /* default */])(openAnimation) === 'object' && openAnimation) {
          Object(warning["a" /* default */])(false, 'Object type of `openAnimation` is removed. Please use `motion` instead.');
        } else if (typeof openAnimation === 'string') {
          return {
            motionName: "".concat(prefixCls, "-open-").concat(openAnimation)
          };
        }
      
        if (openTransitionName) {
          return {
            motionName: openTransitionName
          };
        } // Default logic
      
      
        var defaultMotion = defaultMotions[menuMode];
      
        if (defaultMotion) {
          return defaultMotion;
        } // When mode switch from inline
        // submenu should hide without animation
      
      
        return switchingModeFromInline ? null : defaultMotions.other;
      }
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-menu/es/Menu.js
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      var Menu_Menu = /*#__PURE__*/function (_React$Component) {
        Object(inherits["a" /* default */])(Menu, _React$Component);
      
        var _super = Object(createSuper["a" /* default */])(Menu);
      
        function Menu(props) {
          var _this;
      
          Object(classCallCheck["a" /* default */])(this, Menu);
      
          _this = _super.call(this, props);
      
          _this.onSelect = function (selectInfo) {
            var _assertThisInitialize = Object(assertThisInitialized["a" /* default */])(_this),
                props = _assertThisInitialize.props;
      
            if (props.selectable) {
              // root menu
              var _this$store$getState = _this.store.getState(),
                  _selectedKeys = _this$store$getState.selectedKeys;
      
              var selectedKey = selectInfo.key;
      
              if (props.multiple) {
                _selectedKeys = _selectedKeys.concat([selectedKey]);
              } else {
                _selectedKeys = [selectedKey];
              }
      
              if (!('selectedKeys' in props)) {
                _this.store.setState({
                  selectedKeys: _selectedKeys
                });
              }
      
              props.onSelect(Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, selectInfo), {}, {
                selectedKeys: _selectedKeys
              }));
            }
          };
      
          _this.onClick = function (e) {
            var mode = _this.getRealMenuMode();
      
            var _assertThisInitialize2 = Object(assertThisInitialized["a" /* default */])(_this),
                store = _assertThisInitialize2.store,
                onOpenChange = _assertThisInitialize2.props.onOpenChange;
      
            if (mode !== 'inline' && !('openKeys' in _this.props)) {
              // closing vertical popup submenu after click it
              store.setState({
                openKeys: []
              });
              onOpenChange([]);
            }
      
            _this.props.onClick(e);
          }; // onKeyDown needs to be exposed as a instance method
          // e.g., in rc-select, we need to navigate menu item while
          // current active item is rc-select input box rather than the menu itself
      
      
          _this.onKeyDown = function (e, callback) {
            _this.innerMenu.getWrappedInstance().onKeyDown(e, callback);
          };
      
          _this.onOpenChange = function (event) {
            var _assertThisInitialize3 = Object(assertThisInitialized["a" /* default */])(_this),
                props = _assertThisInitialize3.props;
      
            var openKeys = _this.store.getState().openKeys.concat();
      
            var changed = false;
      
            var processSingle = function processSingle(e) {
              var oneChanged = false;
      
              if (e.open) {
                oneChanged = openKeys.indexOf(e.key) === -1;
      
                if (oneChanged) {
                  openKeys.push(e.key);
                }
              } else {
                var index = openKeys.indexOf(e.key);
                oneChanged = index !== -1;
      
                if (oneChanged) {
                  openKeys.splice(index, 1);
                }
              }
      
              changed = changed || oneChanged;
            };
      
            if (Array.isArray(event)) {
              // batch change call
              event.forEach(processSingle);
            } else {
              processSingle(event);
            }
      
            if (changed) {
              if (!('openKeys' in _this.props)) {
                _this.store.setState({
                  openKeys: openKeys
                });
              }
      
              props.onOpenChange(openKeys);
            }
          };
      
          _this.onDeselect = function (selectInfo) {
            var _assertThisInitialize4 = Object(assertThisInitialized["a" /* default */])(_this),
                props = _assertThisInitialize4.props;
      
            if (props.selectable) {
              var _selectedKeys2 = _this.store.getState().selectedKeys.concat();
      
              var selectedKey = selectInfo.key;
      
              var index = _selectedKeys2.indexOf(selectedKey);
      
              if (index !== -1) {
                _selectedKeys2.splice(index, 1);
              }
      
              if (!('selectedKeys' in props)) {
                _this.store.setState({
                  selectedKeys: _selectedKeys2
                });
              }
      
              props.onDeselect(Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, selectInfo), {}, {
                selectedKeys: _selectedKeys2
              }));
            }
          }; // Restore vertical mode when menu is collapsed responsively when mounted
          // https://github.com/ant-design/ant-design/issues/13104
          // TODO: not a perfect solution,
          // looking a new way to avoid setting switchingModeFromInline in this situation
      
      
          _this.onMouseEnter = function (e) {
            _this.restoreModeVerticalFromInline();
      
            var onMouseEnter = _this.props.onMouseEnter;
      
            if (onMouseEnter) {
              onMouseEnter(e);
            }
          };
      
          _this.onTransitionEnd = function (e) {
            // when inlineCollapsed menu width animation finished
            // https://github.com/ant-design/ant-design/issues/12864
            var widthCollapsed = e.propertyName === 'width' && e.target === e.currentTarget; // Fix SVGElement e.target.className.indexOf is not a function
            // https://github.com/ant-design/ant-design/issues/15699
      
            var className = e.target.className; // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal,
            // unless during an animation.
      
            var classNameValue = Object.prototype.toString.call(className) === '[object SVGAnimatedString]' ? className.animVal : className; // Fix for <Menu style={{ width: '100%' }} />,
            // the width transition won't trigger when menu is collapsed
            // https://github.com/ant-design/ant-design-pro/issues/2783
      
            var iconScaled = e.propertyName === 'font-size' && classNameValue.indexOf('anticon') >= 0;
      
            if (widthCollapsed || iconScaled) {
              _this.restoreModeVerticalFromInline();
            }
          };
      
          _this.setInnerMenu = function (node) {
            _this.innerMenu = node;
          };
      
          _this.isRootMenu = true;
          var selectedKeys = props.defaultSelectedKeys;
          var openKeys = props.defaultOpenKeys;
      
          if ('selectedKeys' in props) {
            selectedKeys = props.selectedKeys || [];
          }
      
          if ('openKeys' in props) {
            openKeys = props.openKeys || [];
          }
      
          _this.store = Object(esm["c" /* create */])({
            selectedKeys: selectedKeys,
            openKeys: openKeys,
            activeKey: {
              '0-menu-': getActiveKey(props, props.activeKey)
            }
          });
          _this.state = {
            switchingModeFromInline: false,
            prevProps: props,
            inlineOpenKeys: [],
            store: _this.store
          };
          return _this;
        }
      
        Object(createClass["a" /* default */])(Menu, [{
          key: "componentDidMount",
          value: function componentDidMount() {
            this.updateMiniStore();
            this.updateMenuDisplay();
          }
        }, {
          key: "componentDidUpdate",
          value: function componentDidUpdate(prevProps) {
            var _this$props = this.props,
                siderCollapsed = _this$props.siderCollapsed,
                inlineCollapsed = _this$props.inlineCollapsed,
                onOpenChange = _this$props.onOpenChange;
      
            if (!prevProps.inlineCollapsed && inlineCollapsed || !prevProps.siderCollapsed && siderCollapsed) {
              onOpenChange([]);
            }
      
            this.updateMiniStore();
            this.updateMenuDisplay();
          }
        }, {
          key: "updateMenuDisplay",
          value: function updateMenuDisplay() {
            var collapsedWidth = this.props.collapsedWidth,
                store = this.store,
                prevOpenKeys = this.prevOpenKeys; // https://github.com/ant-design/ant-design/issues/8587
      
            var hideMenu = this.getInlineCollapsed() && (collapsedWidth === 0 || collapsedWidth === '0' || collapsedWidth === '0px');
      
            if (hideMenu) {
              this.prevOpenKeys = store.getState().openKeys.concat();
              this.store.setState({
                openKeys: []
              });
            } else if (prevOpenKeys) {
              this.store.setState({
                openKeys: prevOpenKeys
              });
              this.prevOpenKeys = null;
            }
          }
        }, {
          key: "getRealMenuMode",
          value: function getRealMenuMode() {
            var mode = this.props.mode;
            var switchingModeFromInline = this.state.switchingModeFromInline;
            var inlineCollapsed = this.getInlineCollapsed();
      
            if (switchingModeFromInline && inlineCollapsed) {
              return 'inline';
            }
      
            return inlineCollapsed ? 'vertical' : mode;
          }
        }, {
          key: "getInlineCollapsed",
          value: function getInlineCollapsed() {
            var _this$props2 = this.props,
                inlineCollapsed = _this$props2.inlineCollapsed,
                siderCollapsed = _this$props2.siderCollapsed;
      
            if (siderCollapsed !== undefined) {
              return siderCollapsed;
            }
      
            return inlineCollapsed;
          }
        }, {
          key: "restoreModeVerticalFromInline",
          value: function restoreModeVerticalFromInline() {
            var switchingModeFromInline = this.state.switchingModeFromInline;
      
            if (switchingModeFromInline) {
              this.setState({
                switchingModeFromInline: false
              });
            }
          }
        }, {
          key: "updateMiniStore",
          value: function updateMiniStore() {
            if ('selectedKeys' in this.props) {
              this.store.setState({
                selectedKeys: this.props.selectedKeys || []
              });
            }
      
            if ('openKeys' in this.props) {
              this.store.setState({
                openKeys: this.props.openKeys || []
              });
            }
          }
        }, {
          key: "render",
          value: function render() {
            var props = Object(objectSpread2["a" /* default */])({}, Object(omit["a" /* default */])(this.props, ['collapsedWidth', 'siderCollapsed', 'defaultMotions']));
      
            var mode = this.getRealMenuMode();
            props.className += " ".concat(props.prefixCls, "-root");
      
            if (props.direction === 'rtl') {
              props.className += " ".concat(props.prefixCls, "-rtl");
            }
      
            props = Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, props), {}, {
              mode: mode,
              onClick: this.onClick,
              onOpenChange: this.onOpenChange,
              onDeselect: this.onDeselect,
              onSelect: this.onSelect,
              onMouseEnter: this.onMouseEnter,
              onTransitionEnd: this.onTransitionEnd,
              parentMenu: this,
              motion: legacyUtil_getMotion(this.props, this.state, mode)
            });
            delete props.openAnimation;
            delete props.openTransitionName;
            return /*#__PURE__*/external_window_React_["createElement"](esm["a" /* Provider */], {
              store: this.store
            }, /*#__PURE__*/external_window_React_["createElement"](es_SubPopupMenu, Object(esm_extends["a" /* default */])({}, props, {
              ref: this.setInnerMenu
            }), this.props.children));
          }
        }], [{
          key: "getDerivedStateFromProps",
          value: function getDerivedStateFromProps(nextProps, prevState) {
            var prevProps = prevState.prevProps,
                store = prevState.store;
            var prevStoreState = store.getState();
            var newStoreState = {};
            var newState = {
              prevProps: nextProps
            };
      
            if (prevProps.mode === 'inline' && nextProps.mode !== 'inline') {
              newState.switchingModeFromInline = true;
            }
      
            if ('openKeys' in nextProps) {
              newStoreState.openKeys = nextProps.openKeys || [];
            } else {
              // [Legacy] Old code will return after `openKeys` changed.
              // Not sure the reason, we should keep this logic still.
              if (nextProps.inlineCollapsed && !prevProps.inlineCollapsed || nextProps.siderCollapsed && !prevProps.siderCollapsed) {
                newState.switchingModeFromInline = true;
                newState.inlineOpenKeys = prevStoreState.openKeys;
                newStoreState.openKeys = [];
              }
      
              if (!nextProps.inlineCollapsed && prevProps.inlineCollapsed || !nextProps.siderCollapsed && prevProps.siderCollapsed) {
                newStoreState.openKeys = prevState.inlineOpenKeys;
                newState.inlineOpenKeys = [];
              }
            }
      
            if (Object.keys(newStoreState).length) {
              store.setState(newStoreState);
            }
      
            return newState;
          }
        }]);
      
        return Menu;
      }(external_window_React_["Component"]);
      
      Menu_Menu.defaultProps = {
        selectable: true,
        onClick: noop,
        onSelect: noop,
        onOpenChange: noop,
        onDeselect: noop,
        defaultSelectedKeys: [],
        defaultOpenKeys: [],
        subMenuOpenDelay: 0.1,
        subMenuCloseDelay: 0.1,
        triggerSubMenuAction: 'hover',
        prefixCls: 'rc-menu',
        className: '',
        mode: 'vertical',
        style: {},
        builtinPlacements: {},
        overflowedIndicator: /*#__PURE__*/external_window_React_["createElement"]("span", null, "\xB7\xB7\xB7")
      };
      /* harmony default export */ var es_Menu = (Menu_Menu);
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-menu/es/MenuItem.js
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      var MenuItem_MenuItem = /*#__PURE__*/function (_React$Component) {
        Object(inherits["a" /* default */])(MenuItem, _React$Component);
      
        var _super = Object(createSuper["a" /* default */])(MenuItem);
      
        function MenuItem() {
          var _this;
      
          Object(classCallCheck["a" /* default */])(this, MenuItem);
      
          _this = _super.apply(this, arguments);
      
          _this.onKeyDown = function (e) {
            var keyCode = e.keyCode;
      
            if (keyCode === KeyCode["a" /* default */].ENTER) {
              _this.onClick(e);
      
              return true;
            }
      
            return undefined;
          };
      
          _this.onMouseLeave = function (e) {
            var _this$props = _this.props,
                eventKey = _this$props.eventKey,
                onItemHover = _this$props.onItemHover,
                onMouseLeave = _this$props.onMouseLeave;
            onItemHover({
              key: eventKey,
              hover: false
            });
            onMouseLeave({
              key: eventKey,
              domEvent: e
            });
          };
      
          _this.onMouseEnter = function (e) {
            var _this$props2 = _this.props,
                eventKey = _this$props2.eventKey,
                onItemHover = _this$props2.onItemHover,
                onMouseEnter = _this$props2.onMouseEnter;
            onItemHover({
              key: eventKey,
              hover: true
            });
            onMouseEnter({
              key: eventKey,
              domEvent: e
            });
          };
      
          _this.onClick = function (e) {
            var _this$props3 = _this.props,
                eventKey = _this$props3.eventKey,
                multiple = _this$props3.multiple,
                onClick = _this$props3.onClick,
                onSelect = _this$props3.onSelect,
                onDeselect = _this$props3.onDeselect,
                isSelected = _this$props3.isSelected;
            var info = {
              key: eventKey,
              keyPath: [eventKey],
              item: Object(assertThisInitialized["a" /* default */])(_this),
              domEvent: e
            };
            onClick(info);
      
            if (multiple) {
              if (isSelected) {
                onDeselect(info);
              } else {
                onSelect(info);
              }
            } else if (!isSelected) {
              onSelect(info);
            }
          };
      
          _this.saveNode = function (node) {
            _this.node = node;
          };
      
          return _this;
        }
      
        Object(createClass["a" /* default */])(MenuItem, [{
          key: "componentDidMount",
          value: function componentDidMount() {
            // invoke customized ref to expose component to mixin
            this.callRef();
          }
        }, {
          key: "componentDidUpdate",
          value: function componentDidUpdate() {
            this.callRef();
          }
        }, {
          key: "componentWillUnmount",
          value: function componentWillUnmount() {
            var props = this.props;
      
            if (props.onDestroy) {
              props.onDestroy(props.eventKey);
            }
          }
        }, {
          key: "getPrefixCls",
          value: function getPrefixCls() {
            return "".concat(this.props.rootPrefixCls, "-item");
          }
        }, {
          key: "getActiveClassName",
          value: function getActiveClassName() {
            return "".concat(this.getPrefixCls(), "-active");
          }
        }, {
          key: "getSelectedClassName",
          value: function getSelectedClassName() {
            return "".concat(this.getPrefixCls(), "-selected");
          }
        }, {
          key: "getDisabledClassName",
          value: function getDisabledClassName() {
            return "".concat(this.getPrefixCls(), "-disabled");
          }
        }, {
          key: "callRef",
          value: function callRef() {
            if (this.props.manualRef) {
              this.props.manualRef(this);
            }
          }
        }, {
          key: "render",
          value: function render() {
            var _classNames;
      
            var props = Object(objectSpread2["a" /* default */])({}, this.props);
      
            var className = classnames_default()(this.getPrefixCls(), props.className, (_classNames = {}, Object(defineProperty["a" /* default */])(_classNames, this.getActiveClassName(), !props.disabled && props.active), Object(defineProperty["a" /* default */])(_classNames, this.getSelectedClassName(), props.isSelected), Object(defineProperty["a" /* default */])(_classNames, this.getDisabledClassName(), props.disabled), _classNames));
      
            var attrs = Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, props.attribute), {}, {
              title: typeof props.title === 'string' ? props.title : undefined,
              className: className,
              // set to menuitem by default
              role: props.role || 'menuitem',
              'aria-disabled': props.disabled
            });
      
            if (props.role === 'option') {
              // overwrite to option
              attrs = Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, attrs), {}, {
                role: 'option',
                'aria-selected': props.isSelected
              });
            } else if (props.role === null || props.role === 'none') {
              // sometimes we want to specify role inside <li/> element
              // <li><a role='menuitem'>Link</a></li> would be a good example
              // in this case the role on <li/> should be "none" to
              // remove the implied listitem role.
              // https://www.w3.org/TR/wai-aria-practices-1.1/examples/menubar/menubar-1/menubar-1.html
              attrs.role = 'none';
            } // In case that onClick/onMouseLeave/onMouseEnter is passed down from owner
      
      
            var mouseEvent = {
              onClick: props.disabled ? null : this.onClick,
              onMouseLeave: props.disabled ? null : this.onMouseLeave,
              onMouseEnter: props.disabled ? null : this.onMouseEnter
            };
      
            var style = Object(objectSpread2["a" /* default */])({}, props.style);
      
            if (props.mode === 'inline') {
              if (props.direction === 'rtl') {
                style.paddingRight = props.inlineIndent * props.level;
              } else {
                style.paddingLeft = props.inlineIndent * props.level;
              }
            }
      
            menuAllProps.forEach(function (key) {
              return delete props[key];
            });
            delete props.direction;
            var icon = this.props.itemIcon;
      
            if (typeof this.props.itemIcon === 'function') {
              // TODO: This is a bug which should fixed after TS refactor
              icon = /*#__PURE__*/external_window_React_["createElement"](this.props.itemIcon, this.props);
            }
      
            return /*#__PURE__*/external_window_React_["createElement"]("li", Object(esm_extends["a" /* default */])({}, Object(omit["a" /* default */])(props, ['onClick', 'onMouseEnter', 'onMouseLeave', 'onSelect']), attrs, mouseEvent, {
              style: style,
              ref: this.saveNode
            }), props.children, icon);
          }
        }]);
      
        return MenuItem;
      }(external_window_React_["Component"]);
      MenuItem_MenuItem.isMenuItem = true;
      MenuItem_MenuItem.defaultProps = {
        onSelect: noop,
        onMouseEnter: noop,
        onMouseLeave: noop,
        manualRef: noop
      };
      var MenuItem_connected = Object(esm["b" /* connect */])(function (_ref, _ref2) {
        var activeKey = _ref.activeKey,
            selectedKeys = _ref.selectedKeys;
        var eventKey = _ref2.eventKey,
            subMenuKey = _ref2.subMenuKey;
        return {
          active: activeKey[subMenuKey] === eventKey,
          // selectedKeys should be array in any circumstance
          // when it is not, we have fallback logic for https://github.com/ant-design/ant-design/issues/29430
          isSelected: Array.isArray(selectedKeys) ? selectedKeys.indexOf(eventKey) !== -1 : selectedKeys === eventKey
        };
      })(MenuItem_MenuItem);
      /* harmony default export */ var es_MenuItem = (MenuItem_connected);
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-menu/es/MenuItemGroup.js
      
      
      
      
      
      
      
      
      var MenuItemGroup_MenuItemGroup = /*#__PURE__*/function (_React$Component) {
        Object(inherits["a" /* default */])(MenuItemGroup, _React$Component);
      
        var _super = Object(createSuper["a" /* default */])(MenuItemGroup);
      
        function MenuItemGroup() {
          var _this;
      
          Object(classCallCheck["a" /* default */])(this, MenuItemGroup);
      
          _this = _super.apply(this, arguments);
      
          _this.renderInnerMenuItem = function (item) {
            var _this$props = _this.props,
                renderMenuItem = _this$props.renderMenuItem,
                index = _this$props.index;
            return renderMenuItem(item, index, _this.props.subMenuKey);
          };
      
          return _this;
        }
      
        Object(createClass["a" /* default */])(MenuItemGroup, [{
          key: "render",
          value: function render() {
            var props = Object(esm_extends["a" /* default */])({}, this.props);
      
            var _props$className = props.className,
                className = _props$className === void 0 ? '' : _props$className,
                rootPrefixCls = props.rootPrefixCls;
            var titleClassName = "".concat(rootPrefixCls, "-item-group-title");
            var listClassName = "".concat(rootPrefixCls, "-item-group-list");
            var title = props.title,
                children = props.children;
            menuAllProps.forEach(function (key) {
              return delete props[key];
            });
            delete props.direction;
            return /*#__PURE__*/external_window_React_["createElement"]("li", Object(esm_extends["a" /* default */])({}, props, {
              onClick: function onClick(e) {
                return e.stopPropagation();
              },
              className: "".concat(className, " ").concat(rootPrefixCls, "-item-group")
            }), /*#__PURE__*/external_window_React_["createElement"]("div", {
              className: titleClassName,
              title: typeof title === 'string' ? title : undefined
            }, title), /*#__PURE__*/external_window_React_["createElement"]("ul", {
              className: listClassName
            }, external_window_React_["Children"].map(children, this.renderInnerMenuItem)));
          }
        }]);
      
        return MenuItemGroup;
      }(external_window_React_["Component"]);
      
      MenuItemGroup_MenuItemGroup.isMenuItemGroup = true;
      MenuItemGroup_MenuItemGroup.defaultProps = {
        disabled: true
      };
      /* harmony default export */ var es_MenuItemGroup = (MenuItemGroup_MenuItemGroup);
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-menu/es/Divider.js
      
      
      var Divider_Divider = function Divider(_ref) {
        var className = _ref.className,
            rootPrefixCls = _ref.rootPrefixCls,
            style = _ref.style;
        return /*#__PURE__*/external_window_React_["createElement"]("li", {
          className: "".concat(className, " ").concat(rootPrefixCls, "-item-divider"),
          style: style
        });
      };
      
      Divider_Divider.defaultProps = {
        // To fix keyboard UX.
        disabled: true,
        className: '',
        style: {}
      };
      /* harmony default export */ var es_Divider = (Divider_Divider);
      // CONCATENATED MODULE: ./node_modules/rc-tabs/node_modules/rc-menu/es/index.js
      
      
      
      
      
      
      /* harmony default export */ var rc_menu_es = (es_Menu);
      // EXTERNAL MODULE: ./node_modules/rc-dropdown/es/index.js + 2 modules
      var rc_dropdown_es = __webpack_require__("eDIo");
      
      // CONCATENATED MODULE: ./node_modules/rc-tabs/es/TabNavList/AddButton.js
      
      
      function AddButton(_ref, ref) {
        var prefixCls = _ref.prefixCls,
            editable = _ref.editable,
            locale = _ref.locale,
            style = _ref.style;
      
        if (!editable || editable.showAdd === false) {
          return null;
        }
      
        return external_window_React_["createElement"]("button", {
          ref: ref,
          type: "button",
          className: "".concat(prefixCls, "-nav-add"),
          style: style,
          "aria-label": (locale === null || locale === void 0 ? void 0 : locale.addAriaLabel) || 'Add tab',
          onClick: function onClick(event) {
            editable.onEdit('add', {
              event: event
            });
          }
        }, editable.addIcon || '+');
      }
      
      /* harmony default export */ var TabNavList_AddButton = (external_window_React_["forwardRef"](AddButton));
      // CONCATENATED MODULE: ./node_modules/rc-tabs/es/TabNavList/OperationNode.js
      
      
      
      
      
      
      
      
      
      
      function OperationNode(_ref, ref) {
        var prefixCls = _ref.prefixCls,
            id = _ref.id,
            tabs = _ref.tabs,
            locale = _ref.locale,
            mobile = _ref.mobile,
            _ref$moreIcon = _ref.moreIcon,
            moreIcon = _ref$moreIcon === void 0 ? 'More' : _ref$moreIcon,
            moreTransitionName = _ref.moreTransitionName,
            style = _ref.style,
            className = _ref.className,
            editable = _ref.editable,
            tabBarGutter = _ref.tabBarGutter,
            rtl = _ref.rtl,
            onTabClick = _ref.onTabClick;
      
        // ======================== Dropdown ========================
        var _useState = Object(external_window_React_["useState"])(false),
            _useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
            open = _useState2[0],
            setOpen = _useState2[1];
      
        var _useState3 = Object(external_window_React_["useState"])(null),
            _useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
            selectedKey = _useState4[0],
            setSelectedKey = _useState4[1];
      
        var popupId = "".concat(id, "-more-popup");
        var dropdownPrefix = "".concat(prefixCls, "-dropdown");
        var selectedItemId = selectedKey !== null ? "".concat(popupId, "-").concat(selectedKey) : null;
        var dropdownAriaLabel = locale === null || locale === void 0 ? void 0 : locale.dropdownAriaLabel;
        var menu = external_window_React_["createElement"](rc_menu_es, {
          onClick: function onClick(_ref2) {
            var key = _ref2.key,
                domEvent = _ref2.domEvent;
            onTabClick(key, domEvent);
            setOpen(false);
          },
          id: popupId,
          tabIndex: -1,
          role: "listbox",
          "aria-activedescendant": selectedItemId,
          selectedKeys: [selectedKey],
          "aria-label": dropdownAriaLabel !== undefined ? dropdownAriaLabel : 'expanded dropdown'
        }, tabs.map(function (tab) {
          return external_window_React_["createElement"](es_MenuItem, {
            key: tab.key,
            id: "".concat(popupId, "-").concat(tab.key),
            role: "option",
            "aria-controls": id && "".concat(id, "-panel-").concat(tab.key),
            disabled: tab.disabled
          }, tab.tab);
        }));
      
        function selectOffset(offset) {
          var enabledTabs = tabs.filter(function (tab) {
            return !tab.disabled;
          });
          var selectedIndex = enabledTabs.findIndex(function (tab) {
            return tab.key === selectedKey;
          }) || 0;
          var len = enabledTabs.length;
      
          for (var i = 0; i < len; i += 1) {
            selectedIndex = (selectedIndex + offset + len) % len;
            var tab = enabledTabs[selectedIndex];
      
            if (!tab.disabled) {
              setSelectedKey(tab.key);
              return;
            }
          }
        }
      
        function onKeyDown(e) {
          var which = e.which;
      
          if (!open) {
            if ([KeyCode["a" /* default */].DOWN, KeyCode["a" /* default */].SPACE, KeyCode["a" /* default */].ENTER].includes(which)) {
              setOpen(true);
              e.preventDefault();
            }
      
            return;
          }
      
          switch (which) {
            case KeyCode["a" /* default */].UP:
              selectOffset(-1);
              e.preventDefault();
              break;
      
            case KeyCode["a" /* default */].DOWN:
              selectOffset(1);
              e.preventDefault();
              break;
      
            case KeyCode["a" /* default */].ESC:
              setOpen(false);
              break;
      
            case KeyCode["a" /* default */].SPACE:
            case KeyCode["a" /* default */].ENTER:
              if (selectedKey !== null) onTabClick(selectedKey, e);
              break;
          }
        } // ========================= Effect =========================
      
      
        Object(external_window_React_["useEffect"])(function () {
          // We use query element here to avoid React strict warning
          var ele = document.getElementById(selectedItemId);
      
          if (ele && ele.scrollIntoView) {
            ele.scrollIntoView(false);
          }
        }, [selectedKey]);
        Object(external_window_React_["useEffect"])(function () {
          if (!open) {
            setSelectedKey(null);
          }
        }, [open]); // ========================= Render =========================
      
        var moreStyle = Object(defineProperty["a" /* default */])({}, rtl ? 'marginLeft' : 'marginRight', tabBarGutter);
      
        if (!tabs.length) {
          moreStyle.visibility = 'hidden';
          moreStyle.order = 1;
        }
      
        var overlayClassName = classnames_default()(Object(defineProperty["a" /* default */])({}, "".concat(dropdownPrefix, "-rtl"), rtl));
        var moreNode = mobile ? null : external_window_React_["createElement"](rc_dropdown_es["a" /* default */], {
          prefixCls: dropdownPrefix,
          overlay: menu,
          trigger: ['hover'],
          visible: open,
          transitionName: moreTransitionName,
          onVisibleChange: setOpen,
          overlayClassName: overlayClassName,
          mouseEnterDelay: 0.1,
          mouseLeaveDelay: 0.1
        }, external_window_React_["createElement"]("button", {
          type: "button",
          className: "".concat(prefixCls, "-nav-more"),
          style: moreStyle,
          tabIndex: -1,
          "aria-hidden": "true",
          "aria-haspopup": "listbox",
          "aria-controls": popupId,
          id: "".concat(id, "-more"),
          "aria-expanded": open,
          onKeyDown: onKeyDown
        }, moreIcon));
        return external_window_React_["createElement"]("div", {
          className: classnames_default()("".concat(prefixCls, "-nav-operations"), className),
          style: style,
          ref: ref
        }, moreNode, external_window_React_["createElement"](TabNavList_AddButton, {
          prefixCls: prefixCls,
          locale: locale,
          editable: editable
        }));
      }
      
      /* harmony default export */ var TabNavList_OperationNode = (external_window_React_["forwardRef"](OperationNode));
      // CONCATENATED MODULE: ./node_modules/rc-tabs/es/TabContext.js
      
      /* harmony default export */ var TabContext = (Object(external_window_React_["createContext"])(null));
      // CONCATENATED MODULE: ./node_modules/rc-tabs/es/hooks/useTouchMove.js
      
      
      
      var MIN_SWIPE_DISTANCE = 0.1;
      var STOP_SWIPE_DISTANCE = 0.01;
      var REFRESH_INTERVAL = 20;
      var SPEED_OFF_MULTIPLE = Math.pow(0.995, REFRESH_INTERVAL); // ========================= Check if is a mobile =========================
      
      function useTouchMove_isMobile() {
        var agent = navigator.userAgent || navigator.vendor || window.opera;
      
        if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(agent) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test(agent.substr(0, 4))) {
          return true;
        }
      
        return false;
      } // ================================= Hook =================================
      
      function useTouchMove(ref, onOffset) {
        var _useState = Object(external_window_React_["useState"])(),
            _useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
            touchPosition = _useState2[0],
            setTouchPosition = _useState2[1];
      
        var _useState3 = Object(external_window_React_["useState"])(0),
            _useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
            lastTimestamp = _useState4[0],
            setLastTimestamp = _useState4[1];
      
        var _useState5 = Object(external_window_React_["useState"])(0),
            _useState6 = Object(slicedToArray["a" /* default */])(_useState5, 2),
            lastTimeDiff = _useState6[0],
            setLastTimeDiff = _useState6[1];
      
        var _useState7 = Object(external_window_React_["useState"])(),
            _useState8 = Object(slicedToArray["a" /* default */])(_useState7, 2),
            lastOffset = _useState8[0],
            setLastOffset = _useState8[1];
      
        var motionRef = Object(external_window_React_["useRef"])(); // ========================= Events =========================
        // >>> Touch events
      
        function onTouchStart(e) {
          var _e$touches$ = e.touches[0],
              screenX = _e$touches$.screenX,
              screenY = _e$touches$.screenY;
          setTouchPosition({
            x: screenX,
            y: screenY
          });
          window.clearInterval(motionRef.current);
        }
      
        function onTouchMove(e) {
          if (!touchPosition) return;
          e.preventDefault();
          var _e$touches$2 = e.touches[0],
              screenX = _e$touches$2.screenX,
              screenY = _e$touches$2.screenY;
          setTouchPosition({
            x: screenX,
            y: screenY
          });
          var offsetX = screenX - touchPosition.x;
          var offsetY = screenY - touchPosition.y;
          onOffset(offsetX, offsetY);
          var now = Date.now();
          setLastTimestamp(now);
          setLastTimeDiff(now - lastTimestamp);
          setLastOffset({
            x: offsetX,
            y: offsetY
          });
        }
      
        function onTouchEnd() {
          if (!touchPosition) return;
          setTouchPosition(null);
          setLastOffset(null); // Swipe if needed
      
          if (lastOffset) {
            var distanceX = lastOffset.x / lastTimeDiff;
            var distanceY = lastOffset.y / lastTimeDiff;
            var absX = Math.abs(distanceX);
            var absY = Math.abs(distanceY); // Skip swipe if low distance
      
            if (Math.max(absX, absY) < MIN_SWIPE_DISTANCE) return;
            var currentX = distanceX;
            var currentY = distanceY;
            motionRef.current = window.setInterval(function () {
              if (Math.abs(currentX) < STOP_SWIPE_DISTANCE && Math.abs(currentY) < STOP_SWIPE_DISTANCE) {
                window.clearInterval(motionRef.current);
                return;
              }
      
              currentX *= SPEED_OFF_MULTIPLE;
              currentY *= SPEED_OFF_MULTIPLE;
              onOffset(currentX * REFRESH_INTERVAL, currentY * REFRESH_INTERVAL);
            }, REFRESH_INTERVAL);
          }
        } // >>> Wheel event
      
      
        var lastWheelTimestampRef = Object(external_window_React_["useRef"])(0);
        var lastWheelPreventRef = Object(external_window_React_["useRef"])(false);
        var lastWheelDirectionRef = Object(external_window_React_["useRef"])();
      
        function onWheel(e) {
          var deltaX = e.deltaX,
              deltaY = e.deltaY; // Convert both to x & y since wheel only happened on PC
      
          var mixed = 0;
          var absX = Math.abs(deltaX);
          var absY = Math.abs(deltaY);
      
          if (absX === absY) {
            mixed = lastWheelDirectionRef.current === 'x' ? deltaX : deltaY;
          } else if (absX > absY) {
            mixed = deltaX;
            lastWheelDirectionRef.current = 'x';
          } else {
            mixed = deltaY;
            lastWheelDirectionRef.current = 'y';
          } // Optimize mac touch scroll
      
      
          var now = Date.now();
      
          if (now - lastWheelTimestampRef.current > 100) {
            lastWheelPreventRef.current = false;
          }
      
          if (onOffset(-mixed, -mixed) || lastWheelPreventRef.current) {
            e.preventDefault();
            lastWheelPreventRef.current = true;
          }
      
          lastWheelTimestampRef.current = now;
        } // ========================= Effect =========================
      
      
        var touchEventsRef = Object(external_window_React_["useRef"])(null);
        touchEventsRef.current = {
          onTouchStart: onTouchStart,
          onTouchMove: onTouchMove,
          onTouchEnd: onTouchEnd,
          onWheel: onWheel
        };
        external_window_React_["useEffect"](function () {
          function onProxyTouchStart(e) {
            touchEventsRef.current.onTouchStart(e);
          }
      
          function onProxyTouchMove(e) {
            touchEventsRef.current.onTouchMove(e);
          }
      
          function onProxyTouchEnd(e) {
            touchEventsRef.current.onTouchEnd(e);
          }
      
          function onProxyWheel(e) {
            touchEventsRef.current.onWheel(e);
          }
      
          document.addEventListener('touchmove', onProxyTouchMove, {
            passive: false
          });
          document.addEventListener('touchend', onProxyTouchEnd, {
            passive: false
          }); // No need to clean up since element removed
      
          ref.current.addEventListener('touchstart', onProxyTouchStart, {
            passive: false
          });
          ref.current.addEventListener('wheel', onProxyWheel);
          return function () {
            document.removeEventListener('touchmove', onProxyTouchMove);
            document.removeEventListener('touchend', onProxyTouchEnd);
          };
        }, []);
      }
      // CONCATENATED MODULE: ./node_modules/rc-tabs/es/hooks/useRefs.js
      
      
      function useRefs() {
        var cacheRefs = Object(external_window_React_["useRef"])(new Map());
      
        function getRef(key) {
          if (!cacheRefs.current.has(key)) {
            cacheRefs.current.set(key, external_window_React_["createRef"]());
          }
      
          return cacheRefs.current.get(key);
        }
      
        function removeRef(key) {
          cacheRefs.current.delete(key);
        }
      
        return [getRef, removeRef];
      }
      // CONCATENATED MODULE: ./node_modules/rc-tabs/es/hooks/useSyncState.js
      
      
      function useSyncState(defaultState, onChange) {
        var stateRef = external_window_React_["useRef"](defaultState);
      
        var _React$useState = external_window_React_["useState"]({}),
            _React$useState2 = Object(slicedToArray["a" /* default */])(_React$useState, 2),
            forceUpdate = _React$useState2[1];
      
        function setState(updater) {
          var newValue = typeof updater === 'function' ? updater(stateRef.current) : updater;
      
          if (newValue !== stateRef.current) {
            onChange(newValue, stateRef.current);
          }
      
          stateRef.current = newValue;
          forceUpdate({});
        }
      
        return [stateRef.current, setState];
      }
      // CONCATENATED MODULE: ./node_modules/rc-tabs/es/TabNavList/index.js
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      var TabNavList_ExtraContent = function ExtraContent(_ref) {
        var position = _ref.position,
            prefixCls = _ref.prefixCls,
            extra = _ref.extra;
        if (!extra) return null;
        var content;
        var assertExtra = extra;
      
        if (position === 'right') {
          content = assertExtra.right || !assertExtra.left && assertExtra || null;
        }
      
        if (position === 'left') {
          content = assertExtra.left || null;
        }
      
        return content ? external_window_React_["createElement"]("div", {
          className: "".concat(prefixCls, "-extra-content")
        }, content) : null;
      };
      
      function TabNavList(props, ref) {
        var _classNames;
      
        var _React$useContext = external_window_React_["useContext"](TabContext),
            prefixCls = _React$useContext.prefixCls,
            tabs = _React$useContext.tabs;
      
        var className = props.className,
            style = props.style,
            id = props.id,
            animated = props.animated,
            activeKey = props.activeKey,
            rtl = props.rtl,
            extra = props.extra,
            editable = props.editable,
            locale = props.locale,
            tabPosition = props.tabPosition,
            tabBarGutter = props.tabBarGutter,
            children = props.children,
            onTabClick = props.onTabClick,
            onTabScroll = props.onTabScroll;
        var tabsWrapperRef = Object(external_window_React_["useRef"])();
        var tabListRef = Object(external_window_React_["useRef"])();
        var operationsRef = Object(external_window_React_["useRef"])();
        var innerAddButtonRef = Object(external_window_React_["useRef"])();
      
        var _useRefs = useRefs(),
            _useRefs2 = Object(slicedToArray["a" /* default */])(_useRefs, 2),
            getBtnRef = _useRefs2[0],
            removeBtnRef = _useRefs2[1];
      
        var tabPositionTopOrBottom = tabPosition === 'top' || tabPosition === 'bottom';
      
        var _useSyncState = useSyncState(0, function (next, prev) {
          if (tabPositionTopOrBottom && onTabScroll) {
            onTabScroll({
              direction: next > prev ? 'left' : 'right'
            });
          }
        }),
            _useSyncState2 = Object(slicedToArray["a" /* default */])(_useSyncState, 2),
            transformLeft = _useSyncState2[0],
            setTransformLeft = _useSyncState2[1];
      
        var _useSyncState3 = useSyncState(0, function (next, prev) {
          if (!tabPositionTopOrBottom && onTabScroll) {
            onTabScroll({
              direction: next > prev ? 'top' : 'bottom'
            });
          }
        }),
            _useSyncState4 = Object(slicedToArray["a" /* default */])(_useSyncState3, 2),
            transformTop = _useSyncState4[0],
            setTransformTop = _useSyncState4[1];
      
        var _useState = Object(external_window_React_["useState"])(0),
            _useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
            wrapperScrollWidth = _useState2[0],
            setWrapperScrollWidth = _useState2[1];
      
        var _useState3 = Object(external_window_React_["useState"])(0),
            _useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
            wrapperScrollHeight = _useState4[0],
            setWrapperScrollHeight = _useState4[1];
      
        var _useState5 = Object(external_window_React_["useState"])(0),
            _useState6 = Object(slicedToArray["a" /* default */])(_useState5, 2),
            wrapperContentWidth = _useState6[0],
            setWrapperContentWidth = _useState6[1];
      
        var _useState7 = Object(external_window_React_["useState"])(0),
            _useState8 = Object(slicedToArray["a" /* default */])(_useState7, 2),
            wrapperContentHeight = _useState8[0],
            setWrapperContentHeight = _useState8[1];
      
        var _useState9 = Object(external_window_React_["useState"])(null),
            _useState10 = Object(slicedToArray["a" /* default */])(_useState9, 2),
            wrapperWidth = _useState10[0],
            setWrapperWidth = _useState10[1];
      
        var _useState11 = Object(external_window_React_["useState"])(null),
            _useState12 = Object(slicedToArray["a" /* default */])(_useState11, 2),
            wrapperHeight = _useState12[0],
            setWrapperHeight = _useState12[1];
      
        var _useState13 = Object(external_window_React_["useState"])(0),
            _useState14 = Object(slicedToArray["a" /* default */])(_useState13, 2),
            addWidth = _useState14[0],
            setAddWidth = _useState14[1];
      
        var _useState15 = Object(external_window_React_["useState"])(0),
            _useState16 = Object(slicedToArray["a" /* default */])(_useState15, 2),
            addHeight = _useState16[0],
            setAddHeight = _useState16[1];
      
        var _useRafState = useRafState(new Map()),
            _useRafState2 = Object(slicedToArray["a" /* default */])(_useRafState, 2),
            tabSizes = _useRafState2[0],
            setTabSizes = _useRafState2[1];
      
        var tabOffsets = useOffsets(tabs, tabSizes, wrapperScrollWidth); // ========================== Util =========================
      
        var operationsHiddenClassName = "".concat(prefixCls, "-nav-operations-hidden");
        var transformMin = 0;
        var transformMax = 0;
      
        if (!tabPositionTopOrBottom) {
          transformMin = Math.min(0, wrapperHeight - wrapperScrollHeight);
          transformMax = 0;
        } else if (rtl) {
          transformMin = 0;
          transformMax = Math.max(0, wrapperScrollWidth - wrapperWidth);
        } else {
          transformMin = Math.min(0, wrapperWidth - wrapperScrollWidth);
          transformMax = 0;
        }
      
        function alignInRange(value) {
          if (value < transformMin) {
            return [transformMin, false];
          }
      
          if (value > transformMax) {
            return [transformMax, false];
          }
      
          return [value, true];
        } // ========================= Mobile ========================
      
      
        var touchMovingRef = Object(external_window_React_["useRef"])();
      
        var _useState17 = Object(external_window_React_["useState"])(),
            _useState18 = Object(slicedToArray["a" /* default */])(_useState17, 2),
            lockAnimation = _useState18[0],
            setLockAnimation = _useState18[1];
      
        function doLockAnimation() {
          setLockAnimation(Date.now());
        }
      
        function clearTouchMoving() {
          window.clearTimeout(touchMovingRef.current);
        }
      
        useTouchMove(tabsWrapperRef, function (offsetX, offsetY) {
          var preventDefault = false;
      
          function doMove(setState, offset) {
            setState(function (value) {
              var _alignInRange = alignInRange(value + offset),
                  _alignInRange2 = Object(slicedToArray["a" /* default */])(_alignInRange, 2),
                  newValue = _alignInRange2[0],
                  needPrevent = _alignInRange2[1];
      
              preventDefault = needPrevent;
              return newValue;
            });
          }
      
          if (tabPositionTopOrBottom) {
            // Skip scroll if place is enough
            if (wrapperWidth >= wrapperScrollWidth) {
              return preventDefault;
            }
      
            doMove(setTransformLeft, offsetX);
          } else {
            if (wrapperHeight >= wrapperScrollHeight) {
              return preventDefault;
            }
      
            doMove(setTransformTop, offsetY);
          }
      
          clearTouchMoving();
          doLockAnimation();
          return preventDefault;
        });
        Object(external_window_React_["useEffect"])(function () {
          clearTouchMoving();
      
          if (lockAnimation) {
            touchMovingRef.current = window.setTimeout(function () {
              setLockAnimation(0);
            }, 100);
          }
      
          return clearTouchMoving;
        }, [lockAnimation]); // ========================= Scroll ========================
      
        function scrollToTab() {
          var key = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : activeKey;
          var tabOffset = tabOffsets.get(key);
          if (!tabOffset) return;
      
          if (tabPositionTopOrBottom) {
            // ============ Align with top & bottom ============
            var newTransform = transformLeft; // RTL
      
            if (rtl) {
              if (tabOffset.right < transformLeft) {
                newTransform = tabOffset.right;
              } else if (tabOffset.right + tabOffset.width > transformLeft + wrapperWidth) {
                newTransform = tabOffset.right + tabOffset.width - wrapperWidth;
              }
            } // LTR
            else if (tabOffset.left < -transformLeft) {
                newTransform = -tabOffset.left;
              } else if (tabOffset.left + tabOffset.width > -transformLeft + wrapperWidth) {
                newTransform = -(tabOffset.left + tabOffset.width - wrapperWidth);
              }
      
            setTransformTop(0);
            setTransformLeft(alignInRange(newTransform)[0]);
          } else {
            // ============ Align with left & right ============
            var _newTransform = transformTop;
      
            if (tabOffset.top < -transformTop) {
              _newTransform = -tabOffset.top;
            } else if (tabOffset.top + tabOffset.height > -transformTop + wrapperHeight) {
              _newTransform = -(tabOffset.top + tabOffset.height - wrapperHeight);
            }
      
            setTransformLeft(0);
            setTransformTop(alignInRange(_newTransform)[0]);
          }
        } // ========================== Tab ==========================
        // Render tab node & collect tab offset
      
      
        var _useVisibleRange = useVisibleRange(tabOffsets, {
          width: wrapperWidth,
          height: wrapperHeight,
          left: transformLeft,
          top: transformTop
        }, {
          width: wrapperContentWidth,
          height: wrapperContentHeight
        }, {
          width: addWidth,
          height: addHeight
        }, Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, props), {}, {
          tabs: tabs
        })),
            _useVisibleRange2 = Object(slicedToArray["a" /* default */])(_useVisibleRange, 2),
            visibleStart = _useVisibleRange2[0],
            visibleEnd = _useVisibleRange2[1];
      
        var tabNodes = tabs.map(function (tab) {
          var key = tab.key;
          return external_window_React_["createElement"](TabNavList_TabNode, {
            id: id,
            prefixCls: prefixCls,
            key: key,
            rtl: rtl,
            tab: tab,
            closable: tab.closable,
            editable: editable,
            active: key === activeKey,
            tabPosition: tabPosition,
            tabBarGutter: tabBarGutter,
            renderWrapper: children,
            removeAriaLabel: locale === null || locale === void 0 ? void 0 : locale.removeAriaLabel,
            ref: getBtnRef(key),
            onClick: function onClick(e) {
              onTabClick(key, e);
            },
            onRemove: function onRemove() {
              removeBtnRef(key);
            },
            onFocus: function onFocus() {
              scrollToTab(key);
              doLockAnimation(); // Focus element will make scrollLeft change which we should reset back
      
              if (!rtl) {
                tabsWrapperRef.current.scrollLeft = 0;
              }
      
              tabsWrapperRef.current.scrollTop = 0;
            }
          });
        });
        var onListHolderResize = useRaf(function () {
          var _tabsWrapperRef$curre, _tabsWrapperRef$curre2, _innerAddButtonRef$cu, _innerAddButtonRef$cu2, _operationsRef$curren, _operationsRef$curren2, _tabListRef$current, _tabListRef$current2, _operationsRef$curren3;
      
          // Update wrapper records
          var offsetWidth = ((_tabsWrapperRef$curre = tabsWrapperRef.current) === null || _tabsWrapperRef$curre === void 0 ? void 0 : _tabsWrapperRef$curre.offsetWidth) || 0;
          var offsetHeight = ((_tabsWrapperRef$curre2 = tabsWrapperRef.current) === null || _tabsWrapperRef$curre2 === void 0 ? void 0 : _tabsWrapperRef$curre2.offsetHeight) || 0;
          var newAddWidth = ((_innerAddButtonRef$cu = innerAddButtonRef.current) === null || _innerAddButtonRef$cu === void 0 ? void 0 : _innerAddButtonRef$cu.offsetWidth) || 0;
          var newAddHeight = ((_innerAddButtonRef$cu2 = innerAddButtonRef.current) === null || _innerAddButtonRef$cu2 === void 0 ? void 0 : _innerAddButtonRef$cu2.offsetHeight) || 0;
          var newOperationWidth = ((_operationsRef$curren = operationsRef.current) === null || _operationsRef$curren === void 0 ? void 0 : _operationsRef$curren.offsetWidth) || 0;
          var newOperationHeight = ((_operationsRef$curren2 = operationsRef.current) === null || _operationsRef$curren2 === void 0 ? void 0 : _operationsRef$curren2.offsetHeight) || 0;
          setWrapperWidth(offsetWidth);
          setWrapperHeight(offsetHeight);
          setAddWidth(newAddWidth);
          setAddHeight(newAddHeight);
          var newWrapperScrollWidth = (((_tabListRef$current = tabListRef.current) === null || _tabListRef$current === void 0 ? void 0 : _tabListRef$current.offsetWidth) || 0) - newAddWidth;
          var newWrapperScrollHeight = (((_tabListRef$current2 = tabListRef.current) === null || _tabListRef$current2 === void 0 ? void 0 : _tabListRef$current2.offsetHeight) || 0) - newAddHeight;
          setWrapperScrollWidth(newWrapperScrollWidth);
          setWrapperScrollHeight(newWrapperScrollHeight);
          var isOperationHidden = (_operationsRef$curren3 = operationsRef.current) === null || _operationsRef$curren3 === void 0 ? void 0 : _operationsRef$curren3.className.includes(operationsHiddenClassName);
          setWrapperContentWidth(newWrapperScrollWidth - (isOperationHidden ? 0 : newOperationWidth));
          setWrapperContentHeight(newWrapperScrollHeight - (isOperationHidden ? 0 : newOperationHeight)); // Update buttons records
      
          setTabSizes(function () {
            var newSizes = new Map();
            tabs.forEach(function (_ref2) {
              var key = _ref2.key;
              var btnNode = getBtnRef(key).current;
      
              if (btnNode) {
                newSizes.set(key, {
                  width: btnNode.offsetWidth,
                  height: btnNode.offsetHeight,
                  left: btnNode.offsetLeft,
                  top: btnNode.offsetTop
                });
              }
            });
            return newSizes;
          });
        }); // ======================== Dropdown =======================
      
        var startHiddenTabs = tabs.slice(0, visibleStart);
        var endHiddenTabs = tabs.slice(visibleEnd + 1);
        var hiddenTabs = [].concat(Object(toConsumableArray["a" /* default */])(startHiddenTabs), Object(toConsumableArray["a" /* default */])(endHiddenTabs)); // =================== Link & Operations ===================
      
        var _useState19 = Object(external_window_React_["useState"])(),
            _useState20 = Object(slicedToArray["a" /* default */])(_useState19, 2),
            inkStyle = _useState20[0],
            setInkStyle = _useState20[1];
      
        var activeTabOffset = tabOffsets.get(activeKey); // Delay set ink style to avoid remove tab blink
      
        var inkBarRafRef = Object(external_window_React_["useRef"])();
      
        function cleanInkBarRaf() {
          raf_default.a.cancel(inkBarRafRef.current);
        }
      
        Object(external_window_React_["useEffect"])(function () {
          var newInkStyle = {};
      
          if (activeTabOffset) {
            if (tabPositionTopOrBottom) {
              if (rtl) {
                newInkStyle.right = activeTabOffset.right;
              } else {
                newInkStyle.left = activeTabOffset.left;
              }
      
              newInkStyle.width = activeTabOffset.width;
            } else {
              newInkStyle.top = activeTabOffset.top;
              newInkStyle.height = activeTabOffset.height;
            }
          }
      
          cleanInkBarRaf();
          inkBarRafRef.current = raf_default()(function () {
            setInkStyle(newInkStyle);
          });
          return cleanInkBarRaf;
        }, [activeTabOffset, tabPositionTopOrBottom, rtl]); // ========================= Effect ========================
      
        Object(external_window_React_["useEffect"])(function () {
          scrollToTab();
        }, [activeKey, activeTabOffset, tabOffsets, tabPositionTopOrBottom]); // Should recalculate when rtl changed
      
        Object(external_window_React_["useEffect"])(function () {
          onListHolderResize();
        }, [rtl, tabBarGutter, activeKey, tabs.map(function (tab) {
          return tab.key;
        }).join('_')]); // ========================= Render ========================
      
        var hasDropdown = !!hiddenTabs.length;
        var wrapPrefix = "".concat(prefixCls, "-nav-wrap");
        var pingLeft;
        var pingRight;
        var pingTop;
        var pingBottom;
      
        if (tabPositionTopOrBottom) {
          if (rtl) {
            pingRight = transformLeft > 0;
            pingLeft = transformLeft + wrapperWidth < wrapperScrollWidth;
          } else {
            pingLeft = transformLeft < 0;
            pingRight = -transformLeft + wrapperWidth < wrapperScrollWidth;
          }
        } else {
          pingTop = transformTop < 0;
          pingBottom = -transformTop + wrapperHeight < wrapperScrollHeight;
        }
        /* eslint-disable jsx-a11y/interactive-supports-focus */
      
      
        return external_window_React_["createElement"]("div", {
          ref: ref,
          role: "tablist",
          className: classnames_default()("".concat(prefixCls, "-nav"), className),
          style: style,
          onKeyDown: function onKeyDown() {
            // No need animation when use keyboard
            doLockAnimation();
          }
        }, external_window_React_["createElement"](TabNavList_ExtraContent, {
          position: "left",
          extra: extra,
          prefixCls: prefixCls
        }), external_window_React_["createElement"](es["a" /* default */], {
          onResize: onListHolderResize
        }, external_window_React_["createElement"]("div", {
          className: classnames_default()(wrapPrefix, (_classNames = {}, Object(defineProperty["a" /* default */])(_classNames, "".concat(wrapPrefix, "-ping-left"), pingLeft), Object(defineProperty["a" /* default */])(_classNames, "".concat(wrapPrefix, "-ping-right"), pingRight), Object(defineProperty["a" /* default */])(_classNames, "".concat(wrapPrefix, "-ping-top"), pingTop), Object(defineProperty["a" /* default */])(_classNames, "".concat(wrapPrefix, "-ping-bottom"), pingBottom), _classNames)),
          ref: tabsWrapperRef
        }, external_window_React_["createElement"](es["a" /* default */], {
          onResize: onListHolderResize
        }, external_window_React_["createElement"]("div", {
          ref: tabListRef,
          className: "".concat(prefixCls, "-nav-list"),
          style: {
            transform: "translate(".concat(transformLeft, "px, ").concat(transformTop, "px)"),
            transition: lockAnimation ? 'none' : undefined
          }
        }, tabNodes, external_window_React_["createElement"](TabNavList_AddButton, {
          ref: innerAddButtonRef,
          prefixCls: prefixCls,
          locale: locale,
          editable: editable,
          style: {
            visibility: hasDropdown ? 'hidden' : null
          }
        }), external_window_React_["createElement"]("div", {
          className: classnames_default()("".concat(prefixCls, "-ink-bar"), Object(defineProperty["a" /* default */])({}, "".concat(prefixCls, "-ink-bar-animated"), animated.inkBar)),
          style: inkStyle
        }))))), external_window_React_["createElement"](TabNavList_OperationNode, Object.assign({}, props, {
          ref: operationsRef,
          prefixCls: prefixCls,
          tabs: hiddenTabs,
          className: !hasDropdown && operationsHiddenClassName
        })), external_window_React_["createElement"](TabNavList_ExtraContent, {
          position: "right",
          extra: extra,
          prefixCls: prefixCls
        }));
        /* eslint-enable */
      }
      
      /* harmony default export */ var es_TabNavList = (external_window_React_["forwardRef"](TabNavList));
      // CONCATENATED MODULE: ./node_modules/rc-tabs/es/TabPanelList/index.js
      
      
      
      
      function TabPanelList(_ref) {
        var id = _ref.id,
            activeKey = _ref.activeKey,
            animated = _ref.animated,
            tabPosition = _ref.tabPosition,
            rtl = _ref.rtl,
            destroyInactiveTabPane = _ref.destroyInactiveTabPane;
      
        var _React$useContext = external_window_React_["useContext"](TabContext),
            prefixCls = _React$useContext.prefixCls,
            tabs = _React$useContext.tabs;
      
        var tabPaneAnimated = animated.tabPane;
        var activeIndex = tabs.findIndex(function (tab) {
          return tab.key === activeKey;
        });
        return external_window_React_["createElement"]("div", {
          className: classnames_default()("".concat(prefixCls, "-content-holder"))
        }, external_window_React_["createElement"]("div", {
          className: classnames_default()("".concat(prefixCls, "-content"), "".concat(prefixCls, "-content-").concat(tabPosition), Object(defineProperty["a" /* default */])({}, "".concat(prefixCls, "-content-animated"), tabPaneAnimated)),
          style: activeIndex && tabPaneAnimated ? Object(defineProperty["a" /* default */])({}, rtl ? 'marginRight' : 'marginLeft', "-".concat(activeIndex, "00%")) : null
        }, tabs.map(function (tab) {
          return external_window_React_["cloneElement"](tab.node, {
            key: tab.key,
            prefixCls: prefixCls,
            tabKey: tab.key,
            id: id,
            animated: tabPaneAnimated,
            active: tab.key === activeKey,
            destroyInactiveTabPane: destroyInactiveTabPane
          });
        })));
      }
      // CONCATENATED MODULE: ./node_modules/rc-tabs/es/TabPanelList/TabPane.js
      
      
      
      
      function TabPane(_ref) {
        var prefixCls = _ref.prefixCls,
            forceRender = _ref.forceRender,
            className = _ref.className,
            style = _ref.style,
            id = _ref.id,
            active = _ref.active,
            animated = _ref.animated,
            destroyInactiveTabPane = _ref.destroyInactiveTabPane,
            tabKey = _ref.tabKey,
            children = _ref.children;
      
        var _React$useState = external_window_React_["useState"](forceRender),
            _React$useState2 = Object(slicedToArray["a" /* default */])(_React$useState, 2),
            visited = _React$useState2[0],
            setVisited = _React$useState2[1];
      
        external_window_React_["useEffect"](function () {
          if (active) {
            setVisited(true);
          } else if (destroyInactiveTabPane) {
            setVisited(false);
          }
        }, [active, destroyInactiveTabPane]);
        var mergedStyle = {};
      
        if (!active) {
          if (animated) {
            mergedStyle.visibility = 'hidden';
            mergedStyle.height = 0;
            mergedStyle.overflowY = 'hidden';
          } else {
            mergedStyle.display = 'none';
          }
        }
      
        return external_window_React_["createElement"]("div", {
          id: id && "".concat(id, "-panel-").concat(tabKey),
          role: "tabpanel",
          tabIndex: active ? 0 : -1,
          "aria-labelledby": id && "".concat(id, "-tab-").concat(tabKey),
          "aria-hidden": !active,
          style: Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, mergedStyle), style),
          className: classnames_default()("".concat(prefixCls, "-tabpane"), active && "".concat(prefixCls, "-tabpane-active"), className)
        }, (active || visited || forceRender) && children);
      }
      // CONCATENATED MODULE: ./node_modules/rc-tabs/es/Tabs.js
      
      
      
      
      // Accessibility https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/Tab_Role
      
      
      
      
      
      
      
      
      
      
      /**
       * Should added antd:
       * - type
       *
       * Removed:
       * - onNextClick
       * - onPrevClick
       * - keyboard
       */
      // Used for accessibility
      
      var uuid = 0;
      
      function parseTabList(children) {
        return Object(toArray["a" /* default */])(children).map(function (node) {
          if (external_window_React_["isValidElement"](node)) {
            var key = node.key !== undefined ? String(node.key) : undefined;
            return Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({
              key: key
            }, node.props), {}, {
              node: node
            });
          }
      
          return null;
        }).filter(function (tab) {
          return tab;
        });
      }
      
      function Tabs(_ref, ref) {
        var _classNames;
      
        var id = _ref.id,
            _ref$prefixCls = _ref.prefixCls,
            prefixCls = _ref$prefixCls === void 0 ? 'rc-tabs' : _ref$prefixCls,
            className = _ref.className,
            children = _ref.children,
            direction = _ref.direction,
            activeKey = _ref.activeKey,
            defaultActiveKey = _ref.defaultActiveKey,
            editable = _ref.editable,
            animated = _ref.animated,
            _ref$tabPosition = _ref.tabPosition,
            tabPosition = _ref$tabPosition === void 0 ? 'top' : _ref$tabPosition,
            tabBarGutter = _ref.tabBarGutter,
            tabBarStyle = _ref.tabBarStyle,
            tabBarExtraContent = _ref.tabBarExtraContent,
            locale = _ref.locale,
            moreIcon = _ref.moreIcon,
            moreTransitionName = _ref.moreTransitionName,
            destroyInactiveTabPane = _ref.destroyInactiveTabPane,
            renderTabBar = _ref.renderTabBar,
            onChange = _ref.onChange,
            onTabClick = _ref.onTabClick,
            onTabScroll = _ref.onTabScroll,
            restProps = Object(objectWithoutProperties["a" /* default */])(_ref, ["id", "prefixCls", "className", "children", "direction", "activeKey", "defaultActiveKey", "editable", "animated", "tabPosition", "tabBarGutter", "tabBarStyle", "tabBarExtraContent", "locale", "moreIcon", "moreTransitionName", "destroyInactiveTabPane", "renderTabBar", "onChange", "onTabClick", "onTabScroll"]);
      
        var tabs = parseTabList(children);
        var rtl = direction === 'rtl';
        var mergedAnimated;
      
        if (animated === false) {
          mergedAnimated = {
            inkBar: false,
            tabPane: false
          };
        } else {
          mergedAnimated = Object(objectSpread2["a" /* default */])({
            inkBar: true,
            tabPane: false
          }, animated !== true ? animated : null);
        } // ======================== Mobile ========================
      
      
        var _useState = Object(external_window_React_["useState"])(false),
            _useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
            mobile = _useState2[0],
            setMobile = _useState2[1];
      
        Object(external_window_React_["useEffect"])(function () {
          // Only update on the client side
          setMobile(useTouchMove_isMobile());
        }, []); // ====================== Active Key ======================
      
        var _useMergedState = Object(useMergedState["a" /* default */])(function () {
          var _tabs$;
      
          return (_tabs$ = tabs[0]) === null || _tabs$ === void 0 ? void 0 : _tabs$.key;
        }, {
          value: activeKey,
          defaultValue: defaultActiveKey
        }),
            _useMergedState2 = Object(slicedToArray["a" /* default */])(_useMergedState, 2),
            mergedActiveKey = _useMergedState2[0],
            setMergedActiveKey = _useMergedState2[1];
      
        var _useState3 = Object(external_window_React_["useState"])(function () {
          return tabs.findIndex(function (tab) {
            return tab.key === mergedActiveKey;
          });
        }),
            _useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
            activeIndex = _useState4[0],
            setActiveIndex = _useState4[1]; // Reset active key if not exist anymore
      
      
        Object(external_window_React_["useEffect"])(function () {
          var newActiveIndex = tabs.findIndex(function (tab) {
            return tab.key === mergedActiveKey;
          });
      
          if (newActiveIndex === -1) {
            var _tabs$newActiveIndex;
      
            newActiveIndex = Math.max(0, Math.min(activeIndex, tabs.length - 1));
            setMergedActiveKey((_tabs$newActiveIndex = tabs[newActiveIndex]) === null || _tabs$newActiveIndex === void 0 ? void 0 : _tabs$newActiveIndex.key);
          }
      
          setActiveIndex(newActiveIndex);
        }, [tabs.map(function (tab) {
          return tab.key;
        }).join('_'), mergedActiveKey, activeIndex]); // ===================== Accessibility ====================
      
        var _useMergedState3 = Object(useMergedState["a" /* default */])(null, {
          value: id
        }),
            _useMergedState4 = Object(slicedToArray["a" /* default */])(_useMergedState3, 2),
            mergedId = _useMergedState4[0],
            setMergedId = _useMergedState4[1];
      
        var mergedTabPosition = tabPosition;
      
        if (mobile && !['left', 'right'].includes(tabPosition)) {
          mergedTabPosition = 'top';
        } // Async generate id to avoid ssr mapping failed
      
      
        Object(external_window_React_["useEffect"])(function () {
          if (!id) {
            setMergedId("rc-tabs-".concat( false ? undefined : uuid));
            uuid += 1;
          }
        }, []); // ======================== Events ========================
      
        function onInternalTabClick(key, e) {
          onTabClick === null || onTabClick === void 0 ? void 0 : onTabClick(key, e);
          setMergedActiveKey(key);
          onChange === null || onChange === void 0 ? void 0 : onChange(key);
        } // ======================== Render ========================
      
      
        var sharedProps = {
          id: mergedId,
          activeKey: mergedActiveKey,
          animated: mergedAnimated,
          tabPosition: mergedTabPosition,
          rtl: rtl,
          mobile: mobile
        };
        var tabNavBar;
      
        var tabNavBarProps = Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, sharedProps), {}, {
          editable: editable,
          locale: locale,
          moreIcon: moreIcon,
          moreTransitionName: moreTransitionName,
          tabBarGutter: tabBarGutter,
          onTabClick: onInternalTabClick,
          onTabScroll: onTabScroll,
          extra: tabBarExtraContent,
          style: tabBarStyle,
          panes: children
        });
      
        if (renderTabBar) {
          tabNavBar = renderTabBar(tabNavBarProps, es_TabNavList);
        } else {
          tabNavBar = external_window_React_["createElement"](es_TabNavList, Object.assign({}, tabNavBarProps));
        }
      
        return external_window_React_["createElement"](TabContext.Provider, {
          value: {
            tabs: tabs,
            prefixCls: prefixCls
          }
        }, external_window_React_["createElement"]("div", Object.assign({
          ref: ref,
          id: id,
          className: classnames_default()(prefixCls, "".concat(prefixCls, "-").concat(mergedTabPosition), (_classNames = {}, Object(defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-mobile"), mobile), Object(defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-editable"), editable), Object(defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-rtl"), rtl), _classNames), className)
        }, restProps), tabNavBar, external_window_React_["createElement"](TabPanelList, Object.assign({
          destroyInactiveTabPane: destroyInactiveTabPane
        }, sharedProps, {
          animated: mergedAnimated
        }))));
      }
      
      var ForwardTabs = external_window_React_["forwardRef"](Tabs);
      ForwardTabs.TabPane = TabPane;
      /* harmony default export */ var es_Tabs = (ForwardTabs);
      // CONCATENATED MODULE: ./node_modules/rc-tabs/es/index.js
      
      
      
      /* harmony default export */ var rc_tabs_es = __webpack_exports__["b"] = (es_Tabs);
      
      /***/ }),
      
      /***/ "p5ED":
      /*!*********************************************!*\
        !*** ./src/components/PreviewAll/index.tsx ***!
        \*********************************************/
      /*! exports provided: default */
      /*! exports used: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      /* harmony import */ var antd_es_button_style__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! antd/es/button/style */ "+L6B");
      /* harmony import */ var antd_es_button__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! antd/es/button */ "2/Rp");
      /* harmony import */ var antd_es_tooltip_style__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! antd/es/tooltip/style */ "5Dmo");
      /* harmony import */ var antd_es_tooltip__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! antd/es/tooltip */ "3S7+");
      /* harmony import */ var _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/objectSpread2 */ "k1fw");
      /* harmony import */ var _root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/slicedToArray */ "tJVT");
      /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! react */ "cDcd");
      /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_6__);
      /* harmony import */ var _index_less_modules__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./index.less?modules */ "vHTk");
      /* harmony import */ var _index_less_modules__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_index_less_modules__WEBPACK_IMPORTED_MODULE_7__);
      /* harmony import */ var _ant_design_icons__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @ant-design/icons */ "yEEn");
      /* harmony import */ var _components_monaco_editor__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @/components/monaco-editor */ "ZW9T");
      /* harmony import */ var _utils_util__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @/utils/util */ "1vsH");
      
      
      
      
      
      
      
      
      
      
      
      
      /* harmony default export */ __webpack_exports__["a"] = (function (_ref) {
        var name = _ref.name,
            data = _ref.data,
            theme = _ref.theme,
            type = _ref.type,
            filename = _ref.filename,
            monacoEditor = _ref.monacoEditor,
            className = _ref.className,
            style = _ref.style,
            close = _ref.close,
            onClose = _ref.onClose,
            hasMask = _ref.hasMask;
      
        var _useState = Object(react__WEBPACK_IMPORTED_MODULE_6__["useState"])('https://view.officeapps.live.com/op/view.aspx?src=http://testgs.educoder.net//rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBCZz09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--03541f6234b93d7ac3b2d84e7eb0e6594a952945/1.ppt'),
            _useState2 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"])(_useState, 2),
            src = _useState2[0],
            setSrc = _useState2[1];
      
        var _useState3 = Object(react__WEBPACK_IMPORTED_MODULE_6__["useState"])(""),
            _useState4 = Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"])(_useState3, 2),
            token = _useState4[0],
            setToken = _useState4[1];
      
        var size;
        var unit = 1024 * 1024;
        var maxSize = 10 * unit;
        var closeRef = Object(react__WEBPACK_IMPORTED_MODULE_6__["useRef"])();
      
        if (type === "office") {
          size = Object(_utils_util__WEBPACK_IMPORTED_MODULE_10__[/* parseUrl */ "V"])(data).filesize;
      
          if (size > maxSize) {
            type = "other";
          }
        }
      
        if (filename) monacoEditor.filename = filename;
        Object(react__WEBPACK_IMPORTED_MODULE_6__["useEffect"])(function () {
          var _document$cookie, _document$cookie$repl;
      
          var cookies = (_document$cookie = document.cookie) === null || _document$cookie === void 0 ? void 0 : (_document$cookie$repl = _document$cookie.replace(/\s/g, "")) === null || _document$cookie$repl === void 0 ? void 0 : _document$cookie$repl.split(";");
          cookies === null || cookies === void 0 ? void 0 : cookies.map(function (item) {
            var i = item.split("=");
      
            if (i[0] === '_educoder_session') {
              setToken(i[1]);
            }
          });
        }, []);
      
        var handleClick = function handleClick() {
          if (data.startsWith("http") || data.startsWith('blob:')) {
            handleDown();
            return;
          }
      
          Object(_utils_util__WEBPACK_IMPORTED_MODULE_10__[/* downloadFile */ "z"])(filename || 'educoder', data, filename);
        };
      
        var handleDown = function handleDown() {
          Object(_utils_util__WEBPACK_IMPORTED_MODULE_10__[/* downLoadLink */ "x"])(filename || 'educoder', decodeURIComponent(data));
        };
      
        return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("div", {
          style: Object(_root_workspace_ppte5yg23_SJ5m_develop_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_4__[/* default */ "a"])({}, style || {}),
          className: "".concat(hasMask && _index_less_modules__WEBPACK_IMPORTED_MODULE_7___default.a.bgBlack, " ").concat(!!type ? _index_less_modules__WEBPACK_IMPORTED_MODULE_7___default.a.wrp : "hide")
        }, close && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("div", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_7___default.a.close,
          ref: closeRef
        }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement(antd_es_tooltip__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"], {
          title: "\u70B9\u51FB\u4E0B\u8F7D\u6B64\u6587\u4EF6",
          getPopupContainer: function getPopupContainer() {
            return closeRef.current;
          }
        }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("span", {
          onClick: handleDown
        }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("i", {
          className: "icon-quxiaozhiding"
        }))), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement(antd_es_tooltip__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"], {
          title: "\u5173\u95ED",
          getPopupContainer: function getPopupContainer() {
            return closeRef.current;
          }
        }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("span", {
          className: "",
          onClick: onClose
        }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("i", {
          className: "icon-guanbi1"
        })))), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("div", {
          className: "".concat(_index_less_modules__WEBPACK_IMPORTED_MODULE_7___default.a[className], " ").concat(className, " ").concat(_index_less_modules__WEBPACK_IMPORTED_MODULE_7___default.a.monaco, " ").concat(type === "txt" ? "show" : "hide")
        }, type === "txt" && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement(_components_monaco_editor__WEBPACK_IMPORTED_MODULE_9__[/* default */ "b"], monacoEditor)), type === "audio" && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("audio", {
          src: "".concat((data === null || data === void 0 ? void 0 : data.indexOf("http://")) > -1 || (data === null || data === void 0 ? void 0 : data.indexOf("https://")) > -1 ? "" : "data:audio/mp3;base64,").concat(data),
          autoPlay: true
        }), type === "video" && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_6___default.a.Fragment, null, (data === null || data === void 0 ? void 0 : data.indexOf("http")) > -1 ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("video", {
          controls: true,
          src: "".concat(data),
          autoPlay: true
        }) : /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("video", {
          controls: true,
          src: "data:video/mp4;base64,".concat(data),
          autoPlay: true
        })), type === 'office' && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("iframe", {
          src: "https://view.officeapps.live.com/op/embed.aspx?src=".concat(data, "?").concat(encodeURIComponent("disposition=office&token=".concat(token)))
        }), type === 'html' && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("iframe", {
          src: data + '&disposition=inline'
        }), type === 'pdf' && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("embed", {
          className: _index_less_modules__WEBPACK_IMPORTED_MODULE_7___default.a.embed,
          src: data
        }), type === "image" && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("img", {
          src: "".concat((data === null || data === void 0 ? void 0 : data.indexOf("http://")) > -1 || (data === null || data === void 0 ? void 0 : data.indexOf("https://")) > -1 ? "" : "data:image/png;base64,").concat(data)
        }), type === "other" && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("div", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement(antd_es_button__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"], {
          type: "primary",
          size: "large",
          onClick: handleClick
        }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement(_ant_design_icons__WEBPACK_IMPORTED_MODULE_8__[/* default */ "a"], null), "\u70B9\u51FB\u4E0B\u8F7D")), type === "download" && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement(antd_es_button__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"], {
          type: "primary",
          size: "large",
          onClick: handleClick
        }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement(_ant_design_icons__WEBPACK_IMPORTED_MODULE_8__[/* default */ "a"], null), "\u70B9\u51FB\u4E0B\u8F7D"));
      });
      
      /***/ }),
      
      /***/ "psGv":
      /*!**********************************************************!*\
        !*** ./node_modules/js-beautify/js/lib/beautify-html.js ***!
        \**********************************************************/
      /*! no static exports found */
      /*! all exports used */
      /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
      /***/ (function(module, exports, __webpack_require__) {
      
      var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* AUTO-GENERATED. DO NOT MODIFY. */
      /*
      
        The MIT License (MIT)
      
        Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
      
        Permission 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:
      
        The above copyright notice and this permission notice shall be
        included in all copies or substantial portions of the Software.
      
        THE 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.
      
      
       Style HTML
      ---------------
      
        Written by Nochum Sossonko, (nsossonko@hotmail.com)
      
        Based on code initially developed by: Einar Lielmanis, <einar@beautifier.io>
          https://beautifier.io/
      
        Usage:
          style_html(html_source);
      
          style_html(html_source, options);
      
        The options are:
          indent_inner_html (default false)  — indent <head> and <body> sections,
          indent_size (default 4)          — indentation size,
          indent_char (default space)      — character to indent with,
          wrap_line_length (default 250)            -  maximum amount of characters per line (0 = disable)
          brace_style (default "collapse") - "collapse" | "expand" | "end-expand" | "none"
                  put braces on the same line as control statements (default), or put braces on own line (Allman / ANSI style), or just put end braces on own line, or attempt to keep them where they are.
          inline (defaults to inline tags) - list of tags to be considered inline tags
          unformatted (defaults to inline tags) - list of tags, that shouldn't be reformatted
          content_unformatted (defaults to ["pre", "textarea"] tags) - list of tags, whose content shouldn't be reformatted
          indent_scripts (default normal)  - "keep"|"separate"|"normal"
          preserve_newlines (default true) - whether existing line breaks before elements should be preserved
                                              Only works before elements, not inside tags or for text.
          max_preserve_newlines (default unlimited) - maximum number of line breaks to be preserved in one chunk
          indent_handlebars (default false) - format and indent {{#foo}} and {{/foo}}
          end_with_newline (false)          - end with a newline
          extra_liners (default [head,body,/html]) -List of tags that should have an extra newline before them.
      
          e.g.
      
          style_html(html_source, {
            'indent_inner_html': false,
            'indent_size': 2,
            'indent_char': ' ',
            'wrap_line_length': 78,
            'brace_style': 'expand',
            'preserve_newlines': true,
            'max_preserve_newlines': 5,
            'indent_handlebars': false,
            'extra_liners': ['/html']
          });
      */
      
      (function() {
      
      /* GENERATED_BUILD_OUTPUT */
      var legacy_beautify_html;
      /******/ (function() { // webpackBootstrap
      /******/ 	"use strict";
      /******/ 	var __webpack_modules__ = ([
      /* 0 */,
      /* 1 */,
      /* 2 */
      /***/ (function(module) {
      
      /*jshint node:true */
      /*
        The MIT License (MIT)
      
        Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
      
        Permission 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:
      
        The above copyright notice and this permission notice shall be
        included in all copies or substantial portions of the Software.
      
        THE 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.
      */
      
      
      
      function OutputLine(parent) {
        this.__parent = parent;
        this.__character_count = 0;
        // use indent_count as a marker for this.__lines that have preserved indentation
        this.__indent_count = -1;
        this.__alignment_count = 0;
        this.__wrap_point_index = 0;
        this.__wrap_point_character_count = 0;
        this.__wrap_point_indent_count = -1;
        this.__wrap_point_alignment_count = 0;
      
        this.__items = [];
      }
      
      OutputLine.prototype.clone_empty = function() {
        var line = new OutputLine(this.__parent);
        line.set_indent(this.__indent_count, this.__alignment_count);
        return line;
      };
      
      OutputLine.prototype.item = function(index) {
        if (index < 0) {
          return this.__items[this.__items.length + index];
        } else {
          return this.__items[index];
        }
      };
      
      OutputLine.prototype.has_match = function(pattern) {
        for (var lastCheckedOutput = this.__items.length - 1; lastCheckedOutput >= 0; lastCheckedOutput--) {
          if (this.__items[lastCheckedOutput].match(pattern)) {
            return true;
          }
        }
        return false;
      };
      
      OutputLine.prototype.set_indent = function(indent, alignment) {
        if (this.is_empty()) {
          this.__indent_count = indent || 0;
          this.__alignment_count = alignment || 0;
          this.__character_count = this.__parent.get_indent_size(this.__indent_count, this.__alignment_count);
        }
      };
      
      OutputLine.prototype._set_wrap_point = function() {
        if (this.__parent.wrap_line_length) {
          this.__wrap_point_index = this.__items.length;
          this.__wrap_point_character_count = this.__character_count;
          this.__wrap_point_indent_count = this.__parent.next_line.__indent_count;
          this.__wrap_point_alignment_count = this.__parent.next_line.__alignment_count;
        }
      };
      
      OutputLine.prototype._should_wrap = function() {
        return this.__wrap_point_index &&
          this.__character_count > this.__parent.wrap_line_length &&
          this.__wrap_point_character_count > this.__parent.next_line.__character_count;
      };
      
      OutputLine.prototype._allow_wrap = function() {
        if (this._should_wrap()) {
          this.__parent.add_new_line();
          var next = this.__parent.current_line;
          next.set_indent(this.__wrap_point_indent_count, this.__wrap_point_alignment_count);
          next.__items = this.__items.slice(this.__wrap_point_index);
          this.__items = this.__items.slice(0, this.__wrap_point_index);
      
          next.__character_count += this.__character_count - this.__wrap_point_character_count;
          this.__character_count = this.__wrap_point_character_count;
      
          if (next.__items[0] === " ") {
            next.__items.splice(0, 1);
            next.__character_count -= 1;
          }
          return true;
        }
        return false;
      };
      
      OutputLine.prototype.is_empty = function() {
        return this.__items.length === 0;
      };
      
      OutputLine.prototype.last = function() {
        if (!this.is_empty()) {
          return this.__items[this.__items.length - 1];
        } else {
          return null;
        }
      };
      
      OutputLine.prototype.push = function(item) {
        this.__items.push(item);
        var last_newline_index = item.lastIndexOf('\n');
        if (last_newline_index !== -1) {
          this.__character_count = item.length - last_newline_index;
        } else {
          this.__character_count += item.length;
        }
      };
      
      OutputLine.prototype.pop = function() {
        var item = null;
        if (!this.is_empty()) {
          item = this.__items.pop();
          this.__character_count -= item.length;
        }
        return item;
      };
      
      
      OutputLine.prototype._remove_indent = function() {
        if (this.__indent_count > 0) {
          this.__indent_count -= 1;
          this.__character_count -= this.__parent.indent_size;
        }
      };
      
      OutputLine.prototype._remove_wrap_indent = function() {
        if (this.__wrap_point_indent_count > 0) {
          this.__wrap_point_indent_count -= 1;
        }
      };
      OutputLine.prototype.trim = function() {
        while (this.last() === ' ') {
          this.__items.pop();
          this.__character_count -= 1;
        }
      };
      
      OutputLine.prototype.toString = function() {
        var result = '';
        if (this.is_empty()) {
          if (this.__parent.indent_empty_lines) {
            result = this.__parent.get_indent_string(this.__indent_count);
          }
        } else {
          result = this.__parent.get_indent_string(this.__indent_count, this.__alignment_count);
          result += this.__items.join('');
        }
        return result;
      };
      
      function IndentStringCache(options, baseIndentString) {
        this.__cache = [''];
        this.__indent_size = options.indent_size;
        this.__indent_string = options.indent_char;
        if (!options.indent_with_tabs) {
          this.__indent_string = new Array(options.indent_size + 1).join(options.indent_char);
        }
      
        // Set to null to continue support for auto detection of base indent
        baseIndentString = baseIndentString || '';
        if (options.indent_level > 0) {
          baseIndentString = new Array(options.indent_level + 1).join(this.__indent_string);
        }
      
        this.__base_string = baseIndentString;
        this.__base_string_length = baseIndentString.length;
      }
      
      IndentStringCache.prototype.get_indent_size = function(indent, column) {
        var result = this.__base_string_length;
        column = column || 0;
        if (indent < 0) {
          result = 0;
        }
        result += indent * this.__indent_size;
        result += column;
        return result;
      };
      
      IndentStringCache.prototype.get_indent_string = function(indent_level, column) {
        var result = this.__base_string;
        column = column || 0;
        if (indent_level < 0) {
          indent_level = 0;
          result = '';
        }
        column += indent_level * this.__indent_size;
        this.__ensure_cache(column);
        result += this.__cache[column];
        return result;
      };
      
      IndentStringCache.prototype.__ensure_cache = function(column) {
        while (column >= this.__cache.length) {
          this.__add_column();
        }
      };
      
      IndentStringCache.prototype.__add_column = function() {
        var column = this.__cache.length;
        var indent = 0;
        var result = '';
        if (this.__indent_size && column >= this.__indent_size) {
          indent = Math.floor(column / this.__indent_size);
          column -= indent * this.__indent_size;
          result = new Array(indent + 1).join(this.__indent_string);
        }
        if (column) {
          result += new Array(column + 1).join(' ');
        }
      
        this.__cache.push(result);
      };
      
      function Output(options, baseIndentString) {
        this.__indent_cache = new IndentStringCache(options, baseIndentString);
        this.raw = false;
        this._end_with_newline = options.end_with_newline;
        this.indent_size = options.indent_size;
        this.wrap_line_length = options.wrap_line_length;
        this.indent_empty_lines = options.indent_empty_lines;
        this.__lines = [];
        this.previous_line = null;
        this.current_line = null;
        this.next_line = new OutputLine(this);
        this.space_before_token = false;
        this.non_breaking_space = false;
        this.previous_token_wrapped = false;
        // initialize
        this.__add_outputline();
      }
      
      Output.prototype.__add_outputline = function() {
        this.previous_line = this.current_line;
        this.current_line = this.next_line.clone_empty();
        this.__lines.push(this.current_line);
      };
      
      Output.prototype.get_line_number = function() {
        return this.__lines.length;
      };
      
      Output.prototype.get_indent_string = function(indent, column) {
        return this.__indent_cache.get_indent_string(indent, column);
      };
      
      Output.prototype.get_indent_size = function(indent, column) {
        return this.__indent_cache.get_indent_size(indent, column);
      };
      
      Output.prototype.is_empty = function() {
        return !this.previous_line && this.current_line.is_empty();
      };
      
      Output.prototype.add_new_line = function(force_newline) {
        // never newline at the start of file
        // otherwise, newline only if we didn't just add one or we're forced
        if (this.is_empty() ||
          (!force_newline && this.just_added_newline())) {
          return false;
        }
      
        // if raw output is enabled, don't print additional newlines,
        // but still return True as though you had
        if (!this.raw) {
          this.__add_outputline();
        }
        return true;
      };
      
      Output.prototype.get_code = function(eol) {
        this.trim(true);
      
        // handle some edge cases where the last tokens
        // has text that ends with newline(s)
        var last_item = this.current_line.pop();
        if (last_item) {
          if (last_item[last_item.length - 1] === '\n') {
            last_item = last_item.replace(/\n+$/g, '');
          }
          this.current_line.push(last_item);
        }
      
        if (this._end_with_newline) {
          this.__add_outputline();
        }
      
        var sweet_code = this.__lines.join('\n');
      
        if (eol !== '\n') {
          sweet_code = sweet_code.replace(/[\n]/g, eol);
        }
        return sweet_code;
      };
      
      Output.prototype.set_wrap_point = function() {
        this.current_line._set_wrap_point();
      };
      
      Output.prototype.set_indent = function(indent, alignment) {
        indent = indent || 0;
        alignment = alignment || 0;
      
        // Next line stores alignment values
        this.next_line.set_indent(indent, alignment);
      
        // Never indent your first output indent at the start of the file
        if (this.__lines.length > 1) {
          this.current_line.set_indent(indent, alignment);
          return true;
        }
      
        this.current_line.set_indent();
        return false;
      };
      
      Output.prototype.add_raw_token = function(token) {
        for (var x = 0; x < token.newlines; x++) {
          this.__add_outputline();
        }
        this.current_line.set_indent(-1);
        this.current_line.push(token.whitespace_before);
        this.current_line.push(token.text);
        this.space_before_token = false;
        this.non_breaking_space = false;
        this.previous_token_wrapped = false;
      };
      
      Output.prototype.add_token = function(printable_token) {
        this.__add_space_before_token();
        this.current_line.push(printable_token);
        this.space_before_token = false;
        this.non_breaking_space = false;
        this.previous_token_wrapped = this.current_line._allow_wrap();
      };
      
      Output.prototype.__add_space_before_token = function() {
        if (this.space_before_token && !this.just_added_newline()) {
          if (!this.non_breaking_space) {
            this.set_wrap_point();
          }
          this.current_line.push(' ');
        }
      };
      
      Output.prototype.remove_indent = function(index) {
        var output_length = this.__lines.length;
        while (index < output_length) {
          this.__lines[index]._remove_indent();
          index++;
        }
        this.current_line._remove_wrap_indent();
      };
      
      Output.prototype.trim = function(eat_newlines) {
        eat_newlines = (eat_newlines === undefined) ? false : eat_newlines;
      
        this.current_line.trim();
      
        while (eat_newlines && this.__lines.length > 1 &&
          this.current_line.is_empty()) {
          this.__lines.pop();
          this.current_line = this.__lines[this.__lines.length - 1];
          this.current_line.trim();
        }
      
        this.previous_line = this.__lines.length > 1 ?
          this.__lines[this.__lines.length - 2] : null;
      };
      
      Output.prototype.just_added_newline = function() {
        return this.current_line.is_empty();
      };
      
      Output.prototype.just_added_blankline = function() {
        return this.is_empty() ||
          (this.current_line.is_empty() && this.previous_line.is_empty());
      };
      
      Output.prototype.ensure_empty_line_above = function(starts_with, ends_with) {
        var index = this.__lines.length - 2;
        while (index >= 0) {
          var potentialEmptyLine = this.__lines[index];
          if (potentialEmptyLine.is_empty()) {
            break;
          } else if (potentialEmptyLine.item(0).indexOf(starts_with) !== 0 &&
            potentialEmptyLine.item(-1) !== ends_with) {
            this.__lines.splice(index + 1, 0, new OutputLine(this));
            this.previous_line = this.__lines[this.__lines.length - 2];
            break;
          }
          index--;
        }
      };
      
      module.exports.Output = Output;
      
      
      /***/ }),
      /* 3 */
      /***/ (function(module) {
      
      /*jshint node:true */
      /*
      
        The MIT License (MIT)
      
        Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
      
        Permission 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:
      
        The above copyright notice and this permission notice shall be
        included in all copies or substantial portions of the Software.
      
        THE 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.
      */
      
      
      
      function Token(type, text, newlines, whitespace_before) {
        this.type = type;
        this.text = text;
      
        // comments_before are
        // comments that have a new line before them
        // and may or may not have a newline after
        // this is a set of comments before
        this.comments_before = null; /* inline comment*/
      
      
        // this.comments_after =  new TokenStream(); // no new line before and newline after
        this.newlines = newlines || 0;
        this.whitespace_before = whitespace_before || '';
        this.parent = null;
        this.next = null;
        this.previous = null;
        this.opened = null;
        this.closed = null;
        this.directives = null;
      }
      
      
      module.exports.Token = Token;
      
      
      /***/ }),
      /* 4 */,
      /* 5 */,
      /* 6 */
      /***/ (function(module) {
      
      /*jshint node:true */
      /*
      
        The MIT License (MIT)
      
        Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
      
        Permission 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:
      
        The above copyright notice and this permission notice shall be
        included in all copies or substantial portions of the Software.
      
        THE 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.
      */
      
      
      
      function Options(options, merge_child_field) {
        this.raw_options = _mergeOpts(options, merge_child_field);
      
        // Support passing the source text back with no change
        this.disabled = this._get_boolean('disabled');
      
        this.eol = this._get_characters('eol', 'auto');
        this.end_with_newline = this._get_boolean('end_with_newline');
        this.indent_size = this._get_number('indent_size', 4);
        this.indent_char = this._get_characters('indent_char', ' ');
        this.indent_level = this._get_number('indent_level');
      
        this.preserve_newlines = this._get_boolean('preserve_newlines', true);
        this.max_preserve_newlines = this._get_number('max_preserve_newlines', 32786);
        if (!this.preserve_newlines) {
          this.max_preserve_newlines = 0;
        }
      
        this.indent_with_tabs = this._get_boolean('indent_with_tabs', this.indent_char === '\t');
        if (this.indent_with_tabs) {
          this.indent_char = '\t';
      
          // indent_size behavior changed after 1.8.6
          // It used to be that indent_size would be
          // set to 1 for indent_with_tabs. That is no longer needed and
          // actually doesn't make sense - why not use spaces? Further,
          // that might produce unexpected behavior - tabs being used
          // for single-column alignment. So, when indent_with_tabs is true
          // and indent_size is 1, reset indent_size to 4.
          if (this.indent_size === 1) {
            this.indent_size = 4;
          }
        }
      
        // Backwards compat with 1.3.x
        this.wrap_line_length = this._get_number('wrap_line_length', this._get_number('max_char'));
      
        this.indent_empty_lines = this._get_boolean('indent_empty_lines');
      
        // valid templating languages ['django', 'erb', 'handlebars', 'php', 'smarty']
        // For now, 'auto' = all off for javascript, all on for html (and inline javascript).
        // other values ignored
        this.templating = this._get_selection_list('templating', ['auto', 'none', 'django', 'erb', 'handlebars', 'php', 'smarty'], ['auto']);
      }
      
      Options.prototype._get_array = function(name, default_value) {
        var option_value = this.raw_options[name];
        var result = default_value || [];
        if (typeof option_value === 'object') {
          if (option_value !== null && typeof option_value.concat === 'function') {
            result = option_value.concat();
          }
        } else if (typeof option_value === 'string') {
          result = option_value.split(/[^a-zA-Z0-9_\/\-]+/);
        }
        return result;
      };
      
      Options.prototype._get_boolean = function(name, default_value) {
        var option_value = this.raw_options[name];
        var result = option_value === undefined ? !!default_value : !!option_value;
        return result;
      };
      
      Options.prototype._get_characters = function(name, default_value) {
        var option_value = this.raw_options[name];
        var result = default_value || '';
        if (typeof option_value === 'string') {
          result = option_value.replace(/\\r/, '\r').replace(/\\n/, '\n').replace(/\\t/, '\t');
        }
        return result;
      };
      
      Options.prototype._get_number = function(name, default_value) {
        var option_value = this.raw_options[name];
        default_value = parseInt(default_value, 10);
        if (isNaN(default_value)) {
          default_value = 0;
        }
        var result = parseInt(option_value, 10);
        if (isNaN(result)) {
          result = default_value;
        }
        return result;
      };
      
      Options.prototype._get_selection = function(name, selection_list, default_value) {
        var result = this._get_selection_list(name, selection_list, default_value);
        if (result.length !== 1) {
          throw new Error(
            "Invalid Option Value: The option '" + name + "' can only be one of the following values:\n" +
            selection_list + "\nYou passed in: '" + this.raw_options[name] + "'");
        }
      
        return result[0];
      };
      
      
      Options.prototype._get_selection_list = function(name, selection_list, default_value) {
        if (!selection_list || selection_list.length === 0) {
          throw new Error("Selection list cannot be empty.");
        }
      
        default_value = default_value || [selection_list[0]];
        if (!this._is_valid_selection(default_value, selection_list)) {
          throw new Error("Invalid Default Value!");
        }
      
        var result = this._get_array(name, default_value);
        if (!this._is_valid_selection(result, selection_list)) {
          throw new Error(
            "Invalid Option Value: The option '" + name + "' can contain only the following values:\n" +
            selection_list + "\nYou passed in: '" + this.raw_options[name] + "'");
        }
      
        return result;
      };
      
      Options.prototype._is_valid_selection = function(result, selection_list) {
        return result.length && selection_list.length &&
          !result.some(function(item) { return selection_list.indexOf(item) === -1; });
      };
      
      
      // merges child options up with the parent options object
      // Example: obj = {a: 1, b: {a: 2}}
      //          mergeOpts(obj, 'b')
      //
      //          Returns: {a: 2}
      function _mergeOpts(allOptions, childFieldName) {
        var finalOpts = {};
        allOptions = _normalizeOpts(allOptions);
        var name;
      
        for (name in allOptions) {
          if (name !== childFieldName) {
            finalOpts[name] = allOptions[name];
          }
        }
      
        //merge in the per type settings for the childFieldName
        if (childFieldName && allOptions[childFieldName]) {
          for (name in allOptions[childFieldName]) {
            finalOpts[name] = allOptions[childFieldName][name];
          }
        }
        return finalOpts;
      }
      
      function _normalizeOpts(options) {
        var convertedOpts = {};
        var key;
      
        for (key in options) {
          var newKey = key.replace(/-/g, "_");
          convertedOpts[newKey] = options[key];
        }
        return convertedOpts;
      }
      
      module.exports.Options = Options;
      module.exports.normalizeOpts = _normalizeOpts;
      module.exports.mergeOpts = _mergeOpts;
      
      
      /***/ }),
      /* 7 */,
      /* 8 */
      /***/ (function(module) {
      
      /*jshint node:true */
      /*
      
        The MIT License (MIT)
      
        Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
      
        Permission 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:
      
        The above copyright notice and this permission notice shall be
        included in all copies or substantial portions of the Software.
      
        THE 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.
      */
      
      
      
      var regexp_has_sticky = RegExp.prototype.hasOwnProperty('sticky');
      
      function InputScanner(input_string) {
        this.__input = input_string || '';
        this.__input_length = this.__input.length;
        this.__position = 0;
      }
      
      InputScanner.prototype.restart = function() {
        this.__position = 0;
      };
      
      InputScanner.prototype.back = function() {
        if (this.__position > 0) {
          this.__position -= 1;
        }
      };
      
      InputScanner.prototype.hasNext = function() {
        return this.__position < this.__input_length;
      };
      
      InputScanner.prototype.next = function() {
        var val = null;
        if (this.hasNext()) {
          val = this.__input.charAt(this.__position);
          this.__position += 1;
        }
        return val;
      };
      
      InputScanner.prototype.peek = function(index) {
        var val = null;
        index = index || 0;
        index += this.__position;
        if (index >= 0 && index < this.__input_length) {
          val = this.__input.charAt(index);
        }
        return val;
      };
      
      // This is a JavaScript only helper function (not in python)
      // Javascript doesn't have a match method
      // and not all implementation support "sticky" flag.
      // If they do not support sticky then both this.match() and this.test() method
      // must get the match and check the index of the match.
      // If sticky is supported and set, this method will use it.
      // Otherwise it will check that global is set, and fall back to the slower method.
      InputScanner.prototype.__match = function(pattern, index) {
        pattern.lastIndex = index;
        var pattern_match = pattern.exec(this.__input);
      
        if (pattern_match && !(regexp_has_sticky && pattern.sticky)) {
          if (pattern_match.index !== index) {
            pattern_match = null;
          }
        }
      
        return pattern_match;
      };
      
      InputScanner.prototype.test = function(pattern, index) {
        index = index || 0;
        index += this.__position;
      
        if (index >= 0 && index < this.__input_length) {
          return !!this.__match(pattern, index);
        } else {
          return false;
        }
      };
      
      InputScanner.prototype.testChar = function(pattern, index) {
        // test one character regex match
        var val = this.peek(index);
        pattern.lastIndex = 0;
        return val !== null && pattern.test(val);
      };
      
      InputScanner.prototype.match = function(pattern) {
        var pattern_match = this.__match(pattern, this.__position);
        if (pattern_match) {
          this.__position += pattern_match[0].length;
        } else {
          pattern_match = null;
        }
        return pattern_match;
      };
      
      InputScanner.prototype.read = function(starting_pattern, until_pattern, until_after) {
        var val = '';
        var match;
        if (starting_pattern) {
          match = this.match(starting_pattern);
          if (match) {
            val += match[0];
          }
        }
        if (until_pattern && (match || !starting_pattern)) {
          val += this.readUntil(until_pattern, until_after);
        }
        return val;
      };
      
      InputScanner.prototype.readUntil = function(pattern, until_after) {
        var val = '';
        var match_index = this.__position;
        pattern.lastIndex = this.__position;
        var pattern_match = pattern.exec(this.__input);
        if (pattern_match) {
          match_index = pattern_match.index;
          if (until_after) {
            match_index += pattern_match[0].length;
          }
        } else {
          match_index = this.__input_length;
        }
      
        val = this.__input.substring(this.__position, match_index);
        this.__position = match_index;
        return val;
      };
      
      InputScanner.prototype.readUntilAfter = function(pattern) {
        return this.readUntil(pattern, true);
      };
      
      InputScanner.prototype.get_regexp = function(pattern, match_from) {
        var result = null;
        var flags = 'g';
        if (match_from && regexp_has_sticky) {
          flags = 'y';
        }
        // strings are converted to regexp
        if (typeof pattern === "string" && pattern !== '') {
          // result = new RegExp(pattern.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), flags);
          result = new RegExp(pattern, flags);
        } else if (pattern) {
          result = new RegExp(pattern.source, flags);
        }
        return result;
      };
      
      InputScanner.prototype.get_literal_regexp = function(literal_string) {
        return RegExp(literal_string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'));
      };
      
      /* css beautifier legacy helpers */
      InputScanner.prototype.peekUntilAfter = function(pattern) {
        var start = this.__position;
        var val = this.readUntilAfter(pattern);
        this.__position = start;
        return val;
      };
      
      InputScanner.prototype.lookBack = function(testVal) {
        var start = this.__position - 1;
        return start >= testVal.length && this.__input.substring(start - testVal.length, start)
          .toLowerCase() === testVal;
      };
      
      module.exports.InputScanner = InputScanner;
      
      
      /***/ }),
      /* 9 */
      /***/ (function(module, __unused_webpack_exports, __webpack_require__) {
      
      /*jshint node:true */
      /*
      
        The MIT License (MIT)
      
        Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
      
        Permission 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:
      
        The above copyright notice and this permission notice shall be
        included in all copies or substantial portions of the Software.
      
        THE 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.
      */
      
      
      
      var InputScanner = (__webpack_require__(8).InputScanner);
      var Token = (__webpack_require__(3).Token);
      var TokenStream = (__webpack_require__(10).TokenStream);
      var WhitespacePattern = (__webpack_require__(11).WhitespacePattern);
      
      var TOKEN = {
        START: 'TK_START',
        RAW: 'TK_RAW',
        EOF: 'TK_EOF'
      };
      
      var Tokenizer = function(input_string, options) {
        this._input = new InputScanner(input_string);
        this._options = options || {};
        this.__tokens = null;
      
        this._patterns = {};
        this._patterns.whitespace = new WhitespacePattern(this._input);
      };
      
      Tokenizer.prototype.tokenize = function() {
        this._input.restart();
        this.__tokens = new TokenStream();
      
        this._reset();
      
        var current;
        var previous = new Token(TOKEN.START, '');
        var open_token = null;
        var open_stack = [];
        var comments = new TokenStream();
      
        while (previous.type !== TOKEN.EOF) {
          current = this._get_next_token(previous, open_token);
          while (this._is_comment(current)) {
            comments.add(current);
            current = this._get_next_token(previous, open_token);
          }
      
          if (!comments.isEmpty()) {
            current.comments_before = comments;
            comments = new TokenStream();
          }
      
          current.parent = open_token;
      
          if (this._is_opening(current)) {
            open_stack.push(open_token);
            open_token = current;
          } else if (open_token && this._is_closing(current, open_token)) {
            current.opened = open_token;
            open_token.closed = current;
            open_token = open_stack.pop();
            current.parent = open_token;
          }
      
          current.previous = previous;
          previous.next = current;
      
          this.__tokens.add(current);
          previous = current;
        }
      
        return this.__tokens;
      };
      
      
      Tokenizer.prototype._is_first_token = function() {
        return this.__tokens.isEmpty();
      };
      
      Tokenizer.prototype._reset = function() {};
      
      Tokenizer.prototype._get_next_token = function(previous_token, open_token) { // jshint unused:false
        this._readWhitespace();
        var resulting_string = this._input.read(/.+/g);
        if (resulting_string) {
          return this._create_token(TOKEN.RAW, resulting_string);
        } else {
          return this._create_token(TOKEN.EOF, '');
        }
      };
      
      Tokenizer.prototype._is_comment = function(current_token) { // jshint unused:false
        return false;
      };
      
      Tokenizer.prototype._is_opening = function(current_token) { // jshint unused:false
        return false;
      };
      
      Tokenizer.prototype._is_closing = function(current_token, open_token) { // jshint unused:false
        return false;
      };
      
      Tokenizer.prototype._create_token = function(type, text) {
        var token = new Token(type, text,
          this._patterns.whitespace.newline_count,
          this._patterns.whitespace.whitespace_before_token);
        return token;
      };
      
      Tokenizer.prototype._readWhitespace = function() {
        return this._patterns.whitespace.read();
      };
      
      
      
      module.exports.Tokenizer = Tokenizer;
      module.exports.TOKEN = TOKEN;
      
      
      /***/ }),
      /* 10 */
      /***/ (function(module) {
      
      /*jshint node:true */
      /*
      
        The MIT License (MIT)
      
        Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
      
        Permission 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:
      
        The above copyright notice and this permission notice shall be
        included in all copies or substantial portions of the Software.
      
        THE 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.
      */
      
      
      
      function TokenStream(parent_token) {
        // private
        this.__tokens = [];
        this.__tokens_length = this.__tokens.length;
        this.__position = 0;
        this.__parent_token = parent_token;
      }
      
      TokenStream.prototype.restart = function() {
        this.__position = 0;
      };
      
      TokenStream.prototype.isEmpty = function() {
        return this.__tokens_length === 0;
      };
      
      TokenStream.prototype.hasNext = function() {
        return this.__position < this.__tokens_length;
      };
      
      TokenStream.prototype.next = function() {
        var val = null;
        if (this.hasNext()) {
          val = this.__tokens[this.__position];
          this.__position += 1;
        }
        return val;
      };
      
      TokenStream.prototype.peek = function(index) {
        var val = null;
        index = index || 0;
        index += this.__position;
        if (index >= 0 && index < this.__tokens_length) {
          val = this.__tokens[index];
        }
        return val;
      };
      
      TokenStream.prototype.add = function(token) {
        if (this.__parent_token) {
          token.parent = this.__parent_token;
        }
        this.__tokens.push(token);
        this.__tokens_length += 1;
      };
      
      module.exports.TokenStream = TokenStream;
      
      
      /***/ }),
      /* 11 */
      /***/ (function(module, __unused_webpack_exports, __webpack_require__) {
      
      /*jshint node:true */
      /*
      
        The MIT License (MIT)
      
        Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
      
        Permission 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:
      
        The above copyright notice and this permission notice shall be
        included in all copies or substantial portions of the Software.
      
        THE 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.
      */
      
      
      
      var Pattern = (__webpack_require__(12).Pattern);
      
      function WhitespacePattern(input_scanner, parent) {
        Pattern.call(this, input_scanner, parent);
        if (parent) {
          this._line_regexp = this._input.get_regexp(parent._line_regexp);
        } else {
          this.__set_whitespace_patterns('', '');
        }
      
        this.newline_count = 0;
        this.whitespace_before_token = '';
      }
      WhitespacePattern.prototype = new Pattern();
      
      WhitespacePattern.prototype.__set_whitespace_patterns = function(whitespace_chars, newline_chars) {
        whitespace_chars += '\\t ';
        newline_chars += '\\n\\r';
      
        this._match_pattern = this._input.get_regexp(
          '[' + whitespace_chars + newline_chars + ']+', true);
        this._newline_regexp = this._input.get_regexp(
          '\\r\\n|[' + newline_chars + ']');
      };
      
      WhitespacePattern.prototype.read = function() {
        this.newline_count = 0;
        this.whitespace_before_token = '';
      
        var resulting_string = this._input.read(this._match_pattern);
        if (resulting_string === ' ') {
          this.whitespace_before_token = ' ';
        } else if (resulting_string) {
          var matches = this.__split(this._newline_regexp, resulting_string);
          this.newline_count = matches.length - 1;
          this.whitespace_before_token = matches[this.newline_count];
        }
      
        return resulting_string;
      };
      
      WhitespacePattern.prototype.matching = function(whitespace_chars, newline_chars) {
        var result = this._create();
        result.__set_whitespace_patterns(whitespace_chars, newline_chars);
        result._update();
        return result;
      };
      
      WhitespacePattern.prototype._create = function() {
        return new WhitespacePattern(this._input, this);
      };
      
      WhitespacePattern.prototype.__split = function(regexp, input_string) {
        regexp.lastIndex = 0;
        var start_index = 0;
        var result = [];
        var next_match = regexp.exec(input_string);
        while (next_match) {
          result.push(input_string.substring(start_index, next_match.index));
          start_index = next_match.index + next_match[0].length;
          next_match = regexp.exec(input_string);
        }
      
        if (start_index < input_string.length) {
          result.push(input_string.substring(start_index, input_string.length));
        } else {
          result.push('');
        }
      
        return result;
      };
      
      
      
      module.exports.WhitespacePattern = WhitespacePattern;
      
      
      /***/ }),
      /* 12 */
      /***/ (function(module) {
      
      /*jshint node:true */
      /*
      
        The MIT License (MIT)
      
        Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
      
        Permission 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:
      
        The above copyright notice and this permission notice shall be
        included in all copies or substantial portions of the Software.
      
        THE 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.
      */
      
      
      
      function Pattern(input_scanner, parent) {
        this._input = input_scanner;
        this._starting_pattern = null;
        this._match_pattern = null;
        this._until_pattern = null;
        this._until_after = false;
      
        if (parent) {
          this._starting_pattern = this._input.get_regexp(parent._starting_pattern, true);
          this._match_pattern = this._input.get_regexp(parent._match_pattern, true);
          this._until_pattern = this._input.get_regexp(parent._until_pattern);
          this._until_after = parent._until_after;
        }
      }
      
      Pattern.prototype.read = function() {
        var result = this._input.read(this._starting_pattern);
        if (!this._starting_pattern || result) {
          result += this._input.read(this._match_pattern, this._until_pattern, this._until_after);
        }
        return result;
      };
      
      Pattern.prototype.read_match = function() {
        return this._input.match(this._match_pattern);
      };
      
      Pattern.prototype.until_after = function(pattern) {
        var result = this._create();
        result._until_after = true;
        result._until_pattern = this._input.get_regexp(pattern);
        result._update();
        return result;
      };
      
      Pattern.prototype.until = function(pattern) {
        var result = this._create();
        result._until_after = false;
        result._until_pattern = this._input.get_regexp(pattern);
        result._update();
        return result;
      };
      
      Pattern.prototype.starting_with = function(pattern) {
        var result = this._create();
        result._starting_pattern = this._input.get_regexp(pattern, true);
        result._update();
        return result;
      };
      
      Pattern.prototype.matching = function(pattern) {
        var result = this._create();
        result._match_pattern = this._input.get_regexp(pattern, true);
        result._update();
        return result;
      };
      
      Pattern.prototype._create = function() {
        return new Pattern(this._input, this);
      };
      
      Pattern.prototype._update = function() {};
      
      module.exports.Pattern = Pattern;
      
      
      /***/ }),
      /* 13 */
      /***/ (function(module) {
      
      /*jshint node:true */
      /*
      
        The MIT License (MIT)
      
        Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
      
        Permission 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:
      
        The above copyright notice and this permission notice shall be
        included in all copies or substantial portions of the Software.
      
        THE 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.
      */
      
      
      
      function Directives(start_block_pattern, end_block_pattern) {
        start_block_pattern = typeof start_block_pattern === 'string' ? start_block_pattern : start_block_pattern.source;
        end_block_pattern = typeof end_block_pattern === 'string' ? end_block_pattern : end_block_pattern.source;
        this.__directives_block_pattern = new RegExp(start_block_pattern + / beautify( \w+[:]\w+)+ /.source + end_block_pattern, 'g');
        this.__directive_pattern = / (\w+)[:](\w+)/g;
      
        this.__directives_end_ignore_pattern = new RegExp(start_block_pattern + /\sbeautify\signore:end\s/.source + end_block_pattern, 'g');
      }
      
      Directives.prototype.get_directives = function(text) {
        if (!text.match(this.__directives_block_pattern)) {
          return null;
        }
      
        var directives = {};
        this.__directive_pattern.lastIndex = 0;
        var directive_match = this.__directive_pattern.exec(text);
      
        while (directive_match) {
          directives[directive_match[1]] = directive_match[2];
          directive_match = this.__directive_pattern.exec(text);
        }
      
        return directives;
      };
      
      Directives.prototype.readIgnored = function(input) {
        return input.readUntilAfter(this.__directives_end_ignore_pattern);
      };
      
      
      module.exports.Directives = Directives;
      
      
      /***/ }),
      /* 14 */
      /***/ (function(module, __unused_webpack_exports, __webpack_require__) {
      
      /*jshint node:true */
      /*
      
        The MIT License (MIT)
      
        Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
      
        Permission 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:
      
        The above copyright notice and this permission notice shall be
        included in all copies or substantial portions of the Software.
      
        THE 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.
      */
      
      
      
      var Pattern = (__webpack_require__(12).Pattern);
      
      
      var template_names = {
        django: false,
        erb: false,
        handlebars: false,
        php: false,
        smarty: false
      };
      
      // This lets templates appear anywhere we would do a readUntil
      // The cost is higher but it is pay to play.
      function TemplatablePattern(input_scanner, parent) {
        Pattern.call(this, input_scanner, parent);
        this.__template_pattern = null;
        this._disabled = Object.assign({}, template_names);
        this._excluded = Object.assign({}, template_names);
      
        if (parent) {
          this.__template_pattern = this._input.get_regexp(parent.__template_pattern);
          this._excluded = Object.assign(this._excluded, parent._excluded);
          this._disabled = Object.assign(this._disabled, parent._disabled);
        }
        var pattern = new Pattern(input_scanner);
        this.__patterns = {
          handlebars_comment: pattern.starting_with(/{{!--/).until_after(/--}}/),
          handlebars_unescaped: pattern.starting_with(/{{{/).until_after(/}}}/),
          handlebars: pattern.starting_with(/{{/).until_after(/}}/),
          php: pattern.starting_with(/<\?(?:[= ]|php)/).until_after(/\?>/),
          erb: pattern.starting_with(/<%[^%]/).until_after(/[^%]%>/),
          // django coflicts with handlebars a bit.
          django: pattern.starting_with(/{%/).until_after(/%}/),
          django_value: pattern.starting_with(/{{/).until_after(/}}/),
          django_comment: pattern.starting_with(/{#/).until_after(/#}/),
          smarty: pattern.starting_with(/{(?=[^}{\s\n])/).until_after(/[^\s\n]}/),
          smarty_comment: pattern.starting_with(/{\*/).until_after(/\*}/),
          smarty_literal: pattern.starting_with(/{literal}/).until_after(/{\/literal}/)
        };
      }
      TemplatablePattern.prototype = new Pattern();
      
      TemplatablePattern.prototype._create = function() {
        return new TemplatablePattern(this._input, this);
      };
      
      TemplatablePattern.prototype._update = function() {
        this.__set_templated_pattern();
      };
      
      TemplatablePattern.prototype.disable = function(language) {
        var result = this._create();
        result._disabled[language] = true;
        result._update();
        return result;
      };
      
      TemplatablePattern.prototype.read_options = function(options) {
        var result = this._create();
        for (var language in template_names) {
          result._disabled[language] = options.templating.indexOf(language) === -1;
        }
        result._update();
        return result;
      };
      
      TemplatablePattern.prototype.exclude = function(language) {
        var result = this._create();
        result._excluded[language] = true;
        result._update();
        return result;
      };
      
      TemplatablePattern.prototype.read = function() {
        var result = '';
        if (this._match_pattern) {
          result = this._input.read(this._starting_pattern);
        } else {
          result = this._input.read(this._starting_pattern, this.__template_pattern);
        }
        var next = this._read_template();
        while (next) {
          if (this._match_pattern) {
            next += this._input.read(this._match_pattern);
          } else {
            next += this._input.readUntil(this.__template_pattern);
          }
          result += next;
          next = this._read_template();
        }
      
        if (this._until_after) {
          result += this._input.readUntilAfter(this._until_pattern);
        }
        return result;
      };
      
      TemplatablePattern.prototype.__set_templated_pattern = function() {
        var items = [];
      
        if (!this._disabled.php) {
          items.push(this.__patterns.php._starting_pattern.source);
        }
        if (!this._disabled.handlebars) {
          items.push(this.__patterns.handlebars._starting_pattern.source);
        }
        if (!this._disabled.erb) {
          items.push(this.__patterns.erb._starting_pattern.source);
        }
        if (!this._disabled.django) {
          items.push(this.__patterns.django._starting_pattern.source);
          // The starting pattern for django is more complex because it has different
          // patterns for value, comment, and other sections
          items.push(this.__patterns.django_value._starting_pattern.source);
          items.push(this.__patterns.django_comment._starting_pattern.source);
        }
        if (!this._disabled.smarty) {
          items.push(this.__patterns.smarty._starting_pattern.source);
        }
      
        if (this._until_pattern) {
          items.push(this._until_pattern.source);
        }
        this.__template_pattern = this._input.get_regexp('(?:' + items.join('|') + ')');
      };
      
      TemplatablePattern.prototype._read_template = function() {
        var resulting_string = '';
        var c = this._input.peek();
        if (c === '<') {
          var peek1 = this._input.peek(1);
          //if we're in a comment, do something special
          // We treat all comments as literals, even more than preformatted tags
          // we just look for the appropriate close tag
          if (!this._disabled.php && !this._excluded.php && peek1 === '?') {
            resulting_string = resulting_string ||
              this.__patterns.php.read();
          }
          if (!this._disabled.erb && !this._excluded.erb && peek1 === '%') {
            resulting_string = resulting_string ||
              this.__patterns.erb.read();
          }
        } else if (c === '{') {
          if (!this._disabled.handlebars && !this._excluded.handlebars) {
            resulting_string = resulting_string ||
              this.__patterns.handlebars_comment.read();
            resulting_string = resulting_string ||
              this.__patterns.handlebars_unescaped.read();
            resulting_string = resulting_string ||
              this.__patterns.handlebars.read();
          }
          if (!this._disabled.django) {
            // django coflicts with handlebars a bit.
            if (!this._excluded.django && !this._excluded.handlebars) {
              resulting_string = resulting_string ||
                this.__patterns.django_value.read();
            }
            if (!this._excluded.django) {
              resulting_string = resulting_string ||
                this.__patterns.django_comment.read();
              resulting_string = resulting_string ||
                this.__patterns.django.read();
            }
          }
          if (!this._disabled.smarty) {
            // smarty cannot be enabled with django or handlebars enabled
            if (this._disabled.django && this._disabled.handlebars) {
              resulting_string = resulting_string ||
                this.__patterns.smarty_comment.read();
              resulting_string = resulting_string ||
                this.__patterns.smarty_literal.read();
              resulting_string = resulting_string ||
                this.__patterns.smarty.read();
            }
          }
        }
        return resulting_string;
      };
      
      
      module.exports.TemplatablePattern = TemplatablePattern;
      
      
      /***/ }),
      /* 15 */,
      /* 16 */,
      /* 17 */,
      /* 18 */
      /***/ (function(module, __unused_webpack_exports, __webpack_require__) {
      
      /*jshint node:true */
      /*
      
        The MIT License (MIT)
      
        Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
      
        Permission 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:
      
        The above copyright notice and this permission notice shall be
        included in all copies or substantial portions of the Software.
      
        THE 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.
      */
      
      
      
      var Beautifier = (__webpack_require__(19).Beautifier),
        Options = (__webpack_require__(20).Options);
      
      function style_html(html_source, options, js_beautify, css_beautify) {
        var beautifier = new Beautifier(html_source, options, js_beautify, css_beautify);
        return beautifier.beautify();
      }
      
      module.exports = style_html;
      module.exports.defaultOptions = function() {
        return new Options();
      };
      
      
      /***/ }),
      /* 19 */
      /***/ (function(module, __unused_webpack_exports, __webpack_require__) {
      
      /*jshint node:true */
      /*
      
        The MIT License (MIT)
      
        Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
      
        Permission 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:
      
        The above copyright notice and this permission notice shall be
        included in all copies or substantial portions of the Software.
      
        THE 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.
      */
      
      
      
      var Options = (__webpack_require__(20).Options);
      var Output = (__webpack_require__(2).Output);
      var Tokenizer = (__webpack_require__(21).Tokenizer);
      var TOKEN = (__webpack_require__(21).TOKEN);
      
      var lineBreak = /\r\n|[\r\n]/;
      var allLineBreaks = /\r\n|[\r\n]/g;
      
      var Printer = function(options, base_indent_string) { //handles input/output and some other printing functions
      
        this.indent_level = 0;
        this.alignment_size = 0;
        this.max_preserve_newlines = options.max_preserve_newlines;
        this.preserve_newlines = options.preserve_newlines;
      
        this._output = new Output(options, base_indent_string);
      
      };
      
      Printer.prototype.current_line_has_match = function(pattern) {
        return this._output.current_line.has_match(pattern);
      };
      
      Printer.prototype.set_space_before_token = function(value, non_breaking) {
        this._output.space_before_token = value;
        this._output.non_breaking_space = non_breaking;
      };
      
      Printer.prototype.set_wrap_point = function() {
        this._output.set_indent(this.indent_level, this.alignment_size);
        this._output.set_wrap_point();
      };
      
      
      Printer.prototype.add_raw_token = function(token) {
        this._output.add_raw_token(token);
      };
      
      Printer.prototype.print_preserved_newlines = function(raw_token) {
        var newlines = 0;
        if (raw_token.type !== TOKEN.TEXT && raw_token.previous.type !== TOKEN.TEXT) {
          newlines = raw_token.newlines ? 1 : 0;
        }
      
        if (this.preserve_newlines) {
          newlines = raw_token.newlines < this.max_preserve_newlines + 1 ? raw_token.newlines : this.max_preserve_newlines + 1;
        }
        for (var n = 0; n < newlines; n++) {
          this.print_newline(n > 0);
        }
      
        return newlines !== 0;
      };
      
      Printer.prototype.traverse_whitespace = function(raw_token) {
        if (raw_token.whitespace_before || raw_token.newlines) {
          if (!this.print_preserved_newlines(raw_token)) {
            this._output.space_before_token = true;
          }
          return true;
        }
        return false;
      };
      
      Printer.prototype.previous_token_wrapped = function() {
        return this._output.previous_token_wrapped;
      };
      
      Printer.prototype.print_newline = function(force) {
        this._output.add_new_line(force);
      };
      
      Printer.prototype.print_token = function(token) {
        if (token.text) {
          this._output.set_indent(this.indent_level, this.alignment_size);
          this._output.add_token(token.text);
        }
      };
      
      Printer.prototype.indent = function() {
        this.indent_level++;
      };
      
      Printer.prototype.get_full_indent = function(level) {
        level = this.indent_level + (level || 0);
        if (level < 1) {
          return '';
        }
      
        return this._output.get_indent_string(level);
      };
      
      var get_type_attribute = function(start_token) {
        var result = null;
        var raw_token = start_token.next;
      
        // Search attributes for a type attribute
        while (raw_token.type !== TOKEN.EOF && start_token.closed !== raw_token) {
          if (raw_token.type === TOKEN.ATTRIBUTE && raw_token.text === 'type') {
            if (raw_token.next && raw_token.next.type === TOKEN.EQUALS &&
              raw_token.next.next && raw_token.next.next.type === TOKEN.VALUE) {
              result = raw_token.next.next.text;
            }
            break;
          }
          raw_token = raw_token.next;
        }
      
        return result;
      };
      
      var get_custom_beautifier_name = function(tag_check, raw_token) {
        var typeAttribute = null;
        var result = null;
      
        if (!raw_token.closed) {
          return null;
        }
      
        if (tag_check === 'script') {
          typeAttribute = 'text/javascript';
        } else if (tag_check === 'style') {
          typeAttribute = 'text/css';
        }
      
        typeAttribute = get_type_attribute(raw_token) || typeAttribute;
      
        // For script and style tags that have a type attribute, only enable custom beautifiers for matching values
        // For those without a type attribute use default;
        if (typeAttribute.search('text/css') > -1) {
          result = 'css';
        } else if (typeAttribute.search(/module|((text|application|dojo)\/(x-)?(javascript|ecmascript|jscript|livescript|(ld\+)?json|method|aspect))/) > -1) {
          result = 'javascript';
        } else if (typeAttribute.search(/(text|application|dojo)\/(x-)?(html)/) > -1) {
          result = 'html';
        } else if (typeAttribute.search(/test\/null/) > -1) {
          // Test only mime-type for testing the beautifier when null is passed as beautifing function
          result = 'null';
        }
      
        return result;
      };
      
      function in_array(what, arr) {
        return arr.indexOf(what) !== -1;
      }
      
      function TagFrame(parent, parser_token, indent_level) {
        this.parent = parent || null;
        this.tag = parser_token ? parser_token.tag_name : '';
        this.indent_level = indent_level || 0;
        this.parser_token = parser_token || null;
      }
      
      function TagStack(printer) {
        this._printer = printer;
        this._current_frame = null;
      }
      
      TagStack.prototype.get_parser_token = function() {
        return this._current_frame ? this._current_frame.parser_token : null;
      };
      
      TagStack.prototype.record_tag = function(parser_token) { //function to record a tag and its parent in this.tags Object
        var new_frame = new TagFrame(this._current_frame, parser_token, this._printer.indent_level);
        this._current_frame = new_frame;
      };
      
      TagStack.prototype._try_pop_frame = function(frame) { //function to retrieve the opening tag to the corresponding closer
        var parser_token = null;
      
        if (frame) {
          parser_token = frame.parser_token;
          this._printer.indent_level = frame.indent_level;
          this._current_frame = frame.parent;
        }
      
        return parser_token;
      };
      
      TagStack.prototype._get_frame = function(tag_list, stop_list) { //function to retrieve the opening tag to the corresponding closer
        var frame = this._current_frame;
      
        while (frame) { //till we reach '' (the initial value);
          if (tag_list.indexOf(frame.tag) !== -1) { //if this is it use it
            break;
          } else if (stop_list && stop_list.indexOf(frame.tag) !== -1) {
            frame = null;
            break;
          }
          frame = frame.parent;
        }
      
        return frame;
      };
      
      TagStack.prototype.try_pop = function(tag, stop_list) { //function to retrieve the opening tag to the corresponding closer
        var frame = this._get_frame([tag], stop_list);
        return this._try_pop_frame(frame);
      };
      
      TagStack.prototype.indent_to_tag = function(tag_list) {
        var frame = this._get_frame(tag_list);
        if (frame) {
          this._printer.indent_level = frame.indent_level;
        }
      };
      
      function Beautifier(source_text, options, js_beautify, css_beautify) {
        //Wrapper function to invoke all the necessary constructors and deal with the output.
        this._source_text = source_text || '';
        options = options || {};
        this._js_beautify = js_beautify;
        this._css_beautify = css_beautify;
        this._tag_stack = null;
      
        // Allow the setting of language/file-type specific options
        // with inheritance of overall settings
        var optionHtml = new Options(options, 'html');
      
        this._options = optionHtml;
      
        this._is_wrap_attributes_force = this._options.wrap_attributes.substr(0, 'force'.length) === 'force';
        this._is_wrap_attributes_force_expand_multiline = (this._options.wrap_attributes === 'force-expand-multiline');
        this._is_wrap_attributes_force_aligned = (this._options.wrap_attributes === 'force-aligned');
        this._is_wrap_attributes_aligned_multiple = (this._options.wrap_attributes === 'aligned-multiple');
        this._is_wrap_attributes_preserve = this._options.wrap_attributes.substr(0, 'preserve'.length) === 'preserve';
        this._is_wrap_attributes_preserve_aligned = (this._options.wrap_attributes === 'preserve-aligned');
      }
      
      Beautifier.prototype.beautify = function() {
      
        // if disabled, return the input unchanged.
        if (this._options.disabled) {
          return this._source_text;
        }
      
        var source_text = this._source_text;
        var eol = this._options.eol;
        if (this._options.eol === 'auto') {
          eol = '\n';
          if (source_text && lineBreak.test(source_text)) {
            eol = source_text.match(lineBreak)[0];
          }
        }
      
        // HACK: newline parsing inconsistent. This brute force normalizes the input.
        source_text = source_text.replace(allLineBreaks, '\n');
      
        var baseIndentString = source_text.match(/^[\t ]*/)[0];
      
        var last_token = {
          text: '',
          type: ''
        };
      
        var last_tag_token = new TagOpenParserToken();
      
        var printer = new Printer(this._options, baseIndentString);
        var tokens = new Tokenizer(source_text, this._options).tokenize();
      
        this._tag_stack = new TagStack(printer);
      
        var parser_token = null;
        var raw_token = tokens.next();
        while (raw_token.type !== TOKEN.EOF) {
      
          if (raw_token.type === TOKEN.TAG_OPEN || raw_token.type === TOKEN.COMMENT) {
            parser_token = this._handle_tag_open(printer, raw_token, last_tag_token, last_token);
            last_tag_token = parser_token;
          } else if ((raw_token.type === TOKEN.ATTRIBUTE || raw_token.type === TOKEN.EQUALS || raw_token.type === TOKEN.VALUE) ||
            (raw_token.type === TOKEN.TEXT && !last_tag_token.tag_complete)) {
            parser_token = this._handle_inside_tag(printer, raw_token, last_tag_token, tokens);
          } else if (raw_token.type === TOKEN.TAG_CLOSE) {
            parser_token = this._handle_tag_close(printer, raw_token, last_tag_token);
          } else if (raw_token.type === TOKEN.TEXT) {
            parser_token = this._handle_text(printer, raw_token, last_tag_token);
          } else {
            // This should never happen, but if it does. Print the raw token
            printer.add_raw_token(raw_token);
          }
      
          last_token = parser_token;
      
          raw_token = tokens.next();
        }
        var sweet_code = printer._output.get_code(eol);
      
        return sweet_code;
      };
      
      Beautifier.prototype._handle_tag_close = function(printer, raw_token, last_tag_token) {
        var parser_token = {
          text: raw_token.text,
          type: raw_token.type
        };
        printer.alignment_size = 0;
        last_tag_token.tag_complete = true;
      
        printer.set_space_before_token(raw_token.newlines || raw_token.whitespace_before !== '', true);
        if (last_tag_token.is_unformatted) {
          printer.add_raw_token(raw_token);
        } else {
          if (last_tag_token.tag_start_char === '<') {
            printer.set_space_before_token(raw_token.text[0] === '/', true); // space before />, no space before >
            if (this._is_wrap_attributes_force_expand_multiline && last_tag_token.has_wrapped_attrs) {
              printer.print_newline(false);
            }
          }
          printer.print_token(raw_token);
      
        }
      
        if (last_tag_token.indent_content &&
          !(last_tag_token.is_unformatted || last_tag_token.is_content_unformatted)) {
          printer.indent();
      
          // only indent once per opened tag
          last_tag_token.indent_content = false;
        }
      
        if (!last_tag_token.is_inline_element &&
          !(last_tag_token.is_unformatted || last_tag_token.is_content_unformatted)) {
          printer.set_wrap_point();
        }
      
        return parser_token;
      };
      
      Beautifier.prototype._handle_inside_tag = function(printer, raw_token, last_tag_token, tokens) {
        var wrapped = last_tag_token.has_wrapped_attrs;
        var parser_token = {
          text: raw_token.text,
          type: raw_token.type
        };
      
        printer.set_space_before_token(raw_token.newlines || raw_token.whitespace_before !== '', true);
        if (last_tag_token.is_unformatted) {
          printer.add_raw_token(raw_token);
        } else if (last_tag_token.tag_start_char === '{' && raw_token.type === TOKEN.TEXT) {
          // For the insides of handlebars allow newlines or a single space between open and contents
          if (printer.print_preserved_newlines(raw_token)) {
            raw_token.newlines = 0;
            printer.add_raw_token(raw_token);
          } else {
            printer.print_token(raw_token);
          }
        } else {
          if (raw_token.type === TOKEN.ATTRIBUTE) {
            printer.set_space_before_token(true);
            last_tag_token.attr_count += 1;
          } else if (raw_token.type === TOKEN.EQUALS) { //no space before =
            printer.set_space_before_token(false);
          } else if (raw_token.type === TOKEN.VALUE && raw_token.previous.type === TOKEN.EQUALS) { //no space before value
            printer.set_space_before_token(false);
          }
      
          if (raw_token.type === TOKEN.ATTRIBUTE && last_tag_token.tag_start_char === '<') {
            if (this._is_wrap_attributes_preserve || this._is_wrap_attributes_preserve_aligned) {
              printer.traverse_whitespace(raw_token);
              wrapped = wrapped || raw_token.newlines !== 0;
            }
      
      
            if (this._is_wrap_attributes_force) {
              var force_attr_wrap = last_tag_token.attr_count > 1;
              if (this._is_wrap_attributes_force_expand_multiline && last_tag_token.attr_count === 1) {
                var is_only_attribute = true;
                var peek_index = 0;
                var peek_token;
                do {
                  peek_token = tokens.peek(peek_index);
                  if (peek_token.type === TOKEN.ATTRIBUTE) {
                    is_only_attribute = false;
                    break;
                  }
                  peek_index += 1;
                } while (peek_index < 4 && peek_token.type !== TOKEN.EOF && peek_token.type !== TOKEN.TAG_CLOSE);
      
                force_attr_wrap = !is_only_attribute;
              }
      
              if (force_attr_wrap) {
                printer.print_newline(false);
                wrapped = true;
              }
            }
          }
          printer.print_token(raw_token);
          wrapped = wrapped || printer.previous_token_wrapped();
          last_tag_token.has_wrapped_attrs = wrapped;
        }
        return parser_token;
      };
      
      Beautifier.prototype._handle_text = function(printer, raw_token, last_tag_token) {
        var parser_token = {
          text: raw_token.text,
          type: 'TK_CONTENT'
        };
        if (last_tag_token.custom_beautifier_name) { //check if we need to format javascript
          this._print_custom_beatifier_text(printer, raw_token, last_tag_token);
        } else if (last_tag_token.is_unformatted || last_tag_token.is_content_unformatted) {
          printer.add_raw_token(raw_token);
        } else {
          printer.traverse_whitespace(raw_token);
          printer.print_token(raw_token);
        }
        return parser_token;
      };
      
      Beautifier.prototype._print_custom_beatifier_text = function(printer, raw_token, last_tag_token) {
        var local = this;
        if (raw_token.text !== '') {
      
          var text = raw_token.text,
            _beautifier,
            script_indent_level = 1,
            pre = '',
            post = '';
          if (last_tag_token.custom_beautifier_name === 'javascript' && typeof this._js_beautify === 'function') {
            _beautifier = this._js_beautify;
          } else if (last_tag_token.custom_beautifier_name === 'css' && typeof this._css_beautify === 'function') {
            _beautifier = this._css_beautify;
          } else if (last_tag_token.custom_beautifier_name === 'html') {
            _beautifier = function(html_source, options) {
              var beautifier = new Beautifier(html_source, options, local._js_beautify, local._css_beautify);
              return beautifier.beautify();
            };
          }
      
          if (this._options.indent_scripts === "keep") {
            script_indent_level = 0;
          } else if (this._options.indent_scripts === "separate") {
            script_indent_level = -printer.indent_level;
          }
      
          var indentation = printer.get_full_indent(script_indent_level);
      
          // if there is at least one empty line at the end of this text, strip it
          // we'll be adding one back after the text but before the containing tag.
          text = text.replace(/\n[ \t]*$/, '');
      
          // Handle the case where content is wrapped in a comment or cdata.
          if (last_tag_token.custom_beautifier_name !== 'html' &&
            text[0] === '<' && text.match(/^(<!--|<!\[CDATA\[)/)) {
            var matched = /^(<!--[^\n]*|<!\[CDATA\[)(\n?)([ \t\n]*)([\s\S]*)(-->|]]>)$/.exec(text);
      
            // if we start to wrap but don't finish, print raw
            if (!matched) {
              printer.add_raw_token(raw_token);
              return;
            }
      
            pre = indentation + matched[1] + '\n';
            text = matched[4];
            if (matched[5]) {
              post = indentation + matched[5];
            }
      
            // if there is at least one empty line at the end of this text, strip it
            // we'll be adding one back after the text but before the containing tag.
            text = text.replace(/\n[ \t]*$/, '');
      
            if (matched[2] || matched[3].indexOf('\n') !== -1) {
              // if the first line of the non-comment text has spaces
              // use that as the basis for indenting in null case.
              matched = matched[3].match(/[ \t]+$/);
              if (matched) {
                raw_token.whitespace_before = matched[0];
              }
            }
          }
      
          if (text) {
            if (_beautifier) {
      
              // call the Beautifier if avaliable
              var Child_options = function() {
                this.eol = '\n';
              };
              Child_options.prototype = this._options.raw_options;
              var child_options = new Child_options();
              text = _beautifier(indentation + text, child_options);
            } else {
              // simply indent the string otherwise
              var white = raw_token.whitespace_before;
              if (white) {
                text = text.replace(new RegExp('\n(' + white + ')?', 'g'), '\n');
              }
      
              text = indentation + text.replace(/\n/g, '\n' + indentation);
            }
          }
      
          if (pre) {
            if (!text) {
              text = pre + post;
            } else {
              text = pre + text + '\n' + post;
            }
          }
      
          printer.print_newline(false);
          if (text) {
            raw_token.text = text;
            raw_token.whitespace_before = '';
            raw_token.newlines = 0;
            printer.add_raw_token(raw_token);
            printer.print_newline(true);
          }
        }
      };
      
      Beautifier.prototype._handle_tag_open = function(printer, raw_token, last_tag_token, last_token) {
        var parser_token = this._get_tag_open_token(raw_token);
      
        if ((last_tag_token.is_unformatted || last_tag_token.is_content_unformatted) &&
          !last_tag_token.is_empty_element &&
          raw_token.type === TOKEN.TAG_OPEN && raw_token.text.indexOf('</') === 0) {
          // End element tags for unformatted or content_unformatted elements
          // are printed raw to keep any newlines inside them exactly the same.
          printer.add_raw_token(raw_token);
          parser_token.start_tag_token = this._tag_stack.try_pop(parser_token.tag_name);
        } else {
          printer.traverse_whitespace(raw_token);
          this._set_tag_position(printer, raw_token, parser_token, last_tag_token, last_token);
          if (!parser_token.is_inline_element) {
            printer.set_wrap_point();
          }
          printer.print_token(raw_token);
        }
      
        //indent attributes an auto, forced, aligned or forced-align line-wrap
        if (this._is_wrap_attributes_force_aligned || this._is_wrap_attributes_aligned_multiple || this._is_wrap_attributes_preserve_aligned) {
          parser_token.alignment_size = raw_token.text.length + 1;
        }
      
        if (!parser_token.tag_complete && !parser_token.is_unformatted) {
          printer.alignment_size = parser_token.alignment_size;
        }
      
        return parser_token;
      };
      
      var TagOpenParserToken = function(parent, raw_token) {
        this.parent = parent || null;
        this.text = '';
        this.type = 'TK_TAG_OPEN';
        this.tag_name = '';
        this.is_inline_element = false;
        this.is_unformatted = false;
        this.is_content_unformatted = false;
        this.is_empty_element = false;
        this.is_start_tag = false;
        this.is_end_tag = false;
        this.indent_content = false;
        this.multiline_content = false;
        this.custom_beautifier_name = null;
        this.start_tag_token = null;
        this.attr_count = 0;
        this.has_wrapped_attrs = false;
        this.alignment_size = 0;
        this.tag_complete = false;
        this.tag_start_char = '';
        this.tag_check = '';
      
        if (!raw_token) {
          this.tag_complete = true;
        } else {
          var tag_check_match;
      
          this.tag_start_char = raw_token.text[0];
          this.text = raw_token.text;
      
          if (this.tag_start_char === '<') {
            tag_check_match = raw_token.text.match(/^<([^\s>]*)/);
            this.tag_check = tag_check_match ? tag_check_match[1] : '';
          } else {
            tag_check_match = raw_token.text.match(/^{{~?(?:[\^]|#\*?)?([^\s}]+)/);
            this.tag_check = tag_check_match ? tag_check_match[1] : '';
      
            // handle "{{#> myPartial}}" or "{{~#> myPartial}}"
            if ((raw_token.text.startsWith('{{#>') || raw_token.text.startsWith('{{~#>')) && this.tag_check[0] === '>') {
              if (this.tag_check === '>' && raw_token.next !== null) {
                this.tag_check = raw_token.next.text.split(' ')[0];
              } else {
                this.tag_check = raw_token.text.split('>')[1];
              }
            }
          }
      
          this.tag_check = this.tag_check.toLowerCase();
      
          if (raw_token.type === TOKEN.COMMENT) {
            this.tag_complete = true;
          }
      
          this.is_start_tag = this.tag_check.charAt(0) !== '/';
          this.tag_name = !this.is_start_tag ? this.tag_check.substr(1) : this.tag_check;
          this.is_end_tag = !this.is_start_tag ||
            (raw_token.closed && raw_token.closed.text === '/>');
      
          // if whitespace handler ~ included (i.e. {{~#if true}}), handlebars tags start at pos 3 not pos 2
          var handlebar_starts = 2;
          if (this.tag_start_char === '{' && this.text.length >= 3) {
            if (this.text.charAt(2) === '~') {
              handlebar_starts = 3;
            }
          }
      
          // handlebars tags that don't start with # or ^ are single_tags, and so also start and end.
          this.is_end_tag = this.is_end_tag ||
            (this.tag_start_char === '{' && (this.text.length < 3 || (/[^#\^]/.test(this.text.charAt(handlebar_starts)))));
        }
      };
      
      Beautifier.prototype._get_tag_open_token = function(raw_token) { //function to get a full tag and parse its type
        var parser_token = new TagOpenParserToken(this._tag_stack.get_parser_token(), raw_token);
      
        parser_token.alignment_size = this._options.wrap_attributes_indent_size;
      
        parser_token.is_end_tag = parser_token.is_end_tag ||
          in_array(parser_token.tag_check, this._options.void_elements);
      
        parser_token.is_empty_element = parser_token.tag_complete ||
          (parser_token.is_start_tag && parser_token.is_end_tag);
      
        parser_token.is_unformatted = !parser_token.tag_complete && in_array(parser_token.tag_check, this._options.unformatted);
        parser_token.is_content_unformatted = !parser_token.is_empty_element && in_array(parser_token.tag_check, this._options.content_unformatted);
        parser_token.is_inline_element = in_array(parser_token.tag_name, this._options.inline) || parser_token.tag_name.includes("-") || parser_token.tag_start_char === '{';
      
        return parser_token;
      };
      
      Beautifier.prototype._set_tag_position = function(printer, raw_token, parser_token, last_tag_token, last_token) {
      
        if (!parser_token.is_empty_element) {
          if (parser_token.is_end_tag) { //this tag is a double tag so check for tag-ending
            parser_token.start_tag_token = this._tag_stack.try_pop(parser_token.tag_name); //remove it and all ancestors
          } else { // it's a start-tag
            // check if this tag is starting an element that has optional end element
            // and do an ending needed
            if (this._do_optional_end_element(parser_token)) {
              if (!parser_token.is_inline_element) {
                printer.print_newline(false);
              }
            }
      
            this._tag_stack.record_tag(parser_token); //push it on the tag stack
      
            if ((parser_token.tag_name === 'script' || parser_token.tag_name === 'style') &&
              !(parser_token.is_unformatted || parser_token.is_content_unformatted)) {
              parser_token.custom_beautifier_name = get_custom_beautifier_name(parser_token.tag_check, raw_token);
            }
          }
        }
      
        if (in_array(parser_token.tag_check, this._options.extra_liners)) { //check if this double needs an extra line
          printer.print_newline(false);
          if (!printer._output.just_added_blankline()) {
            printer.print_newline(true);
          }
        }
      
        if (parser_token.is_empty_element) { //if this tag name is a single tag type (either in the list or has a closing /)
      
          // if you hit an else case, reset the indent level if you are inside an:
          // 'if', 'unless', or 'each' block.
          if (parser_token.tag_start_char === '{' && parser_token.tag_check === 'else') {
            this._tag_stack.indent_to_tag(['if', 'unless', 'each']);
            parser_token.indent_content = true;
            // Don't add a newline if opening {{#if}} tag is on the current line
            var foundIfOnCurrentLine = printer.current_line_has_match(/{{#if/);
            if (!foundIfOnCurrentLine) {
              printer.print_newline(false);
            }
          }
      
          // Don't add a newline before elements that should remain where they are.
          if (parser_token.tag_name === '!--' && last_token.type === TOKEN.TAG_CLOSE &&
            last_tag_token.is_end_tag && parser_token.text.indexOf('\n') === -1) {
            //Do nothing. Leave comments on same line.
          } else {
            if (!(parser_token.is_inline_element || parser_token.is_unformatted)) {
              printer.print_newline(false);
            }
            this._calcluate_parent_multiline(printer, parser_token);
          }
        } else if (parser_token.is_end_tag) { //this tag is a double tag so check for tag-ending
          var do_end_expand = false;
      
          // deciding whether a block is multiline should not be this hard
          do_end_expand = parser_token.start_tag_token && parser_token.start_tag_token.multiline_content;
          do_end_expand = do_end_expand || (!parser_token.is_inline_element &&
            !(last_tag_token.is_inline_element || last_tag_token.is_unformatted) &&
            !(last_token.type === TOKEN.TAG_CLOSE && parser_token.start_tag_token === last_tag_token) &&
            last_token.type !== 'TK_CONTENT'
          );
      
          if (parser_token.is_content_unformatted || parser_token.is_unformatted) {
            do_end_expand = false;
          }
      
          if (do_end_expand) {
            printer.print_newline(false);
          }
        } else { // it's a start-tag
          parser_token.indent_content = !parser_token.custom_beautifier_name;
      
          if (parser_token.tag_start_char === '<') {
            if (parser_token.tag_name === 'html') {
              parser_token.indent_content = this._options.indent_inner_html;
            } else if (parser_token.tag_name === 'head') {
              parser_token.indent_content = this._options.indent_head_inner_html;
            } else if (parser_token.tag_name === 'body') {
              parser_token.indent_content = this._options.indent_body_inner_html;
            }
          }
      
          if (!(parser_token.is_inline_element || parser_token.is_unformatted) &&
            (last_token.type !== 'TK_CONTENT' || parser_token.is_content_unformatted)) {
            printer.print_newline(false);
          }
      
          this._calcluate_parent_multiline(printer, parser_token);
        }
      };
      
      Beautifier.prototype._calcluate_parent_multiline = function(printer, parser_token) {
        if (parser_token.parent && printer._output.just_added_newline() &&
          !((parser_token.is_inline_element || parser_token.is_unformatted) && parser_token.parent.is_inline_element)) {
          parser_token.parent.multiline_content = true;
        }
      };
      
      //To be used for <p> tag special case:
      var p_closers = ['address', 'article', 'aside', 'blockquote', 'details', 'div', 'dl', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hr', 'main', 'nav', 'ol', 'p', 'pre', 'section', 'table', 'ul'];
      var p_parent_excludes = ['a', 'audio', 'del', 'ins', 'map', 'noscript', 'video'];
      
      Beautifier.prototype._do_optional_end_element = function(parser_token) {
        var result = null;
        // NOTE: cases of "if there is no more content in the parent element"
        // are handled automatically by the beautifier.
        // It assumes parent or ancestor close tag closes all children.
        // https://www.w3.org/TR/html5/syntax.html#optional-tags
        if (parser_token.is_empty_element || !parser_token.is_start_tag || !parser_token.parent) {
          return;
      
        }
      
        if (parser_token.tag_name === 'body') {
          // A head element’s end tag may be omitted if the head element is not immediately followed by a space character or a comment.
          result = result || this._tag_stack.try_pop('head');
      
          //} else if (parser_token.tag_name === 'body') {
          // DONE: A body element’s end tag may be omitted if the body element is not immediately followed by a comment.
      
        } else if (parser_token.tag_name === 'li') {
          // An li element’s end tag may be omitted if the li element is immediately followed by another li element or if there is no more content in the parent element.
          result = result || this._tag_stack.try_pop('li', ['ol', 'ul']);
      
        } else if (parser_token.tag_name === 'dd' || parser_token.tag_name === 'dt') {
          // A dd element’s end tag may be omitted if the dd element is immediately followed by another dd element or a dt element, or if there is no more content in the parent element.
          // A dt element’s end tag may be omitted if the dt element is immediately followed by another dt element or a dd element.
          result = result || this._tag_stack.try_pop('dt', ['dl']);
          result = result || this._tag_stack.try_pop('dd', ['dl']);
      
      
        } else if (parser_token.parent.tag_name === 'p' && p_closers.indexOf(parser_token.tag_name) !== -1) {
          // IMPORTANT: this else-if works because p_closers has no overlap with any other element we look for in this method
          // check for the parent element is an HTML element that is not an <a>, <audio>, <del>, <ins>, <map>, <noscript>, or <video> element,  or an autonomous custom element.
          // To do this right, this needs to be coded as an inclusion of the inverse of the exclusion above.
          // But to start with (if we ignore "autonomous custom elements") the exclusion would be fine.
          var p_parent = parser_token.parent.parent;
          if (!p_parent || p_parent_excludes.indexOf(p_parent.tag_name) === -1) {
            result = result || this._tag_stack.try_pop('p');
          }
        } else if (parser_token.tag_name === 'rp' || parser_token.tag_name === 'rt') {
          // An rt element’s end tag may be omitted if the rt element is immediately followed by an rt or rp element, or if there is no more content in the parent element.
          // An rp element’s end tag may be omitted if the rp element is immediately followed by an rt or rp element, or if there is no more content in the parent element.
          result = result || this._tag_stack.try_pop('rt', ['ruby', 'rtc']);
          result = result || this._tag_stack.try_pop('rp', ['ruby', 'rtc']);
      
        } else if (parser_token.tag_name === 'optgroup') {
          // An optgroup element’s end tag may be omitted if the optgroup element is immediately followed by another optgroup element, or if there is no more content in the parent element.
          // An option element’s end tag may be omitted if the option element is immediately followed by another option element, or if it is immediately followed by an optgroup element, or if there is no more content in the parent element.
          result = result || this._tag_stack.try_pop('optgroup', ['select']);
          //result = result || this._tag_stack.try_pop('option', ['select']);
      
        } else if (parser_token.tag_name === 'option') {
          // An option element’s end tag may be omitted if the option element is immediately followed by another option element, or if it is immediately followed by an optgroup element, or if there is no more content in the parent element.
          result = result || this._tag_stack.try_pop('option', ['select', 'datalist', 'optgroup']);
      
        } else if (parser_token.tag_name === 'colgroup') {
          // DONE: A colgroup element’s end tag may be omitted if the colgroup element is not immediately followed by a space character or a comment.
          // A caption element's end tag may be ommitted if a colgroup, thead, tfoot, tbody, or tr element is started.
          result = result || this._tag_stack.try_pop('caption', ['table']);
      
        } else if (parser_token.tag_name === 'thead') {
          // A colgroup element's end tag may be ommitted if a thead, tfoot, tbody, or tr element is started.
          // A caption element's end tag may be ommitted if a colgroup, thead, tfoot, tbody, or tr element is started.
          result = result || this._tag_stack.try_pop('caption', ['table']);
          result = result || this._tag_stack.try_pop('colgroup', ['table']);
      
          //} else if (parser_token.tag_name === 'caption') {
          // DONE: A caption element’s end tag may be omitted if the caption element is not immediately followed by a space character or a comment.
      
        } else if (parser_token.tag_name === 'tbody' || parser_token.tag_name === 'tfoot') {
          // A thead element’s end tag may be omitted if the thead element is immediately followed by a tbody or tfoot element.
          // A tbody element’s end tag may be omitted if the tbody element is immediately followed by a tbody or tfoot element, or if there is no more content in the parent element.
          // A colgroup element's end tag may be ommitted if a thead, tfoot, tbody, or tr element is started.
          // A caption element's end tag may be ommitted if a colgroup, thead, tfoot, tbody, or tr element is started.
          result = result || this._tag_stack.try_pop('caption', ['table']);
          result = result || this._tag_stack.try_pop('colgroup', ['table']);
          result = result || this._tag_stack.try_pop('thead', ['table']);
          result = result || this._tag_stack.try_pop('tbody', ['table']);
      
          //} else if (parser_token.tag_name === 'tfoot') {
          // DONE: A tfoot element’s end tag may be omitted if there is no more content in the parent element.
      
        } else if (parser_token.tag_name === 'tr') {
          // A tr element’s end tag may be omitted if the tr element is immediately followed by another tr element, or if there is no more content in the parent element.
          // A colgroup element's end tag may be ommitted if a thead, tfoot, tbody, or tr element is started.
          // A caption element's end tag may be ommitted if a colgroup, thead, tfoot, tbody, or tr element is started.
          result = result || this._tag_stack.try_pop('caption', ['table']);
          result = result || this._tag_stack.try_pop('colgroup', ['table']);
          result = result || this._tag_stack.try_pop('tr', ['table', 'thead', 'tbody', 'tfoot']);
      
        } else if (parser_token.tag_name === 'th' || parser_token.tag_name === 'td') {
          // A td element’s end tag may be omitted if the td element is immediately followed by a td or th element, or if there is no more content in the parent element.
          // A th element’s end tag may be omitted if the th element is immediately followed by a td or th element, or if there is no more content in the parent element.
          result = result || this._tag_stack.try_pop('td', ['table', 'thead', 'tbody', 'tfoot', 'tr']);
          result = result || this._tag_stack.try_pop('th', ['table', 'thead', 'tbody', 'tfoot', 'tr']);
        }
      
        // Start element omission not handled currently
        // A head element’s start tag may be omitted if the element is empty, or if the first thing inside the head element is an element.
        // A tbody element’s start tag may be omitted if the first thing inside the tbody element is a tr element, and if the element is not immediately preceded by a tbody, thead, or tfoot element whose end tag has been omitted. (It can’t be omitted if the element is empty.)
        // A colgroup element’s start tag may be omitted if the first thing inside the colgroup element is a col element, and if the element is not immediately preceded by another colgroup element whose end tag has been omitted. (It can’t be omitted if the element is empty.)
      
        // Fix up the parent of the parser token
        parser_token.parent = this._tag_stack.get_parser_token();
      
        return result;
      };
      
      module.exports.Beautifier = Beautifier;
      
      
      /***/ }),
      /* 20 */
      /***/ (function(module, __unused_webpack_exports, __webpack_require__) {
      
      /*jshint node:true */
      /*
      
        The MIT License (MIT)
      
        Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
      
        Permission 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:
      
        The above copyright notice and this permission notice shall be
        included in all copies or substantial portions of the Software.
      
        THE 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.
      */
      
      
      
      var BaseOptions = (__webpack_require__(6).Options);
      
      function Options(options) {
        BaseOptions.call(this, options, 'html');
        if (this.templating.length === 1 && this.templating[0] === 'auto') {
          this.templating = ['django', 'erb', 'handlebars', 'php'];
        }
      
        this.indent_inner_html = this._get_boolean('indent_inner_html');
        this.indent_body_inner_html = this._get_boolean('indent_body_inner_html', true);
        this.indent_head_inner_html = this._get_boolean('indent_head_inner_html', true);
      
        this.indent_handlebars = this._get_boolean('indent_handlebars', true);
        this.wrap_attributes = this._get_selection('wrap_attributes',
          ['auto', 'force', 'force-aligned', 'force-expand-multiline', 'aligned-multiple', 'preserve', 'preserve-aligned']);
        this.wrap_attributes_indent_size = this._get_number('wrap_attributes_indent_size', this.indent_size);
        this.extra_liners = this._get_array('extra_liners', ['head', 'body', '/html']);
      
        // Block vs inline elements
        // https://developer.mozilla.org/en-US/docs/Web/HTML/Block-level_elements
        // https://developer.mozilla.org/en-US/docs/Web/HTML/Inline_elements
        // https://www.w3.org/TR/html5/dom.html#phrasing-content
        this.inline = this._get_array('inline', [
          'a', 'abbr', 'area', 'audio', 'b', 'bdi', 'bdo', 'br', 'button', 'canvas', 'cite',
          'code', 'data', 'datalist', 'del', 'dfn', 'em', 'embed', 'i', 'iframe', 'img',
          'input', 'ins', 'kbd', 'keygen', 'label', 'map', 'mark', 'math', 'meter', 'noscript',
          'object', 'output', 'progress', 'q', 'ruby', 's', 'samp', /* 'script', */ 'select', 'small',
          'span', 'strong', 'sub', 'sup', 'svg', 'template', 'textarea', 'time', 'u', 'var',
          'video', 'wbr', 'text',
          // obsolete inline tags
          'acronym', 'big', 'strike', 'tt'
        ]);
        this.void_elements = this._get_array('void_elements', [
          // HTLM void elements - aka self-closing tags - aka singletons
          // https://www.w3.org/html/wg/drafts/html/master/syntax.html#void-elements
          'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen',
          'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr',
          // NOTE: Optional tags are too complex for a simple list
          // they are hard coded in _do_optional_end_element
      
          // Doctype and xml elements
          '!doctype', '?xml',
      
          // obsolete tags
          // basefont: https://www.computerhope.com/jargon/h/html-basefont-tag.htm
          // isndex: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/isindex
          'basefont', 'isindex'
        ]);
        this.unformatted = this._get_array('unformatted', []);
        this.content_unformatted = this._get_array('content_unformatted', [
          'pre', 'textarea'
        ]);
        this.unformatted_content_delimiter = this._get_characters('unformatted_content_delimiter');
        this.indent_scripts = this._get_selection('indent_scripts', ['normal', 'keep', 'separate']);
      
      }
      Options.prototype = new BaseOptions();
      
      
      
      module.exports.Options = Options;
      
      
      /***/ }),
      /* 21 */
      /***/ (function(module, __unused_webpack_exports, __webpack_require__) {
      
      /*jshint node:true */
      /*
      
        The MIT License (MIT)
      
        Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
      
        Permission 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:
      
        The above copyright notice and this permission notice shall be
        included in all copies or substantial portions of the Software.
      
        THE 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.
      */
      
      
      
      var BaseTokenizer = (__webpack_require__(9).Tokenizer);
      var BASETOKEN = (__webpack_require__(9).TOKEN);
      var Directives = (__webpack_require__(13).Directives);
      var TemplatablePattern = (__webpack_require__(14).TemplatablePattern);
      var Pattern = (__webpack_require__(12).Pattern);
      
      var TOKEN = {
        TAG_OPEN: 'TK_TAG_OPEN',
        TAG_CLOSE: 'TK_TAG_CLOSE',
        ATTRIBUTE: 'TK_ATTRIBUTE',
        EQUALS: 'TK_EQUALS',
        VALUE: 'TK_VALUE',
        COMMENT: 'TK_COMMENT',
        TEXT: 'TK_TEXT',
        UNKNOWN: 'TK_UNKNOWN',
        START: BASETOKEN.START,
        RAW: BASETOKEN.RAW,
        EOF: BASETOKEN.EOF
      };
      
      var directives_core = new Directives(/<\!--/, /-->/);
      
      var Tokenizer = function(input_string, options) {
        BaseTokenizer.call(this, input_string, options);
        this._current_tag_name = '';
      
        // Words end at whitespace or when a tag starts
        // if we are indenting handlebars, they are considered tags
        var templatable_reader = new TemplatablePattern(this._input).read_options(this._options);
        var pattern_reader = new Pattern(this._input);
      
        this.__patterns = {
          word: templatable_reader.until(/[\n\r\t <]/),
          single_quote: templatable_reader.until_after(/'/),
          double_quote: templatable_reader.until_after(/"/),
          attribute: templatable_reader.until(/[\n\r\t =>]|\/>/),
          element_name: templatable_reader.until(/[\n\r\t >\/]/),
      
          handlebars_comment: pattern_reader.starting_with(/{{!--/).until_after(/--}}/),
          handlebars: pattern_reader.starting_with(/{{/).until_after(/}}/),
          handlebars_open: pattern_reader.until(/[\n\r\t }]/),
          handlebars_raw_close: pattern_reader.until(/}}/),
          comment: pattern_reader.starting_with(/<!--/).until_after(/-->/),
          cdata: pattern_reader.starting_with(/<!\[CDATA\[/).until_after(/]]>/),
          // https://en.wikipedia.org/wiki/Conditional_comment
          conditional_comment: pattern_reader.starting_with(/<!\[/).until_after(/]>/),
          processing: pattern_reader.starting_with(/<\?/).until_after(/\?>/)
        };
      
        if (this._options.indent_handlebars) {
          this.__patterns.word = this.__patterns.word.exclude('handlebars');
        }
      
        this._unformatted_content_delimiter = null;
      
        if (this._options.unformatted_content_delimiter) {
          var literal_regexp = this._input.get_literal_regexp(this._options.unformatted_content_delimiter);
          this.__patterns.unformatted_content_delimiter =
            pattern_reader.matching(literal_regexp)
            .until_after(literal_regexp);
        }
      };
      Tokenizer.prototype = new BaseTokenizer();
      
      Tokenizer.prototype._is_comment = function(current_token) { // jshint unused:false
        return false; //current_token.type === TOKEN.COMMENT || current_token.type === TOKEN.UNKNOWN;
      };
      
      Tokenizer.prototype._is_opening = function(current_token) {
        return current_token.type === TOKEN.TAG_OPEN;
      };
      
      Tokenizer.prototype._is_closing = function(current_token, open_token) {
        return current_token.type === TOKEN.TAG_CLOSE &&
          (open_token && (
            ((current_token.text === '>' || current_token.text === '/>') && open_token.text[0] === '<') ||
            (current_token.text === '}}' && open_token.text[0] === '{' && open_token.text[1] === '{')));
      };
      
      Tokenizer.prototype._reset = function() {
        this._current_tag_name = '';
      };
      
      Tokenizer.prototype._get_next_token = function(previous_token, open_token) { // jshint unused:false
        var token = null;
        this._readWhitespace();
        var c = this._input.peek();
      
        if (c === null) {
          return this._create_token(TOKEN.EOF, '');
        }
      
        token = token || this._read_open_handlebars(c, open_token);
        token = token || this._read_attribute(c, previous_token, open_token);
        token = token || this._read_close(c, open_token);
        token = token || this._read_raw_content(c, previous_token, open_token);
        token = token || this._read_content_word(c);
        token = token || this._read_comment_or_cdata(c);
        token = token || this._read_processing(c);
        token = token || this._read_open(c, open_token);
        token = token || this._create_token(TOKEN.UNKNOWN, this._input.next());
      
        return token;
      };
      
      Tokenizer.prototype._read_comment_or_cdata = function(c) { // jshint unused:false
        var token = null;
        var resulting_string = null;
        var directives = null;
      
        if (c === '<') {
          var peek1 = this._input.peek(1);
          // We treat all comments as literals, even more than preformatted tags
          // we only look for the appropriate closing marker
          if (peek1 === '!') {
            resulting_string = this.__patterns.comment.read();
      
            // only process directive on html comments
            if (resulting_string) {
              directives = directives_core.get_directives(resulting_string);
              if (directives && directives.ignore === 'start') {
                resulting_string += directives_core.readIgnored(this._input);
              }
            } else {
              resulting_string = this.__patterns.cdata.read();
            }
          }
      
          if (resulting_string) {
            token = this._create_token(TOKEN.COMMENT, resulting_string);
            token.directives = directives;
          }
        }
      
        return token;
      };
      
      Tokenizer.prototype._read_processing = function(c) { // jshint unused:false
        var token = null;
        var resulting_string = null;
        var directives = null;
      
        if (c === '<') {
          var peek1 = this._input.peek(1);
          if (peek1 === '!' || peek1 === '?') {
            resulting_string = this.__patterns.conditional_comment.read();
            resulting_string = resulting_string || this.__patterns.processing.read();
          }
      
          if (resulting_string) {
            token = this._create_token(TOKEN.COMMENT, resulting_string);
            token.directives = directives;
          }
        }
      
        return token;
      };
      
      Tokenizer.prototype._read_open = function(c, open_token) {
        var resulting_string = null;
        var token = null;
        if (!open_token) {
          if (c === '<') {
      
            resulting_string = this._input.next();
            if (this._input.peek() === '/') {
              resulting_string += this._input.next();
            }
            resulting_string += this.__patterns.element_name.read();
            token = this._create_token(TOKEN.TAG_OPEN, resulting_string);
          }
        }
        return token;
      };
      
      Tokenizer.prototype._read_open_handlebars = function(c, open_token) {
        var resulting_string = null;
        var token = null;
        if (!open_token) {
          if (this._options.indent_handlebars && c === '{' && this._input.peek(1) === '{') {
            if (this._input.peek(2) === '!') {
              resulting_string = this.__patterns.handlebars_comment.read();
              resulting_string = resulting_string || this.__patterns.handlebars.read();
              token = this._create_token(TOKEN.COMMENT, resulting_string);
            } else {
              resulting_string = this.__patterns.handlebars_open.read();
              token = this._create_token(TOKEN.TAG_OPEN, resulting_string);
            }
          }
        }
        return token;
      };
      
      
      Tokenizer.prototype._read_close = function(c, open_token) {
        var resulting_string = null;
        var token = null;
        if (open_token) {
          if (open_token.text[0] === '<' && (c === '>' || (c === '/' && this._input.peek(1) === '>'))) {
            resulting_string = this._input.next();
            if (c === '/') { //  for close tag "/>"
              resulting_string += this._input.next();
            }
            token = this._create_token(TOKEN.TAG_CLOSE, resulting_string);
          } else if (open_token.text[0] === '{' && c === '}' && this._input.peek(1) === '}') {
            this._input.next();
            this._input.next();
            token = this._create_token(TOKEN.TAG_CLOSE, '}}');
          }
        }
      
        return token;
      };
      
      Tokenizer.prototype._read_attribute = function(c, previous_token, open_token) {
        var token = null;
        var resulting_string = '';
        if (open_token && open_token.text[0] === '<') {
      
          if (c === '=') {
            token = this._create_token(TOKEN.EQUALS, this._input.next());
          } else if (c === '"' || c === "'") {
            var content = this._input.next();
            if (c === '"') {
              content += this.__patterns.double_quote.read();
            } else {
              content += this.__patterns.single_quote.read();
            }
            token = this._create_token(TOKEN.VALUE, content);
          } else {
            resulting_string = this.__patterns.attribute.read();
      
            if (resulting_string) {
              if (previous_token.type === TOKEN.EQUALS) {
                token = this._create_token(TOKEN.VALUE, resulting_string);
              } else {
                token = this._create_token(TOKEN.ATTRIBUTE, resulting_string);
              }
            }
          }
        }
        return token;
      };
      
      Tokenizer.prototype._is_content_unformatted = function(tag_name) {
        // void_elements have no content and so cannot have unformatted content
        // script and style tags should always be read as unformatted content
        // finally content_unformatted and unformatted element contents are unformatted
        return this._options.void_elements.indexOf(tag_name) === -1 &&
          (this._options.content_unformatted.indexOf(tag_name) !== -1 ||
            this._options.unformatted.indexOf(tag_name) !== -1);
      };
      
      
      Tokenizer.prototype._read_raw_content = function(c, previous_token, open_token) { // jshint unused:false
        var resulting_string = '';
        if (open_token && open_token.text[0] === '{') {
          resulting_string = this.__patterns.handlebars_raw_close.read();
        } else if (previous_token.type === TOKEN.TAG_CLOSE &&
          previous_token.opened.text[0] === '<' && previous_token.text[0] !== '/') {
          // ^^ empty tag has no content 
          var tag_name = previous_token.opened.text.substr(1).toLowerCase();
          if (tag_name === 'script' || tag_name === 'style') {
            // Script and style tags are allowed to have comments wrapping their content
            // or just have regular content.
            var token = this._read_comment_or_cdata(c);
            if (token) {
              token.type = TOKEN.TEXT;
              return token;
            }
            resulting_string = this._input.readUntil(new RegExp('</' + tag_name + '[\\n\\r\\t ]*?>', 'ig'));
          } else if (this._is_content_unformatted(tag_name)) {
      
            resulting_string = this._input.readUntil(new RegExp('</' + tag_name + '[\\n\\r\\t ]*?>', 'ig'));
          }
        }
      
        if (resulting_string) {
          return this._create_token(TOKEN.TEXT, resulting_string);
        }
      
        return null;
      };
      
      Tokenizer.prototype._read_content_word = function(c) {
        var resulting_string = '';
        if (this._options.unformatted_content_delimiter) {
          if (c === this._options.unformatted_content_delimiter[0]) {
            resulting_string = this.__patterns.unformatted_content_delimiter.read();
          }
        }
      
        if (!resulting_string) {
          resulting_string = this.__patterns.word.read();
        }
        if (resulting_string) {
          return this._create_token(TOKEN.TEXT, resulting_string);
        }
      };
      
      module.exports.Tokenizer = Tokenizer;
      module.exports.TOKEN = TOKEN;
      
      
      /***/ })
      /******/ 	]);
      /************************************************************************/
      /******/ 	// The module cache
      /******/ 	var __webpack_module_cache__ = {};
      /******/ 	
      /******/ 	// The require function
      /******/ 	function __webpack_require__(moduleId) {
      /******/ 		// Check if module is in cache
      /******/ 		var cachedModule = __webpack_module_cache__[moduleId];
      /******/ 		if (cachedModule !== undefined) {
      /******/ 			return cachedModule.exports;
      /******/ 		}
      /******/ 		// Create a new module (and put it into the cache)
      /******/ 		var module = __webpack_module_cache__[moduleId] = {
      /******/ 			// no module.id needed
      /******/ 			// no module.loaded needed
      /******/ 			exports: {}
      /******/ 		};
      /******/ 	
      /******/ 		// Execute the module function
      /******/ 		__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
      /******/ 	
      /******/ 		// Return the exports of the module
      /******/ 		return module.exports;
      /******/ 	}
      /******/ 	
      /************************************************************************/
      /******/ 	
      /******/ 	// startup
      /******/ 	// Load entry module and return exports
      /******/ 	// This entry module is referenced by other modules so it can't be inlined
      /******/ 	var __webpack_exports__ = __webpack_require__(18);
      /******/ 	legacy_beautify_html = __webpack_exports__;
      /******/ 	
      /******/ })()
      ;
      var style_html = legacy_beautify_html;
      /* Footer */
      if (true) {
          // Add support for AMD ( https://github.com/amdjs/amdjs-api/wiki/AMD#defineamd-property- )
          !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__, __webpack_require__(/*! ./beautify */ "6UM0"), __webpack_require__(/*! ./beautify-css */ "TXwP")], __WEBPACK_AMD_DEFINE_RESULT__ = (function(requireamd) {
              var js_beautify = __webpack_require__(/*! ./beautify */ "6UM0");
              var css_beautify = __webpack_require__(/*! ./beautify-css */ "TXwP");
      
              return {
                  html_beautify: function(html_source, options) {
                      return style_html(html_source, options, js_beautify.js_beautify, css_beautify.css_beautify);
                  }
              };
          }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
      				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
      } else { var css_beautify, js_beautify; }
      
      }());
      
      
      /***/ }),
      
      /***/ "rAM+":
      /*!*******************************************************************************************************************!*\
        !*** ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelper.js ***!
        \*******************************************************************************************************************/
      /*! exports provided: default */
      /*! exports used: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _createForOfIteratorHelper; });
      /* harmony import */ var _babel_runtime_helpers_esm_unsupportedIterableToArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/esm/unsupportedIterableToArray */ "Qw5x");
      
      function _createForOfIteratorHelper(o, allowArrayLike) {
        var it;
      
        if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
          if (Array.isArray(o) || (it = Object(_babel_runtime_helpers_esm_unsupportedIterableToArray__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])(o)) || allowArrayLike && o && typeof o.length === "number") {
            if (it) o = it;
            var i = 0;
      
            var F = function F() {};
      
            return {
              s: F,
              n: function n() {
                if (i >= o.length) return {
                  done: true
                };
                return {
                  done: false,
                  value: o[i++]
                };
              },
              e: function e(_e) {
                throw _e;
              },
              f: F
            };
          }
      
          throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
        }
      
        var normalCompletion = true,
            didErr = false,
            err;
        return {
          s: function s() {
            it = o[Symbol.iterator]();
          },
          n: function n() {
            var step = it.next();
            normalCompletion = step.done;
            return step;
          },
          e: function e(_e2) {
            didErr = true;
            err = _e2;
          },
          f: function f() {
            try {
              if (!normalCompletion && it["return"] != null) it["return"]();
            } finally {
              if (didErr) throw err;
            }
          }
        };
      }
      
      /***/ }),
      
      /***/ "rUJ1":
      /*!********************************************!*\
        !*** ./node_modules/marked/src/helpers.js ***!
        \********************************************/
      /*! no static exports found */
      /*! exports used: escape */
      /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
      /***/ (function(module, exports) {
      
      /**
       * Helpers
       */
      const escapeTest = /[&<>"']/;
      const escapeReplace = /[&<>"']/g;
      const escapeTestNoEncode = /[<>"']|&(?!#?\w+;)/;
      const escapeReplaceNoEncode = /[<>"']|&(?!#?\w+;)/g;
      const escapeReplacements = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#39;'
      };
      const getEscapeReplacement = (ch) => escapeReplacements[ch];
      function escape(html, encode) {
        if (encode) {
          if (escapeTest.test(html)) {
            return html.replace(escapeReplace, getEscapeReplacement);
          }
        } else {
          if (escapeTestNoEncode.test(html)) {
            return html.replace(escapeReplaceNoEncode, getEscapeReplacement);
          }
        }
      
        return html;
      }
      
      const unescapeTest = /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;
      
      function unescape(html) {
        // explicitly match decimal, hex, and named HTML entities
        return html.replace(unescapeTest, (_, n) => {
          n = n.toLowerCase();
          if (n === 'colon') return ':';
          if (n.charAt(0) === '#') {
            return n.charAt(1) === 'x'
              ? String.fromCharCode(parseInt(n.substring(2), 16))
              : String.fromCharCode(+n.substring(1));
          }
          return '';
        });
      }
      
      const caret = /(^|[^\[])\^/g;
      function edit(regex, opt) {
        regex = regex.source || regex;
        opt = opt || '';
        const obj = {
          replace: (name, val) => {
            val = val.source || val;
            val = val.replace(caret, '$1');
            regex = regex.replace(name, val);
            return obj;
          },
          getRegex: () => {
            return new RegExp(regex, opt);
          }
        };
        return obj;
      }
      
      const nonWordAndColonTest = /[^\w:]/g;
      const originIndependentUrl = /^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;
      function cleanUrl(sanitize, base, href) {
        if (sanitize) {
          let prot;
          try {
            prot = decodeURIComponent(unescape(href))
              .replace(nonWordAndColonTest, '')
              .toLowerCase();
          } catch (e) {
            return null;
          }
          if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) {
            return null;
          }
        }
        if (base && !originIndependentUrl.test(href)) {
          href = resolveUrl(base, href);
        }
        try {
          href = encodeURI(href).replace(/%25/g, '%');
        } catch (e) {
          return null;
        }
        return href;
      }
      
      const baseUrls = {};
      const justDomain = /^[^:]+:\/*[^/]*$/;
      const protocol = /^([^:]+:)[\s\S]*$/;
      const domain = /^([^:]+:\/*[^/]*)[\s\S]*$/;
      
      function resolveUrl(base, href) {
        if (!baseUrls[' ' + base]) {
          // we can ignore everything in base after the last slash of its path component,
          // but we might need to add _that_
          // https://tools.ietf.org/html/rfc3986#section-3
          if (justDomain.test(base)) {
            baseUrls[' ' + base] = base + '/';
          } else {
            baseUrls[' ' + base] = rtrim(base, '/', true);
          }
        }
        base = baseUrls[' ' + base];
        const relativeBase = base.indexOf(':') === -1;
      
        if (href.substring(0, 2) === '//') {
          if (relativeBase) {
            return href;
          }
          return base.replace(protocol, '$1') + href;
        } else if (href.charAt(0) === '/') {
          if (relativeBase) {
            return href;
          }
          return base.replace(domain, '$1') + href;
        } else {
          return base + href;
        }
      }
      
      const noopTest = { exec: function noopTest() {} };
      
      function merge(obj) {
        let i = 1,
          target,
          key;
      
        for (; i < arguments.length; i++) {
          target = arguments[i];
          for (key in target) {
            if (Object.prototype.hasOwnProperty.call(target, key)) {
              obj[key] = target[key];
            }
          }
        }
      
        return obj;
      }
      
      function splitCells(tableRow, count) {
        // ensure that every cell-delimiting pipe has a space
        // before it to distinguish it from an escaped pipe
        const row = tableRow.replace(/\|/g, (match, offset, str) => {
            let escaped = false,
              curr = offset;
            while (--curr >= 0 && str[curr] === '\\') escaped = !escaped;
            if (escaped) {
              // odd number of slashes means | is escaped
              // so we leave it alone
              return '|';
            } else {
              // add space before unescaped |
              return ' |';
            }
          }),
          cells = row.split(/ \|/);
        let i = 0;
      
        if (cells.length > count) {
          cells.splice(count);
        } else {
          while (cells.length < count) cells.push('');
        }
      
        for (; i < cells.length; i++) {
          // leading or trailing whitespace is ignored per the gfm spec
          cells[i] = cells[i].trim().replace(/\\\|/g, '|');
        }
        return cells;
      }
      
      // Remove trailing 'c's. Equivalent to str.replace(/c*$/, '').
      // /c*$/ is vulnerable to REDOS.
      // invert: Remove suffix of non-c chars instead. Default falsey.
      function rtrim(str, c, invert) {
        const l = str.length;
        if (l === 0) {
          return '';
        }
      
        // Length of suffix matching the invert condition.
        let suffLen = 0;
      
        // Step left until we fail to match the invert condition.
        while (suffLen < l) {
          const currChar = str.charAt(l - suffLen - 1);
          if (currChar === c && !invert) {
            suffLen++;
          } else if (currChar !== c && invert) {
            suffLen++;
          } else {
            break;
          }
        }
      
        return str.substr(0, l - suffLen);
      }
      
      function findClosingBracket(str, b) {
        if (str.indexOf(b[1]) === -1) {
          return -1;
        }
        const l = str.length;
        let level = 0,
          i = 0;
        for (; i < l; i++) {
          if (str[i] === '\\') {
            i++;
          } else if (str[i] === b[0]) {
            level++;
          } else if (str[i] === b[1]) {
            level--;
            if (level < 0) {
              return i;
            }
          }
        }
        return -1;
      }
      
      function checkSanitizeDeprecation(opt) {
        if (opt && opt.sanitize && !opt.silent) {
          console.warn('marked(): sanitize and sanitizer parameters are deprecated since version 0.7.0, should not be used and will be removed in the future. Read more here: https://marked.js.org/#/USING_ADVANCED.md#options');
        }
      }
      
      module.exports = {
        escape,
        unescape,
        edit,
        cleanUrl,
        resolveUrl,
        noopTest,
        merge,
        splitCells,
        rtrim,
        findClosingBracket,
        checkSanitizeDeprecation
      };
      
      
      /***/ }),
      
      /***/ "sboe":
      /*!*************************************************!*\
        !*** ./node_modules/rc-tree/es/contextTypes.js ***!
        \*************************************************/
      /*! exports provided: TreeContext */
      /*! exports used: TreeContext */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return TreeContext; });
      /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "cDcd");
      /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
      /**
       * Webpack has bug for import loop, which is not the same behavior as ES module.
       * When util.js imports the TreeNode for tree generate will cause treeContextTypes be empty.
       */
      
      var TreeContext = react__WEBPACK_IMPORTED_MODULE_0__["createContext"](null);
      
      /***/ }),
      
      /***/ "spXi":
      /*!******************************************************!*\
        !*** ./src/components/CustomTree/index.less?modules ***!
        \******************************************************/
      /*! no static exports found */
      /*! exports used: default */
      /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
      /***/ (function(module, exports, __webpack_require__) {
      
      // extracted by mini-css-extract-plugin
      module.exports = {"flex_box_center":"flex_box_center___2B_Y7","flex_space_between":"flex_space_between___2olzC","flex_box_vertical_center":"flex_box_vertical_center___2Z4dV","flex_box_center_end":"flex_box_center_end___3FiwX","flex_box_column":"flex_box_column___8kyK-","customTree":"customTree___1KOYx","name":"name___3pqs4"};
      
      /***/ }),
      
      /***/ "t23M":
      /*!*****************************************************!*\
        !*** ./node_modules/rc-resize-observer/es/index.js ***!
        \*****************************************************/
      /*! exports provided: default */
      /*! exports used: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      /* harmony import */ var _babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/esm/objectSpread2 */ "VTBJ");
      /* harmony import */ var _babel_runtime_helpers_esm_classCallCheck__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/esm/classCallCheck */ "1OyB");
      /* harmony import */ var _babel_runtime_helpers_esm_createClass__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/esm/createClass */ "vuIU");
      /* harmony import */ var _babel_runtime_helpers_esm_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/esm/inherits */ "Ji7U");
      /* harmony import */ var _babel_runtime_helpers_esm_createSuper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/esm/createSuper */ "LK+K");
      /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! react */ "cDcd");
      /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_5__);
      /* harmony import */ var rc_util_es_Dom_findDOMNode__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! rc-util/es/Dom/findDOMNode */ "m+aA");
      /* harmony import */ var rc_util_es_Children_toArray__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! rc-util/es/Children/toArray */ "Zm9Q");
      /* harmony import */ var rc_util_es_warning__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! rc-util/es/warning */ "Kwbf");
      /* harmony import */ var rc_util_es_ref__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! rc-util/es/ref */ "c+Xe");
      /* harmony import */ var resize_observer_polyfill__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! resize-observer-polyfill */ "bdgK");
      
      
      
      
      
      
      
      
      
      
      
      var INTERNAL_PREFIX_KEY = 'rc-observer-key'; // Still need to be compatible with React 15, we use class component here
      
      var ReactResizeObserver = /*#__PURE__*/function (_React$Component) {
        Object(_babel_runtime_helpers_esm_inherits__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"])(ReactResizeObserver, _React$Component);
      
        var _super = Object(_babel_runtime_helpers_esm_createSuper__WEBPACK_IMPORTED_MODULE_4__[/* default */ "a"])(ReactResizeObserver);
      
        function ReactResizeObserver() {
          var _this;
      
          Object(_babel_runtime_helpers_esm_classCallCheck__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"])(this, ReactResizeObserver);
      
          _this = _super.apply(this, arguments);
          _this.resizeObserver = null;
          _this.childNode = null;
          _this.currentElement = null;
          _this.state = {
            width: 0,
            height: 0,
            offsetHeight: 0,
            offsetWidth: 0
          };
      
          _this.onResize = function (entries) {
            var onResize = _this.props.onResize;
            var target = entries[0].target;
      
            var _target$getBoundingCl = target.getBoundingClientRect(),
                width = _target$getBoundingCl.width,
                height = _target$getBoundingCl.height;
      
            var offsetWidth = target.offsetWidth,
                offsetHeight = target.offsetHeight;
            /**
             * Resize observer trigger when content size changed.
             * In most case we just care about element size,
             * let's use `boundary` instead of `contentRect` here to avoid shaking.
             */
      
            var fixedWidth = Math.floor(width);
            var fixedHeight = Math.floor(height);
      
            if (_this.state.width !== fixedWidth || _this.state.height !== fixedHeight || _this.state.offsetWidth !== offsetWidth || _this.state.offsetHeight !== offsetHeight) {
              var size = {
                width: fixedWidth,
                height: fixedHeight,
                offsetWidth: offsetWidth,
                offsetHeight: offsetHeight
              };
      
              _this.setState(size);
      
              if (onResize) {
                // defer the callback but not defer to next frame
                Promise.resolve().then(function () {
                  onResize(Object(_babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])(Object(_babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])({}, size), {}, {
                    offsetWidth: offsetWidth,
                    offsetHeight: offsetHeight
                  }));
                });
              }
            }
          };
      
          _this.setChildNode = function (node) {
            _this.childNode = node;
          };
      
          return _this;
        }
      
        Object(_babel_runtime_helpers_esm_createClass__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"])(ReactResizeObserver, [{
          key: "componentDidMount",
          value: function componentDidMount() {
            this.onComponentUpdated();
          }
        }, {
          key: "componentDidUpdate",
          value: function componentDidUpdate() {
            this.onComponentUpdated();
          }
        }, {
          key: "componentWillUnmount",
          value: function componentWillUnmount() {
            this.destroyObserver();
          }
        }, {
          key: "onComponentUpdated",
          value: function onComponentUpdated() {
            var disabled = this.props.disabled; // Unregister if disabled
      
            if (disabled) {
              this.destroyObserver();
              return;
            } // Unregister if element changed
      
      
            var element = Object(rc_util_es_Dom_findDOMNode__WEBPACK_IMPORTED_MODULE_6__[/* default */ "a"])(this.childNode || this);
            var elementChanged = element !== this.currentElement;
      
            if (elementChanged) {
              this.destroyObserver();
              this.currentElement = element;
            }
      
            if (!this.resizeObserver && element) {
              this.resizeObserver = new resize_observer_polyfill__WEBPACK_IMPORTED_MODULE_10__["default"](this.onResize);
              this.resizeObserver.observe(element);
            }
          }
        }, {
          key: "destroyObserver",
          value: function destroyObserver() {
            if (this.resizeObserver) {
              this.resizeObserver.disconnect();
              this.resizeObserver = null;
            }
          }
        }, {
          key: "render",
          value: function render() {
            var children = this.props.children;
            var childNodes = Object(rc_util_es_Children_toArray__WEBPACK_IMPORTED_MODULE_7__[/* default */ "a"])(children);
      
            if (childNodes.length > 1) {
              Object(rc_util_es_warning__WEBPACK_IMPORTED_MODULE_8__[/* default */ "a"])(false, 'Find more than one child node with `children` in ResizeObserver. Will only observe first one.');
            } else if (childNodes.length === 0) {
              Object(rc_util_es_warning__WEBPACK_IMPORTED_MODULE_8__[/* default */ "a"])(false, '`children` of ResizeObserver is empty. Nothing is in observe.');
              return null;
            }
      
            var childNode = childNodes[0];
      
            if (react__WEBPACK_IMPORTED_MODULE_5__["isValidElement"](childNode) && Object(rc_util_es_ref__WEBPACK_IMPORTED_MODULE_9__[/* supportRef */ "c"])(childNode)) {
              var ref = childNode.ref;
              childNodes[0] = react__WEBPACK_IMPORTED_MODULE_5__["cloneElement"](childNode, {
                ref: Object(rc_util_es_ref__WEBPACK_IMPORTED_MODULE_9__[/* composeRef */ "a"])(ref, this.setChildNode)
              });
            }
      
            return childNodes.length === 1 ? childNodes[0] : childNodes.map(function (node, index) {
              if (!react__WEBPACK_IMPORTED_MODULE_5__["isValidElement"](node) || 'key' in node && node.key !== null) {
                return node;
              }
      
              return react__WEBPACK_IMPORTED_MODULE_5__["cloneElement"](node, {
                key: "".concat(INTERNAL_PREFIX_KEY, "-").concat(index)
              });
            });
          }
        }]);
      
        return ReactResizeObserver;
      }(react__WEBPACK_IMPORTED_MODULE_5__["Component"]);
      
      ReactResizeObserver.displayName = 'ResizeObserver';
      /* harmony default export */ __webpack_exports__["a"] = (ReactResizeObserver);
      
      /***/ }),
      
      /***/ "ulZh":
      /*!*****************************************!*\
        !*** ./node_modules/hls.js/dist/hls.js ***!
        \*****************************************/
      /*! no static exports found */
      /*! exports used: default */
      /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
      /***/ (function(module, exports, __webpack_require__) {
      
      typeof window !== "undefined" &&
      (function webpackUniversalModuleDefinition(root, factory) {
      	if(true)
      		module.exports = factory();
      	else {}
      })(this, function() {
      return /******/ (function(modules) { // webpackBootstrap
      /******/ 	// The module cache
      /******/ 	var installedModules = {};
      /******/
      /******/ 	// The require function
      /******/ 	function __webpack_require__(moduleId) {
      /******/
      /******/ 		// Check if module is in cache
      /******/ 		if(installedModules[moduleId]) {
      /******/ 			return installedModules[moduleId].exports;
      /******/ 		}
      /******/ 		// Create a new module (and put it into the cache)
      /******/ 		var module = installedModules[moduleId] = {
      /******/ 			i: moduleId,
      /******/ 			l: false,
      /******/ 			exports: {}
      /******/ 		};
      /******/
      /******/ 		// Execute the module function
      /******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
      /******/
      /******/ 		// Flag the module as loaded
      /******/ 		module.l = true;
      /******/
      /******/ 		// Return the exports of the module
      /******/ 		return module.exports;
      /******/ 	}
      /******/
      /******/
      /******/ 	// expose the modules object (__webpack_modules__)
      /******/ 	__webpack_require__.m = modules;
      /******/
      /******/ 	// expose the module cache
      /******/ 	__webpack_require__.c = installedModules;
      /******/
      /******/ 	// define getter function for harmony exports
      /******/ 	__webpack_require__.d = function(exports, name, getter) {
      /******/ 		if(!__webpack_require__.o(exports, name)) {
      /******/ 			Object.defineProperty(exports, name, { enumerable: true, get: getter });
      /******/ 		}
      /******/ 	};
      /******/
      /******/ 	// define __esModule on exports
      /******/ 	__webpack_require__.r = function(exports) {
      /******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
      /******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
      /******/ 		}
      /******/ 		Object.defineProperty(exports, '__esModule', { value: true });
      /******/ 	};
      /******/
      /******/ 	// create a fake namespace object
      /******/ 	// mode & 1: value is a module id, require it
      /******/ 	// mode & 2: merge all properties of value into the ns
      /******/ 	// mode & 4: return value when already ns object
      /******/ 	// mode & 8|1: behave like require
      /******/ 	__webpack_require__.t = function(value, mode) {
      /******/ 		if(mode & 1) value = __webpack_require__(value);
      /******/ 		if(mode & 8) return value;
      /******/ 		if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
      /******/ 		var ns = Object.create(null);
      /******/ 		__webpack_require__.r(ns);
      /******/ 		Object.defineProperty(ns, 'default', { enumerable: true, value: value });
      /******/ 		if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
      /******/ 		return ns;
      /******/ 	};
      /******/
      /******/ 	// getDefaultExport function for compatibility with non-harmony modules
      /******/ 	__webpack_require__.n = function(module) {
      /******/ 		var getter = module && module.__esModule ?
      /******/ 			function getDefault() { return module['default']; } :
      /******/ 			function getModuleExports() { return module; };
      /******/ 		__webpack_require__.d(getter, 'a', getter);
      /******/ 		return getter;
      /******/ 	};
      /******/
      /******/ 	// Object.prototype.hasOwnProperty.call
      /******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
      /******/
      /******/ 	// __webpack_public_path__
      /******/ 	__webpack_require__.p = "/dist/";
      /******/
      /******/
      /******/ 	// Load entry module and return exports
      /******/ 	return __webpack_require__(__webpack_require__.s = "./src/hls.ts");
      /******/ })
      /************************************************************************/
      /******/ ({
      
      /***/ "./node_modules/eventemitter3/index.js":
      /*!*********************************************!*\
        !*** ./node_modules/eventemitter3/index.js ***!
        \*********************************************/
      /*! no static exports found */
      /***/ (function(module, exports, __webpack_require__) {
      
      "use strict";
      
      
      var has = Object.prototype.hasOwnProperty
        , prefix = '~';
      
      /**
       * Constructor to create a storage for our `EE` objects.
       * An `Events` instance is a plain object whose properties are event names.
       *
       * @constructor
       * @private
       */
      function Events() {}
      
      //
      // We try to not inherit from `Object.prototype`. In some engines creating an
      // instance in this way is faster than calling `Object.create(null)` directly.
      // If `Object.create(null)` is not supported we prefix the event names with a
      // character to make sure that the built-in object properties are not
      // overridden or used as an attack vector.
      //
      if (Object.create) {
        Events.prototype = Object.create(null);
      
        //
        // This hack is needed because the `__proto__` property is still inherited in
        // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
        //
        if (!new Events().__proto__) prefix = false;
      }
      
      /**
       * Representation of a single event listener.
       *
       * @param {Function} fn The listener function.
       * @param {*} context The context to invoke the listener with.
       * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
       * @constructor
       * @private
       */
      function EE(fn, context, once) {
        this.fn = fn;
        this.context = context;
        this.once = once || false;
      }
      
      /**
       * Add a listener for a given event.
       *
       * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
       * @param {(String|Symbol)} event The event name.
       * @param {Function} fn The listener function.
       * @param {*} context The context to invoke the listener with.
       * @param {Boolean} once Specify if the listener is a one-time listener.
       * @returns {EventEmitter}
       * @private
       */
      function addListener(emitter, event, fn, context, once) {
        if (typeof fn !== 'function') {
          throw new TypeError('The listener must be a function');
        }
      
        var listener = new EE(fn, context || emitter, once)
          , evt = prefix ? prefix + event : event;
      
        if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
        else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
        else emitter._events[evt] = [emitter._events[evt], listener];
      
        return emitter;
      }
      
      /**
       * Clear event by name.
       *
       * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
       * @param {(String|Symbol)} evt The Event name.
       * @private
       */
      function clearEvent(emitter, evt) {
        if (--emitter._eventsCount === 0) emitter._events = new Events();
        else delete emitter._events[evt];
      }
      
      /**
       * Minimal `EventEmitter` interface that is molded against the Node.js
       * `EventEmitter` interface.
       *
       * @constructor
       * @public
       */
      function EventEmitter() {
        this._events = new Events();
        this._eventsCount = 0;
      }
      
      /**
       * Return an array listing the events for which the emitter has registered
       * listeners.
       *
       * @returns {Array}
       * @public
       */
      EventEmitter.prototype.eventNames = function eventNames() {
        var names = []
          , events
          , name;
      
        if (this._eventsCount === 0) return names;
      
        for (name in (events = this._events)) {
          if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
        }
      
        if (Object.getOwnPropertySymbols) {
          return names.concat(Object.getOwnPropertySymbols(events));
        }
      
        return names;
      };
      
      /**
       * Return the listeners registered for a given event.
       *
       * @param {(String|Symbol)} event The event name.
       * @returns {Array} The registered listeners.
       * @public
       */
      EventEmitter.prototype.listeners = function listeners(event) {
        var evt = prefix ? prefix + event : event
          , handlers = this._events[evt];
      
        if (!handlers) return [];
        if (handlers.fn) return [handlers.fn];
      
        for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
          ee[i] = handlers[i].fn;
        }
      
        return ee;
      };
      
      /**
       * Return the number of listeners listening to a given event.
       *
       * @param {(String|Symbol)} event The event name.
       * @returns {Number} The number of listeners.
       * @public
       */
      EventEmitter.prototype.listenerCount = function listenerCount(event) {
        var evt = prefix ? prefix + event : event
          , listeners = this._events[evt];
      
        if (!listeners) return 0;
        if (listeners.fn) return 1;
        return listeners.length;
      };
      
      /**
       * Calls each of the listeners registered for a given event.
       *
       * @param {(String|Symbol)} event The event name.
       * @returns {Boolean} `true` if the event had listeners, else `false`.
       * @public
       */
      EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
        var evt = prefix ? prefix + event : event;
      
        if (!this._events[evt]) return false;
      
        var listeners = this._events[evt]
          , len = arguments.length
          , args
          , i;
      
        if (listeners.fn) {
          if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
      
          switch (len) {
            case 1: return listeners.fn.call(listeners.context), true;
            case 2: return listeners.fn.call(listeners.context, a1), true;
            case 3: return listeners.fn.call(listeners.context, a1, a2), true;
            case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
            case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
            case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
          }
      
          for (i = 1, args = new Array(len -1); i < len; i++) {
            args[i - 1] = arguments[i];
          }
      
          listeners.fn.apply(listeners.context, args);
        } else {
          var length = listeners.length
            , j;
      
          for (i = 0; i < length; i++) {
            if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
      
            switch (len) {
              case 1: listeners[i].fn.call(listeners[i].context); break;
              case 2: listeners[i].fn.call(listeners[i].context, a1); break;
              case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
              case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
              default:
                if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
                  args[j - 1] = arguments[j];
                }
      
                listeners[i].fn.apply(listeners[i].context, args);
            }
          }
        }
      
        return true;
      };
      
      /**
       * Add a listener for a given event.
       *
       * @param {(String|Symbol)} event The event name.
       * @param {Function} fn The listener function.
       * @param {*} [context=this] The context to invoke the listener with.
       * @returns {EventEmitter} `this`.
       * @public
       */
      EventEmitter.prototype.on = function on(event, fn, context) {
        return addListener(this, event, fn, context, false);
      };
      
      /**
       * Add a one-time listener for a given event.
       *
       * @param {(String|Symbol)} event The event name.
       * @param {Function} fn The listener function.
       * @param {*} [context=this] The context to invoke the listener with.
       * @returns {EventEmitter} `this`.
       * @public
       */
      EventEmitter.prototype.once = function once(event, fn, context) {
        return addListener(this, event, fn, context, true);
      };
      
      /**
       * Remove the listeners of a given event.
       *
       * @param {(String|Symbol)} event The event name.
       * @param {Function} fn Only remove the listeners that match this function.
       * @param {*} context Only remove the listeners that have this context.
       * @param {Boolean} once Only remove one-time listeners.
       * @returns {EventEmitter} `this`.
       * @public
       */
      EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
        var evt = prefix ? prefix + event : event;
      
        if (!this._events[evt]) return this;
        if (!fn) {
          clearEvent(this, evt);
          return this;
        }
      
        var listeners = this._events[evt];
      
        if (listeners.fn) {
          if (
            listeners.fn === fn &&
            (!once || listeners.once) &&
            (!context || listeners.context === context)
          ) {
            clearEvent(this, evt);
          }
        } else {
          for (var i = 0, events = [], length = listeners.length; i < length; i++) {
            if (
              listeners[i].fn !== fn ||
              (once && !listeners[i].once) ||
              (context && listeners[i].context !== context)
            ) {
              events.push(listeners[i]);
            }
          }
      
          //
          // Reset the array, or remove it completely if we have no more listeners.
          //
          if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
          else clearEvent(this, evt);
        }
      
        return this;
      };
      
      /**
       * Remove all listeners, or those of the specified event.
       *
       * @param {(String|Symbol)} [event] The event name.
       * @returns {EventEmitter} `this`.
       * @public
       */
      EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
        var evt;
      
        if (event) {
          evt = prefix ? prefix + event : event;
          if (this._events[evt]) clearEvent(this, evt);
        } else {
          this._events = new Events();
          this._eventsCount = 0;
        }
      
        return this;
      };
      
      //
      // Alias methods names because people roll like that.
      //
      EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
      EventEmitter.prototype.addListener = EventEmitter.prototype.on;
      
      //
      // Expose the prefix.
      //
      EventEmitter.prefixed = prefix;
      
      //
      // Allow `EventEmitter` to be imported as module namespace.
      //
      EventEmitter.EventEmitter = EventEmitter;
      
      //
      // Expose the module.
      //
      if (true) {
        module.exports = EventEmitter;
      }
      
      
      /***/ }),
      
      /***/ "./node_modules/url-toolkit/src/url-toolkit.js":
      /*!*****************************************************!*\
        !*** ./node_modules/url-toolkit/src/url-toolkit.js ***!
        \*****************************************************/
      /*! no static exports found */
      /***/ (function(module, exports, __webpack_require__) {
      
      // see https://tools.ietf.org/html/rfc1808
      
      (function (root) {
        var URL_REGEX =
          /^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/?#]*\/)*[^;?#]*)?(;[^?#]*)?(\?[^#]*)?(#[^]*)?$/;
        var FIRST_SEGMENT_REGEX = /^([^\/?#]*)([^]*)$/;
        var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
        var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
      
        var URLToolkit = {
          // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
          // E.g
          // With opts.alwaysNormalize = false (default, spec compliant)
          // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
          // With opts.alwaysNormalize = true (not spec compliant)
          // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
          buildAbsoluteURL: function (baseURL, relativeURL, opts) {
            opts = opts || {};
            // remove any remaining space and CRLF
            baseURL = baseURL.trim();
            relativeURL = relativeURL.trim();
            if (!relativeURL) {
              // 2a) If the embedded URL is entirely empty, it inherits the
              // entire base URL (i.e., is set equal to the base URL)
              // and we are done.
              if (!opts.alwaysNormalize) {
                return baseURL;
              }
              var basePartsForNormalise = URLToolkit.parseURL(baseURL);
              if (!basePartsForNormalise) {
                throw new Error('Error trying to parse base URL.');
              }
              basePartsForNormalise.path = URLToolkit.normalizePath(
                basePartsForNormalise.path
              );
              return URLToolkit.buildURLFromParts(basePartsForNormalise);
            }
            var relativeParts = URLToolkit.parseURL(relativeURL);
            if (!relativeParts) {
              throw new Error('Error trying to parse relative URL.');
            }
            if (relativeParts.scheme) {
              // 2b) If the embedded URL starts with a scheme name, it is
              // interpreted as an absolute URL and we are done.
              if (!opts.alwaysNormalize) {
                return relativeURL;
              }
              relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
              return URLToolkit.buildURLFromParts(relativeParts);
            }
            var baseParts = URLToolkit.parseURL(baseURL);
            if (!baseParts) {
              throw new Error('Error trying to parse base URL.');
            }
            if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
              // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
              // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
              var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
              baseParts.netLoc = pathParts[1];
              baseParts.path = pathParts[2];
            }
            if (baseParts.netLoc && !baseParts.path) {
              baseParts.path = '/';
            }
            var builtParts = {
              // 2c) Otherwise, the embedded URL inherits the scheme of
              // the base URL.
              scheme: baseParts.scheme,
              netLoc: relativeParts.netLoc,
              path: null,
              params: relativeParts.params,
              query: relativeParts.query,
              fragment: relativeParts.fragment,
            };
            if (!relativeParts.netLoc) {
              // 3) If the embedded URL's <net_loc> is non-empty, we skip to
              // Step 7.  Otherwise, the embedded URL inherits the <net_loc>
              // (if any) of the base URL.
              builtParts.netLoc = baseParts.netLoc;
              // 4) If the embedded URL path is preceded by a slash "/", the
              // path is not relative and we skip to Step 7.
              if (relativeParts.path[0] !== '/') {
                if (!relativeParts.path) {
                  // 5) If the embedded URL path is empty (and not preceded by a
                  // slash), then the embedded URL inherits the base URL path
                  builtParts.path = baseParts.path;
                  // 5a) if the embedded URL's <params> is non-empty, we skip to
                  // step 7; otherwise, it inherits the <params> of the base
                  // URL (if any) and
                  if (!relativeParts.params) {
                    builtParts.params = baseParts.params;
                    // 5b) if the embedded URL's <query> is non-empty, we skip to
                    // step 7; otherwise, it inherits the <query> of the base
                    // URL (if any) and we skip to step 7.
                    if (!relativeParts.query) {
                      builtParts.query = baseParts.query;
                    }
                  }
                } else {
                  // 6) The last segment of the base URL's path (anything
                  // following the rightmost slash "/", or the entire path if no
                  // slash is present) is removed and the embedded URL's path is
                  // appended in its place.
                  var baseURLPath = baseParts.path;
                  var newPath =
                    baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) +
                    relativeParts.path;
                  builtParts.path = URLToolkit.normalizePath(newPath);
                }
              }
            }
            if (builtParts.path === null) {
              builtParts.path = opts.alwaysNormalize
                ? URLToolkit.normalizePath(relativeParts.path)
                : relativeParts.path;
            }
            return URLToolkit.buildURLFromParts(builtParts);
          },
          parseURL: function (url) {
            var parts = URL_REGEX.exec(url);
            if (!parts) {
              return null;
            }
            return {
              scheme: parts[1] || '',
              netLoc: parts[2] || '',
              path: parts[3] || '',
              params: parts[4] || '',
              query: parts[5] || '',
              fragment: parts[6] || '',
            };
          },
          normalizePath: function (path) {
            // The following operations are
            // then applied, in order, to the new path:
            // 6a) All occurrences of "./", where "." is a complete path
            // segment, are removed.
            // 6b) If the path ends with "." as a complete path segment,
            // that "." is removed.
            path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');
            // 6c) All occurrences of "<segment>/../", where <segment> is a
            // complete path segment not equal to "..", are removed.
            // Removal of these path segments is performed iteratively,
            // removing the leftmost matching pattern on each iteration,
            // until no matching pattern remains.
            // 6d) If the path ends with "<segment>/..", where <segment> is a
            // complete path segment not equal to "..", that
            // "<segment>/.." is removed.
            while (
              path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length
            ) {}
            return path.split('').reverse().join('');
          },
          buildURLFromParts: function (parts) {
            return (
              parts.scheme +
              parts.netLoc +
              parts.path +
              parts.params +
              parts.query +
              parts.fragment
            );
          },
        };
      
        if (true)
          module.exports = URLToolkit;
        else {}
      })(this);
      
      
      /***/ }),
      
      /***/ "./node_modules/webworkify-webpack/index.js":
      /*!**************************************************!*\
        !*** ./node_modules/webworkify-webpack/index.js ***!
        \**************************************************/
      /*! no static exports found */
      /***/ (function(module, exports, __webpack_require__) {
      
      function webpackBootstrapFunc (modules) {
      /******/  // The module cache
      /******/  var installedModules = {};
      
      /******/  // The require function
      /******/  function __webpack_require__(moduleId) {
      
      /******/    // Check if module is in cache
      /******/    if(installedModules[moduleId])
      /******/      return installedModules[moduleId].exports;
      
      /******/    // Create a new module (and put it into the cache)
      /******/    var module = installedModules[moduleId] = {
      /******/      i: moduleId,
      /******/      l: false,
      /******/      exports: {}
      /******/    };
      
      /******/    // Execute the module function
      /******/    modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
      
      /******/    // Flag the module as loaded
      /******/    module.l = true;
      
      /******/    // Return the exports of the module
      /******/    return module.exports;
      /******/  }
      
      /******/  // expose the modules object (__webpack_modules__)
      /******/  __webpack_require__.m = modules;
      
      /******/  // expose the module cache
      /******/  __webpack_require__.c = installedModules;
      
      /******/  // identity function for calling harmony imports with the correct context
      /******/  __webpack_require__.i = function(value) { return value; };
      
      /******/  // define getter function for harmony exports
      /******/  __webpack_require__.d = function(exports, name, getter) {
      /******/    if(!__webpack_require__.o(exports, name)) {
      /******/      Object.defineProperty(exports, name, {
      /******/        configurable: false,
      /******/        enumerable: true,
      /******/        get: getter
      /******/      });
      /******/    }
      /******/  };
      
      /******/  // define __esModule on exports
      /******/  __webpack_require__.r = function(exports) {
      /******/    Object.defineProperty(exports, '__esModule', { value: true });
      /******/  };
      
      /******/  // getDefaultExport function for compatibility with non-harmony modules
      /******/  __webpack_require__.n = function(module) {
      /******/    var getter = module && module.__esModule ?
      /******/      function getDefault() { return module['default']; } :
      /******/      function getModuleExports() { return module; };
      /******/    __webpack_require__.d(getter, 'a', getter);
      /******/    return getter;
      /******/  };
      
      /******/  // Object.prototype.hasOwnProperty.call
      /******/  __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
      
      /******/  // __webpack_public_path__
      /******/  __webpack_require__.p = "/";
      
      /******/  // on error function for async loading
      /******/  __webpack_require__.oe = function(err) { console.error(err); throw err; };
      
        var f = __webpack_require__(__webpack_require__.s = ENTRY_MODULE)
        return f.default || f // try to call default if defined to also support babel esmodule exports
      }
      
      var moduleNameReqExp = '[\\.|\\-|\\+|\\w|\/|@]+'
      var dependencyRegExp = '\\(\\s*(\/\\*.*?\\*\/)?\\s*.*?(' + moduleNameReqExp + ').*?\\)' // additional chars when output.pathinfo is true
      
      // http://stackoverflow.com/a/2593661/130442
      function quoteRegExp (str) {
        return (str + '').replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&')
      }
      
      function isNumeric(n) {
        return !isNaN(1 * n); // 1 * n converts integers, integers as string ("123"), 1e3 and "1e3" to integers and strings to NaN
      }
      
      function getModuleDependencies (sources, module, queueName) {
        var retval = {}
        retval[queueName] = []
      
        var fnString = module.toString()
        var wrapperSignature = fnString.match(/^function\s?\w*\(\w+,\s*\w+,\s*(\w+)\)/)
        if (!wrapperSignature) return retval
        var webpackRequireName = wrapperSignature[1]
      
        // main bundle deps
        var re = new RegExp('(\\\\n|\\W)' + quoteRegExp(webpackRequireName) + dependencyRegExp, 'g')
        var match
        while ((match = re.exec(fnString))) {
          if (match[3] === 'dll-reference') continue
          retval[queueName].push(match[3])
        }
      
        // dll deps
        re = new RegExp('\\(' + quoteRegExp(webpackRequireName) + '\\("(dll-reference\\s(' + moduleNameReqExp + '))"\\)\\)' + dependencyRegExp, 'g')
        while ((match = re.exec(fnString))) {
          if (!sources[match[2]]) {
            retval[queueName].push(match[1])
            sources[match[2]] = __webpack_require__(match[1]).m
          }
          retval[match[2]] = retval[match[2]] || []
          retval[match[2]].push(match[4])
        }
      
        // convert 1e3 back to 1000 - this can be important after uglify-js converted 1000 to 1e3
        var keys = Object.keys(retval);
        for (var i = 0; i < keys.length; i++) {
          for (var j = 0; j < retval[keys[i]].length; j++) {
            if (isNumeric(retval[keys[i]][j])) {
              retval[keys[i]][j] = 1 * retval[keys[i]][j];
            }
          }
        }
      
        return retval
      }
      
      function hasValuesInQueues (queues) {
        var keys = Object.keys(queues)
        return keys.reduce(function (hasValues, key) {
          return hasValues || queues[key].length > 0
        }, false)
      }
      
      function getRequiredModules (sources, moduleId) {
        var modulesQueue = {
          main: [moduleId]
        }
        var requiredModules = {
          main: []
        }
        var seenModules = {
          main: {}
        }
      
        while (hasValuesInQueues(modulesQueue)) {
          var queues = Object.keys(modulesQueue)
          for (var i = 0; i < queues.length; i++) {
            var queueName = queues[i]
            var queue = modulesQueue[queueName]
            var moduleToCheck = queue.pop()
            seenModules[queueName] = seenModules[queueName] || {}
            if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue
            seenModules[queueName][moduleToCheck] = true
            requiredModules[queueName] = requiredModules[queueName] || []
            requiredModules[queueName].push(moduleToCheck)
            var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName)
            var newModulesKeys = Object.keys(newModules)
            for (var j = 0; j < newModulesKeys.length; j++) {
              modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || []
              modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]])
            }
          }
        }
      
        return requiredModules
      }
      
      module.exports = function (moduleId, options) {
        options = options || {}
        var sources = {
          main: __webpack_require__.m
        }
      
        var requiredModules = options.all ? { main: Object.keys(sources.main) } : getRequiredModules(sources, moduleId)
      
        var src = ''
      
        Object.keys(requiredModules).filter(function (m) { return m !== 'main' }).forEach(function (module) {
          var entryModule = 0
          while (requiredModules[module][entryModule]) {
            entryModule++
          }
          requiredModules[module].push(entryModule)
          sources[module][entryModule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })'
          src = src + 'var ' + module + ' = (' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(entryModule)) + ')({' + requiredModules[module].map(function (id) { return '' + JSON.stringify(id) + ': ' + sources[module][id].toString() }).join(',') + '});\n'
        })
      
        src = src + 'new ((' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(moduleId)) + ')({' + requiredModules.main.map(function (id) { return '' + JSON.stringify(id) + ': ' + sources.main[id].toString() }).join(',') + '}))(self);'
      
        var blob = new window.Blob([src], { type: 'text/javascript' })
        if (options.bare) { return blob }
      
        var URL = window.URL || window.webkitURL || window.mozURL || window.msURL
      
        var workerUrl = URL.createObjectURL(blob)
        var worker = new window.Worker(workerUrl)
        worker.objectURL = workerUrl
      
        return worker
      }
      
      
      /***/ }),
      
      /***/ "./src/config.ts":
      /*!***********************!*\
        !*** ./src/config.ts ***!
        \***********************/
      /*! exports provided: hlsDefaultConfig, mergeConfig, enableStreamingMode */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hlsDefaultConfig", function() { return hlsDefaultConfig; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeConfig", function() { return mergeConfig; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableStreamingMode", function() { return enableStreamingMode; });
      /* harmony import */ var _controller_abr_controller__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./controller/abr-controller */ "./src/controller/abr-controller.ts");
      /* harmony import */ var _controller_audio_stream_controller__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./controller/audio-stream-controller */ "./src/controller/audio-stream-controller.ts");
      /* harmony import */ var _controller_audio_track_controller__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./controller/audio-track-controller */ "./src/controller/audio-track-controller.ts");
      /* harmony import */ var _controller_subtitle_stream_controller__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./controller/subtitle-stream-controller */ "./src/controller/subtitle-stream-controller.ts");
      /* harmony import */ var _controller_subtitle_track_controller__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./controller/subtitle-track-controller */ "./src/controller/subtitle-track-controller.ts");
      /* harmony import */ var _controller_buffer_controller__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./controller/buffer-controller */ "./src/controller/buffer-controller.ts");
      /* harmony import */ var _controller_timeline_controller__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./controller/timeline-controller */ "./src/controller/timeline-controller.ts");
      /* harmony import */ var _controller_cap_level_controller__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./controller/cap-level-controller */ "./src/controller/cap-level-controller.ts");
      /* harmony import */ var _controller_fps_controller__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./controller/fps-controller */ "./src/controller/fps-controller.ts");
      /* harmony import */ var _controller_eme_controller__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./controller/eme-controller */ "./src/controller/eme-controller.ts");
      /* harmony import */ var _controller_cmcd_controller__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./controller/cmcd-controller */ "./src/controller/cmcd-controller.ts");
      /* harmony import */ var _utils_xhr_loader__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./utils/xhr-loader */ "./src/utils/xhr-loader.ts");
      /* harmony import */ var _utils_fetch_loader__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./utils/fetch-loader */ "./src/utils/fetch-loader.ts");
      /* harmony import */ var _utils_cues__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./utils/cues */ "./src/utils/cues.ts");
      /* harmony import */ var _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./utils/mediakeys-helper */ "./src/utils/mediakeys-helper.ts");
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./utils/logger */ "./src/utils/logger.ts");
      function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
      
      function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
      
      function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
      
      function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      // If possible, keep hlsDefaultConfig shallow
      // It is cloned whenever a new Hls instance is created, by keeping the config
      // shallow the properties are cloned, and we don't end up manipulating the default
      var hlsDefaultConfig = _objectSpread(_objectSpread({
        autoStartLoad: true,
        // used by stream-controller
        startPosition: -1,
        // used by stream-controller
        defaultAudioCodec: undefined,
        // used by stream-controller
        debug: false,
        // used by logger
        capLevelOnFPSDrop: false,
        // used by fps-controller
        capLevelToPlayerSize: false,
        // used by cap-level-controller
        initialLiveManifestSize: 1,
        // used by stream-controller
        maxBufferLength: 30,
        // used by stream-controller
        backBufferLength: Infinity,
        // used by buffer-controller
        maxBufferSize: 60 * 1000 * 1000,
        // used by stream-controller
        maxBufferHole: 0.1,
        // used by stream-controller
        highBufferWatchdogPeriod: 2,
        // used by stream-controller
        nudgeOffset: 0.1,
        // used by stream-controller
        nudgeMaxRetry: 3,
        // used by stream-controller
        maxFragLookUpTolerance: 0.25,
        // used by stream-controller
        liveSyncDurationCount: 3,
        // used by latency-controller
        liveMaxLatencyDurationCount: Infinity,
        // used by latency-controller
        liveSyncDuration: undefined,
        // used by latency-controller
        liveMaxLatencyDuration: undefined,
        // used by latency-controller
        maxLiveSyncPlaybackRate: 1,
        // used by latency-controller
        liveDurationInfinity: false,
        // used by buffer-controller
        liveBackBufferLength: null,
        // used by buffer-controller
        maxMaxBufferLength: 600,
        // used by stream-controller
        enableWorker: true,
        // used by demuxer
        enableSoftwareAES: true,
        // used by decrypter
        manifestLoadingTimeOut: 10000,
        // used by playlist-loader
        manifestLoadingMaxRetry: 1,
        // used by playlist-loader
        manifestLoadingRetryDelay: 1000,
        // used by playlist-loader
        manifestLoadingMaxRetryTimeout: 64000,
        // used by playlist-loader
        startLevel: undefined,
        // used by level-controller
        levelLoadingTimeOut: 10000,
        // used by playlist-loader
        levelLoadingMaxRetry: 4,
        // used by playlist-loader
        levelLoadingRetryDelay: 1000,
        // used by playlist-loader
        levelLoadingMaxRetryTimeout: 64000,
        // used by playlist-loader
        fragLoadingTimeOut: 20000,
        // used by fragment-loader
        fragLoadingMaxRetry: 6,
        // used by fragment-loader
        fragLoadingRetryDelay: 1000,
        // used by fragment-loader
        fragLoadingMaxRetryTimeout: 64000,
        // used by fragment-loader
        startFragPrefetch: false,
        // used by stream-controller
        fpsDroppedMonitoringPeriod: 5000,
        // used by fps-controller
        fpsDroppedMonitoringThreshold: 0.2,
        // used by fps-controller
        appendErrorMaxRetry: 3,
        // used by buffer-controller
        loader: _utils_xhr_loader__WEBPACK_IMPORTED_MODULE_11__["default"],
        // loader: FetchLoader,
        fLoader: undefined,
        // used by fragment-loader
        pLoader: undefined,
        // used by playlist-loader
        xhrSetup: undefined,
        // used by xhr-loader
        licenseXhrSetup: undefined,
        // used by eme-controller
        licenseResponseCallback: undefined,
        // used by eme-controller
        abrController: _controller_abr_controller__WEBPACK_IMPORTED_MODULE_0__["default"],
        bufferController: _controller_buffer_controller__WEBPACK_IMPORTED_MODULE_5__["default"],
        capLevelController: _controller_cap_level_controller__WEBPACK_IMPORTED_MODULE_7__["default"],
        fpsController: _controller_fps_controller__WEBPACK_IMPORTED_MODULE_8__["default"],
        stretchShortVideoTrack: false,
        // used by mp4-remuxer
        maxAudioFramesDrift: 1,
        // used by mp4-remuxer
        forceKeyFrameOnDiscontinuity: true,
        // used by ts-demuxer
        abrEwmaFastLive: 3,
        // used by abr-controller
        abrEwmaSlowLive: 9,
        // used by abr-controller
        abrEwmaFastVoD: 3,
        // used by abr-controller
        abrEwmaSlowVoD: 9,
        // used by abr-controller
        abrEwmaDefaultEstimate: 5e5,
        // 500 kbps  // used by abr-controller
        abrBandWidthFactor: 0.95,
        // used by abr-controller
        abrBandWidthUpFactor: 0.7,
        // used by abr-controller
        abrMaxWithRealBitrate: false,
        // used by abr-controller
        maxStarvationDelay: 4,
        // used by abr-controller
        maxLoadingDelay: 4,
        // used by abr-controller
        minAutoBitrate: 0,
        // used by hls
        emeEnabled: false,
        // used by eme-controller
        widevineLicenseUrl: undefined,
        // used by eme-controller
        drmSystemOptions: {},
        // used by eme-controller
        requestMediaKeySystemAccessFunc: _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_14__["requestMediaKeySystemAccess"],
        // used by eme-controller
        testBandwidth: true,
        progressive: false,
        lowLatencyMode: true,
        cmcd: undefined
      }, timelineConfig()), {}, {
        subtitleStreamController:  true ? _controller_subtitle_stream_controller__WEBPACK_IMPORTED_MODULE_3__["SubtitleStreamController"] : undefined,
        subtitleTrackController:  true ? _controller_subtitle_track_controller__WEBPACK_IMPORTED_MODULE_4__["default"] : undefined,
        timelineController:  true ? _controller_timeline_controller__WEBPACK_IMPORTED_MODULE_6__["TimelineController"] : undefined,
        audioStreamController:  true ? _controller_audio_stream_controller__WEBPACK_IMPORTED_MODULE_1__["default"] : undefined,
        audioTrackController:  true ? _controller_audio_track_controller__WEBPACK_IMPORTED_MODULE_2__["default"] : undefined,
        emeController:  true ? _controller_eme_controller__WEBPACK_IMPORTED_MODULE_9__["default"] : undefined,
        cmcdController:  true ? _controller_cmcd_controller__WEBPACK_IMPORTED_MODULE_10__["default"] : undefined
      });
      
      function timelineConfig() {
        return {
          cueHandler: _utils_cues__WEBPACK_IMPORTED_MODULE_13__["default"],
          // used by timeline-controller
          enableCEA708Captions: true,
          // used by timeline-controller
          enableWebVTT: true,
          // used by timeline-controller
          enableIMSC1: true,
          // used by timeline-controller
          captionsTextTrack1Label: 'English',
          // used by timeline-controller
          captionsTextTrack1LanguageCode: 'en',
          // used by timeline-controller
          captionsTextTrack2Label: 'Spanish',
          // used by timeline-controller
          captionsTextTrack2LanguageCode: 'es',
          // used by timeline-controller
          captionsTextTrack3Label: 'Unknown CC',
          // used by timeline-controller
          captionsTextTrack3LanguageCode: '',
          // used by timeline-controller
          captionsTextTrack4Label: 'Unknown CC',
          // used by timeline-controller
          captionsTextTrack4LanguageCode: '',
          // used by timeline-controller
          renderTextTracksNatively: true
        };
      }
      
      function mergeConfig(defaultConfig, userConfig) {
        if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {
          throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");
        }
      
        if (userConfig.liveMaxLatencyDurationCount !== undefined && (userConfig.liveSyncDurationCount === undefined || userConfig.liveMaxLatencyDurationCount <= userConfig.liveSyncDurationCount)) {
          throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');
        }
      
        if (userConfig.liveMaxLatencyDuration !== undefined && (userConfig.liveSyncDuration === undefined || userConfig.liveMaxLatencyDuration <= userConfig.liveSyncDuration)) {
          throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');
        }
      
        return _extends({}, defaultConfig, userConfig);
      }
      function enableStreamingMode(config) {
        var currentLoader = config.loader;
      
        if (currentLoader !== _utils_fetch_loader__WEBPACK_IMPORTED_MODULE_12__["default"] && currentLoader !== _utils_xhr_loader__WEBPACK_IMPORTED_MODULE_11__["default"]) {
          // If a developer has configured their own loader, respect that choice
          _utils_logger__WEBPACK_IMPORTED_MODULE_15__["logger"].log('[config]: Custom loader detected, cannot enable progressive streaming');
          config.progressive = false;
        } else {
          var canStreamProgressively = Object(_utils_fetch_loader__WEBPACK_IMPORTED_MODULE_12__["fetchSupported"])();
      
          if (canStreamProgressively) {
            config.loader = _utils_fetch_loader__WEBPACK_IMPORTED_MODULE_12__["default"];
            config.progressive = true;
            config.enableSoftwareAES = true;
            _utils_logger__WEBPACK_IMPORTED_MODULE_15__["logger"].log('[config]: Progressive streaming enabled, using FetchLoader');
          }
        }
      }
      
      /***/ }),
      
      /***/ "./src/controller/abr-controller.ts":
      /*!******************************************!*\
        !*** ./src/controller/abr-controller.ts ***!
        \******************************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
      /* harmony import */ var _utils_ewma_bandwidth_estimator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/ewma-bandwidth-estimator */ "./src/utils/ewma-bandwidth-estimator.ts");
      /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ "./src/events.ts");
      /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
      /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
      /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      
      
      
      function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
      
      function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
      
      
      
      
      
      
      
      
      var AbrController = /*#__PURE__*/function () {
        function AbrController(hls) {
          this.hls = void 0;
          this.lastLoadedFragLevel = 0;
          this._nextAutoLevel = -1;
          this.timer = void 0;
          this.onCheck = this._abandonRulesCheck.bind(this);
          this.fragCurrent = null;
          this.partCurrent = null;
          this.bitrateTestDelay = 0;
          this.bwEstimator = void 0;
          this.hls = hls;
          var config = hls.config;
          this.bwEstimator = new _utils_ewma_bandwidth_estimator__WEBPACK_IMPORTED_MODULE_1__["default"](config.abrEwmaSlowVoD, config.abrEwmaFastVoD, config.abrEwmaDefaultEstimate);
          this.registerListeners();
        }
      
        var _proto = AbrController.prototype;
      
        _proto.registerListeners = function registerListeners() {
          var hls = this.hls;
          hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOADING, this.onFragLoading, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOADED, this.onFragLoaded, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, this.onError, this);
        };
      
        _proto.unregisterListeners = function unregisterListeners() {
          var hls = this.hls;
          hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOADING, this.onFragLoading, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOADED, this.onFragLoaded, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, this.onError, this);
        };
      
        _proto.destroy = function destroy() {
          this.unregisterListeners();
          this.clearTimer(); // @ts-ignore
      
          this.hls = this.onCheck = null;
          this.fragCurrent = this.partCurrent = null;
        };
      
        _proto.onFragLoading = function onFragLoading(event, data) {
          var frag = data.frag;
      
          if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_5__["PlaylistLevelType"].MAIN) {
            if (!this.timer) {
              var _data$part;
      
              this.fragCurrent = frag;
              this.partCurrent = (_data$part = data.part) != null ? _data$part : null;
              this.timer = self.setInterval(this.onCheck, 100);
            }
          }
        };
      
        _proto.onLevelLoaded = function onLevelLoaded(event, data) {
          var config = this.hls.config;
      
          if (data.details.live) {
            this.bwEstimator.update(config.abrEwmaSlowLive, config.abrEwmaFastLive);
          } else {
            this.bwEstimator.update(config.abrEwmaSlowVoD, config.abrEwmaFastVoD);
          }
        }
        /*
            This method monitors the download rate of the current fragment, and will downswitch if that fragment will not load
            quickly enough to prevent underbuffering
          */
        ;
      
        _proto._abandonRulesCheck = function _abandonRulesCheck() {
          var frag = this.fragCurrent,
              part = this.partCurrent,
              hls = this.hls;
          var autoLevelEnabled = hls.autoLevelEnabled,
              config = hls.config,
              media = hls.media;
      
          if (!frag || !media) {
            return;
          }
      
          var stats = part ? part.stats : frag.stats;
          var duration = part ? part.duration : frag.duration; // If loading has been aborted and not in lowLatencyMode, stop timer and return
      
          if (stats.aborted) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn('frag loader destroy or aborted, disarm abandonRules');
            this.clearTimer(); // reset forced auto level value so that next level will be selected
      
            this._nextAutoLevel = -1;
            return;
          } // This check only runs if we're in ABR mode and actually playing
      
      
          if (!autoLevelEnabled || media.paused || !media.playbackRate || !media.readyState) {
            return;
          }
      
          var requestDelay = performance.now() - stats.loading.start;
          var playbackRate = Math.abs(media.playbackRate); // In order to work with a stable bandwidth, only begin monitoring bandwidth after half of the fragment has been loaded
      
          if (requestDelay <= 500 * duration / playbackRate) {
            return;
          }
      
          var levels = hls.levels,
              minAutoLevel = hls.minAutoLevel;
          var level = levels[frag.level];
          var expectedLen = stats.total || Math.max(stats.loaded, Math.round(duration * level.maxBitrate / 8));
          var loadRate = Math.max(1, stats.bwEstimate ? stats.bwEstimate / 8 : stats.loaded * 1000 / requestDelay); // fragLoadDelay is an estimate of the time (in seconds) it will take to buffer the entire fragment
      
          var fragLoadedDelay = (expectedLen - stats.loaded) / loadRate;
          var pos = media.currentTime; // bufferStarvationDelay is an estimate of the amount time (in seconds) it will take to exhaust the buffer
      
          var bufferStarvationDelay = (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(media, pos, config.maxBufferHole).end - pos) / playbackRate; // Attempt an emergency downswitch only if less than 2 fragment lengths are buffered, and the time to finish loading
          // the current fragment is greater than the amount of buffer we have left
      
          if (bufferStarvationDelay >= 2 * duration / playbackRate || fragLoadedDelay <= bufferStarvationDelay) {
            return;
          }
      
          var fragLevelNextLoadedDelay = Number.POSITIVE_INFINITY;
          var nextLoadLevel; // Iterate through lower level and try to find the largest one that avoids rebuffering
      
          for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
            // compute time to load next fragment at lower level
            // 0.8 : consider only 80% of current bw to be conservative
            // 8 = bits per byte (bps/Bps)
            var levelNextBitrate = levels[nextLoadLevel].maxBitrate;
            fragLevelNextLoadedDelay = duration * levelNextBitrate / (8 * 0.8 * loadRate);
      
            if (fragLevelNextLoadedDelay < bufferStarvationDelay) {
              break;
            }
          } // Only emergency switch down if it takes less time to load a new fragment at lowest level instead of continuing
          // to load the current one
      
      
          if (fragLevelNextLoadedDelay >= fragLoadedDelay) {
            return;
          }
      
          var bwEstimate = this.bwEstimator.getEstimate();
          _utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn("Fragment " + frag.sn + (part ? ' part ' + part.index : '') + " of level " + frag.level + " is loading too slowly and will cause an underbuffer; aborting and switching to level " + nextLoadLevel + "\n      Current BW estimate: " + (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(bwEstimate) ? (bwEstimate / 1024).toFixed(3) : 'Unknown') + " Kb/s\n      Estimated load time for current fragment: " + fragLoadedDelay.toFixed(3) + " s\n      Estimated load time for the next fragment: " + fragLevelNextLoadedDelay.toFixed(3) + " s\n      Time to underbuffer: " + bufferStarvationDelay.toFixed(3) + " s");
          hls.nextLoadLevel = nextLoadLevel;
          this.bwEstimator.sample(requestDelay, stats.loaded);
          this.clearTimer();
      
          if (frag.loader) {
            this.fragCurrent = this.partCurrent = null;
            frag.loader.abort();
          }
      
          hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOAD_EMERGENCY_ABORTED, {
            frag: frag,
            part: part,
            stats: stats
          });
        };
      
        _proto.onFragLoaded = function onFragLoaded(event, _ref) {
          var frag = _ref.frag,
              part = _ref.part;
      
          if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_5__["PlaylistLevelType"].MAIN && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.sn)) {
            var stats = part ? part.stats : frag.stats;
            var duration = part ? part.duration : frag.duration; // stop monitoring bw once frag loaded
      
            this.clearTimer(); // store level id after successful fragment load
      
            this.lastLoadedFragLevel = frag.level; // reset forced auto level value so that next level will be selected
      
            this._nextAutoLevel = -1; // compute level average bitrate
      
            if (this.hls.config.abrMaxWithRealBitrate) {
              var level = this.hls.levels[frag.level];
              var loadedBytes = (level.loaded ? level.loaded.bytes : 0) + stats.loaded;
              var loadedDuration = (level.loaded ? level.loaded.duration : 0) + duration;
              level.loaded = {
                bytes: loadedBytes,
                duration: loadedDuration
              };
              level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
            }
      
            if (frag.bitrateTest) {
              var fragBufferedData = {
                stats: stats,
                frag: frag,
                part: part,
                id: frag.type
              };
              this.onFragBuffered(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, fragBufferedData);
              frag.bitrateTest = false;
            }
          }
        };
      
        _proto.onFragBuffered = function onFragBuffered(event, data) {
          var frag = data.frag,
              part = data.part;
          var stats = part ? part.stats : frag.stats;
      
          if (stats.aborted) {
            return;
          } // Only count non-alt-audio frags which were actually buffered in our BW calculations
      
      
          if (frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_5__["PlaylistLevelType"].MAIN || frag.sn === 'initSegment') {
            return;
          } // Use the difference between parsing and request instead of buffering and request to compute fragLoadingProcessing;
          // rationale is that buffer appending only happens once media is attached. This can happen when config.startFragPrefetch
          // is used. If we used buffering in that case, our BW estimate sample will be very large.
      
      
          var processingMs = stats.parsing.end - stats.loading.start;
          this.bwEstimator.sample(processingMs, stats.loaded);
          stats.bwEstimate = this.bwEstimator.getEstimate();
      
          if (frag.bitrateTest) {
            this.bitrateTestDelay = processingMs / 1000;
          } else {
            this.bitrateTestDelay = 0;
          }
        };
      
        _proto.onError = function onError(event, data) {
          // stop timer in case of frag loading error
          switch (data.details) {
            case _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].FRAG_LOAD_ERROR:
            case _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].FRAG_LOAD_TIMEOUT:
              this.clearTimer();
              break;
      
            default:
              break;
          }
        };
      
        _proto.clearTimer = function clearTimer() {
          self.clearInterval(this.timer);
          this.timer = undefined;
        } // return next auto level
        ;
      
        _proto.getNextABRAutoLevel = function getNextABRAutoLevel() {
          var fragCurrent = this.fragCurrent,
              partCurrent = this.partCurrent,
              hls = this.hls;
          var maxAutoLevel = hls.maxAutoLevel,
              config = hls.config,
              minAutoLevel = hls.minAutoLevel,
              media = hls.media;
          var currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
          var pos = media ? media.currentTime : 0; // playbackRate is the absolute value of the playback rate; if media.playbackRate is 0, we use 1 to load as
          // if we're playing back at the normal rate.
      
          var playbackRate = media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1.0;
          var avgbw = this.bwEstimator ? this.bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate; // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.
      
          var bufferStarvationDelay = (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(media, pos, config.maxBufferHole).end - pos) / playbackRate; // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all
      
          var bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, config.abrBandWidthFactor, config.abrBandWidthUpFactor);
      
          if (bestLevel >= 0) {
            return bestLevel;
          }
      
          _utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].trace((bufferStarvationDelay ? 'rebuffering expected' : 'buffer is empty') + ", finding optimal quality level"); // not possible to get rid of rebuffering ... let's try to find level that will guarantee less than maxStarvationDelay of rebuffering
          // if no matching level found, logic will return 0
      
          var maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay;
          var bwFactor = config.abrBandWidthFactor;
          var bwUpFactor = config.abrBandWidthUpFactor;
      
          if (!bufferStarvationDelay) {
            // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test
            var bitrateTestDelay = this.bitrateTestDelay;
      
            if (bitrateTestDelay) {
              // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value
              // max video loading delay used in  automatic start level selection :
              // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +
              // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )
              // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration
              var maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
              maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
              _utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].trace("bitrate test took " + Math.round(1000 * bitrateTestDelay) + "ms, set first fragment max fetchDuration to " + Math.round(1000 * maxStarvationDelay) + " ms"); // don't use conservative factor on bitrate test
      
              bwFactor = bwUpFactor = 1;
            }
          }
      
          bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay + maxStarvationDelay, bwFactor, bwUpFactor);
          return Math.max(bestLevel, 0);
        };
      
        _proto.findBestLevel = function findBestLevel(currentBw, minAutoLevel, maxAutoLevel, maxFetchDuration, bwFactor, bwUpFactor) {
          var _level$details;
      
          var fragCurrent = this.fragCurrent,
              partCurrent = this.partCurrent,
              currentLevel = this.lastLoadedFragLevel;
          var levels = this.hls.levels;
          var level = levels[currentLevel];
          var live = !!(level !== null && level !== void 0 && (_level$details = level.details) !== null && _level$details !== void 0 && _level$details.live);
          var currentCodecSet = level === null || level === void 0 ? void 0 : level.codecSet;
          var currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
      
          for (var i = maxAutoLevel; i >= minAutoLevel; i--) {
            var levelInfo = levels[i];
      
            if (!levelInfo || currentCodecSet && levelInfo.codecSet !== currentCodecSet) {
              continue;
            }
      
            var levelDetails = levelInfo.details;
            var avgDuration = (partCurrent ? levelDetails === null || levelDetails === void 0 ? void 0 : levelDetails.partTarget : levelDetails === null || levelDetails === void 0 ? void 0 : levelDetails.averagetargetduration) || currentFragDuration;
            var adjustedbw = void 0; // follow algorithm captured from stagefright :
            // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp
            // Pick the highest bandwidth stream below or equal to estimated bandwidth.
            // consider only 80% of the available bandwidth, but if we are switching up,
            // be even more conservative (70%) to avoid overestimating and immediately
            // switching back.
      
            if (i <= currentLevel) {
              adjustedbw = bwFactor * currentBw;
            } else {
              adjustedbw = bwUpFactor * currentBw;
            }
      
            var bitrate = levels[i].maxBitrate;
            var fetchDuration = bitrate * avgDuration / adjustedbw;
            _utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: " + i + "/" + Math.round(adjustedbw) + "/" + bitrate + "/" + avgDuration + "/" + maxFetchDuration + "/" + fetchDuration); // if adjusted bw is greater than level bitrate AND
      
            if (adjustedbw > bitrate && ( // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
            // we don't account for max Fetch Duration for live streams, this is to avoid switching down when near the edge of live sliding window ...
            // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that findBestLevel will return -1
            !fetchDuration || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration)) {
              // as we are looping from highest to lowest, this will return the best achievable quality level
              return i;
            }
          } // not enough time budget even with quality level 0 ... rebuffering might happen
      
      
          return -1;
        };
      
        _createClass(AbrController, [{
          key: "nextAutoLevel",
          get: function get() {
            var forcedAutoLevel = this._nextAutoLevel;
            var bwEstimator = this.bwEstimator; // in case next auto level has been forced, and bw not available or not reliable, return forced value
      
            if (forcedAutoLevel !== -1 && (!bwEstimator || !bwEstimator.canEstimate())) {
              return forcedAutoLevel;
            } // compute next level using ABR logic
      
      
            var nextABRAutoLevel = this.getNextABRAutoLevel(); // if forced auto level has been defined, use it to cap ABR computed quality level
      
            if (forcedAutoLevel !== -1) {
              nextABRAutoLevel = Math.min(forcedAutoLevel, nextABRAutoLevel);
            }
      
            return nextABRAutoLevel;
          },
          set: function set(nextLevel) {
            this._nextAutoLevel = nextLevel;
          }
        }]);
      
        return AbrController;
      }();
      
      /* harmony default export */ __webpack_exports__["default"] = (AbrController);
      
      /***/ }),
      
      /***/ "./src/controller/audio-stream-controller.ts":
      /*!***************************************************!*\
        !*** ./src/controller/audio-stream-controller.ts ***!
        \***************************************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
      /* harmony import */ var _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./base-stream-controller */ "./src/controller/base-stream-controller.ts");
      /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ "./src/events.ts");
      /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
      /* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.ts");
      /* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../types/level */ "./src/types/level.ts");
      /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
      /* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts");
      /* harmony import */ var _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../demux/chunk-cache */ "./src/demux/chunk-cache.ts");
      /* harmony import */ var _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../demux/transmuxer-interface */ "./src/demux/transmuxer-interface.ts");
      /* harmony import */ var _types_transmuxer__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../types/transmuxer */ "./src/types/transmuxer.ts");
      /* harmony import */ var _fragment_finders__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./fragment-finders */ "./src/controller/fragment-finders.ts");
      /* harmony import */ var _utils_discontinuities__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/discontinuities */ "./src/utils/discontinuities.ts");
      /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      
      
      function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
      
      function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
      
      function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      var TICK_INTERVAL = 100; // how often to tick in ms
      
      var AudioStreamController = /*#__PURE__*/function (_BaseStreamController) {
        _inheritsLoose(AudioStreamController, _BaseStreamController);
      
        function AudioStreamController(hls, fragmentTracker) {
          var _this;
      
          _this = _BaseStreamController.call(this, hls, fragmentTracker, '[audio-stream-controller]') || this;
          _this.videoBuffer = null;
          _this.videoTrackCC = -1;
          _this.waitingVideoCC = -1;
          _this.audioSwitch = false;
          _this.trackId = -1;
          _this.waitingData = null;
          _this.mainDetails = null;
          _this.bufferFlushed = false;
      
          _this._registerListeners();
      
          return _this;
        }
      
        var _proto = AudioStreamController.prototype;
      
        _proto.onHandlerDestroying = function onHandlerDestroying() {
          this._unregisterListeners();
      
          this.mainDetails = null;
        };
      
        _proto._registerListeners = function _registerListeners() {
          var hls = this.hls;
          hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, this.onError, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_RESET, this.onBufferReset, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_CREATED, this.onBufferCreated, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_FLUSHED, this.onBufferFlushed, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].INIT_PTS_FOUND, this.onInitPtsFound, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
        };
      
        _proto._unregisterListeners = function _unregisterListeners() {
          var hls = this.hls;
          hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, this.onError, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_RESET, this.onBufferReset, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_CREATED, this.onBufferCreated, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_FLUSHED, this.onBufferFlushed, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].INIT_PTS_FOUND, this.onInitPtsFound, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
        } // INIT_PTS_FOUND is triggered when the video track parsed in the stream-controller has a new PTS value
        ;
      
        _proto.onInitPtsFound = function onInitPtsFound(event, _ref) {
          var frag = _ref.frag,
              id = _ref.id,
              initPTS = _ref.initPTS;
      
          // Always update the new INIT PTS
          // Can change due level switch
          if (id === 'main') {
            var cc = frag.cc;
            this.initPTS[frag.cc] = initPTS;
            this.log("InitPTS for cc: " + cc + " found from main: " + initPTS);
            this.videoTrackCC = cc; // If we are waiting, tick immediately to unblock audio fragment transmuxing
      
            if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_INIT_PTS) {
              this.tick();
            }
          }
        };
      
        _proto.startLoad = function startLoad(startPosition) {
          if (!this.levels) {
            this.startPosition = startPosition;
            this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].STOPPED;
            return;
          }
      
          var lastCurrentTime = this.lastCurrentTime;
          this.stopLoad();
          this.setInterval(TICK_INTERVAL);
          this.fragLoadError = 0;
      
          if (lastCurrentTime > 0 && startPosition === -1) {
            this.log("Override startPosition with lastCurrentTime @" + lastCurrentTime.toFixed(3));
            this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
          } else {
            this.loadedmetadata = false;
            this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_TRACK;
          }
      
          this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
          this.tick();
        };
      
        _proto.doTick = function doTick() {
          switch (this.state) {
            case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE:
              this.doTickIdle();
              break;
      
            case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_TRACK:
              {
                var _levels$trackId;
      
                var levels = this.levels,
                    trackId = this.trackId;
                var details = levels === null || levels === void 0 ? void 0 : (_levels$trackId = levels[trackId]) === null || _levels$trackId === void 0 ? void 0 : _levels$trackId.details;
      
                if (details) {
                  if (this.waitForCdnTuneIn(details)) {
                    break;
                  }
      
                  this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_INIT_PTS;
                }
      
                break;
              }
      
            case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING_WAITING_RETRY:
              {
                var _this$media;
      
                var now = performance.now();
                var retryDate = this.retryDate; // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
      
                if (!retryDate || now >= retryDate || (_this$media = this.media) !== null && _this$media !== void 0 && _this$media.seeking) {
                  this.log('RetryDate reached, switch back to IDLE state');
                  this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
                }
      
                break;
              }
      
            case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_INIT_PTS:
              {
                // Ensure we don't get stuck in the WAITING_INIT_PTS state if the waiting frag CC doesn't match any initPTS
                var waitingData = this.waitingData;
      
                if (waitingData) {
                  var frag = waitingData.frag,
                      part = waitingData.part,
                      cache = waitingData.cache,
                      complete = waitingData.complete;
      
                  if (this.initPTS[frag.cc] !== undefined) {
                    this.waitingData = null;
                    this.waitingVideoCC = -1;
                    this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING;
                    var payload = cache.flush();
                    var data = {
                      frag: frag,
                      part: part,
                      payload: payload,
                      networkDetails: null
                    };
      
                    this._handleFragmentLoadProgress(data);
      
                    if (complete) {
                      _BaseStreamController.prototype._handleFragmentLoadComplete.call(this, data);
                    }
                  } else if (this.videoTrackCC !== this.waitingVideoCC) {
                    // Drop waiting fragment if videoTrackCC has changed since waitingFragment was set and initPTS was not found
                    _utils_logger__WEBPACK_IMPORTED_MODULE_14__["logger"].log("Waiting fragment cc (" + frag.cc + ") cancelled because video is at cc " + this.videoTrackCC);
                    this.clearWaitingFragment();
                  } else {
                    // Drop waiting fragment if an earlier fragment is needed
                    var pos = this.getLoadPosition();
                    var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(this.mediaBuffer, pos, this.config.maxBufferHole);
                    var waitingFragmentAtPosition = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_11__["fragmentWithinToleranceTest"])(bufferInfo.end, this.config.maxFragLookUpTolerance, frag);
      
                    if (waitingFragmentAtPosition < 0) {
                      _utils_logger__WEBPACK_IMPORTED_MODULE_14__["logger"].log("Waiting fragment cc (" + frag.cc + ") @ " + frag.start + " cancelled because another fragment at " + bufferInfo.end + " is needed");
                      this.clearWaitingFragment();
                    }
                  }
                } else {
                  this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
                }
              }
          }
      
          this.onTickEnd();
        };
      
        _proto.clearWaitingFragment = function clearWaitingFragment() {
          var waitingData = this.waitingData;
      
          if (waitingData) {
            this.fragmentTracker.removeFragment(waitingData.frag);
            this.waitingData = null;
            this.waitingVideoCC = -1;
            this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
          }
        };
      
        _proto.onTickEnd = function onTickEnd() {
          var media = this.media;
      
          if (!media || !media.readyState) {
            // Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0)
            return;
          }
      
          var mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;
          var buffered = mediaBuffer.buffered;
      
          if (!this.loadedmetadata && buffered.length) {
            this.loadedmetadata = true;
          }
      
          this.lastCurrentTime = media.currentTime;
        };
      
        _proto.doTickIdle = function doTickIdle() {
          var _frag$decryptdata, _frag$decryptdata2;
      
          var hls = this.hls,
              levels = this.levels,
              media = this.media,
              trackId = this.trackId;
          var config = hls.config;
      
          if (!levels || !levels[trackId]) {
            return;
          } // if video not attached AND
          // start fragment already requested OR start frag prefetch not enabled
          // exit loop
          // => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop
      
      
          if (!media && (this.startFragRequested || !config.startFragPrefetch)) {
            return;
          }
      
          var levelInfo = levels[trackId];
          var trackDetails = levelInfo.details;
      
          if (!trackDetails || trackDetails.live && this.levelLastLoaded !== trackId || this.waitForCdnTuneIn(trackDetails)) {
            this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_TRACK;
            return;
          }
      
          if (this.bufferFlushed) {
            this.bufferFlushed = false;
            this.afterBufferFlushed(this.mediaBuffer ? this.mediaBuffer : this.media, _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO);
          }
      
          var bufferInfo = this.getFwdBufferInfo(this.mediaBuffer ? this.mediaBuffer : this.media, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO);
      
          if (bufferInfo === null) {
            return;
          }
      
          var bufferLen = bufferInfo.len;
          var maxBufLen = this.getMaxBufferLength();
          var audioSwitch = this.audioSwitch; // if buffer length is less than maxBufLen try to load a new fragment
      
          if (bufferLen >= maxBufLen && !audioSwitch) {
            return;
          }
      
          if (!audioSwitch && this._streamEnded(bufferInfo, trackDetails)) {
            hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_EOS, {
              type: 'audio'
            });
            this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ENDED;
            return;
          }
      
          var fragments = trackDetails.fragments;
          var start = fragments[0].start;
          var targetBufferTime = bufferInfo.end;
      
          if (audioSwitch) {
            var pos = this.getLoadPosition();
            targetBufferTime = pos; // if currentTime (pos) is less than alt audio playlist start time, it means that alt audio is ahead of currentTime
      
            if (trackDetails.PTSKnown && pos < start) {
              // if everything is buffered from pos to start or if audio buffer upfront, let's seek to start
              if (bufferInfo.end > start || bufferInfo.nextStart) {
                this.log('Alt audio track ahead of main track, seek to start of alt audio track');
                media.currentTime = start + 0.05;
              }
            }
          }
      
          var frag = this.getNextFragment(targetBufferTime, trackDetails);
      
          if (!frag) {
            this.bufferFlushed = true;
            return;
          }
      
          if (((_frag$decryptdata = frag.decryptdata) === null || _frag$decryptdata === void 0 ? void 0 : _frag$decryptdata.keyFormat) === 'identity' && !((_frag$decryptdata2 = frag.decryptdata) !== null && _frag$decryptdata2 !== void 0 && _frag$decryptdata2.key)) {
            this.loadKey(frag, trackDetails);
          } else {
            this.loadFragment(frag, trackDetails, targetBufferTime);
          }
        };
      
        _proto.getMaxBufferLength = function getMaxBufferLength() {
          var maxConfigBuffer = _BaseStreamController.prototype.getMaxBufferLength.call(this);
      
          var mainBufferInfo = this.getFwdBufferInfo(this.videoBuffer ? this.videoBuffer : this.media, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN);
      
          if (mainBufferInfo === null) {
            return maxConfigBuffer;
          }
      
          return Math.max(maxConfigBuffer, mainBufferInfo.len);
        };
      
        _proto.onMediaDetaching = function onMediaDetaching() {
          this.videoBuffer = null;
      
          _BaseStreamController.prototype.onMediaDetaching.call(this);
        };
      
        _proto.onAudioTracksUpdated = function onAudioTracksUpdated(event, _ref2) {
          var audioTracks = _ref2.audioTracks;
          this.resetTransmuxer();
          this.levels = audioTracks.map(function (mediaPlaylist) {
            return new _types_level__WEBPACK_IMPORTED_MODULE_5__["Level"](mediaPlaylist);
          });
        };
      
        _proto.onAudioTrackSwitching = function onAudioTrackSwitching(event, data) {
          // if any URL found on new audio track, it is an alternate audio track
          var altAudio = !!data.url;
          this.trackId = data.id;
          var fragCurrent = this.fragCurrent;
      
          if (fragCurrent !== null && fragCurrent !== void 0 && fragCurrent.loader) {
            fragCurrent.loader.abort();
          }
      
          this.fragCurrent = null;
          this.clearWaitingFragment(); // destroy useless transmuxer when switching audio to main
      
          if (!altAudio) {
            this.resetTransmuxer();
          } else {
            // switching to audio track, start timer if not already started
            this.setInterval(TICK_INTERVAL);
          } // should we switch tracks ?
      
      
          if (altAudio) {
            this.audioSwitch = true; // main audio track are handled by stream-controller, just do something if switching to alt audio track
      
            this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
          } else {
            this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].STOPPED;
          }
      
          this.tick();
        };
      
        _proto.onManifestLoading = function onManifestLoading() {
          this.mainDetails = null;
          this.fragmentTracker.removeAllFragments();
          this.startPosition = this.lastCurrentTime = 0;
          this.bufferFlushed = false;
        };
      
        _proto.onLevelLoaded = function onLevelLoaded(event, data) {
          this.mainDetails = data.details;
        };
      
        _proto.onAudioTrackLoaded = function onAudioTrackLoaded(event, data) {
          var _track$details;
      
          var levels = this.levels;
          var newDetails = data.details,
              trackId = data.id;
      
          if (!levels) {
            this.warn("Audio tracks were reset while loading level " + trackId);
            return;
          }
      
          this.log("Track " + trackId + " loaded [" + newDetails.startSN + "," + newDetails.endSN + "],duration:" + newDetails.totalduration);
          var track = levels[trackId];
          var sliding = 0;
      
          if (newDetails.live || (_track$details = track.details) !== null && _track$details !== void 0 && _track$details.live) {
            var mainDetails = this.mainDetails;
      
            if (!newDetails.fragments[0]) {
              newDetails.deltaUpdateFailed = true;
            }
      
            if (newDetails.deltaUpdateFailed || !mainDetails) {
              return;
            }
      
            if (!track.details && newDetails.hasProgramDateTime && mainDetails.hasProgramDateTime) {
              // Make sure our audio rendition is aligned with the "main" rendition, using
              // pdt as our reference times.
              Object(_utils_discontinuities__WEBPACK_IMPORTED_MODULE_12__["alignMediaPlaylistByPDT"])(newDetails, mainDetails);
              sliding = newDetails.fragments[0].start;
            } else {
              sliding = this.alignPlaylists(newDetails, track.details);
            }
          }
      
          track.details = newDetails;
          this.levelLastLoaded = trackId; // compute start position if we are aligned with the main playlist
      
          if (!this.startFragRequested && (this.mainDetails || !newDetails.live)) {
            this.setStartPosition(track.details, sliding);
          } // only switch back to IDLE state if we were waiting for track to start downloading a new fragment
      
      
          if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_TRACK && !this.waitForCdnTuneIn(newDetails)) {
            this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
          } // trigger handler right now
      
      
          this.tick();
        };
      
        _proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(data) {
          var _frag$initSegment;
      
          var frag = data.frag,
              part = data.part,
              payload = data.payload;
          var config = this.config,
              trackId = this.trackId,
              levels = this.levels;
      
          if (!levels) {
            this.warn("Audio tracks were reset while fragment load was in progress. Fragment " + frag.sn + " of level " + frag.level + " will not be buffered");
            return;
          }
      
          var track = levels[trackId];
          console.assert(track, 'Audio track is defined on fragment load progress');
          var details = track.details;
          console.assert(details, 'Audio track details are defined on fragment load progress');
          var audioCodec = config.defaultAudioCodec || track.audioCodec || 'mp4a.40.2';
          var transmuxer = this.transmuxer;
      
          if (!transmuxer) {
            transmuxer = this.transmuxer = new _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_9__["default"](this.hls, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
          } // Check if we have video initPTS
          // If not we need to wait for it
      
      
          var initPTS = this.initPTS[frag.cc];
          var initSegmentData = (_frag$initSegment = frag.initSegment) === null || _frag$initSegment === void 0 ? void 0 : _frag$initSegment.data;
      
          if (initPTS !== undefined) {
            // this.log(`Transmuxing ${sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`);
            // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
            var accurateTimeOffset = false; // details.PTSKnown || !details.live;
      
            var partIndex = part ? part.index : -1;
            var partial = partIndex !== -1;
            var chunkMeta = new _types_transmuxer__WEBPACK_IMPORTED_MODULE_10__["ChunkMetadata"](frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
            transmuxer.push(payload, initSegmentData, audioCodec, '', frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
          } else {
            _utils_logger__WEBPACK_IMPORTED_MODULE_14__["logger"].log("Unknown video PTS for cc " + frag.cc + ", waiting for video PTS before demuxing audio frag " + frag.sn + " of [" + details.startSN + " ," + details.endSN + "],track " + trackId);
      
            var _this$waitingData = this.waitingData = this.waitingData || {
              frag: frag,
              part: part,
              cache: new _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_8__["default"](),
              complete: false
            },
                cache = _this$waitingData.cache;
      
            cache.push(new Uint8Array(payload));
            this.waitingVideoCC = this.videoTrackCC;
            this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_INIT_PTS;
          }
        };
      
        _proto._handleFragmentLoadComplete = function _handleFragmentLoadComplete(fragLoadedData) {
          if (this.waitingData) {
            this.waitingData.complete = true;
            return;
          }
      
          _BaseStreamController.prototype._handleFragmentLoadComplete.call(this, fragLoadedData);
        };
      
        _proto.onBufferReset = function
          /* event: Events.BUFFER_RESET */
        onBufferReset() {
          // reset reference to sourcebuffers
          this.mediaBuffer = this.videoBuffer = null;
          this.loadedmetadata = false;
        };
      
        _proto.onBufferCreated = function onBufferCreated(event, data) {
          var audioTrack = data.tracks.audio;
      
          if (audioTrack) {
            this.mediaBuffer = audioTrack.buffer;
          }
      
          if (data.tracks.video) {
            this.videoBuffer = data.tracks.video.buffer;
          }
        };
      
        _proto.onFragBuffered = function onFragBuffered(event, data) {
          var frag = data.frag,
              part = data.part;
      
          if (frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO) {
            return;
          }
      
          if (this.fragContextChanged(frag)) {
            // If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion
            // Avoid setting state back to IDLE or concluding the audio switch; otherwise, the switched-to track will not buffer
            this.warn("Fragment " + frag.sn + (part ? ' p: ' + part.index : '') + " of level " + frag.level + " finished buffering, but was aborted. state: " + this.state + ", audioSwitch: " + this.audioSwitch);
            return;
          }
      
          if (frag.sn !== 'initSegment') {
            this.fragPrevious = frag;
      
            if (this.audioSwitch) {
              this.audioSwitch = false;
              this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_SWITCHED, {
                id: this.trackId
              });
            }
          }
      
          this.fragBufferedComplete(frag, part);
        };
      
        _proto.onError = function onError(event, data) {
          switch (data.details) {
            case _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"].FRAG_LOAD_ERROR:
            case _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"].FRAG_LOAD_TIMEOUT:
            case _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"].KEY_LOAD_ERROR:
            case _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"].KEY_LOAD_TIMEOUT:
              // TODO: Skip fragments that do not belong to this.fragCurrent audio-group id
              this.onFragmentOrKeyLoadError(_types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO, data);
              break;
      
            case _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"].AUDIO_TRACK_LOAD_ERROR:
            case _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"].AUDIO_TRACK_LOAD_TIMEOUT:
              //  when in ERROR state, don't switch back to IDLE state in case a non-fatal error is received
              if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ERROR && this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].STOPPED) {
                // if fatal error, stop processing, otherwise move to IDLE to retry loading
                this.state = data.fatal ? _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ERROR : _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
                this.warn(data.details + " while loading frag, switching to " + this.state + " state");
              }
      
              break;
      
            case _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"].BUFFER_FULL_ERROR:
              // if in appending state
              if (data.parent === 'audio' && (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSED)) {
                var flushBuffer = true;
                var bufferedInfo = this.getFwdBufferInfo(this.mediaBuffer, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO); // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
                // reduce max buf len if current position is buffered
      
                if (bufferedInfo && bufferedInfo.len > 0.5) {
                  flushBuffer = !this.reduceMaxBufferLength(bufferedInfo.len);
                }
      
                if (flushBuffer) {
                  // current position is not buffered, but browser is still complaining about buffer full error
                  // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
                  // in that case flush the whole audio buffer to recover
                  this.warn('Buffer full error also media.currentTime is not buffered, flush audio buffer');
                  this.fragCurrent = null;
      
                  _BaseStreamController.prototype.flushMainBuffer.call(this, 0, Number.POSITIVE_INFINITY, 'audio');
                }
      
                this.resetLoadingState();
              }
      
              break;
      
            default:
              break;
          }
        };
      
        _proto.onBufferFlushed = function onBufferFlushed(event, _ref3) {
          var type = _ref3.type;
      
          if (type === _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO) {
            this.bufferFlushed = true;
          }
        };
      
        _proto._handleTransmuxComplete = function _handleTransmuxComplete(transmuxResult) {
          var _id3$samples;
      
          var id = 'audio';
          var hls = this.hls;
          var remuxResult = transmuxResult.remuxResult,
              chunkMeta = transmuxResult.chunkMeta;
          var context = this.getCurrentContext(chunkMeta);
      
          if (!context) {
            this.warn("The loading context changed while buffering fragment " + chunkMeta.sn + " of level " + chunkMeta.level + ". This chunk will not be buffered.");
            this.resetLiveStartWhenNotLoaded(chunkMeta.level);
            return;
          }
      
          var frag = context.frag,
              part = context.part;
          var audio = remuxResult.audio,
              text = remuxResult.text,
              id3 = remuxResult.id3,
              initSegment = remuxResult.initSegment; // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.
          // If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.
      
          if (this.fragContextChanged(frag)) {
            return;
          }
      
          this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING;
      
          if (this.audioSwitch && audio) {
            this.completeAudioSwitch();
          }
      
          if (initSegment !== null && initSegment !== void 0 && initSegment.tracks) {
            this._bufferInitSegment(initSegment.tracks, frag, chunkMeta);
      
            hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_PARSING_INIT_SEGMENT, {
              frag: frag,
              id: id,
              tracks: initSegment.tracks
            }); // Only flush audio from old audio tracks when PTS is known on new audio track
          }
      
          if (audio) {
            var startPTS = audio.startPTS,
                endPTS = audio.endPTS,
                startDTS = audio.startDTS,
                endDTS = audio.endDTS;
      
            if (part) {
              part.elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO] = {
                startPTS: startPTS,
                endPTS: endPTS,
                startDTS: startDTS,
                endDTS: endDTS
              };
            }
      
            frag.setElementaryStreamInfo(_loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO, startPTS, endPTS, startDTS, endDTS);
            this.bufferFragmentData(audio, frag, part, chunkMeta);
          }
      
          if (id3 !== null && id3 !== void 0 && (_id3$samples = id3.samples) !== null && _id3$samples !== void 0 && _id3$samples.length) {
            var emittedID3 = _extends({
              frag: frag,
              id: id
            }, id3);
      
            hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_PARSING_METADATA, emittedID3);
          }
      
          if (text) {
            var emittedText = _extends({
              frag: frag,
              id: id
            }, text);
      
            hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_PARSING_USERDATA, emittedText);
          }
        };
      
        _proto._bufferInitSegment = function _bufferInitSegment(tracks, frag, chunkMeta) {
          if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING) {
            return;
          } // delete any video track found on audio transmuxer
      
      
          if (tracks.video) {
            delete tracks.video;
          } // include levelCodec in audio and video tracks
      
      
          var track = tracks.audio;
      
          if (!track) {
            return;
          }
      
          track.levelCodec = track.codec;
          track.id = 'audio';
          this.log("Init audio buffer, container:" + track.container + ", codecs[parsed]=[" + track.codec + "]");
          this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_CODECS, tracks);
          var initSegment = track.initSegment;
      
          if (initSegment !== null && initSegment !== void 0 && initSegment.byteLength) {
            var segment = {
              type: 'audio',
              frag: frag,
              part: null,
              chunkMeta: chunkMeta,
              parent: frag.type,
              data: initSegment
            };
            this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_APPENDING, segment);
          } // trigger handler right now
      
      
          this.tick();
        };
      
        _proto.loadFragment = function loadFragment(frag, trackDetails, targetBufferTime) {
          // only load if fragment is not loaded or if in audio switch
          var fragState = this.fragmentTracker.getState(frag);
          this.fragCurrent = frag; // we force a frag loading in audio switch as fragment tracker might not have evicted previous frags in case of quick audio switch
      
          if (this.audioSwitch || fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_4__["FragmentState"].NOT_LOADED || fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_4__["FragmentState"].PARTIAL) {
            if (frag.sn === 'initSegment') {
              this._loadInitSegment(frag);
            } else if (trackDetails.live && !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.initPTS[frag.cc])) {
              this.log("Waiting for video PTS in continuity counter " + frag.cc + " of live stream before loading audio fragment " + frag.sn + " of level " + this.trackId);
              this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_INIT_PTS;
            } else {
              this.startFragRequested = true;
      
              _BaseStreamController.prototype.loadFragment.call(this, frag, trackDetails, targetBufferTime);
            }
          }
        };
      
        _proto.completeAudioSwitch = function completeAudioSwitch() {
          var hls = this.hls,
              media = this.media,
              trackId = this.trackId;
      
          if (media) {
            this.log('Switching audio track : flushing all audio');
      
            _BaseStreamController.prototype.flushMainBuffer.call(this, 0, Number.POSITIVE_INFINITY, 'audio');
          }
      
          this.audioSwitch = false;
          hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_SWITCHED, {
            id: trackId
          });
        };
      
        return AudioStreamController;
      }(_base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["default"]);
      
      /* harmony default export */ __webpack_exports__["default"] = (AudioStreamController);
      
      /***/ }),
      
      /***/ "./src/controller/audio-track-controller.ts":
      /*!**************************************************!*\
        !*** ./src/controller/audio-track-controller.ts ***!
        \**************************************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
      /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
      /* harmony import */ var _base_playlist_controller__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./base-playlist-controller */ "./src/controller/base-playlist-controller.ts");
      /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
      function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
      
      function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
      
      function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
      
      function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
      
      
      
      
      
      
      var AudioTrackController = /*#__PURE__*/function (_BasePlaylistControll) {
        _inheritsLoose(AudioTrackController, _BasePlaylistControll);
      
        function AudioTrackController(hls) {
          var _this;
      
          _this = _BasePlaylistControll.call(this, hls, '[audio-track-controller]') || this;
          _this.tracks = [];
          _this.groupId = null;
          _this.tracksInGroup = [];
          _this.trackId = -1;
          _this.trackName = '';
          _this.selectDefaultTrack = true;
      
          _this.registerListeners();
      
          return _this;
        }
      
        var _proto = AudioTrackController.prototype;
      
        _proto.registerListeners = function registerListeners() {
          var hls = this.hls;
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_SWITCHING, this.onLevelSwitching, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this);
        };
      
        _proto.unregisterListeners = function unregisterListeners() {
          var hls = this.hls;
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_SWITCHING, this.onLevelSwitching, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this);
        };
      
        _proto.destroy = function destroy() {
          this.unregisterListeners();
          this.tracks.length = 0;
          this.tracksInGroup.length = 0;
      
          _BasePlaylistControll.prototype.destroy.call(this);
        };
      
        _proto.onManifestLoading = function onManifestLoading() {
          this.tracks = [];
          this.groupId = null;
          this.tracksInGroup = [];
          this.trackId = -1;
          this.trackName = '';
          this.selectDefaultTrack = true;
        };
      
        _proto.onManifestParsed = function onManifestParsed(event, data) {
          this.tracks = data.audioTracks || [];
        };
      
        _proto.onAudioTrackLoaded = function onAudioTrackLoaded(event, data) {
          var id = data.id,
              details = data.details;
          var currentTrack = this.tracksInGroup[id];
      
          if (!currentTrack) {
            this.warn("Invalid audio track id " + id);
            return;
          }
      
          var curDetails = currentTrack.details;
          currentTrack.details = data.details;
          this.log("audioTrack " + id + " loaded [" + details.startSN + "-" + details.endSN + "]");
      
          if (id === this.trackId) {
            this.retryCount = 0;
            this.playlistLoaded(id, data, curDetails);
          }
        };
      
        _proto.onLevelLoading = function onLevelLoading(event, data) {
          this.switchLevel(data.level);
        };
      
        _proto.onLevelSwitching = function onLevelSwitching(event, data) {
          this.switchLevel(data.level);
        };
      
        _proto.switchLevel = function switchLevel(levelIndex) {
          var levelInfo = this.hls.levels[levelIndex];
      
          if (!(levelInfo !== null && levelInfo !== void 0 && levelInfo.audioGroupIds)) {
            return;
          }
      
          var audioGroupId = levelInfo.audioGroupIds[levelInfo.urlId];
      
          if (this.groupId !== audioGroupId) {
            this.groupId = audioGroupId;
            var audioTracks = this.tracks.filter(function (track) {
              return !audioGroupId || track.groupId === audioGroupId;
            }); // Disable selectDefaultTrack if there are no default tracks
      
            if (this.selectDefaultTrack && !audioTracks.some(function (track) {
              return track.default;
            })) {
              this.selectDefaultTrack = false;
            }
      
            this.tracksInGroup = audioTracks;
            var audioTracksUpdated = {
              audioTracks: audioTracks
            };
            this.log("Updating audio tracks, " + audioTracks.length + " track(s) found in \"" + audioGroupId + "\" group-id");
            this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].AUDIO_TRACKS_UPDATED, audioTracksUpdated);
            this.selectInitialTrack();
          }
        };
      
        _proto.onError = function onError(event, data) {
          _BasePlaylistControll.prototype.onError.call(this, event, data);
      
          if (data.fatal || !data.context) {
            return;
          }
      
          if (data.context.type === _types_loader__WEBPACK_IMPORTED_MODULE_3__["PlaylistContextType"].AUDIO_TRACK && data.context.id === this.trackId && data.context.groupId === this.groupId) {
            this.retryLoadingOrFail(data);
          }
        };
      
        _proto.setAudioTrack = function setAudioTrack(newId) {
          var tracks = this.tracksInGroup; // check if level idx is valid
      
          if (newId < 0 || newId >= tracks.length) {
            this.warn('Invalid id passed to audio-track controller');
            return;
          } // stopping live reloading timer if any
      
      
          this.clearTimer();
          var lastTrack = tracks[this.trackId];
          this.log("Now switching to audio-track index " + newId);
          var track = tracks[newId];
          var id = track.id,
              _track$groupId = track.groupId,
              groupId = _track$groupId === void 0 ? '' : _track$groupId,
              name = track.name,
              type = track.type,
              url = track.url;
          this.trackId = newId;
          this.trackName = name;
          this.selectDefaultTrack = false;
          this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].AUDIO_TRACK_SWITCHING, {
            id: id,
            groupId: groupId,
            name: name,
            type: type,
            url: url
          }); // Do not reload track unless live
      
          if (track.details && !track.details.live) {
            return;
          }
      
          var hlsUrlParameters = this.switchParams(track.url, lastTrack === null || lastTrack === void 0 ? void 0 : lastTrack.details);
          this.loadPlaylist(hlsUrlParameters);
        };
      
        _proto.selectInitialTrack = function selectInitialTrack() {
          var audioTracks = this.tracksInGroup;
          console.assert(audioTracks.length, 'Initial audio track should be selected when tracks are known');
          var currentAudioTrackName = this.trackName;
          var trackId = this.findTrackId(currentAudioTrackName) || this.findTrackId();
      
          if (trackId !== -1) {
            this.setAudioTrack(trackId);
          } else {
            this.warn("No track found for running audio group-ID: " + this.groupId);
            this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
              type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
              details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].AUDIO_TRACK_LOAD_ERROR,
              fatal: true
            });
          }
        };
      
        _proto.findTrackId = function findTrackId(name) {
          var audioTracks = this.tracksInGroup;
      
          for (var i = 0; i < audioTracks.length; i++) {
            var track = audioTracks[i];
      
            if (!this.selectDefaultTrack || track.default) {
              if (!name || name === track.name) {
                return track.id;
              }
            }
          }
      
          return -1;
        };
      
        _proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {
          var audioTrack = this.tracksInGroup[this.trackId];
      
          if (this.shouldLoadTrack(audioTrack)) {
            var id = audioTrack.id;
            var groupId = audioTrack.groupId;
            var url = audioTrack.url;
      
            if (hlsUrlParameters) {
              try {
                url = hlsUrlParameters.addDirectives(url);
              } catch (error) {
                this.warn("Could not construct new URL with HLS Delivery Directives: " + error);
              }
            } // track not retrieved yet, or live playlist we need to (re)load it
      
      
            this.log("loading audio-track playlist for id: " + id);
            this.clearTimer();
            this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].AUDIO_TRACK_LOADING, {
              url: url,
              id: id,
              groupId: groupId,
              deliveryDirectives: hlsUrlParameters || null
            });
          }
        };
      
        _createClass(AudioTrackController, [{
          key: "audioTracks",
          get: function get() {
            return this.tracksInGroup;
          }
        }, {
          key: "audioTrack",
          get: function get() {
            return this.trackId;
          },
          set: function set(newId) {
            // If audio track is selected from API then don't choose from the manifest default track
            this.selectDefaultTrack = false;
            this.setAudioTrack(newId);
          }
        }]);
      
        return AudioTrackController;
      }(_base_playlist_controller__WEBPACK_IMPORTED_MODULE_2__["default"]);
      
      /* harmony default export */ __webpack_exports__["default"] = (AudioTrackController);
      
      /***/ }),
      
      /***/ "./src/controller/base-playlist-controller.ts":
      /*!****************************************************!*\
        !*** ./src/controller/base-playlist-controller.ts ***!
        \****************************************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BasePlaylistController; });
      /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
      /* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../types/level */ "./src/types/level.ts");
      /* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.ts");
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
      
      
      
      
      
      
      
      var BasePlaylistController = /*#__PURE__*/function () {
        function BasePlaylistController(hls, logPrefix) {
          this.hls = void 0;
          this.timer = -1;
          this.canLoad = false;
          this.retryCount = 0;
          this.log = void 0;
          this.warn = void 0;
          this.log = _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"], logPrefix + ":");
          this.warn = _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"], logPrefix + ":");
          this.hls = hls;
        }
      
        var _proto = BasePlaylistController.prototype;
      
        _proto.destroy = function destroy() {
          this.clearTimer(); // @ts-ignore
      
          this.hls = this.log = this.warn = null;
        };
      
        _proto.onError = function onError(event, data) {
          if (data.fatal && data.type === _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorTypes"].NETWORK_ERROR) {
            this.clearTimer();
          }
        };
      
        _proto.clearTimer = function clearTimer() {
          clearTimeout(this.timer);
          this.timer = -1;
        };
      
        _proto.startLoad = function startLoad() {
          this.canLoad = true;
          this.retryCount = 0;
          this.loadPlaylist();
        };
      
        _proto.stopLoad = function stopLoad() {
          this.canLoad = false;
          this.clearTimer();
        };
      
        _proto.switchParams = function switchParams(playlistUri, previous) {
          var renditionReports = previous === null || previous === void 0 ? void 0 : previous.renditionReports;
      
          if (renditionReports) {
            for (var i = 0; i < renditionReports.length; i++) {
              var attr = renditionReports[i];
              var uri = '' + attr.URI;
      
              if (uri === playlistUri.substr(-uri.length)) {
                var msn = parseInt(attr['LAST-MSN']);
                var part = parseInt(attr['LAST-PART']);
      
                if (previous && this.hls.config.lowLatencyMode) {
                  var currentGoal = Math.min(previous.age - previous.partTarget, previous.targetduration);
      
                  if (part !== undefined && currentGoal > previous.partTarget) {
                    part += 1;
                  }
                }
      
                if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(msn)) {
                  return new _types_level__WEBPACK_IMPORTED_MODULE_1__["HlsUrlParameters"](msn, Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(part) ? part : undefined, _types_level__WEBPACK_IMPORTED_MODULE_1__["HlsSkip"].No);
                }
              }
            }
          }
        };
      
        _proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {};
      
        _proto.shouldLoadTrack = function shouldLoadTrack(track) {
          return this.canLoad && track && !!track.url && (!track.details || track.details.live);
        };
      
        _proto.playlistLoaded = function playlistLoaded(index, data, previousDetails) {
          var _this = this;
      
          var details = data.details,
              stats = data.stats; // Set last updated date-time
      
          var elapsed = stats.loading.end ? Math.max(0, self.performance.now() - stats.loading.end) : 0;
          details.advancedDateTime = Date.now() - elapsed; // if current playlist is a live playlist, arm a timer to reload it
      
          if (details.live || previousDetails !== null && previousDetails !== void 0 && previousDetails.live) {
            details.reloaded(previousDetails);
      
            if (previousDetails) {
              this.log("live playlist " + index + " " + (details.advanced ? 'REFRESHED ' + details.lastPartSn + '-' + details.lastPartIndex : 'MISSED'));
            } // Merge live playlists to adjust fragment starts and fill in delta playlist skipped segments
      
      
            if (previousDetails && details.fragments.length > 0) {
              Object(_level_helper__WEBPACK_IMPORTED_MODULE_2__["mergeDetails"])(previousDetails, details);
            }
      
            if (!this.canLoad || !details.live) {
              return;
            }
      
            var deliveryDirectives;
            var msn = undefined;
            var part = undefined;
      
            if (details.canBlockReload && details.endSN && details.advanced) {
              // Load level with LL-HLS delivery directives
              var lowLatencyMode = this.hls.config.lowLatencyMode;
              var lastPartSn = details.lastPartSn;
              var endSn = details.endSN;
              var lastPartIndex = details.lastPartIndex;
              var hasParts = lastPartIndex !== -1;
              var lastPart = lastPartSn === endSn; // When low latency mode is disabled, we'll skip part requests once the last part index is found
      
              var nextSnStartIndex = lowLatencyMode ? 0 : lastPartIndex;
      
              if (hasParts) {
                msn = lastPart ? endSn + 1 : lastPartSn;
                part = lastPart ? nextSnStartIndex : lastPartIndex + 1;
              } else {
                msn = endSn + 1;
              } // Low-Latency CDN Tune-in: "age" header and time since load indicates we're behind by more than one part
              // Update directives to obtain the Playlist that has the estimated additional duration of media
      
      
              var lastAdvanced = details.age;
              var cdnAge = lastAdvanced + details.ageHeader;
              var currentGoal = Math.min(cdnAge - details.partTarget, details.targetduration * 1.5);
      
              if (currentGoal > 0) {
                if (previousDetails && currentGoal > previousDetails.tuneInGoal) {
                  // If we attempted to get the next or latest playlist update, but currentGoal increased,
                  // then we either can't catchup, or the "age" header cannot be trusted.
                  this.warn("CDN Tune-in goal increased from: " + previousDetails.tuneInGoal + " to: " + currentGoal + " with playlist age: " + details.age);
                  currentGoal = 0;
                } else {
                  var segments = Math.floor(currentGoal / details.targetduration);
                  msn += segments;
      
                  if (part !== undefined) {
                    var parts = Math.round(currentGoal % details.targetduration / details.partTarget);
                    part += parts;
                  }
      
                  this.log("CDN Tune-in age: " + details.ageHeader + "s last advanced " + lastAdvanced.toFixed(2) + "s goal: " + currentGoal + " skip sn " + segments + " to part " + part);
                }
      
                details.tuneInGoal = currentGoal;
              }
      
              deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
      
              if (lowLatencyMode || !lastPart) {
                this.loadPlaylist(deliveryDirectives);
                return;
              }
            } else {
              deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
            }
      
            var reloadInterval = Object(_level_helper__WEBPACK_IMPORTED_MODULE_2__["computeReloadInterval"])(details, stats);
      
            if (msn !== undefined && details.canBlockReload) {
              reloadInterval -= details.partTarget || 1;
            }
      
            this.log("reload live playlist " + index + " in " + Math.round(reloadInterval) + " ms");
            this.timer = self.setTimeout(function () {
              return _this.loadPlaylist(deliveryDirectives);
            }, reloadInterval);
          } else {
            this.clearTimer();
          }
        };
      
        _proto.getDeliveryDirectives = function getDeliveryDirectives(details, previousDeliveryDirectives, msn, part) {
          var skip = Object(_types_level__WEBPACK_IMPORTED_MODULE_1__["getSkipValue"])(details, msn);
      
          if (previousDeliveryDirectives !== null && previousDeliveryDirectives !== void 0 && previousDeliveryDirectives.skip && details.deltaUpdateFailed) {
            msn = previousDeliveryDirectives.msn;
            part = previousDeliveryDirectives.part;
            skip = _types_level__WEBPACK_IMPORTED_MODULE_1__["HlsSkip"].No;
          }
      
          return new _types_level__WEBPACK_IMPORTED_MODULE_1__["HlsUrlParameters"](msn, part, skip);
        };
      
        _proto.retryLoadingOrFail = function retryLoadingOrFail(errorEvent) {
          var _this2 = this;
      
          var config = this.hls.config;
          var retry = this.retryCount < config.levelLoadingMaxRetry;
      
          if (retry) {
            var _errorEvent$context;
      
            this.retryCount++;
      
            if (errorEvent.details.indexOf('LoadTimeOut') > -1 && (_errorEvent$context = errorEvent.context) !== null && _errorEvent$context !== void 0 && _errorEvent$context.deliveryDirectives) {
              // The LL-HLS request already timed out so retry immediately
              this.warn("retry playlist loading #" + this.retryCount + " after \"" + errorEvent.details + "\"");
              this.loadPlaylist();
            } else {
              // exponential backoff capped to max retry timeout
              var delay = Math.min(Math.pow(2, this.retryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout); // Schedule level/track reload
      
              this.timer = self.setTimeout(function () {
                return _this2.loadPlaylist();
              }, delay);
              this.warn("retry playlist loading #" + this.retryCount + " in " + delay + " ms after \"" + errorEvent.details + "\"");
            }
          } else {
            this.warn("cannot recover from error \"" + errorEvent.details + "\""); // stopping live reloading timer if any
      
            this.clearTimer(); // switch error to fatal
      
            errorEvent.fatal = true;
          }
      
          return retry;
        };
      
        return BasePlaylistController;
      }();
      
      
      
      /***/ }),
      
      /***/ "./src/controller/base-stream-controller.ts":
      /*!**************************************************!*\
        !*** ./src/controller/base-stream-controller.ts ***!
        \**************************************************/
      /*! exports provided: State, default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "State", function() { return State; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BaseStreamController; });
      /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
      /* harmony import */ var _task_loop__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../task-loop */ "./src/task-loop.ts");
      /* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.ts");
      /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../events */ "./src/events.ts");
      /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
      /* harmony import */ var _types_transmuxer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../types/transmuxer */ "./src/types/transmuxer.ts");
      /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
      /* harmony import */ var _utils_discontinuities__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/discontinuities */ "./src/utils/discontinuities.ts");
      /* harmony import */ var _fragment_finders__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./fragment-finders */ "./src/controller/fragment-finders.ts");
      /* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.ts");
      /* harmony import */ var _loader_fragment_loader__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../loader/fragment-loader */ "./src/loader/fragment-loader.ts");
      /* harmony import */ var _crypt_decrypter__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../crypt/decrypter */ "./src/crypt/decrypter.ts");
      /* harmony import */ var _utils_time_ranges__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/time-ranges */ "./src/utils/time-ranges.ts");
      /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
      
      
      
      
      
      
      function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
      
      function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
      
      function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
      
      function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
      
      function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      var State = {
        STOPPED: 'STOPPED',
        IDLE: 'IDLE',
        KEY_LOADING: 'KEY_LOADING',
        FRAG_LOADING: 'FRAG_LOADING',
        FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
        WAITING_TRACK: 'WAITING_TRACK',
        PARSING: 'PARSING',
        PARSED: 'PARSED',
        BACKTRACKING: 'BACKTRACKING',
        ENDED: 'ENDED',
        ERROR: 'ERROR',
        WAITING_INIT_PTS: 'WAITING_INIT_PTS',
        WAITING_LEVEL: 'WAITING_LEVEL'
      };
      
      var BaseStreamController = /*#__PURE__*/function (_TaskLoop) {
        _inheritsLoose(BaseStreamController, _TaskLoop);
      
        function BaseStreamController(hls, fragmentTracker, logPrefix) {
          var _this;
      
          _this = _TaskLoop.call(this) || this;
          _this.hls = void 0;
          _this.fragPrevious = null;
          _this.fragCurrent = null;
          _this.fragmentTracker = void 0;
          _this.transmuxer = null;
          _this._state = State.STOPPED;
          _this.media = void 0;
          _this.mediaBuffer = void 0;
          _this.config = void 0;
          _this.bitrateTest = false;
          _this.lastCurrentTime = 0;
          _this.nextLoadPosition = 0;
          _this.startPosition = 0;
          _this.loadedmetadata = false;
          _this.fragLoadError = 0;
          _this.retryDate = 0;
          _this.levels = null;
          _this.fragmentLoader = void 0;
          _this.levelLastLoaded = null;
          _this.startFragRequested = false;
          _this.decrypter = void 0;
          _this.initPTS = [];
          _this.onvseeking = null;
          _this.onvended = null;
          _this.logPrefix = '';
          _this.log = void 0;
          _this.warn = void 0;
          _this.logPrefix = logPrefix;
          _this.log = _utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"].log.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"], logPrefix + ":");
          _this.warn = _utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"].warn.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"], logPrefix + ":");
          _this.hls = hls;
          _this.fragmentLoader = new _loader_fragment_loader__WEBPACK_IMPORTED_MODULE_12__["default"](hls.config);
          _this.fragmentTracker = fragmentTracker;
          _this.config = hls.config;
          _this.decrypter = new _crypt_decrypter__WEBPACK_IMPORTED_MODULE_13__["default"](hls, hls.config);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].KEY_LOADED, _this.onKeyLoaded, _assertThisInitialized(_this));
          return _this;
        }
      
        var _proto = BaseStreamController.prototype;
      
        _proto.doTick = function doTick() {
          this.onTickEnd();
        };
      
        _proto.onTickEnd = function onTickEnd() {} // eslint-disable-next-line @typescript-eslint/no-unused-vars
        ;
      
        _proto.startLoad = function startLoad(startPosition) {};
      
        _proto.stopLoad = function stopLoad() {
          this.fragmentLoader.abort();
          var frag = this.fragCurrent;
      
          if (frag) {
            this.fragmentTracker.removeFragment(frag);
          }
      
          this.resetTransmuxer();
          this.fragCurrent = null;
          this.fragPrevious = null;
          this.clearInterval();
          this.clearNextTick();
          this.state = State.STOPPED;
        };
      
        _proto._streamEnded = function _streamEnded(bufferInfo, levelDetails) {
          var fragCurrent = this.fragCurrent,
              fragmentTracker = this.fragmentTracker; // we just got done loading the final fragment and there is no other buffered range after ...
          // rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between
          // so we should not switch to ENDED in that case, to be able to buffer them
      
          if (!levelDetails.live && fragCurrent && fragCurrent.sn === levelDetails.endSN && !bufferInfo.nextStart) {
            var fragState = fragmentTracker.getState(fragCurrent);
            return fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].PARTIAL || fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].OK;
          }
      
          return false;
        };
      
        _proto.onMediaAttached = function onMediaAttached(event, data) {
          var media = this.media = this.mediaBuffer = data.media;
          this.onvseeking = this.onMediaSeeking.bind(this);
          this.onvended = this.onMediaEnded.bind(this);
          media.addEventListener('seeking', this.onvseeking);
          media.addEventListener('ended', this.onvended);
          var config = this.config;
      
          if (this.levels && config.autoStartLoad && this.state === State.STOPPED) {
            this.startLoad(config.startPosition);
          }
        };
      
        _proto.onMediaDetaching = function onMediaDetaching() {
          var media = this.media;
      
          if (media !== null && media !== void 0 && media.ended) {
            this.log('MSE detaching and video ended, reset startPosition');
            this.startPosition = this.lastCurrentTime = 0;
          } // remove video listeners
      
      
          if (media) {
            media.removeEventListener('seeking', this.onvseeking);
            media.removeEventListener('ended', this.onvended);
            this.onvseeking = this.onvended = null;
          }
      
          this.media = this.mediaBuffer = null;
          this.loadedmetadata = false;
          this.fragmentTracker.removeAllFragments();
          this.stopLoad();
        };
      
        _proto.onMediaSeeking = function onMediaSeeking() {
          var config = this.config,
              fragCurrent = this.fragCurrent,
              media = this.media,
              mediaBuffer = this.mediaBuffer,
              state = this.state;
          var currentTime = media ? media.currentTime : 0;
          var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(mediaBuffer || media, currentTime, config.maxBufferHole);
          this.log("media seeking to " + (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(currentTime) ? currentTime.toFixed(3) : currentTime) + ", state: " + state);
      
          if (state === State.ENDED) {
            this.resetLoadingState();
          } else if (fragCurrent && !bufferInfo.len) {
            // check if we are seeking to a unbuffered area AND if frag loading is in progress
            var tolerance = config.maxFragLookUpTolerance;
            var fragStartOffset = fragCurrent.start - tolerance;
            var fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;
            var pastFragment = currentTime > fragEndOffset; // check if the seek position is past current fragment, and if so abort loading
      
            if (currentTime < fragStartOffset || pastFragment) {
              if (pastFragment && fragCurrent.loader) {
                this.log('seeking outside of buffer while fragment load in progress, cancel fragment load');
                fragCurrent.loader.abort();
              }
      
              this.resetLoadingState();
            }
          }
      
          if (media) {
            this.lastCurrentTime = currentTime;
          } // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target
      
      
          if (!this.loadedmetadata && !bufferInfo.len) {
            this.nextLoadPosition = this.startPosition = currentTime;
          } // Async tick to speed up processing
      
      
          this.tickImmediate();
        };
      
        _proto.onMediaEnded = function onMediaEnded() {
          // reset startPosition and lastCurrentTime to restart playback @ stream beginning
          this.startPosition = this.lastCurrentTime = 0;
        };
      
        _proto.onKeyLoaded = function onKeyLoaded(event, data) {
          if (this.state !== State.KEY_LOADING || data.frag !== this.fragCurrent || !this.levels) {
            return;
          }
      
          this.state = State.IDLE;
          var levelDetails = this.levels[data.frag.level].details;
      
          if (levelDetails) {
            this.loadFragment(data.frag, levelDetails, data.frag.start);
          }
        };
      
        _proto.onHandlerDestroying = function onHandlerDestroying() {
          this.stopLoad();
      
          _TaskLoop.prototype.onHandlerDestroying.call(this);
        };
      
        _proto.onHandlerDestroyed = function onHandlerDestroyed() {
          this.state = State.STOPPED;
          this.hls.off(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].KEY_LOADED, this.onKeyLoaded, this);
      
          if (this.fragmentLoader) {
            this.fragmentLoader.destroy();
          }
      
          if (this.decrypter) {
            this.decrypter.destroy();
          }
      
          this.hls = this.log = this.warn = this.decrypter = this.fragmentLoader = this.fragmentTracker = null;
      
          _TaskLoop.prototype.onHandlerDestroyed.call(this);
        };
      
        _proto.loadKey = function loadKey(frag, details) {
          this.log("Loading key for " + frag.sn + " of [" + details.startSN + "-" + details.endSN + "], " + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + " " + frag.level);
          this.state = State.KEY_LOADING;
          this.fragCurrent = frag;
          this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].KEY_LOADING, {
            frag: frag
          });
        };
      
        _proto.loadFragment = function loadFragment(frag, levelDetails, targetBufferTime) {
          this._loadFragForPlayback(frag, levelDetails, targetBufferTime);
        };
      
        _proto._loadFragForPlayback = function _loadFragForPlayback(frag, levelDetails, targetBufferTime) {
          var _this2 = this;
      
          var progressCallback = function progressCallback(data) {
            if (_this2.fragContextChanged(frag)) {
              _this2.warn("Fragment " + frag.sn + (data.part ? ' p: ' + data.part.index : '') + " of level " + frag.level + " was dropped during download.");
      
              _this2.fragmentTracker.removeFragment(frag);
      
              return;
            }
      
            frag.stats.chunkCount++;
      
            _this2._handleFragmentLoadProgress(data);
          };
      
          this._doFragLoad(frag, levelDetails, targetBufferTime, progressCallback).then(function (data) {
            if (!data) {
              // if we're here we probably needed to backtrack or are waiting for more parts
              return;
            }
      
            _this2.fragLoadError = 0;
            var state = _this2.state;
      
            if (_this2.fragContextChanged(frag)) {
              if (state === State.FRAG_LOADING || state === State.BACKTRACKING || !_this2.fragCurrent && state === State.PARSING) {
                _this2.fragmentTracker.removeFragment(frag);
      
                _this2.state = State.IDLE;
              }
      
              return;
            }
      
            if ('payload' in data) {
              _this2.log("Loaded fragment " + frag.sn + " of level " + frag.level);
      
              _this2.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_LOADED, data); // Tracker backtrack must be called after onFragLoaded to update the fragment entity state to BACKTRACKED
              // This happens after handleTransmuxComplete when the worker or progressive is disabled
      
      
              if (_this2.state === State.BACKTRACKING) {
                _this2.fragmentTracker.backtrack(frag, data);
      
                _this2.resetFragmentLoading(frag);
      
                return;
              }
            } // Pass through the whole payload; controllers not implementing progressive loading receive data from this callback
      
      
            _this2._handleFragmentLoadComplete(data);
          }).catch(function (reason) {
            _this2.warn(reason);
      
            _this2.resetFragmentLoading(frag);
          });
        };
      
        _proto.flushMainBuffer = function flushMainBuffer(startOffset, endOffset, type) {
          if (type === void 0) {
            type = null;
          }
      
          if (!(startOffset - endOffset)) {
            return;
          } // When alternate audio is playing, the audio-stream-controller is responsible for the audio buffer. Otherwise,
          // passing a null type flushes both buffers
      
      
          var flushScope = {
            startOffset: startOffset,
            endOffset: endOffset,
            type: type
          }; // Reset load errors on flush
      
          this.fragLoadError = 0;
          this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].BUFFER_FLUSHING, flushScope);
        };
      
        _proto._loadInitSegment = function _loadInitSegment(frag) {
          var _this3 = this;
      
          this._doFragLoad(frag).then(function (data) {
            if (!data || _this3.fragContextChanged(frag) || !_this3.levels) {
              throw new Error('init load aborted');
            }
      
            return data;
          }).then(function (data) {
            var hls = _this3.hls;
            var payload = data.payload;
            var decryptData = frag.decryptdata; // check to see if the payload needs to be decrypted
      
            if (payload && payload.byteLength > 0 && decryptData && decryptData.key && decryptData.iv && decryptData.method === 'AES-128') {
              var startTime = self.performance.now(); // decrypt the subtitles
      
              return _this3.decrypter.webCryptoDecrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer).then(function (decryptedData) {
                var endTime = self.performance.now();
                hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_DECRYPTED, {
                  frag: frag,
                  payload: decryptedData,
                  stats: {
                    tstart: startTime,
                    tdecrypt: endTime
                  }
                });
                data.payload = decryptedData;
                return data;
              });
            }
      
            return data;
          }).then(function (data) {
            var fragCurrent = _this3.fragCurrent,
                hls = _this3.hls,
                levels = _this3.levels;
      
            if (!levels) {
              throw new Error('init load aborted, missing levels');
            }
      
            var details = levels[frag.level].details;
            console.assert(details, 'Level details are defined when init segment is loaded');
            var stats = frag.stats;
            _this3.state = State.IDLE;
            _this3.fragLoadError = 0;
            frag.data = new Uint8Array(data.payload);
            stats.parsing.start = stats.buffering.start = self.performance.now();
            stats.parsing.end = stats.buffering.end = self.performance.now(); // Silence FRAG_BUFFERED event if fragCurrent is null
      
            if (data.frag === fragCurrent) {
              hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_BUFFERED, {
                stats: stats,
                frag: fragCurrent,
                part: null,
                id: frag.type
              });
            }
      
            _this3.tick();
          }).catch(function (reason) {
            _this3.warn(reason);
      
            _this3.resetFragmentLoading(frag);
          });
        };
      
        _proto.fragContextChanged = function fragContextChanged(frag) {
          var fragCurrent = this.fragCurrent;
          return !frag || !fragCurrent || frag.level !== fragCurrent.level || frag.sn !== fragCurrent.sn || frag.urlId !== fragCurrent.urlId;
        };
      
        _proto.fragBufferedComplete = function fragBufferedComplete(frag, part) {
          var media = this.mediaBuffer ? this.mediaBuffer : this.media;
          this.log("Buffered " + frag.type + " sn: " + frag.sn + (part ? ' part: ' + part.index : '') + " of " + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + " " + frag.level + " " + _utils_time_ranges__WEBPACK_IMPORTED_MODULE_14__["default"].toString(_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].getBuffered(media)));
          this.state = State.IDLE;
          this.tick();
        };
      
        _proto._handleFragmentLoadComplete = function _handleFragmentLoadComplete(fragLoadedEndData) {
          var transmuxer = this.transmuxer;
      
          if (!transmuxer) {
            return;
          }
      
          var frag = fragLoadedEndData.frag,
              part = fragLoadedEndData.part,
              partsLoaded = fragLoadedEndData.partsLoaded; // If we did not load parts, or loaded all parts, we have complete (not partial) fragment data
      
          var complete = !partsLoaded || partsLoaded.length === 0 || partsLoaded.some(function (fragLoaded) {
            return !fragLoaded;
          });
          var chunkMeta = new _types_transmuxer__WEBPACK_IMPORTED_MODULE_7__["ChunkMetadata"](frag.level, frag.sn, frag.stats.chunkCount + 1, 0, part ? part.index : -1, !complete);
          transmuxer.flush(chunkMeta);
        } // eslint-disable-next-line @typescript-eslint/no-unused-vars
        ;
      
        _proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(frag) {};
      
        _proto._doFragLoad = function _doFragLoad(frag, details, targetBufferTime, progressCallback) {
          var _this4 = this;
      
          if (targetBufferTime === void 0) {
            targetBufferTime = null;
          }
      
          if (!this.levels) {
            throw new Error('frag load aborted, missing levels');
          }
      
          targetBufferTime = Math.max(frag.start, targetBufferTime || 0);
      
          if (this.config.lowLatencyMode && details) {
            var partList = details.partList;
      
            if (partList && progressCallback) {
              if (targetBufferTime > frag.end && details.fragmentHint) {
                frag = details.fragmentHint;
              }
      
              var partIndex = this.getNextPart(partList, frag, targetBufferTime);
      
              if (partIndex > -1) {
                var part = partList[partIndex];
                this.log("Loading part sn: " + frag.sn + " p: " + part.index + " cc: " + frag.cc + " of playlist [" + details.startSN + "-" + details.endSN + "] parts [0-" + partIndex + "-" + (partList.length - 1) + "] " + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + ": " + frag.level + ", target: " + parseFloat(targetBufferTime.toFixed(3)));
                this.nextLoadPosition = part.start + part.duration;
                this.state = State.FRAG_LOADING;
                this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_LOADING, {
                  frag: frag,
                  part: partList[partIndex],
                  targetBufferTime: targetBufferTime
                });
                return this.doFragPartsLoad(frag, partList, partIndex, progressCallback).catch(function (error) {
                  return _this4.handleFragLoadError(error);
                });
              } else if (!frag.url || this.loadedEndOfParts(partList, targetBufferTime)) {
                // Fragment hint has no parts
                return Promise.resolve(null);
              }
            }
          }
      
          this.log("Loading fragment " + frag.sn + " cc: " + frag.cc + " " + (details ? 'of [' + details.startSN + '-' + details.endSN + '] ' : '') + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + ": " + frag.level + ", target: " + parseFloat(targetBufferTime.toFixed(3))); // Don't update nextLoadPosition for fragments which are not buffered
      
          if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.sn) && !this.bitrateTest) {
            this.nextLoadPosition = frag.start + frag.duration;
          }
      
          this.state = State.FRAG_LOADING;
          this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_LOADING, {
            frag: frag,
            targetBufferTime: targetBufferTime
          });
          return this.fragmentLoader.load(frag, progressCallback).catch(function (error) {
            return _this4.handleFragLoadError(error);
          });
        };
      
        _proto.doFragPartsLoad = function doFragPartsLoad(frag, partList, partIndex, progressCallback) {
          var _this5 = this;
      
          return new Promise(function (resolve, reject) {
            var partsLoaded = [];
      
            var loadPartIndex = function loadPartIndex(index) {
              var part = partList[index];
      
              _this5.fragmentLoader.loadPart(frag, part, progressCallback).then(function (partLoadedData) {
                partsLoaded[part.index] = partLoadedData;
                var loadedPart = partLoadedData.part;
      
                _this5.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_LOADED, partLoadedData);
      
                var nextPart = partList[index + 1];
      
                if (nextPart && nextPart.fragment === frag) {
                  loadPartIndex(index + 1);
                } else {
                  return resolve({
                    frag: frag,
                    part: loadedPart,
                    partsLoaded: partsLoaded
                  });
                }
              }).catch(reject);
            };
      
            loadPartIndex(partIndex);
          });
        };
      
        _proto.handleFragLoadError = function handleFragLoadError(_ref) {
          var data = _ref.data;
      
          if (data && data.details === _errors__WEBPACK_IMPORTED_MODULE_6__["ErrorDetails"].INTERNAL_ABORTED) {
            this.handleFragLoadAborted(data.frag, data.part);
          } else {
            this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, data);
          }
      
          return null;
        };
      
        _proto._handleTransmuxerFlush = function _handleTransmuxerFlush(chunkMeta) {
          var context = this.getCurrentContext(chunkMeta);
      
          if (!context || this.state !== State.PARSING) {
            if (!this.fragCurrent) {
              this.state = State.IDLE;
            }
      
            return;
          }
      
          var frag = context.frag,
              part = context.part,
              level = context.level;
          var now = self.performance.now();
          frag.stats.parsing.end = now;
      
          if (part) {
            part.stats.parsing.end = now;
          }
      
          this.updateLevelTiming(frag, part, level, chunkMeta.partial);
        };
      
        _proto.getCurrentContext = function getCurrentContext(chunkMeta) {
          var levels = this.levels;
          var levelIndex = chunkMeta.level,
              sn = chunkMeta.sn,
              partIndex = chunkMeta.part;
      
          if (!levels || !levels[levelIndex]) {
            this.warn("Levels object was unset while buffering fragment " + sn + " of level " + levelIndex + ". The current chunk will not be buffered.");
            return null;
          }
      
          var level = levels[levelIndex];
          var part = partIndex > -1 ? Object(_level_helper__WEBPACK_IMPORTED_MODULE_11__["getPartWith"])(level, sn, partIndex) : null;
          var frag = part ? part.fragment : Object(_level_helper__WEBPACK_IMPORTED_MODULE_11__["getFragmentWithSN"])(level, sn, this.fragCurrent);
      
          if (!frag) {
            return null;
          }
      
          return {
            frag: frag,
            part: part,
            level: level
          };
        };
      
        _proto.bufferFragmentData = function bufferFragmentData(data, frag, part, chunkMeta) {
          if (!data || this.state !== State.PARSING) {
            return;
          }
      
          var data1 = data.data1,
              data2 = data.data2;
          var buffer = data1;
      
          if (data1 && data2) {
            // Combine the moof + mdat so that we buffer with a single append
            buffer = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_8__["appendUint8Array"])(data1, data2);
          }
      
          if (!buffer || !buffer.length) {
            return;
          }
      
          var segment = {
            type: data.type,
            frag: frag,
            part: part,
            chunkMeta: chunkMeta,
            parent: frag.type,
            data: buffer
          };
          this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].BUFFER_APPENDING, segment);
      
          if (data.dropped && data.independent && !part) {
            // Clear buffer so that we reload previous segments sequentially if required
            this.flushBufferGap(frag);
          }
        };
      
        _proto.flushBufferGap = function flushBufferGap(frag) {
          var media = this.media;
      
          if (!media) {
            return;
          } // If currentTime is not buffered, clear the back buffer so that we can backtrack as much as needed
      
      
          if (!_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].isBuffered(media, media.currentTime)) {
            this.flushMainBuffer(0, frag.start);
            return;
          } // Remove back-buffer without interrupting playback to allow back tracking
      
      
          var currentTime = media.currentTime;
          var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(media, currentTime, 0);
          var fragDuration = frag.duration;
          var segmentFraction = Math.min(this.config.maxFragLookUpTolerance * 2, fragDuration * 0.25);
          var start = Math.max(Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction), currentTime + segmentFraction);
      
          if (frag.start - start > segmentFraction) {
            this.flushMainBuffer(start, frag.start);
          }
        };
      
        _proto.getFwdBufferInfo = function getFwdBufferInfo(bufferable, type) {
          var config = this.config;
          var pos = this.getLoadPosition();
      
          if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(pos)) {
            return null;
          }
      
          var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(bufferable, pos, config.maxBufferHole); // Workaround flaw in getting forward buffer when maxBufferHole is smaller than gap at current pos
      
          if (bufferInfo.len === 0 && bufferInfo.nextStart !== undefined) {
            var bufferedFragAtPos = this.fragmentTracker.getBufferedFrag(pos, type);
      
            if (bufferedFragAtPos && bufferInfo.nextStart < bufferedFragAtPos.end) {
              return _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(bufferable, pos, Math.max(bufferInfo.nextStart, config.maxBufferHole));
            }
          }
      
          return bufferInfo;
        };
      
        _proto.getMaxBufferLength = function getMaxBufferLength(levelBitrate) {
          var config = this.config;
          var maxBufLen;
      
          if (levelBitrate) {
            maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
          } else {
            maxBufLen = config.maxBufferLength;
          }
      
          return Math.min(maxBufLen, config.maxMaxBufferLength);
        };
      
        _proto.reduceMaxBufferLength = function reduceMaxBufferLength(threshold) {
          var config = this.config;
          var minLength = threshold || config.maxBufferLength;
      
          if (config.maxMaxBufferLength >= minLength) {
            // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
            config.maxMaxBufferLength /= 2;
            this.warn("Reduce max buffer length to " + config.maxMaxBufferLength + "s");
            return true;
          }
      
          return false;
        };
      
        _proto.getNextFragment = function getNextFragment(pos, levelDetails) {
          var _frag, _frag2;
      
          var fragments = levelDetails.fragments;
          var fragLen = fragments.length;
      
          if (!fragLen) {
            return null;
          } // find fragment index, contiguous with end of buffer position
      
      
          var config = this.config;
          var start = fragments[0].start;
          var frag;
      
          if (levelDetails.live) {
            var initialLiveManifestSize = config.initialLiveManifestSize;
      
            if (fragLen < initialLiveManifestSize) {
              this.warn("Not enough fragments to start playback (have: " + fragLen + ", need: " + initialLiveManifestSize + ")");
              return null;
            } // The real fragment start times for a live stream are only known after the PTS range for that level is known.
            // In order to discover the range, we load the best matching fragment for that level and demux it.
            // Do not load using live logic if the starting frag is requested - we want to use getFragmentAtPosition() so that
            // we get the fragment matching that start time
      
      
            if (!levelDetails.PTSKnown && !this.startFragRequested && this.startPosition === -1) {
              frag = this.getInitialLiveFragment(levelDetails, fragments);
              this.startPosition = frag ? this.hls.liveSyncPosition || frag.start : pos;
            }
          } else if (pos <= start) {
            // VoD playlist: if loadPosition before start of playlist, load first fragment
            frag = fragments[0];
          } // If we haven't run into any special cases already, just load the fragment most closely matching the requested position
      
      
          if (!frag) {
            var end = config.lowLatencyMode ? levelDetails.partEnd : levelDetails.fragmentEnd;
            frag = this.getFragmentAtPosition(pos, end, levelDetails);
          } // If an initSegment is present, it must be buffered first
      
      
          if ((_frag = frag) !== null && _frag !== void 0 && _frag.initSegment && !((_frag2 = frag) !== null && _frag2 !== void 0 && _frag2.initSegment.data) && !this.bitrateTest) {
            frag = frag.initSegment;
          }
      
          return frag;
        };
      
        _proto.getNextPart = function getNextPart(partList, frag, targetBufferTime) {
          var nextPart = -1;
          var contiguous = false;
          var independentAttrOmitted = true;
      
          for (var i = 0, len = partList.length; i < len; i++) {
            var part = partList[i];
            independentAttrOmitted = independentAttrOmitted && !part.independent;
      
            if (nextPart > -1 && targetBufferTime < part.start) {
              break;
            }
      
            var loaded = part.loaded;
      
            if (!loaded && (contiguous || part.independent || independentAttrOmitted) && part.fragment === frag) {
              nextPart = i;
            }
      
            contiguous = loaded;
          }
      
          return nextPart;
        };
      
        _proto.loadedEndOfParts = function loadedEndOfParts(partList, targetBufferTime) {
          var lastPart = partList[partList.length - 1];
          return lastPart && targetBufferTime > lastPart.start && lastPart.loaded;
        }
        /*
         This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the
         "sliding" of the playlist, which is its offset from the start of playback. After sliding we can compute the real
         start and end times for each fragment in the playlist (after which this method will not need to be called).
        */
        ;
      
        _proto.getInitialLiveFragment = function getInitialLiveFragment(levelDetails, fragments) {
          var fragPrevious = this.fragPrevious;
          var frag = null;
      
          if (fragPrevious) {
            if (levelDetails.hasProgramDateTime) {
              // Prefer using PDT, because it can be accurate enough to choose the correct fragment without knowing the level sliding
              this.log("Live playlist, switching playlist, load frag with same PDT: " + fragPrevious.programDateTime);
              frag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_10__["findFragmentByPDT"])(fragments, fragPrevious.endProgramDateTime, this.config.maxFragLookUpTolerance);
            }
      
            if (!frag) {
              // SN does not need to be accurate between renditions, but depending on the packaging it may be so.
              var targetSN = fragPrevious.sn + 1;
      
              if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
                var fragNext = fragments[targetSN - levelDetails.startSN]; // Ensure that we're staying within the continuity range, since PTS resets upon a new range
      
                if (fragPrevious.cc === fragNext.cc) {
                  frag = fragNext;
                  this.log("Live playlist, switching playlist, load frag with next SN: " + frag.sn);
                }
              } // It's important to stay within the continuity range if available; otherwise the fragments in the playlist
              // will have the wrong start times
      
      
              if (!frag) {
                frag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_10__["findFragWithCC"])(fragments, fragPrevious.cc);
      
                if (frag) {
                  this.log("Live playlist, switching playlist, load frag with same CC: " + frag.sn);
                }
              }
            }
          } else {
            // Find a new start fragment when fragPrevious is null
            var liveStart = this.hls.liveSyncPosition;
      
            if (liveStart !== null) {
              frag = this.getFragmentAtPosition(liveStart, this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge, levelDetails);
            }
          }
      
          return frag;
        }
        /*
        This method finds the best matching fragment given the provided position.
         */
        ;
      
        _proto.getFragmentAtPosition = function getFragmentAtPosition(bufferEnd, end, levelDetails) {
          var config = this.config,
              fragPrevious = this.fragPrevious;
          var fragments = levelDetails.fragments,
              endSN = levelDetails.endSN;
          var fragmentHint = levelDetails.fragmentHint;
          var tolerance = config.maxFragLookUpTolerance;
          var loadingParts = !!(config.lowLatencyMode && levelDetails.partList && fragmentHint);
      
          if (loadingParts && fragmentHint && !this.bitrateTest) {
            // Include incomplete fragment with parts at end
            fragments = fragments.concat(fragmentHint);
            endSN = fragmentHint.sn;
          }
      
          var frag;
      
          if (bufferEnd < end) {
            var lookupTolerance = bufferEnd > end - tolerance ? 0 : tolerance; // Remove the tolerance if it would put the bufferEnd past the actual end of stream
            // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
      
            frag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_10__["findFragmentByPTS"])(fragPrevious, fragments, bufferEnd, lookupTolerance);
          } else {
            // reach end of playlist
            frag = fragments[fragments.length - 1];
          }
      
          if (frag) {
            var curSNIdx = frag.sn - levelDetails.startSN;
            var sameLevel = fragPrevious && frag.level === fragPrevious.level;
            var nextFrag = fragments[curSNIdx + 1];
            var fragState = this.fragmentTracker.getState(frag);
      
            if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].BACKTRACKED) {
              frag = null;
              var i = curSNIdx;
      
              while (fragments[i] && this.fragmentTracker.getState(fragments[i]) === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].BACKTRACKED) {
                // When fragPrevious is null, backtrack to first the first fragment is not BACKTRACKED for loading
                // When fragPrevious is set, we want the first BACKTRACKED fragment for parsing and buffering
                if (!fragPrevious) {
                  frag = fragments[--i];
                } else {
                  frag = fragments[i--];
                }
              }
      
              if (!frag) {
                frag = nextFrag;
              }
            } else if (fragPrevious && frag.sn === fragPrevious.sn && !loadingParts) {
              // Force the next fragment to load if the previous one was already selected. This can occasionally happen with
              // non-uniform fragment durations
              if (sameLevel) {
                if (frag.sn < endSN && this.fragmentTracker.getState(nextFrag) !== _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].OK) {
                  this.log("SN " + frag.sn + " just loaded, load next one: " + nextFrag.sn);
                  frag = nextFrag;
                } else {
                  frag = null;
                }
              }
            }
          }
      
          return frag;
        };
      
        _proto.synchronizeToLiveEdge = function synchronizeToLiveEdge(levelDetails) {
          var config = this.config,
              media = this.media;
      
          if (!media) {
            return;
          }
      
          var liveSyncPosition = this.hls.liveSyncPosition;
          var currentTime = media.currentTime;
          var start = levelDetails.fragments[0].start;
          var end = levelDetails.edge;
          var withinSlidingWindow = currentTime >= start - config.maxFragLookUpTolerance && currentTime <= end; // Continue if we can seek forward to sync position or if current time is outside of sliding window
      
          if (liveSyncPosition !== null && media.duration > liveSyncPosition && (currentTime < liveSyncPosition || !withinSlidingWindow)) {
            // Continue if buffer is starving or if current time is behind max latency
            var maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
      
            if (!withinSlidingWindow && media.readyState < 4 || currentTime < end - maxLatency) {
              if (!this.loadedmetadata) {
                this.nextLoadPosition = liveSyncPosition;
              } // Only seek if ready and there is not a significant forward buffer available for playback
      
      
              if (media.readyState) {
                this.warn("Playback: " + currentTime.toFixed(3) + " is located too far from the end of live sliding playlist: " + end + ", reset currentTime to : " + liveSyncPosition.toFixed(3));
                media.currentTime = liveSyncPosition;
              }
            }
          }
        };
      
        _proto.alignPlaylists = function alignPlaylists(details, previousDetails) {
          var levels = this.levels,
              levelLastLoaded = this.levelLastLoaded,
              fragPrevious = this.fragPrevious;
          var lastLevel = levelLastLoaded !== null ? levels[levelLastLoaded] : null; // FIXME: If not for `shouldAlignOnDiscontinuities` requiring fragPrevious.cc,
          //  this could all go in level-helper mergeDetails()
      
          var length = details.fragments.length;
      
          if (!length) {
            this.warn("No fragments in live playlist");
            return 0;
          }
      
          var slidingStart = details.fragments[0].start;
          var firstLevelLoad = !previousDetails;
      
          var aligned = details.alignedSliding && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(slidingStart);
      
          if (firstLevelLoad || !aligned && !slidingStart) {
            Object(_utils_discontinuities__WEBPACK_IMPORTED_MODULE_9__["alignStream"])(fragPrevious, lastLevel, details);
            var alignedSlidingStart = details.fragments[0].start;
            this.log("Live playlist sliding: " + alignedSlidingStart.toFixed(2) + " start-sn: " + (previousDetails ? previousDetails.startSN : 'na') + "->" + details.startSN + " prev-sn: " + (fragPrevious ? fragPrevious.sn : 'na') + " fragments: " + length);
            return alignedSlidingStart;
          }
      
          return slidingStart;
        };
      
        _proto.waitForCdnTuneIn = function waitForCdnTuneIn(details) {
          // Wait for Low-Latency CDN Tune-in to get an updated playlist
          var advancePartLimit = 3;
          return details.live && details.canBlockReload && details.tuneInGoal > Math.max(details.partHoldBack, details.partTarget * advancePartLimit);
        };
      
        _proto.setStartPosition = function setStartPosition(details, sliding) {
          // compute start position if set to -1. use it straight away if value is defined
          var startPosition = this.startPosition;
      
          if (startPosition < sliding) {
            startPosition = -1;
          }
      
          if (startPosition === -1 || this.lastCurrentTime === -1) {
            // first, check if start time offset has been set in playlist, if yes, use this value
            var startTimeOffset = details.startTimeOffset;
      
            if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(startTimeOffset)) {
              startPosition = sliding + startTimeOffset;
      
              if (startTimeOffset < 0) {
                startPosition += details.totalduration;
              }
      
              startPosition = Math.min(Math.max(sliding, startPosition), sliding + details.totalduration);
              this.log("Start time offset " + startTimeOffset + " found in playlist, adjust startPosition to " + startPosition);
              this.startPosition = startPosition;
            } else if (details.live) {
              // Leave this.startPosition at -1, so that we can use `getInitialLiveFragment` logic when startPosition has
              // not been specified via the config or an as an argument to startLoad (#3736).
              startPosition = this.hls.liveSyncPosition || sliding;
            } else {
              this.startPosition = startPosition = 0;
            }
      
            this.lastCurrentTime = startPosition;
          }
      
          this.nextLoadPosition = startPosition;
        };
      
        _proto.getLoadPosition = function getLoadPosition() {
          var media = this.media; // if we have not yet loaded any fragment, start loading from start position
      
          var pos = 0;
      
          if (this.loadedmetadata && media) {
            pos = media.currentTime;
          } else if (this.nextLoadPosition) {
            pos = this.nextLoadPosition;
          }
      
          return pos;
        };
      
        _proto.handleFragLoadAborted = function handleFragLoadAborted(frag, part) {
          if (this.transmuxer && frag.sn !== 'initSegment' && frag.stats.aborted) {
            this.warn("Fragment " + frag.sn + (part ? ' part' + part.index : '') + " of level " + frag.level + " was aborted");
            this.resetFragmentLoading(frag);
          }
        };
      
        _proto.resetFragmentLoading = function resetFragmentLoading(frag) {
          if (!this.fragCurrent || !this.fragContextChanged(frag)) {
            this.state = State.IDLE;
          }
        };
      
        _proto.onFragmentOrKeyLoadError = function onFragmentOrKeyLoadError(filterType, data) {
          if (data.fatal) {
            return;
          }
      
          var frag = data.frag; // Handle frag error related to caller's filterType
      
          if (!frag || frag.type !== filterType) {
            return;
          }
      
          var fragCurrent = this.fragCurrent;
          console.assert(fragCurrent && frag.sn === fragCurrent.sn && frag.level === fragCurrent.level && frag.urlId === fragCurrent.urlId, 'Frag load error must match current frag to retry');
          var config = this.config; // keep retrying until the limit will be reached
      
          if (this.fragLoadError + 1 <= config.fragLoadingMaxRetry) {
            if (this.resetLiveStartWhenNotLoaded(frag.level)) {
              return;
            } // exponential backoff capped to config.fragLoadingMaxRetryTimeout
      
      
            var delay = Math.min(Math.pow(2, this.fragLoadError) * config.fragLoadingRetryDelay, config.fragLoadingMaxRetryTimeout);
            this.warn("Fragment " + frag.sn + " of " + filterType + " " + frag.level + " failed to load, retrying in " + delay + "ms");
            this.retryDate = self.performance.now() + delay;
            this.fragLoadError++;
            this.state = State.FRAG_LOADING_WAITING_RETRY;
          } else if (data.levelRetry) {
            if (filterType === _types_loader__WEBPACK_IMPORTED_MODULE_15__["PlaylistLevelType"].AUDIO) {
              // Reset current fragment since audio track audio is essential and may not have a fail-over track
              this.fragCurrent = null;
            } // Fragment errors that result in a level switch or redundant fail-over
            // should reset the stream controller state to idle
      
      
            this.fragLoadError = 0;
            this.state = State.IDLE;
          } else {
            _utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"].error(data.details + " reaches max retry, redispatch as fatal ..."); // switch error to fatal
      
            data.fatal = true;
            this.hls.stopLoad();
            this.state = State.ERROR;
          }
        };
      
        _proto.afterBufferFlushed = function afterBufferFlushed(media, bufferType, playlistType) {
          if (!media) {
            return;
          } // After successful buffer flushing, filter flushed fragments from bufferedFrags use mediaBuffered instead of media
          // (so that we will check against video.buffered ranges in case of alt audio track)
      
      
          var bufferedTimeRanges = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].getBuffered(media);
          this.fragmentTracker.detectEvictedFragments(bufferType, bufferedTimeRanges, playlistType);
      
          if (this.state === State.ENDED) {
            this.resetLoadingState();
          }
        };
      
        _proto.resetLoadingState = function resetLoadingState() {
          this.fragCurrent = null;
          this.fragPrevious = null;
          this.state = State.IDLE;
        };
      
        _proto.resetLiveStartWhenNotLoaded = function resetLiveStartWhenNotLoaded(level) {
          // if loadedmetadata is not set, it means that we are emergency switch down on first frag
          // in that case, reset startFragRequested flag
          if (!this.loadedmetadata) {
            this.startFragRequested = false;
            var details = this.levels ? this.levels[level].details : null;
      
            if (details !== null && details !== void 0 && details.live) {
              // We can't afford to retry after a delay in a live scenario. Update the start position and return to IDLE.
              this.startPosition = -1;
              this.setStartPosition(details, 0);
              this.resetLoadingState();
              return true;
            }
      
            this.nextLoadPosition = this.startPosition;
          }
      
          return false;
        };
      
        _proto.updateLevelTiming = function updateLevelTiming(frag, part, level, partial) {
          var _this6 = this;
      
          var details = level.details;
          console.assert(!!details, 'level.details must be defined');
          var parsed = Object.keys(frag.elementaryStreams).reduce(function (result, type) {
            var info = frag.elementaryStreams[type];
      
            if (info) {
              var parsedDuration = info.endPTS - info.startPTS;
      
              if (parsedDuration <= 0) {
                // Destroy the transmuxer after it's next time offset failed to advance because duration was <= 0.
                // The new transmuxer will be configured with a time offset matching the next fragment start,
                // preventing the timeline from shifting.
                _this6.warn("Could not parse fragment " + frag.sn + " " + type + " duration reliably (" + parsedDuration + ") resetting transmuxer to fallback to playlist timing");
      
                _this6.resetTransmuxer();
      
                return result || false;
              }
      
              var drift = partial ? 0 : Object(_level_helper__WEBPACK_IMPORTED_MODULE_11__["updateFragPTSDTS"])(details, frag, info.startPTS, info.endPTS, info.startDTS, info.endDTS);
      
              _this6.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].LEVEL_PTS_UPDATED, {
                details: details,
                level: level,
                drift: drift,
                type: type,
                frag: frag,
                start: info.startPTS,
                end: info.endPTS
              });
      
              return true;
            }
      
            return result;
          }, false);
      
          if (parsed) {
            this.state = State.PARSED;
            this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_PARSED, {
              frag: frag,
              part: part
            });
          } else {
            this.resetLoadingState();
          }
        };
      
        _proto.resetTransmuxer = function resetTransmuxer() {
          if (this.transmuxer) {
            this.transmuxer.destroy();
            this.transmuxer = null;
          }
        };
      
        _createClass(BaseStreamController, [{
          key: "state",
          get: function get() {
            return this._state;
          },
          set: function set(nextState) {
            var previousState = this._state;
      
            if (previousState !== nextState) {
              this._state = nextState;
              this.log(previousState + "->" + nextState);
            }
          }
        }]);
      
        return BaseStreamController;
      }(_task_loop__WEBPACK_IMPORTED_MODULE_1__["default"]);
      
      
      
      /***/ }),
      
      /***/ "./src/controller/buffer-controller.ts":
      /*!*********************************************!*\
        !*** ./src/controller/buffer-controller.ts ***!
        \*********************************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BufferController; });
      /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
      /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
      /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
      /* harmony import */ var _utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/mediasource-helper */ "./src/utils/mediasource-helper.ts");
      /* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts");
      /* harmony import */ var _buffer_operation_queue__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./buffer-operation-queue */ "./src/controller/buffer-operation-queue.ts");
      
      
      
      
      
      
      
      
      
      
      
      
      var MediaSource = Object(_utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__["getMediaSource"])();
      var VIDEO_CODEC_PROFILE_REPACE = /([ha]vc.)(?:\.[^.,]+)+/;
      
      var BufferController = /*#__PURE__*/function () {
        // The level details used to determine duration, target-duration and live
        // cache the self generated object url to detect hijack of video tag
        // A queue of buffer operations which require the SourceBuffer to not be updating upon execution
        // References to event listeners for each SourceBuffer, so that they can be referenced for event removal
        // The number of BUFFER_CODEC events received before any sourceBuffers are created
        // The total number of BUFFER_CODEC events received
        // A reference to the attached media element
        // A reference to the active media source
        // counters
        function BufferController(_hls) {
          var _this = this;
      
          this.details = null;
          this._objectUrl = null;
          this.operationQueue = void 0;
          this.listeners = void 0;
          this.hls = void 0;
          this.bufferCodecEventsExpected = 0;
          this._bufferCodecEventsTotal = 0;
          this.media = null;
          this.mediaSource = null;
          this.appendError = 0;
          this.tracks = {};
          this.pendingTracks = {};
          this.sourceBuffer = void 0;
      
          this._onMediaSourceOpen = function () {
            var hls = _this.hls,
                media = _this.media,
                mediaSource = _this.mediaSource;
            _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Media source opened');
      
            if (media) {
              _this.updateMediaElementDuration();
      
              hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHED, {
                media: media
              });
            }
      
            if (mediaSource) {
              // once received, don't listen anymore to sourceopen event
              mediaSource.removeEventListener('sourceopen', _this._onMediaSourceOpen);
            }
      
            _this.checkPendingTracks();
          };
      
          this._onMediaSourceClose = function () {
            _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Media source closed');
          };
      
          this._onMediaSourceEnded = function () {
            _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Media source ended');
          };
      
          this.hls = _hls;
      
          this._initSourceBuffer();
      
          this.registerListeners();
        }
      
        var _proto = BufferController.prototype;
      
        _proto.hasSourceTypes = function hasSourceTypes() {
          return this.getSourceBufferTypes().length > 0 || Object.keys(this.pendingTracks).length > 0;
        };
      
        _proto.destroy = function destroy() {
          this.unregisterListeners();
          this.details = null;
        };
      
        _proto.registerListeners = function registerListeners() {
          var hls = this.hls;
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_RESET, this.onBufferReset, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_APPENDING, this.onBufferAppending, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_CODECS, this.onBufferCodecs, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_EOS, this.onBufferEos, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_UPDATED, this.onLevelUpdated, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_PARSED, this.onFragParsed, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_CHANGED, this.onFragChanged, this);
        };
      
        _proto.unregisterListeners = function unregisterListeners() {
          var hls = this.hls;
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_RESET, this.onBufferReset, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_APPENDING, this.onBufferAppending, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_CODECS, this.onBufferCodecs, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_EOS, this.onBufferEos, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_UPDATED, this.onLevelUpdated, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_PARSED, this.onFragParsed, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_CHANGED, this.onFragChanged, this);
        };
      
        _proto._initSourceBuffer = function _initSourceBuffer() {
          this.sourceBuffer = {};
          this.operationQueue = new _buffer_operation_queue__WEBPACK_IMPORTED_MODULE_7__["default"](this.sourceBuffer);
          this.listeners = {
            audio: [],
            video: [],
            audiovideo: []
          };
        };
      
        _proto.onManifestParsed = function onManifestParsed(event, data) {
          // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller
          // sourcebuffers will be created all at once when the expected nb of tracks will be reached
          // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller
          // it will contain the expected nb of source buffers, no need to compute it
          var codecEvents = 2;
      
          if (data.audio && !data.video || !data.altAudio) {
            codecEvents = 1;
          }
      
          this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = codecEvents;
          this.details = null;
          _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log(this.bufferCodecEventsExpected + " bufferCodec event(s) expected");
        };
      
        _proto.onMediaAttaching = function onMediaAttaching(event, data) {
          var media = this.media = data.media;
      
          if (media && MediaSource) {
            var ms = this.mediaSource = new MediaSource(); // MediaSource listeners are arrow functions with a lexical scope, and do not need to be bound
      
            ms.addEventListener('sourceopen', this._onMediaSourceOpen);
            ms.addEventListener('sourceended', this._onMediaSourceEnded);
            ms.addEventListener('sourceclose', this._onMediaSourceClose); // link video and media Source
      
            media.src = self.URL.createObjectURL(ms); // cache the locally generated object url
      
            this._objectUrl = media.src;
          }
        };
      
        _proto.onMediaDetaching = function onMediaDetaching() {
          var media = this.media,
              mediaSource = this.mediaSource,
              _objectUrl = this._objectUrl;
      
          if (mediaSource) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: media source detaching');
      
            if (mediaSource.readyState === 'open') {
              try {
                // endOfStream could trigger exception if any sourcebuffer is in updating state
                // we don't really care about checking sourcebuffer state here,
                // as we are anyway detaching the MediaSource
                // let's just avoid this exception to propagate
                mediaSource.endOfStream();
              } catch (err) {
                _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: onMediaDetaching: " + err.message + " while calling endOfStream");
              }
            } // Clean up the SourceBuffers by invoking onBufferReset
      
      
            this.onBufferReset();
            mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);
            mediaSource.removeEventListener('sourceended', this._onMediaSourceEnded);
            mediaSource.removeEventListener('sourceclose', this._onMediaSourceClose); // Detach properly the MediaSource from the HTMLMediaElement as
            // suggested in https://github.com/w3c/media-source/issues/53.
      
            if (media) {
              if (_objectUrl) {
                self.URL.revokeObjectURL(_objectUrl);
              } // clean up video tag src only if it's our own url. some external libraries might
              // hijack the video tag and change its 'src' without destroying the Hls instance first
      
      
              if (media.src === _objectUrl) {
                media.removeAttribute('src');
                media.load();
              } else {
                _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('[buffer-controller]: media.src was changed by a third party - skip cleanup');
              }
            }
      
            this.mediaSource = null;
            this.media = null;
            this._objectUrl = null;
            this.bufferCodecEventsExpected = this._bufferCodecEventsTotal;
            this.pendingTracks = {};
            this.tracks = {};
          }
      
          this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHED, undefined);
        };
      
        _proto.onBufferReset = function onBufferReset() {
          var _this2 = this;
      
          this.getSourceBufferTypes().forEach(function (type) {
            var sb = _this2.sourceBuffer[type];
      
            try {
              if (sb) {
                _this2.removeBufferListeners(type);
      
                if (_this2.mediaSource) {
                  _this2.mediaSource.removeSourceBuffer(sb);
                } // Synchronously remove the SB from the map before the next call in order to prevent an async function from
                // accessing it
      
      
                _this2.sourceBuffer[type] = undefined;
              }
            } catch (err) {
              _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Failed to reset the " + type + " buffer", err);
            }
          });
      
          this._initSourceBuffer();
        };
      
        _proto.onBufferCodecs = function onBufferCodecs(event, data) {
          var _this3 = this;
      
          var sourceBufferCount = this.getSourceBufferTypes().length;
          Object.keys(data).forEach(function (trackName) {
            if (sourceBufferCount) {
              // check if SourceBuffer codec needs to change
              var track = _this3.tracks[trackName];
      
              if (track && typeof track.buffer.changeType === 'function') {
                var _data$trackName = data[trackName],
                    codec = _data$trackName.codec,
                    levelCodec = _data$trackName.levelCodec,
                    container = _data$trackName.container;
                var currentCodec = (track.levelCodec || track.codec).replace(VIDEO_CODEC_PROFILE_REPACE, '$1');
                var nextCodec = (levelCodec || codec).replace(VIDEO_CODEC_PROFILE_REPACE, '$1');
      
                if (currentCodec !== nextCodec) {
                  var mimeType = container + ";codecs=" + (levelCodec || codec);
      
                  _this3.appendChangeType(trackName, mimeType);
                }
              }
            } else {
              // if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks
              _this3.pendingTracks[trackName] = data[trackName];
            }
          }); // if sourcebuffers already created, do nothing ...
      
          if (sourceBufferCount) {
            return;
          }
      
          this.bufferCodecEventsExpected = Math.max(this.bufferCodecEventsExpected - 1, 0);
      
          if (this.mediaSource && this.mediaSource.readyState === 'open') {
            this.checkPendingTracks();
          }
        };
      
        _proto.appendChangeType = function appendChangeType(type, mimeType) {
          var _this4 = this;
      
          var operationQueue = this.operationQueue;
          var operation = {
            execute: function execute() {
              var sb = _this4.sourceBuffer[type];
      
              if (sb) {
                _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: changing " + type + " sourceBuffer type to " + mimeType);
                sb.changeType(mimeType);
              }
      
              operationQueue.shiftAndExecuteNext(type);
            },
            onStart: function onStart() {},
            onComplete: function onComplete() {},
            onError: function onError(e) {
              _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Failed to change " + type + " SourceBuffer type", e);
            }
          };
          operationQueue.append(operation, type);
        };
      
        _proto.onBufferAppending = function onBufferAppending(event, eventData) {
          var _this5 = this;
      
          var hls = this.hls,
              operationQueue = this.operationQueue,
              tracks = this.tracks;
          var data = eventData.data,
              type = eventData.type,
              frag = eventData.frag,
              part = eventData.part,
              chunkMeta = eventData.chunkMeta;
          var chunkStats = chunkMeta.buffering[type];
          var bufferAppendingStart = self.performance.now();
          chunkStats.start = bufferAppendingStart;
          var fragBuffering = frag.stats.buffering;
          var partBuffering = part ? part.stats.buffering : null;
      
          if (fragBuffering.start === 0) {
            fragBuffering.start = bufferAppendingStart;
          }
      
          if (partBuffering && partBuffering.start === 0) {
            partBuffering.start = bufferAppendingStart;
          } // TODO: Only update timestampOffset when audio/mpeg fragment or part is not contiguous with previously appended
          // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)
          // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`
          // is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos).
          // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486
      
      
          var audioTrack = tracks.audio;
          var checkTimestampOffset = type === 'audio' && chunkMeta.id === 1 && (audioTrack === null || audioTrack === void 0 ? void 0 : audioTrack.container) === 'audio/mpeg';
          var operation = {
            execute: function execute() {
              chunkStats.executeStart = self.performance.now();
      
              if (checkTimestampOffset) {
                var sb = _this5.sourceBuffer[type];
      
                if (sb) {
                  var delta = frag.start - sb.timestampOffset;
      
                  if (Math.abs(delta) >= 0.1) {
                    _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: Updating audio SourceBuffer timestampOffset to " + frag.start + " (delta: " + delta + ") sn: " + frag.sn + ")");
                    sb.timestampOffset = frag.start;
                  }
                }
              }
      
              _this5.appendExecutor(data, type);
            },
            onStart: function onStart() {// logger.debug(`[buffer-controller]: ${type} SourceBuffer updatestart`);
            },
            onComplete: function onComplete() {
              // logger.debug(`[buffer-controller]: ${type} SourceBuffer updateend`);
              var end = self.performance.now();
              chunkStats.executeEnd = chunkStats.end = end;
      
              if (fragBuffering.first === 0) {
                fragBuffering.first = end;
              }
      
              if (partBuffering && partBuffering.first === 0) {
                partBuffering.first = end;
              }
      
              var sourceBuffer = _this5.sourceBuffer;
              var timeRanges = {};
      
              for (var _type in sourceBuffer) {
                timeRanges[_type] = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].getBuffered(sourceBuffer[_type]);
              }
      
              _this5.appendError = 0;
      
              _this5.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_APPENDED, {
                type: type,
                frag: frag,
                part: part,
                chunkMeta: chunkMeta,
                parent: frag.type,
                timeRanges: timeRanges
              });
            },
            onError: function onError(err) {
              // in case any error occured while appending, put back segment in segments table
              _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("[buffer-controller]: Error encountered while trying to append to the " + type + " SourceBuffer", err);
              var event = {
                type: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorTypes"].MEDIA_ERROR,
                parent: frag.type,
                details: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_APPEND_ERROR,
                err: err,
                fatal: false
              };
      
              if (err.code === DOMException.QUOTA_EXCEEDED_ERR) {
                // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror
                // let's stop appending any segments, and report BUFFER_FULL_ERROR error
                event.details = _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_FULL_ERROR;
              } else {
                _this5.appendError++;
                event.details = _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_APPEND_ERROR;
                /* with UHD content, we could get loop of quota exceeded error until
                  browser is able to evict some data from sourcebuffer. Retrying can help recover.
                */
      
                if (_this5.appendError > hls.config.appendErrorMaxRetry) {
                  _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("[buffer-controller]: Failed " + hls.config.appendErrorMaxRetry + " times to append segment in sourceBuffer");
                  event.fatal = true;
                }
              }
      
              hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, event);
            }
          };
          operationQueue.append(operation, type);
        };
      
        _proto.onBufferFlushing = function onBufferFlushing(event, data) {
          var _this6 = this;
      
          var operationQueue = this.operationQueue;
      
          var flushOperation = function flushOperation(type) {
            return {
              execute: _this6.removeExecutor.bind(_this6, type, data.startOffset, data.endOffset),
              onStart: function onStart() {// logger.debug(`[buffer-controller]: Started flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
              },
              onComplete: function onComplete() {
                // logger.debug(`[buffer-controller]: Finished flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
                _this6.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHED, {
                  type: type
                });
              },
              onError: function onError(e) {
                _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Failed to remove from " + type + " SourceBuffer", e);
              }
            };
          };
      
          if (data.type) {
            operationQueue.append(flushOperation(data.type), data.type);
          } else {
            this.getSourceBufferTypes().forEach(function (type) {
              operationQueue.append(flushOperation(type), type);
            });
          }
        };
      
        _proto.onFragParsed = function onFragParsed(event, data) {
          var _this7 = this;
      
          var frag = data.frag,
              part = data.part;
          var buffersAppendedTo = [];
          var elementaryStreams = part ? part.elementaryStreams : frag.elementaryStreams;
      
          if (elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_6__["ElementaryStreamTypes"].AUDIOVIDEO]) {
            buffersAppendedTo.push('audiovideo');
          } else {
            if (elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_6__["ElementaryStreamTypes"].AUDIO]) {
              buffersAppendedTo.push('audio');
            }
      
            if (elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_6__["ElementaryStreamTypes"].VIDEO]) {
              buffersAppendedTo.push('video');
            }
          }
      
          var onUnblocked = function onUnblocked() {
            var now = self.performance.now();
            frag.stats.buffering.end = now;
      
            if (part) {
              part.stats.buffering.end = now;
            }
      
            var stats = part ? part.stats : frag.stats;
      
            _this7.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_BUFFERED, {
              frag: frag,
              part: part,
              stats: stats,
              id: frag.type
            });
          };
      
          if (buffersAppendedTo.length === 0) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("Fragments must have at least one ElementaryStreamType set. type: " + frag.type + " level: " + frag.level + " sn: " + frag.sn);
          }
      
          this.blockBuffers(onUnblocked, buffersAppendedTo);
        };
      
        _proto.onFragChanged = function onFragChanged(event, data) {
          this.flushBackBuffer();
        } // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()
        // an undefined data.type will mark all buffers as EOS.
        ;
      
        _proto.onBufferEos = function onBufferEos(event, data) {
          var _this8 = this;
      
          var ended = this.getSourceBufferTypes().reduce(function (acc, type) {
            var sb = _this8.sourceBuffer[type];
      
            if (!data.type || data.type === type) {
              if (sb && !sb.ended) {
                sb.ended = true;
                _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: " + type + " sourceBuffer now EOS");
              }
            }
      
            return acc && !!(!sb || sb.ended);
          }, true);
      
          if (ended) {
            this.blockBuffers(function () {
              var mediaSource = _this8.mediaSource;
      
              if (!mediaSource || mediaSource.readyState !== 'open') {
                return;
              } // Allow this to throw and be caught by the enqueueing function
      
      
              mediaSource.endOfStream();
            });
          }
        };
      
        _proto.onLevelUpdated = function onLevelUpdated(event, _ref) {
          var details = _ref.details;
      
          if (!details.fragments.length) {
            return;
          }
      
          this.details = details;
      
          if (this.getSourceBufferTypes().length) {
            this.blockBuffers(this.updateMediaElementDuration.bind(this));
          } else {
            this.updateMediaElementDuration();
          }
        };
      
        _proto.flushBackBuffer = function flushBackBuffer() {
          var hls = this.hls,
              details = this.details,
              media = this.media,
              sourceBuffer = this.sourceBuffer;
      
          if (!media || details === null) {
            return;
          }
      
          var sourceBufferTypes = this.getSourceBufferTypes();
      
          if (!sourceBufferTypes.length) {
            return;
          } // Support for deprecated liveBackBufferLength
      
      
          var backBufferLength = details.live && hls.config.liveBackBufferLength !== null ? hls.config.liveBackBufferLength : hls.config.backBufferLength;
      
          if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(backBufferLength) || backBufferLength < 0) {
            return;
          }
      
          var currentTime = media.currentTime;
          var targetDuration = details.levelTargetDuration;
          var maxBackBufferLength = Math.max(backBufferLength, targetDuration);
          var targetBackBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration - maxBackBufferLength;
          sourceBufferTypes.forEach(function (type) {
            var sb = sourceBuffer[type];
      
            if (sb) {
              var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].getBuffered(sb); // when target buffer start exceeds actual buffer start
      
              if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {
                hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BACK_BUFFER_REACHED, {
                  bufferEnd: targetBackBufferPosition
                }); // Support for deprecated event:
      
                if (details.live) {
                  hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LIVE_BACK_BUFFER_REACHED, {
                    bufferEnd: targetBackBufferPosition
                  });
                }
      
                hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, {
                  startOffset: 0,
                  endOffset: targetBackBufferPosition,
                  type: type
                });
              }
            }
          });
        }
        /**
         * Update Media Source duration to current level duration or override to Infinity if configuration parameter
         * 'liveDurationInfinity` is set to `true`
         * More details: https://github.com/video-dev/hls.js/issues/355
         */
        ;
      
        _proto.updateMediaElementDuration = function updateMediaElementDuration() {
          if (!this.details || !this.media || !this.mediaSource || this.mediaSource.readyState !== 'open') {
            return;
          }
      
          var details = this.details,
              hls = this.hls,
              media = this.media,
              mediaSource = this.mediaSource;
          var levelDuration = details.fragments[0].start + details.totalduration;
          var mediaDuration = media.duration;
          var msDuration = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(mediaSource.duration) ? mediaSource.duration : 0;
      
          if (details.live && hls.config.liveDurationInfinity) {
            // Override duration to Infinity
            _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Media Source duration is set to Infinity');
            mediaSource.duration = Infinity;
            this.updateSeekableRange(details);
          } else if (levelDuration > msDuration && levelDuration > mediaDuration || !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(mediaDuration)) {
            // levelDuration was the last value we set.
            // not using mediaSource.duration as the browser may tweak this value
            // only update Media Source duration if its value increase, this is to avoid
            // flushing already buffered portion when switching between quality level
            _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: Updating Media Source duration to " + levelDuration.toFixed(3));
            mediaSource.duration = levelDuration;
          }
        };
      
        _proto.updateSeekableRange = function updateSeekableRange(levelDetails) {
          var mediaSource = this.mediaSource;
          var fragments = levelDetails.fragments;
          var len = fragments.length;
      
          if (len && levelDetails.live && mediaSource !== null && mediaSource !== void 0 && mediaSource.setLiveSeekableRange) {
            var start = Math.max(0, fragments[0].start);
            var end = Math.max(start, start + levelDetails.totalduration);
            mediaSource.setLiveSeekableRange(start, end);
          }
        };
      
        _proto.checkPendingTracks = function checkPendingTracks() {
          var bufferCodecEventsExpected = this.bufferCodecEventsExpected,
              operationQueue = this.operationQueue,
              pendingTracks = this.pendingTracks; // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.
          // This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after
          // data has been appended to existing ones.
          // 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.
      
          var pendingTracksCount = Object.keys(pendingTracks).length;
      
          if (pendingTracksCount && !bufferCodecEventsExpected || pendingTracksCount === 2) {
            // ok, let's create them now !
            this.createSourceBuffers(pendingTracks);
            this.pendingTracks = {}; // append any pending segments now !
      
            var buffers = this.getSourceBufferTypes();
      
            if (buffers.length === 0) {
              this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
                type: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorTypes"].MEDIA_ERROR,
                details: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_INCOMPATIBLE_CODECS_ERROR,
                fatal: true,
                reason: 'could not create source buffer for media codec(s)'
              });
              return;
            }
      
            buffers.forEach(function (type) {
              operationQueue.executeNext(type);
            });
          }
        };
      
        _proto.createSourceBuffers = function createSourceBuffers(tracks) {
          var sourceBuffer = this.sourceBuffer,
              mediaSource = this.mediaSource;
      
          if (!mediaSource) {
            throw Error('createSourceBuffers called when mediaSource was null');
          }
      
          var tracksCreated = 0;
      
          for (var trackName in tracks) {
            if (!sourceBuffer[trackName]) {
              var track = tracks[trackName];
      
              if (!track) {
                throw Error("source buffer exists for track " + trackName + ", however track does not");
              } // use levelCodec as first priority
      
      
              var codec = track.levelCodec || track.codec;
              var mimeType = track.container + ";codecs=" + codec;
              _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: creating sourceBuffer(" + mimeType + ")");
      
              try {
                var sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType);
                var sbName = trackName;
                this.addBufferListener(sbName, 'updatestart', this._onSBUpdateStart);
                this.addBufferListener(sbName, 'updateend', this._onSBUpdateEnd);
                this.addBufferListener(sbName, 'error', this._onSBUpdateError);
                this.tracks[trackName] = {
                  buffer: sb,
                  codec: codec,
                  container: track.container,
                  levelCodec: track.levelCodec,
                  id: track.id
                };
                tracksCreated++;
              } catch (err) {
                _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("[buffer-controller]: error while trying to add sourceBuffer: " + err.message);
                this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
                  type: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorTypes"].MEDIA_ERROR,
                  details: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_ADD_CODEC_ERROR,
                  fatal: false,
                  error: err,
                  mimeType: mimeType
                });
              }
            }
          }
      
          if (tracksCreated) {
            this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_CREATED, {
              tracks: this.tracks
            });
          }
        } // Keep as arrow functions so that we can directly reference these functions directly as event listeners
        ;
      
        _proto._onSBUpdateStart = function _onSBUpdateStart(type) {
          var operationQueue = this.operationQueue;
          var operation = operationQueue.current(type);
          operation.onStart();
        };
      
        _proto._onSBUpdateEnd = function _onSBUpdateEnd(type) {
          var operationQueue = this.operationQueue;
          var operation = operationQueue.current(type);
          operation.onComplete();
          operationQueue.shiftAndExecuteNext(type);
        };
      
        _proto._onSBUpdateError = function _onSBUpdateError(type, event) {
          _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("[buffer-controller]: " + type + " SourceBuffer error", event); // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
          // SourceBuffer errors are not necessarily fatal; if so, the HTMLMediaElement will fire an error event
      
          this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
            type: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorTypes"].MEDIA_ERROR,
            details: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_APPENDING_ERROR,
            fatal: false
          }); // updateend is always fired after error, so we'll allow that to shift the current operation off of the queue
      
          var operation = this.operationQueue.current(type);
      
          if (operation) {
            operation.onError(event);
          }
        } // This method must result in an updateend event; if remove is not called, _onSBUpdateEnd must be called manually
        ;
      
        _proto.removeExecutor = function removeExecutor(type, startOffset, endOffset) {
          var media = this.media,
              mediaSource = this.mediaSource,
              operationQueue = this.operationQueue,
              sourceBuffer = this.sourceBuffer;
          var sb = sourceBuffer[type];
      
          if (!media || !mediaSource || !sb) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Attempting to remove from the " + type + " SourceBuffer, but it does not exist");
            operationQueue.shiftAndExecuteNext(type);
            return;
          }
      
          var mediaDuration = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(media.duration) ? media.duration : Infinity;
          var msDuration = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(mediaSource.duration) ? mediaSource.duration : Infinity;
          var removeStart = Math.max(0, startOffset);
          var removeEnd = Math.min(endOffset, mediaDuration, msDuration);
      
          if (removeEnd > removeStart) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: Removing [" + removeStart + "," + removeEnd + "] from the " + type + " SourceBuffer");
            console.assert(!sb.updating, type + " sourceBuffer must not be updating");
            sb.remove(removeStart, removeEnd);
          } else {
            // Cycle the queue
            operationQueue.shiftAndExecuteNext(type);
          }
        } // This method must result in an updateend event; if append is not called, _onSBUpdateEnd must be called manually
        ;
      
        _proto.appendExecutor = function appendExecutor(data, type) {
          var operationQueue = this.operationQueue,
              sourceBuffer = this.sourceBuffer;
          var sb = sourceBuffer[type];
      
          if (!sb) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Attempting to append to the " + type + " SourceBuffer, but it does not exist");
            operationQueue.shiftAndExecuteNext(type);
            return;
          }
      
          sb.ended = false;
          console.assert(!sb.updating, type + " sourceBuffer must not be updating");
          sb.appendBuffer(data);
        } // Enqueues an operation to each SourceBuffer queue which, upon execution, resolves a promise. When all promises
        // resolve, the onUnblocked function is executed. Functions calling this method do not need to unblock the queue
        // upon completion, since we already do it here
        ;
      
        _proto.blockBuffers = function blockBuffers(onUnblocked, buffers) {
          var _this9 = this;
      
          if (buffers === void 0) {
            buffers = this.getSourceBufferTypes();
          }
      
          if (!buffers.length) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Blocking operation requested, but no SourceBuffers exist');
            Promise.resolve(onUnblocked);
            return;
          }
      
          var operationQueue = this.operationQueue; // logger.debug(`[buffer-controller]: Blocking ${buffers} SourceBuffer`);
      
          var blockingOperations = buffers.map(function (type) {
            return operationQueue.appendBlocker(type);
          });
          Promise.all(blockingOperations).then(function () {
            // logger.debug(`[buffer-controller]: Blocking operation resolved; unblocking ${buffers} SourceBuffer`);
            onUnblocked();
            buffers.forEach(function (type) {
              var sb = _this9.sourceBuffer[type]; // Only cycle the queue if the SB is not updating. There's a bug in Chrome which sets the SB updating flag to
              // true when changing the MediaSource duration (https://bugs.chromium.org/p/chromium/issues/detail?id=959359&can=2&q=mediasource%20duration)
              // While this is a workaround, it's probably useful to have around
      
              if (!sb || !sb.updating) {
                operationQueue.shiftAndExecuteNext(type);
              }
            });
          });
        };
      
        _proto.getSourceBufferTypes = function getSourceBufferTypes() {
          return Object.keys(this.sourceBuffer);
        };
      
        _proto.addBufferListener = function addBufferListener(type, event, fn) {
          var buffer = this.sourceBuffer[type];
      
          if (!buffer) {
            return;
          }
      
          var listener = fn.bind(this, type);
          this.listeners[type].push({
            event: event,
            listener: listener
          });
          buffer.addEventListener(event, listener);
        };
      
        _proto.removeBufferListeners = function removeBufferListeners(type) {
          var buffer = this.sourceBuffer[type];
      
          if (!buffer) {
            return;
          }
      
          this.listeners[type].forEach(function (l) {
            buffer.removeEventListener(l.event, l.listener);
          });
        };
      
        return BufferController;
      }();
      
      
      
      /***/ }),
      
      /***/ "./src/controller/buffer-operation-queue.ts":
      /*!**************************************************!*\
        !*** ./src/controller/buffer-operation-queue.ts ***!
        \**************************************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BufferOperationQueue; });
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      
      
      var BufferOperationQueue = /*#__PURE__*/function () {
        function BufferOperationQueue(sourceBufferReference) {
          this.buffers = void 0;
          this.queues = {
            video: [],
            audio: [],
            audiovideo: []
          };
          this.buffers = sourceBufferReference;
        }
      
        var _proto = BufferOperationQueue.prototype;
      
        _proto.append = function append(operation, type) {
          var queue = this.queues[type];
          queue.push(operation);
      
          if (queue.length === 1 && this.buffers[type]) {
            this.executeNext(type);
          }
        };
      
        _proto.insertAbort = function insertAbort(operation, type) {
          var queue = this.queues[type];
          queue.unshift(operation);
          this.executeNext(type);
        };
      
        _proto.appendBlocker = function appendBlocker(type) {
          var execute;
          var promise = new Promise(function (resolve) {
            execute = resolve;
          });
          var operation = {
            execute: execute,
            onStart: function onStart() {},
            onComplete: function onComplete() {},
            onError: function onError() {}
          };
          this.append(operation, type);
          return promise;
        };
      
        _proto.executeNext = function executeNext(type) {
          var buffers = this.buffers,
              queues = this.queues;
          var sb = buffers[type];
          var queue = queues[type];
      
          if (queue.length) {
            var operation = queue[0];
      
            try {
              // Operations are expected to result in an 'updateend' event being fired. If not, the queue will lock. Operations
              // which do not end with this event must call _onSBUpdateEnd manually
              operation.execute();
            } catch (e) {
              _utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].warn('[buffer-operation-queue]: Unhandled exception executing the current operation');
              operation.onError(e); // Only shift the current operation off, otherwise the updateend handler will do this for us
      
              if (!sb || !sb.updating) {
                queue.shift();
                this.executeNext(type);
              }
            }
          }
        };
      
        _proto.shiftAndExecuteNext = function shiftAndExecuteNext(type) {
          this.queues[type].shift();
          this.executeNext(type);
        };
      
        _proto.current = function current(type) {
          return this.queues[type][0];
        };
      
        return BufferOperationQueue;
      }();
      
      
      
      /***/ }),
      
      /***/ "./src/controller/cap-level-controller.ts":
      /*!************************************************!*\
        !*** ./src/controller/cap-level-controller.ts ***!
        \************************************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
      function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
      
      function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
      
      /*
       * cap stream level to media size dimension controller
       */
      
      
      var CapLevelController = /*#__PURE__*/function () {
        function CapLevelController(hls) {
          this.autoLevelCapping = void 0;
          this.firstLevel = void 0;
          this.media = void 0;
          this.restrictedLevels = void 0;
          this.timer = void 0;
          this.hls = void 0;
          this.streamController = void 0;
          this.clientRect = void 0;
          this.hls = hls;
          this.autoLevelCapping = Number.POSITIVE_INFINITY;
          this.firstLevel = -1;
          this.media = null;
          this.restrictedLevels = [];
          this.timer = undefined;
          this.clientRect = null;
          this.registerListeners();
        }
      
        var _proto = CapLevelController.prototype;
      
        _proto.setStreamController = function setStreamController(streamController) {
          this.streamController = streamController;
        };
      
        _proto.destroy = function destroy() {
          this.unregisterListener();
      
          if (this.hls.config.capLevelToPlayerSize) {
            this.stopCapping();
          }
      
          this.media = null;
          this.clientRect = null; // @ts-ignore
      
          this.hls = this.streamController = null;
        };
      
        _proto.registerListeners = function registerListeners() {
          var hls = this.hls;
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_CODECS, this.onBufferCodecs, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
        };
      
        _proto.unregisterListener = function unregisterListener() {
          var hls = this.hls;
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_CODECS, this.onBufferCodecs, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
        };
      
        _proto.onFpsDropLevelCapping = function onFpsDropLevelCapping(event, data) {
          // Don't add a restricted level more than once
          if (CapLevelController.isLevelAllowed(data.droppedLevel, this.restrictedLevels)) {
            this.restrictedLevels.push(data.droppedLevel);
          }
        };
      
        _proto.onMediaAttaching = function onMediaAttaching(event, data) {
          this.media = data.media instanceof HTMLVideoElement ? data.media : null;
        };
      
        _proto.onManifestParsed = function onManifestParsed(event, data) {
          var hls = this.hls;
          this.restrictedLevels = [];
          this.firstLevel = data.firstLevel;
      
          if (hls.config.capLevelToPlayerSize && data.video) {
            // Start capping immediately if the manifest has signaled video codecs
            this.startCapping();
          }
        } // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted
        // to the first level
        ;
      
        _proto.onBufferCodecs = function onBufferCodecs(event, data) {
          var hls = this.hls;
      
          if (hls.config.capLevelToPlayerSize && data.video) {
            // If the manifest did not signal a video codec capping has been deferred until we're certain video is present
            this.startCapping();
          }
        };
      
        _proto.onMediaDetaching = function onMediaDetaching() {
          this.stopCapping();
        };
      
        _proto.detectPlayerSize = function detectPlayerSize() {
          if (this.media && this.mediaHeight > 0 && this.mediaWidth > 0) {
            var levels = this.hls.levels;
      
            if (levels.length) {
              var hls = this.hls;
              hls.autoLevelCapping = this.getMaxLevel(levels.length - 1);
      
              if (hls.autoLevelCapping > this.autoLevelCapping && this.streamController) {
                // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch
                // usually happen when the user go to the fullscreen mode.
                this.streamController.nextLevelSwitch();
              }
      
              this.autoLevelCapping = hls.autoLevelCapping;
            }
          }
        }
        /*
         * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
         */
        ;
      
        _proto.getMaxLevel = function getMaxLevel(capLevelIndex) {
          var _this = this;
      
          var levels = this.hls.levels;
      
          if (!levels.length) {
            return -1;
          }
      
          var validLevels = levels.filter(function (level, index) {
            return CapLevelController.isLevelAllowed(index, _this.restrictedLevels) && index <= capLevelIndex;
          });
          this.clientRect = null;
          return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
        };
      
        _proto.startCapping = function startCapping() {
          if (this.timer) {
            // Don't reset capping if started twice; this can happen if the manifest signals a video codec
            return;
          }
      
          this.autoLevelCapping = Number.POSITIVE_INFINITY;
          this.hls.firstLevel = this.getMaxLevel(this.firstLevel);
          self.clearInterval(this.timer);
          this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1000);
          this.detectPlayerSize();
        };
      
        _proto.stopCapping = function stopCapping() {
          this.restrictedLevels = [];
          this.firstLevel = -1;
          this.autoLevelCapping = Number.POSITIVE_INFINITY;
      
          if (this.timer) {
            self.clearInterval(this.timer);
            this.timer = undefined;
          }
        };
      
        _proto.getDimensions = function getDimensions() {
          if (this.clientRect) {
            return this.clientRect;
          }
      
          var media = this.media;
          var boundsRect = {
            width: 0,
            height: 0
          };
      
          if (media) {
            var clientRect = media.getBoundingClientRect();
            boundsRect.width = clientRect.width;
            boundsRect.height = clientRect.height;
      
            if (!boundsRect.width && !boundsRect.height) {
              // When the media element has no width or height (equivalent to not being in the DOM),
              // then use its width and height attributes (media.width, media.height)
              boundsRect.width = clientRect.right - clientRect.left || media.width || 0;
              boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0;
            }
          }
      
          this.clientRect = boundsRect;
          return boundsRect;
        };
      
        CapLevelController.isLevelAllowed = function isLevelAllowed(level, restrictedLevels) {
          if (restrictedLevels === void 0) {
            restrictedLevels = [];
          }
      
          return restrictedLevels.indexOf(level) === -1;
        };
      
        CapLevelController.getMaxLevelByMediaSize = function getMaxLevelByMediaSize(levels, width, height) {
          if (!levels || !levels.length) {
            return -1;
          } // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next
          // to determine whether we've chosen the greatest bandwidth for the media's dimensions
      
      
          var atGreatestBandiwdth = function atGreatestBandiwdth(curLevel, nextLevel) {
            if (!nextLevel) {
              return true;
            }
      
            return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;
          }; // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to
          // the max level
      
      
          var maxLevelIndex = levels.length - 1;
      
          for (var i = 0; i < levels.length; i += 1) {
            var level = levels[i];
      
            if ((level.width >= width || level.height >= height) && atGreatestBandiwdth(level, levels[i + 1])) {
              maxLevelIndex = i;
              break;
            }
          }
      
          return maxLevelIndex;
        };
      
        _createClass(CapLevelController, [{
          key: "mediaWidth",
          get: function get() {
            return this.getDimensions().width * CapLevelController.contentScaleFactor;
          }
        }, {
          key: "mediaHeight",
          get: function get() {
            return this.getDimensions().height * CapLevelController.contentScaleFactor;
          }
        }], [{
          key: "contentScaleFactor",
          get: function get() {
            var pixelRatio = 1;
      
            try {
              pixelRatio = self.devicePixelRatio;
            } catch (e) {
              /* no-op */
            }
      
            return pixelRatio;
          }
        }]);
      
        return CapLevelController;
      }();
      
      /* harmony default export */ __webpack_exports__["default"] = (CapLevelController);
      
      /***/ }),
      
      /***/ "./src/controller/cmcd-controller.ts":
      /*!*******************************************!*\
        !*** ./src/controller/cmcd-controller.ts ***!
        \*******************************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return CMCDController; });
      /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
      /* harmony import */ var _types_cmcd__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../types/cmcd */ "./src/types/cmcd.ts");
      /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
      
      function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
      
      function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
      
      function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
      
      function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
      
      function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
      
      
      
      
      
      /**
       * Controller to deal with Common Media Client Data (CMCD)
       * @see https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf
       */
      
      var CMCDController = /*#__PURE__*/function () {
        // eslint-disable-line no-restricted-globals
        // eslint-disable-line no-restricted-globals
        function CMCDController(hls) {
          var _this = this;
      
          this.hls = void 0;
          this.config = void 0;
          this.media = void 0;
          this.sid = void 0;
          this.cid = void 0;
          this.useHeaders = false;
          this.initialized = false;
          this.starved = false;
          this.buffering = true;
          this.audioBuffer = void 0;
          this.videoBuffer = void 0;
      
          this.onWaiting = function () {
            if (_this.initialized) {
              _this.starved = true;
            }
      
            _this.buffering = true;
          };
      
          this.onPlaying = function () {
            if (!_this.initialized) {
              _this.initialized = true;
            }
      
            _this.buffering = false;
          };
      
          this.applyPlaylistData = function (context) {
            try {
              _this.apply(context, {
                ot: _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDObjectType"].MANIFEST,
                su: !_this.initialized
              });
            } catch (error) {
              _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('Could not generate manifest CMCD data.', error);
            }
          };
      
          this.applyFragmentData = function (context) {
            try {
              var fragment = context.frag;
              var level = _this.hls.levels[fragment.level];
      
              var ot = _this.getObjectType(fragment);
      
              var data = {
                d: fragment.duration * 1000,
                ot: ot
              };
      
              if (ot === _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDObjectType"].VIDEO || ot === _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDObjectType"].AUDIO || ot == _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDObjectType"].MUXED) {
                data.br = level.bitrate / 1000;
                data.tb = _this.getTopBandwidth(ot);
                data.bl = _this.getBufferLength(ot);
              }
      
              _this.apply(context, data);
            } catch (error) {
              _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('Could not generate segment CMCD data.', error);
            }
          };
      
          this.hls = hls;
          var config = this.config = hls.config;
          var cmcd = config.cmcd;
      
          if (cmcd != null) {
            config.pLoader = this.createPlaylistLoader();
            config.fLoader = this.createFragmentLoader();
            this.sid = cmcd.sessionId || CMCDController.uuid();
            this.cid = cmcd.contentId;
            this.useHeaders = cmcd.useHeaders === true;
            this.registerListeners();
          }
        }
      
        var _proto = CMCDController.prototype;
      
        _proto.registerListeners = function registerListeners() {
          var hls = this.hls;
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHED, this.onMediaDetached, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_CREATED, this.onBufferCreated, this);
        };
      
        _proto.unregisterListeners = function unregisterListeners() {
          var hls = this.hls;
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHED, this.onMediaDetached, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_CREATED, this.onBufferCreated, this);
          this.onMediaDetached();
        };
      
        _proto.destroy = function destroy() {
          this.unregisterListeners(); // @ts-ignore
      
          this.hls = this.config = this.audioBuffer = this.videoBuffer = null;
        };
      
        _proto.onMediaAttached = function onMediaAttached(event, data) {
          this.media = data.media;
          this.media.addEventListener('waiting', this.onWaiting);
          this.media.addEventListener('playing', this.onPlaying);
        };
      
        _proto.onMediaDetached = function onMediaDetached() {
          if (!this.media) {
            return;
          }
      
          this.media.removeEventListener('waiting', this.onWaiting);
          this.media.removeEventListener('playing', this.onPlaying); // @ts-ignore
      
          this.media = null;
        };
      
        _proto.onBufferCreated = function onBufferCreated(event, data) {
          var _data$tracks$audio, _data$tracks$video;
      
          this.audioBuffer = (_data$tracks$audio = data.tracks.audio) === null || _data$tracks$audio === void 0 ? void 0 : _data$tracks$audio.buffer;
          this.videoBuffer = (_data$tracks$video = data.tracks.video) === null || _data$tracks$video === void 0 ? void 0 : _data$tracks$video.buffer;
        };
      
        /**
         * Create baseline CMCD data
         */
        _proto.createData = function createData() {
          var _this$media;
      
          return {
            v: _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDVersion"],
            sf: _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDStreamingFormat"].HLS,
            sid: this.sid,
            cid: this.cid,
            pr: (_this$media = this.media) === null || _this$media === void 0 ? void 0 : _this$media.playbackRate,
            mtp: this.hls.bandwidthEstimate / 1000
          };
        }
        /**
         * Apply CMCD data to a request.
         */
        ;
      
        _proto.apply = function apply(context, data) {
          if (data === void 0) {
            data = {};
          }
      
          // apply baseline data
          _extends(data, this.createData());
      
          var isVideo = data.ot === _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDObjectType"].INIT || data.ot === _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDObjectType"].VIDEO || data.ot === _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDObjectType"].MUXED;
      
          if (this.starved && isVideo) {
            data.bs = true;
            data.su = true;
            this.starved = false;
          }
      
          if (data.su == null) {
            data.su = this.buffering;
          } // TODO: Implement rtp, nrr, nor, dl
      
      
          if (this.useHeaders) {
            var headers = CMCDController.toHeaders(data);
      
            if (!Object.keys(headers).length) {
              return;
            }
      
            if (!context.headers) {
              context.headers = {};
            }
      
            _extends(context.headers, headers);
          } else {
            var query = CMCDController.toQuery(data);
      
            if (!query) {
              return;
            }
      
            context.url = CMCDController.appendQueryToUri(context.url, query);
          }
        }
        /**
         * Apply CMCD data to a manifest request.
         */
        ;
      
        /**
         * The CMCD object type.
         */
        _proto.getObjectType = function getObjectType(fragment) {
          var type = fragment.type;
      
          if (type === 'subtitle') {
            return _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDObjectType"].TIMED_TEXT;
          }
      
          if (fragment.sn === 'initSegment') {
            return _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDObjectType"].INIT;
          }
      
          if (type === 'audio') {
            return _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDObjectType"].AUDIO;
          }
      
          if (type === 'main') {
            if (!this.hls.audioTracks.length) {
              return _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDObjectType"].MUXED;
            }
      
            return _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDObjectType"].VIDEO;
          }
      
          return undefined;
        }
        /**
         * Get the highest bitrate.
         */
        ;
      
        _proto.getTopBandwidth = function getTopBandwidth(type) {
          var bitrate = 0;
          var levels = type === _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDObjectType"].AUDIO ? this.hls.audioTracks : this.hls.levels;
      
          for (var _iterator = _createForOfIteratorHelperLoose(levels), _step; !(_step = _iterator()).done;) {
            var level = _step.value;
      
            if (level.bitrate > bitrate) {
              bitrate = level.bitrate;
            }
          }
      
          return bitrate > 0 ? bitrate : NaN;
        }
        /**
         * Get the buffer length for a media type in milliseconds
         */
        ;
      
        _proto.getBufferLength = function getBufferLength(type) {
          var media = this.hls.media;
          var buffer = type === _types_cmcd__WEBPACK_IMPORTED_MODULE_1__["CMCDObjectType"].AUDIO ? this.audioBuffer : this.videoBuffer;
      
          if (!buffer || !media) {
            return NaN;
          }
      
          var info = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_2__["BufferHelper"].bufferInfo(buffer, media.currentTime, this.config.maxBufferHole);
          return info.len * 1000;
        }
        /**
         * Create a playlist loader
         */
        ;
      
        _proto.createPlaylistLoader = function createPlaylistLoader() {
          var pLoader = this.config.pLoader;
          var apply = this.applyPlaylistData;
          var Ctor = pLoader || this.config.loader;
          return /*#__PURE__*/function () {
            function CmcdPlaylistLoader(config) {
              this.loader = void 0;
              this.loader = new Ctor(config);
            }
      
            var _proto2 = CmcdPlaylistLoader.prototype;
      
            _proto2.destroy = function destroy() {
              this.loader.destroy();
            };
      
            _proto2.abort = function abort() {
              this.loader.abort();
            };
      
            _proto2.load = function load(context, config, callbacks) {
              apply(context);
              this.loader.load(context, config, callbacks);
            };
      
            _createClass(CmcdPlaylistLoader, [{
              key: "stats",
              get: function get() {
                return this.loader.stats;
              }
            }, {
              key: "context",
              get: function get() {
                return this.loader.context;
              }
            }]);
      
            return CmcdPlaylistLoader;
          }();
        }
        /**
         * Create a playlist loader
         */
        ;
      
        _proto.createFragmentLoader = function createFragmentLoader() {
          var fLoader = this.config.fLoader;
          var apply = this.applyFragmentData;
          var Ctor = fLoader || this.config.loader;
          return /*#__PURE__*/function () {
            function CmcdFragmentLoader(config) {
              this.loader = void 0;
              this.loader = new Ctor(config);
            }
      
            var _proto3 = CmcdFragmentLoader.prototype;
      
            _proto3.destroy = function destroy() {
              this.loader.destroy();
            };
      
            _proto3.abort = function abort() {
              this.loader.abort();
            };
      
            _proto3.load = function load(context, config, callbacks) {
              apply(context);
              this.loader.load(context, config, callbacks);
            };
      
            _createClass(CmcdFragmentLoader, [{
              key: "stats",
              get: function get() {
                return this.loader.stats;
              }
            }, {
              key: "context",
              get: function get() {
                return this.loader.context;
              }
            }]);
      
            return CmcdFragmentLoader;
          }();
        }
        /**
         * Generate a random v4 UUI
         *
         * @returns {string}
         */
        ;
      
        CMCDController.uuid = function uuid() {
          var url = URL.createObjectURL(new Blob());
          var uuid = url.toString();
          URL.revokeObjectURL(url);
          return uuid.substr(uuid.lastIndexOf('/') + 1);
        }
        /**
         * Serialize a CMCD data object according to the rules defined in the
         * section 3.2 of
         * [CTA-5004](https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf).
         */
        ;
      
        CMCDController.serialize = function serialize(data) {
          var results = [];
      
          var isValid = function isValid(value) {
            return !Number.isNaN(value) && value != null && value !== '' && value !== false;
          };
      
          var toRounded = function toRounded(value) {
            return Math.round(value);
          };
      
          var toHundred = function toHundred(value) {
            return toRounded(value / 100) * 100;
          };
      
          var toUrlSafe = function toUrlSafe(value) {
            return encodeURIComponent(value);
          };
      
          var formatters = {
            br: toRounded,
            d: toRounded,
            bl: toHundred,
            dl: toHundred,
            mtp: toHundred,
            nor: toUrlSafe,
            rtp: toHundred,
            tb: toRounded
          };
          var keys = Object.keys(data || {}).sort();
      
          for (var _iterator2 = _createForOfIteratorHelperLoose(keys), _step2; !(_step2 = _iterator2()).done;) {
            var key = _step2.value;
            var value = data[key]; // ignore invalid values
      
            if (!isValid(value)) {
              continue;
            } // Version should only be reported if not equal to 1.
      
      
            if (key === 'v' && value === 1) {
              continue;
            } // Playback rate should only be sent if not equal to 1.
      
      
            if (key == 'pr' && value === 1) {
              continue;
            } // Certain values require special formatting
      
      
            var formatter = formatters[key];
      
            if (formatter) {
              value = formatter(value);
            } // Serialize the key/value pair
      
      
            var type = typeof value;
            var result = void 0;
      
            if (key === 'ot' || key === 'sf' || key === 'st') {
              result = key + "=" + value;
            } else if (type === 'boolean') {
              result = key;
            } else if (type === 'number') {
              result = key + "=" + value;
            } else {
              result = key + "=" + JSON.stringify(value);
            }
      
            results.push(result);
          }
      
          return results.join(',');
        }
        /**
         * Convert a CMCD data object to request headers according to the rules
         * defined in the section 2.1 and 3.2 of
         * [CTA-5004](https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf).
         */
        ;
      
        CMCDController.toHeaders = function toHeaders(data) {
          var keys = Object.keys(data);
          var headers = {};
          var headerNames = ['Object', 'Request', 'Session', 'Status'];
          var headerGroups = [{}, {}, {}, {}];
          var headerMap = {
            br: 0,
            d: 0,
            ot: 0,
            tb: 0,
            bl: 1,
            dl: 1,
            mtp: 1,
            nor: 1,
            nrr: 1,
            su: 1,
            cid: 2,
            pr: 2,
            sf: 2,
            sid: 2,
            st: 2,
            v: 2,
            bs: 3,
            rtp: 3
          };
      
          for (var _i = 0, _keys = keys; _i < _keys.length; _i++) {
            var key = _keys[_i];
            // Unmapped fields are mapped to the Request header
            var index = headerMap[key] != null ? headerMap[key] : 1;
            headerGroups[index][key] = data[key];
          }
      
          for (var i = 0; i < headerGroups.length; i++) {
            var value = CMCDController.serialize(headerGroups[i]);
      
            if (value) {
              headers["CMCD-" + headerNames[i]] = value;
            }
          }
      
          return headers;
        }
        /**
         * Convert a CMCD data object to query args according to the rules
         * defined in the section 2.2 and 3.2 of
         * [CTA-5004](https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf).
         */
        ;
      
        CMCDController.toQuery = function toQuery(data) {
          return "CMCD=" + encodeURIComponent(CMCDController.serialize(data));
        }
        /**
         * Append query args to a uri.
         */
        ;
      
        CMCDController.appendQueryToUri = function appendQueryToUri(uri, query) {
          if (!query) {
            return uri;
          }
      
          var separator = uri.includes('?') ? '&' : '?';
          return "" + uri + separator + query;
        };
      
        return CMCDController;
      }();
      
      
      
      /***/ }),
      
      /***/ "./src/controller/eme-controller.ts":
      /*!******************************************!*\
        !*** ./src/controller/eme-controller.ts ***!
        \******************************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
      /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      /* harmony import */ var _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/mediakeys-helper */ "./src/utils/mediakeys-helper.ts");
      function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
      
      function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
      
      /**
       * @author Stephan Hesse <disparat@gmail.com> | <tchakabam@gmail.com>
       *
       * DRM support for Hls.js
       */
      
      
      
      
      var MAX_LICENSE_REQUEST_FAILURES = 3;
      /**
       * @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration
       * @param {Array<string>} audioCodecs List of required audio codecs to support
       * @param {Array<string>} videoCodecs List of required video codecs to support
       * @param {object} drmSystemOptions Optional parameters/requirements for the key-system
       * @returns {Array<MediaSystemConfiguration>} An array of supported configurations
       */
      
      var createWidevineMediaKeySystemConfigurations = function createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs, drmSystemOptions) {
        /* jshint ignore:line */
        var baseConfig = {
          // initDataTypes: ['keyids', 'mp4'],
          // label: "",
          // persistentState: "not-allowed", // or "required" ?
          // distinctiveIdentifier: "not-allowed", // or "required" ?
          // sessionTypes: ['temporary'],
          audioCapabilities: [],
          // { contentType: 'audio/mp4; codecs="mp4a.40.2"' }
          videoCapabilities: [] // { contentType: 'video/mp4; codecs="avc1.42E01E"' }
      
        };
        audioCodecs.forEach(function (codec) {
          baseConfig.audioCapabilities.push({
            contentType: "audio/mp4; codecs=\"" + codec + "\"",
            robustness: drmSystemOptions.audioRobustness || ''
          });
        });
        videoCodecs.forEach(function (codec) {
          baseConfig.videoCapabilities.push({
            contentType: "video/mp4; codecs=\"" + codec + "\"",
            robustness: drmSystemOptions.videoRobustness || ''
          });
        });
        return [baseConfig];
      };
      /**
       * The idea here is to handle key-system (and their respective platforms) specific configuration differences
       * in order to work with the local requestMediaKeySystemAccess method.
       *
       * We can also rule-out platform-related key-system support at this point by throwing an error.
       *
       * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum
       * @param {Array<string>} audioCodecs List of required audio codecs to support
       * @param {Array<string>} videoCodecs List of required video codecs to support
       * @throws will throw an error if a unknown key system is passed
       * @returns {Array<MediaSystemConfiguration>} A non-empty Array of MediaKeySystemConfiguration objects
       */
      
      
      var getSupportedMediaKeySystemConfigurations = function getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, drmSystemOptions) {
        switch (keySystem) {
          case _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__["KeySystems"].WIDEVINE:
            return createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs, drmSystemOptions);
      
          default:
            throw new Error("Unknown key-system: " + keySystem);
        }
      };
      
      /**
       * Controller to deal with encrypted media extensions (EME)
       * @see https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API
       *
       * @class
       * @constructor
       */
      var EMEController = /*#__PURE__*/function () {
        /**
         * @constructs
         * @param {Hls} hls Our Hls.js instance
         */
        function EMEController(hls) {
          this.hls = void 0;
          this._widevineLicenseUrl = void 0;
          this._licenseXhrSetup = void 0;
          this._licenseResponseCallback = void 0;
          this._emeEnabled = void 0;
          this._requestMediaKeySystemAccess = void 0;
          this._drmSystemOptions = void 0;
          this._config = void 0;
          this._mediaKeysList = [];
          this._media = null;
          this._hasSetMediaKeys = false;
          this._requestLicenseFailureCount = 0;
          this.mediaKeysPromise = null;
          this._onMediaEncrypted = this.onMediaEncrypted.bind(this);
          this.hls = hls;
          this._config = hls.config;
          this._widevineLicenseUrl = this._config.widevineLicenseUrl;
          this._licenseXhrSetup = this._config.licenseXhrSetup;
          this._licenseResponseCallback = this._config.licenseResponseCallback;
          this._emeEnabled = this._config.emeEnabled;
          this._requestMediaKeySystemAccess = this._config.requestMediaKeySystemAccessFunc;
          this._drmSystemOptions = this._config.drmSystemOptions;
      
          this._registerListeners();
        }
      
        var _proto = EMEController.prototype;
      
        _proto.destroy = function destroy() {
          this._unregisterListeners(); // @ts-ignore
      
      
          this.hls = this._onMediaEncrypted = null;
          this._requestMediaKeySystemAccess = null;
        };
      
        _proto._registerListeners = function _registerListeners() {
          this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
          this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHED, this.onMediaDetached, this);
          this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
        };
      
        _proto._unregisterListeners = function _unregisterListeners() {
          this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
          this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHED, this.onMediaDetached, this);
          this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
        }
        /**
         * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum
         * @returns {string} License server URL for key-system (if any configured, otherwise causes error)
         * @throws if a unsupported keysystem is passed
         */
        ;
      
        _proto.getLicenseServerUrl = function getLicenseServerUrl(keySystem) {
          switch (keySystem) {
            case _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__["KeySystems"].WIDEVINE:
              if (!this._widevineLicenseUrl) {
                break;
              }
      
              return this._widevineLicenseUrl;
          }
      
          throw new Error("no license server URL configured for key-system \"" + keySystem + "\"");
        }
        /**
         * Requests access object and adds it to our list upon success
         * @private
         * @param {string} keySystem System ID (see `KeySystems`)
         * @param {Array<string>} audioCodecs List of required audio codecs to support
         * @param {Array<string>} videoCodecs List of required video codecs to support
         * @throws When a unsupported KeySystem is passed
         */
        ;
      
        _proto._attemptKeySystemAccess = function _attemptKeySystemAccess(keySystem, audioCodecs, videoCodecs) {
          var _this = this;
      
          // This can throw, but is caught in event handler callpath
          var mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, this._drmSystemOptions);
          _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('Requesting encrypted media key-system access'); // expecting interface like window.navigator.requestMediaKeySystemAccess
      
          var keySystemAccessPromise = this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs);
          this.mediaKeysPromise = keySystemAccessPromise.then(function (mediaKeySystemAccess) {
            return _this._onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess);
          });
          keySystemAccessPromise.catch(function (err) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("Failed to obtain key-system \"" + keySystem + "\" access:", err);
          });
        };
      
        /**
         * Handles obtaining access to a key-system
         * @private
         * @param {string} keySystem
         * @param {MediaKeySystemAccess} mediaKeySystemAccess https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemAccess
         */
        _proto._onMediaKeySystemAccessObtained = function _onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess) {
          var _this2 = this;
      
          _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Access for key-system \"" + keySystem + "\" obtained");
          var mediaKeysListItem = {
            mediaKeysSessionInitialized: false,
            mediaKeySystemAccess: mediaKeySystemAccess,
            mediaKeySystemDomain: keySystem
          };
      
          this._mediaKeysList.push(mediaKeysListItem);
      
          var mediaKeysPromise = Promise.resolve().then(function () {
            return mediaKeySystemAccess.createMediaKeys();
          }).then(function (mediaKeys) {
            mediaKeysListItem.mediaKeys = mediaKeys;
            _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Media-keys created for key-system \"" + keySystem + "\"");
      
            _this2._onMediaKeysCreated();
      
            return mediaKeys;
          });
          mediaKeysPromise.catch(function (err) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Failed to create media-keys:', err);
          });
          return mediaKeysPromise;
        }
        /**
         * Handles key-creation (represents access to CDM). We are going to create key-sessions upon this
         * for all existing keys where no session exists yet.
         *
         * @private
         */
        ;
      
        _proto._onMediaKeysCreated = function _onMediaKeysCreated() {
          var _this3 = this;
      
          // check for all key-list items if a session exists, otherwise, create one
          this._mediaKeysList.forEach(function (mediaKeysListItem) {
            if (!mediaKeysListItem.mediaKeysSession) {
              // mediaKeys is definitely initialized here
              mediaKeysListItem.mediaKeysSession = mediaKeysListItem.mediaKeys.createSession();
      
              _this3._onNewMediaKeySession(mediaKeysListItem.mediaKeysSession);
            }
          });
        }
        /**
         * @private
         * @param {*} keySession
         */
        ;
      
        _proto._onNewMediaKeySession = function _onNewMediaKeySession(keySession) {
          var _this4 = this;
      
          _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("New key-system session " + keySession.sessionId);
          keySession.addEventListener('message', function (event) {
            _this4._onKeySessionMessage(keySession, event.message);
          }, false);
        }
        /**
         * @private
         * @param {MediaKeySession} keySession
         * @param {ArrayBuffer} message
         */
        ;
      
        _proto._onKeySessionMessage = function _onKeySessionMessage(keySession, message) {
          _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('Got EME message event, creating license request');
      
          this._requestLicense(message, function (data) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Received license data (length: " + (data ? data.byteLength : data) + "), updating key-session");
            keySession.update(data);
          });
        }
        /**
         * @private
         * @param e {MediaEncryptedEvent}
         */
        ;
      
        _proto.onMediaEncrypted = function onMediaEncrypted(e) {
          var _this5 = this;
      
          _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Media is encrypted using \"" + e.initDataType + "\" init data type");
      
          if (!this.mediaKeysPromise) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Fatal: Media is encrypted but no CDM access or no keys have been requested');
            this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
              type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
              details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_KEYS,
              fatal: true
            });
            return;
          }
      
          var finallySetKeyAndStartSession = function finallySetKeyAndStartSession(mediaKeys) {
            if (!_this5._media) {
              return;
            }
      
            _this5._attemptSetMediaKeys(mediaKeys);
      
            _this5._generateRequestWithPreferredKeySession(e.initDataType, e.initData);
          }; // Could use `Promise.finally` but some Promise polyfills are missing it
      
      
          this.mediaKeysPromise.then(finallySetKeyAndStartSession).catch(finallySetKeyAndStartSession);
        }
        /**
         * @private
         */
        ;
      
        _proto._attemptSetMediaKeys = function _attemptSetMediaKeys(mediaKeys) {
          if (!this._media) {
            throw new Error('Attempted to set mediaKeys without first attaching a media element');
          }
      
          if (!this._hasSetMediaKeys) {
            // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?
            var keysListItem = this._mediaKeysList[0];
      
            if (!keysListItem || !keysListItem.mediaKeys) {
              _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Fatal: Media is encrypted but no CDM access or no keys have been obtained yet');
              this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
                type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
                details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_KEYS,
                fatal: true
              });
              return;
            }
      
            _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('Setting keys for encrypted media');
      
            this._media.setMediaKeys(keysListItem.mediaKeys);
      
            this._hasSetMediaKeys = true;
          }
        }
        /**
         * @private
         */
        ;
      
        _proto._generateRequestWithPreferredKeySession = function _generateRequestWithPreferredKeySession(initDataType, initData) {
          var _this6 = this;
      
          // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?
          var keysListItem = this._mediaKeysList[0];
      
          if (!keysListItem) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Fatal: Media is encrypted but not any key-system access has been obtained yet');
            this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
              type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
              details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_ACCESS,
              fatal: true
            });
            return;
          }
      
          if (keysListItem.mediaKeysSessionInitialized) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('Key-Session already initialized but requested again');
            return;
          }
      
          var keySession = keysListItem.mediaKeysSession;
      
          if (!keySession) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Fatal: Media is encrypted but no key-session existing');
            this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
              type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
              details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_SESSION,
              fatal: true
            });
            return;
          } // initData is null if the media is not CORS-same-origin
      
      
          if (!initData) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('Fatal: initData required for generating a key session is null');
            this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
              type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
              details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_INIT_DATA,
              fatal: true
            });
            return;
          }
      
          _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Generating key-session request for \"" + initDataType + "\" init data type");
          keysListItem.mediaKeysSessionInitialized = true;
          keySession.generateRequest(initDataType, initData).then(function () {
            _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].debug('Key-session generation succeeded');
          }).catch(function (err) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Error generating key-session request:', err);
      
            _this6.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
              type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
              details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_SESSION,
              fatal: false
            });
          });
        }
        /**
         * @private
         * @param {string} url License server URL
         * @param {ArrayBuffer} keyMessage Message data issued by key-system
         * @param {function} callback Called when XHR has succeeded
         * @returns {XMLHttpRequest} Unsent (but opened state) XHR object
         * @throws if XMLHttpRequest construction failed
         */
        ;
      
        _proto._createLicenseXhr = function _createLicenseXhr(url, keyMessage, callback) {
          var xhr = new XMLHttpRequest();
          xhr.responseType = 'arraybuffer';
          xhr.onreadystatechange = this._onLicenseRequestReadyStageChange.bind(this, xhr, url, keyMessage, callback);
          var licenseXhrSetup = this._licenseXhrSetup;
      
          if (licenseXhrSetup) {
            try {
              licenseXhrSetup.call(this.hls, xhr, url);
              licenseXhrSetup = undefined;
            } catch (e) {
              _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error(e);
            }
          }
      
          try {
            // if licenseXhrSetup did not yet call open, let's do it now
            if (!xhr.readyState) {
              xhr.open('POST', url, true);
            }
      
            if (licenseXhrSetup) {
              licenseXhrSetup.call(this.hls, xhr, url);
            }
          } catch (e) {
            // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
            throw new Error("issue setting up KeySystem license XHR " + e);
          }
      
          return xhr;
        }
        /**
         * @private
         * @param {XMLHttpRequest} xhr
         * @param {string} url License server URL
         * @param {ArrayBuffer} keyMessage Message data issued by key-system
         * @param {function} callback Called when XHR has succeeded
         */
        ;
      
        _proto._onLicenseRequestReadyStageChange = function _onLicenseRequestReadyStageChange(xhr, url, keyMessage, callback) {
          switch (xhr.readyState) {
            case 4:
              if (xhr.status === 200) {
                this._requestLicenseFailureCount = 0;
                _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('License request succeeded');
                var _data = xhr.response;
                var licenseResponseCallback = this._licenseResponseCallback;
      
                if (licenseResponseCallback) {
                  try {
                    _data = licenseResponseCallback.call(this.hls, xhr, url);
                  } catch (e) {
                    _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error(e);
                  }
                }
      
                callback(_data);
              } else {
                _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("License Request XHR failed (" + url + "). Status: " + xhr.status + " (" + xhr.statusText + ")");
                this._requestLicenseFailureCount++;
      
                if (this._requestLicenseFailureCount > MAX_LICENSE_REQUEST_FAILURES) {
                  this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
                    type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
                    details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_LICENSE_REQUEST_FAILED,
                    fatal: true
                  });
                  return;
                }
      
                var attemptsLeft = MAX_LICENSE_REQUEST_FAILURES - this._requestLicenseFailureCount + 1;
                _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("Retrying license request, " + attemptsLeft + " attempts left");
      
                this._requestLicense(keyMessage, callback);
              }
      
              break;
          }
        }
        /**
         * @private
         * @param {MediaKeysListItem} keysListItem
         * @param {ArrayBuffer} keyMessage
         * @returns {ArrayBuffer} Challenge data posted to license server
         * @throws if KeySystem is unsupported
         */
        ;
      
        _proto._generateLicenseRequestChallenge = function _generateLicenseRequestChallenge(keysListItem, keyMessage) {
          switch (keysListItem.mediaKeySystemDomain) {
            // case KeySystems.PLAYREADY:
            // from https://github.com/MicrosoftEdge/Demos/blob/master/eme/scripts/demo.js
      
            /*
            if (this.licenseType !== this.LICENSE_TYPE_WIDEVINE) {
              // For PlayReady CDMs, we need to dig the Challenge out of the XML.
              var keyMessageXml = new DOMParser().parseFromString(String.fromCharCode.apply(null, new Uint16Array(keyMessage)), 'application/xml');
              if (keyMessageXml.getElementsByTagName('Challenge')[0]) {
                  challenge = atob(keyMessageXml.getElementsByTagName('Challenge')[0].childNodes[0].nodeValue);
              } else {
                  throw 'Cannot find <Challenge> in key message';
              }
              var headerNames = keyMessageXml.getElementsByTagName('name');
              var headerValues = keyMessageXml.getElementsByTagName('value');
              if (headerNames.length !== headerValues.length) {
                  throw 'Mismatched header <name>/<value> pair in key message';
              }
              for (var i = 0; i < headerNames.length; i++) {
                  xhr.setRequestHeader(headerNames[i].childNodes[0].nodeValue, headerValues[i].childNodes[0].nodeValue);
              }
            }
            break;
            */
            case _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__["KeySystems"].WIDEVINE:
              // For Widevine CDMs, the challenge is the keyMessage.
              return keyMessage;
          }
      
          throw new Error("unsupported key-system: " + keysListItem.mediaKeySystemDomain);
        }
        /**
         * @private
         * @param keyMessage
         * @param callback
         */
        ;
      
        _proto._requestLicense = function _requestLicense(keyMessage, callback) {
          _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('Requesting content license for key-system');
          var keysListItem = this._mediaKeysList[0];
      
          if (!keysListItem) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Fatal error: Media is encrypted but no key-system access has been obtained yet');
            this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
              type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
              details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_ACCESS,
              fatal: true
            });
            return;
          }
      
          try {
            var _url = this.getLicenseServerUrl(keysListItem.mediaKeySystemDomain);
      
            var _xhr = this._createLicenseXhr(_url, keyMessage, callback);
      
            _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Sending license request to URL: " + _url);
      
            var challenge = this._generateLicenseRequestChallenge(keysListItem, keyMessage);
      
            _xhr.send(challenge);
          } catch (e) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("Failure requesting DRM license: " + e);
            this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
              type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
              details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_LICENSE_REQUEST_FAILED,
              fatal: true
            });
          }
        };
      
        _proto.onMediaAttached = function onMediaAttached(event, data) {
          if (!this._emeEnabled) {
            return;
          }
      
          var media = data.media; // keep reference of media
      
          this._media = media;
          media.addEventListener('encrypted', this._onMediaEncrypted);
        };
      
        _proto.onMediaDetached = function onMediaDetached() {
          var media = this._media;
          var mediaKeysList = this._mediaKeysList;
      
          if (!media) {
            return;
          }
      
          media.removeEventListener('encrypted', this._onMediaEncrypted);
          this._media = null;
          this._mediaKeysList = []; // Close all sessions and remove media keys from the video element.
      
          Promise.all(mediaKeysList.map(function (mediaKeysListItem) {
            if (mediaKeysListItem.mediaKeysSession) {
              return mediaKeysListItem.mediaKeysSession.close().catch(function () {// Ignore errors when closing the sessions. Closing a session that
                // generated no key requests will throw an error.
              });
            }
          })).then(function () {
            return media.setMediaKeys(null);
          }).catch(function () {// Ignore any failures while removing media keys from the video element.
          });
        };
      
        _proto.onManifestParsed = function onManifestParsed(event, data) {
          if (!this._emeEnabled) {
            return;
          }
      
          var audioCodecs = data.levels.map(function (level) {
            return level.audioCodec;
          }).filter(function (audioCodec) {
            return !!audioCodec;
          });
          var videoCodecs = data.levels.map(function (level) {
            return level.videoCodec;
          }).filter(function (videoCodec) {
            return !!videoCodec;
          });
      
          this._attemptKeySystemAccess(_utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__["KeySystems"].WIDEVINE, audioCodecs, videoCodecs);
        };
      
        _createClass(EMEController, [{
          key: "requestMediaKeySystemAccess",
          get: function get() {
            if (!this._requestMediaKeySystemAccess) {
              throw new Error('No requestMediaKeySystemAccess function configured');
            }
      
            return this._requestMediaKeySystemAccess;
          }
        }]);
      
        return EMEController;
      }();
      
      /* harmony default export */ __webpack_exports__["default"] = (EMEController);
      
      /***/ }),
      
      /***/ "./src/controller/fps-controller.ts":
      /*!******************************************!*\
        !*** ./src/controller/fps-controller.ts ***!
        \******************************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      
      
      
      var FPSController = /*#__PURE__*/function () {
        // stream controller must be provided as a dependency!
        function FPSController(hls) {
          this.hls = void 0;
          this.isVideoPlaybackQualityAvailable = false;
          this.timer = void 0;
          this.media = null;
          this.lastTime = void 0;
          this.lastDroppedFrames = 0;
          this.lastDecodedFrames = 0;
          this.streamController = void 0;
          this.hls = hls;
          this.registerListeners();
        }
      
        var _proto = FPSController.prototype;
      
        _proto.setStreamController = function setStreamController(streamController) {
          this.streamController = streamController;
        };
      
        _proto.registerListeners = function registerListeners() {
          this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
        };
      
        _proto.unregisterListeners = function unregisterListeners() {
          this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHING, this.onMediaAttaching);
        };
      
        _proto.destroy = function destroy() {
          if (this.timer) {
            clearInterval(this.timer);
          }
      
          this.unregisterListeners();
          this.isVideoPlaybackQualityAvailable = false;
          this.media = null;
        };
      
        _proto.onMediaAttaching = function onMediaAttaching(event, data) {
          var config = this.hls.config;
      
          if (config.capLevelOnFPSDrop) {
            var media = data.media instanceof self.HTMLVideoElement ? data.media : null;
            this.media = media;
      
            if (media && typeof media.getVideoPlaybackQuality === 'function') {
              this.isVideoPlaybackQualityAvailable = true;
            }
      
            self.clearInterval(this.timer);
            this.timer = self.setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
          }
        };
      
        _proto.checkFPS = function checkFPS(video, decodedFrames, droppedFrames) {
          var currentTime = performance.now();
      
          if (decodedFrames) {
            if (this.lastTime) {
              var currentPeriod = currentTime - this.lastTime;
              var currentDropped = droppedFrames - this.lastDroppedFrames;
              var currentDecoded = decodedFrames - this.lastDecodedFrames;
              var droppedFPS = 1000 * currentDropped / currentPeriod;
              var hls = this.hls;
              hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FPS_DROP, {
                currentDropped: currentDropped,
                currentDecoded: currentDecoded,
                totalDroppedFrames: droppedFrames
              });
      
              if (droppedFPS > 0) {
                // logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));
                if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
                  var currentLevel = hls.currentLevel;
                  _utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);
      
                  if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {
                    currentLevel = currentLevel - 1;
                    hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FPS_DROP_LEVEL_CAPPING, {
                      level: currentLevel,
                      droppedLevel: hls.currentLevel
                    });
                    hls.autoLevelCapping = currentLevel;
                    this.streamController.nextLevelSwitch();
                  }
                }
              }
            }
      
            this.lastTime = currentTime;
            this.lastDroppedFrames = droppedFrames;
            this.lastDecodedFrames = decodedFrames;
          }
        };
      
        _proto.checkFPSInterval = function checkFPSInterval() {
          var video = this.media;
      
          if (video) {
            if (this.isVideoPlaybackQualityAvailable) {
              var videoPlaybackQuality = video.getVideoPlaybackQuality();
              this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
            } else {
              // HTMLVideoElement doesn't include the webkit types
              this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
            }
          }
        };
      
        return FPSController;
      }();
      
      /* harmony default export */ __webpack_exports__["default"] = (FPSController);
      
      /***/ }),
      
      /***/ "./src/controller/fragment-finders.ts":
      /*!********************************************!*\
        !*** ./src/controller/fragment-finders.ts ***!
        \********************************************/
      /*! exports provided: findFragmentByPDT, findFragmentByPTS, fragmentWithinToleranceTest, pdtWithinToleranceTest, findFragWithCC */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findFragmentByPDT", function() { return findFragmentByPDT; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findFragmentByPTS", function() { return findFragmentByPTS; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fragmentWithinToleranceTest", function() { return fragmentWithinToleranceTest; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pdtWithinToleranceTest", function() { return pdtWithinToleranceTest; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findFragWithCC", function() { return findFragWithCC; });
      /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
      /* harmony import */ var _utils_binary_search__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/binary-search */ "./src/utils/binary-search.ts");
      
      
      
      /**
       * Returns first fragment whose endPdt value exceeds the given PDT.
       * @param {Array<Fragment>} fragments - The array of candidate fragments
       * @param {number|null} [PDTValue = null] - The PDT value which must be exceeded
       * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start/end can be within in order to be considered contiguous
       * @returns {*|null} fragment - The best matching fragment
       */
      function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {
        if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(PDTValue)) {
          return null;
        } // if less than start
      
      
        var startPDT = fragments[0].programDateTime;
      
        if (PDTValue < (startPDT || 0)) {
          return null;
        }
      
        var endPDT = fragments[fragments.length - 1].endProgramDateTime;
      
        if (PDTValue >= (endPDT || 0)) {
          return null;
        }
      
        maxFragLookUpTolerance = maxFragLookUpTolerance || 0;
      
        for (var seg = 0; seg < fragments.length; ++seg) {
          var frag = fragments[seg];
      
          if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {
            return frag;
          }
        }
      
        return null;
      }
      /**
       * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.
       * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus
       * breaking any traps which would cause the same fragment to be continuously selected within a small range.
       * @param {*} fragPrevious - The last frag successfully appended
       * @param {Array} fragments - The array of candidate fragments
       * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within
       * @param {number} maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
       * @returns {*} foundFrag - The best matching fragment
       */
      
      function findFragmentByPTS(fragPrevious, fragments, bufferEnd, maxFragLookUpTolerance) {
        if (bufferEnd === void 0) {
          bufferEnd = 0;
        }
      
        if (maxFragLookUpTolerance === void 0) {
          maxFragLookUpTolerance = 0;
        }
      
        var fragNext = null;
      
        if (fragPrevious) {
          fragNext = fragments[fragPrevious.sn - fragments[0].sn + 1] || null;
        } else if (bufferEnd === 0 && fragments[0].start === 0) {
          fragNext = fragments[0];
        } // Prefer the next fragment if it's within tolerance
      
      
        if (fragNext && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0) {
          return fragNext;
        } // We might be seeking past the tolerance so find the best match
      
      
        var foundFragment = _utils_binary_search__WEBPACK_IMPORTED_MODULE_1__["default"].search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));
      
        if (foundFragment) {
          return foundFragment;
        } // If no match was found return the next fragment after fragPrevious, or null
      
      
        return fragNext;
      }
      /**
       * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.
       * @param {*} candidate - The fragment to test
       * @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within
       * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous
       * @returns {number} - 0 if it matches, 1 if too low, -1 if too high
       */
      
      function fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, candidate) {
        if (bufferEnd === void 0) {
          bufferEnd = 0;
        }
      
        if (maxFragLookUpTolerance === void 0) {
          maxFragLookUpTolerance = 0;
        }
      
        // offset should be within fragment boundary - config.maxFragLookUpTolerance
        // this is to cope with situations like
        // bufferEnd = 9.991
        // frag[Ø] : [0,10]
        // frag[1] : [10,20]
        // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
        //              frag start               frag start+duration
        //                  |-----------------------------|
        //              <--->                         <--->
        //  ...--------><-----------------------------><---------....
        // previous frag         matching fragment         next frag
        //  return -1             return 0                 return 1
        // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
        // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
        var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
      
        if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
          return 1;
        } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
          // if maxFragLookUpTolerance will have negative value then don't return -1 for first element
          return -1;
        }
      
        return 0;
      }
      /**
       * The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.
       * This function tests the candidate's program date time values, as represented in Unix time
       * @param {*} candidate - The fragment to test
       * @param {number} [pdtBufferEnd = 0] - The Unix time representing the end of the current buffered range
       * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous
       * @returns {boolean} True if contiguous, false otherwise
       */
      
      function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {
        var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000; // endProgramDateTime can be null, default to zero
      
        var endProgramDateTime = candidate.endProgramDateTime || 0;
        return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;
      }
      function findFragWithCC(fragments, cc) {
        return _utils_binary_search__WEBPACK_IMPORTED_MODULE_1__["default"].search(fragments, function (candidate) {
          if (candidate.cc < cc) {
            return 1;
          } else if (candidate.cc > cc) {
            return -1;
          } else {
            return 0;
          }
        });
      }
      
      /***/ }),
      
      /***/ "./src/controller/fragment-tracker.ts":
      /*!********************************************!*\
        !*** ./src/controller/fragment-tracker.ts ***!
        \********************************************/
      /*! exports provided: FragmentState, FragmentTracker */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FragmentState", function() { return FragmentState; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FragmentTracker", function() { return FragmentTracker; });
      /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
      /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
      
      
      var FragmentState;
      
      (function (FragmentState) {
        FragmentState["NOT_LOADED"] = "NOT_LOADED";
        FragmentState["BACKTRACKED"] = "BACKTRACKED";
        FragmentState["APPENDING"] = "APPENDING";
        FragmentState["PARTIAL"] = "PARTIAL";
        FragmentState["OK"] = "OK";
      })(FragmentState || (FragmentState = {}));
      
      var FragmentTracker = /*#__PURE__*/function () {
        function FragmentTracker(hls) {
          this.activeFragment = null;
          this.activeParts = null;
          this.fragments = Object.create(null);
          this.timeRanges = Object.create(null);
          this.bufferPadding = 0.2;
          this.hls = void 0;
          this.hls = hls;
      
          this._registerListeners();
        }
      
        var _proto = FragmentTracker.prototype;
      
        _proto._registerListeners = function _registerListeners() {
          var hls = this.hls;
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_APPENDED, this.onBufferAppended, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_LOADED, this.onFragLoaded, this);
        };
      
        _proto._unregisterListeners = function _unregisterListeners() {
          var hls = this.hls;
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_APPENDED, this.onBufferAppended, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_LOADED, this.onFragLoaded, this);
        };
      
        _proto.destroy = function destroy() {
          this._unregisterListeners(); // @ts-ignore
      
      
          this.fragments = this.timeRanges = null;
        }
        /**
         * Return a Fragment with an appended range that matches the position and levelType.
         * If not found any Fragment, return null
         */
        ;
      
        _proto.getAppendedFrag = function getAppendedFrag(position, levelType) {
          if (levelType === _types_loader__WEBPACK_IMPORTED_MODULE_1__["PlaylistLevelType"].MAIN) {
            var activeFragment = this.activeFragment,
                activeParts = this.activeParts;
      
            if (!activeFragment) {
              return null;
            }
      
            if (activeParts) {
              for (var i = activeParts.length; i--;) {
                var activePart = activeParts[i];
                var appendedPTS = activePart ? activePart.end : activeFragment.appendedPTS;
      
                if (activePart.start <= position && appendedPTS !== undefined && position <= appendedPTS) {
                  // 9 is a magic number. remove parts from lookup after a match but keep some short seeks back.
                  if (i > 9) {
                    this.activeParts = activeParts.slice(i - 9);
                  }
      
                  return activePart;
                }
              }
            } else if (activeFragment.start <= position && activeFragment.appendedPTS !== undefined && position <= activeFragment.appendedPTS) {
              return activeFragment;
            }
          }
      
          return this.getBufferedFrag(position, levelType);
        }
        /**
         * Return a buffered Fragment that matches the position and levelType.
         * A buffered Fragment is one whose loading, parsing and appending is done (completed or "partial" meaning aborted).
         * If not found any Fragment, return null
         */
        ;
      
        _proto.getBufferedFrag = function getBufferedFrag(position, levelType) {
          var fragments = this.fragments;
          var keys = Object.keys(fragments);
      
          for (var i = keys.length; i--;) {
            var fragmentEntity = fragments[keys[i]];
      
            if ((fragmentEntity === null || fragmentEntity === void 0 ? void 0 : fragmentEntity.body.type) === levelType && fragmentEntity.buffered) {
              var frag = fragmentEntity.body;
      
              if (frag.start <= position && position <= frag.end) {
                return frag;
              }
            }
          }
      
          return null;
        }
        /**
         * Partial fragments effected by coded frame eviction will be removed
         * The browser will unload parts of the buffer to free up memory for new buffer data
         * Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable)
         */
        ;
      
        _proto.detectEvictedFragments = function detectEvictedFragments(elementaryStream, timeRange, playlistType) {
          var _this = this;
      
          // Check if any flagged fragments have been unloaded
          Object.keys(this.fragments).forEach(function (key) {
            var fragmentEntity = _this.fragments[key];
      
            if (!fragmentEntity) {
              return;
            }
      
            if (!fragmentEntity.buffered) {
              if (fragmentEntity.body.type === playlistType) {
                _this.removeFragment(fragmentEntity.body);
              }
      
              return;
            }
      
            var esData = fragmentEntity.range[elementaryStream];
      
            if (!esData) {
              return;
            }
      
            esData.time.some(function (time) {
              var isNotBuffered = !_this.isTimeBuffered(time.startPTS, time.endPTS, timeRange);
      
              if (isNotBuffered) {
                // Unregister partial fragment as it needs to load again to be reused
                _this.removeFragment(fragmentEntity.body);
              }
      
              return isNotBuffered;
            });
          });
        }
        /**
         * Checks if the fragment passed in is loaded in the buffer properly
         * Partially loaded fragments will be registered as a partial fragment
         */
        ;
      
        _proto.detectPartialFragments = function detectPartialFragments(data) {
          var _this2 = this;
      
          var timeRanges = this.timeRanges;
          var frag = data.frag,
              part = data.part;
      
          if (!timeRanges || frag.sn === 'initSegment') {
            return;
          }
      
          var fragKey = getFragmentKey(frag);
          var fragmentEntity = this.fragments[fragKey];
      
          if (!fragmentEntity) {
            return;
          }
      
          Object.keys(timeRanges).forEach(function (elementaryStream) {
            var streamInfo = frag.elementaryStreams[elementaryStream];
      
            if (!streamInfo) {
              return;
            }
      
            var timeRange = timeRanges[elementaryStream];
            var partial = part !== null || streamInfo.partial === true;
            fragmentEntity.range[elementaryStream] = _this2.getBufferedTimes(frag, part, partial, timeRange);
          });
          fragmentEntity.backtrack = fragmentEntity.loaded = null;
      
          if (Object.keys(fragmentEntity.range).length) {
            fragmentEntity.buffered = true;
          } else {
            // remove fragment if nothing was appended
            this.removeFragment(fragmentEntity.body);
          }
        };
      
        _proto.fragBuffered = function fragBuffered(frag) {
          var fragKey = getFragmentKey(frag);
          var fragmentEntity = this.fragments[fragKey];
      
          if (fragmentEntity) {
            fragmentEntity.backtrack = fragmentEntity.loaded = null;
            fragmentEntity.buffered = true;
          }
        };
      
        _proto.getBufferedTimes = function getBufferedTimes(fragment, part, partial, timeRange) {
          var buffered = {
            time: [],
            partial: partial
          };
          var startPTS = part ? part.start : fragment.start;
          var endPTS = part ? part.end : fragment.end;
          var minEndPTS = fragment.minEndPTS || endPTS;
          var maxStartPTS = fragment.maxStartPTS || startPTS;
      
          for (var i = 0; i < timeRange.length; i++) {
            var startTime = timeRange.start(i) - this.bufferPadding;
            var endTime = timeRange.end(i) + this.bufferPadding;
      
            if (maxStartPTS >= startTime && minEndPTS <= endTime) {
              // Fragment is entirely contained in buffer
              // No need to check the other timeRange times since it's completely playable
              buffered.time.push({
                startPTS: Math.max(startPTS, timeRange.start(i)),
                endPTS: Math.min(endPTS, timeRange.end(i))
              });
              break;
            } else if (startPTS < endTime && endPTS > startTime) {
              buffered.partial = true; // Check for intersection with buffer
              // Get playable sections of the fragment
      
              buffered.time.push({
                startPTS: Math.max(startPTS, timeRange.start(i)),
                endPTS: Math.min(endPTS, timeRange.end(i))
              });
            } else if (endPTS <= startTime) {
              // No need to check the rest of the timeRange as it is in order
              break;
            }
          }
      
          return buffered;
        }
        /**
         * Gets the partial fragment for a certain time
         */
        ;
      
        _proto.getPartialFragment = function getPartialFragment(time) {
          var bestFragment = null;
          var timePadding;
          var startTime;
          var endTime;
          var bestOverlap = 0;
          var bufferPadding = this.bufferPadding,
              fragments = this.fragments;
          Object.keys(fragments).forEach(function (key) {
            var fragmentEntity = fragments[key];
      
            if (!fragmentEntity) {
              return;
            }
      
            if (isPartial(fragmentEntity)) {
              startTime = fragmentEntity.body.start - bufferPadding;
              endTime = fragmentEntity.body.end + bufferPadding;
      
              if (time >= startTime && time <= endTime) {
                // Use the fragment that has the most padding from start and end time
                timePadding = Math.min(time - startTime, endTime - time);
      
                if (bestOverlap <= timePadding) {
                  bestFragment = fragmentEntity.body;
                  bestOverlap = timePadding;
                }
              }
            }
          });
          return bestFragment;
        };
      
        _proto.getState = function getState(fragment) {
          var fragKey = getFragmentKey(fragment);
          var fragmentEntity = this.fragments[fragKey];
      
          if (fragmentEntity) {
            if (!fragmentEntity.buffered) {
              if (fragmentEntity.backtrack) {
                return FragmentState.BACKTRACKED;
              }
      
              return FragmentState.APPENDING;
            } else if (isPartial(fragmentEntity)) {
              return FragmentState.PARTIAL;
            } else {
              return FragmentState.OK;
            }
          }
      
          return FragmentState.NOT_LOADED;
        };
      
        _proto.backtrack = function backtrack(frag, data) {
          var fragKey = getFragmentKey(frag);
          var fragmentEntity = this.fragments[fragKey];
      
          if (!fragmentEntity || fragmentEntity.backtrack) {
            return null;
          }
      
          var backtrack = fragmentEntity.backtrack = data ? data : fragmentEntity.loaded;
          fragmentEntity.loaded = null;
          return backtrack;
        };
      
        _proto.getBacktrackData = function getBacktrackData(fragment) {
          var fragKey = getFragmentKey(fragment);
          var fragmentEntity = this.fragments[fragKey];
      
          if (fragmentEntity) {
            var _backtrack$payload;
      
            var backtrack = fragmentEntity.backtrack; // If data was already sent to Worker it is detached no longer available
      
            if (backtrack !== null && backtrack !== void 0 && (_backtrack$payload = backtrack.payload) !== null && _backtrack$payload !== void 0 && _backtrack$payload.byteLength) {
              return backtrack;
            } else {
              this.removeFragment(fragment);
            }
          }
      
          return null;
        };
      
        _proto.isTimeBuffered = function isTimeBuffered(startPTS, endPTS, timeRange) {
          var startTime;
          var endTime;
      
          for (var i = 0; i < timeRange.length; i++) {
            startTime = timeRange.start(i) - this.bufferPadding;
            endTime = timeRange.end(i) + this.bufferPadding;
      
            if (startPTS >= startTime && endPTS <= endTime) {
              return true;
            }
      
            if (endPTS <= startTime) {
              // No need to check the rest of the timeRange as it is in order
              return false;
            }
          }
      
          return false;
        };
      
        _proto.onFragLoaded = function onFragLoaded(event, data) {
          var frag = data.frag,
              part = data.part; // don't track initsegment (for which sn is not a number)
          // don't track frags used for bitrateTest, they're irrelevant.
          // don't track parts for memory efficiency
      
          if (frag.sn === 'initSegment' || frag.bitrateTest || part) {
            return;
          }
      
          var fragKey = getFragmentKey(frag);
          this.fragments[fragKey] = {
            body: frag,
            loaded: data,
            backtrack: null,
            buffered: false,
            range: Object.create(null)
          };
        };
      
        _proto.onBufferAppended = function onBufferAppended(event, data) {
          var _this3 = this;
      
          var frag = data.frag,
              part = data.part,
              timeRanges = data.timeRanges;
      
          if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_1__["PlaylistLevelType"].MAIN) {
            this.activeFragment = frag;
      
            if (part) {
              var activeParts = this.activeParts;
      
              if (!activeParts) {
                this.activeParts = activeParts = [];
              }
      
              activeParts.push(part);
            } else {
              this.activeParts = null;
            }
          } // Store the latest timeRanges loaded in the buffer
      
      
          this.timeRanges = timeRanges;
          Object.keys(timeRanges).forEach(function (elementaryStream) {
            var timeRange = timeRanges[elementaryStream];
      
            _this3.detectEvictedFragments(elementaryStream, timeRange);
      
            if (!part) {
              for (var i = 0; i < timeRange.length; i++) {
                frag.appendedPTS = Math.max(timeRange.end(i), frag.appendedPTS || 0);
              }
            }
          });
        };
      
        _proto.onFragBuffered = function onFragBuffered(event, data) {
          this.detectPartialFragments(data);
        };
      
        _proto.hasFragment = function hasFragment(fragment) {
          var fragKey = getFragmentKey(fragment);
          return !!this.fragments[fragKey];
        };
      
        _proto.removeFragmentsInRange = function removeFragmentsInRange(start, end, playlistType) {
          var _this4 = this;
      
          Object.keys(this.fragments).forEach(function (key) {
            var fragmentEntity = _this4.fragments[key];
      
            if (!fragmentEntity) {
              return;
            }
      
            if (fragmentEntity.buffered) {
              var frag = fragmentEntity.body;
      
              if (frag.type === playlistType && frag.start < end && frag.end > start) {
                _this4.removeFragment(frag);
              }
            }
          });
        };
      
        _proto.removeFragment = function removeFragment(fragment) {
          var fragKey = getFragmentKey(fragment);
          fragment.stats.loaded = 0;
          fragment.clearElementaryStreamInfo();
          delete this.fragments[fragKey];
        };
      
        _proto.removeAllFragments = function removeAllFragments() {
          this.fragments = Object.create(null);
          this.activeFragment = null;
          this.activeParts = null;
        };
      
        return FragmentTracker;
      }();
      
      function isPartial(fragmentEntity) {
        var _fragmentEntity$range, _fragmentEntity$range2;
      
        return fragmentEntity.buffered && (((_fragmentEntity$range = fragmentEntity.range.video) === null || _fragmentEntity$range === void 0 ? void 0 : _fragmentEntity$range.partial) || ((_fragmentEntity$range2 = fragmentEntity.range.audio) === null || _fragmentEntity$range2 === void 0 ? void 0 : _fragmentEntity$range2.partial));
      }
      
      function getFragmentKey(fragment) {
        return fragment.type + "_" + fragment.level + "_" + fragment.urlId + "_" + fragment.sn;
      }
      
      /***/ }),
      
      /***/ "./src/controller/gap-controller.ts":
      /*!******************************************!*\
        !*** ./src/controller/gap-controller.ts ***!
        \******************************************/
      /*! exports provided: STALL_MINIMUM_DURATION_MS, MAX_START_GAP_JUMP, SKIP_BUFFER_HOLE_STEP_SECONDS, SKIP_BUFFER_RANGE_START, default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STALL_MINIMUM_DURATION_MS", function() { return STALL_MINIMUM_DURATION_MS; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MAX_START_GAP_JUMP", function() { return MAX_START_GAP_JUMP; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SKIP_BUFFER_HOLE_STEP_SECONDS", function() { return SKIP_BUFFER_HOLE_STEP_SECONDS; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SKIP_BUFFER_RANGE_START", function() { return SKIP_BUFFER_RANGE_START; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return GapController; });
      /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
      /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
      /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ "./src/events.ts");
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      
      
      
      
      var STALL_MINIMUM_DURATION_MS = 250;
      var MAX_START_GAP_JUMP = 2.0;
      var SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;
      var SKIP_BUFFER_RANGE_START = 0.05;
      
      var GapController = /*#__PURE__*/function () {
        function GapController(config, media, fragmentTracker, hls) {
          this.config = void 0;
          this.media = void 0;
          this.fragmentTracker = void 0;
          this.hls = void 0;
          this.nudgeRetry = 0;
          this.stallReported = false;
          this.stalled = null;
          this.moved = false;
          this.seeking = false;
          this.config = config;
          this.media = media;
          this.fragmentTracker = fragmentTracker;
          this.hls = hls;
        }
      
        var _proto = GapController.prototype;
      
        _proto.destroy = function destroy() {
          // @ts-ignore
          this.hls = this.fragmentTracker = this.media = null;
        }
        /**
         * Checks if the playhead is stuck within a gap, and if so, attempts to free it.
         * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).
         *
         * @param {number} lastCurrentTime Previously read playhead position
         */
        ;
      
        _proto.poll = function poll(lastCurrentTime) {
          var config = this.config,
              media = this.media,
              stalled = this.stalled;
          var currentTime = media.currentTime,
              seeking = media.seeking;
          var seeked = this.seeking && !seeking;
          var beginSeek = !this.seeking && seeking;
          this.seeking = seeking; // The playhead is moving, no-op
      
          if (currentTime !== lastCurrentTime) {
            this.moved = true;
      
            if (stalled !== null) {
              // The playhead is now moving, but was previously stalled
              if (this.stallReported) {
                var _stalledDuration = self.performance.now() - stalled;
      
                _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("playback not stuck anymore @" + currentTime + ", after " + Math.round(_stalledDuration) + "ms");
                this.stallReported = false;
              }
      
              this.stalled = null;
              this.nudgeRetry = 0;
            }
      
            return;
          } // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek
      
      
          if (beginSeek || seeked) {
            this.stalled = null;
          } // The playhead should not be moving
      
      
          if (media.paused || media.ended || media.playbackRate === 0 || !_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__["BufferHelper"].getBuffered(media).length) {
            return;
          }
      
          var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__["BufferHelper"].bufferInfo(media, currentTime, 0);
          var isBuffered = bufferInfo.len > 0;
          var nextStart = bufferInfo.nextStart || 0; // There is no playable buffer (seeked, waiting for buffer)
      
          if (!isBuffered && !nextStart) {
            return;
          }
      
          if (seeking) {
            // Waiting for seeking in a buffered range to complete
            var hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP; // Next buffered range is too far ahead to jump to while still seeking
      
            var noBufferGap = !nextStart || nextStart - currentTime > MAX_START_GAP_JUMP && !this.fragmentTracker.getPartialFragment(currentTime);
      
            if (hasEnoughBuffer || noBufferGap) {
              return;
            } // Reset moved state when seeking to a point in or before a gap
      
      
            this.moved = false;
          } // Skip start gaps if we haven't played, but the last poll detected the start of a stall
          // The addition poll gives the browser a chance to jump the gap for us
      
      
          if (!this.moved && this.stalled !== null) {
            var _level$details;
      
            // Jump start gaps within jump threshold
            var startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime; // When joining a live stream with audio tracks, account for live playlist window sliding by allowing
            // a larger jump over start gaps caused by the audio-stream-controller buffering a start fragment
            // that begins over 1 target duration after the video start position.
      
            var level = this.hls.levels ? this.hls.levels[this.hls.currentLevel] : null;
            var isLive = level === null || level === void 0 ? void 0 : (_level$details = level.details) === null || _level$details === void 0 ? void 0 : _level$details.live;
            var maxStartGapJump = isLive ? level.details.targetduration * 2 : MAX_START_GAP_JUMP;
      
            if (startJump > 0 && startJump <= maxStartGapJump) {
              this._trySkipBufferHole(null);
      
              return;
            }
          } // Start tracking stall time
      
      
          var tnow = self.performance.now();
      
          if (stalled === null) {
            this.stalled = tnow;
            return;
          }
      
          var stalledDuration = tnow - stalled;
      
          if (!seeking && stalledDuration >= STALL_MINIMUM_DURATION_MS) {
            // Report stalling after trying to fix
            this._reportStall(bufferInfo.len);
          }
      
          var bufferedWithHoles = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__["BufferHelper"].bufferInfo(media, currentTime, config.maxBufferHole);
      
          this._tryFixBufferStall(bufferedWithHoles, stalledDuration);
        }
        /**
         * Detects and attempts to fix known buffer stalling issues.
         * @param bufferInfo - The properties of the current buffer.
         * @param stalledDurationMs - The amount of time Hls.js has been stalling for.
         * @private
         */
        ;
      
        _proto._tryFixBufferStall = function _tryFixBufferStall(bufferInfo, stalledDurationMs) {
          var config = this.config,
              fragmentTracker = this.fragmentTracker,
              media = this.media;
          var currentTime = media.currentTime;
          var partial = fragmentTracker.getPartialFragment(currentTime);
      
          if (partial) {
            // Try to skip over the buffer hole caused by a partial fragment
            // This method isn't limited by the size of the gap between buffered ranges
            var targetTime = this._trySkipBufferHole(partial); // we return here in this case, meaning
            // the branch below only executes when we don't handle a partial fragment
      
      
            if (targetTime) {
              return;
            }
          } // if we haven't had to skip over a buffer hole of a partial fragment
          // we may just have to "nudge" the playlist as the browser decoding/rendering engine
          // needs to cross some sort of threshold covering all source-buffers content
          // to start playing properly.
      
      
          if (bufferInfo.len > config.maxBufferHole && stalledDurationMs > config.highBufferWatchdogPeriod * 1000) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('Trying to nudge playhead over buffer-hole'); // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds
            // We only try to jump the hole if it's under the configured size
            // Reset stalled so to rearm watchdog timer
      
            this.stalled = null;
      
            this._tryNudgeBuffer();
          }
        }
        /**
         * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.
         * @param bufferLen - The playhead distance from the end of the current buffer segment.
         * @private
         */
        ;
      
        _proto._reportStall = function _reportStall(bufferLen) {
          var hls = this.hls,
              media = this.media,
              stallReported = this.stallReported;
      
          if (!stallReported) {
            // Report stalled error once
            this.stallReported = true;
            _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("Playback stalling at @" + media.currentTime + " due to low buffer (buffer=" + bufferLen + ")");
            hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, {
              type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
              details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].BUFFER_STALLED_ERROR,
              fatal: false,
              buffer: bufferLen
            });
          }
        }
        /**
         * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments
         * @param partial - The partial fragment found at the current time (where playback is stalling).
         * @private
         */
        ;
      
        _proto._trySkipBufferHole = function _trySkipBufferHole(partial) {
          var config = this.config,
              hls = this.hls,
              media = this.media;
          var currentTime = media.currentTime;
          var lastEndTime = 0; // Check if currentTime is between unbuffered regions of partial fragments
      
          var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__["BufferHelper"].getBuffered(media);
      
          for (var i = 0; i < buffered.length; i++) {
            var startTime = buffered.start(i);
      
            if (currentTime + config.maxBufferHole >= lastEndTime && currentTime < startTime) {
              var targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, media.currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS);
              _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("skipping hole, adjusting currentTime from " + currentTime + " to " + targetTime);
              this.moved = true;
              this.stalled = null;
              media.currentTime = targetTime;
      
              if (partial) {
                hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, {
                  type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
                  details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].BUFFER_SEEK_OVER_HOLE,
                  fatal: false,
                  reason: "fragment loaded with buffer holes, seeking from " + currentTime + " to " + targetTime,
                  frag: partial
                });
              }
      
              return targetTime;
            }
      
            lastEndTime = buffered.end(i);
          }
      
          return 0;
        }
        /**
         * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
         * @private
         */
        ;
      
        _proto._tryNudgeBuffer = function _tryNudgeBuffer() {
          var config = this.config,
              hls = this.hls,
              media = this.media;
          var currentTime = media.currentTime;
          var nudgeRetry = (this.nudgeRetry || 0) + 1;
          this.nudgeRetry = nudgeRetry;
      
          if (nudgeRetry < config.nudgeMaxRetry) {
            var targetTime = currentTime + nudgeRetry * config.nudgeOffset; // playback stalled in buffered area ... let's nudge currentTime to try to overcome this
      
            _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("Nudging 'currentTime' from " + currentTime + " to " + targetTime);
            media.currentTime = targetTime;
            hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, {
              type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
              details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].BUFFER_NUDGE_ON_STALL,
              fatal: false
            });
          } else {
            _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].error("Playhead still not moving while enough data buffered @" + currentTime + " after " + config.nudgeMaxRetry + " nudges");
            hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, {
              type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
              details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].BUFFER_STALLED_ERROR,
              fatal: true
            });
          }
        };
      
        return GapController;
      }();
      
      
      
      /***/ }),
      
      /***/ "./src/controller/id3-track-controller.ts":
      /*!************************************************!*\
        !*** ./src/controller/id3-track-controller.ts ***!
        \************************************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
      /* harmony import */ var _utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/texttrack-utils */ "./src/utils/texttrack-utils.ts");
      /* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
      
      
      
      var MIN_CUE_DURATION = 0.25;
      
      var ID3TrackController = /*#__PURE__*/function () {
        function ID3TrackController(hls) {
          this.hls = void 0;
          this.id3Track = null;
          this.media = null;
          this.hls = hls;
      
          this._registerListeners();
        }
      
        var _proto = ID3TrackController.prototype;
      
        _proto.destroy = function destroy() {
          this._unregisterListeners();
        };
      
        _proto._registerListeners = function _registerListeners() {
          var hls = this.hls;
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this);
        };
      
        _proto._unregisterListeners = function _unregisterListeners() {
          var hls = this.hls;
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this);
        } // Add ID3 metatadata text track.
        ;
      
        _proto.onMediaAttached = function onMediaAttached(event, data) {
          this.media = data.media;
        };
      
        _proto.onMediaDetaching = function onMediaDetaching() {
          if (!this.id3Track) {
            return;
          }
      
          Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__["clearCurrentCues"])(this.id3Track);
          this.id3Track = null;
          this.media = null;
        };
      
        _proto.getID3Track = function getID3Track(textTracks) {
          if (!this.media) {
            return;
          }
      
          for (var i = 0; i < textTracks.length; i++) {
            var textTrack = textTracks[i];
      
            if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {
              // send 'addtrack' when reusing the textTrack for metadata,
              // same as what we do for captions
              Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__["sendAddTrackEvent"])(textTrack, this.media);
              return textTrack;
            }
          }
      
          return this.media.addTextTrack('metadata', 'id3');
        };
      
        _proto.onFragParsingMetadata = function onFragParsingMetadata(event, data) {
          if (!this.media) {
            return;
          }
      
          var fragment = data.frag;
          var samples = data.samples; // create track dynamically
      
          if (!this.id3Track) {
            this.id3Track = this.getID3Track(this.media.textTracks);
            this.id3Track.mode = 'hidden';
          } // Attempt to recreate Safari functionality by creating
          // WebKitDataCue objects when available and store the decoded
          // ID3 data in the value property of the cue
      
      
          var Cue = self.WebKitDataCue || self.VTTCue || self.TextTrackCue;
      
          for (var i = 0; i < samples.length; i++) {
            var frames = _demux_id3__WEBPACK_IMPORTED_MODULE_2__["getID3Frames"](samples[i].data);
      
            if (frames) {
              var startTime = samples[i].pts;
              var endTime = i < samples.length - 1 ? samples[i + 1].pts : fragment.end;
              var timeDiff = endTime - startTime;
      
              if (timeDiff <= 0) {
                endTime = startTime + MIN_CUE_DURATION;
              }
      
              for (var j = 0; j < frames.length; j++) {
                var frame = frames[j]; // Safari doesn't put the timestamp frame in the TextTrack
      
                if (!_demux_id3__WEBPACK_IMPORTED_MODULE_2__["isTimeStampFrame"](frame)) {
                  var cue = new Cue(startTime, endTime, '');
                  cue.value = frame;
                  this.id3Track.addCue(cue);
                }
              }
            }
          }
        };
      
        _proto.onBufferFlushing = function onBufferFlushing(event, _ref) {
          var startOffset = _ref.startOffset,
              endOffset = _ref.endOffset,
              type = _ref.type;
      
          if (!type || type === 'audio') {
            // id3 cues come from parsed audio only remove cues when audio buffer is cleared
            var id3Track = this.id3Track;
      
            if (id3Track) {
              Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__["removeCuesInRange"])(id3Track, startOffset, endOffset);
            }
          }
        };
      
        return ID3TrackController;
      }();
      
      /* harmony default export */ __webpack_exports__["default"] = (ID3TrackController);
      
      /***/ }),
      
      /***/ "./src/controller/latency-controller.ts":
      /*!**********************************************!*\
        !*** ./src/controller/latency-controller.ts ***!
        \**********************************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return LatencyController; });
      /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
      /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
      
      function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
      
      
      
      
      
      var LatencyController = /*#__PURE__*/function () {
        function LatencyController(hls) {
          var _this = this;
      
          this.hls = void 0;
          this.config = void 0;
          this.media = null;
          this.levelDetails = null;
          this.currentTime = 0;
          this.stallCount = 0;
          this._latency = null;
      
          this.timeupdateHandler = function () {
            return _this.timeupdate();
          };
      
          this.hls = hls;
          this.config = hls.config;
          this.registerListeners();
        }
      
        var _proto = LatencyController.prototype;
      
        _proto.destroy = function destroy() {
          this.unregisterListeners();
          this.onMediaDetaching();
          this.levelDetails = null; // @ts-ignore
      
          this.hls = this.timeupdateHandler = null;
        };
      
        _proto.registerListeners = function registerListeners() {
          this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
          this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
          this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
          this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_UPDATED, this.onLevelUpdated, this);
          this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, this.onError, this);
        };
      
        _proto.unregisterListeners = function unregisterListeners() {
          this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHED, this.onMediaAttached);
          this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching);
          this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading);
          this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_UPDATED, this.onLevelUpdated);
          this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, this.onError);
        };
      
        _proto.onMediaAttached = function onMediaAttached(event, data) {
          this.media = data.media;
          this.media.addEventListener('timeupdate', this.timeupdateHandler);
        };
      
        _proto.onMediaDetaching = function onMediaDetaching() {
          if (this.media) {
            this.media.removeEventListener('timeupdate', this.timeupdateHandler);
            this.media = null;
          }
        };
      
        _proto.onManifestLoading = function onManifestLoading() {
          this.levelDetails = null;
          this._latency = null;
          this.stallCount = 0;
        };
      
        _proto.onLevelUpdated = function onLevelUpdated(event, _ref) {
          var details = _ref.details;
          this.levelDetails = details;
      
          if (details.advanced) {
            this.timeupdate();
          }
      
          if (!details.live && this.media) {
            this.media.removeEventListener('timeupdate', this.timeupdateHandler);
          }
        };
      
        _proto.onError = function onError(event, data) {
          if (data.details !== _errors__WEBPACK_IMPORTED_MODULE_0__["ErrorDetails"].BUFFER_STALLED_ERROR) {
            return;
          }
      
          this.stallCount++;
          _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('[playback-rate-controller]: Stall detected, adjusting target latency');
        };
      
        _proto.timeupdate = function timeupdate() {
          var media = this.media,
              levelDetails = this.levelDetails;
      
          if (!media || !levelDetails) {
            return;
          }
      
          this.currentTime = media.currentTime;
          var latency = this.computeLatency();
      
          if (latency === null) {
            return;
          }
      
          this._latency = latency; // Adapt playbackRate to meet target latency in low-latency mode
      
          var _this$config = this.config,
              lowLatencyMode = _this$config.lowLatencyMode,
              maxLiveSyncPlaybackRate = _this$config.maxLiveSyncPlaybackRate;
      
          if (!lowLatencyMode || maxLiveSyncPlaybackRate === 1) {
            return;
          }
      
          var targetLatency = this.targetLatency;
      
          if (targetLatency === null) {
            return;
          }
      
          var distanceFromTarget = latency - targetLatency; // Only adjust playbackRate when within one target duration of targetLatency
          // and more than one second from under-buffering.
          // Playback further than one target duration from target can be considered DVR playback.
      
          var liveMinLatencyDuration = Math.min(this.maxLatency, targetLatency + levelDetails.targetduration);
          var inLiveRange = distanceFromTarget < liveMinLatencyDuration;
      
          if (levelDetails.live && inLiveRange && distanceFromTarget > 0.05 && this.forwardBufferLength > 1) {
            var max = Math.min(2, Math.max(1.0, maxLiveSyncPlaybackRate));
            var rate = Math.round(2 / (1 + Math.exp(-0.75 * distanceFromTarget - this.edgeStalled)) * 20) / 20;
            media.playbackRate = Math.min(max, Math.max(1, rate));
          } else if (media.playbackRate !== 1 && media.playbackRate !== 0) {
            media.playbackRate = 1;
          }
        };
      
        _proto.estimateLiveEdge = function estimateLiveEdge() {
          var levelDetails = this.levelDetails;
      
          if (levelDetails === null) {
            return null;
          }
      
          return levelDetails.edge + levelDetails.age;
        };
      
        _proto.computeLatency = function computeLatency() {
          var liveEdge = this.estimateLiveEdge();
      
          if (liveEdge === null) {
            return null;
          }
      
          return liveEdge - this.currentTime;
        };
      
        _createClass(LatencyController, [{
          key: "latency",
          get: function get() {
            return this._latency || 0;
          }
        }, {
          key: "maxLatency",
          get: function get() {
            var config = this.config,
                levelDetails = this.levelDetails;
      
            if (config.liveMaxLatencyDuration !== undefined) {
              return config.liveMaxLatencyDuration;
            }
      
            return levelDetails ? config.liveMaxLatencyDurationCount * levelDetails.targetduration : 0;
          }
        }, {
          key: "targetLatency",
          get: function get() {
            var levelDetails = this.levelDetails;
      
            if (levelDetails === null) {
              return null;
            }
      
            var holdBack = levelDetails.holdBack,
                partHoldBack = levelDetails.partHoldBack,
                targetduration = levelDetails.targetduration;
            var _this$config2 = this.config,
                liveSyncDuration = _this$config2.liveSyncDuration,
                liveSyncDurationCount = _this$config2.liveSyncDurationCount,
                lowLatencyMode = _this$config2.lowLatencyMode;
            var userConfig = this.hls.userConfig;
            var targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack;
      
            if (userConfig.liveSyncDuration || userConfig.liveSyncDurationCount || targetLatency === 0) {
              targetLatency = liveSyncDuration !== undefined ? liveSyncDuration : liveSyncDurationCount * targetduration;
            }
      
            var maxLiveSyncOnStallIncrease = targetduration;
            var liveSyncOnStallIncrease = 1.0;
            return targetLatency + Math.min(this.stallCount * liveSyncOnStallIncrease, maxLiveSyncOnStallIncrease);
          }
        }, {
          key: "liveSyncPosition",
          get: function get() {
            var liveEdge = this.estimateLiveEdge();
            var targetLatency = this.targetLatency;
            var levelDetails = this.levelDetails;
      
            if (liveEdge === null || targetLatency === null || levelDetails === null) {
              return null;
            }
      
            var edge = levelDetails.edge;
            var syncPosition = liveEdge - targetLatency - this.edgeStalled;
            var min = edge - levelDetails.totalduration;
            var max = edge - (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration);
            return Math.min(Math.max(min, syncPosition), max);
          }
        }, {
          key: "drift",
          get: function get() {
            var levelDetails = this.levelDetails;
      
            if (levelDetails === null) {
              return 1;
            }
      
            return levelDetails.drift;
          }
        }, {
          key: "edgeStalled",
          get: function get() {
            var levelDetails = this.levelDetails;
      
            if (levelDetails === null) {
              return 0;
            }
      
            var maxLevelUpdateAge = (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration) * 3;
            return Math.max(levelDetails.age - maxLevelUpdateAge, 0);
          }
        }, {
          key: "forwardBufferLength",
          get: function get() {
            var media = this.media,
                levelDetails = this.levelDetails;
      
            if (!media || !levelDetails) {
              return 0;
            }
      
            var bufferedRanges = media.buffered.length;
            return bufferedRanges ? media.buffered.end(bufferedRanges - 1) : levelDetails.edge - this.currentTime;
          }
        }]);
      
        return LatencyController;
      }();
      
      
      
      /***/ }),
      
      /***/ "./src/controller/level-controller.ts":
      /*!********************************************!*\
        !*** ./src/controller/level-controller.ts ***!
        \********************************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return LevelController; });
      /* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../types/level */ "./src/types/level.ts");
      /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
      /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
      /* harmony import */ var _utils_codecs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/codecs */ "./src/utils/codecs.ts");
      /* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.ts");
      /* harmony import */ var _base_playlist_controller__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./base-playlist-controller */ "./src/controller/base-playlist-controller.ts");
      /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
      function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
      
      function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
      
      function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
      
      function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
      
      function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
      
      /*
       * Level Controller
       */
      
      
      
      
      
      
      
      var chromeOrFirefox = /chrome|firefox/.test(navigator.userAgent.toLowerCase());
      
      var LevelController = /*#__PURE__*/function (_BasePlaylistControll) {
        _inheritsLoose(LevelController, _BasePlaylistControll);
      
        function LevelController(hls) {
          var _this;
      
          _this = _BasePlaylistControll.call(this, hls, '[level-controller]') || this;
          _this._levels = [];
          _this._firstLevel = -1;
          _this._startLevel = void 0;
          _this.currentLevelIndex = -1;
          _this.manualLevelIndex = -1;
          _this.onParsedComplete = void 0;
      
          _this._registerListeners();
      
          return _this;
        }
      
        var _proto = LevelController.prototype;
      
        _proto._registerListeners = function _registerListeners() {
          var hls = this.hls;
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, this.onManifestLoaded, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, this.onFragLoaded, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, this.onError, this);
        };
      
        _proto._unregisterListeners = function _unregisterListeners() {
          var hls = this.hls;
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, this.onManifestLoaded, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, this.onFragLoaded, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, this.onError, this);
        };
      
        _proto.destroy = function destroy() {
          this._unregisterListeners();
      
          this.manualLevelIndex = -1;
          this._levels.length = 0;
      
          _BasePlaylistControll.prototype.destroy.call(this);
        };
      
        _proto.startLoad = function startLoad() {
          var levels = this._levels; // clean up live level details to force reload them, and reset load errors
      
          levels.forEach(function (level) {
            level.loadError = 0;
          });
      
          _BasePlaylistControll.prototype.startLoad.call(this);
        };
      
        _proto.onManifestLoaded = function onManifestLoaded(event, data) {
          var levels = [];
          var audioTracks = [];
          var subtitleTracks = [];
          var bitrateStart;
          var levelSet = {};
          var levelFromSet;
          var resolutionFound = false;
          var videoCodecFound = false;
          var audioCodecFound = false; // regroup redundant levels together
      
          data.levels.forEach(function (levelParsed) {
            var attributes = levelParsed.attrs;
            resolutionFound = resolutionFound || !!(levelParsed.width && levelParsed.height);
            videoCodecFound = videoCodecFound || !!levelParsed.videoCodec;
            audioCodecFound = audioCodecFound || !!levelParsed.audioCodec; // erase audio codec info if browser does not support mp4a.40.34.
            // demuxer will autodetect codec and fallback to mpeg/audio
      
            if (chromeOrFirefox && levelParsed.audioCodec && levelParsed.audioCodec.indexOf('mp4a.40.34') !== -1) {
              levelParsed.audioCodec = undefined;
            }
      
            var levelKey = levelParsed.bitrate + "-" + levelParsed.attrs.RESOLUTION + "-" + levelParsed.attrs.CODECS;
            levelFromSet = levelSet[levelKey];
      
            if (!levelFromSet) {
              levelFromSet = new _types_level__WEBPACK_IMPORTED_MODULE_0__["Level"](levelParsed);
              levelSet[levelKey] = levelFromSet;
              levels.push(levelFromSet);
            } else {
              levelFromSet.url.push(levelParsed.url);
            }
      
            if (attributes) {
              if (attributes.AUDIO) {
                Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__["addGroupId"])(levelFromSet, 'audio', attributes.AUDIO);
              }
      
              if (attributes.SUBTITLES) {
                Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__["addGroupId"])(levelFromSet, 'text', attributes.SUBTITLES);
              }
            }
          }); // remove audio-only level if we also have levels with video codecs or RESOLUTION signalled
      
          if ((resolutionFound || videoCodecFound) && audioCodecFound) {
            levels = levels.filter(function (_ref) {
              var videoCodec = _ref.videoCodec,
                  width = _ref.width,
                  height = _ref.height;
              return !!videoCodec || !!(width && height);
            });
          } // only keep levels with supported audio/video codecs
      
      
          levels = levels.filter(function (_ref2) {
            var audioCodec = _ref2.audioCodec,
                videoCodec = _ref2.videoCodec;
            return (!audioCodec || Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_3__["isCodecSupportedInMp4"])(audioCodec, 'audio')) && (!videoCodec || Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_3__["isCodecSupportedInMp4"])(videoCodec, 'video'));
          });
      
          if (data.audioTracks) {
            audioTracks = data.audioTracks.filter(function (track) {
              return !track.audioCodec || Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_3__["isCodecSupportedInMp4"])(track.audioCodec, 'audio');
            }); // Assign ids after filtering as array indices by group-id
      
            Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__["assignTrackIdsByGroup"])(audioTracks);
          }
      
          if (data.subtitles) {
            subtitleTracks = data.subtitles;
            Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__["assignTrackIdsByGroup"])(subtitleTracks);
          }
      
          if (levels.length > 0) {
            // start bitrate is the first bitrate of the manifest
            bitrateStart = levels[0].bitrate; // sort level on bitrate
      
            levels.sort(function (a, b) {
              return a.bitrate - b.bitrate;
            });
            this._levels = levels; // find index of first level in sorted levels
      
            for (var i = 0; i < levels.length; i++) {
              if (levels[i].bitrate === bitrateStart) {
                this._firstLevel = i;
                this.log("manifest loaded, " + levels.length + " level(s) found, first bitrate: " + bitrateStart);
                break;
              }
            } // Audio is only alternate if manifest include a URI along with the audio group tag,
            // and this is not an audio-only stream where levels contain audio-only
      
      
            var audioOnly = audioCodecFound && !videoCodecFound;
            var edata = {
              levels: levels,
              audioTracks: audioTracks,
              subtitleTracks: subtitleTracks,
              firstLevel: this._firstLevel,
              stats: data.stats,
              audio: audioCodecFound,
              video: videoCodecFound,
              altAudio: !audioOnly && audioTracks.some(function (t) {
                return !!t.url;
              })
            };
            this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_PARSED, edata); // Initiate loading after all controllers have received MANIFEST_PARSED
      
            if (this.hls.config.autoStartLoad || this.hls.forceStartLoad) {
              this.hls.startLoad(this.hls.config.startPosition);
            }
          } else {
            this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
              type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].MEDIA_ERROR,
              details: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].MANIFEST_INCOMPATIBLE_CODECS_ERROR,
              fatal: true,
              url: data.url,
              reason: 'no level with compatible codecs found in manifest'
            });
          }
        };
      
        _proto.onError = function onError(event, data) {
          _BasePlaylistControll.prototype.onError.call(this, event, data);
      
          if (data.fatal) {
            return;
          } // Switch to redundant level when track fails to load
      
      
          var context = data.context;
          var level = this._levels[this.currentLevelIndex];
      
          if (context && (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK && level.audioGroupIds && context.groupId === level.audioGroupIds[level.urlId] || context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK && level.textGroupIds && context.groupId === level.textGroupIds[level.urlId])) {
            this.redundantFailover(this.currentLevelIndex);
            return;
          }
      
          var levelError = false;
          var levelSwitch = true;
          var levelIndex; // try to recover not fatal errors
      
          switch (data.details) {
            case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].FRAG_LOAD_ERROR:
            case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].FRAG_LOAD_TIMEOUT:
            case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].KEY_LOAD_ERROR:
            case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].KEY_LOAD_TIMEOUT:
              if (data.frag) {
                var _level = this._levels[data.frag.level]; // Set levelIndex when we're out of fragment retries
      
                if (_level) {
                  _level.fragmentError++;
      
                  if (_level.fragmentError > this.hls.config.fragLoadingMaxRetry) {
                    levelIndex = data.frag.level;
                  }
                } else {
                  levelIndex = data.frag.level;
                }
              }
      
              break;
      
            case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_LOAD_ERROR:
            case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_LOAD_TIMEOUT:
              // Do not perform level switch if an error occurred using delivery directives
              // Attempt to reload level without directives first
              if (context) {
                if (context.deliveryDirectives) {
                  levelSwitch = false;
                }
      
                levelIndex = context.level;
              }
      
              levelError = true;
              break;
      
            case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].REMUX_ALLOC_ERROR:
              levelIndex = data.level;
              levelError = true;
              break;
          }
      
          if (levelIndex !== undefined) {
            this.recoverLevel(data, levelIndex, levelError, levelSwitch);
          }
        }
        /**
         * Switch to a redundant stream if any available.
         * If redundant stream is not available, emergency switch down if ABR mode is enabled.
         */
        ;
      
        _proto.recoverLevel = function recoverLevel(errorEvent, levelIndex, levelError, levelSwitch) {
          var errorDetails = errorEvent.details;
          var level = this._levels[levelIndex];
          level.loadError++;
      
          if (levelError) {
            var retrying = this.retryLoadingOrFail(errorEvent);
      
            if (retrying) {
              // boolean used to inform stream controller not to switch back to IDLE on non fatal error
              errorEvent.levelRetry = true;
            } else {
              this.currentLevelIndex = -1;
              return;
            }
          }
      
          if (levelSwitch) {
            var redundantLevels = level.url.length; // Try redundant fail-over until level.loadError reaches redundantLevels
      
            if (redundantLevels > 1 && level.loadError < redundantLevels) {
              errorEvent.levelRetry = true;
              this.redundantFailover(levelIndex);
            } else if (this.manualLevelIndex === -1) {
              // Search for available level in auto level selection mode, cycling from highest to lowest bitrate
              var nextLevel = levelIndex === 0 ? this._levels.length - 1 : levelIndex - 1;
      
              if (this.currentLevelIndex !== nextLevel && this._levels[nextLevel].loadError === 0) {
                this.warn(errorDetails + ": switch to " + nextLevel);
                errorEvent.levelRetry = true;
                this.hls.nextAutoLevel = nextLevel;
              }
            }
          }
        };
      
        _proto.redundantFailover = function redundantFailover(levelIndex) {
          var level = this._levels[levelIndex];
          var redundantLevels = level.url.length;
      
          if (redundantLevels > 1) {
            // Update the url id of all levels so that we stay on the same set of variants when level switching
            var newUrlId = (level.urlId + 1) % redundantLevels;
            this.warn("Switching to redundant URL-id " + newUrlId);
      
            this._levels.forEach(function (level) {
              level.urlId = newUrlId;
            });
      
            this.level = levelIndex;
          }
        } // reset errors on the successful load of a fragment
        ;
      
        _proto.onFragLoaded = function onFragLoaded(event, _ref3) {
          var frag = _ref3.frag;
      
          if (frag !== undefined && frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN) {
            var level = this._levels[frag.level];
      
            if (level !== undefined) {
              level.fragmentError = 0;
              level.loadError = 0;
            }
          }
        };
      
        _proto.onLevelLoaded = function onLevelLoaded(event, data) {
          var _data$deliveryDirecti2;
      
          var level = data.level,
              details = data.details;
          var curLevel = this._levels[level];
      
          if (!curLevel) {
            var _data$deliveryDirecti;
      
            this.warn("Invalid level index " + level);
      
            if ((_data$deliveryDirecti = data.deliveryDirectives) !== null && _data$deliveryDirecti !== void 0 && _data$deliveryDirecti.skip) {
              details.deltaUpdateFailed = true;
            }
      
            return;
          } // only process level loaded events matching with expected level
      
      
          if (level === this.currentLevelIndex) {
            // reset level load error counter on successful level loaded only if there is no issues with fragments
            if (curLevel.fragmentError === 0) {
              curLevel.loadError = 0;
              this.retryCount = 0;
            }
      
            this.playlistLoaded(level, data, curLevel.details);
          } else if ((_data$deliveryDirecti2 = data.deliveryDirectives) !== null && _data$deliveryDirecti2 !== void 0 && _data$deliveryDirecti2.skip) {
            // received a delta playlist update that cannot be merged
            details.deltaUpdateFailed = true;
          }
        };
      
        _proto.onAudioTrackSwitched = function onAudioTrackSwitched(event, data) {
          var currentLevel = this.hls.levels[this.currentLevelIndex];
      
          if (!currentLevel) {
            return;
          }
      
          if (currentLevel.audioGroupIds) {
            var urlId = -1;
            var audioGroupId = this.hls.audioTracks[data.id].groupId;
      
            for (var i = 0; i < currentLevel.audioGroupIds.length; i++) {
              if (currentLevel.audioGroupIds[i] === audioGroupId) {
                urlId = i;
                break;
              }
            }
      
            if (urlId !== currentLevel.urlId) {
              currentLevel.urlId = urlId;
              this.startLoad();
            }
          }
        };
      
        _proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {
          var level = this.currentLevelIndex;
          var currentLevel = this._levels[level];
      
          if (this.canLoad && currentLevel && currentLevel.url.length > 0) {
            var id = currentLevel.urlId;
            var url = currentLevel.url[id];
      
            if (hlsUrlParameters) {
              try {
                url = hlsUrlParameters.addDirectives(url);
              } catch (error) {
                this.warn("Could not construct new URL with HLS Delivery Directives: " + error);
              }
            }
      
            this.log("Attempt loading level index " + level + (hlsUrlParameters ? ' at sn ' + hlsUrlParameters.msn + ' part ' + hlsUrlParameters.part : '') + " with URL-id " + id + " " + url); // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);
            // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);
      
            this.clearTimer();
            this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADING, {
              url: url,
              level: level,
              id: id,
              deliveryDirectives: hlsUrlParameters || null
            });
          }
        };
      
        _proto.removeLevel = function removeLevel(levelIndex, urlId) {
          var filterLevelAndGroupByIdIndex = function filterLevelAndGroupByIdIndex(url, id) {
            return id !== urlId;
          };
      
          var levels = this._levels.filter(function (level, index) {
            if (index !== levelIndex) {
              return true;
            }
      
            if (level.url.length > 1 && urlId !== undefined) {
              level.url = level.url.filter(filterLevelAndGroupByIdIndex);
      
              if (level.audioGroupIds) {
                level.audioGroupIds = level.audioGroupIds.filter(filterLevelAndGroupByIdIndex);
              }
      
              if (level.textGroupIds) {
                level.textGroupIds = level.textGroupIds.filter(filterLevelAndGroupByIdIndex);
              }
      
              level.urlId = 0;
              return true;
            }
      
            return false;
          }).map(function (level, index) {
            var details = level.details;
      
            if (details !== null && details !== void 0 && details.fragments) {
              details.fragments.forEach(function (fragment) {
                fragment.level = index;
              });
            }
      
            return level;
          });
      
          this._levels = levels;
          this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVELS_UPDATED, {
            levels: levels
          });
        };
      
        _createClass(LevelController, [{
          key: "levels",
          get: function get() {
            if (this._levels.length === 0) {
              return null;
            }
      
            return this._levels;
          }
        }, {
          key: "level",
          get: function get() {
            return this.currentLevelIndex;
          },
          set: function set(newLevel) {
            var _levels$newLevel;
      
            var levels = this._levels;
      
            if (levels.length === 0) {
              return;
            }
      
            if (this.currentLevelIndex === newLevel && (_levels$newLevel = levels[newLevel]) !== null && _levels$newLevel !== void 0 && _levels$newLevel.details) {
              return;
            } // check if level idx is valid
      
      
            if (newLevel < 0 || newLevel >= levels.length) {
              // invalid level id given, trigger error
              var fatal = newLevel < 0;
              this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
                type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].OTHER_ERROR,
                details: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_SWITCH_ERROR,
                level: newLevel,
                fatal: fatal,
                reason: 'invalid level idx'
              });
      
              if (fatal) {
                return;
              }
      
              newLevel = Math.min(newLevel, levels.length - 1);
            } // stopping live reloading timer if any
      
      
            this.clearTimer();
            var lastLevelIndex = this.currentLevelIndex;
            var lastLevel = levels[lastLevelIndex];
            var level = levels[newLevel];
            this.log("switching to level " + newLevel + " from " + lastLevelIndex);
            this.currentLevelIndex = newLevel;
      
            var levelSwitchingData = _extends({}, level, {
              level: newLevel,
              maxBitrate: level.maxBitrate,
              uri: level.uri,
              urlId: level.urlId
            }); // @ts-ignore
      
      
            delete levelSwitchingData._urlId;
            this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_SWITCHING, levelSwitchingData); // check if we need to load playlist for this level
      
            var levelDetails = level.details;
      
            if (!levelDetails || levelDetails.live) {
              // level not retrieved yet, or live playlist we need to (re)load it
              var hlsUrlParameters = this.switchParams(level.uri, lastLevel === null || lastLevel === void 0 ? void 0 : lastLevel.details);
              this.loadPlaylist(hlsUrlParameters);
            }
          }
        }, {
          key: "manualLevel",
          get: function get() {
            return this.manualLevelIndex;
          },
          set: function set(newLevel) {
            this.manualLevelIndex = newLevel;
      
            if (this._startLevel === undefined) {
              this._startLevel = newLevel;
            }
      
            if (newLevel !== -1) {
              this.level = newLevel;
            }
          }
        }, {
          key: "firstLevel",
          get: function get() {
            return this._firstLevel;
          },
          set: function set(newLevel) {
            this._firstLevel = newLevel;
          }
        }, {
          key: "startLevel",
          get: function get() {
            // hls.startLevel takes precedence over config.startLevel
            // if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)
            if (this._startLevel === undefined) {
              var configStartLevel = this.hls.config.startLevel;
      
              if (configStartLevel !== undefined) {
                return configStartLevel;
              } else {
                return this._firstLevel;
              }
            } else {
              return this._startLevel;
            }
          },
          set: function set(newLevel) {
            this._startLevel = newLevel;
          }
        }, {
          key: "nextLoadLevel",
          get: function get() {
            if (this.manualLevelIndex !== -1) {
              return this.manualLevelIndex;
            } else {
              return this.hls.nextAutoLevel;
            }
          },
          set: function set(nextLevel) {
            this.level = nextLevel;
      
            if (this.manualLevelIndex === -1) {
              this.hls.nextAutoLevel = nextLevel;
            }
          }
        }]);
      
        return LevelController;
      }(_base_playlist_controller__WEBPACK_IMPORTED_MODULE_5__["default"]);
      
      
      
      /***/ }),
      
      /***/ "./src/controller/level-helper.ts":
      /*!****************************************!*\
        !*** ./src/controller/level-helper.ts ***!
        \****************************************/
      /*! exports provided: addGroupId, assignTrackIdsByGroup, updatePTS, updateFragPTSDTS, mergeDetails, mapPartIntersection, mapFragmentIntersection, adjustSliding, addSliding, computeReloadInterval, getFragmentWithSN, getPartWith */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addGroupId", function() { return addGroupId; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "assignTrackIdsByGroup", function() { return assignTrackIdsByGroup; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updatePTS", function() { return updatePTS; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateFragPTSDTS", function() { return updateFragPTSDTS; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeDetails", function() { return mergeDetails; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mapPartIntersection", function() { return mapPartIntersection; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mapFragmentIntersection", function() { return mapFragmentIntersection; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "adjustSliding", function() { return adjustSliding; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addSliding", function() { return addSliding; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "computeReloadInterval", function() { return computeReloadInterval; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFragmentWithSN", function() { return getFragmentWithSN; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPartWith", function() { return getPartWith; });
      /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      
      
      
      
      
      
      /**
       * @module LevelHelper
       * Providing methods dealing with playlist sliding and drift
       * */
      
      function addGroupId(level, type, id) {
        switch (type) {
          case 'audio':
            if (!level.audioGroupIds) {
              level.audioGroupIds = [];
            }
      
            level.audioGroupIds.push(id);
            break;
      
          case 'text':
            if (!level.textGroupIds) {
              level.textGroupIds = [];
            }
      
            level.textGroupIds.push(id);
            break;
        }
      }
      function assignTrackIdsByGroup(tracks) {
        var groups = {};
        tracks.forEach(function (track) {
          var groupId = track.groupId || '';
          track.id = groups[groupId] = groups[groupId] || 0;
          groups[groupId]++;
        });
      }
      function updatePTS(fragments, fromIdx, toIdx) {
        var fragFrom = fragments[fromIdx];
        var fragTo = fragments[toIdx];
        updateFromToPTS(fragFrom, fragTo);
      }
      
      function updateFromToPTS(fragFrom, fragTo) {
        var fragToPTS = fragTo.startPTS; // if we know startPTS[toIdx]
      
        if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(fragToPTS)) {
          // update fragment duration.
          // it helps to fix drifts between playlist reported duration and fragment real duration
          var duration = 0;
          var frag;
      
          if (fragTo.sn > fragFrom.sn) {
            duration = fragToPTS - fragFrom.start;
            frag = fragFrom;
          } else {
            duration = fragFrom.start - fragToPTS;
            frag = fragTo;
          } // TODO? Drift can go either way, or the playlist could be completely accurate
          // console.assert(duration > 0,
          //   `duration of ${duration} computed for frag ${frag.sn}, level ${frag.level}, there should be some duration drift between playlist and fragment!`);
      
      
          if (frag.duration !== duration) {
            frag.duration = duration;
          } // we dont know startPTS[toIdx]
      
        } else if (fragTo.sn > fragFrom.sn) {
          var contiguous = fragFrom.cc === fragTo.cc; // TODO: With part-loading end/durations we need to confirm the whole fragment is loaded before using (or setting) minEndPTS
      
          if (contiguous && fragFrom.minEndPTS) {
            fragTo.start = fragFrom.start + (fragFrom.minEndPTS - fragFrom.start);
          } else {
            fragTo.start = fragFrom.start + fragFrom.duration;
          }
        } else {
          fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);
        }
      }
      
      function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
        var parsedMediaDuration = endPTS - startPTS;
      
        if (parsedMediaDuration <= 0) {
          _utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].warn('Fragment should have a positive duration', frag);
          endPTS = startPTS + frag.duration;
          endDTS = startDTS + frag.duration;
        }
      
        var maxStartPTS = startPTS;
        var minEndPTS = endPTS;
        var fragStartPts = frag.startPTS;
        var fragEndPts = frag.endPTS;
      
        if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(fragStartPts)) {
          // delta PTS between audio and video
          var deltaPTS = Math.abs(fragStartPts - startPTS);
      
          if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.deltaPTS)) {
            frag.deltaPTS = deltaPTS;
          } else {
            frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
          }
      
          maxStartPTS = Math.max(startPTS, fragStartPts);
          startPTS = Math.min(startPTS, fragStartPts);
          startDTS = Math.min(startDTS, frag.startDTS);
          minEndPTS = Math.min(endPTS, fragEndPts);
          endPTS = Math.max(endPTS, fragEndPts);
          endDTS = Math.max(endDTS, frag.endDTS);
        }
      
        frag.duration = endPTS - startPTS;
        var drift = startPTS - frag.start;
        frag.appendedPTS = endPTS;
        frag.start = frag.startPTS = startPTS;
        frag.maxStartPTS = maxStartPTS;
        frag.startDTS = startDTS;
        frag.endPTS = endPTS;
        frag.minEndPTS = minEndPTS;
        frag.endDTS = endDTS;
        var sn = frag.sn; // 'initSegment'
        // exit if sn out of range
      
        if (!details || sn < details.startSN || sn > details.endSN) {
          return 0;
        }
      
        var i;
        var fragIdx = sn - details.startSN;
        var fragments = details.fragments; // update frag reference in fragments array
        // rationale is that fragments array might not contain this frag object.
        // this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()
        // if we don't update frag, we won't be able to propagate PTS info on the playlist
        // resulting in invalid sliding computation
      
        fragments[fragIdx] = frag; // adjust fragment PTS/duration from seqnum-1 to frag 0
      
        for (i = fragIdx; i > 0; i--) {
          updateFromToPTS(fragments[i], fragments[i - 1]);
        } // adjust fragment PTS/duration from seqnum to last frag
      
      
        for (i = fragIdx; i < fragments.length - 1; i++) {
          updateFromToPTS(fragments[i], fragments[i + 1]);
        }
      
        if (details.fragmentHint) {
          updateFromToPTS(fragments[fragments.length - 1], details.fragmentHint);
        }
      
        details.PTSKnown = details.alignedSliding = true;
        return drift;
      }
      function mergeDetails(oldDetails, newDetails) {
        // Track the last initSegment processed. Initialize it to the last one on the timeline.
        var currentInitSegment = null;
        var oldFragments = oldDetails.fragments;
      
        for (var i = oldFragments.length - 1; i >= 0; i--) {
          var oldInit = oldFragments[i].initSegment;
      
          if (oldInit) {
            currentInitSegment = oldInit;
            break;
          }
        }
      
        if (oldDetails.fragmentHint) {
          // prevent PTS and duration from being adjusted on the next hint
          delete oldDetails.fragmentHint.endPTS;
        } // check if old/new playlists have fragments in common
        // loop through overlapping SN and update startPTS , cc, and duration if any found
      
      
        var ccOffset = 0;
        var PTSFrag;
        mapFragmentIntersection(oldDetails, newDetails, function (oldFrag, newFrag) {
          if (oldFrag.relurl) {
            // Do not compare CC if the old fragment has no url. This is a level.fragmentHint used by LL-HLS parts.
            // It maybe be off by 1 if it was created before any parts or discontinuity tags were appended to the end
            // of the playlist.
            ccOffset = oldFrag.cc - newFrag.cc;
          }
      
          if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(oldFrag.startPTS) && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(oldFrag.endPTS)) {
            newFrag.start = newFrag.startPTS = oldFrag.startPTS;
            newFrag.startDTS = oldFrag.startDTS;
            newFrag.appendedPTS = oldFrag.appendedPTS;
            newFrag.maxStartPTS = oldFrag.maxStartPTS;
            newFrag.endPTS = oldFrag.endPTS;
            newFrag.endDTS = oldFrag.endDTS;
            newFrag.minEndPTS = oldFrag.minEndPTS;
            newFrag.duration = oldFrag.endPTS - oldFrag.startPTS;
      
            if (newFrag.duration) {
              PTSFrag = newFrag;
            } // PTS is known when any segment has startPTS and endPTS
      
      
            newDetails.PTSKnown = newDetails.alignedSliding = true;
          }
      
          newFrag.elementaryStreams = oldFrag.elementaryStreams;
          newFrag.loader = oldFrag.loader;
          newFrag.stats = oldFrag.stats;
          newFrag.urlId = oldFrag.urlId;
      
          if (oldFrag.initSegment) {
            newFrag.initSegment = oldFrag.initSegment;
            currentInitSegment = oldFrag.initSegment;
          }
        });
      
        if (currentInitSegment) {
          var fragmentsToCheck = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;
          fragmentsToCheck.forEach(function (frag) {
            var _currentInitSegment;
      
            if (!frag.initSegment || frag.initSegment.relurl === ((_currentInitSegment = currentInitSegment) === null || _currentInitSegment === void 0 ? void 0 : _currentInitSegment.relurl)) {
              frag.initSegment = currentInitSegment;
            }
          });
        }
      
        if (newDetails.skippedSegments) {
          newDetails.deltaUpdateFailed = newDetails.fragments.some(function (frag) {
            return !frag;
          });
      
          if (newDetails.deltaUpdateFailed) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].warn('[level-helper] Previous playlist missing segments skipped in delta playlist');
      
            for (var _i = newDetails.skippedSegments; _i--;) {
              newDetails.fragments.shift();
            }
      
            newDetails.startSN = newDetails.fragments[0].sn;
            newDetails.startCC = newDetails.fragments[0].cc;
          }
        }
      
        var newFragments = newDetails.fragments;
      
        if (ccOffset) {
          _utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].warn('discontinuity sliding from playlist, take drift into account');
      
          for (var _i2 = 0; _i2 < newFragments.length; _i2++) {
            newFragments[_i2].cc += ccOffset;
          }
        }
      
        if (newDetails.skippedSegments) {
          newDetails.startCC = newDetails.fragments[0].cc;
        } // Merge parts
      
      
        mapPartIntersection(oldDetails.partList, newDetails.partList, function (oldPart, newPart) {
          newPart.elementaryStreams = oldPart.elementaryStreams;
          newPart.stats = oldPart.stats;
        }); // if at least one fragment contains PTS info, recompute PTS information for all fragments
      
        if (PTSFrag) {
          updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
        } else {
          // ensure that delta is within oldFragments range
          // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])
          // in that case we also need to adjust start offset of all fragments
          adjustSliding(oldDetails, newDetails);
        }
      
        if (newFragments.length) {
          newDetails.totalduration = newDetails.edge - newFragments[0].start;
        }
      
        newDetails.driftStartTime = oldDetails.driftStartTime;
        newDetails.driftStart = oldDetails.driftStart;
        var advancedDateTime = newDetails.advancedDateTime;
      
        if (newDetails.advanced && advancedDateTime) {
          var edge = newDetails.edge;
      
          if (!newDetails.driftStart) {
            newDetails.driftStartTime = advancedDateTime;
            newDetails.driftStart = edge;
          }
      
          newDetails.driftEndTime = advancedDateTime;
          newDetails.driftEnd = edge;
        } else {
          newDetails.driftEndTime = oldDetails.driftEndTime;
          newDetails.driftEnd = oldDetails.driftEnd;
          newDetails.advancedDateTime = oldDetails.advancedDateTime;
        }
      }
      function mapPartIntersection(oldParts, newParts, intersectionFn) {
        if (oldParts && newParts) {
          var delta = 0;
      
          for (var i = 0, len = oldParts.length; i <= len; i++) {
            var _oldPart = oldParts[i];
            var _newPart = newParts[i + delta];
      
            if (_oldPart && _newPart && _oldPart.index === _newPart.index && _oldPart.fragment.sn === _newPart.fragment.sn) {
              intersectionFn(_oldPart, _newPart);
            } else {
              delta--;
            }
          }
        }
      }
      function mapFragmentIntersection(oldDetails, newDetails, intersectionFn) {
        var skippedSegments = newDetails.skippedSegments;
        var start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN;
        var end = (oldDetails.fragmentHint ? 1 : 0) + (skippedSegments ? newDetails.endSN : Math.min(oldDetails.endSN, newDetails.endSN)) - newDetails.startSN;
        var delta = newDetails.startSN - oldDetails.startSN;
        var newFrags = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;
        var oldFrags = oldDetails.fragmentHint ? oldDetails.fragments.concat(oldDetails.fragmentHint) : oldDetails.fragments;
      
        for (var i = start; i <= end; i++) {
          var _oldFrag = oldFrags[delta + i];
          var _newFrag = newFrags[i];
      
          if (skippedSegments && !_newFrag && i < skippedSegments) {
            // Fill in skipped segments in delta playlist
            _newFrag = newDetails.fragments[i] = _oldFrag;
          }
      
          if (_oldFrag && _newFrag) {
            intersectionFn(_oldFrag, _newFrag);
          }
        }
      }
      function adjustSliding(oldDetails, newDetails) {
        var delta = newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN;
        var oldFragments = oldDetails.fragments;
      
        if (delta < 0 || delta >= oldFragments.length) {
          return;
        }
      
        addSliding(newDetails, oldFragments[delta].start);
      }
      function addSliding(details, start) {
        if (start) {
          var fragments = details.fragments;
      
          for (var i = details.skippedSegments; i < fragments.length; i++) {
            fragments[i].start += start;
          }
      
          if (details.fragmentHint) {
            details.fragmentHint.start += start;
          }
        }
      }
      function computeReloadInterval(newDetails, stats) {
        var reloadInterval = 1000 * newDetails.levelTargetDuration;
        var reloadIntervalAfterMiss = reloadInterval / 2;
        var timeSinceLastModified = newDetails.age;
        var useLastModified = timeSinceLastModified > 0 && timeSinceLastModified < reloadInterval * 3;
        var roundTrip = stats.loading.end - stats.loading.start;
        var estimatedTimeUntilUpdate;
        var availabilityDelay = newDetails.availabilityDelay; // let estimate = 'average';
      
        if (newDetails.updated === false) {
          if (useLastModified) {
            // estimate = 'miss round trip';
            // We should have had a hit so try again in the time it takes to get a response,
            // but no less than 1/3 second.
            var minRetry = 333 * newDetails.misses;
            estimatedTimeUntilUpdate = Math.max(Math.min(reloadIntervalAfterMiss, roundTrip * 2), minRetry);
            newDetails.availabilityDelay = (newDetails.availabilityDelay || 0) + estimatedTimeUntilUpdate;
          } else {
            // estimate = 'miss half average';
            // follow HLS Spec, If the client reloads a Playlist file and finds that it has not
            // changed then it MUST wait for a period of one-half the target
            // duration before retrying.
            estimatedTimeUntilUpdate = reloadIntervalAfterMiss;
          }
        } else if (useLastModified) {
          // estimate = 'next modified date';
          // Get the closest we've been to timeSinceLastModified on update
          availabilityDelay = Math.min(availabilityDelay || reloadInterval / 2, timeSinceLastModified);
          newDetails.availabilityDelay = availabilityDelay;
          estimatedTimeUntilUpdate = availabilityDelay + reloadInterval - timeSinceLastModified;
        } else {
          estimatedTimeUntilUpdate = reloadInterval - roundTrip;
        } // console.log(`[computeReloadInterval] live reload ${newDetails.updated ? 'REFRESHED' : 'MISSED'}`,
        //   '\n  method', estimate,
        //   '\n  estimated time until update =>', estimatedTimeUntilUpdate,
        //   '\n  average target duration', reloadInterval,
        //   '\n  time since modified', timeSinceLastModified,
        //   '\n  time round trip', roundTrip,
        //   '\n  availability delay', availabilityDelay);
      
      
        return Math.round(estimatedTimeUntilUpdate);
      }
      function getFragmentWithSN(level, sn, fragCurrent) {
        if (!level || !level.details) {
          return null;
        }
      
        var levelDetails = level.details;
        var fragment = levelDetails.fragments[sn - levelDetails.startSN];
      
        if (fragment) {
          return fragment;
        }
      
        fragment = levelDetails.fragmentHint;
      
        if (fragment && fragment.sn === sn) {
          return fragment;
        }
      
        if (sn < levelDetails.startSN && fragCurrent && fragCurrent.sn === sn) {
          return fragCurrent;
        }
      
        return null;
      }
      function getPartWith(level, sn, partIndex) {
        if (!level || !level.details) {
          return null;
        }
      
        var partList = level.details.partList;
      
        if (partList) {
          for (var i = partList.length; i--;) {
            var part = partList[i];
      
            if (part.index === partIndex && part.fragment.sn === sn) {
              return part;
            }
          }
        }
      
        return null;
      }
      
      /***/ }),
      
      /***/ "./src/controller/stream-controller.ts":
      /*!*********************************************!*\
        !*** ./src/controller/stream-controller.ts ***!
        \*********************************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return StreamController; });
      /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
      /* harmony import */ var _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./base-stream-controller */ "./src/controller/base-stream-controller.ts");
      /* harmony import */ var _is_supported__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../is-supported */ "./src/is-supported.ts");
      /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../events */ "./src/events.ts");
      /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
      /* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.ts");
      /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
      /* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts");
      /* harmony import */ var _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../demux/transmuxer-interface */ "./src/demux/transmuxer-interface.ts");
      /* harmony import */ var _types_transmuxer__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../types/transmuxer */ "./src/types/transmuxer.ts");
      /* harmony import */ var _gap_controller__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./gap-controller */ "./src/controller/gap-controller.ts");
      /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      
      
      
      function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
      
      function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
      
      function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
      
      function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
      
      
      
      
      
      
      
      
      
      
      
      
      
      var TICK_INTERVAL = 100; // how often to tick in ms
      
      var StreamController = /*#__PURE__*/function (_BaseStreamController) {
        _inheritsLoose(StreamController, _BaseStreamController);
      
        function StreamController(hls, fragmentTracker) {
          var _this;
      
          _this = _BaseStreamController.call(this, hls, fragmentTracker, '[stream-controller]') || this;
          _this.audioCodecSwap = false;
          _this.gapController = null;
          _this.level = -1;
          _this._forceStartLoad = false;
          _this.altAudio = false;
          _this.audioOnly = false;
          _this.fragPlaying = null;
          _this.onvplaying = null;
          _this.onvseeked = null;
          _this.fragLastKbps = 0;
          _this.stalled = false;
          _this.couldBacktrack = false;
          _this.audioCodecSwitch = false;
          _this.videoBuffer = null;
      
          _this._registerListeners();
      
          return _this;
        }
      
        var _proto = StreamController.prototype;
      
        _proto._registerListeners = function _registerListeners() {
          var hls = this.hls;
          hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, this.onError, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_CREATED, this.onBufferCreated, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_FLUSHED, this.onBufferFlushed, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVELS_UPDATED, this.onLevelsUpdated, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
        };
      
        _proto._unregisterListeners = function _unregisterListeners() {
          var hls = this.hls;
          hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, this.onError, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_CREATED, this.onBufferCreated, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_FLUSHED, this.onBufferFlushed, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVELS_UPDATED, this.onLevelsUpdated, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
        };
      
        _proto.onHandlerDestroying = function onHandlerDestroying() {
          this._unregisterListeners();
      
          this.onMediaDetaching();
        };
      
        _proto.startLoad = function startLoad(startPosition) {
          if (this.levels) {
            var lastCurrentTime = this.lastCurrentTime,
                hls = this.hls;
            this.stopLoad();
            this.setInterval(TICK_INTERVAL);
            this.level = -1;
            this.fragLoadError = 0;
      
            if (!this.startFragRequested) {
              // determine load level
              var startLevel = hls.startLevel;
      
              if (startLevel === -1) {
                if (hls.config.testBandwidth) {
                  // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
                  startLevel = 0;
                  this.bitrateTest = true;
                } else {
                  startLevel = hls.nextAutoLevel;
                }
              } // set new level to playlist loader : this will trigger start level load
              // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded
      
      
              this.level = hls.nextLoadLevel = startLevel;
              this.loadedmetadata = false;
            } // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime
      
      
            if (lastCurrentTime > 0 && startPosition === -1) {
              this.log("Override startPosition with lastCurrentTime @" + lastCurrentTime.toFixed(3));
              startPosition = lastCurrentTime;
            }
      
            this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
            this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
            this.tick();
          } else {
            this._forceStartLoad = true;
            this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].STOPPED;
          }
        };
      
        _proto.stopLoad = function stopLoad() {
          this._forceStartLoad = false;
      
          _BaseStreamController.prototype.stopLoad.call(this);
        };
      
        _proto.doTick = function doTick() {
          switch (this.state) {
            case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE:
              this.doTickIdle();
              break;
      
            case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL:
              {
                var _levels$level;
      
                var levels = this.levels,
                    level = this.level;
                var details = levels === null || levels === void 0 ? void 0 : (_levels$level = levels[level]) === null || _levels$level === void 0 ? void 0 : _levels$level.details;
      
                if (details && (!details.live || this.levelLastLoaded === this.level)) {
                  if (this.waitForCdnTuneIn(details)) {
                    break;
                  }
      
                  this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
                  break;
                }
      
                break;
              }
      
            case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING_WAITING_RETRY:
              {
                var _this$media;
      
                var now = self.performance.now();
                var retryDate = this.retryDate; // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
      
                if (!retryDate || now >= retryDate || (_this$media = this.media) !== null && _this$media !== void 0 && _this$media.seeking) {
                  this.log('retryDate reached, switch back to IDLE state');
                  this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
                }
              }
              break;
      
            default:
              break;
          } // check buffer
          // check/update current fragment
      
      
          this.onTickEnd();
        };
      
        _proto.onTickEnd = function onTickEnd() {
          _BaseStreamController.prototype.onTickEnd.call(this);
      
          this.checkBuffer();
          this.checkFragmentChanged();
        };
      
        _proto.doTickIdle = function doTickIdle() {
          var _frag$decryptdata, _frag$decryptdata2;
      
          var hls = this.hls,
              levelLastLoaded = this.levelLastLoaded,
              levels = this.levels,
              media = this.media;
          var config = hls.config,
              level = hls.nextLoadLevel; // if start level not parsed yet OR
          // if video not attached AND start fragment already requested OR start frag prefetch not enabled
          // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment
      
          if (levelLastLoaded === null || !media && (this.startFragRequested || !config.startFragPrefetch)) {
            return;
          } // If the "main" level is audio-only but we are loading an alternate track in the same group, do not load anything
      
      
          if (this.altAudio && this.audioOnly) {
            return;
          }
      
          if (!levels || !levels[level]) {
            return;
          }
      
          var levelInfo = levels[level]; // if buffer length is less than maxBufLen try to load a new fragment
          // set next load level : this will trigger a playlist load if needed
      
          this.level = hls.nextLoadLevel = level;
          var levelDetails = levelInfo.details; // if level info not retrieved yet, switch state and wait for level retrieval
          // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load
          // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)
      
          if (!levelDetails || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL || levelDetails.live && this.levelLastLoaded !== level) {
            this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL;
            return;
          }
      
          var bufferInfo = this.getFwdBufferInfo(this.mediaBuffer ? this.mediaBuffer : media, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN);
      
          if (bufferInfo === null) {
            return;
          }
      
          var bufferLen = bufferInfo.len; // compute max Buffer Length that we could get from this load level, based on level bitrate. don't buffer more than 60 MB and more than 30s
      
          var maxBufLen = this.getMaxBufferLength(levelInfo.maxBitrate); // Stay idle if we are still with buffer margins
      
          if (bufferLen >= maxBufLen) {
            return;
          }
      
          if (this._streamEnded(bufferInfo, levelDetails)) {
            var data = {};
      
            if (this.altAudio) {
              data.type = 'video';
            }
      
            this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_EOS, data);
            this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ENDED;
            return;
          }
      
          var targetBufferTime = bufferInfo.end;
          var frag = this.getNextFragment(targetBufferTime, levelDetails); // Avoid backtracking after seeking or switching by loading an earlier segment in streams that could backtrack
      
          if (this.couldBacktrack && !this.fragPrevious && frag && frag.sn !== 'initSegment') {
            var fragIdx = frag.sn - levelDetails.startSN;
      
            if (fragIdx > 1) {
              frag = levelDetails.fragments[fragIdx - 1];
              this.fragmentTracker.removeFragment(frag);
            }
          } // Avoid loop loading by using nextLoadPosition set for backtracking
      
      
          if (frag && this.fragmentTracker.getState(frag) === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].OK && this.nextLoadPosition > targetBufferTime) {
            // Cleanup the fragment tracker before trying to find the next unbuffered fragment
            var type = this.audioOnly && !this.altAudio ? _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO : _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].VIDEO;
            this.afterBufferFlushed(media, type, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN);
            frag = this.getNextFragment(this.nextLoadPosition, levelDetails);
          }
      
          if (!frag) {
            return;
          }
      
          if (frag.initSegment && !frag.initSegment.data && !this.bitrateTest) {
            frag = frag.initSegment;
          } // We want to load the key if we're dealing with an identity key, because we will decrypt
          // this content using the key we fetch. Other keys will be handled by the DRM CDM via EME.
      
      
          if (((_frag$decryptdata = frag.decryptdata) === null || _frag$decryptdata === void 0 ? void 0 : _frag$decryptdata.keyFormat) === 'identity' && !((_frag$decryptdata2 = frag.decryptdata) !== null && _frag$decryptdata2 !== void 0 && _frag$decryptdata2.key)) {
            this.loadKey(frag, levelDetails);
          } else {
            this.loadFragment(frag, levelDetails, targetBufferTime);
          }
        };
      
        _proto.loadFragment = function loadFragment(frag, levelDetails, targetBufferTime) {
          var _this$media2;
      
          // Check if fragment is not loaded
          var fragState = this.fragmentTracker.getState(frag);
          this.fragCurrent = frag; // Use data from loaded backtracked fragment if available
      
          if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].BACKTRACKED) {
            var data = this.fragmentTracker.getBacktrackData(frag);
      
            if (data) {
              this._handleFragmentLoadProgress(data);
      
              this._handleFragmentLoadComplete(data);
      
              return;
            } else {
              fragState = _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].NOT_LOADED;
            }
          }
      
          if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].NOT_LOADED || fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].PARTIAL) {
            if (frag.sn === 'initSegment') {
              this._loadInitSegment(frag);
            } else if (this.bitrateTest) {
              frag.bitrateTest = true;
              this.log("Fragment " + frag.sn + " of level " + frag.level + " is being downloaded to test bitrate and will not be buffered");
      
              this._loadBitrateTestFrag(frag);
            } else {
              this.startFragRequested = true;
      
              _BaseStreamController.prototype.loadFragment.call(this, frag, levelDetails, targetBufferTime);
            }
          } else if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].APPENDING) {
            // Lower the buffer size and try again
            if (this.reduceMaxBufferLength(frag.duration)) {
              this.fragmentTracker.removeFragment(frag);
            }
          } else if (((_this$media2 = this.media) === null || _this$media2 === void 0 ? void 0 : _this$media2.buffered.length) === 0) {
            // Stop gap for bad tracker / buffer flush behavior
            this.fragmentTracker.removeAllFragments();
          }
        };
      
        _proto.getAppendedFrag = function getAppendedFrag(position) {
          var fragOrPart = this.fragmentTracker.getAppendedFrag(position, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN);
      
          if (fragOrPart && 'fragment' in fragOrPart) {
            return fragOrPart.fragment;
          }
      
          return fragOrPart;
        };
      
        _proto.getBufferedFrag = function getBufferedFrag(position) {
          return this.fragmentTracker.getBufferedFrag(position, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN);
        };
      
        _proto.followingBufferedFrag = function followingBufferedFrag(frag) {
          if (frag) {
            // try to get range of next fragment (500ms after this range)
            return this.getBufferedFrag(frag.end + 0.5);
          }
      
          return null;
        }
        /*
          on immediate level switch :
           - pause playback if playing
           - cancel any pending load request
           - and trigger a buffer flush
        */
        ;
      
        _proto.immediateLevelSwitch = function immediateLevelSwitch() {
          this.abortCurrentFrag();
          this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
        }
        /**
         * try to switch ASAP without breaking video playback:
         * in order to ensure smooth but quick level switching,
         * we need to find the next flushable buffer range
         * we should take into account new segment fetch time
         */
        ;
      
        _proto.nextLevelSwitch = function nextLevelSwitch() {
          var levels = this.levels,
              media = this.media; // ensure that media is defined and that metadata are available (to retrieve currentTime)
      
          if (media !== null && media !== void 0 && media.readyState) {
            var fetchdelay;
            var fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
      
            if (fragPlayingCurrent && fragPlayingCurrent.start > 1) {
              // flush buffer preceding current fragment (flush until current fragment start offset)
              // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...
              this.flushMainBuffer(0, fragPlayingCurrent.start - 1);
            }
      
            if (!media.paused && levels) {
              // add a safety delay of 1s
              var nextLevelId = this.hls.nextLoadLevel;
              var nextLevel = levels[nextLevelId];
              var fragLastKbps = this.fragLastKbps;
      
              if (fragLastKbps && this.fragCurrent) {
                fetchdelay = this.fragCurrent.duration * nextLevel.maxBitrate / (1000 * fragLastKbps) + 1;
              } else {
                fetchdelay = 0;
              }
            } else {
              fetchdelay = 0;
            } // this.log('fetchdelay:'+fetchdelay);
            // find buffer range that will be reached once new fragment will be fetched
      
      
            var bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
      
            if (bufferedFrag) {
              // we can flush buffer range following this one without stalling playback
              var nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);
      
              if (nextBufferedFrag) {
                // if we are here, we can also cancel any loading/demuxing in progress, as they are useless
                this.abortCurrentFrag(); // start flush position is in next buffered frag. Leave some padding for non-independent segments and smoother playback.
      
                var maxStart = nextBufferedFrag.maxStartPTS ? nextBufferedFrag.maxStartPTS : nextBufferedFrag.start;
                var fragDuration = nextBufferedFrag.duration;
                var startPts = Math.max(bufferedFrag.end, maxStart + Math.min(Math.max(fragDuration - this.config.maxFragLookUpTolerance, fragDuration * 0.5), fragDuration * 0.75));
                this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);
              }
            }
          }
        };
      
        _proto.abortCurrentFrag = function abortCurrentFrag() {
          var fragCurrent = this.fragCurrent;
          this.fragCurrent = null;
      
          if (fragCurrent !== null && fragCurrent !== void 0 && fragCurrent.loader) {
            fragCurrent.loader.abort();
          }
      
          if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].KEY_LOADING) {
            this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
          }
      
          this.nextLoadPosition = this.getLoadPosition();
        };
      
        _proto.flushMainBuffer = function flushMainBuffer(startOffset, endOffset) {
          _BaseStreamController.prototype.flushMainBuffer.call(this, startOffset, endOffset, this.altAudio ? 'video' : null);
        };
      
        _proto.onMediaAttached = function onMediaAttached(event, data) {
          _BaseStreamController.prototype.onMediaAttached.call(this, event, data);
      
          var media = data.media;
          this.onvplaying = this.onMediaPlaying.bind(this);
          this.onvseeked = this.onMediaSeeked.bind(this);
          media.addEventListener('playing', this.onvplaying);
          media.addEventListener('seeked', this.onvseeked);
          this.gapController = new _gap_controller__WEBPACK_IMPORTED_MODULE_10__["default"](this.config, media, this.fragmentTracker, this.hls);
        };
      
        _proto.onMediaDetaching = function onMediaDetaching() {
          var media = this.media;
      
          if (media) {
            media.removeEventListener('playing', this.onvplaying);
            media.removeEventListener('seeked', this.onvseeked);
            this.onvplaying = this.onvseeked = null;
            this.videoBuffer = null;
          }
      
          this.fragPlaying = null;
      
          if (this.gapController) {
            this.gapController.destroy();
            this.gapController = null;
          }
      
          _BaseStreamController.prototype.onMediaDetaching.call(this);
        };
      
        _proto.onMediaPlaying = function onMediaPlaying() {
          // tick to speed up FRAG_CHANGED triggering
          this.tick();
        };
      
        _proto.onMediaSeeked = function onMediaSeeked() {
          var media = this.media;
          var currentTime = media ? media.currentTime : null;
      
          if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(currentTime)) {
            this.log("Media seeked to " + currentTime.toFixed(3));
          } // tick to speed up FRAG_CHANGED triggering
      
      
          this.tick();
        };
      
        _proto.onManifestLoading = function onManifestLoading() {
          // reset buffer on manifest loading
          this.log('Trigger BUFFER_RESET');
          this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_RESET, undefined);
          this.fragmentTracker.removeAllFragments();
          this.couldBacktrack = this.stalled = false;
          this.startPosition = this.lastCurrentTime = 0;
          this.fragPlaying = null;
        };
      
        _proto.onManifestParsed = function onManifestParsed(event, data) {
          var aac = false;
          var heaac = false;
          var codec;
          data.levels.forEach(function (level) {
            // detect if we have different kind of audio codecs used amongst playlists
            codec = level.audioCodec;
      
            if (codec) {
              if (codec.indexOf('mp4a.40.2') !== -1) {
                aac = true;
              }
      
              if (codec.indexOf('mp4a.40.5') !== -1) {
                heaac = true;
              }
            }
          });
          this.audioCodecSwitch = aac && heaac && !Object(_is_supported__WEBPACK_IMPORTED_MODULE_2__["changeTypeSupported"])();
      
          if (this.audioCodecSwitch) {
            this.log('Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');
          }
      
          this.levels = data.levels;
          this.startFragRequested = false;
        };
      
        _proto.onLevelLoading = function onLevelLoading(event, data) {
          var levels = this.levels;
      
          if (!levels || this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE) {
            return;
          }
      
          var level = levels[data.level];
      
          if (!level.details || level.details.live && this.levelLastLoaded !== data.level || this.waitForCdnTuneIn(level.details)) {
            this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL;
          }
        };
      
        _proto.onLevelLoaded = function onLevelLoaded(event, data) {
          var _curLevel$details;
      
          var levels = this.levels;
          var newLevelId = data.level;
          var newDetails = data.details;
          var duration = newDetails.totalduration;
      
          if (!levels) {
            this.warn("Levels were reset while loading level " + newLevelId);
            return;
          }
      
          this.log("Level " + newLevelId + " loaded [" + newDetails.startSN + "," + newDetails.endSN + "], cc [" + newDetails.startCC + ", " + newDetails.endCC + "] duration:" + duration);
          var fragCurrent = this.fragCurrent;
      
          if (fragCurrent && (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING_WAITING_RETRY)) {
            if (fragCurrent.level !== data.level && fragCurrent.loader) {
              this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
              fragCurrent.loader.abort();
            }
          }
      
          var curLevel = levels[newLevelId];
          var sliding = 0;
      
          if (newDetails.live || (_curLevel$details = curLevel.details) !== null && _curLevel$details !== void 0 && _curLevel$details.live) {
            if (!newDetails.fragments[0]) {
              newDetails.deltaUpdateFailed = true;
            }
      
            if (newDetails.deltaUpdateFailed) {
              return;
            }
      
            sliding = this.alignPlaylists(newDetails, curLevel.details);
          } // override level info
      
      
          curLevel.details = newDetails;
          this.levelLastLoaded = newLevelId;
          this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_UPDATED, {
            details: newDetails,
            level: newLevelId
          }); // only switch back to IDLE state if we were waiting for level to start downloading a new fragment
      
          if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL) {
            if (this.waitForCdnTuneIn(newDetails)) {
              // Wait for Low-Latency CDN Tune-in
              return;
            }
      
            this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
          }
      
          if (!this.startFragRequested) {
            this.setStartPosition(newDetails, sliding);
          } else if (newDetails.live) {
            this.synchronizeToLiveEdge(newDetails);
          } // trigger handler right now
      
      
          this.tick();
        };
      
        _proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(data) {
          var _frag$initSegment;
      
          var frag = data.frag,
              part = data.part,
              payload = data.payload;
          var levels = this.levels;
      
          if (!levels) {
            this.warn("Levels were reset while fragment load was in progress. Fragment " + frag.sn + " of level " + frag.level + " will not be buffered");
            return;
          }
      
          var currentLevel = levels[frag.level];
          var details = currentLevel.details;
      
          if (!details) {
            this.warn("Dropping fragment " + frag.sn + " of level " + frag.level + " after level details were reset");
            return;
          }
      
          var videoCodec = currentLevel.videoCodec; // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
      
          var accurateTimeOffset = details.PTSKnown || !details.live;
          var initSegmentData = (_frag$initSegment = frag.initSegment) === null || _frag$initSegment === void 0 ? void 0 : _frag$initSegment.data;
      
          var audioCodec = this._getAudioCodec(currentLevel); // transmux the MPEG-TS data to ISO-BMFF segments
          // this.log(`Transmuxing ${frag.sn} of [${details.startSN} ,${details.endSN}],level ${frag.level}, cc ${frag.cc}`);
      
      
          var transmuxer = this.transmuxer = this.transmuxer || new _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_8__["default"](this.hls, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
          var partIndex = part ? part.index : -1;
          var partial = partIndex !== -1;
          var chunkMeta = new _types_transmuxer__WEBPACK_IMPORTED_MODULE_9__["ChunkMetadata"](frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
          var initPTS = this.initPTS[frag.cc];
          transmuxer.push(payload, initSegmentData, audioCodec, videoCodec, frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
        };
      
        _proto.onAudioTrackSwitching = function onAudioTrackSwitching(event, data) {
          // if any URL found on new audio track, it is an alternate audio track
          var fromAltAudio = this.altAudio;
          var altAudio = !!data.url;
          var trackId = data.id; // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered
          // don't do anything if we switch to alt audio: audio stream controller is handling it.
          // we will just have to change buffer scheduling on audioTrackSwitched
      
          if (!altAudio) {
            if (this.mediaBuffer !== this.media) {
              this.log('Switching on main audio, use media.buffered to schedule main fragment loading');
              this.mediaBuffer = this.media;
              var fragCurrent = this.fragCurrent; // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch
      
              if (fragCurrent !== null && fragCurrent !== void 0 && fragCurrent.loader) {
                this.log('Switching to main audio track, cancel main fragment load');
                fragCurrent.loader.abort();
              } // destroy transmuxer to force init segment generation (following audio switch)
      
      
              this.resetTransmuxer(); // switch to IDLE state to load new fragment
      
              this.resetLoadingState();
            } else if (this.audioOnly) {
              // Reset audio transmuxer so when switching back to main audio we're not still appending where we left off
              this.resetTransmuxer();
            }
      
            var hls = this.hls; // If switching from alt to main audio, flush all audio and trigger track switched
      
            if (fromAltAudio) {
              hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_FLUSHING, {
                startOffset: 0,
                endOffset: Number.POSITIVE_INFINITY,
                type: 'audio'
              });
            }
      
            hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHED, {
              id: trackId
            });
          }
        };
      
        _proto.onAudioTrackSwitched = function onAudioTrackSwitched(event, data) {
          var trackId = data.id;
          var altAudio = !!this.hls.audioTracks[trackId].url;
      
          if (altAudio) {
            var videoBuffer = this.videoBuffer; // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered
      
            if (videoBuffer && this.mediaBuffer !== videoBuffer) {
              this.log('Switching on alternate audio, use video.buffered to schedule main fragment loading');
              this.mediaBuffer = videoBuffer;
            }
          }
      
          this.altAudio = altAudio;
          this.tick();
        };
      
        _proto.onBufferCreated = function onBufferCreated(event, data) {
          var tracks = data.tracks;
          var mediaTrack;
          var name;
          var alternate = false;
      
          for (var type in tracks) {
            var track = tracks[type];
      
            if (track.id === 'main') {
              name = type;
              mediaTrack = track; // keep video source buffer reference
      
              if (type === 'video') {
                var videoTrack = tracks[type];
      
                if (videoTrack) {
                  this.videoBuffer = videoTrack.buffer;
                }
              }
            } else {
              alternate = true;
            }
          }
      
          if (alternate && mediaTrack) {
            this.log("Alternate track found, use " + name + ".buffered to schedule main fragment loading");
            this.mediaBuffer = mediaTrack.buffer;
          } else {
            this.mediaBuffer = this.media;
          }
        };
      
        _proto.onFragBuffered = function onFragBuffered(event, data) {
          var frag = data.frag,
              part = data.part;
      
          if (frag && frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN) {
            return;
          }
      
          if (this.fragContextChanged(frag)) {
            // If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion
            // Avoid setting state back to IDLE, since that will interfere with a level switch
            this.warn("Fragment " + frag.sn + (part ? ' p: ' + part.index : '') + " of level " + frag.level + " finished buffering, but was aborted. state: " + this.state);
      
            if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSED) {
              this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
            }
      
            return;
          }
      
          var stats = part ? part.stats : frag.stats;
          this.fragLastKbps = Math.round(8 * stats.total / (stats.buffering.end - stats.loading.first));
      
          if (frag.sn !== 'initSegment') {
            this.fragPrevious = frag;
          }
      
          this.fragBufferedComplete(frag, part);
        };
      
        _proto.onError = function onError(event, data) {
          switch (data.details) {
            case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].FRAG_LOAD_ERROR:
            case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].FRAG_LOAD_TIMEOUT:
            case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].KEY_LOAD_ERROR:
            case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].KEY_LOAD_TIMEOUT:
              this.onFragmentOrKeyLoadError(_types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN, data);
              break;
      
            case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].LEVEL_LOAD_ERROR:
            case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].LEVEL_LOAD_TIMEOUT:
              if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ERROR) {
                if (data.fatal) {
                  // if fatal error, stop processing
                  this.warn("" + data.details);
                  this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ERROR;
                } else {
                  // in case of non fatal error while loading level, if level controller is not retrying to load level , switch back to IDLE
                  if (!data.levelRetry && this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL) {
                    this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
                  }
                }
              }
      
              break;
      
            case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].BUFFER_FULL_ERROR:
              // if in appending state
              if (data.parent === 'main' && (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSED)) {
                var flushBuffer = true;
                var bufferedInfo = this.getFwdBufferInfo(this.media, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN); // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
                // reduce max buf len if current position is buffered
      
                if (bufferedInfo && bufferedInfo.len > 0.5) {
                  flushBuffer = !this.reduceMaxBufferLength(bufferedInfo.len);
                }
      
                if (flushBuffer) {
                  // current position is not buffered, but browser is still complaining about buffer full error
                  // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
                  // in that case flush the whole buffer to recover
                  this.warn('buffer full error also media.currentTime is not buffered, flush main'); // flush main buffer
      
                  this.immediateLevelSwitch();
                }
      
                this.resetLoadingState();
              }
      
              break;
      
            default:
              break;
          }
        } // Checks the health of the buffer and attempts to resolve playback stalls.
        ;
      
        _proto.checkBuffer = function checkBuffer() {
          var media = this.media,
              gapController = this.gapController;
      
          if (!media || !gapController || !media.readyState) {
            // Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0)
            return;
          } // Check combined buffer
      
      
          var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].getBuffered(media);
      
          if (!this.loadedmetadata && buffered.length) {
            this.loadedmetadata = true;
            this.seekToStartPos();
          } else {
            // Resolve gaps using the main buffer, whose ranges are the intersections of the A/V sourcebuffers
            gapController.poll(this.lastCurrentTime);
          }
      
          this.lastCurrentTime = media.currentTime;
        };
      
        _proto.onFragLoadEmergencyAborted = function onFragLoadEmergencyAborted() {
          this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; // if loadedmetadata is not set, it means that we are emergency switch down on first frag
          // in that case, reset startFragRequested flag
      
          if (!this.loadedmetadata) {
            this.startFragRequested = false;
            this.nextLoadPosition = this.startPosition;
          }
      
          this.tickImmediate();
        };
      
        _proto.onBufferFlushed = function onBufferFlushed(event, _ref) {
          var type = _ref.type;
      
          if (type !== _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO || this.audioOnly && !this.altAudio) {
            var media = (type === _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
            this.afterBufferFlushed(media, type, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN);
          }
        };
      
        _proto.onLevelsUpdated = function onLevelsUpdated(event, data) {
          this.levels = data.levels;
        };
      
        _proto.swapAudioCodec = function swapAudioCodec() {
          this.audioCodecSwap = !this.audioCodecSwap;
        }
        /**
         * Seeks to the set startPosition if not equal to the mediaElement's current time.
         * @private
         */
        ;
      
        _proto.seekToStartPos = function seekToStartPos() {
          var media = this.media;
          var currentTime = media.currentTime;
          var startPosition = this.startPosition; // only adjust currentTime if different from startPosition or if startPosition not buffered
          // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered
      
          if (startPosition >= 0 && currentTime < startPosition) {
            if (media.seeking) {
              _utils_logger__WEBPACK_IMPORTED_MODULE_12__["logger"].log("could not seek to " + startPosition + ", already seeking at " + currentTime);
              return;
            }
      
            var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].getBuffered(media);
            var bufferStart = buffered.length ? buffered.start(0) : 0;
            var delta = bufferStart - startPosition;
      
            if (delta > 0 && (delta < this.config.maxBufferHole || delta < this.config.maxFragLookUpTolerance)) {
              _utils_logger__WEBPACK_IMPORTED_MODULE_12__["logger"].log("adjusting start position by " + delta + " to match buffer start");
              startPosition += delta;
              this.startPosition = startPosition;
            }
      
            this.log("seek to target start position " + startPosition + " from current time " + currentTime);
            media.currentTime = startPosition;
          }
        };
      
        _proto._getAudioCodec = function _getAudioCodec(currentLevel) {
          var audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
      
          if (this.audioCodecSwap && audioCodec) {
            this.log('Swapping audio codec');
      
            if (audioCodec.indexOf('mp4a.40.5') !== -1) {
              audioCodec = 'mp4a.40.2';
            } else {
              audioCodec = 'mp4a.40.5';
            }
          }
      
          return audioCodec;
        };
      
        _proto._loadBitrateTestFrag = function _loadBitrateTestFrag(frag) {
          var _this2 = this;
      
          this._doFragLoad(frag).then(function (data) {
            var hls = _this2.hls;
      
            if (!data || hls.nextLoadLevel || _this2.fragContextChanged(frag)) {
              return;
            }
      
            _this2.fragLoadError = 0;
            _this2.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
            _this2.startFragRequested = false;
            _this2.bitrateTest = false;
            var stats = frag.stats; // Bitrate tests fragments are neither parsed nor buffered
      
            stats.parsing.start = stats.parsing.end = stats.buffering.start = stats.buffering.end = self.performance.now();
            hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_LOADED, data);
          });
        };
      
        _proto._handleTransmuxComplete = function _handleTransmuxComplete(transmuxResult) {
          var _id3$samples;
      
          var id = 'main';
          var hls = this.hls;
          var remuxResult = transmuxResult.remuxResult,
              chunkMeta = transmuxResult.chunkMeta;
          var context = this.getCurrentContext(chunkMeta);
      
          if (!context) {
            this.warn("The loading context changed while buffering fragment " + chunkMeta.sn + " of level " + chunkMeta.level + ". This chunk will not be buffered.");
            this.resetLiveStartWhenNotLoaded(chunkMeta.level);
            return;
          }
      
          var frag = context.frag,
              part = context.part,
              level = context.level;
          var video = remuxResult.video,
              text = remuxResult.text,
              id3 = remuxResult.id3,
              initSegment = remuxResult.initSegment; // The audio-stream-controller handles audio buffering if Hls.js is playing an alternate audio track
      
          var audio = this.altAudio ? undefined : remuxResult.audio; // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.
          // If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.
      
          if (this.fragContextChanged(frag)) {
            return;
          }
      
          this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING;
      
          if (initSegment) {
            if (initSegment.tracks) {
              this._bufferInitSegment(level, initSegment.tracks, frag, chunkMeta);
      
              hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_PARSING_INIT_SEGMENT, {
                frag: frag,
                id: id,
                tracks: initSegment.tracks
              });
            } // This would be nice if Number.isFinite acted as a typeguard, but it doesn't. See: https://github.com/Microsoft/TypeScript/issues/10038
      
      
            var initPTS = initSegment.initPTS;
            var timescale = initSegment.timescale;
      
            if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(initPTS)) {
              this.initPTS[frag.cc] = initPTS;
              hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].INIT_PTS_FOUND, {
                frag: frag,
                id: id,
                initPTS: initPTS,
                timescale: timescale
              });
            }
          } // Avoid buffering if backtracking this fragment
      
      
          if (video && remuxResult.independent !== false) {
            if (level.details) {
              var startPTS = video.startPTS,
                  endPTS = video.endPTS,
                  startDTS = video.startDTS,
                  endDTS = video.endDTS;
      
              if (part) {
                part.elementaryStreams[video.type] = {
                  startPTS: startPTS,
                  endPTS: endPTS,
                  startDTS: startDTS,
                  endDTS: endDTS
                };
              } else {
                if (video.firstKeyFrame && video.independent) {
                  this.couldBacktrack = true;
                }
      
                if (video.dropped && video.independent) {
                  // Backtrack if dropped frames create a gap after currentTime
                  var pos = this.getLoadPosition() + this.config.maxBufferHole;
      
                  if (pos < startPTS) {
                    this.backtrack(frag);
                    return;
                  } // Set video stream start to fragment start so that truncated samples do not distort the timeline, and mark it partial
      
      
                  frag.setElementaryStreamInfo(video.type, frag.start, endPTS, frag.start, endDTS, true);
                }
              }
      
              frag.setElementaryStreamInfo(video.type, startPTS, endPTS, startDTS, endDTS);
              this.bufferFragmentData(video, frag, part, chunkMeta);
            }
          } else if (remuxResult.independent === false) {
            this.backtrack(frag);
            return;
          }
      
          if (audio) {
            var _startPTS = audio.startPTS,
                _endPTS = audio.endPTS,
                _startDTS = audio.startDTS,
                _endDTS = audio.endDTS;
      
            if (part) {
              part.elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO] = {
                startPTS: _startPTS,
                endPTS: _endPTS,
                startDTS: _startDTS,
                endDTS: _endDTS
              };
            }
      
            frag.setElementaryStreamInfo(_loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO, _startPTS, _endPTS, _startDTS, _endDTS);
            this.bufferFragmentData(audio, frag, part, chunkMeta);
          }
      
          if (id3 !== null && id3 !== void 0 && (_id3$samples = id3.samples) !== null && _id3$samples !== void 0 && _id3$samples.length) {
            var emittedID3 = {
              frag: frag,
              id: id,
              samples: id3.samples
            };
            hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_PARSING_METADATA, emittedID3);
          }
      
          if (text) {
            var emittedText = {
              frag: frag,
              id: id,
              samples: text.samples
            };
            hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_PARSING_USERDATA, emittedText);
          }
        };
      
        _proto._bufferInitSegment = function _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
          var _this3 = this;
      
          if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING) {
            return;
          }
      
          this.audioOnly = !!tracks.audio && !tracks.video; // if audio track is expected to come from audio stream controller, discard any coming from main
      
          if (this.altAudio && !this.audioOnly) {
            delete tracks.audio;
          } // include levelCodec in audio and video tracks
      
      
          var audio = tracks.audio,
              video = tracks.video,
              audiovideo = tracks.audiovideo;
      
          if (audio) {
            var audioCodec = currentLevel.audioCodec;
            var ua = navigator.userAgent.toLowerCase();
      
            if (this.audioCodecSwitch) {
              if (audioCodec) {
                if (audioCodec.indexOf('mp4a.40.5') !== -1) {
                  audioCodec = 'mp4a.40.2';
                } else {
                  audioCodec = 'mp4a.40.5';
                }
              } // In the case that AAC and HE-AAC audio codecs are signalled in manifest,
              // force HE-AAC, as it seems that most browsers prefers it.
              // don't force HE-AAC if mono stream, or in Firefox
      
      
              if (audio.metadata.channelCount !== 1 && ua.indexOf('firefox') === -1) {
                audioCodec = 'mp4a.40.5';
              }
            } // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise
      
      
            if (ua.indexOf('android') !== -1 && audio.container !== 'audio/mpeg') {
              // Exclude mpeg audio
              audioCodec = 'mp4a.40.2';
              this.log("Android: force audio codec to " + audioCodec);
            }
      
            if (currentLevel.audioCodec && currentLevel.audioCodec !== audioCodec) {
              this.log("Swapping manifest audio codec \"" + currentLevel.audioCodec + "\" for \"" + audioCodec + "\"");
            }
      
            audio.levelCodec = audioCodec;
            audio.id = 'main';
            this.log("Init audio buffer, container:" + audio.container + ", codecs[selected/level/parsed]=[" + (audioCodec || '') + "/" + (currentLevel.audioCodec || '') + "/" + audio.codec + "]");
          }
      
          if (video) {
            video.levelCodec = currentLevel.videoCodec;
            video.id = 'main';
            this.log("Init video buffer, container:" + video.container + ", codecs[level/parsed]=[" + (currentLevel.videoCodec || '') + "/" + video.codec + "]");
          }
      
          if (audiovideo) {
            this.log("Init audiovideo buffer, container:" + audiovideo.container + ", codecs[level/parsed]=[" + (currentLevel.attrs.CODECS || '') + "/" + audiovideo.codec + "]");
          }
      
          this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_CODECS, tracks); // loop through tracks that are going to be provided to bufferController
      
          Object.keys(tracks).forEach(function (trackName) {
            var track = tracks[trackName];
            var initSegment = track.initSegment;
      
            if (initSegment !== null && initSegment !== void 0 && initSegment.byteLength) {
              _this3.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_APPENDING, {
                type: trackName,
                data: initSegment,
                frag: frag,
                part: null,
                chunkMeta: chunkMeta,
                parent: frag.type
              });
            }
          }); // trigger handler right now
      
          this.tick();
        };
      
        _proto.backtrack = function backtrack(frag) {
          this.couldBacktrack = true; // Causes findFragments to backtrack through fragments to find the keyframe
      
          this.resetTransmuxer();
          this.flushBufferGap(frag);
          var data = this.fragmentTracker.backtrack(frag);
          this.fragPrevious = null;
          this.nextLoadPosition = frag.start;
      
          if (data) {
            this.resetFragmentLoading(frag);
          } else {
            // Change state to BACKTRACKING so that fragmentEntity.backtrack data can be added after _doFragLoad
            this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].BACKTRACKING;
          }
        };
      
        _proto.checkFragmentChanged = function checkFragmentChanged() {
          var video = this.media;
          var fragPlayingCurrent = null;
      
          if (video && video.readyState > 1 && video.seeking === false) {
            var currentTime = video.currentTime;
            /* if video element is in seeked state, currentTime can only increase.
              (assuming that playback rate is positive ...)
              As sometimes currentTime jumps back to zero after a
              media decode error, check this, to avoid seeking back to
              wrong position after a media decode error
            */
      
            if (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].isBuffered(video, currentTime)) {
              fragPlayingCurrent = this.getAppendedFrag(currentTime);
            } else if (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].isBuffered(video, currentTime + 0.1)) {
              /* ensure that FRAG_CHANGED event is triggered at startup,
                when first video frame is displayed and playback is paused.
                add a tolerance of 100ms, in case current position is not buffered,
                check if current pos+100ms is buffered and use that buffer range
                for FRAG_CHANGED event reporting */
              fragPlayingCurrent = this.getAppendedFrag(currentTime + 0.1);
            }
      
            if (fragPlayingCurrent) {
              var fragPlaying = this.fragPlaying;
              var fragCurrentLevel = fragPlayingCurrent.level;
      
              if (!fragPlaying || fragPlayingCurrent.sn !== fragPlaying.sn || fragPlaying.level !== fragCurrentLevel || fragPlayingCurrent.urlId !== fragPlaying.urlId) {
                this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_CHANGED, {
                  frag: fragPlayingCurrent
                });
      
                if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) {
                  this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_SWITCHED, {
                    level: fragCurrentLevel
                  });
                }
      
                this.fragPlaying = fragPlayingCurrent;
              }
            }
          }
        };
      
        _createClass(StreamController, [{
          key: "nextLevel",
          get: function get() {
            var frag = this.nextBufferedFrag;
      
            if (frag) {
              return frag.level;
            } else {
              return -1;
            }
          }
        }, {
          key: "currentLevel",
          get: function get() {
            var media = this.media;
      
            if (media) {
              var fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
      
              if (fragPlayingCurrent) {
                return fragPlayingCurrent.level;
              }
            }
      
            return -1;
          }
        }, {
          key: "nextBufferedFrag",
          get: function get() {
            var media = this.media;
      
            if (media) {
              // first get end range of current fragment
              var fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
              return this.followingBufferedFrag(fragPlayingCurrent);
            } else {
              return null;
            }
          }
        }, {
          key: "forceStartLoad",
          get: function get() {
            return this._forceStartLoad;
          }
        }]);
      
        return StreamController;
      }(_base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["default"]);
      
      
      
      /***/ }),
      
      /***/ "./src/controller/subtitle-stream-controller.ts":
      /*!******************************************************!*\
        !*** ./src/controller/subtitle-stream-controller.ts ***!
        \******************************************************/
      /*! exports provided: SubtitleStreamController */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubtitleStreamController", function() { return SubtitleStreamController; });
      /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      /* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
      /* harmony import */ var _fragment_finders__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./fragment-finders */ "./src/controller/fragment-finders.ts");
      /* harmony import */ var _utils_discontinuities__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/discontinuities */ "./src/utils/discontinuities.ts");
      /* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.ts");
      /* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.ts");
      /* harmony import */ var _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./base-stream-controller */ "./src/controller/base-stream-controller.ts");
      /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
      /* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../types/level */ "./src/types/level.ts");
      function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
      
      function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
      
      function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
      
      function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
      
      
      
      
      
      
      
      
      
      
      
      var TICK_INTERVAL = 500; // how often to tick in ms
      
      var SubtitleStreamController = /*#__PURE__*/function (_BaseStreamController) {
        _inheritsLoose(SubtitleStreamController, _BaseStreamController);
      
        function SubtitleStreamController(hls, fragmentTracker) {
          var _this;
      
          _this = _BaseStreamController.call(this, hls, fragmentTracker, '[subtitle-stream-controller]') || this;
          _this.levels = [];
          _this.currentTrackId = -1;
          _this.tracksBuffered = [];
          _this.mainDetails = null;
      
          _this._registerListeners();
      
          return _this;
        }
      
        var _proto = SubtitleStreamController.prototype;
      
        _proto.onHandlerDestroying = function onHandlerDestroying() {
          this._unregisterListeners();
      
          this.mainDetails = null;
        };
      
        _proto._registerListeners = function _registerListeners() {
          var hls = this.hls;
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this);
        };
      
        _proto._unregisterListeners = function _unregisterListeners() {
          var hls = this.hls;
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this);
        };
      
        _proto.startLoad = function startLoad() {
          this.stopLoad();
          this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__["State"].IDLE;
          this.setInterval(TICK_INTERVAL);
          this.tick();
        };
      
        _proto.onManifestLoading = function onManifestLoading() {
          this.mainDetails = null;
          this.fragmentTracker.removeAllFragments();
        };
      
        _proto.onLevelLoaded = function onLevelLoaded(event, data) {
          this.mainDetails = data.details;
        };
      
        _proto.onSubtitleFragProcessed = function onSubtitleFragProcessed(event, data) {
          var frag = data.frag,
              success = data.success;
          this.fragPrevious = frag;
          this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__["State"].IDLE;
      
          if (!success) {
            return;
          }
      
          var buffered = this.tracksBuffered[this.currentTrackId];
      
          if (!buffered) {
            return;
          } // Create/update a buffered array matching the interface used by BufferHelper.bufferedInfo
          // so we can re-use the logic used to detect how much has been buffered
      
      
          var timeRange;
          var fragStart = frag.start;
      
          for (var i = 0; i < buffered.length; i++) {
            if (fragStart >= buffered[i].start && fragStart <= buffered[i].end) {
              timeRange = buffered[i];
              break;
            }
          }
      
          var fragEnd = frag.start + frag.duration;
      
          if (timeRange) {
            timeRange.end = fragEnd;
          } else {
            timeRange = {
              start: fragStart,
              end: fragEnd
            };
            buffered.push(timeRange);
          }
      
          this.fragmentTracker.fragBuffered(frag);
        };
      
        _proto.onBufferFlushing = function onBufferFlushing(event, data) {
          var startOffset = data.startOffset,
              endOffset = data.endOffset;
      
          if (startOffset === 0 && endOffset !== Number.POSITIVE_INFINITY) {
            var currentTrackId = this.currentTrackId,
                levels = this.levels;
      
            if (!levels.length || !levels[currentTrackId] || !levels[currentTrackId].details) {
              return;
            }
      
            var trackDetails = levels[currentTrackId].details;
            var targetDuration = trackDetails.targetduration;
            var endOffsetSubtitles = endOffset - targetDuration;
      
            if (endOffsetSubtitles <= 0) {
              return;
            }
      
            data.endOffsetSubtitles = Math.max(0, endOffsetSubtitles);
            this.tracksBuffered.forEach(function (buffered) {
              for (var i = 0; i < buffered.length;) {
                if (buffered[i].end <= endOffsetSubtitles) {
                  buffered.shift();
                  continue;
                } else if (buffered[i].start < endOffsetSubtitles) {
                  buffered[i].start = endOffsetSubtitles;
                } else {
                  break;
                }
      
                i++;
              }
            });
            this.fragmentTracker.removeFragmentsInRange(startOffset, endOffsetSubtitles, _types_loader__WEBPACK_IMPORTED_MODULE_8__["PlaylistLevelType"].SUBTITLE);
          }
        } // If something goes wrong, proceed to next frag, if we were processing one.
        ;
      
        _proto.onError = function onError(event, data) {
          var _this$fragCurrent;
      
          var frag = data.frag; // don't handle error not related to subtitle fragment
      
          if (!frag || frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_8__["PlaylistLevelType"].SUBTITLE) {
            return;
          }
      
          if ((_this$fragCurrent = this.fragCurrent) !== null && _this$fragCurrent !== void 0 && _this$fragCurrent.loader) {
            this.fragCurrent.loader.abort();
          }
      
          this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__["State"].IDLE;
        } // Got all new subtitle levels.
        ;
      
        _proto.onSubtitleTracksUpdated = function onSubtitleTracksUpdated(event, _ref) {
          var _this2 = this;
      
          var subtitleTracks = _ref.subtitleTracks;
          this.tracksBuffered = [];
          this.levels = subtitleTracks.map(function (mediaPlaylist) {
            return new _types_level__WEBPACK_IMPORTED_MODULE_9__["Level"](mediaPlaylist);
          });
          this.fragmentTracker.removeAllFragments();
          this.fragPrevious = null;
          this.levels.forEach(function (level) {
            _this2.tracksBuffered[level.id] = [];
          });
          this.mediaBuffer = null;
        };
      
        _proto.onSubtitleTrackSwitch = function onSubtitleTrackSwitch(event, data) {
          this.currentTrackId = data.id;
      
          if (!this.levels.length || this.currentTrackId === -1) {
            this.clearInterval();
            return;
          } // Check if track has the necessary details to load fragments
      
      
          var currentTrack = this.levels[this.currentTrackId];
      
          if (currentTrack !== null && currentTrack !== void 0 && currentTrack.details) {
            this.mediaBuffer = this.mediaBufferTimeRanges;
          } else {
            this.mediaBuffer = null;
          }
      
          if (currentTrack) {
            this.setInterval(TICK_INTERVAL);
          }
        } // Got a new set of subtitle fragments.
        ;
      
        _proto.onSubtitleTrackLoaded = function onSubtitleTrackLoaded(event, data) {
          var _track$details;
      
          var newDetails = data.details,
              trackId = data.id;
          var currentTrackId = this.currentTrackId,
              levels = this.levels;
      
          if (!levels.length) {
            return;
          }
      
          var track = levels[currentTrackId];
      
          if (trackId >= levels.length || trackId !== currentTrackId || !track) {
            return;
          }
      
          this.mediaBuffer = this.mediaBufferTimeRanges;
      
          if (newDetails.live || (_track$details = track.details) !== null && _track$details !== void 0 && _track$details.live) {
            var mainDetails = this.mainDetails;
      
            if (newDetails.deltaUpdateFailed || !mainDetails) {
              return;
            }
      
            var mainSlidingStartFragment = mainDetails.fragments[0];
      
            if (!track.details) {
              if (newDetails.hasProgramDateTime && mainDetails.hasProgramDateTime) {
                Object(_utils_discontinuities__WEBPACK_IMPORTED_MODULE_4__["alignMediaPlaylistByPDT"])(newDetails, mainDetails);
              } else if (mainSlidingStartFragment) {
                // line up live playlist with main so that fragments in range are loaded
                Object(_level_helper__WEBPACK_IMPORTED_MODULE_5__["addSliding"])(newDetails, mainSlidingStartFragment.start);
              }
            } else {
              var sliding = this.alignPlaylists(newDetails, track.details);
      
              if (sliding === 0 && mainSlidingStartFragment) {
                // realign with main when there is no overlap with last refresh
                Object(_level_helper__WEBPACK_IMPORTED_MODULE_5__["addSliding"])(newDetails, mainSlidingStartFragment.start);
              }
            }
          }
      
          track.details = newDetails;
          this.levelLastLoaded = trackId; // trigger handler right now
      
          this.tick(); // If playlist is misaligned because of bad PDT or drift, delete details to resync with main on reload
      
          if (newDetails.live && !this.fragCurrent && this.media && this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__["State"].IDLE) {
            var foundFrag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_3__["findFragmentByPTS"])(null, newDetails.fragments, this.media.currentTime, 0);
      
            if (!foundFrag) {
              this.warn('Subtitle playlist not aligned with playback');
              track.details = undefined;
            }
          }
        };
      
        _proto._handleFragmentLoadComplete = function _handleFragmentLoadComplete(fragLoadedData) {
          var frag = fragLoadedData.frag,
              payload = fragLoadedData.payload;
          var decryptData = frag.decryptdata;
          var hls = this.hls;
      
          if (this.fragContextChanged(frag)) {
            return;
          } // check to see if the payload needs to be decrypted
      
      
          if (payload && payload.byteLength > 0 && decryptData && decryptData.key && decryptData.iv && decryptData.method === 'AES-128') {
            var startTime = performance.now(); // decrypt the subtitles
      
            this.decrypter.webCryptoDecrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer).then(function (decryptedData) {
              var endTime = performance.now();
              hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_DECRYPTED, {
                frag: frag,
                payload: decryptedData,
                stats: {
                  tstart: startTime,
                  tdecrypt: endTime
                }
              });
            });
          }
        };
      
        _proto.doTick = function doTick() {
          if (!this.media) {
            this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__["State"].IDLE;
            return;
          }
      
          if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__["State"].IDLE) {
            var _foundFrag;
      
            var currentTrackId = this.currentTrackId,
                levels = this.levels;
      
            if (!levels.length || !levels[currentTrackId] || !levels[currentTrackId].details) {
              return;
            } // Expand range of subs loaded by one target-duration in either direction to make up for misaligned playlists
      
      
            var trackDetails = levels[currentTrackId].details;
            var targetDuration = trackDetails.targetduration;
            var config = this.config,
                media = this.media;
            var bufferedInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_2__["BufferHelper"].bufferedInfo(this.mediaBufferTimeRanges, media.currentTime - targetDuration, config.maxBufferHole);
            var targetBufferTime = bufferedInfo.end,
                bufferLen = bufferedInfo.len;
            var maxBufLen = this.getMaxBufferLength() + targetDuration;
      
            if (bufferLen > maxBufLen) {
              return;
            }
      
            console.assert(trackDetails, 'Subtitle track details are defined on idle subtitle stream controller tick');
            var fragments = trackDetails.fragments;
            var fragLen = fragments.length;
            var end = trackDetails.edge;
            var foundFrag;
            var fragPrevious = this.fragPrevious;
      
            if (targetBufferTime < end) {
              var maxFragLookUpTolerance = config.maxFragLookUpTolerance;
      
              if (fragPrevious && trackDetails.hasProgramDateTime) {
                foundFrag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_3__["findFragmentByPDT"])(fragments, fragPrevious.endProgramDateTime, maxFragLookUpTolerance);
              }
      
              if (!foundFrag) {
                foundFrag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_3__["findFragmentByPTS"])(fragPrevious, fragments, targetBufferTime, maxFragLookUpTolerance);
      
                if (!foundFrag && fragPrevious && fragPrevious.start < fragments[0].start) {
                  foundFrag = fragments[0];
                }
              }
            } else {
              foundFrag = fragments[fragLen - 1];
            }
      
            if ((_foundFrag = foundFrag) !== null && _foundFrag !== void 0 && _foundFrag.encrypted) {
              _utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log("Loading key for " + foundFrag.sn);
              this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_7__["State"].KEY_LOADING;
              this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADING, {
                frag: foundFrag
              });
            } else if (foundFrag && this.fragmentTracker.getState(foundFrag) === _fragment_tracker__WEBPACK_IMPORTED_MODULE_6__["FragmentState"].NOT_LOADED) {
              // only load if fragment is not loaded
              this.loadFragment(foundFrag, trackDetails, targetBufferTime);
            }
          }
        };
      
        _proto.loadFragment = function loadFragment(frag, levelDetails, targetBufferTime) {
          this.fragCurrent = frag;
      
          _BaseStreamController.prototype.loadFragment.call(this, frag, levelDetails, targetBufferTime);
        };
      
        _createClass(SubtitleStreamController, [{
          key: "mediaBufferTimeRanges",
          get: function get() {
            return this.tracksBuffered[this.currentTrackId] || [];
          }
        }]);
      
        return SubtitleStreamController;
      }(_base_stream_controller__WEBPACK_IMPORTED_MODULE_7__["default"]);
      
      /***/ }),
      
      /***/ "./src/controller/subtitle-track-controller.ts":
      /*!*****************************************************!*\
        !*** ./src/controller/subtitle-track-controller.ts ***!
        \*****************************************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
      /* harmony import */ var _utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/texttrack-utils */ "./src/utils/texttrack-utils.ts");
      /* harmony import */ var _base_playlist_controller__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./base-playlist-controller */ "./src/controller/base-playlist-controller.ts");
      /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
      function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
      
      function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
      
      function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
      
      function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
      
      
      
      
      
      
      var SubtitleTrackController = /*#__PURE__*/function (_BasePlaylistControll) {
        _inheritsLoose(SubtitleTrackController, _BasePlaylistControll);
      
        // Enable/disable subtitle display rendering
        function SubtitleTrackController(hls) {
          var _this;
      
          _this = _BasePlaylistControll.call(this, hls, '[subtitle-track-controller]') || this;
          _this.media = null;
          _this.tracks = [];
          _this.groupId = null;
          _this.tracksInGroup = [];
          _this.trackId = -1;
          _this.selectDefaultTrack = true;
          _this.queuedDefaultTrack = -1;
      
          _this.trackChangeListener = function () {
            return _this.onTextTracksChanged();
          };
      
          _this.asyncPollTrackChange = function () {
            return _this.pollTrackChange(0);
          };
      
          _this.useTextTrackPolling = false;
          _this.subtitlePollingInterval = -1;
          _this.subtitleDisplay = true;
      
          _this.registerListeners();
      
          return _this;
        }
      
        var _proto = SubtitleTrackController.prototype;
      
        _proto.destroy = function destroy() {
          this.unregisterListeners();
          this.tracks.length = 0;
          this.tracksInGroup.length = 0;
          this.trackChangeListener = this.asyncPollTrackChange = null;
      
          _BasePlaylistControll.prototype.destroy.call(this);
        };
      
        _proto.registerListeners = function registerListeners() {
          var hls = this.hls;
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_SWITCHING, this.onLevelSwitching, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this);
        };
      
        _proto.unregisterListeners = function unregisterListeners() {
          var hls = this.hls;
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_SWITCHING, this.onLevelSwitching, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this);
        } // Listen for subtitle track change, then extract the current track ID.
        ;
      
        _proto.onMediaAttached = function onMediaAttached(event, data) {
          this.media = data.media;
      
          if (!this.media) {
            return;
          }
      
          if (this.queuedDefaultTrack > -1) {
            this.subtitleTrack = this.queuedDefaultTrack;
            this.queuedDefaultTrack = -1;
          }
      
          this.useTextTrackPolling = !(this.media.textTracks && 'onchange' in this.media.textTracks);
      
          if (this.useTextTrackPolling) {
            this.pollTrackChange(500);
          } else {
            this.media.textTracks.addEventListener('change', this.asyncPollTrackChange);
          }
        };
      
        _proto.pollTrackChange = function pollTrackChange(timeout) {
          self.clearInterval(this.subtitlePollingInterval);
          this.subtitlePollingInterval = self.setInterval(this.trackChangeListener, timeout);
        };
      
        _proto.onMediaDetaching = function onMediaDetaching() {
          if (!this.media) {
            return;
          }
      
          self.clearInterval(this.subtitlePollingInterval);
      
          if (!this.useTextTrackPolling) {
            this.media.textTracks.removeEventListener('change', this.asyncPollTrackChange);
          }
      
          if (this.trackId > -1) {
            this.queuedDefaultTrack = this.trackId;
          }
      
          var textTracks = filterSubtitleTracks(this.media.textTracks); // Clear loaded cues on media detachment from tracks
      
          textTracks.forEach(function (track) {
            Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__["clearCurrentCues"])(track);
          }); // Disable all subtitle tracks before detachment so when reattached only tracks in that content are enabled.
      
          this.subtitleTrack = -1;
          this.media = null;
        };
      
        _proto.onManifestLoading = function onManifestLoading() {
          this.tracks = [];
          this.groupId = null;
          this.tracksInGroup = [];
          this.trackId = -1;
          this.selectDefaultTrack = true;
        } // Fired whenever a new manifest is loaded.
        ;
      
        _proto.onManifestParsed = function onManifestParsed(event, data) {
          this.tracks = data.subtitleTracks;
        };
      
        _proto.onSubtitleTrackLoaded = function onSubtitleTrackLoaded(event, data) {
          var id = data.id,
              details = data.details;
          var trackId = this.trackId;
          var currentTrack = this.tracksInGroup[trackId];
      
          if (!currentTrack) {
            this.warn("Invalid subtitle track id " + id);
            return;
          }
      
          var curDetails = currentTrack.details;
          currentTrack.details = data.details;
          this.log("subtitle track " + id + " loaded [" + details.startSN + "-" + details.endSN + "]");
      
          if (id === this.trackId) {
            this.retryCount = 0;
            this.playlistLoaded(id, data, curDetails);
          }
        };
      
        _proto.onLevelLoading = function onLevelLoading(event, data) {
          this.switchLevel(data.level);
        };
      
        _proto.onLevelSwitching = function onLevelSwitching(event, data) {
          this.switchLevel(data.level);
        };
      
        _proto.switchLevel = function switchLevel(levelIndex) {
          var levelInfo = this.hls.levels[levelIndex];
      
          if (!(levelInfo !== null && levelInfo !== void 0 && levelInfo.textGroupIds)) {
            return;
          }
      
          var textGroupId = levelInfo.textGroupIds[levelInfo.urlId];
      
          if (this.groupId !== textGroupId) {
            var lastTrack = this.tracksInGroup ? this.tracksInGroup[this.trackId] : undefined;
            var subtitleTracks = this.tracks.filter(function (track) {
              return !textGroupId || track.groupId === textGroupId;
            });
            this.tracksInGroup = subtitleTracks;
            var initialTrackId = this.findTrackId(lastTrack === null || lastTrack === void 0 ? void 0 : lastTrack.name) || this.findTrackId();
            this.groupId = textGroupId;
            var subtitleTracksUpdated = {
              subtitleTracks: subtitleTracks
            };
            this.log("Updating subtitle tracks, " + subtitleTracks.length + " track(s) found in \"" + textGroupId + "\" group-id");
            this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACKS_UPDATED, subtitleTracksUpdated);
      
            if (initialTrackId !== -1) {
              this.setSubtitleTrack(initialTrackId, lastTrack);
            }
          }
        };
      
        _proto.findTrackId = function findTrackId(name) {
          var textTracks = this.tracksInGroup;
      
          for (var i = 0; i < textTracks.length; i++) {
            var track = textTracks[i];
      
            if (!this.selectDefaultTrack || track.default) {
              if (!name || name === track.name) {
                return track.id;
              }
            }
          }
      
          return -1;
        };
      
        _proto.onError = function onError(event, data) {
          _BasePlaylistControll.prototype.onError.call(this, event, data);
      
          if (data.fatal || !data.context) {
            return;
          }
      
          if (data.context.type === _types_loader__WEBPACK_IMPORTED_MODULE_3__["PlaylistContextType"].SUBTITLE_TRACK && data.context.id === this.trackId && data.context.groupId === this.groupId) {
            this.retryLoadingOrFail(data);
          }
        }
        /** get alternate subtitle tracks list from playlist **/
        ;
      
        _proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {
          var currentTrack = this.tracksInGroup[this.trackId];
      
          if (this.shouldLoadTrack(currentTrack)) {
            var id = currentTrack.id;
            var groupId = currentTrack.groupId;
            var url = currentTrack.url;
      
            if (hlsUrlParameters) {
              try {
                url = hlsUrlParameters.addDirectives(url);
              } catch (error) {
                this.warn("Could not construct new URL with HLS Delivery Directives: " + error);
              }
            }
      
            this.log("Loading subtitle playlist for id " + id);
            this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_LOADING, {
              url: url,
              id: id,
              groupId: groupId,
              deliveryDirectives: hlsUrlParameters || null
            });
          }
        }
        /**
         * Disables the old subtitleTrack and sets current mode on the next subtitleTrack.
         * This operates on the DOM textTracks.
         * A value of -1 will disable all subtitle tracks.
         */
        ;
      
        _proto.toggleTrackModes = function toggleTrackModes(newId) {
          var _this2 = this;
      
          var media = this.media,
              subtitleDisplay = this.subtitleDisplay,
              trackId = this.trackId;
      
          if (!media) {
            return;
          }
      
          var textTracks = filterSubtitleTracks(media.textTracks);
          var groupTracks = textTracks.filter(function (track) {
            return track.groupId === _this2.groupId;
          });
      
          if (newId === -1) {
            [].slice.call(textTracks).forEach(function (track) {
              track.mode = 'disabled';
            });
          } else {
            var oldTrack = groupTracks[trackId];
      
            if (oldTrack) {
              oldTrack.mode = 'disabled';
            }
          }
      
          var nextTrack = groupTracks[newId];
      
          if (nextTrack) {
            nextTrack.mode = subtitleDisplay ? 'showing' : 'hidden';
          }
        }
        /**
         * This method is responsible for validating the subtitle index and periodically reloading if live.
         * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.
         */
        ;
      
        _proto.setSubtitleTrack = function setSubtitleTrack(newId, lastTrack) {
          var _tracks$newId;
      
          var tracks = this.tracksInGroup; // setting this.subtitleTrack will trigger internal logic
          // if media has not been attached yet, it will fail
          // we keep a reference to the default track id
          // and we'll set subtitleTrack when onMediaAttached is triggered
      
          if (!this.media) {
            this.queuedDefaultTrack = newId;
            return;
          }
      
          if (this.trackId !== newId) {
            this.toggleTrackModes(newId);
          } // exit if track id as already set or invalid
      
      
          if (this.trackId === newId && (newId === -1 || (_tracks$newId = tracks[newId]) !== null && _tracks$newId !== void 0 && _tracks$newId.details) || newId < -1 || newId >= tracks.length) {
            return;
          } // stopping live reloading timer if any
      
      
          this.clearTimer();
          var track = tracks[newId];
          this.log("Switching to subtitle track " + newId);
          this.trackId = newId;
      
          if (track) {
            var id = track.id,
                _track$groupId = track.groupId,
                groupId = _track$groupId === void 0 ? '' : _track$groupId,
                name = track.name,
                type = track.type,
                url = track.url;
            this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_SWITCH, {
              id: id,
              groupId: groupId,
              name: name,
              type: type,
              url: url
            });
            var hlsUrlParameters = this.switchParams(track.url, lastTrack === null || lastTrack === void 0 ? void 0 : lastTrack.details);
            this.loadPlaylist(hlsUrlParameters);
          } else {
            // switch to -1
            this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_SWITCH, {
              id: newId
            });
          }
        };
      
        _proto.onTextTracksChanged = function onTextTracksChanged() {
          if (!this.useTextTrackPolling) {
            self.clearInterval(this.subtitlePollingInterval);
          } // Media is undefined when switching streams via loadSource()
      
      
          if (!this.media || !this.hls.config.renderTextTracksNatively) {
            return;
          }
      
          var trackId = -1;
          var tracks = filterSubtitleTracks(this.media.textTracks);
      
          for (var id = 0; id < tracks.length; id++) {
            if (tracks[id].mode === 'hidden') {
              // Do not break in case there is a following track with showing.
              trackId = id;
            } else if (tracks[id].mode === 'showing') {
              trackId = id;
              break;
            }
          } // Setting current subtitleTrack will invoke code.
      
      
          if (this.subtitleTrack !== trackId) {
            this.subtitleTrack = trackId;
          }
        };
      
        _createClass(SubtitleTrackController, [{
          key: "subtitleTracks",
          get: function get() {
            return this.tracksInGroup;
          }
          /** get/set index of the selected subtitle track (based on index in subtitle track lists) **/
      
        }, {
          key: "subtitleTrack",
          get: function get() {
            return this.trackId;
          },
          set: function set(newId) {
            this.selectDefaultTrack = false;
            var lastTrack = this.tracksInGroup ? this.tracksInGroup[this.trackId] : undefined;
            this.setSubtitleTrack(newId, lastTrack);
          }
        }]);
      
        return SubtitleTrackController;
      }(_base_playlist_controller__WEBPACK_IMPORTED_MODULE_2__["default"]);
      
      function filterSubtitleTracks(textTrackList) {
        var tracks = [];
      
        for (var i = 0; i < textTrackList.length; i++) {
          var track = textTrackList[i]; // Edge adds a track without a label; we don't want to use it
      
          if (track.kind === 'subtitles' && track.label) {
            tracks.push(textTrackList[i]);
          }
        }
      
        return tracks;
      }
      
      /* harmony default export */ __webpack_exports__["default"] = (SubtitleTrackController);
      
      /***/ }),
      
      /***/ "./src/controller/timeline-controller.ts":
      /*!***********************************************!*\
        !*** ./src/controller/timeline-controller.ts ***!
        \***********************************************/
      /*! exports provided: TimelineController */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TimelineController", function() { return TimelineController; });
      /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
      /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
      /* harmony import */ var _utils_cea_608_parser__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/cea-608-parser */ "./src/utils/cea-608-parser.ts");
      /* harmony import */ var _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/output-filter */ "./src/utils/output-filter.ts");
      /* harmony import */ var _utils_webvtt_parser__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/webvtt-parser */ "./src/utils/webvtt-parser.ts");
      /* harmony import */ var _utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/texttrack-utils */ "./src/utils/texttrack-utils.ts");
      /* harmony import */ var _utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/imsc1-ttml-parser */ "./src/utils/imsc1-ttml-parser.ts");
      /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      
      
      
      
      
      
      
      
      
      
      var TimelineController = /*#__PURE__*/function () {
        function TimelineController(hls) {
          this.hls = void 0;
          this.media = null;
          this.config = void 0;
          this.enabled = true;
          this.Cues = void 0;
          this.textTracks = [];
          this.tracks = [];
          this.initPTS = [];
          this.timescale = [];
          this.unparsedVttFrags = [];
          this.captionsTracks = {};
          this.nonNativeCaptionsTracks = {};
          this.cea608Parser1 = void 0;
          this.cea608Parser2 = void 0;
          this.lastSn = -1;
          this.lastPartIndex = -1;
          this.prevCC = -1;
          this.vttCCs = newVTTCCs();
          this.captionsProperties = void 0;
          this.hls = hls;
          this.config = hls.config;
          this.Cues = hls.config.cueHandler;
          this.captionsProperties = {
            textTrack1: {
              label: this.config.captionsTextTrack1Label,
              languageCode: this.config.captionsTextTrack1LanguageCode
            },
            textTrack2: {
              label: this.config.captionsTextTrack2Label,
              languageCode: this.config.captionsTextTrack2LanguageCode
            },
            textTrack3: {
              label: this.config.captionsTextTrack3Label,
              languageCode: this.config.captionsTextTrack3LanguageCode
            },
            textTrack4: {
              label: this.config.captionsTextTrack4Label,
              languageCode: this.config.captionsTextTrack4LanguageCode
            }
          };
      
          if (this.config.enableCEA708Captions) {
            var channel1 = new _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__["default"](this, 'textTrack1');
            var channel2 = new _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__["default"](this, 'textTrack2');
            var channel3 = new _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__["default"](this, 'textTrack3');
            var channel4 = new _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__["default"](this, 'textTrack4');
            this.cea608Parser1 = new _utils_cea_608_parser__WEBPACK_IMPORTED_MODULE_2__["default"](1, channel1, channel2);
            this.cea608Parser2 = new _utils_cea_608_parser__WEBPACK_IMPORTED_MODULE_2__["default"](3, channel3, channel4);
          }
      
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, this.onManifestLoaded, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADING, this.onFragLoading, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, this.onFragLoaded, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_DECRYPTED, this.onFragDecrypted, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].INIT_PTS_FOUND, this.onInitPtsFound, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this);
        }
      
        var _proto = TimelineController.prototype;
      
        _proto.destroy = function destroy() {
          var hls = this.hls;
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, this.onManifestLoaded, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADING, this.onFragLoading, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, this.onFragLoaded, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_DECRYPTED, this.onFragDecrypted, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].INIT_PTS_FOUND, this.onInitPtsFound, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this); // @ts-ignore
      
          this.hls = this.config = this.cea608Parser1 = this.cea608Parser2 = null;
        };
      
        _proto.addCues = function addCues(trackName, startTime, endTime, screen, cueRanges) {
          // skip cues which overlap more than 50% with previously parsed time ranges
          var merged = false;
      
          for (var i = cueRanges.length; i--;) {
            var cueRange = cueRanges[i];
            var overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);
      
            if (overlap >= 0) {
              cueRange[0] = Math.min(cueRange[0], startTime);
              cueRange[1] = Math.max(cueRange[1], endTime);
              merged = true;
      
              if (overlap / (endTime - startTime) > 0.5) {
                return;
              }
            }
          }
      
          if (!merged) {
            cueRanges.push([startTime, endTime]);
          }
      
          if (this.config.renderTextTracksNatively) {
            var track = this.captionsTracks[trackName];
            this.Cues.newCue(track, startTime, endTime, screen);
          } else {
            var cues = this.Cues.newCue(null, startTime, endTime, screen);
            this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].CUES_PARSED, {
              type: 'captions',
              cues: cues,
              track: trackName
            });
          }
        } // Triggered when an initial PTS is found; used for synchronisation of WebVTT.
        ;
      
        _proto.onInitPtsFound = function onInitPtsFound(event, _ref) {
          var _this = this;
      
          var frag = _ref.frag,
              id = _ref.id,
              initPTS = _ref.initPTS,
              timescale = _ref.timescale;
          var unparsedVttFrags = this.unparsedVttFrags;
      
          if (id === 'main') {
            this.initPTS[frag.cc] = initPTS;
            this.timescale[frag.cc] = timescale;
          } // Due to asynchronous processing, initial PTS may arrive later than the first VTT fragments are loaded.
          // Parse any unparsed fragments upon receiving the initial PTS.
      
      
          if (unparsedVttFrags.length) {
            this.unparsedVttFrags = [];
            unparsedVttFrags.forEach(function (frag) {
              _this.onFragLoaded(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, frag);
            });
          }
        };
      
        _proto.getExistingTrack = function getExistingTrack(trackName) {
          var media = this.media;
      
          if (media) {
            for (var i = 0; i < media.textTracks.length; i++) {
              var textTrack = media.textTracks[i];
      
              if (textTrack[trackName]) {
                return textTrack;
              }
            }
          }
      
          return null;
        };
      
        _proto.createCaptionsTrack = function createCaptionsTrack(trackName) {
          if (this.config.renderTextTracksNatively) {
            this.createNativeTrack(trackName);
          } else {
            this.createNonNativeTrack(trackName);
          }
        };
      
        _proto.createNativeTrack = function createNativeTrack(trackName) {
          if (this.captionsTracks[trackName]) {
            return;
          }
      
          var captionsProperties = this.captionsProperties,
              captionsTracks = this.captionsTracks,
              media = this.media;
          var _captionsProperties$t = captionsProperties[trackName],
              label = _captionsProperties$t.label,
              languageCode = _captionsProperties$t.languageCode; // Enable reuse of existing text track.
      
          var existingTrack = this.getExistingTrack(trackName);
      
          if (!existingTrack) {
            var textTrack = this.createTextTrack('captions', label, languageCode);
      
            if (textTrack) {
              // Set a special property on the track so we know it's managed by Hls.js
              textTrack[trackName] = true;
              captionsTracks[trackName] = textTrack;
            }
          } else {
            captionsTracks[trackName] = existingTrack;
            Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["clearCurrentCues"])(captionsTracks[trackName]);
            Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["sendAddTrackEvent"])(captionsTracks[trackName], media);
          }
        };
      
        _proto.createNonNativeTrack = function createNonNativeTrack(trackName) {
          if (this.nonNativeCaptionsTracks[trackName]) {
            return;
          } // Create a list of a single track for the provider to consume
      
      
          var trackProperties = this.captionsProperties[trackName];
      
          if (!trackProperties) {
            return;
          }
      
          var label = trackProperties.label;
          var track = {
            _id: trackName,
            label: label,
            kind: 'captions',
            default: trackProperties.media ? !!trackProperties.media.default : false,
            closedCaptions: trackProperties.media
          };
          this.nonNativeCaptionsTracks[trackName] = track;
          this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].NON_NATIVE_TEXT_TRACKS_FOUND, {
            tracks: [track]
          });
        };
      
        _proto.createTextTrack = function createTextTrack(kind, label, lang) {
          var media = this.media;
      
          if (!media) {
            return;
          }
      
          return media.addTextTrack(kind, label, lang);
        };
      
        _proto.onMediaAttaching = function onMediaAttaching(event, data) {
          this.media = data.media;
      
          this._cleanTracks();
        };
      
        _proto.onMediaDetaching = function onMediaDetaching() {
          var captionsTracks = this.captionsTracks;
          Object.keys(captionsTracks).forEach(function (trackName) {
            Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["clearCurrentCues"])(captionsTracks[trackName]);
            delete captionsTracks[trackName];
          });
          this.nonNativeCaptionsTracks = {};
        };
      
        _proto.onManifestLoading = function onManifestLoading() {
          this.lastSn = -1; // Detect discontinuity in fragment parsing
      
          this.lastPartIndex = -1;
          this.prevCC = -1;
          this.vttCCs = newVTTCCs(); // Detect discontinuity in subtitle manifests
      
          this._cleanTracks();
      
          this.tracks = [];
          this.captionsTracks = {};
          this.nonNativeCaptionsTracks = {};
          this.textTracks = [];
          this.unparsedVttFrags = this.unparsedVttFrags || [];
          this.initPTS = [];
          this.timescale = [];
      
          if (this.cea608Parser1 && this.cea608Parser2) {
            this.cea608Parser1.reset();
            this.cea608Parser2.reset();
          }
        };
      
        _proto._cleanTracks = function _cleanTracks() {
          // clear outdated subtitles
          var media = this.media;
      
          if (!media) {
            return;
          }
      
          var textTracks = media.textTracks;
      
          if (textTracks) {
            for (var i = 0; i < textTracks.length; i++) {
              Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["clearCurrentCues"])(textTracks[i]);
            }
          }
        };
      
        _proto.onSubtitleTracksUpdated = function onSubtitleTracksUpdated(event, data) {
          var _this2 = this;
      
          this.textTracks = [];
          var tracks = data.subtitleTracks || [];
          var hasIMSC1 = tracks.some(function (track) {
            return track.textCodec === _utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__["IMSC1_CODEC"];
          });
      
          if (this.config.enableWebVTT || hasIMSC1 && this.config.enableIMSC1) {
            var sameTracks = this.tracks && tracks && this.tracks.length === tracks.length;
            this.tracks = tracks || [];
      
            if (this.config.renderTextTracksNatively) {
              var inUseTracks = this.media ? this.media.textTracks : [];
              this.tracks.forEach(function (track, index) {
                var textTrack;
      
                if (index < inUseTracks.length) {
                  var inUseTrack = null;
      
                  for (var i = 0; i < inUseTracks.length; i++) {
                    if (canReuseVttTextTrack(inUseTracks[i], track)) {
                      inUseTrack = inUseTracks[i];
                      break;
                    }
                  } // Reuse tracks with the same label, but do not reuse 608/708 tracks
      
      
                  if (inUseTrack) {
                    textTrack = inUseTrack;
                  }
                }
      
                if (textTrack) {
                  Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["clearCurrentCues"])(textTrack);
                } else {
                  textTrack = _this2.createTextTrack('subtitles', track.name, track.lang);
      
                  if (textTrack) {
                    textTrack.mode = 'disabled';
                  }
                }
      
                if (textTrack) {
                  textTrack.groupId = track.groupId;
      
                  _this2.textTracks.push(textTrack);
                }
              });
            } else if (!sameTracks && this.tracks && this.tracks.length) {
              // Create a list of tracks for the provider to consume
              var tracksList = this.tracks.map(function (track) {
                return {
                  label: track.name,
                  kind: track.type.toLowerCase(),
                  default: track.default,
                  subtitleTrack: track
                };
              });
              this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].NON_NATIVE_TEXT_TRACKS_FOUND, {
                tracks: tracksList
              });
            }
          }
        };
      
        _proto.onManifestLoaded = function onManifestLoaded(event, data) {
          var _this3 = this;
      
          if (this.config.enableCEA708Captions && data.captions) {
            data.captions.forEach(function (captionsTrack) {
              var instreamIdMatch = /(?:CC|SERVICE)([1-4])/.exec(captionsTrack.instreamId);
      
              if (!instreamIdMatch) {
                return;
              }
      
              var trackName = "textTrack" + instreamIdMatch[1];
              var trackProperties = _this3.captionsProperties[trackName];
      
              if (!trackProperties) {
                return;
              }
      
              trackProperties.label = captionsTrack.name;
      
              if (captionsTrack.lang) {
                // optional attribute
                trackProperties.languageCode = captionsTrack.lang;
              }
      
              trackProperties.media = captionsTrack;
            });
          }
        };
      
        _proto.onFragLoading = function onFragLoading(event, data) {
          var cea608Parser1 = this.cea608Parser1,
              cea608Parser2 = this.cea608Parser2,
              lastSn = this.lastSn,
              lastPartIndex = this.lastPartIndex;
      
          if (!this.enabled || !(cea608Parser1 && cea608Parser2)) {
            return;
          } // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack
      
      
          if (data.frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_7__["PlaylistLevelType"].MAIN) {
            var _data$part$index, _data$part;
      
            var sn = data.frag.sn;
            var partIndex = (_data$part$index = data === null || data === void 0 ? void 0 : (_data$part = data.part) === null || _data$part === void 0 ? void 0 : _data$part.index) != null ? _data$part$index : -1;
      
            if (!(sn === lastSn + 1 || sn === lastSn && partIndex === lastPartIndex + 1)) {
              cea608Parser1.reset();
              cea608Parser2.reset();
            }
      
            this.lastSn = sn;
            this.lastPartIndex = partIndex;
          }
        };
      
        _proto.onFragLoaded = function onFragLoaded(event, data) {
          var frag = data.frag,
              payload = data.payload;
          var initPTS = this.initPTS,
              unparsedVttFrags = this.unparsedVttFrags;
      
          if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_7__["PlaylistLevelType"].SUBTITLE) {
            // If fragment is subtitle type, parse as WebVTT.
            if (payload.byteLength) {
              // We need an initial synchronisation PTS. Store fragments as long as none has arrived.
              if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(initPTS[frag.cc])) {
                unparsedVttFrags.push(data);
      
                if (initPTS.length) {
                  // finish unsuccessfully, otherwise the subtitle-stream-controller could be blocked from loading new frags.
                  this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, {
                    success: false,
                    frag: frag,
                    error: new Error('Missing initial subtitle PTS')
                  });
                }
      
                return;
              }
      
              var decryptData = frag.decryptdata; // If the subtitles are not encrypted, parse VTTs now. Otherwise, we need to wait.
      
              if (decryptData == null || decryptData.key == null || decryptData.method !== 'AES-128') {
                var trackPlaylistMedia = this.tracks[frag.level];
                var vttCCs = this.vttCCs;
      
                if (!vttCCs[frag.cc]) {
                  vttCCs[frag.cc] = {
                    start: frag.start,
                    prevCC: this.prevCC,
                    new: true
                  };
                  this.prevCC = frag.cc;
                }
      
                if (trackPlaylistMedia && trackPlaylistMedia.textCodec === _utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__["IMSC1_CODEC"]) {
                  this._parseIMSC1(frag, payload);
                } else {
                  this._parseVTTs(frag, payload, vttCCs);
                }
              }
            } else {
              // In case there is no payload, finish unsuccessfully.
              this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, {
                success: false,
                frag: frag,
                error: new Error('Empty subtitle payload')
              });
            }
          }
        };
      
        _proto._parseIMSC1 = function _parseIMSC1(frag, payload) {
          var _this4 = this;
      
          var hls = this.hls;
          Object(_utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__["parseIMSC1"])(payload, this.initPTS[frag.cc], this.timescale[frag.cc], function (cues) {
            _this4._appendCues(cues, frag.level);
      
            hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, {
              success: true,
              frag: frag
            });
          }, function (error) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_8__["logger"].log("Failed to parse IMSC1: " + error);
            hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, {
              success: false,
              frag: frag,
              error: error
            });
          });
        };
      
        _proto._parseVTTs = function _parseVTTs(frag, payload, vttCCs) {
          var _this5 = this;
      
          var hls = this.hls; // Parse the WebVTT file contents.
      
          Object(_utils_webvtt_parser__WEBPACK_IMPORTED_MODULE_4__["parseWebVTT"])(payload, this.initPTS[frag.cc], this.timescale[frag.cc], vttCCs, frag.cc, frag.start, function (cues) {
            _this5._appendCues(cues, frag.level);
      
            hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, {
              success: true,
              frag: frag
            });
          }, function (error) {
            _this5._fallbackToIMSC1(frag, payload); // Something went wrong while parsing. Trigger event with success false.
      
      
            _utils_logger__WEBPACK_IMPORTED_MODULE_8__["logger"].log("Failed to parse VTT cue: " + error);
            hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, {
              success: false,
              frag: frag,
              error: error
            });
          });
        };
      
        _proto._fallbackToIMSC1 = function _fallbackToIMSC1(frag, payload) {
          var _this6 = this;
      
          // If textCodec is unknown, try parsing as IMSC1. Set textCodec based on the result
          var trackPlaylistMedia = this.tracks[frag.level];
      
          if (!trackPlaylistMedia.textCodec) {
            Object(_utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__["parseIMSC1"])(payload, this.initPTS[frag.cc], this.timescale[frag.cc], function () {
              trackPlaylistMedia.textCodec = _utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__["IMSC1_CODEC"];
      
              _this6._parseIMSC1(frag, payload);
            }, function () {
              trackPlaylistMedia.textCodec = 'wvtt';
            });
          }
        };
      
        _proto._appendCues = function _appendCues(cues, fragLevel) {
          var hls = this.hls;
      
          if (this.config.renderTextTracksNatively) {
            var textTrack = this.textTracks[fragLevel]; // WebVTTParser.parse is an async method and if the currently selected text track mode is set to "disabled"
            // before parsing is done then don't try to access currentTrack.cues.getCueById as cues will be null
            // and trying to access getCueById method of cues will throw an exception
            // Because we check if the mode is disabled, we can force check `cues` below. They can't be null.
      
            if (textTrack.mode === 'disabled') {
              return;
            }
      
            cues.forEach(function (cue) {
              return Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["addCueToTrack"])(textTrack, cue);
            });
          } else {
            var currentTrack = this.tracks[fragLevel];
            var track = currentTrack.default ? 'default' : 'subtitles' + fragLevel;
            hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].CUES_PARSED, {
              type: 'subtitles',
              cues: cues,
              track: track
            });
          }
        };
      
        _proto.onFragDecrypted = function onFragDecrypted(event, data) {
          var frag = data.frag;
      
          if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_7__["PlaylistLevelType"].SUBTITLE) {
            if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.initPTS[frag.cc])) {
              this.unparsedVttFrags.push(data);
              return;
            }
      
            this.onFragLoaded(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, data);
          }
        };
      
        _proto.onSubtitleTracksCleared = function onSubtitleTracksCleared() {
          this.tracks = [];
          this.captionsTracks = {};
        };
      
        _proto.onFragParsingUserdata = function onFragParsingUserdata(event, data) {
          var cea608Parser1 = this.cea608Parser1,
              cea608Parser2 = this.cea608Parser2;
      
          if (!this.enabled || !(cea608Parser1 && cea608Parser2)) {
            return;
          } // If the event contains captions (found in the bytes property), push all bytes into the parser immediately
          // It will create the proper timestamps based on the PTS value
      
      
          for (var i = 0; i < data.samples.length; i++) {
            var ccBytes = data.samples[i].bytes;
      
            if (ccBytes) {
              var ccdatas = this.extractCea608Data(ccBytes);
              cea608Parser1.addData(data.samples[i].pts, ccdatas[0]);
              cea608Parser2.addData(data.samples[i].pts, ccdatas[1]);
            }
          }
        };
      
        _proto.onBufferFlushing = function onBufferFlushing(event, _ref2) {
          var startOffset = _ref2.startOffset,
              endOffset = _ref2.endOffset,
              endOffsetSubtitles = _ref2.endOffsetSubtitles,
              type = _ref2.type;
          var media = this.media;
      
          if (!media || media.currentTime < endOffset) {
            return;
          } // Clear 608 caption cues from the captions TextTracks when the video back buffer is flushed
          // Forward cues are never removed because we can loose streamed 608 content from recent fragments
      
      
          if (!type || type === 'video') {
            var captionsTracks = this.captionsTracks;
            Object.keys(captionsTracks).forEach(function (trackName) {
              return Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["removeCuesInRange"])(captionsTracks[trackName], startOffset, endOffset);
            });
          }
      
          if (this.config.renderTextTracksNatively) {
            // Clear VTT/IMSC1 subtitle cues from the subtitle TextTracks when the back buffer is flushed
            if (startOffset === 0 && endOffsetSubtitles !== undefined) {
              var textTracks = this.textTracks;
              Object.keys(textTracks).forEach(function (trackName) {
                return Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["removeCuesInRange"])(textTracks[trackName], startOffset, endOffsetSubtitles);
              });
            }
          }
        };
      
        _proto.extractCea608Data = function extractCea608Data(byteArray) {
          var count = byteArray[0] & 31;
          var position = 2;
          var actualCCBytes = [[], []];
      
          for (var j = 0; j < count; j++) {
            var tmpByte = byteArray[position++];
            var ccbyte1 = 0x7f & byteArray[position++];
            var ccbyte2 = 0x7f & byteArray[position++];
            var ccValid = (4 & tmpByte) !== 0;
            var ccType = 3 & tmpByte;
      
            if (ccbyte1 === 0 && ccbyte2 === 0) {
              continue;
            }
      
            if (ccValid) {
              if (ccType === 0 || ccType === 1) {
                actualCCBytes[ccType].push(ccbyte1);
                actualCCBytes[ccType].push(ccbyte2);
              }
            }
          }
      
          return actualCCBytes;
        };
      
        return TimelineController;
      }();
      
      function canReuseVttTextTrack(inUseTrack, manifestTrack) {
        return inUseTrack && inUseTrack.label === manifestTrack.name && !(inUseTrack.textTrack1 || inUseTrack.textTrack2);
      }
      
      function intersection(x1, x2, y1, y2) {
        return Math.min(x2, y2) - Math.max(x1, y1);
      }
      
      function newVTTCCs() {
        return {
          ccOffset: 0,
          presentationOffset: 0,
          0: {
            start: 0,
            prevCC: -1,
            new: false
          }
        };
      }
      
      /***/ }),
      
      /***/ "./src/crypt/aes-crypto.ts":
      /*!*********************************!*\
        !*** ./src/crypt/aes-crypto.ts ***!
        \*********************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return AESCrypto; });
      var AESCrypto = /*#__PURE__*/function () {
        function AESCrypto(subtle, iv) {
          this.subtle = void 0;
          this.aesIV = void 0;
          this.subtle = subtle;
          this.aesIV = iv;
        }
      
        var _proto = AESCrypto.prototype;
      
        _proto.decrypt = function decrypt(data, key) {
          return this.subtle.decrypt({
            name: 'AES-CBC',
            iv: this.aesIV
          }, key, data);
        };
      
        return AESCrypto;
      }();
      
      
      
      /***/ }),
      
      /***/ "./src/crypt/aes-decryptor.ts":
      /*!************************************!*\
        !*** ./src/crypt/aes-decryptor.ts ***!
        \************************************/
      /*! exports provided: removePadding, default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removePadding", function() { return removePadding; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return AESDecryptor; });
      /* harmony import */ var _utils_typed_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/typed-array */ "./src/utils/typed-array.ts");
       // PKCS7
      
      function removePadding(array) {
        var outputBytes = array.byteLength;
        var paddingBytes = outputBytes && new DataView(array.buffer).getUint8(outputBytes - 1);
      
        if (paddingBytes) {
          return Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_0__["sliceUint8"])(array, 0, outputBytes - paddingBytes);
        }
      
        return array;
      }
      
      var AESDecryptor = /*#__PURE__*/function () {
        function AESDecryptor() {
          this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
          this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
          this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
          this.sBox = new Uint32Array(256);
          this.invSBox = new Uint32Array(256);
          this.key = new Uint32Array(0);
          this.ksRows = 0;
          this.keySize = 0;
          this.keySchedule = void 0;
          this.invKeySchedule = void 0;
          this.initTable();
        } // Using view.getUint32() also swaps the byte order.
      
      
        var _proto = AESDecryptor.prototype;
      
        _proto.uint8ArrayToUint32Array_ = function uint8ArrayToUint32Array_(arrayBuffer) {
          var view = new DataView(arrayBuffer);
          var newArray = new Uint32Array(4);
      
          for (var i = 0; i < 4; i++) {
            newArray[i] = view.getUint32(i * 4);
          }
      
          return newArray;
        };
      
        _proto.initTable = function initTable() {
          var sBox = this.sBox;
          var invSBox = this.invSBox;
          var subMix = this.subMix;
          var subMix0 = subMix[0];
          var subMix1 = subMix[1];
          var subMix2 = subMix[2];
          var subMix3 = subMix[3];
          var invSubMix = this.invSubMix;
          var invSubMix0 = invSubMix[0];
          var invSubMix1 = invSubMix[1];
          var invSubMix2 = invSubMix[2];
          var invSubMix3 = invSubMix[3];
          var d = new Uint32Array(256);
          var x = 0;
          var xi = 0;
          var i = 0;
      
          for (i = 0; i < 256; i++) {
            if (i < 128) {
              d[i] = i << 1;
            } else {
              d[i] = i << 1 ^ 0x11b;
            }
          }
      
          for (i = 0; i < 256; i++) {
            var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
            sx = sx >>> 8 ^ sx & 0xff ^ 0x63;
            sBox[x] = sx;
            invSBox[sx] = x; // Compute multiplication
      
            var x2 = d[x];
            var x4 = d[x2];
            var x8 = d[x4]; // Compute sub/invSub bytes, mix columns tables
      
            var t = d[sx] * 0x101 ^ sx * 0x1010100;
            subMix0[x] = t << 24 | t >>> 8;
            subMix1[x] = t << 16 | t >>> 16;
            subMix2[x] = t << 8 | t >>> 24;
            subMix3[x] = t; // Compute inv sub bytes, inv mix columns tables
      
            t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
            invSubMix0[sx] = t << 24 | t >>> 8;
            invSubMix1[sx] = t << 16 | t >>> 16;
            invSubMix2[sx] = t << 8 | t >>> 24;
            invSubMix3[sx] = t; // Compute next counter
      
            if (!x) {
              x = xi = 1;
            } else {
              x = x2 ^ d[d[d[x8 ^ x2]]];
              xi ^= d[d[xi]];
            }
          }
        };
      
        _proto.expandKey = function expandKey(keyBuffer) {
          // convert keyBuffer to Uint32Array
          var key = this.uint8ArrayToUint32Array_(keyBuffer);
          var sameKey = true;
          var offset = 0;
      
          while (offset < key.length && sameKey) {
            sameKey = key[offset] === this.key[offset];
            offset++;
          }
      
          if (sameKey) {
            return;
          }
      
          this.key = key;
          var keySize = this.keySize = key.length;
      
          if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
            throw new Error('Invalid aes key size=' + keySize);
          }
      
          var ksRows = this.ksRows = (keySize + 6 + 1) * 4;
          var ksRow;
          var invKsRow;
          var keySchedule = this.keySchedule = new Uint32Array(ksRows);
          var invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
          var sbox = this.sBox;
          var rcon = this.rcon;
          var invSubMix = this.invSubMix;
          var invSubMix0 = invSubMix[0];
          var invSubMix1 = invSubMix[1];
          var invSubMix2 = invSubMix[2];
          var invSubMix3 = invSubMix[3];
          var prev;
          var t;
      
          for (ksRow = 0; ksRow < ksRows; ksRow++) {
            if (ksRow < keySize) {
              prev = keySchedule[ksRow] = key[ksRow];
              continue;
            }
      
            t = prev;
      
            if (ksRow % keySize === 0) {
              // Rot word
              t = t << 8 | t >>> 24; // Sub word
      
              t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff]; // Mix Rcon
      
              t ^= rcon[ksRow / keySize | 0] << 24;
            } else if (keySize > 6 && ksRow % keySize === 4) {
              // Sub word
              t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
            }
      
            keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;
          }
      
          for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
            ksRow = ksRows - invKsRow;
      
            if (invKsRow & 3) {
              t = keySchedule[ksRow];
            } else {
              t = keySchedule[ksRow - 4];
            }
      
            if (invKsRow < 4 || ksRow <= 4) {
              invKeySchedule[invKsRow] = t;
            } else {
              invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 0xff]] ^ invSubMix2[sbox[t >>> 8 & 0xff]] ^ invSubMix3[sbox[t & 0xff]];
            }
      
            invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
          }
        } // Adding this as a method greatly improves performance.
        ;
      
        _proto.networkToHostOrderSwap = function networkToHostOrderSwap(word) {
          return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
        };
      
        _proto.decrypt = function decrypt(inputArrayBuffer, offset, aesIV) {
          var nRounds = this.keySize + 6;
          var invKeySchedule = this.invKeySchedule;
          var invSBOX = this.invSBox;
          var invSubMix = this.invSubMix;
          var invSubMix0 = invSubMix[0];
          var invSubMix1 = invSubMix[1];
          var invSubMix2 = invSubMix[2];
          var invSubMix3 = invSubMix[3];
          var initVector = this.uint8ArrayToUint32Array_(aesIV);
          var initVector0 = initVector[0];
          var initVector1 = initVector[1];
          var initVector2 = initVector[2];
          var initVector3 = initVector[3];
          var inputInt32 = new Int32Array(inputArrayBuffer);
          var outputInt32 = new Int32Array(inputInt32.length);
          var t0, t1, t2, t3;
          var s0, s1, s2, s3;
          var inputWords0, inputWords1, inputWords2, inputWords3;
          var ksRow, i;
          var swapWord = this.networkToHostOrderSwap;
      
          while (offset < inputInt32.length) {
            inputWords0 = swapWord(inputInt32[offset]);
            inputWords1 = swapWord(inputInt32[offset + 1]);
            inputWords2 = swapWord(inputInt32[offset + 2]);
            inputWords3 = swapWord(inputInt32[offset + 3]);
            s0 = inputWords0 ^ invKeySchedule[0];
            s1 = inputWords3 ^ invKeySchedule[1];
            s2 = inputWords2 ^ invKeySchedule[2];
            s3 = inputWords1 ^ invKeySchedule[3];
            ksRow = 4; // Iterate through the rounds of decryption
      
            for (i = 1; i < nRounds; i++) {
              t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 0xff] ^ invSubMix2[s2 >> 8 & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];
              t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 0xff] ^ invSubMix2[s3 >> 8 & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
              t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 0xff] ^ invSubMix2[s0 >> 8 & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
              t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 0xff] ^ invSubMix2[s1 >> 8 & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3]; // Update state
      
              s0 = t0;
              s1 = t1;
              s2 = t2;
              s3 = t3;
              ksRow = ksRow + 4;
            } // Shift rows, sub bytes, add round key
      
      
            t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 0xff] << 16 ^ invSBOX[s2 >> 8 & 0xff] << 8 ^ invSBOX[s3 & 0xff] ^ invKeySchedule[ksRow];
            t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 0xff] << 16 ^ invSBOX[s3 >> 8 & 0xff] << 8 ^ invSBOX[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
            t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 0xff] << 16 ^ invSBOX[s0 >> 8 & 0xff] << 8 ^ invSBOX[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
            t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 0xff] << 16 ^ invSBOX[s1 >> 8 & 0xff] << 8 ^ invSBOX[s2 & 0xff] ^ invKeySchedule[ksRow + 3]; // Write
      
            outputInt32[offset] = swapWord(t0 ^ initVector0);
            outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
            outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
            outputInt32[offset + 3] = swapWord(t1 ^ initVector3); // reset initVector to last 4 unsigned int
      
            initVector0 = inputWords0;
            initVector1 = inputWords1;
            initVector2 = inputWords2;
            initVector3 = inputWords3;
            offset = offset + 4;
          }
      
          return outputInt32.buffer;
        };
      
        return AESDecryptor;
      }();
      
      
      
      /***/ }),
      
      /***/ "./src/crypt/decrypter.ts":
      /*!********************************!*\
        !*** ./src/crypt/decrypter.ts ***!
        \********************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Decrypter; });
      /* harmony import */ var _aes_crypto__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./aes-crypto */ "./src/crypt/aes-crypto.ts");
      /* harmony import */ var _fast_aes_key__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./fast-aes-key */ "./src/crypt/fast-aes-key.ts");
      /* harmony import */ var _aes_decryptor__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./aes-decryptor */ "./src/crypt/aes-decryptor.ts");
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
      /* harmony import */ var _utils_typed_array__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/typed-array */ "./src/utils/typed-array.ts");
      
      
      
      
      
      
      var CHUNK_SIZE = 16; // 16 bytes, 128 bits
      
      var Decrypter = /*#__PURE__*/function () {
        function Decrypter(observer, config, _temp) {
          var _ref = _temp === void 0 ? {} : _temp,
              _ref$removePKCS7Paddi = _ref.removePKCS7Padding,
              removePKCS7Padding = _ref$removePKCS7Paddi === void 0 ? true : _ref$removePKCS7Paddi;
      
          this.logEnabled = true;
          this.observer = void 0;
          this.config = void 0;
          this.removePKCS7Padding = void 0;
          this.subtle = null;
          this.softwareDecrypter = null;
          this.key = null;
          this.fastAesKey = null;
          this.remainderData = null;
          this.currentIV = null;
          this.currentResult = null;
          this.observer = observer;
          this.config = config;
          this.removePKCS7Padding = removePKCS7Padding; // built in decryptor expects PKCS7 padding
      
          if (removePKCS7Padding) {
            try {
              var browserCrypto = self.crypto;
      
              if (browserCrypto) {
                this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
              }
            } catch (e) {
              /* no-op */
            }
          }
      
          if (this.subtle === null) {
            this.config.enableSoftwareAES = true;
          }
        }
      
        var _proto = Decrypter.prototype;
      
        _proto.destroy = function destroy() {
          // @ts-ignore
          this.observer = null;
        };
      
        _proto.isSync = function isSync() {
          return this.config.enableSoftwareAES;
        };
      
        _proto.flush = function flush() {
          var currentResult = this.currentResult;
      
          if (!currentResult) {
            this.reset();
            return;
          }
      
          var data = new Uint8Array(currentResult);
          this.reset();
      
          if (this.removePKCS7Padding) {
            return Object(_aes_decryptor__WEBPACK_IMPORTED_MODULE_2__["removePadding"])(data);
          }
      
          return data;
        };
      
        _proto.reset = function reset() {
          this.currentResult = null;
          this.currentIV = null;
          this.remainderData = null;
      
          if (this.softwareDecrypter) {
            this.softwareDecrypter = null;
          }
        };
      
        _proto.decrypt = function decrypt(data, key, iv, callback) {
          if (this.config.enableSoftwareAES) {
            this.softwareDecrypt(new Uint8Array(data), key, iv);
            var decryptResult = this.flush();
      
            if (decryptResult) {
              callback(decryptResult.buffer);
            }
          } else {
            this.webCryptoDecrypt(new Uint8Array(data), key, iv).then(callback);
          }
        };
      
        _proto.softwareDecrypt = function softwareDecrypt(data, key, iv) {
          var currentIV = this.currentIV,
              currentResult = this.currentResult,
              remainderData = this.remainderData;
          this.logOnce('JS AES decrypt'); // The output is staggered during progressive parsing - the current result is cached, and emitted on the next call
          // This is done in order to strip PKCS7 padding, which is found at the end of each segment. We only know we've reached
          // the end on flush(), but by that time we have already received all bytes for the segment.
          // Progressive decryption does not work with WebCrypto
      
          if (remainderData) {
            data = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__["appendUint8Array"])(remainderData, data);
            this.remainderData = null;
          } // Byte length must be a multiple of 16 (AES-128 = 128 bit blocks = 16 bytes)
      
      
          var currentChunk = this.getValidChunk(data);
      
          if (!currentChunk.length) {
            return null;
          }
      
          if (currentIV) {
            iv = currentIV;
          }
      
          var softwareDecrypter = this.softwareDecrypter;
      
          if (!softwareDecrypter) {
            softwareDecrypter = this.softwareDecrypter = new _aes_decryptor__WEBPACK_IMPORTED_MODULE_2__["default"]();
          }
      
          softwareDecrypter.expandKey(key);
          var result = currentResult;
          this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv);
          this.currentIV = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_5__["sliceUint8"])(currentChunk, -16).buffer;
      
          if (!result) {
            return null;
          }
      
          return result;
        };
      
        _proto.webCryptoDecrypt = function webCryptoDecrypt(data, key, iv) {
          var _this = this;
      
          var subtle = this.subtle;
      
          if (this.key !== key || !this.fastAesKey) {
            this.key = key;
            this.fastAesKey = new _fast_aes_key__WEBPACK_IMPORTED_MODULE_1__["default"](subtle, key);
          }
      
          return this.fastAesKey.expandKey().then(function (aesKey) {
            // decrypt using web crypto
            if (!subtle) {
              return Promise.reject(new Error('web crypto not initialized'));
            }
      
            var crypto = new _aes_crypto__WEBPACK_IMPORTED_MODULE_0__["default"](subtle, iv);
            return crypto.decrypt(data.buffer, aesKey);
          }).catch(function (err) {
            return _this.onWebCryptoError(err, data, key, iv);
          });
        };
      
        _proto.onWebCryptoError = function onWebCryptoError(err, data, key, iv) {
          _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('[decrypter.ts]: WebCrypto Error, disable WebCrypto API:', err);
          this.config.enableSoftwareAES = true;
          this.logEnabled = true;
          return this.softwareDecrypt(data, key, iv);
        };
      
        _proto.getValidChunk = function getValidChunk(data) {
          var currentChunk = data;
          var splitPoint = data.length - data.length % CHUNK_SIZE;
      
          if (splitPoint !== data.length) {
            currentChunk = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_5__["sliceUint8"])(data, 0, splitPoint);
            this.remainderData = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_5__["sliceUint8"])(data, splitPoint);
          }
      
          return currentChunk;
        };
      
        _proto.logOnce = function logOnce(msg) {
          if (!this.logEnabled) {
            return;
          }
      
          _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log("[decrypter.ts]: " + msg);
          this.logEnabled = false;
        };
      
        return Decrypter;
      }();
      
      
      
      /***/ }),
      
      /***/ "./src/crypt/fast-aes-key.ts":
      /*!***********************************!*\
        !*** ./src/crypt/fast-aes-key.ts ***!
        \***********************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return FastAESKey; });
      var FastAESKey = /*#__PURE__*/function () {
        function FastAESKey(subtle, key) {
          this.subtle = void 0;
          this.key = void 0;
          this.subtle = subtle;
          this.key = key;
        }
      
        var _proto = FastAESKey.prototype;
      
        _proto.expandKey = function expandKey() {
          return this.subtle.importKey('raw', this.key, {
            name: 'AES-CBC'
          }, false, ['encrypt', 'decrypt']);
        };
      
        return FastAESKey;
      }();
      
      
      
      /***/ }),
      
      /***/ "./src/demux/aacdemuxer.ts":
      /*!*********************************!*\
        !*** ./src/demux/aacdemuxer.ts ***!
        \*********************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony import */ var _base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base-audio-demuxer */ "./src/demux/base-audio-demuxer.ts");
      /* harmony import */ var _adts__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./adts */ "./src/demux/adts.ts");
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      /* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
      function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
      
      function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
      
      /**
       * AAC demuxer
       */
      
      
      
      
      
      var AACDemuxer = /*#__PURE__*/function (_BaseAudioDemuxer) {
        _inheritsLoose(AACDemuxer, _BaseAudioDemuxer);
      
        function AACDemuxer(observer, config) {
          var _this;
      
          _this = _BaseAudioDemuxer.call(this) || this;
          _this.observer = void 0;
          _this.config = void 0;
          _this.observer = observer;
          _this.config = config;
          return _this;
        }
      
        var _proto = AACDemuxer.prototype;
      
        _proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) {
          _BaseAudioDemuxer.prototype.resetInitSegment.call(this, audioCodec, videoCodec, duration);
      
          this._audioTrack = {
            container: 'audio/adts',
            type: 'audio',
            id: 2,
            pid: -1,
            sequenceNumber: 0,
            isAAC: true,
            samples: [],
            manifestCodec: audioCodec,
            duration: duration,
            inputTimeScale: 90000,
            dropped: 0
          };
        } // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS
        ;
      
        AACDemuxer.probe = function probe(data) {
          if (!data) {
            return false;
          } // Check for the ADTS sync word
          // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
          // Layer bits (position 14 and 15) in header should be always 0 for ADTS
          // More info https://wiki.multimedia.cx/index.php?title=ADTS
      
      
          var id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_3__["getID3Data"](data, 0) || [];
          var offset = id3Data.length;
      
          for (var length = data.length; offset < length; offset++) {
            if (_adts__WEBPACK_IMPORTED_MODULE_1__["probe"](data, offset)) {
              _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('ADTS sync word found !');
              return true;
            }
          }
      
          return false;
        };
      
        _proto.canParse = function canParse(data, offset) {
          return _adts__WEBPACK_IMPORTED_MODULE_1__["canParse"](data, offset);
        };
      
        _proto.appendFrame = function appendFrame(track, data, offset) {
          _adts__WEBPACK_IMPORTED_MODULE_1__["initTrackConfig"](track, this.observer, data, offset, track.manifestCodec);
          var frame = _adts__WEBPACK_IMPORTED_MODULE_1__["appendFrame"](track, data, offset, this.initPTS, this.frameIndex);
      
          if (frame && frame.missing === 0) {
            return frame;
          }
        };
      
        return AACDemuxer;
      }(_base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__["default"]);
      
      AACDemuxer.minProbeByteLength = 9;
      /* harmony default export */ __webpack_exports__["default"] = (AACDemuxer);
      
      /***/ }),
      
      /***/ "./src/demux/adts.ts":
      /*!***************************!*\
        !*** ./src/demux/adts.ts ***!
        \***************************/
      /*! exports provided: getAudioConfig, isHeaderPattern, getHeaderLength, getFullFrameLength, canGetFrameLength, isHeader, canParse, probe, initTrackConfig, getFrameDuration, parseFrameHeader, appendFrame */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getAudioConfig", function() { return getAudioConfig; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeaderPattern", function() { return isHeaderPattern; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getHeaderLength", function() { return getHeaderLength; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFullFrameLength", function() { return getFullFrameLength; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canGetFrameLength", function() { return canGetFrameLength; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeader", function() { return isHeader; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canParse", function() { return canParse; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "probe", function() { return probe; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initTrackConfig", function() { return initTrackConfig; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFrameDuration", function() { return getFrameDuration; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseFrameHeader", function() { return parseFrameHeader; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appendFrame", function() { return appendFrame; });
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
      /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ "./src/events.ts");
      /**
       * ADTS parser helper
       * @link https://wiki.multimedia.cx/index.php?title=ADTS
       */
      
      
      
      function getAudioConfig(observer, data, offset, audioCodec) {
        var adtsObjectType;
        var adtsExtensionSamplingIndex;
        var adtsChanelConfig;
        var config;
        var userAgent = navigator.userAgent.toLowerCase();
        var manifestCodec = audioCodec;
        var adtsSampleingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; // byte 2
      
        adtsObjectType = ((data[offset + 2] & 0xc0) >>> 6) + 1;
        var adtsSamplingIndex = (data[offset + 2] & 0x3c) >>> 2;
      
        if (adtsSamplingIndex > adtsSampleingRates.length - 1) {
          observer.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, {
            type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
            details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_PARSING_ERROR,
            fatal: true,
            reason: "invalid ADTS sampling index:" + adtsSamplingIndex
          });
          return;
        }
      
        adtsChanelConfig = (data[offset + 2] & 0x01) << 2; // byte 3
      
        adtsChanelConfig |= (data[offset + 3] & 0xc0) >>> 6;
        _utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].log("manifest codec:" + audioCodec + ", ADTS type:" + adtsObjectType + ", samplingIndex:" + adtsSamplingIndex); // firefox: freq less than 24kHz = AAC SBR (HE-AAC)
      
        if (/firefox/i.test(userAgent)) {
          if (adtsSamplingIndex >= 6) {
            adtsObjectType = 5;
            config = new Array(4); // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
            // there is a factor 2 between frame sample rate and output sample rate
            // multiply frequency by 2 (see table below, equivalent to substract 3)
      
            adtsExtensionSamplingIndex = adtsSamplingIndex - 3;
          } else {
            adtsObjectType = 2;
            config = new Array(2);
            adtsExtensionSamplingIndex = adtsSamplingIndex;
          } // Android : always use AAC
      
        } else if (userAgent.indexOf('android') !== -1) {
          adtsObjectType = 2;
          config = new Array(2);
          adtsExtensionSamplingIndex = adtsSamplingIndex;
        } else {
          /*  for other browsers (Chrome/Vivaldi/Opera ...)
              always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)
          */
          adtsObjectType = 5;
          config = new Array(4); // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)
      
          if (audioCodec && (audioCodec.indexOf('mp4a.40.29') !== -1 || audioCodec.indexOf('mp4a.40.5') !== -1) || !audioCodec && adtsSamplingIndex >= 6) {
            // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
            // there is a factor 2 between frame sample rate and output sample rate
            // multiply frequency by 2 (see table below, equivalent to substract 3)
            adtsExtensionSamplingIndex = adtsSamplingIndex - 3;
          } else {
            // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)
            // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC.  This is not a problem with stereo.
            if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && (adtsSamplingIndex >= 6 && adtsChanelConfig === 1 || /vivaldi/i.test(userAgent)) || !audioCodec && adtsChanelConfig === 1) {
              adtsObjectType = 2;
              config = new Array(2);
            }
      
            adtsExtensionSamplingIndex = adtsSamplingIndex;
          }
        }
        /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config
            ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()
          Audio Profile / Audio Object Type
          0: Null
          1: AAC Main
          2: AAC LC (Low Complexity)
          3: AAC SSR (Scalable Sample Rate)
          4: AAC LTP (Long Term Prediction)
          5: SBR (Spectral Band Replication)
          6: AAC Scalable
         sampling freq
          0: 96000 Hz
          1: 88200 Hz
          2: 64000 Hz
          3: 48000 Hz
          4: 44100 Hz
          5: 32000 Hz
          6: 24000 Hz
          7: 22050 Hz
          8: 16000 Hz
          9: 12000 Hz
          10: 11025 Hz
          11: 8000 Hz
          12: 7350 Hz
          13: Reserved
          14: Reserved
          15: frequency is written explictly
          Channel Configurations
          These are the channel configurations:
          0: Defined in AOT Specifc Config
          1: 1 channel: front-center
          2: 2 channels: front-left, front-right
        */
        // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1
      
      
        config[0] = adtsObjectType << 3; // samplingFrequencyIndex
      
        config[0] |= (adtsSamplingIndex & 0x0e) >> 1;
        config[1] |= (adtsSamplingIndex & 0x01) << 7; // channelConfiguration
      
        config[1] |= adtsChanelConfig << 3;
      
        if (adtsObjectType === 5) {
          // adtsExtensionSampleingIndex
          config[1] |= (adtsExtensionSamplingIndex & 0x0e) >> 1;
          config[2] = (adtsExtensionSamplingIndex & 0x01) << 7; // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???
          //    https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc
      
          config[2] |= 2 << 2;
          config[3] = 0;
        }
      
        return {
          config: config,
          samplerate: adtsSampleingRates[adtsSamplingIndex],
          channelCount: adtsChanelConfig,
          codec: 'mp4a.40.' + adtsObjectType,
          manifestCodec: manifestCodec
        };
      }
      function isHeaderPattern(data, offset) {
        return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;
      }
      function getHeaderLength(data, offset) {
        return data[offset + 1] & 0x01 ? 7 : 9;
      }
      function getFullFrameLength(data, offset) {
        return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xe0) >>> 5;
      }
      function canGetFrameLength(data, offset) {
        return offset + 5 < data.length;
      }
      function isHeader(data, offset) {
        // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
        // Layer bits (position 14 and 15) in header should be always 0 for ADTS
        // More info https://wiki.multimedia.cx/index.php?title=ADTS
        return offset + 1 < data.length && isHeaderPattern(data, offset);
      }
      function canParse(data, offset) {
        return canGetFrameLength(data, offset) && isHeaderPattern(data, offset) && getFullFrameLength(data, offset) <= data.length - offset;
      }
      function probe(data, offset) {
        // same as isHeader but we also check that ADTS frame follows last ADTS frame
        // or end of data is reached
        if (isHeader(data, offset)) {
          // ADTS header Length
          var headerLength = getHeaderLength(data, offset);
      
          if (offset + headerLength >= data.length) {
            return false;
          } // ADTS frame Length
      
      
          var frameLength = getFullFrameLength(data, offset);
      
          if (frameLength <= headerLength) {
            return false;
          }
      
          var newOffset = offset + frameLength;
          return newOffset === data.length || isHeader(data, newOffset);
        }
      
        return false;
      }
      function initTrackConfig(track, observer, data, offset, audioCodec) {
        if (!track.samplerate) {
          var config = getAudioConfig(observer, data, offset, audioCodec);
      
          if (!config) {
            return;
          }
      
          track.config = config.config;
          track.samplerate = config.samplerate;
          track.channelCount = config.channelCount;
          track.codec = config.codec;
          track.manifestCodec = config.manifestCodec;
          _utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].log("parsed codec:" + track.codec + ", rate:" + config.samplerate + ", channels:" + config.channelCount);
        }
      }
      function getFrameDuration(samplerate) {
        return 1024 * 90000 / samplerate;
      }
      function parseFrameHeader(data, offset, pts, frameIndex, frameDuration) {
        // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
        var headerLength = getHeaderLength(data, offset); // retrieve frame size
      
        var frameLength = getFullFrameLength(data, offset);
        frameLength -= headerLength;
      
        if (frameLength > 0) {
          var stamp = pts + frameIndex * frameDuration; // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
      
          return {
            headerLength: headerLength,
            frameLength: frameLength,
            stamp: stamp
          };
        }
      }
      function appendFrame(track, data, offset, pts, frameIndex) {
        var frameDuration = getFrameDuration(track.samplerate);
        var header = parseFrameHeader(data, offset, pts, frameIndex, frameDuration);
      
        if (header) {
          var frameLength = header.frameLength,
              headerLength = header.headerLength,
              stamp = header.stamp;
          var length = headerLength + frameLength;
          var missing = Math.max(0, offset + length - data.length); // logger.log(`AAC frame ${frameIndex}, pts:${stamp} length@offset/total: ${frameLength}@${offset+headerLength}/${data.byteLength} missing: ${missing}`);
      
          var unit;
      
          if (missing) {
            unit = new Uint8Array(length - headerLength);
            unit.set(data.subarray(offset + headerLength, data.length), 0);
          } else {
            unit = data.subarray(offset + headerLength, offset + length);
          }
      
          var sample = {
            unit: unit,
            pts: stamp
          };
      
          if (!missing) {
            track.samples.push(sample);
          }
      
          return {
            sample: sample,
            length: length,
            missing: missing
          };
        }
      }
      
      /***/ }),
      
      /***/ "./src/demux/base-audio-demuxer.ts":
      /*!*****************************************!*\
        !*** ./src/demux/base-audio-demuxer.ts ***!
        \*****************************************/
      /*! exports provided: initPTSFn, default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initPTSFn", function() { return initPTSFn; });
      /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
      /* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
      /* harmony import */ var _dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./dummy-demuxed-track */ "./src/demux/dummy-demuxed-track.ts");
      /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
      /* harmony import */ var _utils_typed_array__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/typed-array */ "./src/utils/typed-array.ts");
      
      
      
      
      
      
      var BaseAudioDemuxer = /*#__PURE__*/function () {
        function BaseAudioDemuxer() {
          this._audioTrack = void 0;
          this._id3Track = void 0;
          this.frameIndex = 0;
          this.cachedData = null;
          this.initPTS = null;
        }
      
        var _proto = BaseAudioDemuxer.prototype;
      
        _proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) {
          this._id3Track = {
            type: 'id3',
            id: 3,
            pid: -1,
            inputTimeScale: 90000,
            sequenceNumber: 0,
            samples: [],
            dropped: 0
          };
        };
      
        _proto.resetTimeStamp = function resetTimeStamp() {};
      
        _proto.resetContiguity = function resetContiguity() {};
      
        _proto.canParse = function canParse(data, offset) {
          return false;
        };
      
        _proto.appendFrame = function appendFrame(track, data, offset) {} // feed incoming data to the front of the parsing pipeline
        ;
      
        _proto.demux = function demux(data, timeOffset) {
          if (this.cachedData) {
            data = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_3__["appendUint8Array"])(this.cachedData, data);
            this.cachedData = null;
          }
      
          var id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_1__["getID3Data"](data, 0);
          var offset = id3Data ? id3Data.length : 0;
          var lastDataIndex;
          var pts;
          var track = this._audioTrack;
          var id3Track = this._id3Track;
          var timestamp = id3Data ? _demux_id3__WEBPACK_IMPORTED_MODULE_1__["getTimeStamp"](id3Data) : undefined;
          var length = data.length;
      
          if (this.frameIndex === 0 || this.initPTS === null) {
            this.initPTS = initPTSFn(timestamp, timeOffset);
          } // more expressive than alternative: id3Data?.length
      
      
          if (id3Data && id3Data.length > 0) {
            id3Track.samples.push({
              pts: this.initPTS,
              dts: this.initPTS,
              data: id3Data
            });
          }
      
          pts = this.initPTS;
      
          while (offset < length) {
            if (this.canParse(data, offset)) {
              var frame = this.appendFrame(track, data, offset);
      
              if (frame) {
                this.frameIndex++;
                pts = frame.sample.pts;
                offset += frame.length;
                lastDataIndex = offset;
              } else {
                offset = length;
              }
            } else if (_demux_id3__WEBPACK_IMPORTED_MODULE_1__["canParse"](data, offset)) {
              // after a ID3.canParse, a call to ID3.getID3Data *should* always returns some data
              id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_1__["getID3Data"](data, offset);
              id3Track.samples.push({
                pts: pts,
                dts: pts,
                data: id3Data
              });
              offset += id3Data.length;
              lastDataIndex = offset;
            } else {
              offset++;
            }
      
            if (offset === length && lastDataIndex !== length) {
              var partialData = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_4__["sliceUint8"])(data, lastDataIndex);
      
              if (this.cachedData) {
                this.cachedData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_3__["appendUint8Array"])(this.cachedData, partialData);
              } else {
                this.cachedData = partialData;
              }
            }
          }
      
          return {
            audioTrack: track,
            avcTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__["dummyTrack"])(),
            id3Track: id3Track,
            textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__["dummyTrack"])()
          };
        };
      
        _proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
          return Promise.reject(new Error("[" + this + "] This demuxer does not support Sample-AES decryption"));
        };
      
        _proto.flush = function flush(timeOffset) {
          // Parse cache in case of remaining frames.
          var cachedData = this.cachedData;
      
          if (cachedData) {
            this.cachedData = null;
            this.demux(cachedData, 0);
          }
      
          this.frameIndex = 0;
          return {
            audioTrack: this._audioTrack,
            avcTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__["dummyTrack"])(),
            id3Track: this._id3Track,
            textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__["dummyTrack"])()
          };
        };
      
        _proto.destroy = function destroy() {};
      
        return BaseAudioDemuxer;
      }();
      /**
       * Initialize PTS
       * <p>
       *    use timestamp unless it is undefined, NaN or Infinity
       * </p>
       */
      
      
      var initPTSFn = function initPTSFn(timestamp, timeOffset) {
        return Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(timestamp) ? timestamp * 90 : timeOffset * 90000;
      };
      /* harmony default export */ __webpack_exports__["default"] = (BaseAudioDemuxer);
      
      /***/ }),
      
      /***/ "./src/demux/chunk-cache.ts":
      /*!**********************************!*\
        !*** ./src/demux/chunk-cache.ts ***!
        \**********************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ChunkCache; });
      var ChunkCache = /*#__PURE__*/function () {
        function ChunkCache() {
          this.chunks = [];
          this.dataLength = 0;
        }
      
        var _proto = ChunkCache.prototype;
      
        _proto.push = function push(chunk) {
          this.chunks.push(chunk);
          this.dataLength += chunk.length;
        };
      
        _proto.flush = function flush() {
          var chunks = this.chunks,
              dataLength = this.dataLength;
          var result;
      
          if (!chunks.length) {
            return new Uint8Array(0);
          } else if (chunks.length === 1) {
            result = chunks[0];
          } else {
            result = concatUint8Arrays(chunks, dataLength);
          }
      
          this.reset();
          return result;
        };
      
        _proto.reset = function reset() {
          this.chunks.length = 0;
          this.dataLength = 0;
        };
      
        return ChunkCache;
      }();
      
      
      
      function concatUint8Arrays(chunks, dataLength) {
        var result = new Uint8Array(dataLength);
        var offset = 0;
      
        for (var i = 0; i < chunks.length; i++) {
          var chunk = chunks[i];
          result.set(chunk, offset);
          offset += chunk.length;
        }
      
        return result;
      }
      
      /***/ }),
      
      /***/ "./src/demux/dummy-demuxed-track.ts":
      /*!******************************************!*\
        !*** ./src/demux/dummy-demuxed-track.ts ***!
        \******************************************/
      /*! exports provided: dummyTrack */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dummyTrack", function() { return dummyTrack; });
      function dummyTrack() {
        return {
          type: '',
          id: -1,
          pid: -1,
          inputTimeScale: 90000,
          sequenceNumber: -1,
          samples: [],
          dropped: 0
        };
      }
      
      /***/ }),
      
      /***/ "./src/demux/exp-golomb.ts":
      /*!*********************************!*\
        !*** ./src/demux/exp-golomb.ts ***!
        \*********************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      /**
       * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.
       */
      
      
      var ExpGolomb = /*#__PURE__*/function () {
        function ExpGolomb(data) {
          this.data = void 0;
          this.bytesAvailable = void 0;
          this.word = void 0;
          this.bitsAvailable = void 0;
          this.data = data; // the number of bytes left to examine in this.data
      
          this.bytesAvailable = data.byteLength; // the current word being examined
      
          this.word = 0; // :uint
          // the number of bits left to examine in the current word
      
          this.bitsAvailable = 0; // :uint
        } // ():void
      
      
        var _proto = ExpGolomb.prototype;
      
        _proto.loadWord = function loadWord() {
          var data = this.data;
          var bytesAvailable = this.bytesAvailable;
          var position = data.byteLength - bytesAvailable;
          var workingBytes = new Uint8Array(4);
          var availableBytes = Math.min(4, bytesAvailable);
      
          if (availableBytes === 0) {
            throw new Error('no bytes available');
          }
      
          workingBytes.set(data.subarray(position, position + availableBytes));
          this.word = new DataView(workingBytes.buffer).getUint32(0); // track the amount of this.data that has been processed
      
          this.bitsAvailable = availableBytes * 8;
          this.bytesAvailable -= availableBytes;
        } // (count:int):void
        ;
      
        _proto.skipBits = function skipBits(count) {
          var skipBytes; // :int
      
          if (this.bitsAvailable > count) {
            this.word <<= count;
            this.bitsAvailable -= count;
          } else {
            count -= this.bitsAvailable;
            skipBytes = count >> 3;
            count -= skipBytes >> 3;
            this.bytesAvailable -= skipBytes;
            this.loadWord();
            this.word <<= count;
            this.bitsAvailable -= count;
          }
        } // (size:int):uint
        ;
      
        _proto.readBits = function readBits(size) {
          var bits = Math.min(this.bitsAvailable, size); // :uint
      
          var valu = this.word >>> 32 - bits; // :uint
      
          if (size > 32) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].error('Cannot read more than 32 bits at a time');
          }
      
          this.bitsAvailable -= bits;
      
          if (this.bitsAvailable > 0) {
            this.word <<= bits;
          } else if (this.bytesAvailable > 0) {
            this.loadWord();
          }
      
          bits = size - bits;
      
          if (bits > 0 && this.bitsAvailable) {
            return valu << bits | this.readBits(bits);
          } else {
            return valu;
          }
        } // ():uint
        ;
      
        _proto.skipLZ = function skipLZ() {
          var leadingZeroCount; // :uint
      
          for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
            if ((this.word & 0x80000000 >>> leadingZeroCount) !== 0) {
              // the first bit of working word is 1
              this.word <<= leadingZeroCount;
              this.bitsAvailable -= leadingZeroCount;
              return leadingZeroCount;
            }
          } // we exhausted word and still have not found a 1
      
      
          this.loadWord();
          return leadingZeroCount + this.skipLZ();
        } // ():void
        ;
      
        _proto.skipUEG = function skipUEG() {
          this.skipBits(1 + this.skipLZ());
        } // ():void
        ;
      
        _proto.skipEG = function skipEG() {
          this.skipBits(1 + this.skipLZ());
        } // ():uint
        ;
      
        _proto.readUEG = function readUEG() {
          var clz = this.skipLZ(); // :uint
      
          return this.readBits(clz + 1) - 1;
        } // ():int
        ;
      
        _proto.readEG = function readEG() {
          var valu = this.readUEG(); // :int
      
          if (0x01 & valu) {
            // the number is odd if the low order bit is set
            return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
          } else {
            return -1 * (valu >>> 1); // divide by two then make it negative
          }
        } // Some convenience functions
        // :Boolean
        ;
      
        _proto.readBoolean = function readBoolean() {
          return this.readBits(1) === 1;
        } // ():int
        ;
      
        _proto.readUByte = function readUByte() {
          return this.readBits(8);
        } // ():int
        ;
      
        _proto.readUShort = function readUShort() {
          return this.readBits(16);
        } // ():int
        ;
      
        _proto.readUInt = function readUInt() {
          return this.readBits(32);
        }
        /**
         * Advance the ExpGolomb decoder past a scaling list. The scaling
         * list is optionally transmitted as part of a sequence parameter
         * set and is not relevant to transmuxing.
         * @param count the number of entries in this scaling list
         * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
         */
        ;
      
        _proto.skipScalingList = function skipScalingList(count) {
          var lastScale = 8;
          var nextScale = 8;
          var deltaScale;
      
          for (var j = 0; j < count; j++) {
            if (nextScale !== 0) {
              deltaScale = this.readEG();
              nextScale = (lastScale + deltaScale + 256) % 256;
            }
      
            lastScale = nextScale === 0 ? lastScale : nextScale;
          }
        }
        /**
         * Read a sequence parameter set and return some interesting video
         * properties. A sequence parameter set is the H264 metadata that
         * describes the properties of upcoming video frames.
         * @param data {Uint8Array} the bytes of a sequence parameter set
         * @return {object} an object with configuration parsed from the
         * sequence parameter set, including the dimensions of the
         * associated video frames.
         */
        ;
      
        _proto.readSPS = function readSPS() {
          var frameCropLeftOffset = 0;
          var frameCropRightOffset = 0;
          var frameCropTopOffset = 0;
          var frameCropBottomOffset = 0;
          var numRefFramesInPicOrderCntCycle;
          var scalingListCount;
          var i;
          var readUByte = this.readUByte.bind(this);
          var readBits = this.readBits.bind(this);
          var readUEG = this.readUEG.bind(this);
          var readBoolean = this.readBoolean.bind(this);
          var skipBits = this.skipBits.bind(this);
          var skipEG = this.skipEG.bind(this);
          var skipUEG = this.skipUEG.bind(this);
          var skipScalingList = this.skipScalingList.bind(this);
          readUByte();
          var profileIdc = readUByte(); // profile_idc
      
          readBits(5); // profileCompat constraint_set[0-4]_flag, u(5)
      
          skipBits(3); // reserved_zero_3bits u(3),
      
          readUByte(); // level_idc u(8)
      
          skipUEG(); // seq_parameter_set_id
          // some profiles have more optional data we don't need
      
          if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
            var chromaFormatIdc = readUEG();
      
            if (chromaFormatIdc === 3) {
              skipBits(1);
            } // separate_colour_plane_flag
      
      
            skipUEG(); // bit_depth_luma_minus8
      
            skipUEG(); // bit_depth_chroma_minus8
      
            skipBits(1); // qpprime_y_zero_transform_bypass_flag
      
            if (readBoolean()) {
              // seq_scaling_matrix_present_flag
              scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
      
              for (i = 0; i < scalingListCount; i++) {
                if (readBoolean()) {
                  // seq_scaling_list_present_flag[ i ]
                  if (i < 6) {
                    skipScalingList(16);
                  } else {
                    skipScalingList(64);
                  }
                }
              }
            }
          }
      
          skipUEG(); // log2_max_frame_num_minus4
      
          var picOrderCntType = readUEG();
      
          if (picOrderCntType === 0) {
            readUEG(); // log2_max_pic_order_cnt_lsb_minus4
          } else if (picOrderCntType === 1) {
            skipBits(1); // delta_pic_order_always_zero_flag
      
            skipEG(); // offset_for_non_ref_pic
      
            skipEG(); // offset_for_top_to_bottom_field
      
            numRefFramesInPicOrderCntCycle = readUEG();
      
            for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
              skipEG();
            } // offset_for_ref_frame[ i ]
      
          }
      
          skipUEG(); // max_num_ref_frames
      
          skipBits(1); // gaps_in_frame_num_value_allowed_flag
      
          var picWidthInMbsMinus1 = readUEG();
          var picHeightInMapUnitsMinus1 = readUEG();
          var frameMbsOnlyFlag = readBits(1);
      
          if (frameMbsOnlyFlag === 0) {
            skipBits(1);
          } // mb_adaptive_frame_field_flag
      
      
          skipBits(1); // direct_8x8_inference_flag
      
          if (readBoolean()) {
            // frame_cropping_flag
            frameCropLeftOffset = readUEG();
            frameCropRightOffset = readUEG();
            frameCropTopOffset = readUEG();
            frameCropBottomOffset = readUEG();
          }
      
          var pixelRatio = [1, 1];
      
          if (readBoolean()) {
            // vui_parameters_present_flag
            if (readBoolean()) {
              // aspect_ratio_info_present_flag
              var aspectRatioIdc = readUByte();
      
              switch (aspectRatioIdc) {
                case 1:
                  pixelRatio = [1, 1];
                  break;
      
                case 2:
                  pixelRatio = [12, 11];
                  break;
      
                case 3:
                  pixelRatio = [10, 11];
                  break;
      
                case 4:
                  pixelRatio = [16, 11];
                  break;
      
                case 5:
                  pixelRatio = [40, 33];
                  break;
      
                case 6:
                  pixelRatio = [24, 11];
                  break;
      
                case 7:
                  pixelRatio = [20, 11];
                  break;
      
                case 8:
                  pixelRatio = [32, 11];
                  break;
      
                case 9:
                  pixelRatio = [80, 33];
                  break;
      
                case 10:
                  pixelRatio = [18, 11];
                  break;
      
                case 11:
                  pixelRatio = [15, 11];
                  break;
      
                case 12:
                  pixelRatio = [64, 33];
                  break;
      
                case 13:
                  pixelRatio = [160, 99];
                  break;
      
                case 14:
                  pixelRatio = [4, 3];
                  break;
      
                case 15:
                  pixelRatio = [3, 2];
                  break;
      
                case 16:
                  pixelRatio = [2, 1];
                  break;
      
                case 255:
                  {
                    pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
                    break;
                  }
              }
            }
          }
      
          return {
            width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),
            height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),
            pixelRatio: pixelRatio
          };
        };
      
        _proto.readSliceType = function readSliceType() {
          // skip NALu type
          this.readUByte(); // discard first_mb_in_slice
      
          this.readUEG(); // return slice_type
      
          return this.readUEG();
        };
      
        return ExpGolomb;
      }();
      
      /* harmony default export */ __webpack_exports__["default"] = (ExpGolomb);
      
      /***/ }),
      
      /***/ "./src/demux/id3.ts":
      /*!**************************!*\
        !*** ./src/demux/id3.ts ***!
        \**************************/
      /*! exports provided: isHeader, isFooter, getID3Data, canParse, getTimeStamp, isTimeStampFrame, getID3Frames, decodeFrame, utf8ArrayToStr, testables */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeader", function() { return isHeader; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFooter", function() { return isFooter; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getID3Data", function() { return getID3Data; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canParse", function() { return canParse; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getTimeStamp", function() { return getTimeStamp; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isTimeStampFrame", function() { return isTimeStampFrame; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getID3Frames", function() { return getID3Frames; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "decodeFrame", function() { return decodeFrame; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "utf8ArrayToStr", function() { return utf8ArrayToStr; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "testables", function() { return testables; });
      // breaking up those two types in order to clarify what is happening in the decoding path.
      
      /**
       * Returns true if an ID3 header can be found at offset in data
       * @param {Uint8Array} data - The data to search in
       * @param {number} offset - The offset at which to start searching
       * @return {boolean} - True if an ID3 header is found
       */
      var isHeader = function isHeader(data, offset) {
        /*
         * http://id3.org/id3v2.3.0
         * [0]     = 'I'
         * [1]     = 'D'
         * [2]     = '3'
         * [3,4]   = {Version}
         * [5]     = {Flags}
         * [6-9]   = {ID3 Size}
         *
         * An ID3v2 tag can be detected with the following pattern:
         *  $49 44 33 yy yy xx zz zz zz zz
         * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80
         */
        if (offset + 10 <= data.length) {
          // look for 'ID3' identifier
          if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) {
            // check version is within range
            if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {
              // check size is within range
              if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
                return true;
              }
            }
          }
        }
      
        return false;
      };
      /**
       * Returns true if an ID3 footer can be found at offset in data
       * @param {Uint8Array} data - The data to search in
       * @param {number} offset - The offset at which to start searching
       * @return {boolean} - True if an ID3 footer is found
       */
      
      var isFooter = function isFooter(data, offset) {
        /*
         * The footer is a copy of the header, but with a different identifier
         */
        if (offset + 10 <= data.length) {
          // look for '3DI' identifier
          if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) {
            // check version is within range
            if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {
              // check size is within range
              if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
                return true;
              }
            }
          }
        }
      
        return false;
      };
      /**
       * Returns any adjacent ID3 tags found in data starting at offset, as one block of data
       * @param {Uint8Array} data - The data to search in
       * @param {number} offset - The offset at which to start searching
       * @return {Uint8Array | undefined} - The block of data containing any ID3 tags found
       * or *undefined* if no header is found at the starting offset
       */
      
      var getID3Data = function getID3Data(data, offset) {
        var front = offset;
        var length = 0;
      
        while (isHeader(data, offset)) {
          // ID3 header is 10 bytes
          length += 10;
          var size = readSize(data, offset + 6);
          length += size;
      
          if (isFooter(data, offset + 10)) {
            // ID3 footer is 10 bytes
            length += 10;
          }
      
          offset += length;
        }
      
        if (length > 0) {
          return data.subarray(front, front + length);
        }
      
        return undefined;
      };
      
      var readSize = function readSize(data, offset) {
        var size = 0;
        size = (data[offset] & 0x7f) << 21;
        size |= (data[offset + 1] & 0x7f) << 14;
        size |= (data[offset + 2] & 0x7f) << 7;
        size |= data[offset + 3] & 0x7f;
        return size;
      };
      
      var canParse = function canParse(data, offset) {
        return isHeader(data, offset) && readSize(data, offset + 6) + 10 <= data.length - offset;
      };
      /**
       * Searches for the Elementary Stream timestamp found in the ID3 data chunk
       * @param {Uint8Array} data - Block of data containing one or more ID3 tags
       * @return {number | undefined} - The timestamp
       */
      
      var getTimeStamp = function getTimeStamp(data) {
        var frames = getID3Frames(data);
      
        for (var i = 0; i < frames.length; i++) {
          var frame = frames[i];
      
          if (isTimeStampFrame(frame)) {
            return readTimeStamp(frame);
          }
        }
      
        return undefined;
      };
      /**
       * Returns true if the ID3 frame is an Elementary Stream timestamp frame
       * @param {ID3 frame} frame
       */
      
      var isTimeStampFrame = function isTimeStampFrame(frame) {
        return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp';
      };
      
      var getFrameData = function getFrameData(data) {
        /*
        Frame ID       $xx xx xx xx (four characters)
        Size           $xx xx xx xx
        Flags          $xx xx
        */
        var type = String.fromCharCode(data[0], data[1], data[2], data[3]);
        var size = readSize(data, 4); // skip frame id, size, and flags
      
        var offset = 10;
        return {
          type: type,
          size: size,
          data: data.subarray(offset, offset + size)
        };
      };
      /**
       * Returns an array of ID3 frames found in all the ID3 tags in the id3Data
       * @param {Uint8Array} id3Data - The ID3 data containing one or more ID3 tags
       * @return {ID3.Frame[]} - Array of ID3 frame objects
       */
      
      
      var getID3Frames = function getID3Frames(id3Data) {
        var offset = 0;
        var frames = [];
      
        while (isHeader(id3Data, offset)) {
          var size = readSize(id3Data, offset + 6); // skip past ID3 header
      
          offset += 10;
          var end = offset + size; // loop through frames in the ID3 tag
      
          while (offset + 8 < end) {
            var frameData = getFrameData(id3Data.subarray(offset));
            var frame = decodeFrame(frameData);
      
            if (frame) {
              frames.push(frame);
            } // skip frame header and frame data
      
      
            offset += frameData.size + 10;
          }
      
          if (isFooter(id3Data, offset)) {
            offset += 10;
          }
        }
      
        return frames;
      };
      var decodeFrame = function decodeFrame(frame) {
        if (frame.type === 'PRIV') {
          return decodePrivFrame(frame);
        } else if (frame.type[0] === 'W') {
          return decodeURLFrame(frame);
        }
      
        return decodeTextFrame(frame);
      };
      
      var decodePrivFrame = function decodePrivFrame(frame) {
        /*
        Format: <text string>\0<binary data>
        */
        if (frame.size < 2) {
          return undefined;
        }
      
        var owner = utf8ArrayToStr(frame.data, true);
        var privateData = new Uint8Array(frame.data.subarray(owner.length + 1));
        return {
          key: frame.type,
          info: owner,
          data: privateData.buffer
        };
      };
      
      var decodeTextFrame = function decodeTextFrame(frame) {
        if (frame.size < 2) {
          return undefined;
        }
      
        if (frame.type === 'TXXX') {
          /*
          Format:
          [0]   = {Text Encoding}
          [1-?] = {Description}\0{Value}
          */
          var index = 1;
          var description = utf8ArrayToStr(frame.data.subarray(index), true);
          index += description.length + 1;
          var value = utf8ArrayToStr(frame.data.subarray(index));
          return {
            key: frame.type,
            info: description,
            data: value
          };
        }
        /*
        Format:
        [0]   = {Text Encoding}
        [1-?] = {Value}
        */
      
      
        var text = utf8ArrayToStr(frame.data.subarray(1));
        return {
          key: frame.type,
          data: text
        };
      };
      
      var decodeURLFrame = function decodeURLFrame(frame) {
        if (frame.type === 'WXXX') {
          /*
          Format:
          [0]   = {Text Encoding}
          [1-?] = {Description}\0{URL}
          */
          if (frame.size < 2) {
            return undefined;
          }
      
          var index = 1;
          var description = utf8ArrayToStr(frame.data.subarray(index), true);
          index += description.length + 1;
          var value = utf8ArrayToStr(frame.data.subarray(index));
          return {
            key: frame.type,
            info: description,
            data: value
          };
        }
        /*
        Format:
        [0-?] = {URL}
        */
      
      
        var url = utf8ArrayToStr(frame.data);
        return {
          key: frame.type,
          data: url
        };
      };
      
      var readTimeStamp = function readTimeStamp(timeStampFrame) {
        if (timeStampFrame.data.byteLength === 8) {
          var data = new Uint8Array(timeStampFrame.data); // timestamp is 33 bit expressed as a big-endian eight-octet number,
          // with the upper 31 bits set to zero.
      
          var pts33Bit = data[3] & 0x1;
          var timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];
          timestamp /= 45;
      
          if (pts33Bit) {
            timestamp += 47721858.84;
          } // 2^32 / 90
      
      
          return Math.round(timestamp);
        }
      
        return undefined;
      }; // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197
      // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
      
      /* utf.js - UTF-8 <=> UTF-16 convertion
       *
       * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
       * Version: 1.0
       * LastModified: Dec 25 1999
       * This library is free.  You can redistribute it and/or modify it.
       */
      
      
      var utf8ArrayToStr = function utf8ArrayToStr(array, exitOnNull) {
        if (exitOnNull === void 0) {
          exitOnNull = false;
        }
      
        var decoder = getTextDecoder();
      
        if (decoder) {
          var decoded = decoder.decode(array);
      
          if (exitOnNull) {
            // grab up to the first null
            var idx = decoded.indexOf('\0');
            return idx !== -1 ? decoded.substring(0, idx) : decoded;
          } // remove any null characters
      
      
          return decoded.replace(/\0/g, '');
        }
      
        var len = array.length;
        var c;
        var char2;
        var char3;
        var out = '';
        var i = 0;
      
        while (i < len) {
          c = array[i++];
      
          if (c === 0x00 && exitOnNull) {
            return out;
          } else if (c === 0x00 || c === 0x03) {
            // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it
            continue;
          }
      
          switch (c >> 4) {
            case 0:
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
              // 0xxxxxxx
              out += String.fromCharCode(c);
              break;
      
            case 12:
            case 13:
              // 110x xxxx   10xx xxxx
              char2 = array[i++];
              out += String.fromCharCode((c & 0x1f) << 6 | char2 & 0x3f);
              break;
      
            case 14:
              // 1110 xxxx  10xx xxxx  10xx xxxx
              char2 = array[i++];
              char3 = array[i++];
              out += String.fromCharCode((c & 0x0f) << 12 | (char2 & 0x3f) << 6 | (char3 & 0x3f) << 0);
              break;
      
            default:
          }
        }
      
        return out;
      };
      var testables = {
        decodeTextFrame: decodeTextFrame
      };
      var decoder;
      
      function getTextDecoder() {
        if (!decoder && typeof self.TextDecoder !== 'undefined') {
          decoder = new self.TextDecoder('utf-8');
        }
      
        return decoder;
      }
      
      /***/ }),
      
      /***/ "./src/demux/mp3demuxer.ts":
      /*!*********************************!*\
        !*** ./src/demux/mp3demuxer.ts ***!
        \*********************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony import */ var _base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base-audio-demuxer */ "./src/demux/base-audio-demuxer.ts");
      /* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      /* harmony import */ var _mpegaudio__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./mpegaudio */ "./src/demux/mpegaudio.ts");
      function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
      
      function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
      
      /**
       * MP3 demuxer
       */
      
      
      
      
      
      var MP3Demuxer = /*#__PURE__*/function (_BaseAudioDemuxer) {
        _inheritsLoose(MP3Demuxer, _BaseAudioDemuxer);
      
        function MP3Demuxer() {
          return _BaseAudioDemuxer.apply(this, arguments) || this;
        }
      
        var _proto = MP3Demuxer.prototype;
      
        _proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) {
          _BaseAudioDemuxer.prototype.resetInitSegment.call(this, audioCodec, videoCodec, duration);
      
          this._audioTrack = {
            container: 'audio/mpeg',
            type: 'audio',
            id: 2,
            pid: -1,
            sequenceNumber: 0,
            isAAC: false,
            samples: [],
            manifestCodec: audioCodec,
            duration: duration,
            inputTimeScale: 90000,
            dropped: 0
          };
        };
      
        MP3Demuxer.probe = function probe(data) {
          if (!data) {
            return false;
          } // check if data contains ID3 timestamp and MPEG sync word
          // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
          // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
          // More info http://www.mp3-tech.org/programmer/frame_header.html
      
      
          var id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_1__["getID3Data"](data, 0) || [];
          var offset = id3Data.length;
      
          for (var length = data.length; offset < length; offset++) {
            if (_mpegaudio__WEBPACK_IMPORTED_MODULE_3__["probe"](data, offset)) {
              _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('MPEG Audio sync word found !');
              return true;
            }
          }
      
          return false;
        };
      
        _proto.canParse = function canParse(data, offset) {
          return _mpegaudio__WEBPACK_IMPORTED_MODULE_3__["canParse"](data, offset);
        };
      
        _proto.appendFrame = function appendFrame(track, data, offset) {
          if (this.initPTS === null) {
            return;
          }
      
          return _mpegaudio__WEBPACK_IMPORTED_MODULE_3__["appendFrame"](track, data, offset, this.initPTS, this.frameIndex);
        };
      
        return MP3Demuxer;
      }(_base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__["default"]);
      
      MP3Demuxer.minProbeByteLength = 4;
      /* harmony default export */ __webpack_exports__["default"] = (MP3Demuxer);
      
      /***/ }),
      
      /***/ "./src/demux/mp4demuxer.ts":
      /*!*********************************!*\
        !*** ./src/demux/mp4demuxer.ts ***!
        \*********************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
      /* harmony import */ var _dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./dummy-demuxed-track */ "./src/demux/dummy-demuxed-track.ts");
      /**
       * MP4 demuxer
       */
      
      
      
      var MP4Demuxer = /*#__PURE__*/function () {
        function MP4Demuxer(observer, config) {
          this.remainderData = null;
          this.config = void 0;
          this.config = config;
        }
      
        var _proto = MP4Demuxer.prototype;
      
        _proto.resetTimeStamp = function resetTimeStamp() {};
      
        _proto.resetInitSegment = function resetInitSegment() {};
      
        _proto.resetContiguity = function resetContiguity() {};
      
        MP4Demuxer.probe = function probe(data) {
          // ensure we find a moof box in the first 16 kB
          return Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__["findBox"])({
            data: data,
            start: 0,
            end: Math.min(data.length, 16384)
          }, ['moof']).length > 0;
        };
      
        _proto.demux = function demux(data) {
          // Load all data into the avc track. The CMAF remuxer will look for the data in the samples object; the rest of the fields do not matter
          var avcSamples = data;
          var avcTrack = Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])();
      
          if (this.config.progressive) {
            // Split the bytestream into two ranges: one encompassing all data up until the start of the last moof, and everything else.
            // This is done to guarantee that we're sending valid data to MSE - when demuxing progressively, we have no guarantee
            // that the fetch loader gives us flush moof+mdat pairs. If we push jagged data to MSE, it will throw an exception.
            if (this.remainderData) {
              avcSamples = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__["appendUint8Array"])(this.remainderData, data);
            }
      
            var segmentedData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__["segmentValidRange"])(avcSamples);
            this.remainderData = segmentedData.remainder;
            avcTrack.samples = segmentedData.valid || new Uint8Array();
          } else {
            avcTrack.samples = avcSamples;
          }
      
          return {
            audioTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(),
            avcTrack: avcTrack,
            id3Track: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(),
            textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])()
          };
        };
      
        _proto.flush = function flush() {
          var avcTrack = Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])();
          avcTrack.samples = this.remainderData || new Uint8Array();
          this.remainderData = null;
          return {
            audioTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(),
            avcTrack: avcTrack,
            id3Track: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(),
            textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])()
          };
        };
      
        _proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
          return Promise.reject(new Error('The MP4 demuxer does not support SAMPLE-AES decryption'));
        };
      
        _proto.destroy = function destroy() {};
      
        return MP4Demuxer;
      }();
      
      MP4Demuxer.minProbeByteLength = 1024;
      /* harmony default export */ __webpack_exports__["default"] = (MP4Demuxer);
      
      /***/ }),
      
      /***/ "./src/demux/mpegaudio.ts":
      /*!********************************!*\
        !*** ./src/demux/mpegaudio.ts ***!
        \********************************/
      /*! exports provided: appendFrame, parseHeader, isHeaderPattern, isHeader, canParse, probe */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appendFrame", function() { return appendFrame; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseHeader", function() { return parseHeader; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeaderPattern", function() { return isHeaderPattern; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeader", function() { return isHeader; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canParse", function() { return canParse; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "probe", function() { return probe; });
      /**
       *  MPEG parser helper
       */
      var chromeVersion = null;
      var BitratesMap = [32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160];
      var SamplingRateMap = [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000];
      var SamplesCoefficients = [// MPEG 2.5
      [0, // Reserved
      72, // Layer3
      144, // Layer2
      12 // Layer1
      ], // Reserved
      [0, // Reserved
      0, // Layer3
      0, // Layer2
      0 // Layer1
      ], // MPEG 2
      [0, // Reserved
      72, // Layer3
      144, // Layer2
      12 // Layer1
      ], // MPEG 1
      [0, // Reserved
      144, // Layer3
      144, // Layer2
      12 // Layer1
      ]];
      var BytesInSlot = [0, // Reserved
      1, // Layer3
      1, // Layer2
      4 // Layer1
      ];
      function appendFrame(track, data, offset, pts, frameIndex) {
        // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference
        if (offset + 24 > data.length) {
          return;
        }
      
        var header = parseHeader(data, offset);
      
        if (header && offset + header.frameLength <= data.length) {
          var frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;
          var stamp = pts + frameIndex * frameDuration;
          var sample = {
            unit: data.subarray(offset, offset + header.frameLength),
            pts: stamp,
            dts: stamp
          };
          track.config = [];
          track.channelCount = header.channelCount;
          track.samplerate = header.sampleRate;
          track.samples.push(sample);
          return {
            sample: sample,
            length: header.frameLength,
            missing: 0
          };
        }
      }
      function parseHeader(data, offset) {
        var mpegVersion = data[offset + 1] >> 3 & 3;
        var mpegLayer = data[offset + 1] >> 1 & 3;
        var bitRateIndex = data[offset + 2] >> 4 & 15;
        var sampleRateIndex = data[offset + 2] >> 2 & 3;
      
        if (mpegVersion !== 1 && bitRateIndex !== 0 && bitRateIndex !== 15 && sampleRateIndex !== 3) {
          var paddingBit = data[offset + 2] >> 1 & 1;
          var channelMode = data[offset + 3] >> 6;
          var columnInBitrates = mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4;
          var bitRate = BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1000;
          var columnInSampleRates = mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2;
          var sampleRate = SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex];
          var channelCount = channelMode === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)
      
          var sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer];
          var bytesInSlot = BytesInSlot[mpegLayer];
          var samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;
          var frameLength = Math.floor(sampleCoefficient * bitRate / sampleRate + paddingBit) * bytesInSlot;
      
          if (chromeVersion === null) {
            var userAgent = navigator.userAgent || '';
            var result = userAgent.match(/Chrome\/(\d+)/i);
            chromeVersion = result ? parseInt(result[1]) : 0;
          }
      
          var needChromeFix = !!chromeVersion && chromeVersion <= 87;
      
          if (needChromeFix && mpegLayer === 2 && bitRate >= 224000 && channelMode === 0) {
            // Work around bug in Chromium by setting channelMode to dual-channel (01) instead of stereo (00)
            data[offset + 3] = data[offset + 3] | 0x80;
          }
      
          return {
            sampleRate: sampleRate,
            channelCount: channelCount,
            frameLength: frameLength,
            samplesPerFrame: samplesPerFrame
          };
        }
      }
      function isHeaderPattern(data, offset) {
        return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;
      }
      function isHeader(data, offset) {
        // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
        // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
        // More info http://www.mp3-tech.org/programmer/frame_header.html
        return offset + 1 < data.length && isHeaderPattern(data, offset);
      }
      function canParse(data, offset) {
        var headerSize = 4;
        return isHeaderPattern(data, offset) && headerSize <= data.length - offset;
      }
      function probe(data, offset) {
        // same as isHeader but we also check that MPEG frame follows last MPEG frame
        // or end of data is reached
        if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
          // MPEG header Length
          var headerLength = 4; // MPEG frame Length
      
          var header = parseHeader(data, offset);
          var frameLength = headerLength;
      
          if (header !== null && header !== void 0 && header.frameLength) {
            frameLength = header.frameLength;
          }
      
          var newOffset = offset + frameLength;
          return newOffset === data.length || isHeader(data, newOffset);
        }
      
        return false;
      }
      
      /***/ }),
      
      /***/ "./src/demux/sample-aes.ts":
      /*!*********************************!*\
        !*** ./src/demux/sample-aes.ts ***!
        \*********************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony import */ var _crypt_decrypter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../crypt/decrypter */ "./src/crypt/decrypter.ts");
      /* harmony import */ var _tsdemuxer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./tsdemuxer */ "./src/demux/tsdemuxer.ts");
      /**
       * SAMPLE-AES decrypter
       */
      
      
      
      var SampleAesDecrypter = /*#__PURE__*/function () {
        function SampleAesDecrypter(observer, config, keyData) {
          this.keyData = void 0;
          this.decrypter = void 0;
          this.keyData = keyData;
          this.decrypter = new _crypt_decrypter__WEBPACK_IMPORTED_MODULE_0__["default"](observer, config, {
            removePKCS7Padding: false
          });
        }
      
        var _proto = SampleAesDecrypter.prototype;
      
        _proto.decryptBuffer = function decryptBuffer(encryptedData, callback) {
          this.decrypter.decrypt(encryptedData, this.keyData.key.buffer, this.keyData.iv.buffer, callback);
        } // AAC - encrypt all full 16 bytes blocks starting from offset 16
        ;
      
        _proto.decryptAacSample = function decryptAacSample(samples, sampleIndex, callback, sync) {
          var curUnit = samples[sampleIndex].unit;
          var encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
          var encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
          var localthis = this;
          this.decryptBuffer(encryptedBuffer, function (decryptedBuffer) {
            var decryptedData = new Uint8Array(decryptedBuffer);
            curUnit.set(decryptedData, 16);
      
            if (!sync) {
              localthis.decryptAacSamples(samples, sampleIndex + 1, callback);
            }
          });
        };
      
        _proto.decryptAacSamples = function decryptAacSamples(samples, sampleIndex, callback) {
          for (;; sampleIndex++) {
            if (sampleIndex >= samples.length) {
              callback();
              return;
            }
      
            if (samples[sampleIndex].unit.length < 32) {
              continue;
            }
      
            var sync = this.decrypter.isSync();
            this.decryptAacSample(samples, sampleIndex, callback, sync);
      
            if (!sync) {
              return;
            }
          }
        } // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
        ;
      
        _proto.getAvcEncryptedData = function getAvcEncryptedData(decodedData) {
          var encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
          var encryptedData = new Int8Array(encryptedDataLen);
          var outputPos = 0;
      
          for (var inputPos = 32; inputPos <= decodedData.length - 16; inputPos += 160, outputPos += 16) {
            encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
          }
      
          return encryptedData;
        };
      
        _proto.getAvcDecryptedUnit = function getAvcDecryptedUnit(decodedData, decryptedData) {
          var uint8DecryptedData = new Uint8Array(decryptedData);
          var inputPos = 0;
      
          for (var outputPos = 32; outputPos <= decodedData.length - 16; outputPos += 160, inputPos += 16) {
            decodedData.set(uint8DecryptedData.subarray(inputPos, inputPos + 16), outputPos);
          }
      
          return decodedData;
        };
      
        _proto.decryptAvcSample = function decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync) {
          var decodedData = Object(_tsdemuxer__WEBPACK_IMPORTED_MODULE_1__["discardEPB"])(curUnit.data);
          var encryptedData = this.getAvcEncryptedData(decodedData);
          var localthis = this;
          this.decryptBuffer(encryptedData.buffer, function (decryptedBuffer) {
            curUnit.data = localthis.getAvcDecryptedUnit(decodedData, decryptedBuffer);
      
            if (!sync) {
              localthis.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
            }
          });
        };
      
        _proto.decryptAvcSamples = function decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {
          if (samples instanceof Uint8Array) {
            throw new Error('Cannot decrypt samples of type Uint8Array');
          }
      
          for (;; sampleIndex++, unitIndex = 0) {
            if (sampleIndex >= samples.length) {
              callback();
              return;
            }
      
            var curUnits = samples[sampleIndex].units;
      
            for (;; unitIndex++) {
              if (unitIndex >= curUnits.length) {
                break;
              }
      
              var curUnit = curUnits[unitIndex];
      
              if (curUnit.data.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {
                continue;
              }
      
              var sync = this.decrypter.isSync();
              this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync);
      
              if (!sync) {
                return;
              }
            }
          }
        };
      
        return SampleAesDecrypter;
      }();
      
      /* harmony default export */ __webpack_exports__["default"] = (SampleAesDecrypter);
      
      /***/ }),
      
      /***/ "./src/demux/transmuxer-interface.ts":
      /*!*******************************************!*\
        !*** ./src/demux/transmuxer-interface.ts ***!
        \*******************************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TransmuxerInterface; });
      /* harmony import */ var webworkify_webpack__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! webworkify-webpack */ "./node_modules/webworkify-webpack/index.js");
      /* harmony import */ var webworkify_webpack__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(webworkify_webpack__WEBPACK_IMPORTED_MODULE_0__);
      /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
      /* harmony import */ var _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/transmuxer */ "./src/demux/transmuxer.ts");
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
      /* harmony import */ var _utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/mediasource-helper */ "./src/utils/mediasource-helper.ts");
      /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! eventemitter3 */ "./node_modules/eventemitter3/index.js");
      /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_6__);
      
      
      
      
      
      
      
      var MediaSource = Object(_utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__["getMediaSource"])() || {
        isTypeSupported: function isTypeSupported() {
          return false;
        }
      };
      
      var TransmuxerInterface = /*#__PURE__*/function () {
        function TransmuxerInterface(hls, id, onTransmuxComplete, onFlush) {
          var _this = this;
      
          this.hls = void 0;
          this.id = void 0;
          this.observer = void 0;
          this.frag = null;
          this.part = null;
          this.worker = void 0;
          this.onwmsg = void 0;
          this.transmuxer = null;
          this.onTransmuxComplete = void 0;
          this.onFlush = void 0;
          this.hls = hls;
          this.id = id;
          this.onTransmuxComplete = onTransmuxComplete;
          this.onFlush = onFlush;
          var config = hls.config;
      
          var forwardMessage = function forwardMessage(ev, data) {
            data = data || {};
            data.frag = _this.frag;
            data.id = _this.id;
            hls.trigger(ev, data);
          }; // forward events to main thread
      
      
          this.observer = new eventemitter3__WEBPACK_IMPORTED_MODULE_6__["EventEmitter"]();
          this.observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_DECRYPTED, forwardMessage);
          this.observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, forwardMessage);
          var typeSupported = {
            mp4: MediaSource.isTypeSupported('video/mp4'),
            mpeg: MediaSource.isTypeSupported('audio/mpeg'),
            mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"')
          }; // navigator.vendor is not always available in Web Worker
          // refer to https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/navigator
      
          var vendor = navigator.vendor;
      
          if (config.enableWorker && typeof Worker !== 'undefined') {
            _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log('demuxing in webworker');
            var worker;
      
            try {
              worker = this.worker = webworkify_webpack__WEBPACK_IMPORTED_MODULE_0__(/*require.resolve*/(/*! ../demux/transmuxer-worker.ts */ "./src/demux/transmuxer-worker.ts"));
              this.onwmsg = this.onWorkerMessage.bind(this);
              worker.addEventListener('message', this.onwmsg);
      
              worker.onerror = function (event) {
                hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
                  type: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorTypes"].OTHER_ERROR,
                  details: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].INTERNAL_EXCEPTION,
                  fatal: true,
                  event: 'demuxerWorker',
                  error: new Error(event.message + "  (" + event.filename + ":" + event.lineno + ")")
                });
              };
      
              worker.postMessage({
                cmd: 'init',
                typeSupported: typeSupported,
                vendor: vendor,
                id: id,
                config: JSON.stringify(config)
              });
            } catch (err) {
              _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('Error in worker:', err);
              _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].error('Error while initializing DemuxerWorker, fallback to inline');
      
              if (worker) {
                // revoke the Object URL that was used to create transmuxer worker, so as not to leak it
                self.URL.revokeObjectURL(worker.objectURL);
              }
      
              this.transmuxer = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["default"](this.observer, typeSupported, config, vendor, id);
              this.worker = null;
            }
          } else {
            this.transmuxer = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["default"](this.observer, typeSupported, config, vendor, id);
          }
        }
      
        var _proto = TransmuxerInterface.prototype;
      
        _proto.destroy = function destroy() {
          var w = this.worker;
      
          if (w) {
            w.removeEventListener('message', this.onwmsg);
            w.terminate();
            this.worker = null;
          } else {
            var transmuxer = this.transmuxer;
      
            if (transmuxer) {
              transmuxer.destroy();
              this.transmuxer = null;
            }
          }
      
          var observer = this.observer;
      
          if (observer) {
            observer.removeAllListeners();
          } // @ts-ignore
      
      
          this.observer = null;
        };
      
        _proto.push = function push(data, initSegmentData, audioCodec, videoCodec, frag, part, duration, accurateTimeOffset, chunkMeta, defaultInitPTS) {
          var _this2 = this;
      
          chunkMeta.transmuxing.start = self.performance.now();
          var transmuxer = this.transmuxer,
              worker = this.worker;
          var timeOffset = part ? part.start : frag.start;
          var decryptdata = frag.decryptdata;
          var lastFrag = this.frag;
          var discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
          var trackSwitch = !(lastFrag && chunkMeta.level === lastFrag.level);
          var snDiff = lastFrag ? chunkMeta.sn - lastFrag.sn : -1;
          var partDiff = this.part ? chunkMeta.part - this.part.index : 1;
          var contiguous = !trackSwitch && (snDiff === 1 || snDiff === 0 && partDiff === 1);
          var now = self.performance.now();
      
          if (trackSwitch || snDiff || frag.stats.parsing.start === 0) {
            frag.stats.parsing.start = now;
          }
      
          if (part && (partDiff || !contiguous)) {
            part.stats.parsing.start = now;
          }
      
          var state = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["TransmuxState"](discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset);
      
          if (!contiguous || discontinuity) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log("[transmuxer-interface, " + frag.type + "]: Starting new transmux session for sn: " + chunkMeta.sn + " p: " + chunkMeta.part + " level: " + chunkMeta.level + " id: " + chunkMeta.id + "\n        discontinuity: " + discontinuity + "\n        trackSwitch: " + trackSwitch + "\n        contiguous: " + contiguous + "\n        accurateTimeOffset: " + accurateTimeOffset + "\n        timeOffset: " + timeOffset);
            var config = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["TransmuxConfig"](audioCodec, videoCodec, initSegmentData, duration, defaultInitPTS);
            this.configureTransmuxer(config);
          }
      
          this.frag = frag;
          this.part = part; // Frags with sn of 'initSegment' are not transmuxed
      
          if (worker) {
            // post fragment payload as transferable objects for ArrayBuffer (no copy)
            worker.postMessage({
              cmd: 'demux',
              data: data,
              decryptdata: decryptdata,
              chunkMeta: chunkMeta,
              state: state
            }, data instanceof ArrayBuffer ? [data] : []);
          } else if (transmuxer) {
            var _transmuxResult = transmuxer.push(data, decryptdata, chunkMeta, state);
      
            if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["isPromise"])(_transmuxResult)) {
              _transmuxResult.then(function (data) {
                _this2.handleTransmuxComplete(data);
              });
            } else {
              this.handleTransmuxComplete(_transmuxResult);
            }
          }
        };
      
        _proto.flush = function flush(chunkMeta) {
          var _this3 = this;
      
          chunkMeta.transmuxing.start = self.performance.now();
          var transmuxer = this.transmuxer,
              worker = this.worker;
      
          if (worker) {
            worker.postMessage({
              cmd: 'flush',
              chunkMeta: chunkMeta
            });
          } else if (transmuxer) {
            var _transmuxResult2 = transmuxer.flush(chunkMeta);
      
            if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["isPromise"])(_transmuxResult2)) {
              _transmuxResult2.then(function (data) {
                _this3.handleFlushResult(data, chunkMeta);
              });
            } else {
              this.handleFlushResult(_transmuxResult2, chunkMeta);
            }
          }
        };
      
        _proto.handleFlushResult = function handleFlushResult(results, chunkMeta) {
          var _this4 = this;
      
          results.forEach(function (result) {
            _this4.handleTransmuxComplete(result);
          });
          this.onFlush(chunkMeta);
        };
      
        _proto.onWorkerMessage = function onWorkerMessage(ev) {
          var data = ev.data;
          var hls = this.hls;
      
          switch (data.event) {
            case 'init':
              {
                // revoke the Object URL that was used to create transmuxer worker, so as not to leak it
                self.URL.revokeObjectURL(this.worker.objectURL);
                break;
              }
      
            case 'transmuxComplete':
              {
                this.handleTransmuxComplete(data.data);
                break;
              }
      
            case 'flush':
              {
                this.onFlush(data.data);
                break;
              }
      
            /* falls through */
      
            default:
              {
                data.data = data.data || {};
                data.data.frag = this.frag;
                data.data.id = this.id;
                hls.trigger(data.event, data.data);
                break;
              }
          }
        };
      
        _proto.configureTransmuxer = function configureTransmuxer(config) {
          var worker = this.worker,
              transmuxer = this.transmuxer;
      
          if (worker) {
            worker.postMessage({
              cmd: 'configure',
              config: config
            });
          } else if (transmuxer) {
            transmuxer.configure(config);
          }
        };
      
        _proto.handleTransmuxComplete = function handleTransmuxComplete(result) {
          result.chunkMeta.transmuxing.end = self.performance.now();
          this.onTransmuxComplete(result);
        };
      
        return TransmuxerInterface;
      }();
      
      
      
      /***/ }),
      
      /***/ "./src/demux/transmuxer-worker.ts":
      /*!****************************************!*\
        !*** ./src/demux/transmuxer-worker.ts ***!
        \****************************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TransmuxerWorker; });
      /* harmony import */ var _demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../demux/transmuxer */ "./src/demux/transmuxer.ts");
      /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! eventemitter3 */ "./node_modules/eventemitter3/index.js");
      /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_3__);
      
      
      
      
      function TransmuxerWorker(self) {
        var observer = new eventemitter3__WEBPACK_IMPORTED_MODULE_3__["EventEmitter"]();
      
        var forwardMessage = function forwardMessage(ev, data) {
          self.postMessage({
            event: ev,
            data: data
          });
        }; // forward events to main thread
      
      
        observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_DECRYPTED, forwardMessage);
        observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, forwardMessage);
        self.addEventListener('message', function (ev) {
          var data = ev.data;
      
          switch (data.cmd) {
            case 'init':
              {
                var config = JSON.parse(data.config);
                self.transmuxer = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__["default"](observer, data.typeSupported, config, data.vendor, data.id);
                Object(_utils_logger__WEBPACK_IMPORTED_MODULE_2__["enableLogs"])(config.debug);
                forwardMessage('init', null);
                break;
              }
      
            case 'configure':
              {
                self.transmuxer.configure(data.config);
                break;
              }
      
            case 'demux':
              {
                var transmuxResult = self.transmuxer.push(data.data, data.decryptdata, data.chunkMeta, data.state);
      
                if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__["isPromise"])(transmuxResult)) {
                  transmuxResult.then(function (data) {
                    emitTransmuxComplete(self, data);
                  });
                } else {
                  emitTransmuxComplete(self, transmuxResult);
                }
      
                break;
              }
      
            case 'flush':
              {
                var id = data.chunkMeta;
      
                var _transmuxResult = self.transmuxer.flush(id);
      
                if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__["isPromise"])(_transmuxResult)) {
                  _transmuxResult.then(function (results) {
                    handleFlushResult(self, results, id);
                  });
                } else {
                  handleFlushResult(self, _transmuxResult, id);
                }
      
                break;
              }
      
            default:
              break;
          }
        });
      }
      
      function emitTransmuxComplete(self, transmuxResult) {
        if (isEmptyResult(transmuxResult.remuxResult)) {
          return;
        }
      
        var transferable = [];
        var _transmuxResult$remux = transmuxResult.remuxResult,
            audio = _transmuxResult$remux.audio,
            video = _transmuxResult$remux.video;
      
        if (audio) {
          addToTransferable(transferable, audio);
        }
      
        if (video) {
          addToTransferable(transferable, video);
        }
      
        self.postMessage({
          event: 'transmuxComplete',
          data: transmuxResult
        }, transferable);
      } // Converts data to a transferable object https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast)
      // in order to minimize message passing overhead
      
      
      function addToTransferable(transferable, track) {
        if (track.data1) {
          transferable.push(track.data1.buffer);
        }
      
        if (track.data2) {
          transferable.push(track.data2.buffer);
        }
      }
      
      function handleFlushResult(self, results, chunkMeta) {
        results.forEach(function (result) {
          emitTransmuxComplete(self, result);
        });
        self.postMessage({
          event: 'flush',
          data: chunkMeta
        });
      }
      
      function isEmptyResult(remuxResult) {
        return !remuxResult.audio && !remuxResult.video && !remuxResult.text && !remuxResult.id3 && !remuxResult.initSegment;
      }
      
      /***/ }),
      
      /***/ "./src/demux/transmuxer.ts":
      /*!*********************************!*\
        !*** ./src/demux/transmuxer.ts ***!
        \*********************************/
      /*! exports provided: default, isPromise, TransmuxConfig, TransmuxState */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Transmuxer; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isPromise", function() { return isPromise; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransmuxConfig", function() { return TransmuxConfig; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransmuxState", function() { return TransmuxState; });
      /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
      /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
      /* harmony import */ var _crypt_decrypter__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../crypt/decrypter */ "./src/crypt/decrypter.ts");
      /* harmony import */ var _demux_aacdemuxer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../demux/aacdemuxer */ "./src/demux/aacdemuxer.ts");
      /* harmony import */ var _demux_mp4demuxer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../demux/mp4demuxer */ "./src/demux/mp4demuxer.ts");
      /* harmony import */ var _demux_tsdemuxer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../demux/tsdemuxer */ "./src/demux/tsdemuxer.ts");
      /* harmony import */ var _demux_mp3demuxer__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../demux/mp3demuxer */ "./src/demux/mp3demuxer.ts");
      /* harmony import */ var _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../remux/mp4-remuxer */ "./src/remux/mp4-remuxer.ts");
      /* harmony import */ var _remux_passthrough_remuxer__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../remux/passthrough-remuxer */ "./src/remux/passthrough-remuxer.ts");
      /* harmony import */ var _chunk_cache__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./chunk-cache */ "./src/demux/chunk-cache.ts");
      /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      
      
      
      
      
      
      
      
      
      
      
      
      var now; // performance.now() not available on WebWorker, at least on Safari Desktop
      
      try {
        now = self.performance.now.bind(self.performance);
      } catch (err) {
        _utils_logger__WEBPACK_IMPORTED_MODULE_11__["logger"].debug('Unable to use Performance API on this environment');
        now = self.Date.now;
      }
      
      var muxConfig = [{
        demux: _demux_tsdemuxer__WEBPACK_IMPORTED_MODULE_5__["default"],
        remux: _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__["default"]
      }, {
        demux: _demux_mp4demuxer__WEBPACK_IMPORTED_MODULE_4__["default"],
        remux: _remux_passthrough_remuxer__WEBPACK_IMPORTED_MODULE_8__["default"]
      }, {
        demux: _demux_aacdemuxer__WEBPACK_IMPORTED_MODULE_3__["default"],
        remux: _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__["default"]
      }, {
        demux: _demux_mp3demuxer__WEBPACK_IMPORTED_MODULE_6__["default"],
        remux: _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__["default"]
      }];
      var minProbeByteLength = 1024;
      muxConfig.forEach(function (_ref) {
        var demux = _ref.demux;
        minProbeByteLength = Math.max(minProbeByteLength, demux.minProbeByteLength);
      });
      
      var Transmuxer = /*#__PURE__*/function () {
        function Transmuxer(observer, typeSupported, config, vendor, id) {
          this.observer = void 0;
          this.typeSupported = void 0;
          this.config = void 0;
          this.vendor = void 0;
          this.id = void 0;
          this.demuxer = void 0;
          this.remuxer = void 0;
          this.decrypter = void 0;
          this.probe = void 0;
          this.decryptionPromise = null;
          this.transmuxConfig = void 0;
          this.currentTransmuxState = void 0;
          this.cache = new _chunk_cache__WEBPACK_IMPORTED_MODULE_9__["default"]();
          this.observer = observer;
          this.typeSupported = typeSupported;
          this.config = config;
          this.vendor = vendor;
          this.id = id;
        }
      
        var _proto = Transmuxer.prototype;
      
        _proto.configure = function configure(transmuxConfig) {
          this.transmuxConfig = transmuxConfig;
      
          if (this.decrypter) {
            this.decrypter.reset();
          }
        };
      
        _proto.push = function push(data, decryptdata, chunkMeta, state) {
          var _this = this;
      
          var stats = chunkMeta.transmuxing;
          stats.executeStart = now();
          var uintData = new Uint8Array(data);
          var cache = this.cache,
              config = this.config,
              currentTransmuxState = this.currentTransmuxState,
              transmuxConfig = this.transmuxConfig;
      
          if (state) {
            this.currentTransmuxState = state;
          }
      
          var keyData = getEncryptionType(uintData, decryptdata);
      
          if (keyData && keyData.method === 'AES-128') {
            var decrypter = this.getDecrypter(); // Software decryption is synchronous; webCrypto is not
      
            if (config.enableSoftwareAES) {
              // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
              // data is handled in the flush() call
              var decryptedData = decrypter.softwareDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer);
      
              if (!decryptedData) {
                stats.executeEnd = now();
                return emptyResult(chunkMeta);
              }
      
              uintData = new Uint8Array(decryptedData);
            } else {
              this.decryptionPromise = decrypter.webCryptoDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer).then(function (decryptedData) {
                // Calling push here is important; if flush() is called while this is still resolving, this ensures that
                // the decrypted data has been transmuxed
                var result = _this.push(decryptedData, null, chunkMeta);
      
                _this.decryptionPromise = null;
                return result;
              });
              return this.decryptionPromise;
            }
          }
      
          var _ref2 = state || currentTransmuxState,
              contiguous = _ref2.contiguous,
              discontinuity = _ref2.discontinuity,
              trackSwitch = _ref2.trackSwitch,
              accurateTimeOffset = _ref2.accurateTimeOffset,
              timeOffset = _ref2.timeOffset;
      
          var audioCodec = transmuxConfig.audioCodec,
              videoCodec = transmuxConfig.videoCodec,
              defaultInitPts = transmuxConfig.defaultInitPts,
              duration = transmuxConfig.duration,
              initSegmentData = transmuxConfig.initSegmentData; // Reset muxers before probing to ensure that their state is clean, even if flushing occurs before a successful probe
      
          if (discontinuity || trackSwitch) {
            this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration);
          }
      
          if (discontinuity) {
            this.resetInitialTimestamp(defaultInitPts);
          }
      
          if (!contiguous) {
            this.resetContiguity();
          }
      
          if (this.needsProbing(uintData, discontinuity, trackSwitch)) {
            if (cache.dataLength) {
              var cachedData = cache.flush();
              uintData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_10__["appendUint8Array"])(cachedData, uintData);
            }
      
            this.configureTransmuxer(uintData, transmuxConfig);
          }
      
          var result = this.transmux(uintData, keyData, timeOffset, accurateTimeOffset, chunkMeta);
          var currentState = this.currentTransmuxState;
          currentState.contiguous = true;
          currentState.discontinuity = false;
          currentState.trackSwitch = false;
          stats.executeEnd = now();
          return result;
        } // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type)
        ;
      
        _proto.flush = function flush(chunkMeta) {
          var _this2 = this;
      
          var stats = chunkMeta.transmuxing;
          stats.executeStart = now();
          var decrypter = this.decrypter,
              cache = this.cache,
              currentTransmuxState = this.currentTransmuxState,
              decryptionPromise = this.decryptionPromise;
      
          if (decryptionPromise) {
            // Upon resolution, the decryption promise calls push() and returns its TransmuxerResult up the stack. Therefore
            // only flushing is required for async decryption
            return decryptionPromise.then(function () {
              return _this2.flush(chunkMeta);
            });
          }
      
          var transmuxResults = [];
          var timeOffset = currentTransmuxState.timeOffset;
      
          if (decrypter) {
            // The decrypter may have data cached, which needs to be demuxed. In this case we'll have two TransmuxResults
            // This happens in the case that we receive only 1 push call for a segment (either for non-progressive downloads,
            // or for progressive downloads with small segments)
            var decryptedData = decrypter.flush();
      
            if (decryptedData) {
              // Push always returns a TransmuxerResult if decryptdata is null
              transmuxResults.push(this.push(decryptedData, null, chunkMeta));
            }
          }
      
          var bytesSeen = cache.dataLength;
          cache.reset();
          var demuxer = this.demuxer,
              remuxer = this.remuxer;
      
          if (!demuxer || !remuxer) {
            // If probing failed, and each demuxer saw enough bytes to be able to probe, then Hls.js has been given content its not able to handle
            if (bytesSeen >= minProbeByteLength) {
              this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
                type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
                details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_PARSING_ERROR,
                fatal: true,
                reason: 'no demux matching with content found'
              });
            }
      
            stats.executeEnd = now();
            return [emptyResult(chunkMeta)];
          }
      
          var demuxResultOrPromise = demuxer.flush(timeOffset);
      
          if (isPromise(demuxResultOrPromise)) {
            // Decrypt final SAMPLE-AES samples
            return demuxResultOrPromise.then(function (demuxResult) {
              _this2.flushRemux(transmuxResults, demuxResult, chunkMeta);
      
              return transmuxResults;
            });
          }
      
          this.flushRemux(transmuxResults, demuxResultOrPromise, chunkMeta);
          return transmuxResults;
        };
      
        _proto.flushRemux = function flushRemux(transmuxResults, demuxResult, chunkMeta) {
          var audioTrack = demuxResult.audioTrack,
              avcTrack = demuxResult.avcTrack,
              id3Track = demuxResult.id3Track,
              textTrack = demuxResult.textTrack;
          var _this$currentTransmux = this.currentTransmuxState,
              accurateTimeOffset = _this$currentTransmux.accurateTimeOffset,
              timeOffset = _this$currentTransmux.timeOffset;
          _utils_logger__WEBPACK_IMPORTED_MODULE_11__["logger"].log("[transmuxer.ts]: Flushed fragment " + chunkMeta.sn + (chunkMeta.part > -1 ? ' p: ' + chunkMeta.part : '') + " of level " + chunkMeta.level);
          var remuxResult = this.remuxer.remux(audioTrack, avcTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, true, this.id);
          transmuxResults.push({
            remuxResult: remuxResult,
            chunkMeta: chunkMeta
          });
          chunkMeta.transmuxing.executeEnd = now();
        };
      
        _proto.resetInitialTimestamp = function resetInitialTimestamp(defaultInitPts) {
          var demuxer = this.demuxer,
              remuxer = this.remuxer;
      
          if (!demuxer || !remuxer) {
            return;
          }
      
          demuxer.resetTimeStamp(defaultInitPts);
          remuxer.resetTimeStamp(defaultInitPts);
        };
      
        _proto.resetContiguity = function resetContiguity() {
          var demuxer = this.demuxer,
              remuxer = this.remuxer;
      
          if (!demuxer || !remuxer) {
            return;
          }
      
          demuxer.resetContiguity();
          remuxer.resetNextTimestamp();
        };
      
        _proto.resetInitSegment = function resetInitSegment(initSegmentData, audioCodec, videoCodec, duration) {
          var demuxer = this.demuxer,
              remuxer = this.remuxer;
      
          if (!demuxer || !remuxer) {
            return;
          }
      
          demuxer.resetInitSegment(audioCodec, videoCodec, duration);
          remuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec);
        };
      
        _proto.destroy = function destroy() {
          if (this.demuxer) {
            this.demuxer.destroy();
            this.demuxer = undefined;
          }
      
          if (this.remuxer) {
            this.remuxer.destroy();
            this.remuxer = undefined;
          }
        };
      
        _proto.transmux = function transmux(data, keyData, timeOffset, accurateTimeOffset, chunkMeta) {
          var result;
      
          if (keyData && keyData.method === 'SAMPLE-AES') {
            result = this.transmuxSampleAes(data, keyData, timeOffset, accurateTimeOffset, chunkMeta);
          } else {
            result = this.transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta);
          }
      
          return result;
        };
      
        _proto.transmuxUnencrypted = function transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta) {
          var _demux = this.demuxer.demux(data, timeOffset, false, !this.config.progressive),
              audioTrack = _demux.audioTrack,
              avcTrack = _demux.avcTrack,
              id3Track = _demux.id3Track,
              textTrack = _demux.textTrack;
      
          var remuxResult = this.remuxer.remux(audioTrack, avcTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, false, this.id);
          return {
            remuxResult: remuxResult,
            chunkMeta: chunkMeta
          };
        };
      
        _proto.transmuxSampleAes = function transmuxSampleAes(data, decryptData, timeOffset, accurateTimeOffset, chunkMeta) {
          var _this3 = this;
      
          return this.demuxer.demuxSampleAes(data, decryptData, timeOffset).then(function (demuxResult) {
            var remuxResult = _this3.remuxer.remux(demuxResult.audioTrack, demuxResult.avcTrack, demuxResult.id3Track, demuxResult.textTrack, timeOffset, accurateTimeOffset, false, _this3.id);
      
            return {
              remuxResult: remuxResult,
              chunkMeta: chunkMeta
            };
          });
        };
      
        _proto.configureTransmuxer = function configureTransmuxer(data, transmuxConfig) {
          var config = this.config,
              observer = this.observer,
              typeSupported = this.typeSupported,
              vendor = this.vendor;
          var audioCodec = transmuxConfig.audioCodec,
              defaultInitPts = transmuxConfig.defaultInitPts,
              duration = transmuxConfig.duration,
              initSegmentData = transmuxConfig.initSegmentData,
              videoCodec = transmuxConfig.videoCodec; // probe for content type
      
          var mux;
      
          for (var i = 0, len = muxConfig.length; i < len; i++) {
            if (muxConfig[i].demux.probe(data)) {
              mux = muxConfig[i];
              break;
            }
          }
      
          if (!mux) {
            // If probing previous configs fail, use mp4 passthrough
            _utils_logger__WEBPACK_IMPORTED_MODULE_11__["logger"].warn('Failed to find demuxer by probing frag, treating as mp4 passthrough');
            mux = {
              demux: _demux_mp4demuxer__WEBPACK_IMPORTED_MODULE_4__["default"],
              remux: _remux_passthrough_remuxer__WEBPACK_IMPORTED_MODULE_8__["default"]
            };
          } // so let's check that current remuxer and demuxer are still valid
      
      
          var demuxer = this.demuxer;
          var remuxer = this.remuxer;
          var Remuxer = mux.remux;
          var Demuxer = mux.demux;
      
          if (!remuxer || !(remuxer instanceof Remuxer)) {
            this.remuxer = new Remuxer(observer, config, typeSupported, vendor);
          }
      
          if (!demuxer || !(demuxer instanceof Demuxer)) {
            this.demuxer = new Demuxer(observer, config, typeSupported);
            this.probe = Demuxer.probe;
          } // Ensure that muxers are always initialized with an initSegment
      
      
          this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration);
          this.resetInitialTimestamp(defaultInitPts);
        };
      
        _proto.needsProbing = function needsProbing(data, discontinuity, trackSwitch) {
          // in case of continuity change, or track switch
          // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)
          return !this.demuxer || !this.remuxer || discontinuity || trackSwitch;
        };
      
        _proto.getDecrypter = function getDecrypter() {
          var decrypter = this.decrypter;
      
          if (!decrypter) {
            decrypter = this.decrypter = new _crypt_decrypter__WEBPACK_IMPORTED_MODULE_2__["default"](this.observer, this.config);
          }
      
          return decrypter;
        };
      
        return Transmuxer;
      }();
      
      
      
      function getEncryptionType(data, decryptData) {
        var encryptionType = null;
      
        if (data.byteLength > 0 && decryptData != null && decryptData.key != null && decryptData.iv !== null && decryptData.method != null) {
          encryptionType = decryptData;
        }
      
        return encryptionType;
      }
      
      var emptyResult = function emptyResult(chunkMeta) {
        return {
          remuxResult: {},
          chunkMeta: chunkMeta
        };
      };
      
      function isPromise(p) {
        return 'then' in p && p.then instanceof Function;
      }
      var TransmuxConfig = function TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPts) {
        this.audioCodec = void 0;
        this.videoCodec = void 0;
        this.initSegmentData = void 0;
        this.duration = void 0;
        this.defaultInitPts = void 0;
        this.audioCodec = audioCodec;
        this.videoCodec = videoCodec;
        this.initSegmentData = initSegmentData;
        this.duration = duration;
        this.defaultInitPts = defaultInitPts;
      };
      var TransmuxState = function TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset) {
        this.discontinuity = void 0;
        this.contiguous = void 0;
        this.accurateTimeOffset = void 0;
        this.trackSwitch = void 0;
        this.timeOffset = void 0;
        this.discontinuity = discontinuity;
        this.contiguous = contiguous;
        this.accurateTimeOffset = accurateTimeOffset;
        this.trackSwitch = trackSwitch;
        this.timeOffset = timeOffset;
      };
      
      /***/ }),
      
      /***/ "./src/demux/tsdemuxer.ts":
      /*!********************************!*\
        !*** ./src/demux/tsdemuxer.ts ***!
        \********************************/
      /*! exports provided: discardEPB, default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "discardEPB", function() { return discardEPB; });
      /* harmony import */ var _adts__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./adts */ "./src/demux/adts.ts");
      /* harmony import */ var _mpegaudio__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./mpegaudio */ "./src/demux/mpegaudio.ts");
      /* harmony import */ var _exp_golomb__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./exp-golomb */ "./src/demux/exp-golomb.ts");
      /* harmony import */ var _id3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./id3 */ "./src/demux/id3.ts");
      /* harmony import */ var _sample_aes__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./sample-aes */ "./src/demux/sample-aes.ts");
      /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../events */ "./src/events.ts");
      /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
      /**
       * highly optimized TS demuxer:
       * parse PAT, PMT
       * extract PES packet from audio and video PIDs
       * extract AVC/H264 NAL units and AAC/ADTS samples from PES packet
       * trigger the remuxer upon parsing completion
       * it also tries to workaround as best as it can audio codec switch (HE-AAC to AAC and vice versa), without having to restart the MediaSource.
       * it also controls the remuxing process :
       * upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state.
       */
      
      
      
      
      
      
      
      
      
      // We are using fixed track IDs for driving the MP4 remuxer
      // instead of following the TS PIDs.
      // There is no reason not to do this and some browsers/SourceBuffer-demuxers
      // may not like if there are TrackID "switches"
      // See https://github.com/video-dev/hls.js/issues/1331
      // Here we are mapping our internal track types to constant MP4 track IDs
      // With MSE currently one can only have one track of each, and we are muxing
      // whatever video/audio rendition in them.
      var RemuxerTrackIdConfig = {
        video: 1,
        audio: 2,
        id3: 3,
        text: 4
      };
      
      var TSDemuxer = /*#__PURE__*/function () {
        function TSDemuxer(observer, config, typeSupported) {
          this.observer = void 0;
          this.config = void 0;
          this.typeSupported = void 0;
          this.sampleAes = null;
          this.pmtParsed = false;
          this.audioCodec = void 0;
          this.videoCodec = void 0;
          this._duration = 0;
          this.aacLastPTS = null;
          this._initPTS = null;
          this._initDTS = null;
          this._pmtId = -1;
          this._avcTrack = void 0;
          this._audioTrack = void 0;
          this._id3Track = void 0;
          this._txtTrack = void 0;
          this.aacOverFlow = null;
          this.avcSample = null;
          this.remainderData = null;
          this.observer = observer;
          this.config = config;
          this.typeSupported = typeSupported;
        }
      
        TSDemuxer.probe = function probe(data) {
          var syncOffset = TSDemuxer.syncOffset(data);
      
          if (syncOffset < 0) {
            return false;
          } else {
            if (syncOffset) {
              _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn("MPEG2-TS detected but first sync word found @ offset " + syncOffset + ", junk ahead ?");
            }
      
            return true;
          }
        };
      
        TSDemuxer.syncOffset = function syncOffset(data) {
          // scan 1000 first bytes
          var scanwindow = Math.min(1000, data.length - 3 * 188);
          var i = 0;
      
          while (i < scanwindow) {
            // a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47
            if (data[i] === 0x47 && data[i + 188] === 0x47 && data[i + 2 * 188] === 0x47) {
              return i;
            } else {
              i++;
            }
          }
      
          return -1;
        }
        /**
         * Creates a track model internal to demuxer used to drive remuxing input
         *
         * @param type 'audio' | 'video' | 'id3' | 'text'
         * @param duration
         * @return TSDemuxer's internal track model
         */
        ;
      
        TSDemuxer.createTrack = function createTrack(type, duration) {
          return {
            container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,
            type: type,
            id: RemuxerTrackIdConfig[type],
            pid: -1,
            inputTimeScale: 90000,
            sequenceNumber: 0,
            samples: [],
            dropped: 0,
            duration: type === 'audio' ? duration : undefined
          };
        }
        /**
         * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)
         * Resets all internal track instances of the demuxer.
         */
        ;
      
        var _proto = TSDemuxer.prototype;
      
        _proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) {
          this.pmtParsed = false;
          this._pmtId = -1;
          this._avcTrack = TSDemuxer.createTrack('video', duration);
          this._audioTrack = TSDemuxer.createTrack('audio', duration);
          this._id3Track = TSDemuxer.createTrack('id3', duration);
          this._txtTrack = TSDemuxer.createTrack('text', duration);
          this._audioTrack.isAAC = true; // flush any partial content
      
          this.aacOverFlow = null;
          this.aacLastPTS = null;
          this.avcSample = null;
          this.audioCodec = audioCodec;
          this.videoCodec = videoCodec;
          this._duration = duration;
        };
      
        _proto.resetTimeStamp = function resetTimeStamp() {};
      
        _proto.resetContiguity = function resetContiguity() {
          var _audioTrack = this._audioTrack,
              _avcTrack = this._avcTrack,
              _id3Track = this._id3Track;
      
          if (_audioTrack) {
            _audioTrack.pesData = null;
          }
      
          if (_avcTrack) {
            _avcTrack.pesData = null;
          }
      
          if (_id3Track) {
            _id3Track.pesData = null;
          }
      
          this.aacOverFlow = null;
          this.aacLastPTS = null;
        };
      
        _proto.demux = function demux(data, timeOffset, isSampleAes, flush) {
          if (isSampleAes === void 0) {
            isSampleAes = false;
          }
      
          if (flush === void 0) {
            flush = false;
          }
      
          if (!isSampleAes) {
            this.sampleAes = null;
          }
      
          var pes;
          var avcTrack = this._avcTrack;
          var audioTrack = this._audioTrack;
          var id3Track = this._id3Track;
          var avcId = avcTrack.pid;
          var avcData = avcTrack.pesData;
          var audioId = audioTrack.pid;
          var id3Id = id3Track.pid;
          var audioData = audioTrack.pesData;
          var id3Data = id3Track.pesData;
          var unknownPIDs = false;
          var pmtParsed = this.pmtParsed;
          var pmtId = this._pmtId;
          var len = data.length;
      
          if (this.remainderData) {
            data = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_6__["appendUint8Array"])(this.remainderData, data);
            len = data.length;
            this.remainderData = null;
          }
      
          if (len < 188 && !flush) {
            this.remainderData = data;
            return {
              audioTrack: audioTrack,
              avcTrack: avcTrack,
              id3Track: id3Track,
              textTrack: this._txtTrack
            };
          }
      
          var syncOffset = Math.max(0, TSDemuxer.syncOffset(data));
          len -= (len + syncOffset) % 188;
      
          if (len < data.byteLength && !flush) {
            this.remainderData = new Uint8Array(data.buffer, len, data.buffer.byteLength - len);
          } // loop through TS packets
      
      
          for (var start = syncOffset; start < len; start += 188) {
            if (data[start] === 0x47) {
              var stt = !!(data[start + 1] & 0x40); // pid is a 13-bit field starting at the last bit of TS[1]
      
              var pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2];
              var atf = (data[start + 3] & 0x30) >> 4; // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.
      
              var offset = void 0;
      
              if (atf > 1) {
                offset = start + 5 + data[start + 4]; // continue if there is only adaptation field
      
                if (offset === start + 188) {
                  continue;
                }
              } else {
                offset = start + 4;
              }
      
              switch (pid) {
                case avcId:
                  if (stt) {
                    if (avcData && (pes = parsePES(avcData))) {
                      this.parseAVCPES(pes, false);
                    }
      
                    avcData = {
                      data: [],
                      size: 0
                    };
                  }
      
                  if (avcData) {
                    avcData.data.push(data.subarray(offset, start + 188));
                    avcData.size += start + 188 - offset;
                  }
      
                  break;
      
                case audioId:
                  if (stt) {
                    if (audioData && (pes = parsePES(audioData))) {
                      if (audioTrack.isAAC) {
                        this.parseAACPES(pes);
                      } else {
                        this.parseMPEGPES(pes);
                      }
                    }
      
                    audioData = {
                      data: [],
                      size: 0
                    };
                  }
      
                  if (audioData) {
                    audioData.data.push(data.subarray(offset, start + 188));
                    audioData.size += start + 188 - offset;
                  }
      
                  break;
      
                case id3Id:
                  if (stt) {
                    if (id3Data && (pes = parsePES(id3Data))) {
                      this.parseID3PES(pes);
                    }
      
                    id3Data = {
                      data: [],
                      size: 0
                    };
                  }
      
                  if (id3Data) {
                    id3Data.data.push(data.subarray(offset, start + 188));
                    id3Data.size += start + 188 - offset;
                  }
      
                  break;
      
                case 0:
                  if (stt) {
                    offset += data[offset] + 1;
                  }
      
                  pmtId = this._pmtId = parsePAT(data, offset);
                  break;
      
                case pmtId:
                  {
                    if (stt) {
                      offset += data[offset] + 1;
                    }
      
                    var parsedPIDs = parsePMT(data, offset, this.typeSupported.mpeg === true || this.typeSupported.mp3 === true, isSampleAes); // only update track id if track PID found while parsing PMT
                    // this is to avoid resetting the PID to -1 in case
                    // track PID transiently disappears from the stream
                    // this could happen in case of transient missing audio samples for example
                    // NOTE this is only the PID of the track as found in TS,
                    // but we are not using this for MP4 track IDs.
      
                    avcId = parsedPIDs.avc;
      
                    if (avcId > 0) {
                      avcTrack.pid = avcId;
                    }
      
                    audioId = parsedPIDs.audio;
      
                    if (audioId > 0) {
                      audioTrack.pid = audioId;
                      audioTrack.isAAC = parsedPIDs.isAAC;
                    }
      
                    id3Id = parsedPIDs.id3;
      
                    if (id3Id > 0) {
                      id3Track.pid = id3Id;
                    }
      
                    if (unknownPIDs && !pmtParsed) {
                      _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('reparse from beginning');
                      unknownPIDs = false; // we set it to -188, the += 188 in the for loop will reset start to 0
      
                      start = syncOffset - 188;
                    }
      
                    pmtParsed = this.pmtParsed = true;
                    break;
                  }
      
                case 17:
                case 0x1fff:
                  break;
      
                default:
                  unknownPIDs = true;
                  break;
              }
            } else {
              this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, {
                type: _errors__WEBPACK_IMPORTED_MODULE_8__["ErrorTypes"].MEDIA_ERROR,
                details: _errors__WEBPACK_IMPORTED_MODULE_8__["ErrorDetails"].FRAG_PARSING_ERROR,
                fatal: false,
                reason: 'TS packet did not start with 0x47'
              });
            }
          }
      
          avcTrack.pesData = avcData;
          audioTrack.pesData = audioData;
          id3Track.pesData = id3Data;
          var demuxResult = {
            audioTrack: audioTrack,
            avcTrack: avcTrack,
            id3Track: id3Track,
            textTrack: this._txtTrack
          };
      
          if (flush) {
            this.extractRemainingSamples(demuxResult);
          }
      
          return demuxResult;
        };
      
        _proto.flush = function flush() {
          var remainderData = this.remainderData;
          this.remainderData = null;
          var result;
      
          if (remainderData) {
            result = this.demux(remainderData, -1, false, true);
          } else {
            result = {
              audioTrack: this._audioTrack,
              avcTrack: this._avcTrack,
              textTrack: this._txtTrack,
              id3Track: this._id3Track
            };
          }
      
          this.extractRemainingSamples(result);
      
          if (this.sampleAes) {
            return this.decrypt(result, this.sampleAes);
          }
      
          return result;
        };
      
        _proto.extractRemainingSamples = function extractRemainingSamples(demuxResult) {
          var audioTrack = demuxResult.audioTrack,
              avcTrack = demuxResult.avcTrack,
              id3Track = demuxResult.id3Track;
          var avcData = avcTrack.pesData;
          var audioData = audioTrack.pesData;
          var id3Data = id3Track.pesData; // try to parse last PES packets
      
          var pes;
      
          if (avcData && (pes = parsePES(avcData))) {
            this.parseAVCPES(pes, true);
            avcTrack.pesData = null;
          } else {
            // either avcData null or PES truncated, keep it for next frag parsing
            avcTrack.pesData = avcData;
          }
      
          if (audioData && (pes = parsePES(audioData))) {
            if (audioTrack.isAAC) {
              this.parseAACPES(pes);
            } else {
              this.parseMPEGPES(pes);
            }
      
            audioTrack.pesData = null;
          } else {
            if (audioData !== null && audioData !== void 0 && audioData.size) {
              _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('last AAC PES packet truncated,might overlap between fragments');
            } // either audioData null or PES truncated, keep it for next frag parsing
      
      
            audioTrack.pesData = audioData;
          }
      
          if (id3Data && (pes = parsePES(id3Data))) {
            this.parseID3PES(pes);
            id3Track.pesData = null;
          } else {
            // either id3Data null or PES truncated, keep it for next frag parsing
            id3Track.pesData = id3Data;
          }
        };
      
        _proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
          var demuxResult = this.demux(data, timeOffset, true, !this.config.progressive);
          var sampleAes = this.sampleAes = new _sample_aes__WEBPACK_IMPORTED_MODULE_4__["default"](this.observer, this.config, keyData);
          return this.decrypt(demuxResult, sampleAes);
        };
      
        _proto.decrypt = function decrypt(demuxResult, sampleAes) {
          return new Promise(function (resolve) {
            var audioTrack = demuxResult.audioTrack,
                avcTrack = demuxResult.avcTrack;
      
            if (audioTrack.samples && audioTrack.isAAC) {
              sampleAes.decryptAacSamples(audioTrack.samples, 0, function () {
                if (avcTrack.samples) {
                  sampleAes.decryptAvcSamples(avcTrack.samples, 0, 0, function () {
                    resolve(demuxResult);
                  });
                } else {
                  resolve(demuxResult);
                }
              });
            } else if (avcTrack.samples) {
              sampleAes.decryptAvcSamples(avcTrack.samples, 0, 0, function () {
                resolve(demuxResult);
              });
            }
          });
        };
      
        _proto.destroy = function destroy() {
          this._initPTS = this._initDTS = null;
          this._duration = 0;
        };
      
        _proto.parseAVCPES = function parseAVCPES(pes, last) {
          var _this = this;
      
          var track = this._avcTrack;
          var units = this.parseAVCNALu(pes.data);
          var debug = false;
          var avcSample = this.avcSample;
          var push;
          var spsfound = false; // free pes.data to save up some memory
      
          pes.data = null; // if new NAL units found and last sample still there, let's push ...
          // this helps parsing streams with missing AUD (only do this if AUD never found)
      
          if (avcSample && units.length && !track.audFound) {
            pushAccessUnit(avcSample, track);
            avcSample = this.avcSample = createAVCSample(false, pes.pts, pes.dts, '');
          }
      
          units.forEach(function (unit) {
            switch (unit.type) {
              // NDR
              case 1:
                {
                  push = true;
      
                  if (!avcSample) {
                    avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
                  }
      
                  if (debug) {
                    avcSample.debug += 'NDR ';
                  }
      
                  avcSample.frame = true;
                  var data = unit.data; // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)
      
                  if (spsfound && data.length > 4) {
                    // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR
                    var sliceType = new _exp_golomb__WEBPACK_IMPORTED_MODULE_2__["default"](data).readSliceType(); // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice
                    // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.
                    // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.
                    // I slice: A slice that is not an SI slice that is decoded using intra prediction only.
                    // if (sliceType === 2 || sliceType === 7) {
      
                    if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
                      avcSample.key = true;
                    }
                  }
      
                  break; // IDR
                }
      
              case 5:
                push = true; // handle PES not starting with AUD
      
                if (!avcSample) {
                  avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
                }
      
                if (debug) {
                  avcSample.debug += 'IDR ';
                }
      
                avcSample.key = true;
                avcSample.frame = true;
                break;
              // SEI
      
              case 6:
                {
                  push = true;
      
                  if (debug && avcSample) {
                    avcSample.debug += 'SEI ';
                  }
      
                  var expGolombDecoder = new _exp_golomb__WEBPACK_IMPORTED_MODULE_2__["default"](discardEPB(unit.data)); // skip frameType
      
                  expGolombDecoder.readUByte();
                  var payloadType = 0;
                  var payloadSize = 0;
                  var endOfCaptions = false;
                  var b = 0;
      
                  while (!endOfCaptions && expGolombDecoder.bytesAvailable > 1) {
                    payloadType = 0;
      
                    do {
                      b = expGolombDecoder.readUByte();
                      payloadType += b;
                    } while (b === 0xff); // Parse payload size.
      
      
                    payloadSize = 0;
      
                    do {
                      b = expGolombDecoder.readUByte();
                      payloadSize += b;
                    } while (b === 0xff); // TODO: there can be more than one payload in an SEI packet...
                    // TODO: need to read type and size in a while loop to get them all
      
      
                    if (payloadType === 4 && expGolombDecoder.bytesAvailable !== 0) {
                      endOfCaptions = true;
                      var countryCode = expGolombDecoder.readUByte();
      
                      if (countryCode === 181) {
                        var providerCode = expGolombDecoder.readUShort();
      
                        if (providerCode === 49) {
                          var userStructure = expGolombDecoder.readUInt();
      
                          if (userStructure === 0x47413934) {
                            var userDataType = expGolombDecoder.readUByte(); // Raw CEA-608 bytes wrapped in CEA-708 packet
      
                            if (userDataType === 3) {
                              var firstByte = expGolombDecoder.readUByte();
                              var secondByte = expGolombDecoder.readUByte();
                              var totalCCs = 31 & firstByte;
                              var byteArray = [firstByte, secondByte];
      
                              for (var i = 0; i < totalCCs; i++) {
                                // 3 bytes per CC
                                byteArray.push(expGolombDecoder.readUByte());
                                byteArray.push(expGolombDecoder.readUByte());
                                byteArray.push(expGolombDecoder.readUByte());
                              }
      
                              insertSampleInOrder(_this._txtTrack.samples, {
                                type: 3,
                                pts: pes.pts,
                                bytes: byteArray
                              });
                            }
                          }
                        }
                      }
                    } else if (payloadType === 5 && expGolombDecoder.bytesAvailable !== 0) {
                      endOfCaptions = true;
      
                      if (payloadSize > 16) {
                        var uuidStrArray = [];
      
                        for (var _i = 0; _i < 16; _i++) {
                          uuidStrArray.push(expGolombDecoder.readUByte().toString(16));
      
                          if (_i === 3 || _i === 5 || _i === 7 || _i === 9) {
                            uuidStrArray.push('-');
                          }
                        }
      
                        var length = payloadSize - 16;
                        var userDataPayloadBytes = new Uint8Array(length);
      
                        for (var _i2 = 0; _i2 < length; _i2++) {
                          userDataPayloadBytes[_i2] = expGolombDecoder.readUByte();
                        }
      
                        insertSampleInOrder(_this._txtTrack.samples, {
                          pts: pes.pts,
                          payloadType: payloadType,
                          uuid: uuidStrArray.join(''),
                          userData: Object(_id3__WEBPACK_IMPORTED_MODULE_3__["utf8ArrayToStr"])(userDataPayloadBytes),
                          userDataBytes: userDataPayloadBytes
                        });
                      }
                    } else if (payloadSize < expGolombDecoder.bytesAvailable) {
                      for (var _i3 = 0; _i3 < payloadSize; _i3++) {
                        expGolombDecoder.readUByte();
                      }
                    }
                  }
      
                  break; // SPS
                }
      
              case 7:
                push = true;
                spsfound = true;
      
                if (debug && avcSample) {
                  avcSample.debug += 'SPS ';
                }
      
                if (!track.sps) {
                  var _expGolombDecoder = new _exp_golomb__WEBPACK_IMPORTED_MODULE_2__["default"](unit.data);
      
                  var config = _expGolombDecoder.readSPS();
      
                  track.width = config.width;
                  track.height = config.height;
                  track.pixelRatio = config.pixelRatio; // TODO: `track.sps` is defined as a `number[]`, but we're setting it to a `Uint8Array[]`.
      
                  track.sps = [unit.data];
                  track.duration = _this._duration;
                  var codecarray = unit.data.subarray(1, 4);
                  var codecstring = 'avc1.';
      
                  for (var _i4 = 0; _i4 < 3; _i4++) {
                    var h = codecarray[_i4].toString(16);
      
                    if (h.length < 2) {
                      h = '0' + h;
                    }
      
                    codecstring += h;
                  }
      
                  track.codec = codecstring;
                }
      
                break;
              // PPS
      
              case 8:
                push = true;
      
                if (debug && avcSample) {
                  avcSample.debug += 'PPS ';
                }
      
                if (!track.pps) {
                  // TODO: `track.pss` is defined as a `number[]`, but we're setting it to a `Uint8Array[]`.
                  track.pps = [unit.data];
                }
      
                break;
              // AUD
      
              case 9:
                push = false;
                track.audFound = true;
      
                if (avcSample) {
                  pushAccessUnit(avcSample, track);
                }
      
                avcSample = _this.avcSample = createAVCSample(false, pes.pts, pes.dts, debug ? 'AUD ' : '');
                break;
              // Filler Data
      
              case 12:
                push = false;
                break;
      
              default:
                push = false;
      
                if (avcSample) {
                  avcSample.debug += 'unknown NAL ' + unit.type + ' ';
                }
      
                break;
            }
      
            if (avcSample && push) {
              var _units = avcSample.units;
      
              _units.push(unit);
            }
          }); // if last PES packet, push samples
      
          if (last && avcSample) {
            pushAccessUnit(avcSample, track);
            this.avcSample = null;
          }
        };
      
        _proto.getLastNalUnit = function getLastNalUnit() {
          var _avcSample;
      
          var avcSample = this.avcSample;
          var lastUnit; // try to fallback to previous sample if current one is empty
      
          if (!avcSample || avcSample.units.length === 0) {
            var samples = this._avcTrack.samples;
            avcSample = samples[samples.length - 1];
          }
      
          if ((_avcSample = avcSample) !== null && _avcSample !== void 0 && _avcSample.units) {
            var units = avcSample.units;
            lastUnit = units[units.length - 1];
          }
      
          return lastUnit;
        };
      
        _proto.parseAVCNALu = function parseAVCNALu(array) {
          var len = array.byteLength;
          var track = this._avcTrack;
          var state = track.naluState || 0;
          var lastState = state;
          var units = [];
          var i = 0;
          var value;
          var overflow;
          var unitType;
          var lastUnitStart = -1;
          var lastUnitType = 0; // logger.log('PES:' + Hex.hexDump(array));
      
          if (state === -1) {
            // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet
            lastUnitStart = 0; // NALu type is value read from offset 0
      
            lastUnitType = array[0] & 0x1f;
            state = 0;
            i = 1;
          }
      
          while (i < len) {
            value = array[i++]; // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case
      
            if (!state) {
              state = value ? 0 : 1;
              continue;
            }
      
            if (state === 1) {
              state = value ? 0 : 2;
              continue;
            } // here we have state either equal to 2 or 3
      
      
            if (!value) {
              state = 3;
            } else if (value === 1) {
              if (lastUnitStart >= 0) {
                var unit = {
                  data: array.subarray(lastUnitStart, i - state - 1),
                  type: lastUnitType
                }; // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);
      
                units.push(unit);
              } else {
                // lastUnitStart is undefined => this is the first start code found in this PES packet
                // first check if start code delimiter is overlapping between 2 PES packets,
                // ie it started in last packet (lastState not zero)
                // and ended at the beginning of this PES packet (i <= 4 - lastState)
                var lastUnit = this.getLastNalUnit();
      
                if (lastUnit) {
                  if (lastState && i <= 4 - lastState) {
                    // start delimiter overlapping between PES packets
                    // strip start delimiter bytes from the end of last NAL unit
                    // check if lastUnit had a state different from zero
                    if (lastUnit.state) {
                      // strip last bytes
                      lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
                    }
                  } // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.
      
      
                  overflow = i - state - 1;
      
                  if (overflow > 0) {
                    // logger.log('first NALU found with overflow:' + overflow);
                    var tmp = new Uint8Array(lastUnit.data.byteLength + overflow);
                    tmp.set(lastUnit.data, 0);
                    tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength);
                    lastUnit.data = tmp;
                    lastUnit.state = 0;
                  }
                }
              } // check if we can read unit type
      
      
              if (i < len) {
                unitType = array[i] & 0x1f; // logger.log('find NALU @ offset:' + i + ',type:' + unitType);
      
                lastUnitStart = i;
                lastUnitType = unitType;
                state = 0;
              } else {
                // not enough byte to read unit type. let's read it on next PES parsing
                state = -1;
              }
            } else {
              state = 0;
            }
          }
      
          if (lastUnitStart >= 0 && state >= 0) {
            var _unit = {
              data: array.subarray(lastUnitStart, len),
              type: lastUnitType,
              state: state
            };
            units.push(_unit); // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);
          } // no NALu found
      
      
          if (units.length === 0) {
            // append pes.data to previous NAL unit
            var _lastUnit = this.getLastNalUnit();
      
            if (_lastUnit) {
              var _tmp = new Uint8Array(_lastUnit.data.byteLength + array.byteLength);
      
              _tmp.set(_lastUnit.data, 0);
      
              _tmp.set(array, _lastUnit.data.byteLength);
      
              _lastUnit.data = _tmp;
            }
          }
      
          track.naluState = state;
          return units;
        };
      
        _proto.parseAACPES = function parseAACPES(pes) {
          var startOffset = 0;
          var track = this._audioTrack;
          var aacOverFlow = this.aacOverFlow;
          var data = pes.data;
      
          if (aacOverFlow) {
            this.aacOverFlow = null;
            var sampleLength = aacOverFlow.sample.unit.byteLength;
            var frameMissingBytes = Math.min(aacOverFlow.missing, sampleLength);
            var frameOverflowBytes = sampleLength - frameMissingBytes;
            aacOverFlow.sample.unit.set(data.subarray(0, frameMissingBytes), frameOverflowBytes);
            track.samples.push(aacOverFlow.sample); // logger.log(`AAC: append overflowing ${frameOverflowBytes} bytes to beginning of new PES`);
      
            startOffset = aacOverFlow.missing;
          } // look for ADTS header (0xFFFx)
      
      
          var offset;
          var len;
      
          for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
            if (_adts__WEBPACK_IMPORTED_MODULE_0__["isHeader"](data, offset)) {
              break;
            }
          } // if ADTS header does not start straight from the beginning of the PES payload, raise an error
      
      
          if (offset !== startOffset) {
            var reason;
            var fatal;
      
            if (offset < len - 1) {
              reason = "AAC PES did not start with ADTS header,offset:" + offset;
              fatal = false;
            } else {
              reason = 'no ADTS header found in AAC PES';
              fatal = true;
            }
      
            _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn("parsing error:" + reason);
            this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, {
              type: _errors__WEBPACK_IMPORTED_MODULE_8__["ErrorTypes"].MEDIA_ERROR,
              details: _errors__WEBPACK_IMPORTED_MODULE_8__["ErrorDetails"].FRAG_PARSING_ERROR,
              fatal: fatal,
              reason: reason
            });
      
            if (fatal) {
              return;
            }
          }
      
          _adts__WEBPACK_IMPORTED_MODULE_0__["initTrackConfig"](track, this.observer, data, offset, this.audioCodec);
          var pts;
      
          if (pes.pts !== undefined) {
            pts = pes.pts;
          } else if (aacOverFlow) {
            // if last AAC frame is overflowing, we should ensure timestamps are contiguous:
            // first sample PTS should be equal to last sample PTS + frameDuration
            var frameDuration = _adts__WEBPACK_IMPORTED_MODULE_0__["getFrameDuration"](track.samplerate);
            pts = aacOverFlow.sample.pts + frameDuration;
          } else {
            _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn('[tsdemuxer]: AAC PES unknown PTS');
            return;
          } // scan for aac samples
      
      
          var frameIndex = 0;
      
          while (offset < len) {
            if (_adts__WEBPACK_IMPORTED_MODULE_0__["isHeader"](data, offset)) {
              if (offset + 5 < len) {
                var frame = _adts__WEBPACK_IMPORTED_MODULE_0__["appendFrame"](track, data, offset, pts, frameIndex);
      
                if (frame) {
                  if (frame.missing) {
                    this.aacOverFlow = frame;
                  } else {
                    offset += frame.length;
                    frameIndex++;
                    continue;
                  }
                }
              } // We are at an ADTS header, but do not have enough data for a frame
              // Remaining data will be added to aacOverFlow
      
      
              break;
            } else {
              // nothing found, keep looking
              offset++;
            }
          }
        };
      
        _proto.parseMPEGPES = function parseMPEGPES(pes) {
          var data = pes.data;
          var length = data.length;
          var frameIndex = 0;
          var offset = 0;
          var pts = pes.pts;
      
          if (pts === undefined) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn('[tsdemuxer]: MPEG PES unknown PTS');
            return;
          }
      
          while (offset < length) {
            if (_mpegaudio__WEBPACK_IMPORTED_MODULE_1__["isHeader"](data, offset)) {
              var frame = _mpegaudio__WEBPACK_IMPORTED_MODULE_1__["appendFrame"](this._audioTrack, data, offset, pts, frameIndex);
      
              if (frame) {
                offset += frame.length;
                frameIndex++;
              } else {
                // logger.log('Unable to parse Mpeg audio frame');
                break;
              }
            } else {
              // nothing found, keep looking
              offset++;
            }
          }
        };
      
        _proto.parseID3PES = function parseID3PES(pes) {
          if (pes.pts === undefined) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn('[tsdemuxer]: ID3 PES unknown PTS');
            return;
          }
      
          this._id3Track.samples.push(pes);
        };
      
        return TSDemuxer;
      }();
      
      TSDemuxer.minProbeByteLength = 188;
      
      function createAVCSample(key, pts, dts, debug) {
        return {
          key: key,
          frame: false,
          pts: pts,
          dts: dts,
          units: [],
          debug: debug,
          length: 0
        };
      }
      
      function parsePAT(data, offset) {
        // skip the PSI header and parse the first PMT entry
        return (data[offset + 10] & 0x1f) << 8 | data[offset + 11]; // logger.log('PMT PID:'  + this._pmtId);
      }
      
      function parsePMT(data, offset, mpegSupported, isSampleAes) {
        var result = {
          audio: -1,
          avc: -1,
          id3: -1,
          isAAC: true
        };
        var sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];
        var tableEnd = offset + 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
        // long the program info descriptors are
      
        var programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11]; // advance the offset to the first entry in the mapping table
      
        offset += 12 + programInfoLength;
      
        while (offset < tableEnd) {
          var pid = (data[offset + 1] & 0x1f) << 8 | data[offset + 2];
      
          switch (data[offset]) {
            case 0xcf:
              // SAMPLE-AES AAC
              if (!isSampleAes) {
                _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream');
                break;
              }
      
            /* falls through */
      
            case 0x0f:
              // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)
              // logger.log('AAC PID:'  + pid);
              if (result.audio === -1) {
                result.audio = pid;
              }
      
              break;
            // Packetized metadata (ID3)
      
            case 0x15:
              // logger.log('ID3 PID:'  + pid);
              if (result.id3 === -1) {
                result.id3 = pid;
              }
      
              break;
      
            case 0xdb:
              // SAMPLE-AES AVC
              if (!isSampleAes) {
                _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('H.264 with AES-128-CBC slice encryption found in unencrypted stream');
                break;
              }
      
            /* falls through */
      
            case 0x1b:
              // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)
              // logger.log('AVC PID:'  + pid);
              if (result.avc === -1) {
                result.avc = pid;
              }
      
              break;
            // ISO/IEC 11172-3 (MPEG-1 audio)
            // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)
      
            case 0x03:
            case 0x04:
              // logger.log('MPEG PID:'  + pid);
              if (!mpegSupported) {
                _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('MPEG audio found, not supported in this browser');
              } else if (result.audio === -1) {
                result.audio = pid;
                result.isAAC = false;
              }
      
              break;
      
            case 0x24:
              _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn('Unsupported HEVC stream type found');
              break;
      
            default:
              // logger.log('unknown stream type:' + data[offset]);
              break;
          } // move to the next table entry
          // skip past the elementary stream descriptors, if present
      
      
          offset += ((data[offset + 3] & 0x0f) << 8 | data[offset + 4]) + 5;
        }
      
        return result;
      }
      
      function parsePES(stream) {
        var i = 0;
        var frag;
        var pesLen;
        var pesHdrLen;
        var pesPts;
        var pesDts;
        var data = stream.data; // safety check
      
        if (!stream || stream.size === 0) {
          return null;
        } // we might need up to 19 bytes to read PES header
        // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes
        // usually only one merge is needed (and this is rare ...)
      
      
        while (data[0].length < 19 && data.length > 1) {
          var newData = new Uint8Array(data[0].length + data[1].length);
          newData.set(data[0]);
          newData.set(data[1], data[0].length);
          data[0] = newData;
          data.splice(1, 1);
        } // retrieve PTS/DTS from first fragment
      
      
        frag = data[0];
        var pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
      
        if (pesPrefix === 1) {
          pesLen = (frag[4] << 8) + frag[5]; // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated
          // minus 6 : PES header size
      
          if (pesLen && pesLen > stream.size - 6) {
            return null;
          }
      
          var pesFlags = frag[7];
      
          if (pesFlags & 0xc0) {
            /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
                as PTS / DTS is 33 bit we cannot use bitwise operator in JS,
                as Bitwise operators treat their operands as a sequence of 32 bits */
            pesPts = (frag[9] & 0x0e) * 536870912 + // 1 << 29
            (frag[10] & 0xff) * 4194304 + // 1 << 22
            (frag[11] & 0xfe) * 16384 + // 1 << 14
            (frag[12] & 0xff) * 128 + // 1 << 7
            (frag[13] & 0xfe) / 2;
      
            if (pesFlags & 0x40) {
              pesDts = (frag[14] & 0x0e) * 536870912 + // 1 << 29
              (frag[15] & 0xff) * 4194304 + // 1 << 22
              (frag[16] & 0xfe) * 16384 + // 1 << 14
              (frag[17] & 0xff) * 128 + // 1 << 7
              (frag[18] & 0xfe) / 2;
      
              if (pesPts - pesDts > 60 * 90000) {
                _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn(Math.round((pesPts - pesDts) / 90000) + "s delta between PTS and DTS, align them");
                pesPts = pesDts;
              }
            } else {
              pesDts = pesPts;
            }
          }
      
          pesHdrLen = frag[8]; // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension
      
          var payloadStartOffset = pesHdrLen + 9;
      
          if (stream.size <= payloadStartOffset) {
            return null;
          }
      
          stream.size -= payloadStartOffset; // reassemble PES packet
      
          var pesData = new Uint8Array(stream.size);
      
          for (var j = 0, dataLen = data.length; j < dataLen; j++) {
            frag = data[j];
            var len = frag.byteLength;
      
            if (payloadStartOffset) {
              if (payloadStartOffset > len) {
                // trim full frag if PES header bigger than frag
                payloadStartOffset -= len;
                continue;
              } else {
                // trim partial frag if PES header smaller than frag
                frag = frag.subarray(payloadStartOffset);
                len -= payloadStartOffset;
                payloadStartOffset = 0;
              }
            }
      
            pesData.set(frag, i);
            i += len;
          }
      
          if (pesLen) {
            // payload size : remove PES header + PES extension
            pesLen -= pesHdrLen + 3;
          }
      
          return {
            data: pesData,
            pts: pesPts,
            dts: pesDts,
            len: pesLen
          };
        }
      
        return null;
      }
      
      function pushAccessUnit(avcSample, avcTrack) {
        if (avcSample.units.length && avcSample.frame) {
          // if sample does not have PTS/DTS, patch with last sample PTS/DTS
          if (avcSample.pts === undefined) {
            var samples = avcTrack.samples;
            var nbSamples = samples.length;
      
            if (nbSamples) {
              var lastSample = samples[nbSamples - 1];
              avcSample.pts = lastSample.pts;
              avcSample.dts = lastSample.dts;
            } else {
              // dropping samples, no timestamp found
              avcTrack.dropped++;
              return;
            }
          }
      
          avcTrack.samples.push(avcSample);
        }
      
        if (avcSample.debug.length) {
          _utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug);
        }
      }
      
      function insertSampleInOrder(arr, data) {
        var len = arr.length;
      
        if (len > 0) {
          if (data.pts >= arr[len - 1].pts) {
            arr.push(data);
          } else {
            for (var pos = len - 1; pos >= 0; pos--) {
              if (data.pts < arr[pos].pts) {
                arr.splice(pos, 0, data);
                break;
              }
            }
          }
        } else {
          arr.push(data);
        }
      }
      /**
       * remove Emulation Prevention bytes from a RBSP
       */
      
      
      function discardEPB(data) {
        var length = data.byteLength;
        var EPBPositions = [];
        var i = 1; // Find all `Emulation Prevention Bytes`
      
        while (i < length - 2) {
          if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
            EPBPositions.push(i + 2);
            i += 2;
          } else {
            i++;
          }
        } // If no Emulation Prevention Bytes were found just return the original
        // array
      
      
        if (EPBPositions.length === 0) {
          return data;
        } // Create a new array to hold the NAL unit data
      
      
        var newLength = length - EPBPositions.length;
        var newData = new Uint8Array(newLength);
        var sourceIndex = 0;
      
        for (i = 0; i < newLength; sourceIndex++, i++) {
          if (sourceIndex === EPBPositions[0]) {
            // Skip this byte
            sourceIndex++; // Remove this position index
      
            EPBPositions.shift();
          }
      
          newData[i] = data[sourceIndex];
        }
      
        return newData;
      }
      /* harmony default export */ __webpack_exports__["default"] = (TSDemuxer);
      
      /***/ }),
      
      /***/ "./src/errors.ts":
      /*!***********************!*\
        !*** ./src/errors.ts ***!
        \***********************/
      /*! exports provided: ErrorTypes, ErrorDetails */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorTypes", function() { return ErrorTypes; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorDetails", function() { return ErrorDetails; });
      var ErrorTypes;
      /**
       * @enum {ErrorDetails}
       * @typedef {string} ErrorDetail
       */
      
      (function (ErrorTypes) {
        ErrorTypes["NETWORK_ERROR"] = "networkError";
        ErrorTypes["MEDIA_ERROR"] = "mediaError";
        ErrorTypes["KEY_SYSTEM_ERROR"] = "keySystemError";
        ErrorTypes["MUX_ERROR"] = "muxError";
        ErrorTypes["OTHER_ERROR"] = "otherError";
      })(ErrorTypes || (ErrorTypes = {}));
      
      var ErrorDetails;
      
      (function (ErrorDetails) {
        ErrorDetails["KEY_SYSTEM_NO_KEYS"] = "keySystemNoKeys";
        ErrorDetails["KEY_SYSTEM_NO_ACCESS"] = "keySystemNoAccess";
        ErrorDetails["KEY_SYSTEM_NO_SESSION"] = "keySystemNoSession";
        ErrorDetails["KEY_SYSTEM_LICENSE_REQUEST_FAILED"] = "keySystemLicenseRequestFailed";
        ErrorDetails["KEY_SYSTEM_NO_INIT_DATA"] = "keySystemNoInitData";
        ErrorDetails["MANIFEST_LOAD_ERROR"] = "manifestLoadError";
        ErrorDetails["MANIFEST_LOAD_TIMEOUT"] = "manifestLoadTimeOut";
        ErrorDetails["MANIFEST_PARSING_ERROR"] = "manifestParsingError";
        ErrorDetails["MANIFEST_INCOMPATIBLE_CODECS_ERROR"] = "manifestIncompatibleCodecsError";
        ErrorDetails["LEVEL_EMPTY_ERROR"] = "levelEmptyError";
        ErrorDetails["LEVEL_LOAD_ERROR"] = "levelLoadError";
        ErrorDetails["LEVEL_LOAD_TIMEOUT"] = "levelLoadTimeOut";
        ErrorDetails["LEVEL_SWITCH_ERROR"] = "levelSwitchError";
        ErrorDetails["AUDIO_TRACK_LOAD_ERROR"] = "audioTrackLoadError";
        ErrorDetails["AUDIO_TRACK_LOAD_TIMEOUT"] = "audioTrackLoadTimeOut";
        ErrorDetails["SUBTITLE_LOAD_ERROR"] = "subtitleTrackLoadError";
        ErrorDetails["SUBTITLE_TRACK_LOAD_TIMEOUT"] = "subtitleTrackLoadTimeOut";
        ErrorDetails["FRAG_LOAD_ERROR"] = "fragLoadError";
        ErrorDetails["FRAG_LOAD_TIMEOUT"] = "fragLoadTimeOut";
        ErrorDetails["FRAG_DECRYPT_ERROR"] = "fragDecryptError";
        ErrorDetails["FRAG_PARSING_ERROR"] = "fragParsingError";
        ErrorDetails["REMUX_ALLOC_ERROR"] = "remuxAllocError";
        ErrorDetails["KEY_LOAD_ERROR"] = "keyLoadError";
        ErrorDetails["KEY_LOAD_TIMEOUT"] = "keyLoadTimeOut";
        ErrorDetails["BUFFER_ADD_CODEC_ERROR"] = "bufferAddCodecError";
        ErrorDetails["BUFFER_INCOMPATIBLE_CODECS_ERROR"] = "bufferIncompatibleCodecsError";
        ErrorDetails["BUFFER_APPEND_ERROR"] = "bufferAppendError";
        ErrorDetails["BUFFER_APPENDING_ERROR"] = "bufferAppendingError";
        ErrorDetails["BUFFER_STALLED_ERROR"] = "bufferStalledError";
        ErrorDetails["BUFFER_FULL_ERROR"] = "bufferFullError";
        ErrorDetails["BUFFER_SEEK_OVER_HOLE"] = "bufferSeekOverHole";
        ErrorDetails["BUFFER_NUDGE_ON_STALL"] = "bufferNudgeOnStall";
        ErrorDetails["INTERNAL_EXCEPTION"] = "internalException";
        ErrorDetails["INTERNAL_ABORTED"] = "aborted";
        ErrorDetails["UNKNOWN"] = "unknown";
      })(ErrorDetails || (ErrorDetails = {}));
      
      /***/ }),
      
      /***/ "./src/events.ts":
      /*!***********************!*\
        !*** ./src/events.ts ***!
        \***********************/
      /*! exports provided: Events */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Events", function() { return Events; });
      /**
       * @readonly
       * @enum {string}
       */
      var Events;
      
      (function (Events) {
        Events["MEDIA_ATTACHING"] = "hlsMediaAttaching";
        Events["MEDIA_ATTACHED"] = "hlsMediaAttached";
        Events["MEDIA_DETACHING"] = "hlsMediaDetaching";
        Events["MEDIA_DETACHED"] = "hlsMediaDetached";
        Events["BUFFER_RESET"] = "hlsBufferReset";
        Events["BUFFER_CODECS"] = "hlsBufferCodecs";
        Events["BUFFER_CREATED"] = "hlsBufferCreated";
        Events["BUFFER_APPENDING"] = "hlsBufferAppending";
        Events["BUFFER_APPENDED"] = "hlsBufferAppended";
        Events["BUFFER_EOS"] = "hlsBufferEos";
        Events["BUFFER_FLUSHING"] = "hlsBufferFlushing";
        Events["BUFFER_FLUSHED"] = "hlsBufferFlushed";
        Events["MANIFEST_LOADING"] = "hlsManifestLoading";
        Events["MANIFEST_LOADED"] = "hlsManifestLoaded";
        Events["MANIFEST_PARSED"] = "hlsManifestParsed";
        Events["LEVEL_SWITCHING"] = "hlsLevelSwitching";
        Events["LEVEL_SWITCHED"] = "hlsLevelSwitched";
        Events["LEVEL_LOADING"] = "hlsLevelLoading";
        Events["LEVEL_LOADED"] = "hlsLevelLoaded";
        Events["LEVEL_UPDATED"] = "hlsLevelUpdated";
        Events["LEVEL_PTS_UPDATED"] = "hlsLevelPtsUpdated";
        Events["LEVELS_UPDATED"] = "hlsLevelsUpdated";
        Events["AUDIO_TRACKS_UPDATED"] = "hlsAudioTracksUpdated";
        Events["AUDIO_TRACK_SWITCHING"] = "hlsAudioTrackSwitching";
        Events["AUDIO_TRACK_SWITCHED"] = "hlsAudioTrackSwitched";
        Events["AUDIO_TRACK_LOADING"] = "hlsAudioTrackLoading";
        Events["AUDIO_TRACK_LOADED"] = "hlsAudioTrackLoaded";
        Events["SUBTITLE_TRACKS_UPDATED"] = "hlsSubtitleTracksUpdated";
        Events["SUBTITLE_TRACKS_CLEARED"] = "hlsSubtitleTracksCleared";
        Events["SUBTITLE_TRACK_SWITCH"] = "hlsSubtitleTrackSwitch";
        Events["SUBTITLE_TRACK_LOADING"] = "hlsSubtitleTrackLoading";
        Events["SUBTITLE_TRACK_LOADED"] = "hlsSubtitleTrackLoaded";
        Events["SUBTITLE_FRAG_PROCESSED"] = "hlsSubtitleFragProcessed";
        Events["CUES_PARSED"] = "hlsCuesParsed";
        Events["NON_NATIVE_TEXT_TRACKS_FOUND"] = "hlsNonNativeTextTracksFound";
        Events["INIT_PTS_FOUND"] = "hlsInitPtsFound";
        Events["FRAG_LOADING"] = "hlsFragLoading";
        Events["FRAG_LOAD_EMERGENCY_ABORTED"] = "hlsFragLoadEmergencyAborted";
        Events["FRAG_LOADED"] = "hlsFragLoaded";
        Events["FRAG_DECRYPTED"] = "hlsFragDecrypted";
        Events["FRAG_PARSING_INIT_SEGMENT"] = "hlsFragParsingInitSegment";
        Events["FRAG_PARSING_USERDATA"] = "hlsFragParsingUserdata";
        Events["FRAG_PARSING_METADATA"] = "hlsFragParsingMetadata";
        Events["FRAG_PARSED"] = "hlsFragParsed";
        Events["FRAG_BUFFERED"] = "hlsFragBuffered";
        Events["FRAG_CHANGED"] = "hlsFragChanged";
        Events["FPS_DROP"] = "hlsFpsDrop";
        Events["FPS_DROP_LEVEL_CAPPING"] = "hlsFpsDropLevelCapping";
        Events["ERROR"] = "hlsError";
        Events["DESTROYING"] = "hlsDestroying";
        Events["KEY_LOADING"] = "hlsKeyLoading";
        Events["KEY_LOADED"] = "hlsKeyLoaded";
        Events["LIVE_BACK_BUFFER_REACHED"] = "hlsLiveBackBufferReached";
        Events["BACK_BUFFER_REACHED"] = "hlsBackBufferReached";
      })(Events || (Events = {}));
      
      /***/ }),
      
      /***/ "./src/hls.ts":
      /*!********************!*\
        !*** ./src/hls.ts ***!
        \********************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Hls; });
      /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js");
      /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_0__);
      /* harmony import */ var _loader_playlist_loader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./loader/playlist-loader */ "./src/loader/playlist-loader.ts");
      /* harmony import */ var _loader_key_loader__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./loader/key-loader */ "./src/loader/key-loader.ts");
      /* harmony import */ var _controller_id3_track_controller__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./controller/id3-track-controller */ "./src/controller/id3-track-controller.ts");
      /* harmony import */ var _controller_latency_controller__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./controller/latency-controller */ "./src/controller/latency-controller.ts");
      /* harmony import */ var _controller_level_controller__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./controller/level-controller */ "./src/controller/level-controller.ts");
      /* harmony import */ var _controller_fragment_tracker__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./controller/fragment-tracker */ "./src/controller/fragment-tracker.ts");
      /* harmony import */ var _controller_stream_controller__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./controller/stream-controller */ "./src/controller/stream-controller.ts");
      /* harmony import */ var _is_supported__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./is-supported */ "./src/is-supported.ts");
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./utils/logger */ "./src/utils/logger.ts");
      /* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./config */ "./src/config.ts");
      /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! eventemitter3 */ "./node_modules/eventemitter3/index.js");
      /* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_11__);
      /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./events */ "./src/events.ts");
      /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./errors */ "./src/errors.ts");
      function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
      
      function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      /**
       * @module Hls
       * @class
       * @constructor
       */
      var Hls = /*#__PURE__*/function () {
        Hls.isSupported = function isSupported() {
          return Object(_is_supported__WEBPACK_IMPORTED_MODULE_8__["isSupported"])();
        };
      
        /**
         * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
         *
         * @constructs Hls
         * @param {HlsConfig} config
         */
        function Hls(userConfig) {
          if (userConfig === void 0) {
            userConfig = {};
          }
      
          this.config = void 0;
          this.userConfig = void 0;
          this.coreComponents = void 0;
          this.networkControllers = void 0;
          this._emitter = new eventemitter3__WEBPACK_IMPORTED_MODULE_11__["EventEmitter"]();
          this._autoLevelCapping = void 0;
          this.abrController = void 0;
          this.bufferController = void 0;
          this.capLevelController = void 0;
          this.latencyController = void 0;
          this.levelController = void 0;
          this.streamController = void 0;
          this.audioTrackController = void 0;
          this.subtitleTrackController = void 0;
          this.emeController = void 0;
          this.cmcdController = void 0;
          this._media = null;
          this.url = null;
          var config = this.config = Object(_config__WEBPACK_IMPORTED_MODULE_10__["mergeConfig"])(Hls.DefaultConfig, userConfig);
          this.userConfig = userConfig;
          Object(_utils_logger__WEBPACK_IMPORTED_MODULE_9__["enableLogs"])(config.debug);
          this._autoLevelCapping = -1;
      
          if (config.progressive) {
            Object(_config__WEBPACK_IMPORTED_MODULE_10__["enableStreamingMode"])(config);
          } // core controllers and network loaders
      
      
          var ConfigAbrController = config.abrController,
              ConfigBufferController = config.bufferController,
              ConfigCapLevelController = config.capLevelController,
              ConfigFpsController = config.fpsController;
          var abrController = this.abrController = new ConfigAbrController(this);
          var bufferController = this.bufferController = new ConfigBufferController(this);
          var capLevelController = this.capLevelController = new ConfigCapLevelController(this);
          var fpsController = new ConfigFpsController(this);
          var playListLoader = new _loader_playlist_loader__WEBPACK_IMPORTED_MODULE_1__["default"](this);
          var keyLoader = new _loader_key_loader__WEBPACK_IMPORTED_MODULE_2__["default"](this);
          var id3TrackController = new _controller_id3_track_controller__WEBPACK_IMPORTED_MODULE_3__["default"](this); // network controllers
      
          var levelController = this.levelController = new _controller_level_controller__WEBPACK_IMPORTED_MODULE_5__["default"](this); // FragmentTracker must be defined before StreamController because the order of event handling is important
      
          var fragmentTracker = new _controller_fragment_tracker__WEBPACK_IMPORTED_MODULE_6__["FragmentTracker"](this);
          var streamController = this.streamController = new _controller_stream_controller__WEBPACK_IMPORTED_MODULE_7__["default"](this, fragmentTracker); // Cap level controller uses streamController to flush the buffer
      
          capLevelController.setStreamController(streamController); // fpsController uses streamController to switch when frames are being dropped
      
          fpsController.setStreamController(streamController);
          var networkControllers = [levelController, streamController];
          this.networkControllers = networkControllers;
          var coreComponents = [playListLoader, keyLoader, abrController, bufferController, capLevelController, fpsController, id3TrackController, fragmentTracker];
          this.audioTrackController = this.createController(config.audioTrackController, null, networkControllers);
          this.createController(config.audioStreamController, fragmentTracker, networkControllers); // subtitleTrackController must be defined before  because the order of event handling is important
      
          this.subtitleTrackController = this.createController(config.subtitleTrackController, null, networkControllers);
          this.createController(config.subtitleStreamController, fragmentTracker, networkControllers);
          this.createController(config.timelineController, null, coreComponents);
          this.emeController = this.createController(config.emeController, null, coreComponents);
          this.cmcdController = this.createController(config.cmcdController, null, coreComponents);
          this.latencyController = this.createController(_controller_latency_controller__WEBPACK_IMPORTED_MODULE_4__["default"], null, coreComponents);
          this.coreComponents = coreComponents;
        }
      
        var _proto = Hls.prototype;
      
        _proto.createController = function createController(ControllerClass, fragmentTracker, components) {
          if (ControllerClass) {
            var controllerInstance = fragmentTracker ? new ControllerClass(this, fragmentTracker) : new ControllerClass(this);
      
            if (components) {
              components.push(controllerInstance);
            }
      
            return controllerInstance;
          }
      
          return null;
        } // Delegate the EventEmitter through the public API of Hls.js
        ;
      
        _proto.on = function on(event, listener, context) {
          if (context === void 0) {
            context = this;
          }
      
          this._emitter.on(event, listener, context);
        };
      
        _proto.once = function once(event, listener, context) {
          if (context === void 0) {
            context = this;
          }
      
          this._emitter.once(event, listener, context);
        };
      
        _proto.removeAllListeners = function removeAllListeners(event) {
          this._emitter.removeAllListeners(event);
        };
      
        _proto.off = function off(event, listener, context, once) {
          if (context === void 0) {
            context = this;
          }
      
          this._emitter.off(event, listener, context, once);
        };
      
        _proto.listeners = function listeners(event) {
          return this._emitter.listeners(event);
        };
      
        _proto.emit = function emit(event, name, eventObject) {
          return this._emitter.emit(event, name, eventObject);
        };
      
        _proto.trigger = function trigger(event, eventObject) {
          if (this.config.debug) {
            return this.emit(event, event, eventObject);
          } else {
            try {
              return this.emit(event, event, eventObject);
            } catch (e) {
              _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].error('An internal error happened while handling event ' + event + '. Error message: "' + e.message + '". Here is a stacktrace:', e);
              this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].ERROR, {
                type: _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorTypes"].OTHER_ERROR,
                details: _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"].INTERNAL_EXCEPTION,
                fatal: false,
                event: event,
                error: e
              });
            }
          }
      
          return false;
        };
      
        _proto.listenerCount = function listenerCount(event) {
          return this._emitter.listenerCount(event);
        }
        /**
         * Dispose of the instance
         */
        ;
      
        _proto.destroy = function destroy() {
          _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('destroy');
          this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].DESTROYING, undefined);
          this.detachMedia();
          this.removeAllListeners();
          this._autoLevelCapping = -1;
          this.url = null;
          this.networkControllers.forEach(function (component) {
            return component.destroy();
          });
          this.networkControllers.length = 0;
          this.coreComponents.forEach(function (component) {
            return component.destroy();
          });
          this.coreComponents.length = 0;
        }
        /**
         * Attaches Hls.js to a media element
         * @param {HTMLMediaElement} media
         */
        ;
      
        _proto.attachMedia = function attachMedia(media) {
          _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('attachMedia');
          this._media = media;
          this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].MEDIA_ATTACHING, {
            media: media
          });
        }
        /**
         * Detach Hls.js from the media
         */
        ;
      
        _proto.detachMedia = function detachMedia() {
          _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('detachMedia');
          this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].MEDIA_DETACHING, undefined);
          this._media = null;
        }
        /**
         * Set the source URL. Can be relative or absolute.
         * @param {string} url
         */
        ;
      
        _proto.loadSource = function loadSource(url) {
          this.stopLoad();
          var media = this.media;
          var loadedSource = this.url;
          var loadingSource = this.url = url_toolkit__WEBPACK_IMPORTED_MODULE_0__["buildAbsoluteURL"](self.location.href, url, {
            alwaysNormalize: true
          });
          _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("loadSource:" + loadingSource);
      
          if (media && loadedSource && loadedSource !== loadingSource && this.bufferController.hasSourceTypes()) {
            this.detachMedia();
            this.attachMedia(media);
          } // when attaching to a source URL, trigger a playlist load
      
      
          this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].MANIFEST_LOADING, {
            url: url
          });
        }
        /**
         * Start loading data from the stream source.
         * Depending on default config, client starts loading automatically when a source is set.
         *
         * @param {number} startPosition Set the start position to stream from
         * @default -1 None (from earliest point)
         */
        ;
      
        _proto.startLoad = function startLoad(startPosition) {
          if (startPosition === void 0) {
            startPosition = -1;
          }
      
          _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("startLoad(" + startPosition + ")");
          this.networkControllers.forEach(function (controller) {
            controller.startLoad(startPosition);
          });
        }
        /**
         * Stop loading of any stream data.
         */
        ;
      
        _proto.stopLoad = function stopLoad() {
          _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('stopLoad');
          this.networkControllers.forEach(function (controller) {
            controller.stopLoad();
          });
        }
        /**
         * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)
         */
        ;
      
        _proto.swapAudioCodec = function swapAudioCodec() {
          _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('swapAudioCodec');
          this.streamController.swapAudioCodec();
        }
        /**
         * When the media-element fails, this allows to detach and then re-attach it
         * as one call (convenience method).
         *
         * Automatic recovery of media-errors by this process is configurable.
         */
        ;
      
        _proto.recoverMediaError = function recoverMediaError() {
          _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('recoverMediaError');
          var media = this._media;
          this.detachMedia();
      
          if (media) {
            this.attachMedia(media);
          }
        };
      
        _proto.removeLevel = function removeLevel(levelIndex, urlId) {
          if (urlId === void 0) {
            urlId = 0;
          }
      
          this.levelController.removeLevel(levelIndex, urlId);
        }
        /**
         * @type {Level[]}
         */
        ;
      
        _createClass(Hls, [{
          key: "levels",
          get: function get() {
            var levels = this.levelController.levels;
            return levels ? levels : [];
          }
          /**
           * Index of quality level currently played
           * @type {number}
           */
      
        }, {
          key: "currentLevel",
          get: function get() {
            return this.streamController.currentLevel;
          }
          /**
           * Set quality level index immediately .
           * This will flush the current buffer to replace the quality asap.
           * That means playback will interrupt at least shortly to re-buffer and re-sync eventually.
           * @type {number} -1 for automatic level selection
           */
          ,
          set: function set(newLevel) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set currentLevel:" + newLevel);
            this.loadLevel = newLevel;
            this.abrController.clearTimer();
            this.streamController.immediateLevelSwitch();
          }
          /**
           * Index of next quality level loaded as scheduled by stream controller.
           * @type {number}
           */
      
        }, {
          key: "nextLevel",
          get: function get() {
            return this.streamController.nextLevel;
          }
          /**
           * Set quality level index for next loaded data.
           * This will switch the video quality asap, without interrupting playback.
           * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).
           * @type {number} -1 for automatic level selection
           */
          ,
          set: function set(newLevel) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set nextLevel:" + newLevel);
            this.levelController.manualLevel = newLevel;
            this.streamController.nextLevelSwitch();
          }
          /**
           * Return the quality level of the currently or last (of none is loaded currently) segment
           * @type {number}
           */
      
        }, {
          key: "loadLevel",
          get: function get() {
            return this.levelController.level;
          }
          /**
           * Set quality level index for next loaded data in a conservative way.
           * This will switch the quality without flushing, but interrupt current loading.
           * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.
           * @type {number} newLevel -1 for automatic level selection
           */
          ,
          set: function set(newLevel) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set loadLevel:" + newLevel);
            this.levelController.manualLevel = newLevel;
          }
          /**
           * get next quality level loaded
           * @type {number}
           */
      
        }, {
          key: "nextLoadLevel",
          get: function get() {
            return this.levelController.nextLoadLevel;
          }
          /**
           * Set quality level of next loaded segment in a fully "non-destructive" way.
           * Same as `loadLevel` but will wait for next switch (until current loading is done).
           * @type {number} level
           */
          ,
          set: function set(level) {
            this.levelController.nextLoadLevel = level;
          }
          /**
           * Return "first level": like a default level, if not set,
           * falls back to index of first level referenced in manifest
           * @type {number}
           */
      
        }, {
          key: "firstLevel",
          get: function get() {
            return Math.max(this.levelController.firstLevel, this.minAutoLevel);
          }
          /**
           * Sets "first-level", see getter.
           * @type {number}
           */
          ,
          set: function set(newLevel) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set firstLevel:" + newLevel);
            this.levelController.firstLevel = newLevel;
          }
          /**
           * Return start level (level of first fragment that will be played back)
           * if not overrided by user, first level appearing in manifest will be used as start level
           * if -1 : automatic start level selection, playback will start from level matching download bandwidth
           * (determined from download of first segment)
           * @type {number}
           */
      
        }, {
          key: "startLevel",
          get: function get() {
            return this.levelController.startLevel;
          }
          /**
           * set  start level (level of first fragment that will be played back)
           * if not overrided by user, first level appearing in manifest will be used as start level
           * if -1 : automatic start level selection, playback will start from level matching download bandwidth
           * (determined from download of first segment)
           * @type {number} newLevel
           */
          ,
          set: function set(newLevel) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set startLevel:" + newLevel); // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel
      
            if (newLevel !== -1) {
              newLevel = Math.max(newLevel, this.minAutoLevel);
            }
      
            this.levelController.startLevel = newLevel;
          }
          /**
           * Get the current setting for capLevelToPlayerSize
           *
           * @type {boolean}
           */
      
        }, {
          key: "capLevelToPlayerSize",
          get: function get() {
            return this.config.capLevelToPlayerSize;
          }
          /**
           * set  dynamically set capLevelToPlayerSize against (`CapLevelController`)
           *
           * @type {boolean}
           */
          ,
          set: function set(shouldStartCapping) {
            var newCapLevelToPlayerSize = !!shouldStartCapping;
      
            if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {
              if (newCapLevelToPlayerSize) {
                this.capLevelController.startCapping(); // If capping occurs, nextLevelSwitch will happen based on size.
              } else {
                this.capLevelController.stopCapping();
                this.autoLevelCapping = -1;
                this.streamController.nextLevelSwitch(); // Now we're uncapped, get the next level asap.
              }
      
              this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;
            }
          }
          /**
           * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
           * @type {number}
           */
      
        }, {
          key: "autoLevelCapping",
          get: function get() {
            return this._autoLevelCapping;
          }
          /**
           * get bandwidth estimate
           * @type {number}
           */
          ,
          set:
          /**
           * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
           * @type {number}
           */
          function set(newLevel) {
            if (this._autoLevelCapping !== newLevel) {
              _utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set autoLevelCapping:" + newLevel);
              this._autoLevelCapping = newLevel;
            }
          }
          /**
           * True when automatic level selection enabled
           * @type {boolean}
           */
      
        }, {
          key: "bandwidthEstimate",
          get: function get() {
            var bwEstimator = this.abrController.bwEstimator;
      
            if (!bwEstimator) {
              return NaN;
            }
      
            return bwEstimator.getEstimate();
          }
        }, {
          key: "autoLevelEnabled",
          get: function get() {
            return this.levelController.manualLevel === -1;
          }
          /**
           * Level set manually (if any)
           * @type {number}
           */
      
        }, {
          key: "manualLevel",
          get: function get() {
            return this.levelController.manualLevel;
          }
          /**
           * min level selectable in auto mode according to config.minAutoBitrate
           * @type {number}
           */
      
        }, {
          key: "minAutoLevel",
          get: function get() {
            var levels = this.levels,
                minAutoBitrate = this.config.minAutoBitrate;
            if (!levels) return 0;
            var len = levels.length;
      
            for (var i = 0; i < len; i++) {
              if (levels[i].maxBitrate > minAutoBitrate) {
                return i;
              }
            }
      
            return 0;
          }
          /**
           * max level selectable in auto mode according to autoLevelCapping
           * @type {number}
           */
      
        }, {
          key: "maxAutoLevel",
          get: function get() {
            var levels = this.levels,
                autoLevelCapping = this.autoLevelCapping;
            var maxAutoLevel;
      
            if (autoLevelCapping === -1 && levels && levels.length) {
              maxAutoLevel = levels.length - 1;
            } else {
              maxAutoLevel = autoLevelCapping;
            }
      
            return maxAutoLevel;
          }
          /**
           * next automatically selected quality level
           * @type {number}
           */
      
        }, {
          key: "nextAutoLevel",
          get: function get() {
            // ensure next auto level is between  min and max auto level
            return Math.min(Math.max(this.abrController.nextAutoLevel, this.minAutoLevel), this.maxAutoLevel);
          }
          /**
           * this setter is used to force next auto level.
           * this is useful to force a switch down in auto mode:
           * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)
           * forced value is valid for one fragment. upon succesful frag loading at forced level,
           * this value will be resetted to -1 by ABR controller.
           * @type {number}
           */
          ,
          set: function set(nextLevel) {
            this.abrController.nextAutoLevel = Math.max(this.minAutoLevel, nextLevel);
          }
          /**
           * @type {AudioTrack[]}
           */
      
        }, {
          key: "audioTracks",
          get: function get() {
            var audioTrackController = this.audioTrackController;
            return audioTrackController ? audioTrackController.audioTracks : [];
          }
          /**
           * index of the selected audio track (index in audio track lists)
           * @type {number}
           */
      
        }, {
          key: "audioTrack",
          get: function get() {
            var audioTrackController = this.audioTrackController;
            return audioTrackController ? audioTrackController.audioTrack : -1;
          }
          /**
           * selects an audio track, based on its index in audio track lists
           * @type {number}
           */
          ,
          set: function set(audioTrackId) {
            var audioTrackController = this.audioTrackController;
      
            if (audioTrackController) {
              audioTrackController.audioTrack = audioTrackId;
            }
          }
          /**
           * get alternate subtitle tracks list from playlist
           * @type {MediaPlaylist[]}
           */
      
        }, {
          key: "subtitleTracks",
          get: function get() {
            var subtitleTrackController = this.subtitleTrackController;
            return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
          }
          /**
           * index of the selected subtitle track (index in subtitle track lists)
           * @type {number}
           */
      
        }, {
          key: "subtitleTrack",
          get: function get() {
            var subtitleTrackController = this.subtitleTrackController;
            return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
          },
          set:
          /**
           * select an subtitle track, based on its index in subtitle track lists
           * @type {number}
           */
          function set(subtitleTrackId) {
            var subtitleTrackController = this.subtitleTrackController;
      
            if (subtitleTrackController) {
              subtitleTrackController.subtitleTrack = subtitleTrackId;
            }
          }
          /**
           * @type {boolean}
           */
      
        }, {
          key: "media",
          get: function get() {
            return this._media;
          }
        }, {
          key: "subtitleDisplay",
          get: function get() {
            var subtitleTrackController = this.subtitleTrackController;
            return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
          }
          /**
           * Enable/disable subtitle display rendering
           * @type {boolean}
           */
          ,
          set: function set(value) {
            var subtitleTrackController = this.subtitleTrackController;
      
            if (subtitleTrackController) {
              subtitleTrackController.subtitleDisplay = value;
            }
          }
          /**
           * get mode for Low-Latency HLS loading
           * @type {boolean}
           */
      
        }, {
          key: "lowLatencyMode",
          get: function get() {
            return this.config.lowLatencyMode;
          }
          /**
           * Enable/disable Low-Latency HLS part playlist and segment loading, and start live streams at playlist PART-HOLD-BACK rather than HOLD-BACK.
           * @type {boolean}
           */
          ,
          set: function set(mode) {
            this.config.lowLatencyMode = mode;
          }
          /**
           * position (in seconds) of live sync point (ie edge of live position minus safety delay defined by ```hls.config.liveSyncDuration```)
           * @type {number}
           */
      
        }, {
          key: "liveSyncPosition",
          get: function get() {
            return this.latencyController.liveSyncPosition;
          }
          /**
           * estimated position (in seconds) of live edge (ie edge of live playlist plus time sync playlist advanced)
           * returns 0 before first playlist is loaded
           * @type {number}
           */
      
        }, {
          key: "latency",
          get: function get() {
            return this.latencyController.latency;
          }
          /**
           * maximum distance from the edge before the player seeks forward to ```hls.liveSyncPosition```
           * configured using ```liveMaxLatencyDurationCount``` (multiple of target duration) or ```liveMaxLatencyDuration```
           * returns 0 before first playlist is loaded
           * @type {number}
           */
      
        }, {
          key: "maxLatency",
          get: function get() {
            return this.latencyController.maxLatency;
          }
          /**
           * target distance from the edge as calculated by the latency controller
           * @type {number}
           */
      
        }, {
          key: "targetLatency",
          get: function get() {
            return this.latencyController.targetLatency;
          }
          /**
           * the rate at which the edge of the current live playlist is advancing or 1 if there is none
           * @type {number}
           */
      
        }, {
          key: "drift",
          get: function get() {
            return this.latencyController.drift;
          }
          /**
           * set to true when startLoad is called before MANIFEST_PARSED event
           * @type {boolean}
           */
      
        }, {
          key: "forceStartLoad",
          get: function get() {
            return this.streamController.forceStartLoad;
          }
        }], [{
          key: "version",
          get: function get() {
            return "1.1.2";
          }
        }, {
          key: "Events",
          get: function get() {
            return _events__WEBPACK_IMPORTED_MODULE_12__["Events"];
          }
        }, {
          key: "ErrorTypes",
          get: function get() {
            return _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorTypes"];
          }
        }, {
          key: "ErrorDetails",
          get: function get() {
            return _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"];
          }
        }, {
          key: "DefaultConfig",
          get: function get() {
            if (!Hls.defaultConfig) {
              return _config__WEBPACK_IMPORTED_MODULE_10__["hlsDefaultConfig"];
            }
      
            return Hls.defaultConfig;
          }
          /**
           * @type {HlsConfig}
           */
          ,
          set: function set(defaultConfig) {
            Hls.defaultConfig = defaultConfig;
          }
        }]);
      
        return Hls;
      }();
      
      Hls.defaultConfig = void 0;
      
      
      /***/ }),
      
      /***/ "./src/is-supported.ts":
      /*!*****************************!*\
        !*** ./src/is-supported.ts ***!
        \*****************************/
      /*! exports provided: isSupported, changeTypeSupported */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isSupported", function() { return isSupported; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "changeTypeSupported", function() { return changeTypeSupported; });
      /* harmony import */ var _utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/mediasource-helper */ "./src/utils/mediasource-helper.ts");
      
      
      function getSourceBuffer() {
        return self.SourceBuffer || self.WebKitSourceBuffer;
      }
      
      function isSupported() {
        var mediaSource = Object(_utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_0__["getMediaSource"])();
      
        if (!mediaSource) {
          return false;
        }
      
        var sourceBuffer = getSourceBuffer();
        var isTypeSupported = mediaSource && typeof mediaSource.isTypeSupported === 'function' && mediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'); // if SourceBuffer is exposed ensure its API is valid
        // safari and old version of Chrome doe not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible
      
        var sourceBufferValidAPI = !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function';
        return !!isTypeSupported && !!sourceBufferValidAPI;
      }
      function changeTypeSupported() {
        var _sourceBuffer$prototy;
      
        var sourceBuffer = getSourceBuffer();
        return typeof (sourceBuffer === null || sourceBuffer === void 0 ? void 0 : (_sourceBuffer$prototy = sourceBuffer.prototype) === null || _sourceBuffer$prototy === void 0 ? void 0 : _sourceBuffer$prototy.changeType) === 'function';
      }
      
      /***/ }),
      
      /***/ "./src/loader/fragment-loader.ts":
      /*!***************************************!*\
        !*** ./src/loader/fragment-loader.ts ***!
        \***************************************/
      /*! exports provided: default, LoadError */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return FragmentLoader; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoadError", function() { return LoadError; });
      /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
      /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
      
      
      
      function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
      
      function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
      
      function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
      
      function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
      
      function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
      
      function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
      
      function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
      
      
      var MIN_CHUNK_SIZE = Math.pow(2, 17); // 128kb
      
      var FragmentLoader = /*#__PURE__*/function () {
        function FragmentLoader(config) {
          this.config = void 0;
          this.loader = null;
          this.partLoadTimeout = -1;
          this.config = config;
        }
      
        var _proto = FragmentLoader.prototype;
      
        _proto.destroy = function destroy() {
          if (this.loader) {
            this.loader.destroy();
            this.loader = null;
          }
        };
      
        _proto.abort = function abort() {
          if (this.loader) {
            // Abort the loader for current fragment. Only one may load at any given time
            this.loader.abort();
          }
        };
      
        _proto.load = function load(frag, _onProgress) {
          var _this = this;
      
          var url = frag.url;
      
          if (!url) {
            return Promise.reject(new LoadError({
              type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
              details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_ERROR,
              fatal: false,
              frag: frag,
              networkDetails: null
            }, "Fragment does not have a " + (url ? 'part list' : 'url')));
          }
      
          this.abort();
          var config = this.config;
          var FragmentILoader = config.fLoader;
          var DefaultILoader = config.loader;
          return new Promise(function (resolve, reject) {
            if (_this.loader) {
              _this.loader.destroy();
            }
      
            var loader = _this.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
            var loaderContext = createLoaderContext(frag);
            var loaderConfig = {
              timeout: config.fragLoadingTimeOut,
              maxRetry: 0,
              retryDelay: 0,
              maxRetryDelay: config.fragLoadingMaxRetryTimeout,
              highWaterMark: MIN_CHUNK_SIZE
            }; // Assign frag stats to the loader's stats reference
      
            frag.stats = loader.stats;
            loader.load(loaderContext, loaderConfig, {
              onSuccess: function onSuccess(response, stats, context, networkDetails) {
                _this.resetLoader(frag, loader);
      
                resolve({
                  frag: frag,
                  part: null,
                  payload: response.data,
                  networkDetails: networkDetails
                });
              },
              onError: function onError(response, context, networkDetails) {
                _this.resetLoader(frag, loader);
      
                reject(new LoadError({
                  type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
                  details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_ERROR,
                  fatal: false,
                  frag: frag,
                  response: response,
                  networkDetails: networkDetails
                }));
              },
              onAbort: function onAbort(stats, context, networkDetails) {
                _this.resetLoader(frag, loader);
      
                reject(new LoadError({
                  type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
                  details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].INTERNAL_ABORTED,
                  fatal: false,
                  frag: frag,
                  networkDetails: networkDetails
                }));
              },
              onTimeout: function onTimeout(response, context, networkDetails) {
                _this.resetLoader(frag, loader);
      
                reject(new LoadError({
                  type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
                  details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_TIMEOUT,
                  fatal: false,
                  frag: frag,
                  networkDetails: networkDetails
                }));
              },
              onProgress: function onProgress(stats, context, data, networkDetails) {
                if (_onProgress) {
                  _onProgress({
                    frag: frag,
                    part: null,
                    payload: data,
                    networkDetails: networkDetails
                  });
                }
              }
            });
          });
        };
      
        _proto.loadPart = function loadPart(frag, part, onProgress) {
          var _this2 = this;
      
          this.abort();
          var config = this.config;
          var FragmentILoader = config.fLoader;
          var DefaultILoader = config.loader;
          return new Promise(function (resolve, reject) {
            if (_this2.loader) {
              _this2.loader.destroy();
            }
      
            var loader = _this2.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
            var loaderContext = createLoaderContext(frag, part);
            var loaderConfig = {
              timeout: config.fragLoadingTimeOut,
              maxRetry: 0,
              retryDelay: 0,
              maxRetryDelay: config.fragLoadingMaxRetryTimeout,
              highWaterMark: MIN_CHUNK_SIZE
            }; // Assign part stats to the loader's stats reference
      
            part.stats = loader.stats;
            loader.load(loaderContext, loaderConfig, {
              onSuccess: function onSuccess(response, stats, context, networkDetails) {
                _this2.resetLoader(frag, loader);
      
                _this2.updateStatsFromPart(frag, part);
      
                var partLoadedData = {
                  frag: frag,
                  part: part,
                  payload: response.data,
                  networkDetails: networkDetails
                };
                onProgress(partLoadedData);
                resolve(partLoadedData);
              },
              onError: function onError(response, context, networkDetails) {
                _this2.resetLoader(frag, loader);
      
                reject(new LoadError({
                  type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
                  details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_ERROR,
                  fatal: false,
                  frag: frag,
                  part: part,
                  response: response,
                  networkDetails: networkDetails
                }));
              },
              onAbort: function onAbort(stats, context, networkDetails) {
                frag.stats.aborted = part.stats.aborted;
      
                _this2.resetLoader(frag, loader);
      
                reject(new LoadError({
                  type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
                  details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].INTERNAL_ABORTED,
                  fatal: false,
                  frag: frag,
                  part: part,
                  networkDetails: networkDetails
                }));
              },
              onTimeout: function onTimeout(response, context, networkDetails) {
                _this2.resetLoader(frag, loader);
      
                reject(new LoadError({
                  type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
                  details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_TIMEOUT,
                  fatal: false,
                  frag: frag,
                  part: part,
                  networkDetails: networkDetails
                }));
              }
            });
          });
        };
      
        _proto.updateStatsFromPart = function updateStatsFromPart(frag, part) {
          var fragStats = frag.stats;
          var partStats = part.stats;
          var partTotal = partStats.total;
          fragStats.loaded += partStats.loaded;
      
          if (partTotal) {
            var estTotalParts = Math.round(frag.duration / part.duration);
            var estLoadedParts = Math.min(Math.round(fragStats.loaded / partTotal), estTotalParts);
            var estRemainingParts = estTotalParts - estLoadedParts;
            var estRemainingBytes = estRemainingParts * Math.round(fragStats.loaded / estLoadedParts);
            fragStats.total = fragStats.loaded + estRemainingBytes;
          } else {
            fragStats.total = Math.max(fragStats.loaded, fragStats.total);
          }
      
          var fragLoading = fragStats.loading;
          var partLoading = partStats.loading;
      
          if (fragLoading.start) {
            // add to fragment loader latency
            fragLoading.first += partLoading.first - partLoading.start;
          } else {
            fragLoading.start = partLoading.start;
            fragLoading.first = partLoading.first;
          }
      
          fragLoading.end = partLoading.end;
        };
      
        _proto.resetLoader = function resetLoader(frag, loader) {
          frag.loader = null;
      
          if (this.loader === loader) {
            self.clearTimeout(this.partLoadTimeout);
            this.loader = null;
          }
      
          loader.destroy();
        };
      
        return FragmentLoader;
      }();
      
      
      
      function createLoaderContext(frag, part) {
        if (part === void 0) {
          part = null;
        }
      
        var segment = part || frag;
        var loaderContext = {
          frag: frag,
          part: part,
          responseType: 'arraybuffer',
          url: segment.url,
          headers: {},
          rangeStart: 0,
          rangeEnd: 0
        };
        var start = segment.byteRangeStartOffset;
        var end = segment.byteRangeEndOffset;
      
        if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(start) && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(end)) {
          loaderContext.rangeStart = start;
          loaderContext.rangeEnd = end;
        }
      
        return loaderContext;
      }
      
      var LoadError = /*#__PURE__*/function (_Error) {
        _inheritsLoose(LoadError, _Error);
      
        function LoadError(data) {
          var _this3;
      
          for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
            params[_key - 1] = arguments[_key];
          }
      
          _this3 = _Error.call.apply(_Error, [this].concat(params)) || this;
          _this3.data = void 0;
          _this3.data = data;
          return _this3;
        }
      
        return LoadError;
      }( /*#__PURE__*/_wrapNativeSuper(Error));
      
      /***/ }),
      
      /***/ "./src/loader/fragment.ts":
      /*!********************************!*\
        !*** ./src/loader/fragment.ts ***!
        \********************************/
      /*! exports provided: ElementaryStreamTypes, BaseSegment, Fragment, Part */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ElementaryStreamTypes", function() { return ElementaryStreamTypes; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BaseSegment", function() { return BaseSegment; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Fragment", function() { return Fragment; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Part", function() { return Part; });
      /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
      /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js");
      /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_1__);
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      /* harmony import */ var _level_key__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./level-key */ "./src/loader/level-key.ts");
      /* harmony import */ var _load_stats__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./load-stats */ "./src/loader/load-stats.ts");
      
      
      
      function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
      
      function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
      
      function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
      
      function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
      
      
      
      
      
      var ElementaryStreamTypes;
      
      (function (ElementaryStreamTypes) {
        ElementaryStreamTypes["AUDIO"] = "audio";
        ElementaryStreamTypes["VIDEO"] = "video";
        ElementaryStreamTypes["AUDIOVIDEO"] = "audiovideo";
      })(ElementaryStreamTypes || (ElementaryStreamTypes = {}));
      
      var BaseSegment = /*#__PURE__*/function () {
        // baseurl is the URL to the playlist
        // relurl is the portion of the URL that comes from inside the playlist.
        // Holds the types of data this fragment supports
        function BaseSegment(baseurl) {
          var _this$elementaryStrea;
      
          this._byteRange = null;
          this._url = null;
          this.baseurl = void 0;
          this.relurl = void 0;
          this.elementaryStreams = (_this$elementaryStrea = {}, _this$elementaryStrea[ElementaryStreamTypes.AUDIO] = null, _this$elementaryStrea[ElementaryStreamTypes.VIDEO] = null, _this$elementaryStrea[ElementaryStreamTypes.AUDIOVIDEO] = null, _this$elementaryStrea);
          this.baseurl = baseurl;
        } // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array
      
      
        var _proto = BaseSegment.prototype;
      
        _proto.setByteRange = function setByteRange(value, previous) {
          var params = value.split('@', 2);
          var byteRange = [];
      
          if (params.length === 1) {
            byteRange[0] = previous ? previous.byteRangeEndOffset : 0;
          } else {
            byteRange[0] = parseInt(params[1]);
          }
      
          byteRange[1] = parseInt(params[0]) + byteRange[0];
          this._byteRange = byteRange;
        };
      
        _createClass(BaseSegment, [{
          key: "byteRange",
          get: function get() {
            if (!this._byteRange) {
              return [];
            }
      
            return this._byteRange;
          }
        }, {
          key: "byteRangeStartOffset",
          get: function get() {
            return this.byteRange[0];
          }
        }, {
          key: "byteRangeEndOffset",
          get: function get() {
            return this.byteRange[1];
          }
        }, {
          key: "url",
          get: function get() {
            if (!this._url && this.baseurl && this.relurl) {
              this._url = Object(url_toolkit__WEBPACK_IMPORTED_MODULE_1__["buildAbsoluteURL"])(this.baseurl, this.relurl, {
                alwaysNormalize: true
              });
            }
      
            return this._url || '';
          },
          set: function set(value) {
            this._url = value;
          }
        }]);
      
        return BaseSegment;
      }();
      var Fragment = /*#__PURE__*/function (_BaseSegment) {
        _inheritsLoose(Fragment, _BaseSegment);
      
        // EXTINF has to be present for a m38 to be considered valid
        // sn notates the sequence number for a segment, and if set to a string can be 'initSegment'
        // levelkey is the EXT-X-KEY that applies to this segment for decryption
        // core difference from the private field _decryptdata is the lack of the initialized IV
        // _decryptdata will set the IV for this segment based on the segment number in the fragment
        // A string representing the fragment type
        // A reference to the loader. Set while the fragment is loading, and removed afterwards. Used to abort fragment loading
        // The level/track index to which the fragment belongs
        // The continuity counter of the fragment
        // The starting Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.
        // The ending Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.
        // The latest Presentation Time Stamp (PTS) appended to the buffer.
        // The starting Decode Time Stamp (DTS) of the fragment. Set after transmux complete.
        // The ending Decode Time Stamp (DTS) of the fragment. Set after transmux complete.
        // The start time of the fragment, as listed in the manifest. Updated after transmux complete.
        // Set by `updateFragPTSDTS` in level-helper
        // The maximum starting Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.
        // The minimum ending Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.
        // Load/parse timing information
        // A flag indicating whether the segment was downloaded in order to test bitrate, and was not buffered
        // #EXTINF  segment title
        // The Media Initialization Section for this segment
        function Fragment(type, baseurl) {
          var _this;
      
          _this = _BaseSegment.call(this, baseurl) || this;
          _this._decryptdata = null;
          _this.rawProgramDateTime = null;
          _this.programDateTime = null;
          _this.tagList = [];
          _this.duration = 0;
          _this.sn = 0;
          _this.levelkey = void 0;
          _this.type = void 0;
          _this.loader = null;
          _this.level = -1;
          _this.cc = 0;
          _this.startPTS = void 0;
          _this.endPTS = void 0;
          _this.appendedPTS = void 0;
          _this.startDTS = void 0;
          _this.endDTS = void 0;
          _this.start = 0;
          _this.deltaPTS = void 0;
          _this.maxStartPTS = void 0;
          _this.minEndPTS = void 0;
          _this.stats = new _load_stats__WEBPACK_IMPORTED_MODULE_4__["LoadStats"]();
          _this.urlId = 0;
          _this.data = void 0;
          _this.bitrateTest = false;
          _this.title = null;
          _this.initSegment = null;
          _this.type = type;
          return _this;
        }
      
        var _proto2 = Fragment.prototype;
      
        /**
         * Utility method for parseLevelPlaylist to create an initialization vector for a given segment
         * @param {number} segmentNumber - segment number to generate IV with
         * @returns {Uint8Array}
         */
        _proto2.createInitializationVector = function createInitializationVector(segmentNumber) {
          var uint8View = new Uint8Array(16);
      
          for (var i = 12; i < 16; i++) {
            uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff;
          }
      
          return uint8View;
        }
        /**
         * Utility method for parseLevelPlaylist to get a fragment's decryption data from the currently parsed encryption key data
         * @param levelkey - a playlist's encryption info
         * @param segmentNumber - the fragment's segment number
         * @returns {LevelKey} - an object to be applied as a fragment's decryptdata
         */
        ;
      
        _proto2.setDecryptDataFromLevelKey = function setDecryptDataFromLevelKey(levelkey, segmentNumber) {
          var decryptdata = levelkey;
      
          if ((levelkey === null || levelkey === void 0 ? void 0 : levelkey.method) === 'AES-128' && levelkey.uri && !levelkey.iv) {
            decryptdata = _level_key__WEBPACK_IMPORTED_MODULE_3__["LevelKey"].fromURI(levelkey.uri);
            decryptdata.method = levelkey.method;
            decryptdata.iv = this.createInitializationVector(segmentNumber);
            decryptdata.keyFormat = 'identity';
          }
      
          return decryptdata;
        };
      
        _proto2.setElementaryStreamInfo = function setElementaryStreamInfo(type, startPTS, endPTS, startDTS, endDTS, partial) {
          if (partial === void 0) {
            partial = false;
          }
      
          var elementaryStreams = this.elementaryStreams;
          var info = elementaryStreams[type];
      
          if (!info) {
            elementaryStreams[type] = {
              startPTS: startPTS,
              endPTS: endPTS,
              startDTS: startDTS,
              endDTS: endDTS,
              partial: partial
            };
            return;
          }
      
          info.startPTS = Math.min(info.startPTS, startPTS);
          info.endPTS = Math.max(info.endPTS, endPTS);
          info.startDTS = Math.min(info.startDTS, startDTS);
          info.endDTS = Math.max(info.endDTS, endDTS);
        };
      
        _proto2.clearElementaryStreamInfo = function clearElementaryStreamInfo() {
          var elementaryStreams = this.elementaryStreams;
          elementaryStreams[ElementaryStreamTypes.AUDIO] = null;
          elementaryStreams[ElementaryStreamTypes.VIDEO] = null;
          elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO] = null;
        };
      
        _createClass(Fragment, [{
          key: "decryptdata",
          get: function get() {
            if (!this.levelkey && !this._decryptdata) {
              return null;
            }
      
            if (!this._decryptdata && this.levelkey) {
              var sn = this.sn;
      
              if (typeof sn !== 'number') {
                // We are fetching decryption data for a initialization segment
                // If the segment was encrypted with AES-128
                // It must have an IV defined. We cannot substitute the Segment Number in.
                if (this.levelkey && this.levelkey.method === 'AES-128' && !this.levelkey.iv) {
                  _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("missing IV for initialization segment with method=\"" + this.levelkey.method + "\" - compliance issue");
                }
                /*
                Be converted to a Number.
                'initSegment' will become NaN.
                NaN, which when converted through ToInt32() -> +0.
                ---
                Explicitly set sn to resulting value from implicit conversions 'initSegment' values for IV generation.
                */
      
      
                sn = 0;
              }
      
              this._decryptdata = this.setDecryptDataFromLevelKey(this.levelkey, sn);
            }
      
            return this._decryptdata;
          }
        }, {
          key: "end",
          get: function get() {
            return this.start + this.duration;
          }
        }, {
          key: "endProgramDateTime",
          get: function get() {
            if (this.programDateTime === null) {
              return null;
            }
      
            if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.programDateTime)) {
              return null;
            }
      
            var duration = !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.duration) ? 0 : this.duration;
            return this.programDateTime + duration * 1000;
          }
        }, {
          key: "encrypted",
          get: function get() {
            var _this$decryptdata;
      
            // At the m3u8-parser level we need to add support for manifest signalled keyformats
            // when we want the fragment to start reporting that it is encrypted.
            // Currently, keyFormat will only be set for identity keys
            if ((_this$decryptdata = this.decryptdata) !== null && _this$decryptdata !== void 0 && _this$decryptdata.keyFormat && this.decryptdata.uri) {
              return true;
            }
      
            return false;
          }
        }]);
      
        return Fragment;
      }(BaseSegment);
      var Part = /*#__PURE__*/function (_BaseSegment2) {
        _inheritsLoose(Part, _BaseSegment2);
      
        function Part(partAttrs, frag, baseurl, index, previous) {
          var _this2;
      
          _this2 = _BaseSegment2.call(this, baseurl) || this;
          _this2.fragOffset = 0;
          _this2.duration = 0;
          _this2.gap = false;
          _this2.independent = false;
          _this2.relurl = void 0;
          _this2.fragment = void 0;
          _this2.index = void 0;
          _this2.stats = new _load_stats__WEBPACK_IMPORTED_MODULE_4__["LoadStats"]();
          _this2.duration = partAttrs.decimalFloatingPoint('DURATION');
          _this2.gap = partAttrs.bool('GAP');
          _this2.independent = partAttrs.bool('INDEPENDENT');
          _this2.relurl = partAttrs.enumeratedString('URI');
          _this2.fragment = frag;
          _this2.index = index;
          var byteRange = partAttrs.enumeratedString('BYTERANGE');
      
          if (byteRange) {
            _this2.setByteRange(byteRange, previous);
          }
      
          if (previous) {
            _this2.fragOffset = previous.fragOffset + previous.duration;
          }
      
          return _this2;
        }
      
        _createClass(Part, [{
          key: "start",
          get: function get() {
            return this.fragment.start + this.fragOffset;
          }
        }, {
          key: "end",
          get: function get() {
            return this.start + this.duration;
          }
        }, {
          key: "loaded",
          get: function get() {
            var elementaryStreams = this.elementaryStreams;
            return !!(elementaryStreams.audio || elementaryStreams.video || elementaryStreams.audiovideo);
          }
        }]);
      
        return Part;
      }(BaseSegment);
      
      /***/ }),
      
      /***/ "./src/loader/key-loader.ts":
      /*!**********************************!*\
        !*** ./src/loader/key-loader.ts ***!
        \**********************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return KeyLoader; });
      /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
      /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      /*
       * Decrypt key Loader
       */
      
      
      
      
      var KeyLoader = /*#__PURE__*/function () {
        function KeyLoader(hls) {
          this.hls = void 0;
          this.loaders = {};
          this.decryptkey = null;
          this.decrypturl = null;
          this.hls = hls;
      
          this._registerListeners();
        }
      
        var _proto = KeyLoader.prototype;
      
        _proto._registerListeners = function _registerListeners() {
          this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADING, this.onKeyLoading, this);
        };
      
        _proto._unregisterListeners = function _unregisterListeners() {
          this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADING, this.onKeyLoading);
        };
      
        _proto.destroy = function destroy() {
          this._unregisterListeners();
      
          for (var loaderName in this.loaders) {
            var loader = this.loaders[loaderName];
      
            if (loader) {
              loader.destroy();
            }
          }
      
          this.loaders = {};
        };
      
        _proto.onKeyLoading = function onKeyLoading(event, data) {
          var frag = data.frag;
          var type = frag.type;
          var loader = this.loaders[type];
      
          if (!frag.decryptdata) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('Missing decryption data on fragment in onKeyLoading');
            return;
          } // Load the key if the uri is different from previous one, or if the decrypt key has not yet been retrieved
      
      
          var uri = frag.decryptdata.uri;
      
          if (uri !== this.decrypturl || this.decryptkey === null) {
            var config = this.hls.config;
      
            if (loader) {
              _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("abort previous key loader for type:" + type);
              loader.abort();
            }
      
            if (!uri) {
              _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('key uri is falsy');
              return;
            }
      
            var Loader = config.loader;
            var fragLoader = frag.loader = this.loaders[type] = new Loader(config);
            this.decrypturl = uri;
            this.decryptkey = null;
            var loaderContext = {
              url: uri,
              frag: frag,
              responseType: 'arraybuffer'
            }; // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,
            // key-loader will trigger an error and rely on stream-controller to handle retry logic.
            // this will also align retry logic with fragment-loader
      
            var loaderConfig = {
              timeout: config.fragLoadingTimeOut,
              maxRetry: 0,
              retryDelay: config.fragLoadingRetryDelay,
              maxRetryDelay: config.fragLoadingMaxRetryTimeout,
              highWaterMark: 0
            };
            var loaderCallbacks = {
              onSuccess: this.loadsuccess.bind(this),
              onError: this.loaderror.bind(this),
              onTimeout: this.loadtimeout.bind(this)
            };
            fragLoader.load(loaderContext, loaderConfig, loaderCallbacks);
          } else if (this.decryptkey) {
            // Return the key if it's already been loaded
            frag.decryptdata.key = this.decryptkey;
            this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADED, {
              frag: frag
            });
          }
        };
      
        _proto.loadsuccess = function loadsuccess(response, stats, context) {
          var frag = context.frag;
      
          if (!frag.decryptdata) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('after key load, decryptdata unset');
            return;
          }
      
          this.decryptkey = frag.decryptdata.key = new Uint8Array(response.data); // detach fragment loader on load success
      
          frag.loader = null;
          delete this.loaders[frag.type];
          this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADED, {
            frag: frag
          });
        };
      
        _proto.loaderror = function loaderror(response, context) {
          var frag = context.frag;
          var loader = frag.loader;
      
          if (loader) {
            loader.abort();
          }
      
          delete this.loaders[frag.type];
          this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
            type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
            details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_LOAD_ERROR,
            fatal: false,
            frag: frag,
            response: response
          });
        };
      
        _proto.loadtimeout = function loadtimeout(stats, context) {
          var frag = context.frag;
          var loader = frag.loader;
      
          if (loader) {
            loader.abort();
          }
      
          delete this.loaders[frag.type];
          this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
            type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
            details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_LOAD_TIMEOUT,
            fatal: false,
            frag: frag
          });
        };
      
        return KeyLoader;
      }();
      
      
      
      /***/ }),
      
      /***/ "./src/loader/level-details.ts":
      /*!*************************************!*\
        !*** ./src/loader/level-details.ts ***!
        \*************************************/
      /*! exports provided: LevelDetails */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LevelDetails", function() { return LevelDetails; });
      /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
      
      
      function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
      
      function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
      
      var DEFAULT_TARGET_DURATION = 10;
      var LevelDetails = /*#__PURE__*/function () {
        // Manifest reload synchronization
        function LevelDetails(baseUrl) {
          this.PTSKnown = false;
          this.alignedSliding = false;
          this.averagetargetduration = void 0;
          this.endCC = 0;
          this.endSN = 0;
          this.fragments = void 0;
          this.fragmentHint = void 0;
          this.partList = null;
          this.live = true;
          this.ageHeader = 0;
          this.advancedDateTime = void 0;
          this.updated = true;
          this.advanced = true;
          this.availabilityDelay = void 0;
          this.misses = 0;
          this.needSidxRanges = false;
          this.startCC = 0;
          this.startSN = 0;
          this.startTimeOffset = null;
          this.targetduration = 0;
          this.totalduration = 0;
          this.type = null;
          this.url = void 0;
          this.m3u8 = '';
          this.version = null;
          this.canBlockReload = false;
          this.canSkipUntil = 0;
          this.canSkipDateRanges = false;
          this.skippedSegments = 0;
          this.recentlyRemovedDateranges = void 0;
          this.partHoldBack = 0;
          this.holdBack = 0;
          this.partTarget = 0;
          this.preloadHint = void 0;
          this.renditionReports = void 0;
          this.tuneInGoal = 0;
          this.deltaUpdateFailed = void 0;
          this.driftStartTime = 0;
          this.driftEndTime = 0;
          this.driftStart = 0;
          this.driftEnd = 0;
          this.fragments = [];
          this.url = baseUrl;
        }
      
        var _proto = LevelDetails.prototype;
      
        _proto.reloaded = function reloaded(previous) {
          if (!previous) {
            this.advanced = true;
            this.updated = true;
            return;
          }
      
          var partSnDiff = this.lastPartSn - previous.lastPartSn;
          var partIndexDiff = this.lastPartIndex - previous.lastPartIndex;
          this.updated = this.endSN !== previous.endSN || !!partIndexDiff || !!partSnDiff;
          this.advanced = this.endSN > previous.endSN || partSnDiff > 0 || partSnDiff === 0 && partIndexDiff > 0;
      
          if (this.updated || this.advanced) {
            this.misses = Math.floor(previous.misses * 0.6);
          } else {
            this.misses = previous.misses + 1;
          }
      
          this.availabilityDelay = previous.availabilityDelay;
        };
      
        _createClass(LevelDetails, [{
          key: "hasProgramDateTime",
          get: function get() {
            if (this.fragments.length) {
              return Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.fragments[this.fragments.length - 1].programDateTime);
            }
      
            return false;
          }
        }, {
          key: "levelTargetDuration",
          get: function get() {
            return this.averagetargetduration || this.targetduration || DEFAULT_TARGET_DURATION;
          }
        }, {
          key: "drift",
          get: function get() {
            var runTime = this.driftEndTime - this.driftStartTime;
      
            if (runTime > 0) {
              var runDuration = this.driftEnd - this.driftStart;
              return runDuration * 1000 / runTime;
            }
      
            return 1;
          }
        }, {
          key: "edge",
          get: function get() {
            return this.partEnd || this.fragmentEnd;
          }
        }, {
          key: "partEnd",
          get: function get() {
            var _this$partList;
      
            if ((_this$partList = this.partList) !== null && _this$partList !== void 0 && _this$partList.length) {
              return this.partList[this.partList.length - 1].end;
            }
      
            return this.fragmentEnd;
          }
        }, {
          key: "fragmentEnd",
          get: function get() {
            var _this$fragments;
      
            if ((_this$fragments = this.fragments) !== null && _this$fragments !== void 0 && _this$fragments.length) {
              return this.fragments[this.fragments.length - 1].end;
            }
      
            return 0;
          }
        }, {
          key: "age",
          get: function get() {
            if (this.advancedDateTime) {
              return Math.max(Date.now() - this.advancedDateTime, 0) / 1000;
            }
      
            return 0;
          }
        }, {
          key: "lastPartIndex",
          get: function get() {
            var _this$partList2;
      
            if ((_this$partList2 = this.partList) !== null && _this$partList2 !== void 0 && _this$partList2.length) {
              return this.partList[this.partList.length - 1].index;
            }
      
            return -1;
          }
        }, {
          key: "lastPartSn",
          get: function get() {
            var _this$partList3;
      
            if ((_this$partList3 = this.partList) !== null && _this$partList3 !== void 0 && _this$partList3.length) {
              return this.partList[this.partList.length - 1].fragment.sn;
            }
      
            return this.endSN;
          }
        }]);
      
        return LevelDetails;
      }();
      
      /***/ }),
      
      /***/ "./src/loader/level-key.ts":
      /*!*********************************!*\
        !*** ./src/loader/level-key.ts ***!
        \*********************************/
      /*! exports provided: LevelKey */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LevelKey", function() { return LevelKey; });
      /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js");
      /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_0__);
      function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
      
      function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
      
      
      var LevelKey = /*#__PURE__*/function () {
        LevelKey.fromURL = function fromURL(baseUrl, relativeUrl) {
          return new LevelKey(baseUrl, relativeUrl);
        };
      
        LevelKey.fromURI = function fromURI(uri) {
          return new LevelKey(uri);
        };
      
        function LevelKey(absoluteOrBaseURI, relativeURL) {
          this._uri = null;
          this.method = null;
          this.keyFormat = null;
          this.keyFormatVersions = null;
          this.keyID = null;
          this.key = null;
          this.iv = null;
      
          if (relativeURL) {
            this._uri = Object(url_toolkit__WEBPACK_IMPORTED_MODULE_0__["buildAbsoluteURL"])(absoluteOrBaseURI, relativeURL, {
              alwaysNormalize: true
            });
          } else {
            this._uri = absoluteOrBaseURI;
          }
        }
      
        _createClass(LevelKey, [{
          key: "uri",
          get: function get() {
            return this._uri;
          }
        }]);
      
        return LevelKey;
      }();
      
      /***/ }),
      
      /***/ "./src/loader/load-stats.ts":
      /*!**********************************!*\
        !*** ./src/loader/load-stats.ts ***!
        \**********************************/
      /*! exports provided: LoadStats */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoadStats", function() { return LoadStats; });
      var LoadStats = function LoadStats() {
        this.aborted = false;
        this.loaded = 0;
        this.retry = 0;
        this.total = 0;
        this.chunkCount = 0;
        this.bwEstimate = 0;
        this.loading = {
          start: 0,
          first: 0,
          end: 0
        };
        this.parsing = {
          start: 0,
          end: 0
        };
        this.buffering = {
          start: 0,
          first: 0,
          end: 0
        };
      };
      
      /***/ }),
      
      /***/ "./src/loader/m3u8-parser.ts":
      /*!***********************************!*\
        !*** ./src/loader/m3u8-parser.ts ***!
        \***********************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return M3U8Parser; });
      /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
      /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js");
      /* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_1__);
      /* harmony import */ var _fragment__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./fragment */ "./src/loader/fragment.ts");
      /* harmony import */ var _level_details__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./level-details */ "./src/loader/level-details.ts");
      /* harmony import */ var _level_key__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./level-key */ "./src/loader/level-key.ts");
      /* harmony import */ var _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/attr-list */ "./src/utils/attr-list.ts");
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      /* harmony import */ var _utils_codecs__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/codecs */ "./src/utils/codecs.ts");
      
      
      
      
      
      
      
      
      
      
      
      // https://regex101.com is your friend
      var MASTER_PLAYLIST_REGEX = /#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-SESSION-DATA:([^\r\n]*)[\r\n]+/g;
      var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
      var LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source, // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title
      /(?!#) *(\S[\S ]*)/.source, // segment URI, group 3 => the URI (note newline is not eaten)
      /#EXT-X-BYTERANGE:*(.+)/.source, // next segment's byterange, group 4 => range spec (x@y)
      /#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, // next segment's program date/time group 5 => the datetime spec
      /#.*/.source // All other non-segment oriented tags will match with all groups empty
      ].join('|'), 'g');
      var LEVEL_PLAYLIST_REGEX_SLOW = new RegExp([/#(EXTM3U)/.source, /#EXT-X-(PLAYLIST-TYPE):(.+)/.source, /#EXT-X-(MEDIA-SEQUENCE): *(\d+)/.source, /#EXT-X-(SKIP):(.+)/.source, /#EXT-X-(TARGETDURATION): *(\d+)/.source, /#EXT-X-(KEY):(.+)/.source, /#EXT-X-(START):(.+)/.source, /#EXT-X-(ENDLIST)/.source, /#EXT-X-(DISCONTINUITY-SEQ)UENCE: *(\d+)/.source, /#EXT-X-(DIS)CONTINUITY/.source, /#EXT-X-(VERSION):(\d+)/.source, /#EXT-X-(MAP):(.+)/.source, /#EXT-X-(SERVER-CONTROL):(.+)/.source, /#EXT-X-(PART-INF):(.+)/.source, /#EXT-X-(GAP)/.source, /#EXT-X-(BITRATE):\s*(\d+)/.source, /#EXT-X-(PART):(.+)/.source, /#EXT-X-(PRELOAD-HINT):(.+)/.source, /#EXT-X-(RENDITION-REPORT):(.+)/.source, /(#)([^:]*):(.*)/.source, /(#)(.*)(?:.*)\r?\n?/.source].join('|'));
      var MP4_REGEX_SUFFIX = /\.(mp4|m4s|m4v|m4a)$/i;
      
      function isMP4Url(url) {
        var _URLToolkit$parseURL$, _URLToolkit$parseURL;
      
        return MP4_REGEX_SUFFIX.test((_URLToolkit$parseURL$ = (_URLToolkit$parseURL = url_toolkit__WEBPACK_IMPORTED_MODULE_1__["parseURL"](url)) === null || _URLToolkit$parseURL === void 0 ? void 0 : _URLToolkit$parseURL.path) != null ? _URLToolkit$parseURL$ : '');
      }
      
      var M3U8Parser = /*#__PURE__*/function () {
        function M3U8Parser() {}
      
        M3U8Parser.findGroup = function findGroup(groups, mediaGroupId) {
          for (var i = 0; i < groups.length; i++) {
            var group = groups[i];
      
            if (group.id === mediaGroupId) {
              return group;
            }
          }
        };
      
        M3U8Parser.convertAVC1ToAVCOTI = function convertAVC1ToAVCOTI(codec) {
          // Convert avc1 codec string from RFC-4281 to RFC-6381 for MediaSource.isTypeSupported
          var avcdata = codec.split('.');
      
          if (avcdata.length > 2) {
            var result = avcdata.shift() + '.';
            result += parseInt(avcdata.shift()).toString(16);
            result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4);
            return result;
          }
      
          return codec;
        };
      
        M3U8Parser.resolve = function resolve(url, baseUrl) {
          return url_toolkit__WEBPACK_IMPORTED_MODULE_1__["buildAbsoluteURL"](baseUrl, url, {
            alwaysNormalize: true
          });
        };
      
        M3U8Parser.parseMasterPlaylist = function parseMasterPlaylist(string, baseurl) {
          var levels = [];
          var sessionData = {};
          var hasSessionData = false;
          MASTER_PLAYLIST_REGEX.lastIndex = 0;
          var result;
      
          while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
            if (result[1]) {
              // '#EXT-X-STREAM-INF' is found, parse level tag  in group 1
              var attrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](result[1]);
              var level = {
                attrs: attrs,
                bitrate: attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH'),
                name: attrs.NAME,
                url: M3U8Parser.resolve(result[2], baseurl)
              };
              var resolution = attrs.decimalResolution('RESOLUTION');
      
              if (resolution) {
                level.width = resolution.width;
                level.height = resolution.height;
              }
      
              setCodecs((attrs.CODECS || '').split(/[ ,]+/).filter(function (c) {
                return c;
              }), level);
      
              if (level.videoCodec && level.videoCodec.indexOf('avc1') !== -1) {
                level.videoCodec = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec);
              }
      
              levels.push(level);
            } else if (result[3]) {
              // '#EXT-X-SESSION-DATA' is found, parse session data in group 3
              var sessionAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](result[3]);
      
              if (sessionAttrs['DATA-ID']) {
                hasSessionData = true;
                sessionData[sessionAttrs['DATA-ID']] = sessionAttrs;
              }
            }
          }
      
          return {
            levels: levels,
            sessionData: hasSessionData ? sessionData : null
          };
        };
      
        M3U8Parser.parseMasterPlaylistMedia = function parseMasterPlaylistMedia(string, baseurl, type, groups) {
          if (groups === void 0) {
            groups = [];
          }
      
          var result;
          var medias = [];
          var id = 0;
          MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
      
          while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {
            var attrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](result[1]);
      
            if (attrs.TYPE === type) {
              var media = {
                attrs: attrs,
                bitrate: 0,
                id: id++,
                groupId: attrs['GROUP-ID'],
                instreamId: attrs['INSTREAM-ID'],
                name: attrs.NAME || attrs.LANGUAGE || '',
                type: type,
                default: attrs.bool('DEFAULT'),
                autoselect: attrs.bool('AUTOSELECT'),
                forced: attrs.bool('FORCED'),
                lang: attrs.LANGUAGE,
                url: attrs.URI ? M3U8Parser.resolve(attrs.URI, baseurl) : ''
              };
      
              if (groups.length) {
                // If there are audio or text groups signalled in the manifest, let's look for a matching codec string for this track
                // If we don't find the track signalled, lets use the first audio groups codec we have
                // Acting as a best guess
                var groupCodec = M3U8Parser.findGroup(groups, media.groupId) || groups[0];
                assignCodec(media, groupCodec, 'audioCodec');
                assignCodec(media, groupCodec, 'textCodec');
              }
      
              medias.push(media);
            }
          }
      
          return medias;
        };
      
        M3U8Parser.parseLevelPlaylist = function parseLevelPlaylist(string, baseurl, id, type, levelUrlId) {
          var level = new _level_details__WEBPACK_IMPORTED_MODULE_3__["LevelDetails"](baseurl);
          var fragments = level.fragments; // The most recent init segment seen (applies to all subsequent segments)
      
          var currentInitSegment = null;
          var currentSN = 0;
          var currentPart = 0;
          var totalduration = 0;
          var discontinuityCounter = 0;
          var prevFrag = null;
          var frag = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Fragment"](type, baseurl);
          var result;
          var i;
          var levelkey;
          var firstPdtIndex = -1;
          var createNextFrag = false;
          LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
          level.m3u8 = string;
      
          while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
            if (createNextFrag) {
              createNextFrag = false;
              frag = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Fragment"](type, baseurl); // setup the next fragment for part loading
      
              frag.start = totalduration;
              frag.sn = currentSN;
              frag.cc = discontinuityCounter;
              frag.level = id;
      
              if (currentInitSegment) {
                frag.initSegment = currentInitSegment;
                frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;
              }
            }
      
            var duration = result[1];
      
            if (duration) {
              // INF
              frag.duration = parseFloat(duration); // avoid sliced strings    https://github.com/video-dev/hls.js/issues/939
      
              var title = (' ' + result[2]).slice(1);
              frag.title = title || null;
              frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);
            } else if (result[3]) {
              // url
              if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.duration)) {
                frag.start = totalduration;
      
                if (levelkey) {
                  frag.levelkey = levelkey;
                }
      
                frag.sn = currentSN;
                frag.level = id;
                frag.cc = discontinuityCounter;
                frag.urlId = levelUrlId;
                fragments.push(frag); // avoid sliced strings    https://github.com/video-dev/hls.js/issues/939
      
                frag.relurl = (' ' + result[3]).slice(1);
                assignProgramDateTime(frag, prevFrag);
                prevFrag = frag;
                totalduration += frag.duration;
                currentSN++;
                currentPart = 0;
                createNextFrag = true;
              }
            } else if (result[4]) {
              // X-BYTERANGE
              var data = (' ' + result[4]).slice(1);
      
              if (prevFrag) {
                frag.setByteRange(data, prevFrag);
              } else {
                frag.setByteRange(data);
              }
            } else if (result[5]) {
              // PROGRAM-DATE-TIME
              // avoid sliced strings    https://github.com/video-dev/hls.js/issues/939
              frag.rawProgramDateTime = (' ' + result[5]).slice(1);
              frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);
      
              if (firstPdtIndex === -1) {
                firstPdtIndex = fragments.length;
              }
            } else {
              result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
      
              if (!result) {
                _utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn('No matches on slow regex match for level playlist!');
                continue;
              }
      
              for (i = 1; i < result.length; i++) {
                if (typeof result[i] !== 'undefined') {
                  break;
                }
              } // avoid sliced strings    https://github.com/video-dev/hls.js/issues/939
      
      
              var tag = (' ' + result[i]).slice(1);
              var value1 = (' ' + result[i + 1]).slice(1);
              var value2 = result[i + 2] ? (' ' + result[i + 2]).slice(1) : '';
      
              switch (tag) {
                case 'PLAYLIST-TYPE':
                  level.type = value1.toUpperCase();
                  break;
      
                case 'MEDIA-SEQUENCE':
                  currentSN = level.startSN = parseInt(value1);
                  break;
      
                case 'SKIP':
                  {
                    var skipAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
                    var skippedSegments = skipAttrs.decimalInteger('SKIPPED-SEGMENTS');
      
                    if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(skippedSegments)) {
                      level.skippedSegments = skippedSegments; // This will result in fragments[] containing undefined values, which we will fill in with `mergeDetails`
      
                      for (var _i = skippedSegments; _i--;) {
                        fragments.unshift(null);
                      }
      
                      currentSN += skippedSegments;
                    }
      
                    var recentlyRemovedDateranges = skipAttrs.enumeratedString('RECENTLY-REMOVED-DATERANGES');
      
                    if (recentlyRemovedDateranges) {
                      level.recentlyRemovedDateranges = recentlyRemovedDateranges.split('\t');
                    }
      
                    break;
                  }
      
                case 'TARGETDURATION':
                  level.targetduration = parseFloat(value1);
                  break;
      
                case 'VERSION':
                  level.version = parseInt(value1);
                  break;
      
                case 'EXTM3U':
                  break;
      
                case 'ENDLIST':
                  level.live = false;
                  break;
      
                case '#':
                  if (value1 || value2) {
                    frag.tagList.push(value2 ? [value1, value2] : [value1]);
                  }
      
                  break;
      
                case 'DIS':
                  discontinuityCounter++;
      
                /* falls through */
      
                case 'GAP':
                  frag.tagList.push([tag]);
                  break;
      
                case 'BITRATE':
                  frag.tagList.push([tag, value1]);
                  break;
      
                case 'DISCONTINUITY-SEQ':
                  discontinuityCounter = parseInt(value1);
                  break;
      
                case 'KEY':
                  {
                    var _keyAttrs$enumeratedS;
      
                    // https://tools.ietf.org/html/rfc8216#section-4.3.2.4
                    var keyAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
                    var decryptmethod = keyAttrs.enumeratedString('METHOD');
                    var decrypturi = keyAttrs.URI;
                    var decryptiv = keyAttrs.hexadecimalInteger('IV');
                    var decryptkeyformatversions = keyAttrs.enumeratedString('KEYFORMATVERSIONS');
                    var decryptkeyid = keyAttrs.enumeratedString('KEYID'); // From RFC: This attribute is OPTIONAL; its absence indicates an implicit value of "identity".
      
                    var decryptkeyformat = (_keyAttrs$enumeratedS = keyAttrs.enumeratedString('KEYFORMAT')) != null ? _keyAttrs$enumeratedS : 'identity';
                    var unsupportedKnownKeyformatsInManifest = ['com.apple.streamingkeydelivery', 'com.microsoft.playready', 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed', // widevine (v2)
                    'com.widevine' // earlier widevine (v1)
                    ];
      
                    if (unsupportedKnownKeyformatsInManifest.indexOf(decryptkeyformat) > -1) {
                      _utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn("Keyformat " + decryptkeyformat + " is not supported from the manifest");
                      continue;
                    } else if (decryptkeyformat !== 'identity') {
                      // We are supposed to skip keys we don't understand.
                      // As we currently only officially support identity keys
                      // from the manifest we shouldn't save any other key.
                      continue;
                    } // TODO: multiple keys can be defined on a fragment, and we need to support this
                    // for clients that support both playready and widevine
      
      
                    if (decryptmethod) {
                      // TODO: need to determine if the level key is actually a relative URL
                      // if it isn't, then we should instead construct the LevelKey using fromURI.
                      levelkey = _level_key__WEBPACK_IMPORTED_MODULE_4__["LevelKey"].fromURL(baseurl, decrypturi);
      
                      if (decrypturi && ['AES-128', 'SAMPLE-AES', 'SAMPLE-AES-CENC'].indexOf(decryptmethod) >= 0) {
                        levelkey.method = decryptmethod;
                        levelkey.keyFormat = decryptkeyformat;
      
                        if (decryptkeyid) {
                          levelkey.keyID = decryptkeyid;
                        }
      
                        if (decryptkeyformatversions) {
                          levelkey.keyFormatVersions = decryptkeyformatversions;
                        } // Initialization Vector (IV)
      
      
                        levelkey.iv = decryptiv;
                      }
                    }
      
                    break;
                  }
      
                case 'START':
                  {
                    var startAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
                    var startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET'); // TIME-OFFSET can be 0
      
                    if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(startTimeOffset)) {
                      level.startTimeOffset = startTimeOffset;
                    }
      
                    break;
                  }
      
                case 'MAP':
                  {
                    var mapAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
                    frag.relurl = mapAttrs.URI;
      
                    if (mapAttrs.BYTERANGE) {
                      frag.setByteRange(mapAttrs.BYTERANGE);
                    }
      
                    frag.level = id;
                    frag.sn = 'initSegment';
      
                    if (levelkey) {
                      frag.levelkey = levelkey;
                    }
      
                    frag.initSegment = null;
                    currentInitSegment = frag;
                    createNextFrag = true;
                    break;
                  }
      
                case 'SERVER-CONTROL':
                  {
                    var serverControlAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
                    level.canBlockReload = serverControlAttrs.bool('CAN-BLOCK-RELOAD');
                    level.canSkipUntil = serverControlAttrs.optionalFloat('CAN-SKIP-UNTIL', 0);
                    level.canSkipDateRanges = level.canSkipUntil > 0 && serverControlAttrs.bool('CAN-SKIP-DATERANGES');
                    level.partHoldBack = serverControlAttrs.optionalFloat('PART-HOLD-BACK', 0);
                    level.holdBack = serverControlAttrs.optionalFloat('HOLD-BACK', 0);
                    break;
                  }
      
                case 'PART-INF':
                  {
                    var partInfAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
                    level.partTarget = partInfAttrs.decimalFloatingPoint('PART-TARGET');
                    break;
                  }
      
                case 'PART':
                  {
                    var partList = level.partList;
      
                    if (!partList) {
                      partList = level.partList = [];
                    }
      
                    var previousFragmentPart = currentPart > 0 ? partList[partList.length - 1] : undefined;
                    var index = currentPart++;
                    var part = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Part"](new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1), frag, baseurl, index, previousFragmentPart);
                    partList.push(part);
                    frag.duration += part.duration;
                    break;
                  }
      
                case 'PRELOAD-HINT':
                  {
                    var preloadHintAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
                    level.preloadHint = preloadHintAttrs;
                    break;
                  }
      
                case 'RENDITION-REPORT':
                  {
                    var renditionReportAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
                    level.renditionReports = level.renditionReports || [];
                    level.renditionReports.push(renditionReportAttrs);
                    break;
                  }
      
                default:
                  _utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn("line parsed but not handled: " + result);
                  break;
              }
            }
          }
      
          if (prevFrag && !prevFrag.relurl) {
            fragments.pop();
            totalduration -= prevFrag.duration;
      
            if (level.partList) {
              level.fragmentHint = prevFrag;
            }
          } else if (level.partList) {
            assignProgramDateTime(frag, prevFrag);
            frag.cc = discontinuityCounter;
            level.fragmentHint = frag;
          }
      
          var fragmentLength = fragments.length;
          var firstFragment = fragments[0];
          var lastFragment = fragments[fragmentLength - 1];
          totalduration += level.skippedSegments * level.targetduration;
      
          if (totalduration > 0 && fragmentLength && lastFragment) {
            level.averagetargetduration = totalduration / fragmentLength;
            var lastSn = lastFragment.sn;
            level.endSN = lastSn !== 'initSegment' ? lastSn : 0;
      
            if (firstFragment) {
              level.startCC = firstFragment.cc;
      
              if (!firstFragment.initSegment) {
                // this is a bit lurky but HLS really has no other way to tell us
                // if the fragments are TS or MP4, except if we download them :/
                // but this is to be able to handle SIDX.
                if (level.fragments.every(function (frag) {
                  return frag.relurl && isMP4Url(frag.relurl);
                })) {
                  _utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn('MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX');
                  frag = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Fragment"](type, baseurl);
                  frag.relurl = lastFragment.relurl;
                  frag.level = id;
                  frag.sn = 'initSegment';
                  firstFragment.initSegment = frag;
                  level.needSidxRanges = true;
                }
              }
            }
          } else {
            level.endSN = 0;
            level.startCC = 0;
          }
      
          if (level.fragmentHint) {
            totalduration += level.fragmentHint.duration;
          }
      
          level.totalduration = totalduration;
          level.endCC = discontinuityCounter;
          /**
           * Backfill any missing PDT values
           * "If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after
           * one or more Media Segment URIs, the client SHOULD extrapolate
           * backward from that tag (using EXTINF durations and/or media
           * timestamps) to associate dates with those segments."
           * We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs
           * computed.
           */
      
          if (firstPdtIndex > 0) {
            backfillProgramDateTimes(fragments, firstPdtIndex);
          }
      
          return level;
        };
      
        return M3U8Parser;
      }();
      
      
      
      function setCodecs(codecs, level) {
        ['video', 'audio', 'text'].forEach(function (type) {
          var filtered = codecs.filter(function (codec) {
            return Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_7__["isCodecType"])(codec, type);
          });
      
          if (filtered.length) {
            var preferred = filtered.filter(function (codec) {
              return codec.lastIndexOf('avc1', 0) === 0 || codec.lastIndexOf('mp4a', 0) === 0;
            });
            level[type + "Codec"] = preferred.length > 0 ? preferred[0] : filtered[0]; // remove from list
      
            codecs = codecs.filter(function (codec) {
              return filtered.indexOf(codec) === -1;
            });
          }
        });
        level.unknownCodecs = codecs;
      }
      
      function assignCodec(media, groupItem, codecProperty) {
        var codecValue = groupItem[codecProperty];
      
        if (codecValue) {
          media[codecProperty] = codecValue;
        }
      }
      
      function backfillProgramDateTimes(fragments, firstPdtIndex) {
        var fragPrev = fragments[firstPdtIndex];
      
        for (var i = firstPdtIndex; i--;) {
          var frag = fragments[i]; // Exit on delta-playlist skipped segments
      
          if (!frag) {
            return;
          }
      
          frag.programDateTime = fragPrev.programDateTime - frag.duration * 1000;
          fragPrev = frag;
        }
      }
      
      function assignProgramDateTime(frag, prevFrag) {
        if (frag.rawProgramDateTime) {
          frag.programDateTime = Date.parse(frag.rawProgramDateTime);
        } else if (prevFrag !== null && prevFrag !== void 0 && prevFrag.programDateTime) {
          frag.programDateTime = prevFrag.endProgramDateTime;
        }
      
        if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.programDateTime)) {
          frag.programDateTime = null;
          frag.rawProgramDateTime = null;
        }
      }
      
      /***/ }),
      
      /***/ "./src/loader/playlist-loader.ts":
      /*!***************************************!*\
        !*** ./src/loader/playlist-loader.ts ***!
        \***************************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
      /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
      /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
      /* harmony import */ var _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./m3u8-parser */ "./src/loader/m3u8-parser.ts");
      /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
      /* harmony import */ var _utils_attr_list__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/attr-list */ "./src/utils/attr-list.ts");
      
      
      
      /**
       * PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models.
       *
       * Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks.
       *
       * Uses loader(s) set in config to do actual internal loading of resource tasks.
       *
       * @module
       *
       */
      
      
      
      
      
      
      
      
      function mapContextToLevelType(context) {
        var type = context.type;
      
        switch (type) {
          case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK:
            return _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO;
      
          case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK:
            return _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].SUBTITLE;
      
          default:
            return _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN;
        }
      }
      
      function getResponseUrl(response, context) {
        var url = response.url; // responseURL not supported on some browsers (it is used to detect URL redirection)
        // data-uri mode also not supported (but no need to detect redirection)
      
        if (url === undefined || url.indexOf('data:') === 0) {
          // fallback to initial URL
          url = context.url;
        }
      
        return url;
      }
      
      var PlaylistLoader = /*#__PURE__*/function () {
        function PlaylistLoader(hls) {
          this.hls = void 0;
          this.loaders = Object.create(null);
          this.hls = hls;
          this.registerListeners();
        }
      
        var _proto = PlaylistLoader.prototype;
      
        _proto.registerListeners = function registerListeners() {
          var hls = this.hls;
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
          hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
        };
      
        _proto.unregisterListeners = function unregisterListeners() {
          var hls = this.hls;
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
          hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
        }
        /**
         * Returns defaults or configured loader-type overloads (pLoader and loader config params)
         */
        ;
      
        _proto.createInternalLoader = function createInternalLoader(context) {
          var config = this.hls.config;
          var PLoader = config.pLoader;
          var Loader = config.loader;
          var InternalLoader = PLoader || Loader;
          var loader = new InternalLoader(config);
          context.loader = loader;
          this.loaders[context.type] = loader;
          return loader;
        };
      
        _proto.getInternalLoader = function getInternalLoader(context) {
          return this.loaders[context.type];
        };
      
        _proto.resetInternalLoader = function resetInternalLoader(contextType) {
          if (this.loaders[contextType]) {
            delete this.loaders[contextType];
          }
        }
        /**
         * Call `destroy` on all internal loader instances mapped (one per context type)
         */
        ;
      
        _proto.destroyInternalLoaders = function destroyInternalLoaders() {
          for (var contextType in this.loaders) {
            var loader = this.loaders[contextType];
      
            if (loader) {
              loader.destroy();
            }
      
            this.resetInternalLoader(contextType);
          }
        };
      
        _proto.destroy = function destroy() {
          this.unregisterListeners();
          this.destroyInternalLoaders();
        };
      
        _proto.onManifestLoading = function onManifestLoading(event, data) {
          var url = data.url;
          this.load({
            id: null,
            groupId: null,
            level: 0,
            responseType: 'text',
            type: _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST,
            url: url,
            deliveryDirectives: null
          });
        };
      
        _proto.onLevelLoading = function onLevelLoading(event, data) {
          var id = data.id,
              level = data.level,
              url = data.url,
              deliveryDirectives = data.deliveryDirectives;
          this.load({
            id: id,
            groupId: null,
            level: level,
            responseType: 'text',
            type: _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL,
            url: url,
            deliveryDirectives: deliveryDirectives
          });
        };
      
        _proto.onAudioTrackLoading = function onAudioTrackLoading(event, data) {
          var id = data.id,
              groupId = data.groupId,
              url = data.url,
              deliveryDirectives = data.deliveryDirectives;
          this.load({
            id: id,
            groupId: groupId,
            level: null,
            responseType: 'text',
            type: _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK,
            url: url,
            deliveryDirectives: deliveryDirectives
          });
        };
      
        _proto.onSubtitleTrackLoading = function onSubtitleTrackLoading(event, data) {
          var id = data.id,
              groupId = data.groupId,
              url = data.url,
              deliveryDirectives = data.deliveryDirectives;
          this.load({
            id: id,
            groupId: groupId,
            level: null,
            responseType: 'text',
            type: _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK,
            url: url,
            deliveryDirectives: deliveryDirectives
          });
        };
      
        _proto.load = function load(context) {
          var _context$deliveryDire;
      
          var config = this.hls.config; // logger.debug(`[playlist-loader]: Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`);
          // Check if a loader for this context already exists
      
          var loader = this.getInternalLoader(context);
      
          if (loader) {
            var loaderContext = loader.context;
      
            if (loaderContext && loaderContext.url === context.url) {
              // same URL can't overlap
              _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].trace('[playlist-loader]: playlist request ongoing');
              return;
            }
      
            _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log("[playlist-loader]: aborting previous loader for type: " + context.type);
            loader.abort();
          }
      
          var maxRetry;
          var timeout;
          var retryDelay;
          var maxRetryDelay; // apply different configs for retries depending on
          // context (manifest, level, audio/subs playlist)
      
          switch (context.type) {
            case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST:
              maxRetry = config.manifestLoadingMaxRetry;
              timeout = config.manifestLoadingTimeOut;
              retryDelay = config.manifestLoadingRetryDelay;
              maxRetryDelay = config.manifestLoadingMaxRetryTimeout;
              break;
      
            case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL:
            case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK:
            case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK:
              // Manage retries in Level/Track Controller
              maxRetry = 0;
              timeout = config.levelLoadingTimeOut;
              break;
      
            default:
              maxRetry = config.levelLoadingMaxRetry;
              timeout = config.levelLoadingTimeOut;
              retryDelay = config.levelLoadingRetryDelay;
              maxRetryDelay = config.levelLoadingMaxRetryTimeout;
              break;
          }
      
          loader = this.createInternalLoader(context); // Override level/track timeout for LL-HLS requests
          // (the default of 10000ms is counter productive to blocking playlist reload requests)
      
          if ((_context$deliveryDire = context.deliveryDirectives) !== null && _context$deliveryDire !== void 0 && _context$deliveryDire.part) {
            var levelDetails;
      
            if (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL && context.level !== null) {
              levelDetails = this.hls.levels[context.level].details;
            } else if (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK && context.id !== null) {
              levelDetails = this.hls.audioTracks[context.id].details;
            } else if (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK && context.id !== null) {
              levelDetails = this.hls.subtitleTracks[context.id].details;
            }
      
            if (levelDetails) {
              var partTarget = levelDetails.partTarget;
              var targetDuration = levelDetails.targetduration;
      
              if (partTarget && targetDuration) {
                timeout = Math.min(Math.max(partTarget * 3, targetDuration * 0.8) * 1000, timeout);
              }
            }
          }
      
          var loaderConfig = {
            timeout: timeout,
            maxRetry: maxRetry,
            retryDelay: retryDelay,
            maxRetryDelay: maxRetryDelay,
            highWaterMark: 0
          };
          var loaderCallbacks = {
            onSuccess: this.loadsuccess.bind(this),
            onError: this.loaderror.bind(this),
            onTimeout: this.loadtimeout.bind(this)
          }; // logger.debug(`[playlist-loader]: Calling internal loader delegate for URL: ${context.url}`);
      
          loader.load(context, loaderConfig, loaderCallbacks);
        };
      
        _proto.loadsuccess = function loadsuccess(response, stats, context, networkDetails) {
          if (networkDetails === void 0) {
            networkDetails = null;
          }
      
          if (context.isSidxRequest) {
            this.handleSidxRequest(response, context);
            this.handlePlaylistLoaded(response, stats, context, networkDetails);
            return;
          }
      
          this.resetInternalLoader(context.type);
          var string = response.data; // Validate if it is an M3U8 at all
      
          if (string.indexOf('#EXTM3U') !== 0) {
            this.handleManifestParsingError(response, context, 'no EXTM3U delimiter', networkDetails);
            return;
          }
      
          stats.parsing.start = performance.now(); // Check if chunk-list or master. handle empty chunk list case (first EXTINF not signaled, but TARGETDURATION present)
      
          if (string.indexOf('#EXTINF:') > 0 || string.indexOf('#EXT-X-TARGETDURATION:') > 0) {
            this.handleTrackOrLevelPlaylist(response, stats, context, networkDetails);
          } else {
            this.handleMasterPlaylist(response, stats, context, networkDetails);
          }
        };
      
        _proto.loaderror = function loaderror(response, context, networkDetails) {
          if (networkDetails === void 0) {
            networkDetails = null;
          }
      
          this.handleNetworkError(context, networkDetails, false, response);
        };
      
        _proto.loadtimeout = function loadtimeout(stats, context, networkDetails) {
          if (networkDetails === void 0) {
            networkDetails = null;
          }
      
          this.handleNetworkError(context, networkDetails, true);
        };
      
        _proto.handleMasterPlaylist = function handleMasterPlaylist(response, stats, context, networkDetails) {
          var hls = this.hls;
          var string = response.data;
          var url = getResponseUrl(response, context);
      
          var _M3U8Parser$parseMast = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylist(string, url),
              levels = _M3U8Parser$parseMast.levels,
              sessionData = _M3U8Parser$parseMast.sessionData;
      
          if (!levels.length) {
            this.handleManifestParsingError(response, context, 'no level found in manifest', networkDetails);
            return;
          } // multi level playlist, parse level info
      
      
          var audioGroups = levels.map(function (level) {
            return {
              id: level.attrs.AUDIO,
              audioCodec: level.audioCodec
            };
          });
          var subtitleGroups = levels.map(function (level) {
            return {
              id: level.attrs.SUBTITLES,
              textCodec: level.textCodec
            };
          });
          var audioTracks = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups);
          var subtitles = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylistMedia(string, url, 'SUBTITLES', subtitleGroups);
          var captions = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylistMedia(string, url, 'CLOSED-CAPTIONS');
      
          if (audioTracks.length) {
            // check if we have found an audio track embedded in main playlist (audio track without URI attribute)
            var embeddedAudioFound = audioTracks.some(function (audioTrack) {
              return !audioTrack.url;
            }); // if no embedded audio track defined, but audio codec signaled in quality level,
            // we need to signal this main audio track this could happen with playlists with
            // alt audio rendition in which quality levels (main)
            // contains both audio+video. but with mixed audio track not signaled
      
            if (!embeddedAudioFound && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
              _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log('[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one');
              audioTracks.unshift({
                type: 'main',
                name: 'main',
                default: false,
                autoselect: false,
                forced: false,
                id: -1,
                attrs: new _utils_attr_list__WEBPACK_IMPORTED_MODULE_7__["AttrList"]({}),
                bitrate: 0,
                url: ''
              });
            }
          }
      
          hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, {
            levels: levels,
            audioTracks: audioTracks,
            subtitles: subtitles,
            captions: captions,
            url: url,
            stats: stats,
            networkDetails: networkDetails,
            sessionData: sessionData
          });
        };
      
        _proto.handleTrackOrLevelPlaylist = function handleTrackOrLevelPlaylist(response, stats, context, networkDetails) {
          var hls = this.hls;
          var id = context.id,
              level = context.level,
              type = context.type;
          var url = getResponseUrl(response, context);
          var levelUrlId = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(id) ? id : 0;
          var levelId = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(level) ? level : levelUrlId;
          var levelType = mapContextToLevelType(context);
          var levelDetails = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId);
      
          if (!levelDetails.fragments.length) {
            hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
              type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].NETWORK_ERROR,
              details: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_EMPTY_ERROR,
              fatal: false,
              url: url,
              reason: 'no fragments found in level',
              level: typeof context.level === 'number' ? context.level : undefined
            });
            return;
          } // We have done our first request (Manifest-type) and receive
          // not a master playlist but a chunk-list (track/level)
          // We fire the manifest-loaded event anyway with the parsed level-details
          // by creating a single-level structure for it.
      
      
          if (type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST) {
            var singleLevel = {
              attrs: new _utils_attr_list__WEBPACK_IMPORTED_MODULE_7__["AttrList"]({}),
              bitrate: 0,
              details: levelDetails,
              name: '',
              url: url
            };
            hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, {
              levels: [singleLevel],
              audioTracks: [],
              url: url,
              stats: stats,
              networkDetails: networkDetails,
              sessionData: null
            });
          } // save parsing time
      
      
          stats.parsing.end = performance.now(); // in case we need SIDX ranges
          // return early after calling load for
          // the SIDX box.
      
          if (levelDetails.needSidxRanges) {
            var _levelDetails$fragmen;
      
            var sidxUrl = (_levelDetails$fragmen = levelDetails.fragments[0].initSegment) === null || _levelDetails$fragmen === void 0 ? void 0 : _levelDetails$fragmen.url;
            this.load({
              url: sidxUrl,
              isSidxRequest: true,
              type: type,
              level: level,
              levelDetails: levelDetails,
              id: id,
              groupId: null,
              rangeStart: 0,
              rangeEnd: 2048,
              responseType: 'arraybuffer',
              deliveryDirectives: null
            });
            return;
          } // extend the context with the new levelDetails property
      
      
          context.levelDetails = levelDetails;
          this.handlePlaylistLoaded(response, stats, context, networkDetails);
        };
      
        _proto.handleSidxRequest = function handleSidxRequest(response, context) {
          var sidxInfo = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__["parseSegmentIndex"])(new Uint8Array(response.data)); // if provided fragment does not contain sidx, early return
      
          if (!sidxInfo) {
            return;
          }
      
          var sidxReferences = sidxInfo.references;
          var levelDetails = context.levelDetails;
          sidxReferences.forEach(function (segmentRef, index) {
            var segRefInfo = segmentRef.info;
            var frag = levelDetails.fragments[index];
      
            if (frag.byteRange.length === 0) {
              frag.setByteRange(String(1 + segRefInfo.end - segRefInfo.start) + '@' + String(segRefInfo.start));
            }
      
            if (frag.initSegment) {
              frag.initSegment.setByteRange(String(sidxInfo.moovEndOffset) + '@0');
            }
          });
        };
      
        _proto.handleManifestParsingError = function handleManifestParsingError(response, context, reason, networkDetails) {
          this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
            type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].NETWORK_ERROR,
            details: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].MANIFEST_PARSING_ERROR,
            fatal: context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST,
            url: response.url,
            reason: reason,
            response: response,
            context: context,
            networkDetails: networkDetails
          });
        };
      
        _proto.handleNetworkError = function handleNetworkError(context, networkDetails, timeout, response) {
          if (timeout === void 0) {
            timeout = false;
          }
      
          _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("[playlist-loader]: A network " + (timeout ? 'timeout' : 'error') + " occurred while loading " + context.type + " level: " + context.level + " id: " + context.id + " group-id: \"" + context.groupId + "\"");
          var details = _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].UNKNOWN;
          var fatal = false;
          var loader = this.getInternalLoader(context);
      
          switch (context.type) {
            case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST:
              details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].MANIFEST_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].MANIFEST_LOAD_ERROR;
              fatal = true;
              break;
      
            case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL:
              details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_LOAD_ERROR;
              fatal = false;
              break;
      
            case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK:
              details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].AUDIO_TRACK_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].AUDIO_TRACK_LOAD_ERROR;
              fatal = false;
              break;
      
            case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK:
              details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].SUBTITLE_TRACK_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].SUBTITLE_LOAD_ERROR;
              fatal = false;
              break;
          }
      
          if (loader) {
            this.resetInternalLoader(context.type);
          }
      
          var errorData = {
            type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].NETWORK_ERROR,
            details: details,
            fatal: fatal,
            url: context.url,
            loader: loader,
            context: context,
            networkDetails: networkDetails
          };
      
          if (response) {
            errorData.response = response;
          }
      
          this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, errorData);
        };
      
        _proto.handlePlaylistLoaded = function handlePlaylistLoaded(response, stats, context, networkDetails) {
          var type = context.type,
              level = context.level,
              id = context.id,
              groupId = context.groupId,
              loader = context.loader,
              levelDetails = context.levelDetails,
              deliveryDirectives = context.deliveryDirectives;
      
          if (!(levelDetails !== null && levelDetails !== void 0 && levelDetails.targetduration)) {
            this.handleManifestParsingError(response, context, 'invalid target duration', networkDetails);
            return;
          }
      
          if (!loader) {
            return;
          }
      
          if (levelDetails.live) {
            if (loader.getCacheAge) {
              levelDetails.ageHeader = loader.getCacheAge() || 0;
            }
      
            if (!loader.getCacheAge || isNaN(levelDetails.ageHeader)) {
              levelDetails.ageHeader = 0;
            }
          }
      
          switch (type) {
            case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST:
            case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL:
              this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADED, {
                details: levelDetails,
                level: level || 0,
                id: id || 0,
                stats: stats,
                networkDetails: networkDetails,
                deliveryDirectives: deliveryDirectives
              });
              break;
      
            case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK:
              this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_LOADED, {
                details: levelDetails,
                id: id || 0,
                groupId: groupId || '',
                stats: stats,
                networkDetails: networkDetails,
                deliveryDirectives: deliveryDirectives
              });
              break;
      
            case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK:
              this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACK_LOADED, {
                details: levelDetails,
                id: id || 0,
                groupId: groupId || '',
                stats: stats,
                networkDetails: networkDetails,
                deliveryDirectives: deliveryDirectives
              });
              break;
          }
        };
      
        return PlaylistLoader;
      }();
      
      /* harmony default export */ __webpack_exports__["default"] = (PlaylistLoader);
      
      /***/ }),
      
      /***/ "./src/polyfills/number.ts":
      /*!*********************************!*\
        !*** ./src/polyfills/number.ts ***!
        \*********************************/
      /*! exports provided: isFiniteNumber, MAX_SAFE_INTEGER */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFiniteNumber", function() { return isFiniteNumber; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MAX_SAFE_INTEGER", function() { return MAX_SAFE_INTEGER; });
      var isFiniteNumber = Number.isFinite || function (value) {
        return typeof value === 'number' && isFinite(value);
      };
      var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
      
      /***/ }),
      
      /***/ "./src/remux/aac-helper.ts":
      /*!*********************************!*\
        !*** ./src/remux/aac-helper.ts ***!
        \*********************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /**
       *  AAC helper
       */
      var AAC = /*#__PURE__*/function () {
        function AAC() {}
      
        AAC.getSilentFrame = function getSilentFrame(codec, channelCount) {
          switch (codec) {
            case 'mp4a.40.2':
              if (channelCount === 1) {
                return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
              } else if (channelCount === 2) {
                return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
              } else if (channelCount === 3) {
                return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
              } else if (channelCount === 4) {
                return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
              } else if (channelCount === 5) {
                return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
              } else if (channelCount === 6) {
                return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x00, 0xb2, 0x00, 0x20, 0x08, 0xe0]);
              }
      
              break;
            // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)
      
            default:
              if (channelCount === 1) {
                // ffmpeg -y -f lavfi -i "aevalsrc=0:d=0.05" -c:a libfdk_aac -profile:a aac_he -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
                return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x4e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x1c, 0x6, 0xf1, 0xc1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
              } else if (channelCount === 2) {
                // ffmpeg -y -f lavfi -i "aevalsrc=0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
                return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
              } else if (channelCount === 3) {
                // ffmpeg -y -f lavfi -i "aevalsrc=0|0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
                return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
              }
      
              break;
          }
      
          return undefined;
        };
      
        return AAC;
      }();
      
      /* harmony default export */ __webpack_exports__["default"] = (AAC);
      
      /***/ }),
      
      /***/ "./src/remux/mp4-generator.ts":
      /*!************************************!*\
        !*** ./src/remux/mp4-generator.ts ***!
        \************************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /**
       * Generate MP4 Box
       */
      var UINT32_MAX = Math.pow(2, 32) - 1;
      
      var MP4 = /*#__PURE__*/function () {
        function MP4() {}
      
        MP4.init = function init() {
          MP4.types = {
            avc1: [],
            // codingname
            avcC: [],
            btrt: [],
            dinf: [],
            dref: [],
            esds: [],
            ftyp: [],
            hdlr: [],
            mdat: [],
            mdhd: [],
            mdia: [],
            mfhd: [],
            minf: [],
            moof: [],
            moov: [],
            mp4a: [],
            '.mp3': [],
            mvex: [],
            mvhd: [],
            pasp: [],
            sdtp: [],
            stbl: [],
            stco: [],
            stsc: [],
            stsd: [],
            stsz: [],
            stts: [],
            tfdt: [],
            tfhd: [],
            traf: [],
            trak: [],
            trun: [],
            trex: [],
            tkhd: [],
            vmhd: [],
            smhd: []
          };
          var i;
      
          for (i in MP4.types) {
            if (MP4.types.hasOwnProperty(i)) {
              MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
            }
          }
      
          var videoHdlr = new Uint8Array([0x00, // version 0
          0x00, 0x00, 0x00, // flags
          0x00, 0x00, 0x00, 0x00, // pre_defined
          0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
          0x00, 0x00, 0x00, 0x00, // reserved
          0x00, 0x00, 0x00, 0x00, // reserved
          0x00, 0x00, 0x00, 0x00, // reserved
          0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
          ]);
          var audioHdlr = new Uint8Array([0x00, // version 0
          0x00, 0x00, 0x00, // flags
          0x00, 0x00, 0x00, 0x00, // pre_defined
          0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
          0x00, 0x00, 0x00, 0x00, // reserved
          0x00, 0x00, 0x00, 0x00, // reserved
          0x00, 0x00, 0x00, 0x00, // reserved
          0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
          ]);
          MP4.HDLR_TYPES = {
            video: videoHdlr,
            audio: audioHdlr
          };
          var dref = new Uint8Array([0x00, // version 0
          0x00, 0x00, 0x00, // flags
          0x00, 0x00, 0x00, 0x01, // entry_count
          0x00, 0x00, 0x00, 0x0c, // entry_size
          0x75, 0x72, 0x6c, 0x20, // 'url' type
          0x00, // version 0
          0x00, 0x00, 0x01 // entry_flags
          ]);
          var stco = new Uint8Array([0x00, // version
          0x00, 0x00, 0x00, // flags
          0x00, 0x00, 0x00, 0x00 // entry_count
          ]);
          MP4.STTS = MP4.STSC = MP4.STCO = stco;
          MP4.STSZ = new Uint8Array([0x00, // version
          0x00, 0x00, 0x00, // flags
          0x00, 0x00, 0x00, 0x00, // sample_size
          0x00, 0x00, 0x00, 0x00 // sample_count
          ]);
          MP4.VMHD = new Uint8Array([0x00, // version
          0x00, 0x00, 0x01, // flags
          0x00, 0x00, // graphicsmode
          0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
          ]);
          MP4.SMHD = new Uint8Array([0x00, // version
          0x00, 0x00, 0x00, // flags
          0x00, 0x00, // balance
          0x00, 0x00 // reserved
          ]);
          MP4.STSD = new Uint8Array([0x00, // version 0
          0x00, 0x00, 0x00, // flags
          0x00, 0x00, 0x00, 0x01]); // entry_count
      
          var majorBrand = new Uint8Array([105, 115, 111, 109]); // isom
      
          var avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1
      
          var minorVersion = new Uint8Array([0, 0, 0, 1]);
          MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
          MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
        };
      
        MP4.box = function box(type) {
          var size = 8;
      
          for (var _len = arguments.length, payload = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
            payload[_key - 1] = arguments[_key];
          }
      
          var i = payload.length;
          var len = i; // calculate the total size we need to allocate
      
          while (i--) {
            size += payload[i].byteLength;
          }
      
          var result = new Uint8Array(size);
          result[0] = size >> 24 & 0xff;
          result[1] = size >> 16 & 0xff;
          result[2] = size >> 8 & 0xff;
          result[3] = size & 0xff;
          result.set(type, 4); // copy the payload into the result
      
          for (i = 0, size = 8; i < len; i++) {
            // copy payload[i] array @ offset size
            result.set(payload[i], size);
            size += payload[i].byteLength;
          }
      
          return result;
        };
      
        MP4.hdlr = function hdlr(type) {
          return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
        };
      
        MP4.mdat = function mdat(data) {
          return MP4.box(MP4.types.mdat, data);
        };
      
        MP4.mdhd = function mdhd(timescale, duration) {
          duration *= timescale;
          var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
          var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
          return MP4.box(MP4.types.mdhd, new Uint8Array([0x01, // version 1
          0x00, 0x00, 0x00, // flags
          0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
          0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
          timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff, // timescale
          upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x55, 0xc4, // 'und' language (undetermined)
          0x00, 0x00]));
        };
      
        MP4.mdia = function mdia(track) {
          return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));
        };
      
        MP4.mfhd = function mfhd(sequenceNumber) {
          return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
          sequenceNumber >> 24, sequenceNumber >> 16 & 0xff, sequenceNumber >> 8 & 0xff, sequenceNumber & 0xff // sequence_number
          ]));
        };
      
        MP4.minf = function minf(track) {
          if (track.type === 'audio') {
            return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));
          } else {
            return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));
          }
        };
      
        MP4.moof = function moof(sn, baseMediaDecodeTime, track) {
          return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));
        }
        /**
         * @param tracks... (optional) {array} the tracks associated with this movie
         */
        ;
      
        MP4.moov = function moov(tracks) {
          var i = tracks.length;
          var boxes = [];
      
          while (i--) {
            boxes[i] = MP4.trak(tracks[i]);
          }
      
          return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks)));
        };
      
        MP4.mvex = function mvex(tracks) {
          var i = tracks.length;
          var boxes = [];
      
          while (i--) {
            boxes[i] = MP4.trex(tracks[i]);
          }
      
          return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));
        };
      
        MP4.mvhd = function mvhd(timescale, duration) {
          duration *= timescale;
          var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
          var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
          var bytes = new Uint8Array([0x01, // version 1
          0x00, 0x00, 0x00, // flags
          0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
          0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
          timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff, // timescale
          upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x00, 0x01, 0x00, 0x00, // 1.0 rate
          0x01, 0x00, // 1.0 volume
          0x00, 0x00, // reserved
          0x00, 0x00, 0x00, 0x00, // reserved
          0x00, 0x00, 0x00, 0x00, // reserved
          0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
          0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
          0xff, 0xff, 0xff, 0xff // next_track_ID
          ]);
          return MP4.box(MP4.types.mvhd, bytes);
        };
      
        MP4.sdtp = function sdtp(track) {
          var samples = track.samples || [];
          var bytes = new Uint8Array(4 + samples.length);
          var i;
          var flags; // leave the full box header (4 bytes) all zero
          // write the sample table
      
          for (i = 0; i < samples.length; i++) {
            flags = samples[i].flags;
            bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
          }
      
          return MP4.box(MP4.types.sdtp, bytes);
        };
      
        MP4.stbl = function stbl(track) {
          return MP4.box(MP4.types.stbl, MP4.stsd(track), MP4.box(MP4.types.stts, MP4.STTS), MP4.box(MP4.types.stsc, MP4.STSC), MP4.box(MP4.types.stsz, MP4.STSZ), MP4.box(MP4.types.stco, MP4.STCO));
        };
      
        MP4.avc1 = function avc1(track) {
          var sps = [];
          var pps = [];
          var i;
          var data;
          var len; // assemble the SPSs
      
          for (i = 0; i < track.sps.length; i++) {
            data = track.sps[i];
            len = data.byteLength;
            sps.push(len >>> 8 & 0xff);
            sps.push(len & 0xff); // SPS
      
            sps = sps.concat(Array.prototype.slice.call(data));
          } // assemble the PPSs
      
      
          for (i = 0; i < track.pps.length; i++) {
            data = track.pps[i];
            len = data.byteLength;
            pps.push(len >>> 8 & 0xff);
            pps.push(len & 0xff);
            pps = pps.concat(Array.prototype.slice.call(data));
          }
      
          var avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01, // version
          sps[3], // profile
          sps[4], // profile compat
          sps[5], // level
          0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes
          0xe0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets
          ].concat(sps).concat([track.pps.length // numOfPictureParameterSets
          ]).concat(pps))); // "PPS"
      
          var width = track.width;
          var height = track.height;
          var hSpacing = track.pixelRatio[0];
          var vSpacing = track.pixelRatio[1];
          return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00, // reserved
          0x00, 0x00, 0x00, // reserved
          0x00, 0x01, // data_reference_index
          0x00, 0x00, // pre_defined
          0x00, 0x00, // reserved
          0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
          width >> 8 & 0xff, width & 0xff, // width
          height >> 8 & 0xff, height & 0xff, // height
          0x00, 0x48, 0x00, 0x00, // horizresolution
          0x00, 0x48, 0x00, 0x00, // vertresolution
          0x00, 0x00, 0x00, 0x00, // reserved
          0x00, 0x01, // frame_count
          0x12, 0x64, 0x61, 0x69, 0x6c, // dailymotion/hls.js
          0x79, 0x6d, 0x6f, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x68, 0x6c, 0x73, 0x2e, 0x6a, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // compressorname
          0x00, 0x18, // depth = 24
          0x11, 0x11]), // pre_defined = -1
          avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
          0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
          0x00, 0x2d, 0xc6, 0xc0])), // avgBitrate
          MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24, // hSpacing
          hSpacing >> 16 & 0xff, hSpacing >> 8 & 0xff, hSpacing & 0xff, vSpacing >> 24, // vSpacing
          vSpacing >> 16 & 0xff, vSpacing >> 8 & 0xff, vSpacing & 0xff])));
        };
      
        MP4.esds = function esds(track) {
          var configlen = track.config.length;
          return new Uint8Array([0x00, // version 0
          0x00, 0x00, 0x00, // flags
          0x03, // descriptor_type
          0x17 + configlen, // length
          0x00, 0x01, // es_id
          0x00, // stream_priority
          0x04, // descriptor_type
          0x0f + configlen, // length
          0x40, // codec : mpeg4_audio
          0x15, // stream_type
          0x00, 0x00, 0x00, // buffer_size
          0x00, 0x00, 0x00, 0x00, // maxBitrate
          0x00, 0x00, 0x00, 0x00, // avgBitrate
          0x05 // descriptor_type
          ].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor
        };
      
        MP4.mp4a = function mp4a(track) {
          var samplerate = track.samplerate;
          return MP4.box(MP4.types.mp4a, new Uint8Array([0x00, 0x00, 0x00, // reserved
          0x00, 0x00, 0x00, // reserved
          0x00, 0x01, // data_reference_index
          0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
          0x00, track.channelCount, // channelcount
          0x00, 0x10, // sampleSize:16bits
          0x00, 0x00, 0x00, 0x00, // reserved2
          samplerate >> 8 & 0xff, samplerate & 0xff, //
          0x00, 0x00]), MP4.box(MP4.types.esds, MP4.esds(track)));
        };
      
        MP4.mp3 = function mp3(track) {
          var samplerate = track.samplerate;
          return MP4.box(MP4.types['.mp3'], new Uint8Array([0x00, 0x00, 0x00, // reserved
          0x00, 0x00, 0x00, // reserved
          0x00, 0x01, // data_reference_index
          0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
          0x00, track.channelCount, // channelcount
          0x00, 0x10, // sampleSize:16bits
          0x00, 0x00, 0x00, 0x00, // reserved2
          samplerate >> 8 & 0xff, samplerate & 0xff, //
          0x00, 0x00]));
        };
      
        MP4.stsd = function stsd(track) {
          if (track.type === 'audio') {
            if (!track.isAAC && track.codec === 'mp3') {
              return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));
            }
      
            return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));
          } else {
            return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));
          }
        };
      
        MP4.tkhd = function tkhd(track) {
          var id = track.id;
          var duration = track.duration * track.timescale;
          var width = track.width;
          var height = track.height;
          var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
          var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
          return MP4.box(MP4.types.tkhd, new Uint8Array([0x01, // version 1
          0x00, 0x00, 0x07, // flags
          0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
          0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
          id >> 24 & 0xff, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff, // track_ID
          0x00, 0x00, 0x00, 0x00, // reserved
          upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
          0x00, 0x00, // layer
          0x00, 0x00, // alternate_group
          0x00, 0x00, // non-audio track volume
          0x00, 0x00, // reserved
          0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
          width >> 8 & 0xff, width & 0xff, 0x00, 0x00, // width
          height >> 8 & 0xff, height & 0xff, 0x00, 0x00 // height
          ]));
        };
      
        MP4.traf = function traf(track, baseMediaDecodeTime) {
          var sampleDependencyTable = MP4.sdtp(track);
          var id = track.id;
          var upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
          var lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
          return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00, // version 0
          0x00, 0x00, 0x00, // flags
          id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff // track_ID
          ])), MP4.box(MP4.types.tfdt, new Uint8Array([0x01, // version 1
          0x00, 0x00, 0x00, // flags
          upperWordBaseMediaDecodeTime >> 24, upperWordBaseMediaDecodeTime >> 16 & 0xff, upperWordBaseMediaDecodeTime >> 8 & 0xff, upperWordBaseMediaDecodeTime & 0xff, lowerWordBaseMediaDecodeTime >> 24, lowerWordBaseMediaDecodeTime >> 16 & 0xff, lowerWordBaseMediaDecodeTime >> 8 & 0xff, lowerWordBaseMediaDecodeTime & 0xff])), MP4.trun(track, sampleDependencyTable.length + 16 + // tfhd
          20 + // tfdt
          8 + // traf header
          16 + // mfhd
          8 + // moof header
          8), // mdat header
          sampleDependencyTable);
        }
        /**
         * Generate a track box.
         * @param track {object} a track definition
         * @return {Uint8Array} the track box
         */
        ;
      
        MP4.trak = function trak(track) {
          track.duration = track.duration || 0xffffffff;
          return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
        };
      
        MP4.trex = function trex(track) {
          var id = track.id;
          return MP4.box(MP4.types.trex, new Uint8Array([0x00, // version 0
          0x00, 0x00, 0x00, // flags
          id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff, // track_ID
          0x00, 0x00, 0x00, 0x01, // default_sample_description_index
          0x00, 0x00, 0x00, 0x00, // default_sample_duration
          0x00, 0x00, 0x00, 0x00, // default_sample_size
          0x00, 0x01, 0x00, 0x01 // default_sample_flags
          ]));
        };
      
        MP4.trun = function trun(track, offset) {
          var samples = track.samples || [];
          var len = samples.length;
          var arraylen = 12 + 16 * len;
          var array = new Uint8Array(arraylen);
          var i;
          var sample;
          var duration;
          var size;
          var flags;
          var cts;
          offset += 8 + arraylen;
          array.set([0x00, // version 0
          0x00, 0x0f, 0x01, // flags
          len >>> 24 & 0xff, len >>> 16 & 0xff, len >>> 8 & 0xff, len & 0xff, // sample_count
          offset >>> 24 & 0xff, offset >>> 16 & 0xff, offset >>> 8 & 0xff, offset & 0xff // data_offset
          ], 0);
      
          for (i = 0; i < len; i++) {
            sample = samples[i];
            duration = sample.duration;
            size = sample.size;
            flags = sample.flags;
            cts = sample.cts;
            array.set([duration >>> 24 & 0xff, duration >>> 16 & 0xff, duration >>> 8 & 0xff, duration & 0xff, // sample_duration
            size >>> 24 & 0xff, size >>> 16 & 0xff, size >>> 8 & 0xff, size & 0xff, // sample_size
            flags.isLeading << 2 | flags.dependsOn, flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync, flags.degradPrio & 0xf0 << 8, flags.degradPrio & 0x0f, // sample_flags
            cts >>> 24 & 0xff, cts >>> 16 & 0xff, cts >>> 8 & 0xff, cts & 0xff // sample_composition_time_offset
            ], 12 + 16 * i);
          }
      
          return MP4.box(MP4.types.trun, array);
        };
      
        MP4.initSegment = function initSegment(tracks) {
          if (!MP4.types) {
            MP4.init();
          }
      
          var movie = MP4.moov(tracks);
          var result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);
          result.set(MP4.FTYP);
          result.set(movie, MP4.FTYP.byteLength);
          return result;
        };
      
        return MP4;
      }();
      
      MP4.types = void 0;
      MP4.HDLR_TYPES = void 0;
      MP4.STTS = void 0;
      MP4.STSC = void 0;
      MP4.STCO = void 0;
      MP4.STSZ = void 0;
      MP4.VMHD = void 0;
      MP4.SMHD = void 0;
      MP4.STSD = void 0;
      MP4.FTYP = void 0;
      MP4.DINF = void 0;
      /* harmony default export */ __webpack_exports__["default"] = (MP4);
      
      /***/ }),
      
      /***/ "./src/remux/mp4-remuxer.ts":
      /*!**********************************!*\
        !*** ./src/remux/mp4-remuxer.ts ***!
        \**********************************/
      /*! exports provided: default, normalizePts */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return MP4Remuxer; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "normalizePts", function() { return normalizePts; });
      /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
      /* harmony import */ var _aac_helper__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./aac-helper */ "./src/remux/aac-helper.ts");
      /* harmony import */ var _mp4_generator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./mp4-generator */ "./src/remux/mp4-generator.ts");
      /* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../events */ "./src/events.ts");
      /* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      /* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
      /* harmony import */ var _utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/timescale-conversion */ "./src/utils/timescale-conversion.ts");
      
      
      function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
      
      
      
      
      
      
      
      
      var MAX_SILENT_FRAME_DURATION = 10 * 1000; // 10 seconds
      
      var AAC_SAMPLES_PER_FRAME = 1024;
      var MPEG_AUDIO_SAMPLE_PER_FRAME = 1152;
      var chromeVersion = null;
      var safariWebkitVersion = null;
      var requiresPositiveDts = false;
      
      var MP4Remuxer = /*#__PURE__*/function () {
        function MP4Remuxer(observer, config, typeSupported, vendor) {
          if (vendor === void 0) {
            vendor = '';
          }
      
          this.observer = void 0;
          this.config = void 0;
          this.typeSupported = void 0;
          this.ISGenerated = false;
          this._initPTS = void 0;
          this._initDTS = void 0;
          this.nextAvcDts = null;
          this.nextAudioPts = null;
          this.isAudioContiguous = false;
          this.isVideoContiguous = false;
          this.observer = observer;
          this.config = config;
          this.typeSupported = typeSupported;
          this.ISGenerated = false;
      
          if (chromeVersion === null) {
            var userAgent = navigator.userAgent || '';
            var result = userAgent.match(/Chrome\/(\d+)/i);
            chromeVersion = result ? parseInt(result[1]) : 0;
          }
      
          if (safariWebkitVersion === null) {
            var _result = navigator.userAgent.match(/Safari\/(\d+)/i);
      
            safariWebkitVersion = _result ? parseInt(_result[1]) : 0;
          }
      
          requiresPositiveDts = !!chromeVersion && chromeVersion < 75 || !!safariWebkitVersion && safariWebkitVersion < 600;
        }
      
        var _proto = MP4Remuxer.prototype;
      
        _proto.destroy = function destroy() {};
      
        _proto.resetTimeStamp = function resetTimeStamp(defaultTimeStamp) {
          _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: initPTS & initDTS reset');
          this._initPTS = this._initDTS = defaultTimeStamp;
        };
      
        _proto.resetNextTimestamp = function resetNextTimestamp() {
          _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: reset next timestamp');
          this.isVideoContiguous = false;
          this.isAudioContiguous = false;
        };
      
        _proto.resetInitSegment = function resetInitSegment() {
          _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: ISGenerated flag reset');
          this.ISGenerated = false;
        };
      
        _proto.getVideoStartPts = function getVideoStartPts(videoSamples) {
          var rolloverDetected = false;
          var startPTS = videoSamples.reduce(function (minPTS, sample) {
            var delta = sample.pts - minPTS;
      
            if (delta < -4294967296) {
              // 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation
              rolloverDetected = true;
              return normalizePts(minPTS, sample.pts);
            } else if (delta > 0) {
              return minPTS;
            } else {
              return sample.pts;
            }
          }, videoSamples[0].pts);
      
          if (rolloverDetected) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].debug('PTS rollover detected');
          }
      
          return startPTS;
        };
      
        _proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, flush, playlistType) {
          var video;
          var audio;
          var initSegment;
          var text;
          var id3;
          var independent;
          var audioTimeOffset = timeOffset;
          var videoTimeOffset = timeOffset; // If we're remuxing audio and video progressively, wait until we've received enough samples for each track before proceeding.
          // This is done to synchronize the audio and video streams. We know if the current segment will have samples if the "pid"
          // parameter is greater than -1. The pid is set when the PMT is parsed, which contains the tracks list.
          // However, if the initSegment has already been generated, or we've reached the end of a segment (flush),
          // then we can remux one track without waiting for the other.
      
          var hasAudio = audioTrack.pid > -1;
          var hasVideo = videoTrack.pid > -1;
          var length = videoTrack.samples.length;
          var enoughAudioSamples = audioTrack.samples.length > 0;
          var enoughVideoSamples = length > 1;
          var canRemuxAvc = (!hasAudio || enoughAudioSamples) && (!hasVideo || enoughVideoSamples) || this.ISGenerated || flush;
      
          if (canRemuxAvc) {
            if (!this.ISGenerated) {
              initSegment = this.generateIS(audioTrack, videoTrack, timeOffset);
            }
      
            var isVideoContiguous = this.isVideoContiguous;
            var firstKeyFrameIndex = -1;
      
            if (enoughVideoSamples) {
              firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples);
      
              if (!isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) {
                independent = true;
      
                if (firstKeyFrameIndex > 0) {
                  _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("[mp4-remuxer]: Dropped " + firstKeyFrameIndex + " out of " + length + " video samples due to a missing keyframe");
                  var startPTS = this.getVideoStartPts(videoTrack.samples);
                  videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex);
                  videoTrack.dropped += firstKeyFrameIndex;
                  videoTimeOffset += (videoTrack.samples[0].pts - startPTS) / (videoTrack.timescale || 90000);
                } else if (firstKeyFrameIndex === -1) {
                  _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("[mp4-remuxer]: No keyframe found out of " + length + " video samples");
                  independent = false;
                }
              }
            }
      
            if (this.ISGenerated) {
              if (enoughAudioSamples && enoughVideoSamples) {
                // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)
                // if first audio DTS is not aligned with first video DTS then we need to take that into account
                // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small
                // drift between audio and video streams
                var _startPTS = this.getVideoStartPts(videoTrack.samples);
      
                var tsDelta = normalizePts(audioTrack.samples[0].pts, _startPTS) - _startPTS;
      
                var audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;
                audioTimeOffset += Math.max(0, audiovideoTimestampDelta);
                videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);
              } // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is calculated in remuxAudio.
      
      
              if (enoughAudioSamples) {
                // if initSegment was generated without audio samples, regenerate it again
                if (!audioTrack.samplerate) {
                  _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn('[mp4-remuxer]: regenerate InitSegment as audio detected');
                  initSegment = this.generateIS(audioTrack, videoTrack, timeOffset);
                }
      
                audio = this.remuxAudio(audioTrack, audioTimeOffset, this.isAudioContiguous, accurateTimeOffset, hasVideo || enoughVideoSamples || playlistType === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO ? videoTimeOffset : undefined);
      
                if (enoughVideoSamples) {
                  var audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0; // if initSegment was generated without video samples, regenerate it again
      
                  if (!videoTrack.inputTimeScale) {
                    _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn('[mp4-remuxer]: regenerate InitSegment as video detected');
                    initSegment = this.generateIS(audioTrack, videoTrack, timeOffset);
                  }
      
                  video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, audioTrackLength);
                }
              } else if (enoughVideoSamples) {
                video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, 0);
              }
      
              if (video) {
                video.firstKeyFrame = firstKeyFrameIndex;
                video.independent = firstKeyFrameIndex !== -1;
              }
            }
          } // Allow ID3 and text to remux, even if more audio/video samples are required
      
      
          if (this.ISGenerated) {
            if (id3Track.samples.length) {
              id3 = this.remuxID3(id3Track, timeOffset);
            }
      
            if (textTrack.samples.length) {
              text = this.remuxText(textTrack, timeOffset);
            }
          }
      
          return {
            audio: audio,
            video: video,
            initSegment: initSegment,
            independent: independent,
            text: text,
            id3: id3
          };
        };
      
        _proto.generateIS = function generateIS(audioTrack, videoTrack, timeOffset) {
          var audioSamples = audioTrack.samples;
          var videoSamples = videoTrack.samples;
          var typeSupported = this.typeSupported;
          var tracks = {};
          var computePTSDTS = !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this._initPTS);
          var container = 'audio/mp4';
          var initPTS;
          var initDTS;
          var timescale;
      
          if (computePTSDTS) {
            initPTS = initDTS = Infinity;
          }
      
          if (audioTrack.config && audioSamples.length) {
            // let's use audio sampling rate as MP4 time scale.
            // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)
            // using audio sampling rate here helps having an integer MP4 frame duration
            // this avoids potential rounding issue and AV sync issue
            audioTrack.timescale = audioTrack.samplerate;
      
            if (!audioTrack.isAAC) {
              if (typeSupported.mpeg) {
                // Chrome and Safari
                container = 'audio/mpeg';
                audioTrack.codec = '';
              } else if (typeSupported.mp3) {
                // Firefox
                audioTrack.codec = 'mp3';
              }
            }
      
            tracks.audio = {
              id: 'audio',
              container: container,
              codec: audioTrack.codec,
              initSegment: !audioTrack.isAAC && typeSupported.mpeg ? new Uint8Array(0) : _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].initSegment([audioTrack]),
              metadata: {
                channelCount: audioTrack.channelCount
              }
            };
      
            if (computePTSDTS) {
              timescale = audioTrack.inputTimeScale; // remember first PTS of this demuxing context. for audio, PTS = DTS
      
              initPTS = initDTS = audioSamples[0].pts - Math.round(timescale * timeOffset);
            }
          }
      
          if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
            // let's use input time scale as MP4 video timescale
            // we use input time scale straight away to avoid rounding issues on frame duration / cts computation
            videoTrack.timescale = videoTrack.inputTimeScale;
            tracks.video = {
              id: 'main',
              container: 'video/mp4',
              codec: videoTrack.codec,
              initSegment: _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].initSegment([videoTrack]),
              metadata: {
                width: videoTrack.width,
                height: videoTrack.height
              }
            };
      
            if (computePTSDTS) {
              timescale = videoTrack.inputTimeScale;
              var startPTS = this.getVideoStartPts(videoSamples);
              var startOffset = Math.round(timescale * timeOffset);
              initDTS = Math.min(initDTS, normalizePts(videoSamples[0].dts, startPTS) - startOffset);
              initPTS = Math.min(initPTS, startPTS - startOffset);
            }
          }
      
          if (Object.keys(tracks).length) {
            this.ISGenerated = true;
      
            if (computePTSDTS) {
              this._initPTS = initPTS;
              this._initDTS = initDTS;
            }
      
            return {
              tracks: tracks,
              initPTS: initPTS,
              timescale: timescale
            };
          }
        };
      
        _proto.remuxVideo = function remuxVideo(track, timeOffset, contiguous, audioTrackLength) {
          var timeScale = track.inputTimeScale;
          var inputSamples = track.samples;
          var outputSamples = [];
          var nbSamples = inputSamples.length;
          var initPTS = this._initPTS;
          var nextAvcDts = this.nextAvcDts;
          var offset = 8;
          var mp4SampleDuration;
          var firstDTS;
          var lastDTS;
          var minPTS = Number.POSITIVE_INFINITY;
          var maxPTS = Number.NEGATIVE_INFINITY;
          var ptsDtsShift = 0;
          var sortSamples = false; // if parsed fragment is contiguous with last one, let's use last DTS value as reference
      
          if (!contiguous || nextAvcDts === null) {
            var pts = timeOffset * timeScale;
            var cts = inputSamples[0].pts - normalizePts(inputSamples[0].dts, inputSamples[0].pts); // if not contiguous, let's use target timeOffset
      
            nextAvcDts = pts - cts;
          } // PTS is coded on 33bits, and can loop from -2^32 to 2^32
          // PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value
      
      
          for (var i = 0; i < nbSamples; i++) {
            var sample = inputSamples[i];
            sample.pts = normalizePts(sample.pts - initPTS, nextAvcDts);
            sample.dts = normalizePts(sample.dts - initPTS, nextAvcDts);
      
            if (sample.dts > sample.pts) {
              var PTS_DTS_SHIFT_TOLERANCE_90KHZ = 90000 * 0.2;
              ptsDtsShift = Math.max(Math.min(ptsDtsShift, sample.pts - sample.dts), -1 * PTS_DTS_SHIFT_TOLERANCE_90KHZ);
            }
      
            if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {
              sortSamples = true;
            }
          } // sort video samples by DTS then PTS then demux id order
      
      
          if (sortSamples) {
            inputSamples.sort(function (a, b) {
              var deltadts = a.dts - b.dts;
              var deltapts = a.pts - b.pts;
              return deltadts || deltapts;
            });
          } // Get first/last DTS
      
      
          firstDTS = inputSamples[0].dts;
          lastDTS = inputSamples[inputSamples.length - 1].dts; // on Safari let's signal the same sample duration for all samples
          // sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS
          // set this constant duration as being the avg delta between consecutive DTS.
      
          var averageSampleDuration = Math.round((lastDTS - firstDTS) / (nbSamples - 1)); // handle broken streams with PTS < DTS, tolerance up 0.2 seconds
      
          if (ptsDtsShift < 0) {
            if (ptsDtsShift < averageSampleDuration * -2) {
              // Fix for "CNN special report, with CC" in test-streams (including Safari browser)
              // With large PTS < DTS errors such as this, we want to correct CTS while maintaining increasing DTS values
              _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("PTS < DTS detected in video samples, offsetting DTS from PTS by " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(-averageSampleDuration, true) + " ms");
              var lastDts = ptsDtsShift;
      
              for (var _i = 0; _i < nbSamples; _i++) {
                inputSamples[_i].dts = lastDts = Math.max(lastDts, inputSamples[_i].pts - averageSampleDuration);
                inputSamples[_i].pts = Math.max(lastDts, inputSamples[_i].pts);
              }
            } else {
              // Fix for "Custom IV with bad PTS DTS" in test-streams
              // With smaller PTS < DTS errors we can simply move all DTS back. This increases CTS without causing buffer gaps or decode errors in Safari
              _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("PTS < DTS detected in video samples, shifting DTS by " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(ptsDtsShift, true) + " ms to overcome this issue");
      
              for (var _i2 = 0; _i2 < nbSamples; _i2++) {
                inputSamples[_i2].dts = inputSamples[_i2].dts + ptsDtsShift;
              }
            }
      
            firstDTS = inputSamples[0].dts;
          } // if fragment are contiguous, detect hole/overlapping between fragments
      
      
          if (contiguous) {
            // check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole)
            var delta = firstDTS - nextAvcDts;
            var foundHole = delta > averageSampleDuration;
            var foundOverlap = delta < -1;
      
            if (foundHole || foundOverlap) {
              if (foundHole) {
                _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("AVC: " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(delta, true) + " ms (" + delta + "dts) hole between fragments detected, filling it");
              } else {
                _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("AVC: " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(-delta, true) + " ms (" + delta + "dts) overlapping between fragments detected");
              }
      
              firstDTS = nextAvcDts;
              var firstPTS = inputSamples[0].pts - delta;
              inputSamples[0].dts = firstDTS;
              inputSamples[0].pts = firstPTS;
              _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log("Video: First PTS/DTS adjusted: " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(firstPTS, true) + "/" + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(firstDTS, true) + ", delta: " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_7__["toMsFromMpegTsClock"])(delta, true) + " ms");
            }
          }
      
          if (requiresPositiveDts) {
            firstDTS = Math.max(0, firstDTS);
          }
      
          var nbNalu = 0;
          var naluLen = 0;
      
          for (var _i3 = 0; _i3 < nbSamples; _i3++) {
            // compute total/avc sample length and nb of NAL units
            var _sample = inputSamples[_i3];
            var units = _sample.units;
            var nbUnits = units.length;
            var sampleLen = 0;
      
            for (var j = 0; j < nbUnits; j++) {
              sampleLen += units[j].data.length;
            }
      
            naluLen += sampleLen;
            nbNalu += nbUnits;
            _sample.length = sampleLen; // normalize PTS/DTS
            // ensure sample monotonic DTS
      
            _sample.dts = Math.max(_sample.dts, firstDTS); // ensure that computed value is greater or equal than sample DTS
      
            _sample.pts = Math.max(_sample.pts, _sample.dts, 0);
            minPTS = Math.min(_sample.pts, minPTS);
            maxPTS = Math.max(_sample.pts, maxPTS);
          }
      
          lastDTS = inputSamples[nbSamples - 1].dts;
          /* concatenate the video data and construct the mdat in place
            (need 8 more bytes to fill length and mpdat type) */
      
          var mdatSize = naluLen + 4 * nbNalu + 8;
          var mdat;
      
          try {
            mdat = new Uint8Array(mdatSize);
          } catch (err) {
            this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, {
              type: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorTypes"].MUX_ERROR,
              details: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].REMUX_ALLOC_ERROR,
              fatal: false,
              bytes: mdatSize,
              reason: "fail allocating video mdat " + mdatSize
            });
            return;
          }
      
          var view = new DataView(mdat.buffer);
          view.setUint32(0, mdatSize);
          mdat.set(_mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].types.mdat, 4);
      
          for (var _i4 = 0; _i4 < nbSamples; _i4++) {
            var avcSample = inputSamples[_i4];
            var avcSampleUnits = avcSample.units;
            var mp4SampleLength = 0; // convert NALU bitstream to MP4 format (prepend NALU with size field)
      
            for (var _j = 0, _nbUnits = avcSampleUnits.length; _j < _nbUnits; _j++) {
              var unit = avcSampleUnits[_j];
              var unitData = unit.data;
              var unitDataLen = unit.data.byteLength;
              view.setUint32(offset, unitDataLen);
              offset += 4;
              mdat.set(unitData, offset);
              offset += unitDataLen;
              mp4SampleLength += 4 + unitDataLen;
            } // expected sample duration is the Decoding Timestamp diff of consecutive samples
      
      
            if (_i4 < nbSamples - 1) {
              mp4SampleDuration = inputSamples[_i4 + 1].dts - avcSample.dts;
            } else {
              var config = this.config;
              var lastFrameDuration = avcSample.dts - inputSamples[_i4 > 0 ? _i4 - 1 : _i4].dts;
      
              if (config.stretchShortVideoTrack && this.nextAudioPts !== null) {
                // In some cases, a segment's audio track duration may exceed the video track duration.
                // Since we've already remuxed audio, and we know how long the audio track is, we look to
                // see if the delta to the next segment is longer than maxBufferHole.
                // If so, playback would potentially get stuck, so we artificially inflate
                // the duration of the last frame to minimize any potential gap between segments.
                var gapTolerance = Math.floor(config.maxBufferHole * timeScale);
                var deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioPts) - avcSample.pts;
      
                if (deltaToFrameEnd > gapTolerance) {
                  // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video
                  // frame overlap. maxBufferHole should be >> lastFrameDuration anyway.
                  mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
      
                  if (mp4SampleDuration < 0) {
                    mp4SampleDuration = lastFrameDuration;
                  }
      
                  _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log("[mp4-remuxer]: It is approximately " + deltaToFrameEnd / 90 + " ms to the next segment; using duration " + mp4SampleDuration / 90 + " ms for the last video frame.");
                } else {
                  mp4SampleDuration = lastFrameDuration;
                }
              } else {
                mp4SampleDuration = lastFrameDuration;
              }
            }
      
            var compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts);
            outputSamples.push(new Mp4Sample(avcSample.key, mp4SampleDuration, mp4SampleLength, compositionTimeOffset));
          }
      
          if (outputSamples.length && chromeVersion && chromeVersion < 70) {
            // Chrome workaround, mark first sample as being a Random Access Point (keyframe) to avoid sourcebuffer append issue
            // https://code.google.com/p/chromium/issues/detail?id=229412
            var flags = outputSamples[0].flags;
            flags.dependsOn = 2;
            flags.isNonSync = 0;
          }
      
          console.assert(mp4SampleDuration !== undefined, 'mp4SampleDuration must be computed'); // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)
      
          this.nextAvcDts = nextAvcDts = lastDTS + mp4SampleDuration;
          this.isVideoContiguous = true;
          var moof = _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].moof(track.sequenceNumber++, firstDTS, _extends({}, track, {
            samples: outputSamples
          }));
          var type = 'video';
          var data = {
            data1: moof,
            data2: mdat,
            startPTS: minPTS / timeScale,
            endPTS: (maxPTS + mp4SampleDuration) / timeScale,
            startDTS: firstDTS / timeScale,
            endDTS: nextAvcDts / timeScale,
            type: type,
            hasAudio: false,
            hasVideo: true,
            nb: outputSamples.length,
            dropped: track.dropped
          };
          track.samples = [];
          track.dropped = 0;
          console.assert(mdat.length, 'MDAT length must not be zero');
          return data;
        };
      
        _proto.remuxAudio = function remuxAudio(track, timeOffset, contiguous, accurateTimeOffset, videoTimeOffset) {
          var inputTimeScale = track.inputTimeScale;
          var mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
          var scaleFactor = inputTimeScale / mp4timeScale;
          var mp4SampleDuration = track.isAAC ? AAC_SAMPLES_PER_FRAME : MPEG_AUDIO_SAMPLE_PER_FRAME;
          var inputSampleDuration = mp4SampleDuration * scaleFactor;
          var initPTS = this._initPTS;
          var rawMPEG = !track.isAAC && this.typeSupported.mpeg;
          var outputSamples = [];
          var inputSamples = track.samples;
          var offset = rawMPEG ? 0 : 8;
          var nextAudioPts = this.nextAudioPts || -1; // window.audioSamples ? window.audioSamples.push(inputSamples.map(s => s.pts)) : (window.audioSamples = [inputSamples.map(s => s.pts)]);
          // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),
          // for sake of clarity:
          // consecutive fragments are frags with
          //  - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
          //  - less than 20 audio frames distance
          // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
          // this helps ensuring audio continuity
          // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame
      
          var timeOffsetMpegTS = timeOffset * inputTimeScale;
          this.isAudioContiguous = contiguous = contiguous || inputSamples.length && nextAudioPts > 0 && (accurateTimeOffset && Math.abs(timeOffsetMpegTS - nextAudioPts) < 9000 || Math.abs(normalizePts(inputSamples[0].pts - initPTS, timeOffsetMpegTS) - nextAudioPts) < 20 * inputSampleDuration); // compute normalized PTS
      
          inputSamples.forEach(function (sample) {
            sample.pts = normalizePts(sample.pts - initPTS, timeOffsetMpegTS);
          });
      
          if (!contiguous || nextAudioPts < 0) {
            // filter out sample with negative PTS that are not playable anyway
            // if we don't remove these negative samples, they will shift all audio samples forward.
            // leading to audio overlap between current / next fragment
            inputSamples = inputSamples.filter(function (sample) {
              return sample.pts >= 0;
            }); // in case all samples have negative PTS, and have been filtered out, return now
      
            if (!inputSamples.length) {
              return;
            }
      
            if (videoTimeOffset === 0) {
              // Set the start to 0 to match video so that start gaps larger than inputSampleDuration are filled with silence
              nextAudioPts = 0;
            } else if (accurateTimeOffset) {
              // When not seeking, not live, and LevelDetails.PTSKnown, use fragment start as predicted next audio PTS
              nextAudioPts = Math.max(0, timeOffsetMpegTS);
            } else {
              // if frags are not contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS
              nextAudioPts = inputSamples[0].pts;
            }
          } // If the audio track is missing samples, the frames seem to get "left-shifted" within the
          // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.
          // In an effort to prevent this from happening, we inject frames here where there are gaps.
          // When possible, we inject a silent frame; when that's not possible, we duplicate the last
          // frame.
      
      
          if (track.isAAC) {
            var alignedWithVideo = videoTimeOffset !== undefined;
            var maxAudioFramesDrift = this.config.maxAudioFramesDrift;
      
            for (var i = 0, nextPts = nextAudioPts; i < inputSamples.length; i++) {
              // First, let's see how far off this frame is from where we expect it to be
              var sample = inputSamples[i];
              var pts = sample.pts;
              var delta = pts - nextPts;
              var duration = Math.abs(1000 * delta / inputTimeScale); // When remuxing with video, if we're overlapping by more than a duration, drop this sample to stay in sync
      
              if (delta <= -maxAudioFramesDrift * inputSampleDuration && alignedWithVideo) {
                if (i === 0) {
                  _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("Audio frame @ " + (pts / inputTimeScale).toFixed(3) + "s overlaps nextAudioPts by " + Math.round(1000 * delta / inputTimeScale) + " ms.");
                  this.nextAudioPts = nextAudioPts = nextPts = pts;
                }
              } // eslint-disable-line brace-style
              // Insert missing frames if:
              // 1: We're more than maxAudioFramesDrift frame away
              // 2: Not more than MAX_SILENT_FRAME_DURATION away
              // 3: currentTime (aka nextPtsNorm) is not 0
              // 4: remuxing with video (videoTimeOffset !== undefined)
              else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && alignedWithVideo) {
                var missing = Math.round(delta / inputSampleDuration); // Adjust nextPts so that silent samples are aligned with media pts. This will prevent media samples from
                // later being shifted if nextPts is based on timeOffset and delta is not a multiple of inputSampleDuration.
      
                nextPts = pts - missing * inputSampleDuration;
      
                if (nextPts < 0) {
                  missing--;
                  nextPts += inputSampleDuration;
                }
      
                if (i === 0) {
                  this.nextAudioPts = nextAudioPts = nextPts;
                }
      
                _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("[mp4-remuxer]: Injecting " + missing + " audio frame @ " + (nextPts / inputTimeScale).toFixed(3) + "s due to " + Math.round(1000 * delta / inputTimeScale) + " ms gap.");
      
                for (var j = 0; j < missing; j++) {
                  var newStamp = Math.max(nextPts, 0);
                  var fillFrame = _aac_helper__WEBPACK_IMPORTED_MODULE_1__["default"].getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
      
                  if (!fillFrame) {
                    _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead.');
                    fillFrame = sample.unit.subarray();
                  }
      
                  inputSamples.splice(i, 0, {
                    unit: fillFrame,
                    pts: newStamp
                  });
                  nextPts += inputSampleDuration;
                  i++;
                }
              }
      
              sample.pts = nextPts;
              nextPts += inputSampleDuration;
            }
          }
      
          var firstPTS = null;
          var lastPTS = null;
          var mdat;
          var mdatSize = 0;
          var sampleLength = inputSamples.length;
      
          while (sampleLength--) {
            mdatSize += inputSamples[sampleLength].unit.byteLength;
          }
      
          for (var _j2 = 0, _nbSamples = inputSamples.length; _j2 < _nbSamples; _j2++) {
            var audioSample = inputSamples[_j2];
            var unit = audioSample.unit;
            var _pts = audioSample.pts;
      
            if (lastPTS !== null) {
              // If we have more than one sample, set the duration of the sample to the "real" duration; the PTS diff with
              // the previous sample
              var prevSample = outputSamples[_j2 - 1];
              prevSample.duration = Math.round((_pts - lastPTS) / scaleFactor);
            } else {
              if (contiguous && track.isAAC) {
                // set PTS/DTS to expected PTS/DTS
                _pts = nextAudioPts;
              } // remember first PTS of our audioSamples
      
      
              firstPTS = _pts;
      
              if (mdatSize > 0) {
                /* concatenate the audio data and construct the mdat in place
                  (need 8 more bytes to fill length and mdat type) */
                mdatSize += offset;
      
                try {
                  mdat = new Uint8Array(mdatSize);
                } catch (err) {
                  this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, {
                    type: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorTypes"].MUX_ERROR,
                    details: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].REMUX_ALLOC_ERROR,
                    fatal: false,
                    bytes: mdatSize,
                    reason: "fail allocating audio mdat " + mdatSize
                  });
                  return;
                }
      
                if (!rawMPEG) {
                  var view = new DataView(mdat.buffer);
                  view.setUint32(0, mdatSize);
                  mdat.set(_mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].types.mdat, 4);
                }
              } else {
                // no audio samples
                return;
              }
            }
      
            mdat.set(unit, offset);
            var unitLen = unit.byteLength;
            offset += unitLen; // Default the sample's duration to the computed mp4SampleDuration, which will either be 1024 for AAC or 1152 for MPEG
            // In the case that we have 1 sample, this will be the duration. If we have more than one sample, the duration
            // becomes the PTS diff with the previous sample
      
            outputSamples.push(new Mp4Sample(true, mp4SampleDuration, unitLen, 0));
            lastPTS = _pts;
          } // We could end up with no audio samples if all input samples were overlapping with the previously remuxed ones
      
      
          var nbSamples = outputSamples.length;
      
          if (!nbSamples) {
            return;
          } // The next audio sample PTS should be equal to last sample PTS + duration
      
      
          var lastSample = outputSamples[outputSamples.length - 1];
          this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSample.duration; // Set the track samples from inputSamples to outputSamples before remuxing
      
          var moof = rawMPEG ? new Uint8Array(0) : _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].moof(track.sequenceNumber++, firstPTS / scaleFactor, _extends({}, track, {
            samples: outputSamples
          })); // Clear the track samples. This also clears the samples array in the demuxer, since the reference is shared
      
          track.samples = [];
          var start = firstPTS / inputTimeScale;
          var end = nextAudioPts / inputTimeScale;
          var type = 'audio';
          var audioData = {
            data1: moof,
            data2: mdat,
            startPTS: start,
            endPTS: end,
            startDTS: start,
            endDTS: end,
            type: type,
            hasAudio: true,
            hasVideo: false,
            nb: nbSamples
          };
          this.isAudioContiguous = true;
          console.assert(mdat.length, 'MDAT length must not be zero');
          return audioData;
        };
      
        _proto.remuxEmptyAudio = function remuxEmptyAudio(track, timeOffset, contiguous, videoData) {
          var inputTimeScale = track.inputTimeScale;
          var mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
          var scaleFactor = inputTimeScale / mp4timeScale;
          var nextAudioPts = this.nextAudioPts; // sync with video's timestamp
      
          var startDTS = (nextAudioPts !== null ? nextAudioPts : videoData.startDTS * inputTimeScale) + this._initDTS;
          var endDTS = videoData.endDTS * inputTimeScale + this._initDTS; // one sample's duration value
      
          var frameDuration = scaleFactor * AAC_SAMPLES_PER_FRAME; // samples count of this segment's duration
      
          var nbSamples = Math.ceil((endDTS - startDTS) / frameDuration); // silent frame
      
          var silentFrame = _aac_helper__WEBPACK_IMPORTED_MODULE_1__["default"].getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
          _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn('[mp4-remuxer]: remux empty Audio'); // Can't remux if we can't generate a silent frame...
      
          if (!silentFrame) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].trace('[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec');
            return;
          }
      
          var samples = [];
      
          for (var i = 0; i < nbSamples; i++) {
            var stamp = startDTS + i * frameDuration;
            samples.push({
              unit: silentFrame,
              pts: stamp,
              dts: stamp
            });
          }
      
          track.samples = samples;
          return this.remuxAudio(track, timeOffset, contiguous, false);
        };
      
        _proto.remuxID3 = function remuxID3(track, timeOffset) {
          var length = track.samples.length;
      
          if (!length) {
            return;
          }
      
          var inputTimeScale = track.inputTimeScale;
          var initPTS = this._initPTS;
          var initDTS = this._initDTS;
      
          for (var index = 0; index < length; index++) {
            var sample = track.samples[index]; // setting id3 pts, dts to relative time
            // using this._initPTS and this._initDTS to calculate relative time
      
            sample.pts = normalizePts(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale;
            sample.dts = normalizePts(sample.dts - initDTS, timeOffset * inputTimeScale) / inputTimeScale;
          }
      
          var samples = track.samples;
          track.samples = [];
          return {
            samples: samples
          };
        };
      
        _proto.remuxText = function remuxText(track, timeOffset) {
          var length = track.samples.length;
      
          if (!length) {
            return;
          }
      
          var inputTimeScale = track.inputTimeScale;
          var initPTS = this._initPTS;
      
          for (var index = 0; index < length; index++) {
            var sample = track.samples[index]; // setting text pts, dts to relative time
            // using this._initPTS and this._initDTS to calculate relative time
      
            sample.pts = normalizePts(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale;
          }
      
          track.samples.sort(function (a, b) {
            return a.pts - b.pts;
          });
          var samples = track.samples;
          track.samples = [];
          return {
            samples: samples
          };
        };
      
        return MP4Remuxer;
      }();
      
      
      function normalizePts(value, reference) {
        var offset;
      
        if (reference === null) {
          return value;
        }
      
        if (reference < value) {
          // - 2^33
          offset = -8589934592;
        } else {
          // + 2^33
          offset = 8589934592;
        }
        /* PTS is 33bit (from 0 to 2^33 -1)
          if diff between value and reference is bigger than half of the amplitude (2^32) then it means that
          PTS looping occured. fill the gap */
      
      
        while (Math.abs(value - reference) > 4294967296) {
          value += offset;
        }
      
        return value;
      }
      
      function findKeyframeIndex(samples) {
        for (var i = 0; i < samples.length; i++) {
          if (samples[i].key) {
            return i;
          }
        }
      
        return -1;
      }
      
      var Mp4Sample = function Mp4Sample(isKeyframe, duration, size, cts) {
        this.size = void 0;
        this.duration = void 0;
        this.cts = void 0;
        this.flags = void 0;
        this.duration = duration;
        this.size = size;
        this.cts = cts;
        this.flags = new Mp4SampleFlags(isKeyframe);
      };
      
      var Mp4SampleFlags = function Mp4SampleFlags(isKeyframe) {
        this.isLeading = 0;
        this.isDependedOn = 0;
        this.hasRedundancy = 0;
        this.degradPrio = 0;
        this.dependsOn = 1;
        this.isNonSync = 1;
        this.dependsOn = isKeyframe ? 2 : 1;
        this.isNonSync = isKeyframe ? 0 : 1;
      };
      
      /***/ }),
      
      /***/ "./src/remux/passthrough-remuxer.ts":
      /*!******************************************!*\
        !*** ./src/remux/passthrough-remuxer.ts ***!
        \******************************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
      /* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
      /* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts");
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      
      
      
      
      
      
      var PassThroughRemuxer = /*#__PURE__*/function () {
        function PassThroughRemuxer() {
          this.emitInitSegment = false;
          this.audioCodec = void 0;
          this.videoCodec = void 0;
          this.initData = void 0;
          this.initPTS = void 0;
          this.initTracks = void 0;
          this.lastEndDTS = null;
        }
      
        var _proto = PassThroughRemuxer.prototype;
      
        _proto.destroy = function destroy() {};
      
        _proto.resetTimeStamp = function resetTimeStamp(defaultInitPTS) {
          this.initPTS = defaultInitPTS;
          this.lastEndDTS = null;
        };
      
        _proto.resetNextTimestamp = function resetNextTimestamp() {
          this.lastEndDTS = null;
        };
      
        _proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec) {
          this.audioCodec = audioCodec;
          this.videoCodec = videoCodec;
          this.generateInitSegment(initSegment);
          this.emitInitSegment = true;
        };
      
        _proto.generateInitSegment = function generateInitSegment(initSegment) {
          var audioCodec = this.audioCodec,
              videoCodec = this.videoCodec;
      
          if (!initSegment || !initSegment.byteLength) {
            this.initTracks = undefined;
            this.initData = undefined;
            return;
          }
      
          var initData = this.initData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__["parseInitSegment"])(initSegment); // Get codec from initSegment or fallback to default
      
          if (!audioCodec) {
            audioCodec = getParsedTrackCodec(initData.audio, _loader_fragment__WEBPACK_IMPORTED_MODULE_2__["ElementaryStreamTypes"].AUDIO);
          }
      
          if (!videoCodec) {
            videoCodec = getParsedTrackCodec(initData.video, _loader_fragment__WEBPACK_IMPORTED_MODULE_2__["ElementaryStreamTypes"].VIDEO);
          }
      
          var tracks = {};
      
          if (initData.audio && initData.video) {
            tracks.audiovideo = {
              container: 'video/mp4',
              codec: audioCodec + ',' + videoCodec,
              initSegment: initSegment,
              id: 'main'
            };
          } else if (initData.audio) {
            tracks.audio = {
              container: 'audio/mp4',
              codec: audioCodec,
              initSegment: initSegment,
              id: 'audio'
            };
          } else if (initData.video) {
            tracks.video = {
              container: 'video/mp4',
              codec: videoCodec,
              initSegment: initSegment,
              id: 'main'
            };
          } else {
            _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes.');
          }
      
          this.initTracks = tracks;
        };
      
        _proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset) {
          var initPTS = this.initPTS,
              lastEndDTS = this.lastEndDTS;
          var result = {
            audio: undefined,
            video: undefined,
            text: textTrack,
            id3: id3Track,
            initSegment: undefined
          }; // If we haven't yet set a lastEndDTS, or it was reset, set it to the provided timeOffset. We want to use the
          // lastEndDTS over timeOffset whenever possible; during progressive playback, the media source will not update
          // the media duration (which is what timeOffset is provided as) before we need to process the next chunk.
      
          if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(lastEndDTS)) {
            lastEndDTS = this.lastEndDTS = timeOffset || 0;
          } // The binary segment data is added to the videoTrack in the mp4demuxer. We don't check to see if the data is only
          // audio or video (or both); adding it to video was an arbitrary choice.
      
      
          var data = videoTrack.samples;
      
          if (!data || !data.length) {
            return result;
          }
      
          var initSegment = {
            initPTS: undefined,
            timescale: 1
          };
          var initData = this.initData;
      
          if (!initData || !initData.length) {
            this.generateInitSegment(data);
            initData = this.initData;
          }
      
          if (!initData || !initData.length) {
            // We can't remux if the initSegment could not be generated
            _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('[passthrough-remuxer.ts]: Failed to generate initSegment.');
            return result;
          }
      
          if (this.emitInitSegment) {
            initSegment.tracks = this.initTracks;
            this.emitInitSegment = false;
          }
      
          if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(initPTS)) {
            this.initPTS = initSegment.initPTS = initPTS = computeInitPTS(initData, data, lastEndDTS);
          }
      
          var duration = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__["getDuration"])(data, initData);
          var startDTS = lastEndDTS;
          var endDTS = duration + startDTS;
          Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__["offsetStartDTS"])(initData, data, initPTS);
      
          if (duration > 0) {
            this.lastEndDTS = endDTS;
          } else {
            _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('Duration parsed from mp4 should be greater than zero');
            this.resetNextTimestamp();
          }
      
          var hasAudio = !!initData.audio;
          var hasVideo = !!initData.video;
          var type = '';
      
          if (hasAudio) {
            type += 'audio';
          }
      
          if (hasVideo) {
            type += 'video';
          }
      
          var track = {
            data1: data,
            startPTS: startDTS,
            startDTS: startDTS,
            endPTS: endDTS,
            endDTS: endDTS,
            type: type,
            hasAudio: hasAudio,
            hasVideo: hasVideo,
            nb: 1,
            dropped: 0
          };
          result.audio = track.type === 'audio' ? track : undefined;
          result.video = track.type !== 'audio' ? track : undefined;
          result.text = textTrack;
          result.id3 = id3Track;
          result.initSegment = initSegment;
          return result;
        };
      
        return PassThroughRemuxer;
      }();
      
      var computeInitPTS = function computeInitPTS(initData, data, timeOffset) {
        return Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__["getStartDTS"])(initData, data) - timeOffset;
      };
      
      function getParsedTrackCodec(track, type) {
        var parsedCodec = track === null || track === void 0 ? void 0 : track.codec;
      
        if (parsedCodec && parsedCodec.length > 4) {
          return parsedCodec;
        } // Since mp4-tools cannot parse full codec string (see 'TODO: Parse codec details'... in mp4-tools)
        // Provide defaults based on codec type
        // This allows for some playback of some fmp4 playlists without CODECS defined in manifest
      
      
        if (parsedCodec === 'hvc1') {
          return 'hvc1.1.c.L120.90';
        }
      
        if (parsedCodec === 'av01') {
          return 'av01.0.04M.08';
        }
      
        if (parsedCodec === 'avc1' || type === _loader_fragment__WEBPACK_IMPORTED_MODULE_2__["ElementaryStreamTypes"].VIDEO) {
          return 'avc1.42e01e';
        }
      
        return 'mp4a.40.5';
      }
      
      /* harmony default export */ __webpack_exports__["default"] = (PassThroughRemuxer);
      
      /***/ }),
      
      /***/ "./src/task-loop.ts":
      /*!**************************!*\
        !*** ./src/task-loop.ts ***!
        \**************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TaskLoop; });
      /**
       * Sub-class specialization of EventHandler base class.
       *
       * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,
       * scheduled asynchroneously, avoiding recursive calls in the same tick.
       *
       * The task itself is implemented in `doTick`. It can be requested and called for single execution
       * using the `tick` method.
       *
       * It will be assured that the task execution method (`tick`) only gets called once per main loop "tick",
       * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.
       *
       * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,
       * and cancelled with `clearNextTick`.
       *
       * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).
       *
       * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.
       *
       * Further explanations:
       *
       * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously
       * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.
       *
       * When the task execution (`tick` method) is called in re-entrant way this is detected and
       * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further
       * task processing on the next main loop iteration (also known as "next tick" in the Node/JS runtime lingo).
       */
      var TaskLoop = /*#__PURE__*/function () {
        function TaskLoop() {
          this._boundTick = void 0;
          this._tickTimer = null;
          this._tickInterval = null;
          this._tickCallCount = 0;
          this._boundTick = this.tick.bind(this);
        }
      
        var _proto = TaskLoop.prototype;
      
        _proto.destroy = function destroy() {
          this.onHandlerDestroying();
          this.onHandlerDestroyed();
        };
      
        _proto.onHandlerDestroying = function onHandlerDestroying() {
          // clear all timers before unregistering from event bus
          this.clearNextTick();
          this.clearInterval();
        };
      
        _proto.onHandlerDestroyed = function onHandlerDestroyed() {}
        /**
         * @returns {boolean}
         */
        ;
      
        _proto.hasInterval = function hasInterval() {
          return !!this._tickInterval;
        }
        /**
         * @returns {boolean}
         */
        ;
      
        _proto.hasNextTick = function hasNextTick() {
          return !!this._tickTimer;
        }
        /**
         * @param {number} millis Interval time (ms)
         * @returns {boolean} True when interval has been scheduled, false when already scheduled (no effect)
         */
        ;
      
        _proto.setInterval = function setInterval(millis) {
          if (!this._tickInterval) {
            this._tickInterval = self.setInterval(this._boundTick, millis);
            return true;
          }
      
          return false;
        }
        /**
         * @returns {boolean} True when interval was cleared, false when none was set (no effect)
         */
        ;
      
        _proto.clearInterval = function clearInterval() {
          if (this._tickInterval) {
            self.clearInterval(this._tickInterval);
            this._tickInterval = null;
            return true;
          }
      
          return false;
        }
        /**
         * @returns {boolean} True when timeout was cleared, false when none was set (no effect)
         */
        ;
      
        _proto.clearNextTick = function clearNextTick() {
          if (this._tickTimer) {
            self.clearTimeout(this._tickTimer);
            this._tickTimer = null;
            return true;
          }
      
          return false;
        }
        /**
         * Will call the subclass doTick implementation in this main loop tick
         * or in the next one (via setTimeout(,0)) in case it has already been called
         * in this tick (in case this is a re-entrant call).
         */
        ;
      
        _proto.tick = function tick() {
          this._tickCallCount++;
      
          if (this._tickCallCount === 1) {
            this.doTick(); // re-entrant call to tick from previous doTick call stack
            // -> schedule a call on the next main loop iteration to process this task processing request
      
            if (this._tickCallCount > 1) {
              // make sure only one timer exists at any time at max
              this.tickImmediate();
            }
      
            this._tickCallCount = 0;
          }
        };
      
        _proto.tickImmediate = function tickImmediate() {
          this.clearNextTick();
          this._tickTimer = self.setTimeout(this._boundTick, 0);
        }
        /**
         * For subclass to implement task logic
         * @abstract
         */
        ;
      
        _proto.doTick = function doTick() {};
      
        return TaskLoop;
      }();
      
      
      
      /***/ }),
      
      /***/ "./src/types/cmcd.ts":
      /*!***************************!*\
        !*** ./src/types/cmcd.ts ***!
        \***************************/
      /*! exports provided: CMCDVersion, CMCDObjectType, CMCDStreamingFormat, CMCDStreamType */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CMCDVersion", function() { return CMCDVersion; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CMCDObjectType", function() { return CMCDObjectType; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CMCDStreamingFormat", function() { return CMCDStreamingFormat; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CMCDStreamType", function() { return CMCDStreamType; });
      /**
       * CMCD spec version
       */
      var CMCDVersion = 1;
      /**
       * CMCD Object Type
       */
      
      var CMCDObjectType;
      /**
       * CMCD Streaming Format
       */
      
      (function (CMCDObjectType) {
        CMCDObjectType["MANIFEST"] = "m";
        CMCDObjectType["AUDIO"] = "a";
        CMCDObjectType["VIDEO"] = "v";
        CMCDObjectType["MUXED"] = "av";
        CMCDObjectType["INIT"] = "i";
        CMCDObjectType["CAPTION"] = "c";
        CMCDObjectType["TIMED_TEXT"] = "tt";
        CMCDObjectType["KEY"] = "k";
        CMCDObjectType["OTHER"] = "o";
      })(CMCDObjectType || (CMCDObjectType = {}));
      
      var CMCDStreamingFormat;
      /**
       * CMCD Streaming Type
       */
      
      (function (CMCDStreamingFormat) {
        CMCDStreamingFormat["DASH"] = "d";
        CMCDStreamingFormat["HLS"] = "h";
        CMCDStreamingFormat["SMOOTH"] = "s";
        CMCDStreamingFormat["OTHER"] = "o";
      })(CMCDStreamingFormat || (CMCDStreamingFormat = {}));
      
      var CMCDStreamType;
      /**
       * CMCD Headers
       */
      
      (function (CMCDStreamType) {
        CMCDStreamType["VOD"] = "v";
        CMCDStreamType["LIVE"] = "l";
      })(CMCDStreamType || (CMCDStreamType = {}));
      
      /***/ }),
      
      /***/ "./src/types/level.ts":
      /*!****************************!*\
        !*** ./src/types/level.ts ***!
        \****************************/
      /*! exports provided: HlsSkip, getSkipValue, HlsUrlParameters, Level */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HlsSkip", function() { return HlsSkip; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getSkipValue", function() { return getSkipValue; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HlsUrlParameters", function() { return HlsUrlParameters; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Level", function() { return Level; });
      function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
      
      function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
      
      var HlsSkip;
      
      (function (HlsSkip) {
        HlsSkip["No"] = "";
        HlsSkip["Yes"] = "YES";
        HlsSkip["v2"] = "v2";
      })(HlsSkip || (HlsSkip = {}));
      
      function getSkipValue(details, msn) {
        var canSkipUntil = details.canSkipUntil,
            canSkipDateRanges = details.canSkipDateRanges,
            endSN = details.endSN;
        var snChangeGoal = msn !== undefined ? msn - endSN : 0;
      
        if (canSkipUntil && snChangeGoal < canSkipUntil) {
          if (canSkipDateRanges) {
            return HlsSkip.v2;
          }
      
          return HlsSkip.Yes;
        }
      
        return HlsSkip.No;
      }
      var HlsUrlParameters = /*#__PURE__*/function () {
        function HlsUrlParameters(msn, part, skip) {
          this.msn = void 0;
          this.part = void 0;
          this.skip = void 0;
          this.msn = msn;
          this.part = part;
          this.skip = skip;
        }
      
        var _proto = HlsUrlParameters.prototype;
      
        _proto.addDirectives = function addDirectives(uri) {
          var url = new self.URL(uri);
      
          if (this.msn !== undefined) {
            url.searchParams.set('_HLS_msn', this.msn.toString());
          }
      
          if (this.part !== undefined) {
            url.searchParams.set('_HLS_part', this.part.toString());
          }
      
          if (this.skip) {
            url.searchParams.set('_HLS_skip', this.skip);
          }
      
          return url.toString();
        };
      
        return HlsUrlParameters;
      }();
      var Level = /*#__PURE__*/function () {
        function Level(data) {
          this.attrs = void 0;
          this.audioCodec = void 0;
          this.bitrate = void 0;
          this.codecSet = void 0;
          this.height = void 0;
          this.id = void 0;
          this.name = void 0;
          this.videoCodec = void 0;
          this.width = void 0;
          this.unknownCodecs = void 0;
          this.audioGroupIds = void 0;
          this.details = void 0;
          this.fragmentError = 0;
          this.loadError = 0;
          this.loaded = void 0;
          this.realBitrate = 0;
          this.textGroupIds = void 0;
          this.url = void 0;
          this._urlId = 0;
          this.url = [data.url];
          this.attrs = data.attrs;
          this.bitrate = data.bitrate;
      
          if (data.details) {
            this.details = data.details;
          }
      
          this.id = data.id || 0;
          this.name = data.name;
          this.width = data.width || 0;
          this.height = data.height || 0;
          this.audioCodec = data.audioCodec;
          this.videoCodec = data.videoCodec;
          this.unknownCodecs = data.unknownCodecs;
          this.codecSet = [data.videoCodec, data.audioCodec].filter(function (c) {
            return c;
          }).join(',').replace(/\.[^.,]+/g, '');
        }
      
        _createClass(Level, [{
          key: "maxBitrate",
          get: function get() {
            return Math.max(this.realBitrate, this.bitrate);
          }
        }, {
          key: "uri",
          get: function get() {
            return this.url[this._urlId] || '';
          }
        }, {
          key: "urlId",
          get: function get() {
            return this._urlId;
          },
          set: function set(value) {
            var newValue = value % this.url.length;
      
            if (this._urlId !== newValue) {
              this.details = undefined;
              this._urlId = newValue;
            }
          }
        }]);
      
        return Level;
      }();
      
      /***/ }),
      
      /***/ "./src/types/loader.ts":
      /*!*****************************!*\
        !*** ./src/types/loader.ts ***!
        \*****************************/
      /*! exports provided: PlaylistContextType, PlaylistLevelType */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaylistContextType", function() { return PlaylistContextType; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaylistLevelType", function() { return PlaylistLevelType; });
      var PlaylistContextType;
      
      (function (PlaylistContextType) {
        PlaylistContextType["MANIFEST"] = "manifest";
        PlaylistContextType["LEVEL"] = "level";
        PlaylistContextType["AUDIO_TRACK"] = "audioTrack";
        PlaylistContextType["SUBTITLE_TRACK"] = "subtitleTrack";
      })(PlaylistContextType || (PlaylistContextType = {}));
      
      var PlaylistLevelType;
      
      (function (PlaylistLevelType) {
        PlaylistLevelType["MAIN"] = "main";
        PlaylistLevelType["AUDIO"] = "audio";
        PlaylistLevelType["SUBTITLE"] = "subtitle";
      })(PlaylistLevelType || (PlaylistLevelType = {}));
      
      /***/ }),
      
      /***/ "./src/types/transmuxer.ts":
      /*!*********************************!*\
        !*** ./src/types/transmuxer.ts ***!
        \*********************************/
      /*! exports provided: ChunkMetadata */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ChunkMetadata", function() { return ChunkMetadata; });
      var ChunkMetadata = function ChunkMetadata(level, sn, id, size, part, partial) {
        if (size === void 0) {
          size = 0;
        }
      
        if (part === void 0) {
          part = -1;
        }
      
        if (partial === void 0) {
          partial = false;
        }
      
        this.level = void 0;
        this.sn = void 0;
        this.part = void 0;
        this.id = void 0;
        this.size = void 0;
        this.partial = void 0;
        this.transmuxing = getNewPerformanceTiming();
        this.buffering = {
          audio: getNewPerformanceTiming(),
          video: getNewPerformanceTiming(),
          audiovideo: getNewPerformanceTiming()
        };
        this.level = level;
        this.sn = sn;
        this.id = id;
        this.size = size;
        this.part = part;
        this.partial = partial;
      };
      
      function getNewPerformanceTiming() {
        return {
          start: 0,
          executeStart: 0,
          executeEnd: 0,
          end: 0
        };
      }
      
      /***/ }),
      
      /***/ "./src/utils/attr-list.ts":
      /*!********************************!*\
        !*** ./src/utils/attr-list.ts ***!
        \********************************/
      /*! exports provided: AttrList */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AttrList", function() { return AttrList; });
      var DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/; // eslint-disable-line no-useless-escape
      
      var ATTR_LIST_REGEX = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape
      // adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js
      
      var AttrList = /*#__PURE__*/function () {
        function AttrList(attrs) {
          if (typeof attrs === 'string') {
            attrs = AttrList.parseAttrList(attrs);
          }
      
          for (var attr in attrs) {
            if (attrs.hasOwnProperty(attr)) {
              this[attr] = attrs[attr];
            }
          }
        }
      
        var _proto = AttrList.prototype;
      
        _proto.decimalInteger = function decimalInteger(attrName) {
          var intValue = parseInt(this[attrName], 10);
      
          if (intValue > Number.MAX_SAFE_INTEGER) {
            return Infinity;
          }
      
          return intValue;
        };
      
        _proto.hexadecimalInteger = function hexadecimalInteger(attrName) {
          if (this[attrName]) {
            var stringValue = (this[attrName] || '0x').slice(2);
            stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;
            var value = new Uint8Array(stringValue.length / 2);
      
            for (var i = 0; i < stringValue.length / 2; i++) {
              value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);
            }
      
            return value;
          } else {
            return null;
          }
        };
      
        _proto.hexadecimalIntegerAsNumber = function hexadecimalIntegerAsNumber(attrName) {
          var intValue = parseInt(this[attrName], 16);
      
          if (intValue > Number.MAX_SAFE_INTEGER) {
            return Infinity;
          }
      
          return intValue;
        };
      
        _proto.decimalFloatingPoint = function decimalFloatingPoint(attrName) {
          return parseFloat(this[attrName]);
        };
      
        _proto.optionalFloat = function optionalFloat(attrName, defaultValue) {
          var value = this[attrName];
          return value ? parseFloat(value) : defaultValue;
        };
      
        _proto.enumeratedString = function enumeratedString(attrName) {
          return this[attrName];
        };
      
        _proto.bool = function bool(attrName) {
          return this[attrName] === 'YES';
        };
      
        _proto.decimalResolution = function decimalResolution(attrName) {
          var res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);
      
          if (res === null) {
            return undefined;
          }
      
          return {
            width: parseInt(res[1], 10),
            height: parseInt(res[2], 10)
          };
        };
      
        AttrList.parseAttrList = function parseAttrList(input) {
          var match;
          var attrs = {};
          var quote = '"';
          ATTR_LIST_REGEX.lastIndex = 0;
      
          while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
            var value = match[2];
      
            if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) {
              value = value.slice(1, -1);
            }
      
            attrs[match[1]] = value;
          }
      
          return attrs;
        };
      
        return AttrList;
      }();
      
      /***/ }),
      
      /***/ "./src/utils/binary-search.ts":
      /*!************************************!*\
        !*** ./src/utils/binary-search.ts ***!
        \************************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      var BinarySearch = {
        /**
         * Searches for an item in an array which matches a certain condition.
         * This requires the condition to only match one item in the array,
         * and for the array to be ordered.
         *
         * @param {Array<T>} list The array to search.
         * @param {BinarySearchComparison<T>} comparisonFn
         *      Called and provided a candidate item as the first argument.
         *      Should return:
         *          > -1 if the item should be located at a lower index than the provided item.
         *          > 1 if the item should be located at a higher index than the provided item.
         *          > 0 if the item is the item you're looking for.
         *
         * @return {T | null} The object if it is found or null otherwise.
         */
        search: function search(list, comparisonFn) {
          var minIndex = 0;
          var maxIndex = list.length - 1;
          var currentIndex = null;
          var currentElement = null;
      
          while (minIndex <= maxIndex) {
            currentIndex = (minIndex + maxIndex) / 2 | 0;
            currentElement = list[currentIndex];
            var comparisonResult = comparisonFn(currentElement);
      
            if (comparisonResult > 0) {
              minIndex = currentIndex + 1;
            } else if (comparisonResult < 0) {
              maxIndex = currentIndex - 1;
            } else {
              return currentElement;
            }
          }
      
          return null;
        }
      };
      /* harmony default export */ __webpack_exports__["default"] = (BinarySearch);
      
      /***/ }),
      
      /***/ "./src/utils/buffer-helper.ts":
      /*!************************************!*\
        !*** ./src/utils/buffer-helper.ts ***!
        \************************************/
      /*! exports provided: BufferHelper */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BufferHelper", function() { return BufferHelper; });
      /* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./logger */ "./src/utils/logger.ts");
      /**
       * @module BufferHelper
       *
       * Providing methods dealing with buffer length retrieval for example.
       *
       * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.
       *
       * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered
       */
      
      var noopBuffered = {
        length: 0,
        start: function start() {
          return 0;
        },
        end: function end() {
          return 0;
        }
      };
      var BufferHelper = /*#__PURE__*/function () {
        function BufferHelper() {}
      
        /**
         * Return true if `media`'s buffered include `position`
         * @param {Bufferable} media
         * @param {number} position
         * @returns {boolean}
         */
        BufferHelper.isBuffered = function isBuffered(media, position) {
          try {
            if (media) {
              var buffered = BufferHelper.getBuffered(media);
      
              for (var i = 0; i < buffered.length; i++) {
                if (position >= buffered.start(i) && position <= buffered.end(i)) {
                  return true;
                }
              }
            }
          } catch (error) {// this is to catch
            // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
            // This SourceBuffer has been removed from the parent media source
          }
      
          return false;
        };
      
        BufferHelper.bufferInfo = function bufferInfo(media, pos, maxHoleDuration) {
          try {
            if (media) {
              var vbuffered = BufferHelper.getBuffered(media);
              var buffered = [];
              var i;
      
              for (i = 0; i < vbuffered.length; i++) {
                buffered.push({
                  start: vbuffered.start(i),
                  end: vbuffered.end(i)
                });
              }
      
              return this.bufferedInfo(buffered, pos, maxHoleDuration);
            }
          } catch (error) {// this is to catch
            // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
            // This SourceBuffer has been removed from the parent media source
          }
      
          return {
            len: 0,
            start: pos,
            end: pos,
            nextStart: undefined
          };
        };
      
        BufferHelper.bufferedInfo = function bufferedInfo(buffered, pos, maxHoleDuration) {
          pos = Math.max(0, pos); // sort on buffer.start/smaller end (IE does not always return sorted buffered range)
      
          buffered.sort(function (a, b) {
            var diff = a.start - b.start;
      
            if (diff) {
              return diff;
            } else {
              return b.end - a.end;
            }
          });
          var buffered2 = [];
      
          if (maxHoleDuration) {
            // there might be some small holes between buffer time range
            // consider that holes smaller than maxHoleDuration are irrelevant and build another
            // buffer time range representations that discards those holes
            for (var i = 0; i < buffered.length; i++) {
              var buf2len = buffered2.length;
      
              if (buf2len) {
                var buf2end = buffered2[buf2len - 1].end; // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)
      
                if (buffered[i].start - buf2end < maxHoleDuration) {
                  // merge overlapping time ranges
                  // update lastRange.end only if smaller than item.end
                  // e.g.  [ 1, 15] with  [ 2,8] => [ 1,15] (no need to modify lastRange.end)
                  // whereas [ 1, 8] with  [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])
                  if (buffered[i].end > buf2end) {
                    buffered2[buf2len - 1].end = buffered[i].end;
                  }
                } else {
                  // big hole
                  buffered2.push(buffered[i]);
                }
              } else {
                // first value
                buffered2.push(buffered[i]);
              }
            }
          } else {
            buffered2 = buffered;
          }
      
          var bufferLen = 0; // bufferStartNext can possibly be undefined based on the conditional logic below
      
          var bufferStartNext; // bufferStart and bufferEnd are buffer boundaries around current video position
      
          var bufferStart = pos;
          var bufferEnd = pos;
      
          for (var _i = 0; _i < buffered2.length; _i++) {
            var start = buffered2[_i].start;
            var end = buffered2[_i].end; // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));
      
            if (pos + maxHoleDuration >= start && pos < end) {
              // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length
              bufferStart = start;
              bufferEnd = end;
              bufferLen = bufferEnd - pos;
            } else if (pos + maxHoleDuration < start) {
              bufferStartNext = start;
              break;
            }
          }
      
          return {
            len: bufferLen,
            start: bufferStart || 0,
            end: bufferEnd || 0,
            nextStart: bufferStartNext
          };
        }
        /**
         * Safe method to get buffered property.
         * SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource
         */
        ;
      
        BufferHelper.getBuffered = function getBuffered(media) {
          try {
            return media.buffered;
          } catch (e) {
            _logger__WEBPACK_IMPORTED_MODULE_0__["logger"].log('failed to get media.buffered', e);
            return noopBuffered;
          }
        };
      
        return BufferHelper;
      }();
      
      /***/ }),
      
      /***/ "./src/utils/cea-608-parser.ts":
      /*!*************************************!*\
        !*** ./src/utils/cea-608-parser.ts ***!
        \*************************************/
      /*! exports provided: Row, CaptionScreen, default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Row", function() { return Row; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CaptionScreen", function() { return CaptionScreen; });
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      
      /**
       *
       * This code was ported from the dash.js project at:
       *   https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js
       *   https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2
       *
       * The original copyright appears below:
       *
       * The copyright in this software is being made available under the BSD License,
       * included below. This software may be subject to other third party and contributor
       * rights, including patent rights, and no such rights are granted under this license.
       *
       * Copyright (c) 2015-2016, DASH Industry Forum.
       * All rights reserved.
       *
       * Redistribution and use in source and binary forms, with or without modification,
       * are permitted provided that the following conditions are met:
       *  1. Redistributions of source code must retain the above copyright notice, this
       *  list of conditions and the following disclaimer.
       *  * Redistributions in binary form must reproduce the above copyright notice,
       *  this list of conditions and the following disclaimer in the documentation and/or
       *  other materials provided with the distribution.
       *  2. Neither the name of Dash Industry Forum nor the names of its
       *  contributors may be used to endorse or promote products derived from this software
       *  without specific prior written permission.
       *
       *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
       *  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
       *  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
       *  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
       *  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
       *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
       *  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
       *  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
       *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
       *  POSSIBILITY OF SUCH DAMAGE.
       */
      
      /**
       *  Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes
       */
      
      var specialCea608CharsCodes = {
        0x2a: 0xe1,
        // lowercase a, acute accent
        0x5c: 0xe9,
        // lowercase e, acute accent
        0x5e: 0xed,
        // lowercase i, acute accent
        0x5f: 0xf3,
        // lowercase o, acute accent
        0x60: 0xfa,
        // lowercase u, acute accent
        0x7b: 0xe7,
        // lowercase c with cedilla
        0x7c: 0xf7,
        // division symbol
        0x7d: 0xd1,
        // uppercase N tilde
        0x7e: 0xf1,
        // lowercase n tilde
        0x7f: 0x2588,
        // Full block
        // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
        // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F
        // THIS MEANS THAT \x50 MUST BE ADDED TO THE VALUES
        0x80: 0xae,
        // Registered symbol (R)
        0x81: 0xb0,
        // degree sign
        0x82: 0xbd,
        // 1/2 symbol
        0x83: 0xbf,
        // Inverted (open) question mark
        0x84: 0x2122,
        // Trademark symbol (TM)
        0x85: 0xa2,
        // Cents symbol
        0x86: 0xa3,
        // Pounds sterling
        0x87: 0x266a,
        // Music 8'th note
        0x88: 0xe0,
        // lowercase a, grave accent
        0x89: 0x20,
        // transparent space (regular)
        0x8a: 0xe8,
        // lowercase e, grave accent
        0x8b: 0xe2,
        // lowercase a, circumflex accent
        0x8c: 0xea,
        // lowercase e, circumflex accent
        0x8d: 0xee,
        // lowercase i, circumflex accent
        0x8e: 0xf4,
        // lowercase o, circumflex accent
        0x8f: 0xfb,
        // lowercase u, circumflex accent
        // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
        // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F
        0x90: 0xc1,
        // capital letter A with acute
        0x91: 0xc9,
        // capital letter E with acute
        0x92: 0xd3,
        // capital letter O with acute
        0x93: 0xda,
        // capital letter U with acute
        0x94: 0xdc,
        // capital letter U with diaresis
        0x95: 0xfc,
        // lowercase letter U with diaeresis
        0x96: 0x2018,
        // opening single quote
        0x97: 0xa1,
        // inverted exclamation mark
        0x98: 0x2a,
        // asterisk
        0x99: 0x2019,
        // closing single quote
        0x9a: 0x2501,
        // box drawings heavy horizontal
        0x9b: 0xa9,
        // copyright sign
        0x9c: 0x2120,
        // Service mark
        0x9d: 0x2022,
        // (round) bullet
        0x9e: 0x201c,
        // Left double quotation mark
        0x9f: 0x201d,
        // Right double quotation mark
        0xa0: 0xc0,
        // uppercase A, grave accent
        0xa1: 0xc2,
        // uppercase A, circumflex
        0xa2: 0xc7,
        // uppercase C with cedilla
        0xa3: 0xc8,
        // uppercase E, grave accent
        0xa4: 0xca,
        // uppercase E, circumflex
        0xa5: 0xcb,
        // capital letter E with diaresis
        0xa6: 0xeb,
        // lowercase letter e with diaresis
        0xa7: 0xce,
        // uppercase I, circumflex
        0xa8: 0xcf,
        // uppercase I, with diaresis
        0xa9: 0xef,
        // lowercase i, with diaresis
        0xaa: 0xd4,
        // uppercase O, circumflex
        0xab: 0xd9,
        // uppercase U, grave accent
        0xac: 0xf9,
        // lowercase u, grave accent
        0xad: 0xdb,
        // uppercase U, circumflex
        0xae: 0xab,
        // left-pointing double angle quotation mark
        0xaf: 0xbb,
        // right-pointing double angle quotation mark
        // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
        // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F
        0xb0: 0xc3,
        // Uppercase A, tilde
        0xb1: 0xe3,
        // Lowercase a, tilde
        0xb2: 0xcd,
        // Uppercase I, acute accent
        0xb3: 0xcc,
        // Uppercase I, grave accent
        0xb4: 0xec,
        // Lowercase i, grave accent
        0xb5: 0xd2,
        // Uppercase O, grave accent
        0xb6: 0xf2,
        // Lowercase o, grave accent
        0xb7: 0xd5,
        // Uppercase O, tilde
        0xb8: 0xf5,
        // Lowercase o, tilde
        0xb9: 0x7b,
        // Open curly brace
        0xba: 0x7d,
        // Closing curly brace
        0xbb: 0x5c,
        // Backslash
        0xbc: 0x5e,
        // Caret
        0xbd: 0x5f,
        // Underscore
        0xbe: 0x7c,
        // Pipe (vertical line)
        0xbf: 0x223c,
        // Tilde operator
        0xc0: 0xc4,
        // Uppercase A, umlaut
        0xc1: 0xe4,
        // Lowercase A, umlaut
        0xc2: 0xd6,
        // Uppercase O, umlaut
        0xc3: 0xf6,
        // Lowercase o, umlaut
        0xc4: 0xdf,
        // Esszett (sharp S)
        0xc5: 0xa5,
        // Yen symbol
        0xc6: 0xa4,
        // Generic currency sign
        0xc7: 0x2503,
        // Box drawings heavy vertical
        0xc8: 0xc5,
        // Uppercase A, ring
        0xc9: 0xe5,
        // Lowercase A, ring
        0xca: 0xd8,
        // Uppercase O, stroke
        0xcb: 0xf8,
        // Lowercase o, strok
        0xcc: 0x250f,
        // Box drawings heavy down and right
        0xcd: 0x2513,
        // Box drawings heavy down and left
        0xce: 0x2517,
        // Box drawings heavy up and right
        0xcf: 0x251b // Box drawings heavy up and left
      
      };
      /**
       * Utils
       */
      
      var getCharForByte = function getCharForByte(_byte) {
        var charCode = _byte;
      
        if (specialCea608CharsCodes.hasOwnProperty(_byte)) {
          charCode = specialCea608CharsCodes[_byte];
        }
      
        return String.fromCharCode(charCode);
      };
      
      var NR_ROWS = 15;
      var NR_COLS = 100; // Tables to look up row from PAC data
      
      var rowsLowCh1 = {
        0x11: 1,
        0x12: 3,
        0x15: 5,
        0x16: 7,
        0x17: 9,
        0x10: 11,
        0x13: 12,
        0x14: 14
      };
      var rowsHighCh1 = {
        0x11: 2,
        0x12: 4,
        0x15: 6,
        0x16: 8,
        0x17: 10,
        0x13: 13,
        0x14: 15
      };
      var rowsLowCh2 = {
        0x19: 1,
        0x1a: 3,
        0x1d: 5,
        0x1e: 7,
        0x1f: 9,
        0x18: 11,
        0x1b: 12,
        0x1c: 14
      };
      var rowsHighCh2 = {
        0x19: 2,
        0x1a: 4,
        0x1d: 6,
        0x1e: 8,
        0x1f: 10,
        0x1b: 13,
        0x1c: 15
      };
      var backgroundColors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'black', 'transparent'];
      var VerboseLevel;
      
      (function (VerboseLevel) {
        VerboseLevel[VerboseLevel["ERROR"] = 0] = "ERROR";
        VerboseLevel[VerboseLevel["TEXT"] = 1] = "TEXT";
        VerboseLevel[VerboseLevel["WARNING"] = 2] = "WARNING";
        VerboseLevel[VerboseLevel["INFO"] = 2] = "INFO";
        VerboseLevel[VerboseLevel["DEBUG"] = 3] = "DEBUG";
        VerboseLevel[VerboseLevel["DATA"] = 3] = "DATA";
      })(VerboseLevel || (VerboseLevel = {}));
      
      var CaptionsLogger = /*#__PURE__*/function () {
        function CaptionsLogger() {
          this.time = null;
          this.verboseLevel = VerboseLevel.ERROR;
        }
      
        var _proto = CaptionsLogger.prototype;
      
        _proto.log = function log(severity, msg) {
          if (this.verboseLevel >= severity) {
            _utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].log(this.time + " [" + severity + "] " + msg);
          }
        };
      
        return CaptionsLogger;
      }();
      
      var numArrayToHexArray = function numArrayToHexArray(numArray) {
        var hexArray = [];
      
        for (var j = 0; j < numArray.length; j++) {
          hexArray.push(numArray[j].toString(16));
        }
      
        return hexArray;
      };
      
      var PenState = /*#__PURE__*/function () {
        function PenState(foreground, underline, italics, background, flash) {
          this.foreground = void 0;
          this.underline = void 0;
          this.italics = void 0;
          this.background = void 0;
          this.flash = void 0;
          this.foreground = foreground || 'white';
          this.underline = underline || false;
          this.italics = italics || false;
          this.background = background || 'black';
          this.flash = flash || false;
        }
      
        var _proto2 = PenState.prototype;
      
        _proto2.reset = function reset() {
          this.foreground = 'white';
          this.underline = false;
          this.italics = false;
          this.background = 'black';
          this.flash = false;
        };
      
        _proto2.setStyles = function setStyles(styles) {
          var attribs = ['foreground', 'underline', 'italics', 'background', 'flash'];
      
          for (var i = 0; i < attribs.length; i++) {
            var style = attribs[i];
      
            if (styles.hasOwnProperty(style)) {
              this[style] = styles[style];
            }
          }
        };
      
        _proto2.isDefault = function isDefault() {
          return this.foreground === 'white' && !this.underline && !this.italics && this.background === 'black' && !this.flash;
        };
      
        _proto2.equals = function equals(other) {
          return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash;
        };
      
        _proto2.copy = function copy(newPenState) {
          this.foreground = newPenState.foreground;
          this.underline = newPenState.underline;
          this.italics = newPenState.italics;
          this.background = newPenState.background;
          this.flash = newPenState.flash;
        };
      
        _proto2.toString = function toString() {
          return 'color=' + this.foreground + ', underline=' + this.underline + ', italics=' + this.italics + ', background=' + this.background + ', flash=' + this.flash;
        };
      
        return PenState;
      }();
      /**
       * Unicode character with styling and background.
       * @constructor
       */
      
      
      var StyledUnicodeChar = /*#__PURE__*/function () {
        function StyledUnicodeChar(uchar, foreground, underline, italics, background, flash) {
          this.uchar = void 0;
          this.penState = void 0;
          this.uchar = uchar || ' '; // unicode character
      
          this.penState = new PenState(foreground, underline, italics, background, flash);
        }
      
        var _proto3 = StyledUnicodeChar.prototype;
      
        _proto3.reset = function reset() {
          this.uchar = ' ';
          this.penState.reset();
        };
      
        _proto3.setChar = function setChar(uchar, newPenState) {
          this.uchar = uchar;
          this.penState.copy(newPenState);
        };
      
        _proto3.setPenState = function setPenState(newPenState) {
          this.penState.copy(newPenState);
        };
      
        _proto3.equals = function equals(other) {
          return this.uchar === other.uchar && this.penState.equals(other.penState);
        };
      
        _proto3.copy = function copy(newChar) {
          this.uchar = newChar.uchar;
          this.penState.copy(newChar.penState);
        };
      
        _proto3.isEmpty = function isEmpty() {
          return this.uchar === ' ' && this.penState.isDefault();
        };
      
        return StyledUnicodeChar;
      }();
      /**
       * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.
       * @constructor
       */
      
      
      var Row = /*#__PURE__*/function () {
        function Row(logger) {
          this.chars = void 0;
          this.pos = void 0;
          this.currPenState = void 0;
          this.cueStartTime = void 0;
          this.logger = void 0;
          this.chars = [];
      
          for (var i = 0; i < NR_COLS; i++) {
            this.chars.push(new StyledUnicodeChar());
          }
      
          this.logger = logger;
          this.pos = 0;
          this.currPenState = new PenState();
        }
      
        var _proto4 = Row.prototype;
      
        _proto4.equals = function equals(other) {
          var equal = true;
      
          for (var i = 0; i < NR_COLS; i++) {
            if (!this.chars[i].equals(other.chars[i])) {
              equal = false;
              break;
            }
          }
      
          return equal;
        };
      
        _proto4.copy = function copy(other) {
          for (var i = 0; i < NR_COLS; i++) {
            this.chars[i].copy(other.chars[i]);
          }
        };
      
        _proto4.isEmpty = function isEmpty() {
          var empty = true;
      
          for (var i = 0; i < NR_COLS; i++) {
            if (!this.chars[i].isEmpty()) {
              empty = false;
              break;
            }
          }
      
          return empty;
        }
        /**
         *  Set the cursor to a valid column.
         */
        ;
      
        _proto4.setCursor = function setCursor(absPos) {
          if (this.pos !== absPos) {
            this.pos = absPos;
          }
      
          if (this.pos < 0) {
            this.logger.log(VerboseLevel.DEBUG, 'Negative cursor position ' + this.pos);
            this.pos = 0;
          } else if (this.pos > NR_COLS) {
            this.logger.log(VerboseLevel.DEBUG, 'Too large cursor position ' + this.pos);
            this.pos = NR_COLS;
          }
        }
        /**
         * Move the cursor relative to current position.
         */
        ;
      
        _proto4.moveCursor = function moveCursor(relPos) {
          var newPos = this.pos + relPos;
      
          if (relPos > 1) {
            for (var i = this.pos + 1; i < newPos + 1; i++) {
              this.chars[i].setPenState(this.currPenState);
            }
          }
      
          this.setCursor(newPos);
        }
        /**
         * Backspace, move one step back and clear character.
         */
        ;
      
        _proto4.backSpace = function backSpace() {
          this.moveCursor(-1);
          this.chars[this.pos].setChar(' ', this.currPenState);
        };
      
        _proto4.insertChar = function insertChar(_byte2) {
          if (_byte2 >= 0x90) {
            // Extended char
            this.backSpace();
          }
      
          var _char = getCharForByte(_byte2);
      
          if (this.pos >= NR_COLS) {
            this.logger.log(VerboseLevel.ERROR, 'Cannot insert ' + _byte2.toString(16) + ' (' + _char + ') at position ' + this.pos + '. Skipping it!');
            return;
          }
      
          this.chars[this.pos].setChar(_char, this.currPenState);
          this.moveCursor(1);
        };
      
        _proto4.clearFromPos = function clearFromPos(startPos) {
          var i;
      
          for (i = startPos; i < NR_COLS; i++) {
            this.chars[i].reset();
          }
        };
      
        _proto4.clear = function clear() {
          this.clearFromPos(0);
          this.pos = 0;
          this.currPenState.reset();
        };
      
        _proto4.clearToEndOfRow = function clearToEndOfRow() {
          this.clearFromPos(this.pos);
        };
      
        _proto4.getTextString = function getTextString() {
          var chars = [];
          var empty = true;
      
          for (var i = 0; i < NR_COLS; i++) {
            var _char2 = this.chars[i].uchar;
      
            if (_char2 !== ' ') {
              empty = false;
            }
      
            chars.push(_char2);
          }
      
          if (empty) {
            return '';
          } else {
            return chars.join('');
          }
        };
      
        _proto4.setPenStyles = function setPenStyles(styles) {
          this.currPenState.setStyles(styles);
          var currChar = this.chars[this.pos];
          currChar.setPenState(this.currPenState);
        };
      
        return Row;
      }();
      /**
       * Keep a CEA-608 screen of 32x15 styled characters
       * @constructor
       */
      
      var CaptionScreen = /*#__PURE__*/function () {
        function CaptionScreen(logger) {
          this.rows = void 0;
          this.currRow = void 0;
          this.nrRollUpRows = void 0;
          this.lastOutputScreen = void 0;
          this.logger = void 0;
          this.rows = [];
      
          for (var i = 0; i < NR_ROWS; i++) {
            this.rows.push(new Row(logger));
          } // Note that we use zero-based numbering (0-14)
      
      
          this.logger = logger;
          this.currRow = NR_ROWS - 1;
          this.nrRollUpRows = null;
          this.lastOutputScreen = null;
          this.reset();
        }
      
        var _proto5 = CaptionScreen.prototype;
      
        _proto5.reset = function reset() {
          for (var i = 0; i < NR_ROWS; i++) {
            this.rows[i].clear();
          }
      
          this.currRow = NR_ROWS - 1;
        };
      
        _proto5.equals = function equals(other) {
          var equal = true;
      
          for (var i = 0; i < NR_ROWS; i++) {
            if (!this.rows[i].equals(other.rows[i])) {
              equal = false;
              break;
            }
          }
      
          return equal;
        };
      
        _proto5.copy = function copy(other) {
          for (var i = 0; i < NR_ROWS; i++) {
            this.rows[i].copy(other.rows[i]);
          }
        };
      
        _proto5.isEmpty = function isEmpty() {
          var empty = true;
      
          for (var i = 0; i < NR_ROWS; i++) {
            if (!this.rows[i].isEmpty()) {
              empty = false;
              break;
            }
          }
      
          return empty;
        };
      
        _proto5.backSpace = function backSpace() {
          var row = this.rows[this.currRow];
          row.backSpace();
        };
      
        _proto5.clearToEndOfRow = function clearToEndOfRow() {
          var row = this.rows[this.currRow];
          row.clearToEndOfRow();
        }
        /**
         * Insert a character (without styling) in the current row.
         */
        ;
      
        _proto5.insertChar = function insertChar(_char3) {
          var row = this.rows[this.currRow];
          row.insertChar(_char3);
        };
      
        _proto5.setPen = function setPen(styles) {
          var row = this.rows[this.currRow];
          row.setPenStyles(styles);
        };
      
        _proto5.moveCursor = function moveCursor(relPos) {
          var row = this.rows[this.currRow];
          row.moveCursor(relPos);
        };
      
        _proto5.setCursor = function setCursor(absPos) {
          this.logger.log(VerboseLevel.INFO, 'setCursor: ' + absPos);
          var row = this.rows[this.currRow];
          row.setCursor(absPos);
        };
      
        _proto5.setPAC = function setPAC(pacData) {
          this.logger.log(VerboseLevel.INFO, 'pacData = ' + JSON.stringify(pacData));
          var newRow = pacData.row - 1;
      
          if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {
            newRow = this.nrRollUpRows - 1;
          } // Make sure this only affects Roll-up Captions by checking this.nrRollUpRows
      
      
          if (this.nrRollUpRows && this.currRow !== newRow) {
            // clear all rows first
            for (var i = 0; i < NR_ROWS; i++) {
              this.rows[i].clear();
            } // Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location
            // topRowIndex - the start of rows to copy (inclusive index)
      
      
            var topRowIndex = this.currRow + 1 - this.nrRollUpRows; // We only copy if the last position was already shown.
            // We use the cueStartTime value to check this.
      
            var lastOutputScreen = this.lastOutputScreen;
      
            if (lastOutputScreen) {
              var prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;
              var time = this.logger.time;
      
              if (prevLineTime && time !== null && prevLineTime < time) {
                for (var _i = 0; _i < this.nrRollUpRows; _i++) {
                  this.rows[newRow - this.nrRollUpRows + _i + 1].copy(lastOutputScreen.rows[topRowIndex + _i]);
                }
              }
            }
          }
      
          this.currRow = newRow;
          var row = this.rows[this.currRow];
      
          if (pacData.indent !== null) {
            var indent = pacData.indent;
            var prevPos = Math.max(indent - 1, 0);
            row.setCursor(pacData.indent);
            pacData.color = row.chars[prevPos].penState.foreground;
          }
      
          var styles = {
            foreground: pacData.color,
            underline: pacData.underline,
            italics: pacData.italics,
            background: 'black',
            flash: false
          };
          this.setPen(styles);
        }
        /**
         * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).
         */
        ;
      
        _proto5.setBkgData = function setBkgData(bkgData) {
          this.logger.log(VerboseLevel.INFO, 'bkgData = ' + JSON.stringify(bkgData));
          this.backSpace();
          this.setPen(bkgData);
          this.insertChar(0x20); // Space
        };
      
        _proto5.setRollUpRows = function setRollUpRows(nrRows) {
          this.nrRollUpRows = nrRows;
        };
      
        _proto5.rollUp = function rollUp() {
          if (this.nrRollUpRows === null) {
            this.logger.log(VerboseLevel.DEBUG, 'roll_up but nrRollUpRows not set yet');
            return; // Not properly setup
          }
      
          this.logger.log(VerboseLevel.TEXT, this.getDisplayText());
          var topRowIndex = this.currRow + 1 - this.nrRollUpRows;
          var topRow = this.rows.splice(topRowIndex, 1)[0];
          topRow.clear();
          this.rows.splice(this.currRow, 0, topRow);
          this.logger.log(VerboseLevel.INFO, 'Rolling up'); // this.logger.log(VerboseLevel.TEXT, this.get_display_text())
        }
        /**
         * Get all non-empty rows with as unicode text.
         */
        ;
      
        _proto5.getDisplayText = function getDisplayText(asOneRow) {
          asOneRow = asOneRow || false;
          var displayText = [];
          var text = '';
          var rowNr = -1;
      
          for (var i = 0; i < NR_ROWS; i++) {
            var rowText = this.rows[i].getTextString();
      
            if (rowText) {
              rowNr = i + 1;
      
              if (asOneRow) {
                displayText.push('Row ' + rowNr + ": '" + rowText + "'");
              } else {
                displayText.push(rowText.trim());
              }
            }
          }
      
          if (displayText.length > 0) {
            if (asOneRow) {
              text = '[' + displayText.join(' | ') + ']';
            } else {
              text = displayText.join('\n');
            }
          }
      
          return text;
        };
      
        _proto5.getTextAndFormat = function getTextAndFormat() {
          return this.rows;
        };
      
        return CaptionScreen;
      }(); // var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];
      
      var Cea608Channel = /*#__PURE__*/function () {
        function Cea608Channel(channelNumber, outputFilter, logger) {
          this.chNr = void 0;
          this.outputFilter = void 0;
          this.mode = void 0;
          this.verbose = void 0;
          this.displayedMemory = void 0;
          this.nonDisplayedMemory = void 0;
          this.lastOutputScreen = void 0;
          this.currRollUpRow = void 0;
          this.writeScreen = void 0;
          this.cueStartTime = void 0;
          this.logger = void 0;
          this.chNr = channelNumber;
          this.outputFilter = outputFilter;
          this.mode = null;
          this.verbose = 0;
          this.displayedMemory = new CaptionScreen(logger);
          this.nonDisplayedMemory = new CaptionScreen(logger);
          this.lastOutputScreen = new CaptionScreen(logger);
          this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
          this.writeScreen = this.displayedMemory;
          this.mode = null;
          this.cueStartTime = null; // Keeps track of where a cue started.
      
          this.logger = logger;
        }
      
        var _proto6 = Cea608Channel.prototype;
      
        _proto6.reset = function reset() {
          this.mode = null;
          this.displayedMemory.reset();
          this.nonDisplayedMemory.reset();
          this.lastOutputScreen.reset();
          this.outputFilter.reset();
          this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
          this.writeScreen = this.displayedMemory;
          this.mode = null;
          this.cueStartTime = null;
        };
      
        _proto6.getHandler = function getHandler() {
          return this.outputFilter;
        };
      
        _proto6.setHandler = function setHandler(newHandler) {
          this.outputFilter = newHandler;
        };
      
        _proto6.setPAC = function setPAC(pacData) {
          this.writeScreen.setPAC(pacData);
        };
      
        _proto6.setBkgData = function setBkgData(bkgData) {
          this.writeScreen.setBkgData(bkgData);
        };
      
        _proto6.setMode = function setMode(newMode) {
          if (newMode === this.mode) {
            return;
          }
      
          this.mode = newMode;
          this.logger.log(VerboseLevel.INFO, 'MODE=' + newMode);
      
          if (this.mode === 'MODE_POP-ON') {
            this.writeScreen = this.nonDisplayedMemory;
          } else {
            this.writeScreen = this.displayedMemory;
            this.writeScreen.reset();
          }
      
          if (this.mode !== 'MODE_ROLL-UP') {
            this.displayedMemory.nrRollUpRows = null;
            this.nonDisplayedMemory.nrRollUpRows = null;
          }
      
          this.mode = newMode;
        };
      
        _proto6.insertChars = function insertChars(chars) {
          for (var i = 0; i < chars.length; i++) {
            this.writeScreen.insertChar(chars[i]);
          }
      
          var screen = this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP';
          this.logger.log(VerboseLevel.INFO, screen + ': ' + this.writeScreen.getDisplayText(true));
      
          if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') {
            this.logger.log(VerboseLevel.TEXT, 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true));
            this.outputDataUpdate();
          }
        };
      
        _proto6.ccRCL = function ccRCL() {
          // Resume Caption Loading (switch mode to Pop On)
          this.logger.log(VerboseLevel.INFO, 'RCL - Resume Caption Loading');
          this.setMode('MODE_POP-ON');
        };
      
        _proto6.ccBS = function ccBS() {
          // BackSpace
          this.logger.log(VerboseLevel.INFO, 'BS - BackSpace');
      
          if (this.mode === 'MODE_TEXT') {
            return;
          }
      
          this.writeScreen.backSpace();
      
          if (this.writeScreen === this.displayedMemory) {
            this.outputDataUpdate();
          }
        };
      
        _proto6.ccAOF = function ccAOF() {// Reserved (formerly Alarm Off)
        };
      
        _proto6.ccAON = function ccAON() {// Reserved (formerly Alarm On)
        };
      
        _proto6.ccDER = function ccDER() {
          // Delete to End of Row
          this.logger.log(VerboseLevel.INFO, 'DER- Delete to End of Row');
          this.writeScreen.clearToEndOfRow();
          this.outputDataUpdate();
        };
      
        _proto6.ccRU = function ccRU(nrRows) {
          // Roll-Up Captions-2,3,or 4 Rows
          this.logger.log(VerboseLevel.INFO, 'RU(' + nrRows + ') - Roll Up');
          this.writeScreen = this.displayedMemory;
          this.setMode('MODE_ROLL-UP');
          this.writeScreen.setRollUpRows(nrRows);
        };
      
        _proto6.ccFON = function ccFON() {
          // Flash On
          this.logger.log(VerboseLevel.INFO, 'FON - Flash On');
          this.writeScreen.setPen({
            flash: true
          });
        };
      
        _proto6.ccRDC = function ccRDC() {
          // Resume Direct Captioning (switch mode to PaintOn)
          this.logger.log(VerboseLevel.INFO, 'RDC - Resume Direct Captioning');
          this.setMode('MODE_PAINT-ON');
        };
      
        _proto6.ccTR = function ccTR() {
          // Text Restart in text mode (not supported, however)
          this.logger.log(VerboseLevel.INFO, 'TR');
          this.setMode('MODE_TEXT');
        };
      
        _proto6.ccRTD = function ccRTD() {
          // Resume Text Display in Text mode (not supported, however)
          this.logger.log(VerboseLevel.INFO, 'RTD');
          this.setMode('MODE_TEXT');
        };
      
        _proto6.ccEDM = function ccEDM() {
          // Erase Displayed Memory
          this.logger.log(VerboseLevel.INFO, 'EDM - Erase Displayed Memory');
          this.displayedMemory.reset();
          this.outputDataUpdate(true);
        };
      
        _proto6.ccCR = function ccCR() {
          // Carriage Return
          this.logger.log(VerboseLevel.INFO, 'CR - Carriage Return');
          this.writeScreen.rollUp();
          this.outputDataUpdate(true);
        };
      
        _proto6.ccENM = function ccENM() {
          // Erase Non-Displayed Memory
          this.logger.log(VerboseLevel.INFO, 'ENM - Erase Non-displayed Memory');
          this.nonDisplayedMemory.reset();
        };
      
        _proto6.ccEOC = function ccEOC() {
          // End of Caption (Flip Memories)
          this.logger.log(VerboseLevel.INFO, 'EOC - End Of Caption');
      
          if (this.mode === 'MODE_POP-ON') {
            var tmp = this.displayedMemory;
            this.displayedMemory = this.nonDisplayedMemory;
            this.nonDisplayedMemory = tmp;
            this.writeScreen = this.nonDisplayedMemory;
            this.logger.log(VerboseLevel.TEXT, 'DISP: ' + this.displayedMemory.getDisplayText());
          }
      
          this.outputDataUpdate(true);
        };
      
        _proto6.ccTO = function ccTO(nrCols) {
          // Tab Offset 1,2, or 3 columns
          this.logger.log(VerboseLevel.INFO, 'TO(' + nrCols + ') - Tab Offset');
          this.writeScreen.moveCursor(nrCols);
        };
      
        _proto6.ccMIDROW = function ccMIDROW(secondByte) {
          // Parse MIDROW command
          var styles = {
            flash: false
          };
          styles.underline = secondByte % 2 === 1;
          styles.italics = secondByte >= 0x2e;
      
          if (!styles.italics) {
            var colorIndex = Math.floor(secondByte / 2) - 0x10;
            var colors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta'];
            styles.foreground = colors[colorIndex];
          } else {
            styles.foreground = 'white';
          }
      
          this.logger.log(VerboseLevel.INFO, 'MIDROW: ' + JSON.stringify(styles));
          this.writeScreen.setPen(styles);
        };
      
        _proto6.outputDataUpdate = function outputDataUpdate(dispatch) {
          if (dispatch === void 0) {
            dispatch = false;
          }
      
          var time = this.logger.time;
      
          if (time === null) {
            return;
          }
      
          if (this.outputFilter) {
            if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {
              // Start of a new cue
              this.cueStartTime = time;
            } else {
              if (!this.displayedMemory.equals(this.lastOutputScreen)) {
                this.outputFilter.newCue(this.cueStartTime, time, this.lastOutputScreen);
      
                if (dispatch && this.outputFilter.dispatchCue) {
                  this.outputFilter.dispatchCue();
                }
      
                this.cueStartTime = this.displayedMemory.isEmpty() ? null : time;
              }
            }
      
            this.lastOutputScreen.copy(this.displayedMemory);
          }
        };
      
        _proto6.cueSplitAtTime = function cueSplitAtTime(t) {
          if (this.outputFilter) {
            if (!this.displayedMemory.isEmpty()) {
              if (this.outputFilter.newCue) {
                this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory);
              }
      
              this.cueStartTime = t;
            }
          }
        };
      
        return Cea608Channel;
      }();
      
      var Cea608Parser = /*#__PURE__*/function () {
        function Cea608Parser(field, out1, out2) {
          this.channels = void 0;
          this.currentChannel = 0;
          this.cmdHistory = void 0;
          this.logger = void 0;
          var logger = new CaptionsLogger();
          this.channels = [null, new Cea608Channel(field, out1, logger), new Cea608Channel(field + 1, out2, logger)];
          this.cmdHistory = createCmdHistory();
          this.logger = logger;
        }
      
        var _proto7 = Cea608Parser.prototype;
      
        _proto7.getHandler = function getHandler(channel) {
          return this.channels[channel].getHandler();
        };
      
        _proto7.setHandler = function setHandler(channel, newHandler) {
          this.channels[channel].setHandler(newHandler);
        }
        /**
         * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.
         */
        ;
      
        _proto7.addData = function addData(time, byteList) {
          var cmdFound;
          var a;
          var b;
          var charsFound = false;
          this.logger.time = time;
      
          for (var i = 0; i < byteList.length; i += 2) {
            a = byteList[i] & 0x7f;
            b = byteList[i + 1] & 0x7f;
      
            if (a === 0 && b === 0) {
              continue;
            } else {
              this.logger.log(VerboseLevel.DATA, '[' + numArrayToHexArray([byteList[i], byteList[i + 1]]) + '] -> (' + numArrayToHexArray([a, b]) + ')');
            }
      
            cmdFound = this.parseCmd(a, b);
      
            if (!cmdFound) {
              cmdFound = this.parseMidrow(a, b);
            }
      
            if (!cmdFound) {
              cmdFound = this.parsePAC(a, b);
            }
      
            if (!cmdFound) {
              cmdFound = this.parseBackgroundAttributes(a, b);
            }
      
            if (!cmdFound) {
              charsFound = this.parseChars(a, b);
      
              if (charsFound) {
                var currChNr = this.currentChannel;
      
                if (currChNr && currChNr > 0) {
                  var channel = this.channels[currChNr];
                  channel.insertChars(charsFound);
                } else {
                  this.logger.log(VerboseLevel.WARNING, 'No channel found yet. TEXT-MODE?');
                }
              }
            }
      
            if (!cmdFound && !charsFound) {
              this.logger.log(VerboseLevel.WARNING, "Couldn't parse cleaned data " + numArrayToHexArray([a, b]) + ' orig: ' + numArrayToHexArray([byteList[i], byteList[i + 1]]));
            }
          }
        }
        /**
         * Parse Command.
         * @returns {Boolean} Tells if a command was found
         */
        ;
      
        _proto7.parseCmd = function parseCmd(a, b) {
          var cmdHistory = this.cmdHistory;
          var cond1 = (a === 0x14 || a === 0x1c || a === 0x15 || a === 0x1d) && b >= 0x20 && b <= 0x2f;
          var cond2 = (a === 0x17 || a === 0x1f) && b >= 0x21 && b <= 0x23;
      
          if (!(cond1 || cond2)) {
            return false;
          }
      
          if (hasCmdRepeated(a, b, cmdHistory)) {
            setLastCmd(null, null, cmdHistory);
            this.logger.log(VerboseLevel.DEBUG, 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped');
            return true;
          }
      
          var chNr = a === 0x14 || a === 0x15 || a === 0x17 ? 1 : 2;
          var channel = this.channels[chNr];
      
          if (a === 0x14 || a === 0x15 || a === 0x1c || a === 0x1d) {
            if (b === 0x20) {
              channel.ccRCL();
            } else if (b === 0x21) {
              channel.ccBS();
            } else if (b === 0x22) {
              channel.ccAOF();
            } else if (b === 0x23) {
              channel.ccAON();
            } else if (b === 0x24) {
              channel.ccDER();
            } else if (b === 0x25) {
              channel.ccRU(2);
            } else if (b === 0x26) {
              channel.ccRU(3);
            } else if (b === 0x27) {
              channel.ccRU(4);
            } else if (b === 0x28) {
              channel.ccFON();
            } else if (b === 0x29) {
              channel.ccRDC();
            } else if (b === 0x2a) {
              channel.ccTR();
            } else if (b === 0x2b) {
              channel.ccRTD();
            } else if (b === 0x2c) {
              channel.ccEDM();
            } else if (b === 0x2d) {
              channel.ccCR();
            } else if (b === 0x2e) {
              channel.ccENM();
            } else if (b === 0x2f) {
              channel.ccEOC();
            }
          } else {
            // a == 0x17 || a == 0x1F
            channel.ccTO(b - 0x20);
          }
      
          setLastCmd(a, b, cmdHistory);
          this.currentChannel = chNr;
          return true;
        }
        /**
         * Parse midrow styling command
         * @returns {Boolean}
         */
        ;
      
        _proto7.parseMidrow = function parseMidrow(a, b) {
          var chNr = 0;
      
          if ((a === 0x11 || a === 0x19) && b >= 0x20 && b <= 0x2f) {
            if (a === 0x11) {
              chNr = 1;
            } else {
              chNr = 2;
            }
      
            if (chNr !== this.currentChannel) {
              this.logger.log(VerboseLevel.ERROR, 'Mismatch channel in midrow parsing');
              return false;
            }
      
            var channel = this.channels[chNr];
      
            if (!channel) {
              return false;
            }
      
            channel.ccMIDROW(b);
            this.logger.log(VerboseLevel.DEBUG, 'MIDROW (' + numArrayToHexArray([a, b]) + ')');
            return true;
          }
      
          return false;
        }
        /**
         * Parse Preable Access Codes (Table 53).
         * @returns {Boolean} Tells if PAC found
         */
        ;
      
        _proto7.parsePAC = function parsePAC(a, b) {
          var row;
          var cmdHistory = this.cmdHistory;
          var case1 = (a >= 0x11 && a <= 0x17 || a >= 0x19 && a <= 0x1f) && b >= 0x40 && b <= 0x7f;
          var case2 = (a === 0x10 || a === 0x18) && b >= 0x40 && b <= 0x5f;
      
          if (!(case1 || case2)) {
            return false;
          }
      
          if (hasCmdRepeated(a, b, cmdHistory)) {
            setLastCmd(null, null, cmdHistory);
            return true; // Repeated commands are dropped (once)
          }
      
          var chNr = a <= 0x17 ? 1 : 2;
      
          if (b >= 0x40 && b <= 0x5f) {
            row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a];
          } else {
            // 0x60 <= b <= 0x7F
            row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a];
          }
      
          var channel = this.channels[chNr];
      
          if (!channel) {
            return false;
          }
      
          channel.setPAC(this.interpretPAC(row, b));
          setLastCmd(a, b, cmdHistory);
          this.currentChannel = chNr;
          return true;
        }
        /**
         * Interpret the second byte of the pac, and return the information.
         * @returns {Object} pacData with style parameters.
         */
        ;
      
        _proto7.interpretPAC = function interpretPAC(row, _byte3) {
          var pacIndex;
          var pacData = {
            color: null,
            italics: false,
            indent: null,
            underline: false,
            row: row
          };
      
          if (_byte3 > 0x5f) {
            pacIndex = _byte3 - 0x60;
          } else {
            pacIndex = _byte3 - 0x40;
          }
      
          pacData.underline = (pacIndex & 1) === 1;
      
          if (pacIndex <= 0xd) {
            pacData.color = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'white'][Math.floor(pacIndex / 2)];
          } else if (pacIndex <= 0xf) {
            pacData.italics = true;
            pacData.color = 'white';
          } else {
            pacData.indent = Math.floor((pacIndex - 0x10) / 2) * 4;
          }
      
          return pacData; // Note that row has zero offset. The spec uses 1.
        }
        /**
         * Parse characters.
         * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.
         */
        ;
      
        _proto7.parseChars = function parseChars(a, b) {
          var channelNr;
          var charCodes = null;
          var charCode1 = null;
      
          if (a >= 0x19) {
            channelNr = 2;
            charCode1 = a - 8;
          } else {
            channelNr = 1;
            charCode1 = a;
          }
      
          if (charCode1 >= 0x11 && charCode1 <= 0x13) {
            // Special character
            var oneCode;
      
            if (charCode1 === 0x11) {
              oneCode = b + 0x50;
            } else if (charCode1 === 0x12) {
              oneCode = b + 0x70;
            } else {
              oneCode = b + 0x90;
            }
      
            this.logger.log(VerboseLevel.INFO, "Special char '" + getCharForByte(oneCode) + "' in channel " + channelNr);
            charCodes = [oneCode];
          } else if (a >= 0x20 && a <= 0x7f) {
            charCodes = b === 0 ? [a] : [a, b];
          }
      
          if (charCodes) {
            var hexCodes = numArrayToHexArray(charCodes);
            this.logger.log(VerboseLevel.DEBUG, 'Char codes =  ' + hexCodes.join(','));
            setLastCmd(a, b, this.cmdHistory);
          }
      
          return charCodes;
        }
        /**
         * Parse extended background attributes as well as new foreground color black.
         * @returns {Boolean} Tells if background attributes are found
         */
        ;
      
        _proto7.parseBackgroundAttributes = function parseBackgroundAttributes(a, b) {
          var case1 = (a === 0x10 || a === 0x18) && b >= 0x20 && b <= 0x2f;
          var case2 = (a === 0x17 || a === 0x1f) && b >= 0x2d && b <= 0x2f;
      
          if (!(case1 || case2)) {
            return false;
          }
      
          var index;
          var bkgData = {};
      
          if (a === 0x10 || a === 0x18) {
            index = Math.floor((b - 0x20) / 2);
            bkgData.background = backgroundColors[index];
      
            if (b % 2 === 1) {
              bkgData.background = bkgData.background + '_semi';
            }
          } else if (b === 0x2d) {
            bkgData.background = 'transparent';
          } else {
            bkgData.foreground = 'black';
      
            if (b === 0x2f) {
              bkgData.underline = true;
            }
          }
      
          var chNr = a <= 0x17 ? 1 : 2;
          var channel = this.channels[chNr];
          channel.setBkgData(bkgData);
          setLastCmd(a, b, this.cmdHistory);
          return true;
        }
        /**
         * Reset state of parser and its channels.
         */
        ;
      
        _proto7.reset = function reset() {
          for (var i = 0; i < Object.keys(this.channels).length; i++) {
            var channel = this.channels[i];
      
            if (channel) {
              channel.reset();
            }
          }
      
          this.cmdHistory = createCmdHistory();
        }
        /**
         * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.
         */
        ;
      
        _proto7.cueSplitAtTime = function cueSplitAtTime(t) {
          for (var i = 0; i < this.channels.length; i++) {
            var channel = this.channels[i];
      
            if (channel) {
              channel.cueSplitAtTime(t);
            }
          }
        };
      
        return Cea608Parser;
      }();
      
      function setLastCmd(a, b, cmdHistory) {
        cmdHistory.a = a;
        cmdHistory.b = b;
      }
      
      function hasCmdRepeated(a, b, cmdHistory) {
        return cmdHistory.a === a && cmdHistory.b === b;
      }
      
      function createCmdHistory() {
        return {
          a: null,
          b: null
        };
      }
      
      /* harmony default export */ __webpack_exports__["default"] = (Cea608Parser);
      
      /***/ }),
      
      /***/ "./src/utils/codecs.ts":
      /*!*****************************!*\
        !*** ./src/utils/codecs.ts ***!
        \*****************************/
      /*! exports provided: isCodecType, isCodecSupportedInMp4 */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isCodecType", function() { return isCodecType; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isCodecSupportedInMp4", function() { return isCodecSupportedInMp4; });
      // from http://mp4ra.org/codecs.html
      var sampleEntryCodesISO = {
        audio: {
          a3ds: true,
          'ac-3': true,
          'ac-4': true,
          alac: true,
          alaw: true,
          dra1: true,
          'dts+': true,
          'dts-': true,
          dtsc: true,
          dtse: true,
          dtsh: true,
          'ec-3': true,
          enca: true,
          g719: true,
          g726: true,
          m4ae: true,
          mha1: true,
          mha2: true,
          mhm1: true,
          mhm2: true,
          mlpa: true,
          mp4a: true,
          'raw ': true,
          Opus: true,
          samr: true,
          sawb: true,
          sawp: true,
          sevc: true,
          sqcp: true,
          ssmv: true,
          twos: true,
          ulaw: true
        },
        video: {
          avc1: true,
          avc2: true,
          avc3: true,
          avc4: true,
          avcp: true,
          av01: true,
          drac: true,
          dvav: true,
          dvhe: true,
          encv: true,
          hev1: true,
          hvc1: true,
          mjp2: true,
          mp4v: true,
          mvc1: true,
          mvc2: true,
          mvc3: true,
          mvc4: true,
          resv: true,
          rv60: true,
          s263: true,
          svc1: true,
          svc2: true,
          'vc-1': true,
          vp08: true,
          vp09: true
        },
        text: {
          stpp: true,
          wvtt: true
        }
      };
      function isCodecType(codec, type) {
        var typeCodes = sampleEntryCodesISO[type];
        return !!typeCodes && typeCodes[codec.slice(0, 4)] === true;
      }
      function isCodecSupportedInMp4(codec, type) {
        return MediaSource.isTypeSupported((type || 'video') + "/mp4;codecs=\"" + codec + "\"");
      }
      
      /***/ }),
      
      /***/ "./src/utils/cues.ts":
      /*!***************************!*\
        !*** ./src/utils/cues.ts ***!
        \***************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony import */ var _vttparser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./vttparser */ "./src/utils/vttparser.ts");
      /* harmony import */ var _webvtt_parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./webvtt-parser */ "./src/utils/webvtt-parser.ts");
      /* harmony import */ var _texttrack_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./texttrack-utils */ "./src/utils/texttrack-utils.ts");
      
      
      
      var WHITESPACE_CHAR = /\s/;
      var Cues = {
        newCue: function newCue(track, startTime, endTime, captionScreen) {
          var result = [];
          var row; // the type data states this is VTTCue, but it can potentially be a TextTrackCue on old browsers
      
          var cue;
          var indenting;
          var indent;
          var text;
          var Cue = self.VTTCue || self.TextTrackCue;
      
          for (var r = 0; r < captionScreen.rows.length; r++) {
            row = captionScreen.rows[r];
            indenting = true;
            indent = 0;
            text = '';
      
            if (!row.isEmpty()) {
              for (var c = 0; c < row.chars.length; c++) {
                if (WHITESPACE_CHAR.test(row.chars[c].uchar) && indenting) {
                  indent++;
                } else {
                  text += row.chars[c].uchar;
                  indenting = false;
                }
              } // To be used for cleaning-up orphaned roll-up captions
      
      
              row.cueStartTime = startTime; // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE
      
              if (startTime === endTime) {
                endTime += 0.0001;
              }
      
              if (indent >= 16) {
                indent--;
              } else {
                indent++;
              }
      
              var cueText = Object(_vttparser__WEBPACK_IMPORTED_MODULE_0__["fixLineBreaks"])(text.trim());
              var id = Object(_webvtt_parser__WEBPACK_IMPORTED_MODULE_1__["generateCueId"])(startTime, endTime, cueText); // If this cue already exists in the track do not push it
      
              if (!track || !track.cues || !track.cues.getCueById(id)) {
                cue = new Cue(startTime, endTime, cueText);
                cue.id = id;
                cue.line = r + 1;
                cue.align = 'left'; // Clamp the position between 10 and 80 percent (CEA-608 PAC indent code)
                // https://dvcs.w3.org/hg/text-tracks/raw-file/default/608toVTT/608toVTT.html#positioning-in-cea-608
                // Firefox throws an exception and captions break with out of bounds 0-100 values
      
                cue.position = 10 + Math.min(80, Math.floor(indent * 8 / 32) * 10);
                result.push(cue);
              }
            }
          }
      
          if (track && result.length) {
            // Sort bottom cues in reverse order so that they render in line order when overlapping in Chrome
            result.sort(function (cueA, cueB) {
              if (cueA.line === 'auto' || cueB.line === 'auto') {
                return 0;
              }
      
              if (cueA.line > 8 && cueB.line > 8) {
                return cueB.line - cueA.line;
              }
      
              return cueA.line - cueB.line;
            });
            result.forEach(function (cue) {
              return Object(_texttrack_utils__WEBPACK_IMPORTED_MODULE_2__["addCueToTrack"])(track, cue);
            });
          }
      
          return result;
        }
      };
      /* harmony default export */ __webpack_exports__["default"] = (Cues);
      
      /***/ }),
      
      /***/ "./src/utils/discontinuities.ts":
      /*!**************************************!*\
        !*** ./src/utils/discontinuities.ts ***!
        \**************************************/
      /*! exports provided: findFirstFragWithCC, shouldAlignOnDiscontinuities, findDiscontinuousReferenceFrag, adjustSlidingStart, alignStream, alignPDT, alignFragmentByPDTDelta, alignMediaPlaylistByPDT */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findFirstFragWithCC", function() { return findFirstFragWithCC; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "shouldAlignOnDiscontinuities", function() { return shouldAlignOnDiscontinuities; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findDiscontinuousReferenceFrag", function() { return findDiscontinuousReferenceFrag; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "adjustSlidingStart", function() { return adjustSlidingStart; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alignStream", function() { return alignStream; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alignPDT", function() { return alignPDT; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alignFragmentByPDTDelta", function() { return alignFragmentByPDTDelta; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alignMediaPlaylistByPDT", function() { return alignMediaPlaylistByPDT; });
      /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
      /* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./logger */ "./src/utils/logger.ts");
      /* harmony import */ var _controller_level_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../controller/level-helper */ "./src/controller/level-helper.ts");
      
      
      
      
      function findFirstFragWithCC(fragments, cc) {
        var firstFrag = null;
      
        for (var i = 0, len = fragments.length; i < len; i++) {
          var currentFrag = fragments[i];
      
          if (currentFrag && currentFrag.cc === cc) {
            firstFrag = currentFrag;
            break;
          }
        }
      
        return firstFrag;
      }
      function shouldAlignOnDiscontinuities(lastFrag, lastLevel, details) {
        if (lastLevel.details) {
          if (details.endCC > details.startCC || lastFrag && lastFrag.cc < details.startCC) {
            return true;
          }
        }
      
        return false;
      } // Find the first frag in the previous level which matches the CC of the first frag of the new level
      
      function findDiscontinuousReferenceFrag(prevDetails, curDetails) {
        var prevFrags = prevDetails.fragments;
        var curFrags = curDetails.fragments;
      
        if (!curFrags.length || !prevFrags.length) {
          _logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log('No fragments to align');
          return;
        }
      
        var prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);
      
        if (!prevStartFrag || prevStartFrag && !prevStartFrag.startPTS) {
          _logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log('No frag in previous level to align on');
          return;
        }
      
        return prevStartFrag;
      }
      
      function adjustFragmentStart(frag, sliding) {
        if (frag) {
          var start = frag.start + sliding;
          frag.start = frag.startPTS = start;
          frag.endPTS = start + frag.duration;
        }
      }
      
      function adjustSlidingStart(sliding, details) {
        // Update segments
        var fragments = details.fragments;
      
        for (var i = 0, len = fragments.length; i < len; i++) {
          adjustFragmentStart(fragments[i], sliding);
        } // Update LL-HLS parts at the end of the playlist
      
      
        if (details.fragmentHint) {
          adjustFragmentStart(details.fragmentHint, sliding);
        }
      
        details.alignedSliding = true;
      }
      /**
       * Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a
       * contiguous stream with the last fragments.
       * The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to
       * download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time
       * and an extra download.
       * @param lastFrag
       * @param lastLevel
       * @param details
       */
      
      function alignStream(lastFrag, lastLevel, details) {
        if (!lastLevel) {
          return;
        }
      
        alignDiscontinuities(lastFrag, details, lastLevel);
      
        if (!details.alignedSliding && lastLevel.details) {
          // If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.
          // Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same
          // discontinuity sequence.
          alignPDT(details, lastLevel.details);
        }
      
        if (!details.alignedSliding && lastLevel.details && !details.skippedSegments) {
          // Try to align on sn so that we pick a better start fragment.
          // Do not perform this on playlists with delta updates as this is only to align levels on switch
          // and adjustSliding only adjusts fragments after skippedSegments.
          Object(_controller_level_helper__WEBPACK_IMPORTED_MODULE_2__["adjustSliding"])(lastLevel.details, details);
        }
      }
      /**
       * Computes the PTS if a new level's fragments using the PTS of a fragment in the last level which shares the same
       * discontinuity sequence.
       * @param lastFrag - The last Fragment which shares the same discontinuity sequence
       * @param lastLevel - The details of the last loaded level
       * @param details - The details of the new level
       */
      
      function alignDiscontinuities(lastFrag, details, lastLevel) {
        if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) {
          var referenceFrag = findDiscontinuousReferenceFrag(lastLevel.details, details);
      
          if (referenceFrag && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(referenceFrag.start)) {
            _logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log("Adjusting PTS using last level due to CC increase within current level " + details.url);
            adjustSlidingStart(referenceFrag.start, details);
          }
        }
      }
      /**
       * Computes the PTS of a new level's fragments using the difference in Program Date Time from the last level.
       * @param details - The details of the new level
       * @param lastDetails - The details of the last loaded level
       */
      
      
      function alignPDT(details, lastDetails) {
        // This check protects the unsafe "!" usage below for null program date time access.
        if (!lastDetails.fragments.length || !details.hasProgramDateTime || !lastDetails.hasProgramDateTime) {
          return;
        } // if last level sliding is 1000 and its first frag PROGRAM-DATE-TIME is 2017-08-20 1:10:00 AM
        // and if new details first frag PROGRAM DATE-TIME is 2017-08-20 1:10:08 AM
        // then we can deduce that playlist B sliding is 1000+8 = 1008s
      
      
        var lastPDT = lastDetails.fragments[0].programDateTime; // hasProgramDateTime check above makes this safe.
      
        var newPDT = details.fragments[0].programDateTime; // date diff is in ms. frag.start is in seconds
      
        var sliding = (newPDT - lastPDT) / 1000 + lastDetails.fragments[0].start;
      
        if (sliding && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(sliding)) {
          _logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log("Adjusting PTS using programDateTime delta " + (newPDT - lastPDT) + "ms, sliding:" + sliding.toFixed(3) + " " + details.url + " ");
          adjustSlidingStart(sliding, details);
        }
      }
      function alignFragmentByPDTDelta(frag, delta) {
        var programDateTime = frag.programDateTime;
        if (!programDateTime) return;
        var start = (programDateTime - delta) / 1000;
        frag.start = frag.startPTS = start;
        frag.endPTS = start + frag.duration;
      }
      /**
       * Ensures appropriate time-alignment between renditions based on PDT. Unlike `alignPDT`, which adjusts
       * the timeline based on the delta between PDTs of the 0th fragment of two playlists/`LevelDetails`,
       * this function assumes the timelines represented in `refDetails` are accurate, including the PDTs,
       * and uses the "wallclock"/PDT timeline as a cross-reference to `details`, adjusting the presentation
       * times/timelines of `details` accordingly.
       * Given the asynchronous nature of fetches and initial loads of live `main` and audio/subtitle tracks,
       * the primary purpose of this function is to ensure the "local timelines" of audio/subtitle tracks
       * are aligned to the main/video timeline, using PDT as the cross-reference/"anchor" that should
       * be consistent across playlists, per the HLS spec.
       * @param details - The details of the rendition you'd like to time-align (e.g. an audio rendition).
       * @param refDetails - The details of the reference rendition with start and PDT times for alignment.
       */
      
      function alignMediaPlaylistByPDT(details, refDetails) {
        // This check protects the unsafe "!" usage below for null program date time access.
        if (!refDetails.fragments.length || !details.hasProgramDateTime || !refDetails.hasProgramDateTime) {
          return;
        }
      
        var refPDT = refDetails.fragments[0].programDateTime; // hasProgramDateTime check above makes this safe.
      
        var refStart = refDetails.fragments[0].start; // Use the delta between the reference details' presentation timeline's start time and its PDT
        // to align the other rendtion's timeline.
      
        var delta = refPDT - refStart * 1000; // Per spec: "If any Media Playlist in a Master Playlist contains an EXT-X-PROGRAM-DATE-TIME tag, then all
        // Media Playlists in that Master Playlist MUST contain EXT-X-PROGRAM-DATE-TIME tags with consistent mappings
        // of date and time to media timestamps."
        // So we should be able to use each rendition's PDT as a reference time and use the delta to compute our relevant
        // start and end times.
        // NOTE: This code assumes each level/details timelines have already been made "internally consistent"
      
        details.fragments.forEach(function (frag) {
          alignFragmentByPDTDelta(frag, delta);
        });
      
        if (details.fragmentHint) {
          alignFragmentByPDTDelta(details.fragmentHint, delta);
        }
      
        details.alignedSliding = true;
      }
      
      /***/ }),
      
      /***/ "./src/utils/ewma-bandwidth-estimator.ts":
      /*!***********************************************!*\
        !*** ./src/utils/ewma-bandwidth-estimator.ts ***!
        \***********************************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony import */ var _utils_ewma__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/ewma */ "./src/utils/ewma.ts");
      /*
       * EWMA Bandwidth Estimator
       *  - heavily inspired from shaka-player
       * Tracks bandwidth samples and estimates available bandwidth.
       * Based on the minimum of two exponentially-weighted moving averages with
       * different half-lives.
       */
      
      
      var EwmaBandWidthEstimator = /*#__PURE__*/function () {
        function EwmaBandWidthEstimator(slow, fast, defaultEstimate) {
          this.defaultEstimate_ = void 0;
          this.minWeight_ = void 0;
          this.minDelayMs_ = void 0;
          this.slow_ = void 0;
          this.fast_ = void 0;
          this.defaultEstimate_ = defaultEstimate;
          this.minWeight_ = 0.001;
          this.minDelayMs_ = 50;
          this.slow_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](slow);
          this.fast_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](fast);
        }
      
        var _proto = EwmaBandWidthEstimator.prototype;
      
        _proto.update = function update(slow, fast) {
          var slow_ = this.slow_,
              fast_ = this.fast_;
      
          if (this.slow_.halfLife !== slow) {
            this.slow_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](slow, slow_.getEstimate(), slow_.getTotalWeight());
          }
      
          if (this.fast_.halfLife !== fast) {
            this.fast_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](fast, fast_.getEstimate(), fast_.getTotalWeight());
          }
        };
      
        _proto.sample = function sample(durationMs, numBytes) {
          durationMs = Math.max(durationMs, this.minDelayMs_);
          var numBits = 8 * numBytes; // weight is duration in seconds
      
          var durationS = durationMs / 1000; // value is bandwidth in bits/s
      
          var bandwidthInBps = numBits / durationS;
          this.fast_.sample(durationS, bandwidthInBps);
          this.slow_.sample(durationS, bandwidthInBps);
        };
      
        _proto.canEstimate = function canEstimate() {
          var fast = this.fast_;
          return fast && fast.getTotalWeight() >= this.minWeight_;
        };
      
        _proto.getEstimate = function getEstimate() {
          if (this.canEstimate()) {
            // console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));
            // console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));
            // Take the minimum of these two estimates.  This should have the effect of
            // adapting down quickly, but up more slowly.
            return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
          } else {
            return this.defaultEstimate_;
          }
        };
      
        _proto.destroy = function destroy() {};
      
        return EwmaBandWidthEstimator;
      }();
      
      /* harmony default export */ __webpack_exports__["default"] = (EwmaBandWidthEstimator);
      
      /***/ }),
      
      /***/ "./src/utils/ewma.ts":
      /*!***************************!*\
        !*** ./src/utils/ewma.ts ***!
        \***************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /*
       * compute an Exponential Weighted moving average
       * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
       *  - heavily inspired from shaka-player
       */
      var EWMA = /*#__PURE__*/function () {
        //  About half of the estimated value will be from the last |halfLife| samples by weight.
        function EWMA(halfLife, estimate, weight) {
          if (estimate === void 0) {
            estimate = 0;
          }
      
          if (weight === void 0) {
            weight = 0;
          }
      
          this.halfLife = void 0;
          this.alpha_ = void 0;
          this.estimate_ = void 0;
          this.totalWeight_ = void 0;
          this.halfLife = halfLife; // Larger values of alpha expire historical data more slowly.
      
          this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
          this.estimate_ = estimate;
          this.totalWeight_ = weight;
        }
      
        var _proto = EWMA.prototype;
      
        _proto.sample = function sample(weight, value) {
          var adjAlpha = Math.pow(this.alpha_, weight);
          this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
          this.totalWeight_ += weight;
        };
      
        _proto.getTotalWeight = function getTotalWeight() {
          return this.totalWeight_;
        };
      
        _proto.getEstimate = function getEstimate() {
          if (this.alpha_) {
            var zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
      
            if (zeroFactor) {
              return this.estimate_ / zeroFactor;
            }
          }
      
          return this.estimate_;
        };
      
        return EWMA;
      }();
      
      /* harmony default export */ __webpack_exports__["default"] = (EWMA);
      
      /***/ }),
      
      /***/ "./src/utils/fetch-loader.ts":
      /*!***********************************!*\
        !*** ./src/utils/fetch-loader.ts ***!
        \***********************************/
      /*! exports provided: fetchSupported, default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fetchSupported", function() { return fetchSupported; });
      /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
      /* harmony import */ var _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../loader/load-stats */ "./src/loader/load-stats.ts");
      /* harmony import */ var _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/chunk-cache */ "./src/demux/chunk-cache.ts");
      
      
      
      function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
      
      function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
      
      function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
      
      function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
      
      function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
      
      function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
      
      function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
      
      function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
      
      
      
      function fetchSupported() {
        if ( // @ts-ignore
        self.fetch && self.AbortController && self.ReadableStream && self.Request) {
          try {
            new self.ReadableStream({}); // eslint-disable-line no-new
      
            return true;
          } catch (e) {
            /* noop */
          }
        }
      
        return false;
      }
      
      var FetchLoader = /*#__PURE__*/function () {
        function FetchLoader(config
        /* HlsConfig */
        ) {
          this.fetchSetup = void 0;
          this.requestTimeout = void 0;
          this.request = void 0;
          this.response = void 0;
          this.controller = void 0;
          this.context = void 0;
          this.config = null;
          this.callbacks = null;
          this.stats = void 0;
          this.loader = null;
          this.fetchSetup = config.fetchSetup || getRequest;
          this.controller = new self.AbortController();
          this.stats = new _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__["LoadStats"]();
        }
      
        var _proto = FetchLoader.prototype;
      
        _proto.destroy = function destroy() {
          this.loader = this.callbacks = null;
          this.abortInternal();
        };
      
        _proto.abortInternal = function abortInternal() {
          var response = this.response;
      
          if (!response || !response.ok) {
            this.stats.aborted = true;
            this.controller.abort();
          }
        };
      
        _proto.abort = function abort() {
          var _this$callbacks;
      
          this.abortInternal();
      
          if ((_this$callbacks = this.callbacks) !== null && _this$callbacks !== void 0 && _this$callbacks.onAbort) {
            this.callbacks.onAbort(this.stats, this.context, this.response);
          }
        };
      
        _proto.load = function load(context, config, callbacks) {
          var _this = this;
      
          var stats = this.stats;
      
          if (stats.loading.start) {
            throw new Error('Loader can only be used once.');
          }
      
          stats.loading.start = self.performance.now();
          var initParams = getRequestParameters(context, this.controller.signal);
          var onProgress = callbacks.onProgress;
          var isArrayBuffer = context.responseType === 'arraybuffer';
          var LENGTH = isArrayBuffer ? 'byteLength' : 'length';
          this.context = context;
          this.config = config;
          this.callbacks = callbacks;
          this.request = this.fetchSetup(context, initParams);
          self.clearTimeout(this.requestTimeout);
          this.requestTimeout = self.setTimeout(function () {
            _this.abortInternal();
      
            callbacks.onTimeout(stats, context, _this.response);
          }, config.timeout);
          self.fetch(this.request).then(function (response) {
            _this.response = _this.loader = response;
      
            if (!response.ok) {
              var status = response.status,
                  statusText = response.statusText;
              throw new FetchError(statusText || 'fetch, bad network response', status, response);
            }
      
            stats.loading.first = Math.max(self.performance.now(), stats.loading.start);
            stats.total = parseInt(response.headers.get('Content-Length') || '0');
      
            if (onProgress && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(config.highWaterMark)) {
              return _this.loadProgressively(response, stats, context, config.highWaterMark, onProgress);
            }
      
            if (isArrayBuffer) {
              return response.arrayBuffer();
            }
      
            return response.text();
          }).then(function (responseData) {
            var response = _this.response;
            self.clearTimeout(_this.requestTimeout);
            stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
            stats.loaded = stats.total = responseData[LENGTH];
            var loaderResponse = {
              url: response.url,
              data: responseData
            };
      
            if (onProgress && !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(config.highWaterMark)) {
              onProgress(stats, context, responseData, response);
            }
      
            callbacks.onSuccess(loaderResponse, stats, context, response);
          }).catch(function (error) {
            self.clearTimeout(_this.requestTimeout);
      
            if (stats.aborted) {
              return;
            } // CORS errors result in an undefined code. Set it to 0 here to align with XHR's behavior
      
      
            var code = error.code || 0;
            callbacks.onError({
              code: code,
              text: error.message
            }, context, error.details);
          });
        };
      
        _proto.getCacheAge = function getCacheAge() {
          var result = null;
      
          if (this.response) {
            var ageHeader = this.response.headers.get('age');
            result = ageHeader ? parseFloat(ageHeader) : null;
          }
      
          return result;
        };
      
        _proto.loadProgressively = function loadProgressively(response, stats, context, highWaterMark, onProgress) {
          if (highWaterMark === void 0) {
            highWaterMark = 0;
          }
      
          var chunkCache = new _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_2__["default"]();
          var reader = response.body.getReader();
      
          var pump = function pump() {
            return reader.read().then(function (data) {
              if (data.done) {
                if (chunkCache.dataLength) {
                  onProgress(stats, context, chunkCache.flush(), response);
                }
      
                return Promise.resolve(new ArrayBuffer(0));
              }
      
              var chunk = data.value;
              var len = chunk.length;
              stats.loaded += len;
      
              if (len < highWaterMark || chunkCache.dataLength) {
                // The current chunk is too small to to be emitted or the cache already has data
                // Push it to the cache
                chunkCache.push(chunk);
      
                if (chunkCache.dataLength >= highWaterMark) {
                  // flush in order to join the typed arrays
                  onProgress(stats, context, chunkCache.flush(), response);
                }
              } else {
                // If there's nothing cached already, and the chache is large enough
                // just emit the progress event
                onProgress(stats, context, chunk, response);
              }
      
              return pump();
            }).catch(function () {
              /* aborted */
              return Promise.reject();
            });
          };
      
          return pump();
        };
      
        return FetchLoader;
      }();
      
      function getRequestParameters(context, signal) {
        var initParams = {
          method: 'GET',
          mode: 'cors',
          credentials: 'same-origin',
          signal: signal,
          headers: new self.Headers(_extends({}, context.headers))
        };
      
        if (context.rangeEnd) {
          initParams.headers.set('Range', 'bytes=' + context.rangeStart + '-' + String(context.rangeEnd - 1));
        }
      
        return initParams;
      }
      
      function getRequest(context, initParams) {
        return new self.Request(context.url, initParams);
      }
      
      var FetchError = /*#__PURE__*/function (_Error) {
        _inheritsLoose(FetchError, _Error);
      
        function FetchError(message, code, details) {
          var _this2;
      
          _this2 = _Error.call(this, message) || this;
          _this2.code = void 0;
          _this2.details = void 0;
          _this2.code = code;
          _this2.details = details;
          return _this2;
        }
      
        return FetchError;
      }( /*#__PURE__*/_wrapNativeSuper(Error));
      
      /* harmony default export */ __webpack_exports__["default"] = (FetchLoader);
      
      /***/ }),
      
      /***/ "./src/utils/imsc1-ttml-parser.ts":
      /*!****************************************!*\
        !*** ./src/utils/imsc1-ttml-parser.ts ***!
        \****************************************/
      /*! exports provided: IMSC1_CODEC, parseIMSC1 */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IMSC1_CODEC", function() { return IMSC1_CODEC; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseIMSC1", function() { return parseIMSC1; });
      /* harmony import */ var _mp4_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./mp4-tools */ "./src/utils/mp4-tools.ts");
      /* harmony import */ var _vttparser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./vttparser */ "./src/utils/vttparser.ts");
      /* harmony import */ var _vttcue__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./vttcue */ "./src/utils/vttcue.ts");
      /* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
      /* harmony import */ var _timescale_conversion__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./timescale-conversion */ "./src/utils/timescale-conversion.ts");
      /* harmony import */ var _webvtt_parser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./webvtt-parser */ "./src/utils/webvtt-parser.ts");
      function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
      
      
      
      
      
      
      
      var IMSC1_CODEC = 'stpp.ttml.im1t'; // Time format: h:m:s:frames(.subframes)
      
      var HMSF_REGEX = /^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/; // Time format: hours, minutes, seconds, milliseconds, frames, ticks
      
      var TIME_UNIT_REGEX = /^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/;
      var textAlignToLineAlign = {
        left: 'start',
        center: 'center',
        right: 'end',
        start: 'start',
        end: 'end'
      };
      function parseIMSC1(payload, initPTS, timescale, callBack, errorCallBack) {
        var results = Object(_mp4_tools__WEBPACK_IMPORTED_MODULE_0__["findBox"])(new Uint8Array(payload), ['mdat']);
      
        if (results.length === 0) {
          errorCallBack(new Error('Could not parse IMSC1 mdat'));
          return;
        }
      
        var mdat = results[0];
        var ttml = Object(_demux_id3__WEBPACK_IMPORTED_MODULE_3__["utf8ArrayToStr"])(new Uint8Array(payload, mdat.start, mdat.end - mdat.start));
        var syncTime = Object(_timescale_conversion__WEBPACK_IMPORTED_MODULE_4__["toTimescaleFromScale"])(initPTS, 1, timescale);
      
        try {
          callBack(parseTTML(ttml, syncTime));
        } catch (error) {
          errorCallBack(error);
        }
      }
      
      function parseTTML(ttml, syncTime) {
        var parser = new DOMParser();
        var xmlDoc = parser.parseFromString(ttml, 'text/xml');
        var tt = xmlDoc.getElementsByTagName('tt')[0];
      
        if (!tt) {
          throw new Error('Invalid ttml');
        }
      
        var defaultRateInfo = {
          frameRate: 30,
          subFrameRate: 1,
          frameRateMultiplier: 0,
          tickRate: 0
        };
        var rateInfo = Object.keys(defaultRateInfo).reduce(function (result, key) {
          result[key] = tt.getAttribute("ttp:" + key) || defaultRateInfo[key];
          return result;
        }, {});
        var trim = tt.getAttribute('xml:space') !== 'preserve';
        var styleElements = collectionToDictionary(getElementCollection(tt, 'styling', 'style'));
        var regionElements = collectionToDictionary(getElementCollection(tt, 'layout', 'region'));
        var cueElements = getElementCollection(tt, 'body', '[begin]');
        return [].map.call(cueElements, function (cueElement) {
          var cueText = getTextContent(cueElement, trim);
      
          if (!cueText || !cueElement.hasAttribute('begin')) {
            return null;
          }
      
          var startTime = parseTtmlTime(cueElement.getAttribute('begin'), rateInfo);
          var duration = parseTtmlTime(cueElement.getAttribute('dur'), rateInfo);
          var endTime = parseTtmlTime(cueElement.getAttribute('end'), rateInfo);
      
          if (startTime === null) {
            throw timestampParsingError(cueElement);
          }
      
          if (endTime === null) {
            if (duration === null) {
              throw timestampParsingError(cueElement);
            }
      
            endTime = startTime + duration;
          }
      
          var cue = new _vttcue__WEBPACK_IMPORTED_MODULE_2__["default"](startTime - syncTime, endTime - syncTime, cueText);
          cue.id = Object(_webvtt_parser__WEBPACK_IMPORTED_MODULE_5__["generateCueId"])(cue.startTime, cue.endTime, cue.text);
          var region = regionElements[cueElement.getAttribute('region')];
          var style = styleElements[cueElement.getAttribute('style')]; // TODO: Add regions to track and cue (origin and extend)
          // These values are hard-coded (for now) to simulate region settings in the demo
      
          cue.position = 10;
          cue.size = 80; // Apply styles to cue
      
          var styles = getTtmlStyles(region, style);
          var textAlign = styles.textAlign;
      
          if (textAlign) {
            // cue.positionAlign not settable in FF~2016
            var lineAlign = textAlignToLineAlign[textAlign];
      
            if (lineAlign) {
              cue.lineAlign = lineAlign;
            }
      
            cue.align = textAlign;
          }
      
          _extends(cue, styles);
      
          return cue;
        }).filter(function (cue) {
          return cue !== null;
        });
      }
      
      function getElementCollection(fromElement, parentName, childName) {
        var parent = fromElement.getElementsByTagName(parentName)[0];
      
        if (parent) {
          return [].slice.call(parent.querySelectorAll(childName));
        }
      
        return [];
      }
      
      function collectionToDictionary(elementsWithId) {
        return elementsWithId.reduce(function (dict, element) {
          var id = element.getAttribute('xml:id');
      
          if (id) {
            dict[id] = element;
          }
      
          return dict;
        }, {});
      }
      
      function getTextContent(element, trim) {
        return [].slice.call(element.childNodes).reduce(function (str, node, i) {
          var _node$childNodes;
      
          if (node.nodeName === 'br' && i) {
            return str + '\n';
          }
      
          if ((_node$childNodes = node.childNodes) !== null && _node$childNodes !== void 0 && _node$childNodes.length) {
            return getTextContent(node, trim);
          } else if (trim) {
            return str + node.textContent.trim().replace(/\s+/g, ' ');
          }
      
          return str + node.textContent;
        }, '');
      }
      
      function getTtmlStyles(region, style) {
        var ttsNs = 'http://www.w3.org/ns/ttml#styling';
        var styleAttributes = ['displayAlign', 'textAlign', 'color', 'backgroundColor', 'fontSize', 'fontFamily' // 'fontWeight',
        // 'lineHeight',
        // 'wrapOption',
        // 'fontStyle',
        // 'direction',
        // 'writingMode'
        ];
        return styleAttributes.reduce(function (styles, name) {
          var value = getAttributeNS(style, ttsNs, name) || getAttributeNS(region, ttsNs, name);
      
          if (value) {
            styles[name] = value;
          }
      
          return styles;
        }, {});
      }
      
      function getAttributeNS(element, ns, name) {
        return element.hasAttributeNS(ns, name) ? element.getAttributeNS(ns, name) : null;
      }
      
      function timestampParsingError(node) {
        return new Error("Could not parse ttml timestamp " + node);
      }
      
      function parseTtmlTime(timeAttributeValue, rateInfo) {
        if (!timeAttributeValue) {
          return null;
        }
      
        var seconds = Object(_vttparser__WEBPACK_IMPORTED_MODULE_1__["parseTimeStamp"])(timeAttributeValue);
      
        if (seconds === null) {
          if (HMSF_REGEX.test(timeAttributeValue)) {
            seconds = parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo);
          } else if (TIME_UNIT_REGEX.test(timeAttributeValue)) {
            seconds = parseTimeUnits(timeAttributeValue, rateInfo);
          }
        }
      
        return seconds;
      }
      
      function parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo) {
        var m = HMSF_REGEX.exec(timeAttributeValue);
        var frames = (m[4] | 0) + (m[5] | 0) / rateInfo.subFrameRate;
        return (m[1] | 0) * 3600 + (m[2] | 0) * 60 + (m[3] | 0) + frames / rateInfo.frameRate;
      }
      
      function parseTimeUnits(timeAttributeValue, rateInfo) {
        var m = TIME_UNIT_REGEX.exec(timeAttributeValue);
        var value = Number(m[1]);
        var unit = m[2];
      
        switch (unit) {
          case 'h':
            return value * 3600;
      
          case 'm':
            return value * 60;
      
          case 'ms':
            return value * 1000;
      
          case 'f':
            return value / rateInfo.frameRate;
      
          case 't':
            return value / rateInfo.tickRate;
        }
      
        return value;
      }
      
      /***/ }),
      
      /***/ "./src/utils/logger.ts":
      /*!*****************************!*\
        !*** ./src/utils/logger.ts ***!
        \*****************************/
      /*! exports provided: enableLogs, logger */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableLogs", function() { return enableLogs; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logger", function() { return logger; });
      var noop = function noop() {};
      
      var fakeLogger = {
        trace: noop,
        debug: noop,
        log: noop,
        warn: noop,
        info: noop,
        error: noop
      };
      var exportedLogger = fakeLogger; // let lastCallTime;
      // function formatMsgWithTimeInfo(type, msg) {
      //   const now = Date.now();
      //   const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';
      //   lastCallTime = now;
      //   msg = (new Date(now)).toISOString() + ' | [' +  type + '] > ' + msg + ' ( ' + diff + ' ms )';
      //   return msg;
      // }
      
      function consolePrintFn(type) {
        var func = self.console[type];
      
        if (func) {
          return func.bind(self.console, "[" + type + "] >");
        }
      
        return noop;
      }
      
      function exportLoggerFunctions(debugConfig) {
        for (var _len = arguments.length, functions = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
          functions[_key - 1] = arguments[_key];
        }
      
        functions.forEach(function (type) {
          exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type);
        });
      }
      
      function enableLogs(debugConfig) {
        // check that console is available
        if (self.console && debugConfig === true || typeof debugConfig === 'object') {
          exportLoggerFunctions(debugConfig, // Remove out from list here to hard-disable a log-level
          // 'trace',
          'debug', 'log', 'info', 'warn', 'error'); // Some browsers don't allow to use bind on console object anyway
          // fallback to default if needed
      
          try {
            exportedLogger.log();
          } catch (e) {
            exportedLogger = fakeLogger;
          }
        } else {
          exportedLogger = fakeLogger;
        }
      }
      var logger = exportedLogger;
      
      /***/ }),
      
      /***/ "./src/utils/mediakeys-helper.ts":
      /*!***************************************!*\
        !*** ./src/utils/mediakeys-helper.ts ***!
        \***************************************/
      /*! exports provided: KeySystems, requestMediaKeySystemAccess */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeySystems", function() { return KeySystems; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "requestMediaKeySystemAccess", function() { return requestMediaKeySystemAccess; });
      /**
       * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess
       */
      var KeySystems;
      
      (function (KeySystems) {
        KeySystems["WIDEVINE"] = "com.widevine.alpha";
        KeySystems["PLAYREADY"] = "com.microsoft.playready";
      })(KeySystems || (KeySystems = {}));
      
      var requestMediaKeySystemAccess = function () {
        if (typeof self !== 'undefined' && self.navigator && self.navigator.requestMediaKeySystemAccess) {
          return self.navigator.requestMediaKeySystemAccess.bind(self.navigator);
        } else {
          return null;
        }
      }();
      
      
      
      /***/ }),
      
      /***/ "./src/utils/mediasource-helper.ts":
      /*!*****************************************!*\
        !*** ./src/utils/mediasource-helper.ts ***!
        \*****************************************/
      /*! exports provided: getMediaSource */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getMediaSource", function() { return getMediaSource; });
      /**
       * MediaSource helper
       */
      function getMediaSource() {
        return self.MediaSource || self.WebKitMediaSource;
      }
      
      /***/ }),
      
      /***/ "./src/utils/mp4-tools.ts":
      /*!********************************!*\
        !*** ./src/utils/mp4-tools.ts ***!
        \********************************/
      /*! exports provided: bin2str, readUint16, readUint32, writeUint32, findBox, parseSegmentIndex, parseInitSegment, getStartDTS, getDuration, computeRawDurationFromSamples, offsetStartDTS, segmentValidRange, appendUint8Array */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bin2str", function() { return bin2str; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "readUint16", function() { return readUint16; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "readUint32", function() { return readUint32; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "writeUint32", function() { return writeUint32; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findBox", function() { return findBox; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseSegmentIndex", function() { return parseSegmentIndex; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseInitSegment", function() { return parseInitSegment; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getStartDTS", function() { return getStartDTS; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDuration", function() { return getDuration; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "computeRawDurationFromSamples", function() { return computeRawDurationFromSamples; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "offsetStartDTS", function() { return offsetStartDTS; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "segmentValidRange", function() { return segmentValidRange; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appendUint8Array", function() { return appendUint8Array; });
      /* harmony import */ var _typed_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./typed-array */ "./src/utils/typed-array.ts");
      /* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts");
      
      
      var UINT32_MAX = Math.pow(2, 32) - 1;
      var push = [].push;
      function bin2str(data) {
        return String.fromCharCode.apply(null, data);
      }
      function readUint16(buffer, offset) {
        if ('data' in buffer) {
          offset += buffer.start;
          buffer = buffer.data;
        }
      
        var val = buffer[offset] << 8 | buffer[offset + 1];
        return val < 0 ? 65536 + val : val;
      }
      function readUint32(buffer, offset) {
        if ('data' in buffer) {
          offset += buffer.start;
          buffer = buffer.data;
        }
      
        var val = buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3];
        return val < 0 ? 4294967296 + val : val;
      }
      function writeUint32(buffer, offset, value) {
        if ('data' in buffer) {
          offset += buffer.start;
          buffer = buffer.data;
        }
      
        buffer[offset] = value >> 24;
        buffer[offset + 1] = value >> 16 & 0xff;
        buffer[offset + 2] = value >> 8 & 0xff;
        buffer[offset + 3] = value & 0xff;
      } // Find the data for a box specified by its path
      
      function findBox(input, path) {
        var results = [];
      
        if (!path.length) {
          // short-circuit the search for empty paths
          return results;
        }
      
        var data;
        var start;
        var end;
      
        if ('data' in input) {
          data = input.data;
          start = input.start;
          end = input.end;
        } else {
          data = input;
          start = 0;
          end = data.byteLength;
        }
      
        for (var i = start; i < end;) {
          var size = readUint32(data, i);
          var type = bin2str(data.subarray(i + 4, i + 8));
          var endbox = size > 1 ? i + size : end;
      
          if (type === path[0]) {
            if (path.length === 1) {
              // this is the end of the path and we've found the box we were
              // looking for
              results.push({
                data: data,
                start: i + 8,
                end: endbox
              });
            } else {
              // recursively search for the next box along the path
              var subresults = findBox({
                data: data,
                start: i + 8,
                end: endbox
              }, path.slice(1));
      
              if (subresults.length) {
                push.apply(results, subresults);
              }
            }
          }
      
          i = endbox;
        } // we've finished searching all of data
      
      
        return results;
      }
      function parseSegmentIndex(initSegment) {
        var moovBox = findBox(initSegment, ['moov']);
        var moov = moovBox[0];
        var moovEndOffset = moov ? moov.end : null; // we need this in case we need to chop of garbage of the end of current data
      
        var sidxBox = findBox(initSegment, ['sidx']);
      
        if (!sidxBox || !sidxBox[0]) {
          return null;
        }
      
        var references = [];
        var sidx = sidxBox[0];
        var version = sidx.data[0]; // set initial offset, we skip the reference ID (not needed)
      
        var index = version === 0 ? 8 : 16;
        var timescale = readUint32(sidx, index);
        index += 4; // TODO: parse earliestPresentationTime and firstOffset
        // usually zero in our case
      
        var earliestPresentationTime = 0;
        var firstOffset = 0;
      
        if (version === 0) {
          index += 8;
        } else {
          index += 16;
        } // skip reserved
      
      
        index += 2;
        var startByte = sidx.end + firstOffset;
        var referencesCount = readUint16(sidx, index);
        index += 2;
      
        for (var i = 0; i < referencesCount; i++) {
          var referenceIndex = index;
          var referenceInfo = readUint32(sidx, referenceIndex);
          referenceIndex += 4;
          var referenceSize = referenceInfo & 0x7fffffff;
          var referenceType = (referenceInfo & 0x80000000) >>> 31;
      
          if (referenceType === 1) {
            // eslint-disable-next-line no-console
            console.warn('SIDX has hierarchical references (not supported)');
            return null;
          }
      
          var subsegmentDuration = readUint32(sidx, referenceIndex);
          referenceIndex += 4;
          references.push({
            referenceSize: referenceSize,
            subsegmentDuration: subsegmentDuration,
            // unscaled
            info: {
              duration: subsegmentDuration / timescale,
              start: startByte,
              end: startByte + referenceSize - 1
            }
          });
          startByte += referenceSize; // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits
          // for |sapDelta|.
      
          referenceIndex += 4; // skip to next ref
      
          index = referenceIndex;
        }
      
        return {
          earliestPresentationTime: earliestPresentationTime,
          timescale: timescale,
          version: version,
          referencesCount: referencesCount,
          references: references,
          moovEndOffset: moovEndOffset
        };
      }
      /**
       * Parses an MP4 initialization segment and extracts stream type and
       * timescale values for any declared tracks. Timescale values indicate the
       * number of clock ticks per second to assume for time-based values
       * elsewhere in the MP4.
       *
       * To determine the start time of an MP4, you need two pieces of
       * information: the timescale unit and the earliest base media decode
       * time. Multiple timescales can be specified within an MP4 but the
       * base media decode time is always expressed in the timescale from
       * the media header box for the track:
       * ```
       * moov > trak > mdia > mdhd.timescale
       * moov > trak > mdia > hdlr
       * ```
       * @param initSegment {Uint8Array} the bytes of the init segment
       * @return {InitData} a hash of track type to timescale values or null if
       * the init segment is malformed.
       */
      
      function parseInitSegment(initSegment) {
        var result = [];
        var traks = findBox(initSegment, ['moov', 'trak']);
      
        for (var i = 0; i < traks.length; i++) {
          var trak = traks[i];
          var tkhd = findBox(trak, ['tkhd'])[0];
      
          if (tkhd) {
            var version = tkhd.data[tkhd.start];
      
            var _index = version === 0 ? 12 : 20;
      
            var trackId = readUint32(tkhd, _index);
            var mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
      
            if (mdhd) {
              version = mdhd.data[mdhd.start];
              _index = version === 0 ? 12 : 20;
              var timescale = readUint32(mdhd, _index);
              var hdlr = findBox(trak, ['mdia', 'hdlr'])[0];
      
              if (hdlr) {
                var hdlrType = bin2str(hdlr.data.subarray(hdlr.start + 8, hdlr.start + 12));
                var type = {
                  soun: _loader_fragment__WEBPACK_IMPORTED_MODULE_1__["ElementaryStreamTypes"].AUDIO,
                  vide: _loader_fragment__WEBPACK_IMPORTED_MODULE_1__["ElementaryStreamTypes"].VIDEO
                }[hdlrType];
      
                if (type) {
                  // Parse codec details
                  var stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
                  var codec = void 0;
      
                  if (stsd) {
                    codec = bin2str(stsd.data.subarray(stsd.start + 12, stsd.start + 16)); // TODO: Parse codec details to be able to build MIME type.
                    // stsd.start += 8;
                    // const codecBox = findBox(stsd, [codec])[0];
                    // if (codecBox) {
                    //   TODO: Codec parsing support for avc1, mp4a, hevc, av01...
                    // }
                  }
      
                  result[trackId] = {
                    timescale: timescale,
                    type: type
                  };
                  result[type] = {
                    timescale: timescale,
                    id: trackId,
                    codec: codec
                  };
                }
              }
            }
          }
        }
      
        var trex = findBox(initSegment, ['moov', 'mvex', 'trex']);
        trex.forEach(function (trex) {
          var trackId = readUint32(trex, 4);
          var track = result[trackId];
      
          if (track) {
            track.default = {
              duration: readUint32(trex, 12),
              flags: readUint32(trex, 20)
            };
          }
        });
        return result;
      }
      /**
       * Determine the base media decode start time, in seconds, for an MP4
       * fragment. If multiple fragments are specified, the earliest time is
       * returned.
       *
       * The base media decode time can be parsed from track fragment
       * metadata:
       * ```
       * moof > traf > tfdt.baseMediaDecodeTime
       * ```
       * It requires the timescale value from the mdhd to interpret.
       *
       * @param initData {InitData} a hash of track type to timescale values
       * @param fmp4 {Uint8Array} the bytes of the mp4 fragment
       * @return {number} the earliest base media decode start time for the
       * fragment, in seconds
       */
      
      function getStartDTS(initData, fmp4) {
        // we need info from two children of each track fragment box
        return findBox(fmp4, ['moof', 'traf']).reduce(function (result, traf) {
          var tfdt = findBox(traf, ['tfdt'])[0];
          var version = tfdt.data[tfdt.start];
          var start = findBox(traf, ['tfhd']).reduce(function (result, tfhd) {
            // get the track id from the tfhd
            var id = readUint32(tfhd, 4);
            var track = initData[id];
      
            if (track) {
              var baseTime = readUint32(tfdt, 4);
      
              if (version === 1) {
                baseTime *= Math.pow(2, 32);
                baseTime += readUint32(tfdt, 8);
              } // assume a 90kHz clock if no timescale was specified
      
      
              var scale = track.timescale || 90e3; // convert base time to seconds
      
              var startTime = baseTime / scale;
      
              if (isFinite(startTime) && (result === null || startTime < result)) {
                return startTime;
              }
            }
      
            return result;
          }, null);
      
          if (start !== null && isFinite(start) && (result === null || start < result)) {
            return start;
          }
      
          return result;
        }, null) || 0;
      }
      /*
        For Reference:
        aligned(8) class TrackFragmentHeaderBox
                 extends FullBox(‘tfhd’, 0, tf_flags){
           unsigned int(32)  track_ID;
           // all the following are optional fields
           unsigned int(64)  base_data_offset;
           unsigned int(32)  sample_description_index;
           unsigned int(32)  default_sample_duration;
           unsigned int(32)  default_sample_size;
           unsigned int(32)  default_sample_flags
        }
       */
      
      function getDuration(data, initData) {
        var rawDuration = 0;
        var videoDuration = 0;
        var audioDuration = 0;
        var trafs = findBox(data, ['moof', 'traf']);
      
        for (var i = 0; i < trafs.length; i++) {
          var traf = trafs[i]; // There is only one tfhd & trun per traf
          // This is true for CMAF style content, and we should perhaps check the ftyp
          // and only look for a single trun then, but for ISOBMFF we should check
          // for multiple track runs.
      
          var tfhd = findBox(traf, ['tfhd'])[0]; // get the track id from the tfhd
      
          var id = readUint32(tfhd, 4);
          var track = initData[id];
      
          if (!track) {
            continue;
          }
      
          var trackDefault = track.default;
          var tfhdFlags = readUint32(tfhd, 0) | (trackDefault === null || trackDefault === void 0 ? void 0 : trackDefault.flags);
          var sampleDuration = trackDefault === null || trackDefault === void 0 ? void 0 : trackDefault.duration;
      
          if (tfhdFlags & 0x000008) {
            // 0x000008 indicates the presence of the default_sample_duration field
            if (tfhdFlags & 0x000002) {
              // 0x000002 indicates the presence of the sample_description_index field, which precedes default_sample_duration
              // If present, the default_sample_duration exists at byte offset 12
              sampleDuration = readUint32(tfhd, 12);
            } else {
              // Otherwise, the duration is at byte offset 8
              sampleDuration = readUint32(tfhd, 8);
            }
          } // assume a 90kHz clock if no timescale was specified
      
      
          var timescale = track.timescale || 90e3;
          var truns = findBox(traf, ['trun']);
      
          for (var j = 0; j < truns.length; j++) {
            if (sampleDuration) {
              var sampleCount = readUint32(truns[j], 4);
              rawDuration = sampleDuration * sampleCount;
            } else {
              rawDuration = computeRawDurationFromSamples(truns[j]);
            }
      
            if (track.type === _loader_fragment__WEBPACK_IMPORTED_MODULE_1__["ElementaryStreamTypes"].VIDEO) {
              videoDuration += rawDuration / timescale;
            } else if (track.type === _loader_fragment__WEBPACK_IMPORTED_MODULE_1__["ElementaryStreamTypes"].AUDIO) {
              audioDuration += rawDuration / timescale;
            }
          }
        }
      
        if (videoDuration === 0 && audioDuration === 0) {
          // If duration samples are not available in the traf use sidx subsegment_duration
          var sidx = parseSegmentIndex(data);
      
          if (sidx !== null && sidx !== void 0 && sidx.references) {
            return sidx.references.reduce(function (dur, ref) {
              return dur + ref.info.duration || 0;
            }, 0);
          }
        }
      
        if (videoDuration) {
          return videoDuration;
        }
      
        return audioDuration;
      }
      /*
        For Reference:
        aligned(8) class TrackRunBox
                 extends FullBox(‘trun’, version, tr_flags) {
           unsigned int(32)  sample_count;
           // the following are optional fields
           signed int(32) data_offset;
           unsigned int(32)  first_sample_flags;
           // all fields in the following array are optional
           {
              unsigned int(32)  sample_duration;
              unsigned int(32)  sample_size;
              unsigned int(32)  sample_flags
              if (version == 0)
                 { unsigned int(32)
              else
                 { signed int(32)
           }[ sample_count ]
        }
       */
      
      function computeRawDurationFromSamples(trun) {
        var flags = readUint32(trun, 0); // Flags are at offset 0, non-optional sample_count is at offset 4. Therefore we start 8 bytes in.
        // Each field is an int32, which is 4 bytes
      
        var offset = 8; // data-offset-present flag
      
        if (flags & 0x000001) {
          offset += 4;
        } // first-sample-flags-present flag
      
      
        if (flags & 0x000004) {
          offset += 4;
        }
      
        var duration = 0;
        var sampleCount = readUint32(trun, 4);
      
        for (var i = 0; i < sampleCount; i++) {
          // sample-duration-present flag
          if (flags & 0x000100) {
            var sampleDuration = readUint32(trun, offset);
            duration += sampleDuration;
            offset += 4;
          } // sample-size-present flag
      
      
          if (flags & 0x000200) {
            offset += 4;
          } // sample-flags-present flag
      
      
          if (flags & 0x000400) {
            offset += 4;
          } // sample-composition-time-offsets-present flag
      
      
          if (flags & 0x000800) {
            offset += 4;
          }
        }
      
        return duration;
      }
      function offsetStartDTS(initData, fmp4, timeOffset) {
        findBox(fmp4, ['moof', 'traf']).forEach(function (traf) {
          findBox(traf, ['tfhd']).forEach(function (tfhd) {
            // get the track id from the tfhd
            var id = readUint32(tfhd, 4);
            var track = initData[id];
      
            if (!track) {
              return;
            } // assume a 90kHz clock if no timescale was specified
      
      
            var timescale = track.timescale || 90e3; // get the base media decode time from the tfdt
      
            findBox(traf, ['tfdt']).forEach(function (tfdt) {
              var version = tfdt.data[tfdt.start];
              var baseMediaDecodeTime = readUint32(tfdt, 4);
      
              if (version === 0) {
                writeUint32(tfdt, 4, baseMediaDecodeTime - timeOffset * timescale);
              } else {
                baseMediaDecodeTime *= Math.pow(2, 32);
                baseMediaDecodeTime += readUint32(tfdt, 8);
                baseMediaDecodeTime -= timeOffset * timescale;
                baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);
                var upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
                var lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
                writeUint32(tfdt, 4, upper);
                writeUint32(tfdt, 8, lower);
              }
            });
          });
        });
      } // TODO: Check if the last moof+mdat pair is part of the valid range
      
      function segmentValidRange(data) {
        var segmentedRange = {
          valid: null,
          remainder: null
        };
        var moofs = findBox(data, ['moof']);
      
        if (!moofs) {
          return segmentedRange;
        } else if (moofs.length < 2) {
          segmentedRange.remainder = data;
          return segmentedRange;
        }
      
        var last = moofs[moofs.length - 1]; // Offset by 8 bytes; findBox offsets the start by as much
      
        segmentedRange.valid = Object(_typed_array__WEBPACK_IMPORTED_MODULE_0__["sliceUint8"])(data, 0, last.start - 8);
        segmentedRange.remainder = Object(_typed_array__WEBPACK_IMPORTED_MODULE_0__["sliceUint8"])(data, last.start - 8);
        return segmentedRange;
      }
      function appendUint8Array(data1, data2) {
        var temp = new Uint8Array(data1.length + data2.length);
        temp.set(data1);
        temp.set(data2, data1.length);
        return temp;
      }
      
      /***/ }),
      
      /***/ "./src/utils/output-filter.ts":
      /*!************************************!*\
        !*** ./src/utils/output-filter.ts ***!
        \************************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return OutputFilter; });
      var OutputFilter = /*#__PURE__*/function () {
        function OutputFilter(timelineController, trackName) {
          this.timelineController = void 0;
          this.cueRanges = [];
          this.trackName = void 0;
          this.startTime = null;
          this.endTime = null;
          this.screen = null;
          this.timelineController = timelineController;
          this.trackName = trackName;
        }
      
        var _proto = OutputFilter.prototype;
      
        _proto.dispatchCue = function dispatchCue() {
          if (this.startTime === null) {
            return;
          }
      
          this.timelineController.addCues(this.trackName, this.startTime, this.endTime, this.screen, this.cueRanges);
          this.startTime = null;
        };
      
        _proto.newCue = function newCue(startTime, endTime, screen) {
          if (this.startTime === null || this.startTime > startTime) {
            this.startTime = startTime;
          }
      
          this.endTime = endTime;
          this.screen = screen;
          this.timelineController.createCaptionsTrack(this.trackName);
        };
      
        _proto.reset = function reset() {
          this.cueRanges = [];
        };
      
        return OutputFilter;
      }();
      
      
      
      /***/ }),
      
      /***/ "./src/utils/texttrack-utils.ts":
      /*!**************************************!*\
        !*** ./src/utils/texttrack-utils.ts ***!
        \**************************************/
      /*! exports provided: sendAddTrackEvent, addCueToTrack, clearCurrentCues, removeCuesInRange, getCuesInRange */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sendAddTrackEvent", function() { return sendAddTrackEvent; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addCueToTrack", function() { return addCueToTrack; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearCurrentCues", function() { return clearCurrentCues; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeCuesInRange", function() { return removeCuesInRange; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getCuesInRange", function() { return getCuesInRange; });
      /* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./logger */ "./src/utils/logger.ts");
      
      function sendAddTrackEvent(track, videoEl) {
        var event;
      
        try {
          event = new Event('addtrack');
        } catch (err) {
          // for IE11
          event = document.createEvent('Event');
          event.initEvent('addtrack', false, false);
        }
      
        event.track = track;
        videoEl.dispatchEvent(event);
      }
      function addCueToTrack(track, cue) {
        // Sometimes there are cue overlaps on segmented vtts so the same
        // cue can appear more than once in different vtt files.
        // This avoid showing duplicated cues with same timecode and text.
        var mode = track.mode;
      
        if (mode === 'disabled') {
          track.mode = 'hidden';
        }
      
        if (track.cues && !track.cues.getCueById(cue.id)) {
          try {
            track.addCue(cue);
      
            if (!track.cues.getCueById(cue.id)) {
              throw new Error("addCue is failed for: " + cue);
            }
          } catch (err) {
            _logger__WEBPACK_IMPORTED_MODULE_0__["logger"].debug("[texttrack-utils]: " + err);
            var textTrackCue = new self.TextTrackCue(cue.startTime, cue.endTime, cue.text);
            textTrackCue.id = cue.id;
            track.addCue(textTrackCue);
          }
        }
      
        if (mode === 'disabled') {
          track.mode = mode;
        }
      }
      function clearCurrentCues(track) {
        // When track.mode is disabled, track.cues will be null.
        // To guarantee the removal of cues, we need to temporarily
        // change the mode to hidden
        var mode = track.mode;
      
        if (mode === 'disabled') {
          track.mode = 'hidden';
        }
      
        if (track.cues) {
          for (var i = track.cues.length; i--;) {
            track.removeCue(track.cues[i]);
          }
        }
      
        if (mode === 'disabled') {
          track.mode = mode;
        }
      }
      function removeCuesInRange(track, start, end) {
        var mode = track.mode;
      
        if (mode === 'disabled') {
          track.mode = 'hidden';
        }
      
        if (track.cues && track.cues.length > 0) {
          var cues = getCuesInRange(track.cues, start, end);
      
          for (var i = 0; i < cues.length; i++) {
            track.removeCue(cues[i]);
          }
        }
      
        if (mode === 'disabled') {
          track.mode = mode;
        }
      } // Find first cue starting after given time.
      // Modified version of binary search O(log(n)).
      
      function getFirstCueIndexAfterTime(cues, time) {
        // If first cue starts after time, start there
        if (time < cues[0].startTime) {
          return 0;
        } // If the last cue ends before time there is no overlap
      
      
        var len = cues.length - 1;
      
        if (time > cues[len].endTime) {
          return -1;
        }
      
        var left = 0;
        var right = len;
      
        while (left <= right) {
          var mid = Math.floor((right + left) / 2);
      
          if (time < cues[mid].startTime) {
            right = mid - 1;
          } else if (time > cues[mid].startTime && left < len) {
            left = mid + 1;
          } else {
            // If it's not lower or higher, it must be equal.
            return mid;
          }
        } // At this point, left and right have swapped.
        // No direct match was found, left or right element must be the closest. Check which one has the smallest diff.
      
      
        return cues[left].startTime - time < time - cues[right].startTime ? left : right;
      }
      
      function getCuesInRange(cues, start, end) {
        var cuesFound = [];
        var firstCueInRange = getFirstCueIndexAfterTime(cues, start);
      
        if (firstCueInRange > -1) {
          for (var i = firstCueInRange, len = cues.length; i < len; i++) {
            var cue = cues[i];
      
            if (cue.startTime >= start && cue.endTime <= end) {
              cuesFound.push(cue);
            } else if (cue.startTime > end) {
              return cuesFound;
            }
          }
        }
      
        return cuesFound;
      }
      
      /***/ }),
      
      /***/ "./src/utils/time-ranges.ts":
      /*!**********************************!*\
        !*** ./src/utils/time-ranges.ts ***!
        \**********************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /**
       *  TimeRanges to string helper
       */
      var TimeRanges = {
        toString: function toString(r) {
          var log = '';
          var len = r.length;
      
          for (var i = 0; i < len; i++) {
            log += '[' + r.start(i).toFixed(3) + ',' + r.end(i).toFixed(3) + ']';
          }
      
          return log;
        }
      };
      /* harmony default export */ __webpack_exports__["default"] = (TimeRanges);
      
      /***/ }),
      
      /***/ "./src/utils/timescale-conversion.ts":
      /*!*******************************************!*\
        !*** ./src/utils/timescale-conversion.ts ***!
        \*******************************************/
      /*! exports provided: toTimescaleFromBase, toTimescaleFromScale, toMsFromMpegTsClock, toMpegTsClockFromTimescale */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toTimescaleFromBase", function() { return toTimescaleFromBase; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toTimescaleFromScale", function() { return toTimescaleFromScale; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toMsFromMpegTsClock", function() { return toMsFromMpegTsClock; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toMpegTsClockFromTimescale", function() { return toMpegTsClockFromTimescale; });
      var MPEG_TS_CLOCK_FREQ_HZ = 90000;
      function toTimescaleFromBase(value, destScale, srcBase, round) {
        if (srcBase === void 0) {
          srcBase = 1;
        }
      
        if (round === void 0) {
          round = false;
        }
      
        var result = value * destScale * srcBase; // equivalent to `(value * scale) / (1 / base)`
      
        return round ? Math.round(result) : result;
      }
      function toTimescaleFromScale(value, destScale, srcScale, round) {
        if (srcScale === void 0) {
          srcScale = 1;
        }
      
        if (round === void 0) {
          round = false;
        }
      
        return toTimescaleFromBase(value, destScale, 1 / srcScale, round);
      }
      function toMsFromMpegTsClock(value, round) {
        if (round === void 0) {
          round = false;
        }
      
        return toTimescaleFromBase(value, 1000, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);
      }
      function toMpegTsClockFromTimescale(value, srcScale) {
        if (srcScale === void 0) {
          srcScale = 1;
        }
      
        return toTimescaleFromBase(value, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale);
      }
      
      /***/ }),
      
      /***/ "./src/utils/typed-array.ts":
      /*!**********************************!*\
        !*** ./src/utils/typed-array.ts ***!
        \**********************************/
      /*! exports provided: sliceUint8 */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sliceUint8", function() { return sliceUint8; });
      function sliceUint8(array, start, end) {
        // @ts-expect-error This polyfills IE11 usage of Uint8Array slice.
        // It always exists in the TypeScript definition so fails, but it fails at runtime on IE11.
        return Uint8Array.prototype.slice ? array.slice(start, end) : new Uint8Array(Array.prototype.slice.call(array, start, end));
      }
      
      /***/ }),
      
      /***/ "./src/utils/vttcue.ts":
      /*!*****************************!*\
        !*** ./src/utils/vttcue.ts ***!
        \*****************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /**
       * Copyright 2013 vtt.js Contributors
       *
       * Licensed under the Apache License, Version 2.0 (the 'License');
       * you may not use this file except in compliance with the License.
       * You may obtain a copy of the License at
       *
       *   http://www.apache.org/licenses/LICENSE-2.0
       *
       * Unless required by applicable law or agreed to in writing, software
       * distributed under the License is distributed on an 'AS IS' BASIS,
       * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       * See the License for the specific language governing permissions and
       * limitations under the License.
       */
      /* harmony default export */ __webpack_exports__["default"] = ((function () {
        if (typeof self !== 'undefined' && self.VTTCue) {
          return self.VTTCue;
        }
      
        var AllowedDirections = ['', 'lr', 'rl'];
        var AllowedAlignments = ['start', 'middle', 'end', 'left', 'right'];
      
        function isAllowedValue(allowed, value) {
          if (typeof value !== 'string') {
            return false;
          } // necessary for assuring the generic conforms to the Array interface
      
      
          if (!Array.isArray(allowed)) {
            return false;
          } // reset the type so that the next narrowing works well
      
      
          var lcValue = value.toLowerCase(); // use the allow list to narrow the type to a specific subset of strings
      
          if (~allowed.indexOf(lcValue)) {
            return lcValue;
          }
      
          return false;
        }
      
        function findDirectionSetting(value) {
          return isAllowedValue(AllowedDirections, value);
        }
      
        function findAlignSetting(value) {
          return isAllowedValue(AllowedAlignments, value);
        }
      
        function extend(obj) {
          for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
            rest[_key - 1] = arguments[_key];
          }
      
          var i = 1;
      
          for (; i < arguments.length; i++) {
            var cobj = arguments[i];
      
            for (var p in cobj) {
              obj[p] = cobj[p];
            }
          }
      
          return obj;
        }
      
        function VTTCue(startTime, endTime, text) {
          var cue = this;
          var baseObj = {
            enumerable: true
          };
          /**
           * Shim implementation specific properties. These properties are not in
           * the spec.
           */
          // Lets us know when the VTTCue's data has changed in such a way that we need
          // to recompute its display state. This lets us compute its display state
          // lazily.
      
          cue.hasBeenReset = false;
          /**
           * VTTCue and TextTrackCue properties
           * http://dev.w3.org/html5/webvtt/#vttcue-interface
           */
      
          var _id = '';
          var _pauseOnExit = false;
          var _startTime = startTime;
          var _endTime = endTime;
          var _text = text;
          var _region = null;
          var _vertical = '';
          var _snapToLines = true;
          var _line = 'auto';
          var _lineAlign = 'start';
          var _position = 50;
          var _positionAlign = 'middle';
          var _size = 50;
          var _align = 'middle';
          Object.defineProperty(cue, 'id', extend({}, baseObj, {
            get: function get() {
              return _id;
            },
            set: function set(value) {
              _id = '' + value;
            }
          }));
          Object.defineProperty(cue, 'pauseOnExit', extend({}, baseObj, {
            get: function get() {
              return _pauseOnExit;
            },
            set: function set(value) {
              _pauseOnExit = !!value;
            }
          }));
          Object.defineProperty(cue, 'startTime', extend({}, baseObj, {
            get: function get() {
              return _startTime;
            },
            set: function set(value) {
              if (typeof value !== 'number') {
                throw new TypeError('Start time must be set to a number.');
              }
      
              _startTime = value;
              this.hasBeenReset = true;
            }
          }));
          Object.defineProperty(cue, 'endTime', extend({}, baseObj, {
            get: function get() {
              return _endTime;
            },
            set: function set(value) {
              if (typeof value !== 'number') {
                throw new TypeError('End time must be set to a number.');
              }
      
              _endTime = value;
              this.hasBeenReset = true;
            }
          }));
          Object.defineProperty(cue, 'text', extend({}, baseObj, {
            get: function get() {
              return _text;
            },
            set: function set(value) {
              _text = '' + value;
              this.hasBeenReset = true;
            }
          })); // todo: implement VTTRegion polyfill?
      
          Object.defineProperty(cue, 'region', extend({}, baseObj, {
            get: function get() {
              return _region;
            },
            set: function set(value) {
              _region = value;
              this.hasBeenReset = true;
            }
          }));
          Object.defineProperty(cue, 'vertical', extend({}, baseObj, {
            get: function get() {
              return _vertical;
            },
            set: function set(value) {
              var setting = findDirectionSetting(value); // Have to check for false because the setting an be an empty string.
      
              if (setting === false) {
                throw new SyntaxError('An invalid or illegal string was specified.');
              }
      
              _vertical = setting;
              this.hasBeenReset = true;
            }
          }));
          Object.defineProperty(cue, 'snapToLines', extend({}, baseObj, {
            get: function get() {
              return _snapToLines;
            },
            set: function set(value) {
              _snapToLines = !!value;
              this.hasBeenReset = true;
            }
          }));
          Object.defineProperty(cue, 'line', extend({}, baseObj, {
            get: function get() {
              return _line;
            },
            set: function set(value) {
              if (typeof value !== 'number' && value !== 'auto') {
                throw new SyntaxError('An invalid number or illegal string was specified.');
              }
      
              _line = value;
              this.hasBeenReset = true;
            }
          }));
          Object.defineProperty(cue, 'lineAlign', extend({}, baseObj, {
            get: function get() {
              return _lineAlign;
            },
            set: function set(value) {
              var setting = findAlignSetting(value);
      
              if (!setting) {
                throw new SyntaxError('An invalid or illegal string was specified.');
              }
      
              _lineAlign = setting;
              this.hasBeenReset = true;
            }
          }));
          Object.defineProperty(cue, 'position', extend({}, baseObj, {
            get: function get() {
              return _position;
            },
            set: function set(value) {
              if (value < 0 || value > 100) {
                throw new Error('Position must be between 0 and 100.');
              }
      
              _position = value;
              this.hasBeenReset = true;
            }
          }));
          Object.defineProperty(cue, 'positionAlign', extend({}, baseObj, {
            get: function get() {
              return _positionAlign;
            },
            set: function set(value) {
              var setting = findAlignSetting(value);
      
              if (!setting) {
                throw new SyntaxError('An invalid or illegal string was specified.');
              }
      
              _positionAlign = setting;
              this.hasBeenReset = true;
            }
          }));
          Object.defineProperty(cue, 'size', extend({}, baseObj, {
            get: function get() {
              return _size;
            },
            set: function set(value) {
              if (value < 0 || value > 100) {
                throw new Error('Size must be between 0 and 100.');
              }
      
              _size = value;
              this.hasBeenReset = true;
            }
          }));
          Object.defineProperty(cue, 'align', extend({}, baseObj, {
            get: function get() {
              return _align;
            },
            set: function set(value) {
              var setting = findAlignSetting(value);
      
              if (!setting) {
                throw new SyntaxError('An invalid or illegal string was specified.');
              }
      
              _align = setting;
              this.hasBeenReset = true;
            }
          }));
          /**
           * Other <track> spec defined properties
           */
          // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state
      
          cue.displayState = undefined;
        }
        /**
         * VTTCue methods
         */
      
      
        VTTCue.prototype.getCueAsHTML = function () {
          // Assume WebVTT.convertCueToDOMTree is on the global.
          var WebVTT = self.WebVTT;
          return WebVTT.convertCueToDOMTree(self, this.text);
        }; // this is a polyfill hack
      
      
        return VTTCue;
      })());
      
      /***/ }),
      
      /***/ "./src/utils/vttparser.ts":
      /*!********************************!*\
        !*** ./src/utils/vttparser.ts ***!
        \********************************/
      /*! exports provided: parseTimeStamp, fixLineBreaks, VTTParser */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseTimeStamp", function() { return parseTimeStamp; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fixLineBreaks", function() { return fixLineBreaks; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VTTParser", function() { return VTTParser; });
      /* harmony import */ var _vttcue__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./vttcue */ "./src/utils/vttcue.ts");
      /*
       * Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js
       */
      
      
      var StringDecoder = /*#__PURE__*/function () {
        function StringDecoder() {}
      
        var _proto = StringDecoder.prototype;
      
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        _proto.decode = function decode(data, options) {
          if (!data) {
            return '';
          }
      
          if (typeof data !== 'string') {
            throw new Error('Error - expected string data.');
          }
      
          return decodeURIComponent(encodeURIComponent(data));
        };
      
        return StringDecoder;
      }(); // Try to parse input as a time stamp.
      
      
      function parseTimeStamp(input) {
        function computeSeconds(h, m, s, f) {
          return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + parseFloat(f || 0);
        }
      
        var m = input.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);
      
        if (!m) {
          return null;
        }
      
        if (parseFloat(m[2]) > 59) {
          // Timestamp takes the form of [hours]:[minutes].[milliseconds]
          // First position is hours as it's over 59.
          return computeSeconds(m[2], m[3], 0, m[4]);
        } // Timestamp takes the form of [hours (optional)]:[minutes]:[seconds].[milliseconds]
      
      
        return computeSeconds(m[1], m[2], m[3], m[4]);
      } // A settings object holds key/value pairs and will ignore anything but the first
      // assignment to a specific key.
      
      var Settings = /*#__PURE__*/function () {
        function Settings() {
          this.values = Object.create(null);
        }
      
        var _proto2 = Settings.prototype;
      
        // Only accept the first assignment to any key.
        _proto2.set = function set(k, v) {
          if (!this.get(k) && v !== '') {
            this.values[k] = v;
          }
        } // Return the value for a key, or a default value.
        // If 'defaultKey' is passed then 'dflt' is assumed to be an object with
        // a number of possible default values as properties where 'defaultKey' is
        // the key of the property that will be chosen; otherwise it's assumed to be
        // a single value.
        ;
      
        _proto2.get = function get(k, dflt, defaultKey) {
          if (defaultKey) {
            return this.has(k) ? this.values[k] : dflt[defaultKey];
          }
      
          return this.has(k) ? this.values[k] : dflt;
        } // Check whether we have a value for a key.
        ;
      
        _proto2.has = function has(k) {
          return k in this.values;
        } // Accept a setting if its one of the given alternatives.
        ;
      
        _proto2.alt = function alt(k, v, a) {
          for (var n = 0; n < a.length; ++n) {
            if (v === a[n]) {
              this.set(k, v);
              break;
            }
          }
        } // Accept a setting if its a valid (signed) integer.
        ;
      
        _proto2.integer = function integer(k, v) {
          if (/^-?\d+$/.test(v)) {
            // integer
            this.set(k, parseInt(v, 10));
          }
        } // Accept a setting if its a valid percentage.
        ;
      
        _proto2.percent = function percent(k, v) {
          if (/^([\d]{1,3})(\.[\d]*)?%$/.test(v)) {
            var percent = parseFloat(v);
      
            if (percent >= 0 && percent <= 100) {
              this.set(k, percent);
              return true;
            }
          }
      
          return false;
        };
      
        return Settings;
      }(); // Helper function to parse input into groups separated by 'groupDelim', and
      // interpret each group as a key/value pair separated by 'keyValueDelim'.
      
      
      function parseOptions(input, callback, keyValueDelim, groupDelim) {
        var groups = groupDelim ? input.split(groupDelim) : [input];
      
        for (var i in groups) {
          if (typeof groups[i] !== 'string') {
            continue;
          }
      
          var kv = groups[i].split(keyValueDelim);
      
          if (kv.length !== 2) {
            continue;
          }
      
          var _k = kv[0];
          var _v = kv[1];
          callback(_k, _v);
        }
      }
      
      var defaults = new _vttcue__WEBPACK_IMPORTED_MODULE_0__["default"](0, 0, ''); // 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244
      //  Safari doesn't yet support this change, but FF and Chrome do.
      
      var center = defaults.align === 'middle' ? 'middle' : 'center';
      
      function parseCue(input, cue, regionList) {
        // Remember the original input if we need to throw an error.
        var oInput = input; // 4.1 WebVTT timestamp
      
        function consumeTimeStamp() {
          var ts = parseTimeStamp(input);
      
          if (ts === null) {
            throw new Error('Malformed timestamp: ' + oInput);
          } // Remove time stamp from input.
      
      
          input = input.replace(/^[^\sa-zA-Z-]+/, '');
          return ts;
        } // 4.4.2 WebVTT cue settings
      
      
        function consumeCueSettings(input, cue) {
          var settings = new Settings();
          parseOptions(input, function (k, v) {
            var vals;
      
            switch (k) {
              case 'region':
                // Find the last region we parsed with the same region id.
                for (var i = regionList.length - 1; i >= 0; i--) {
                  if (regionList[i].id === v) {
                    settings.set(k, regionList[i].region);
                    break;
                  }
                }
      
                break;
      
              case 'vertical':
                settings.alt(k, v, ['rl', 'lr']);
                break;
      
              case 'line':
                vals = v.split(',');
                settings.integer(k, vals[0]);
      
                if (settings.percent(k, vals[0])) {
                  settings.set('snapToLines', false);
                }
      
                settings.alt(k, vals[0], ['auto']);
      
                if (vals.length === 2) {
                  settings.alt('lineAlign', vals[1], ['start', center, 'end']);
                }
      
                break;
      
              case 'position':
                vals = v.split(',');
                settings.percent(k, vals[0]);
      
                if (vals.length === 2) {
                  settings.alt('positionAlign', vals[1], ['start', center, 'end', 'line-left', 'line-right', 'auto']);
                }
      
                break;
      
              case 'size':
                settings.percent(k, v);
                break;
      
              case 'align':
                settings.alt(k, v, ['start', center, 'end', 'left', 'right']);
                break;
            }
          }, /:/, /\s/); // Apply default values for any missing fields.
      
          cue.region = settings.get('region', null);
          cue.vertical = settings.get('vertical', '');
          var line = settings.get('line', 'auto');
      
          if (line === 'auto' && defaults.line === -1) {
            // set numeric line number for Safari
            line = -1;
          }
      
          cue.line = line;
          cue.lineAlign = settings.get('lineAlign', 'start');
          cue.snapToLines = settings.get('snapToLines', true);
          cue.size = settings.get('size', 100);
          cue.align = settings.get('align', center);
          var position = settings.get('position', 'auto');
      
          if (position === 'auto' && defaults.position === 50) {
            // set numeric position for Safari
            position = cue.align === 'start' || cue.align === 'left' ? 0 : cue.align === 'end' || cue.align === 'right' ? 100 : 50;
          }
      
          cue.position = position;
        }
      
        function skipWhitespace() {
          input = input.replace(/^\s+/, '');
        } // 4.1 WebVTT cue timings.
      
      
        skipWhitespace();
        cue.startTime = consumeTimeStamp(); // (1) collect cue start time
      
        skipWhitespace();
      
        if (input.substr(0, 3) !== '-->') {
          // (3) next characters must match '-->'
          throw new Error("Malformed time stamp (time stamps must be separated by '-->'): " + oInput);
        }
      
        input = input.substr(3);
        skipWhitespace();
        cue.endTime = consumeTimeStamp(); // (5) collect cue end time
        // 4.1 WebVTT cue settings list.
      
        skipWhitespace();
        consumeCueSettings(input, cue);
      }
      
      function fixLineBreaks(input) {
        return input.replace(/<br(?: \/)?>/gi, '\n');
      }
      var VTTParser = /*#__PURE__*/function () {
        function VTTParser() {
          this.state = 'INITIAL';
          this.buffer = '';
          this.decoder = new StringDecoder();
          this.regionList = [];
          this.cue = null;
          this.oncue = void 0;
          this.onparsingerror = void 0;
          this.onflush = void 0;
        }
      
        var _proto3 = VTTParser.prototype;
      
        _proto3.parse = function parse(data) {
          var _this = this; // If there is no data then we won't decode it, but will just try to parse
          // whatever is in buffer already. This may occur in circumstances, for
          // example when flush() is called.
      
      
          if (data) {
            // Try to decode the data that we received.
            _this.buffer += _this.decoder.decode(data, {
              stream: true
            });
          }
      
          function collectNextLine() {
            var buffer = _this.buffer;
            var pos = 0;
            buffer = fixLineBreaks(buffer);
      
            while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') {
              ++pos;
            }
      
            var line = buffer.substr(0, pos); // Advance the buffer early in case we fail below.
      
            if (buffer[pos] === '\r') {
              ++pos;
            }
      
            if (buffer[pos] === '\n') {
              ++pos;
            }
      
            _this.buffer = buffer.substr(pos);
            return line;
          } // 3.2 WebVTT metadata header syntax
      
      
          function parseHeader(input) {
            parseOptions(input, function (k, v) {// switch (k) {
              // case 'region':
              // 3.3 WebVTT region metadata header syntax
              // console.log('parse region', v);
              // parseRegion(v);
              // break;
              // }
            }, /:/);
          } // 5.1 WebVTT file parsing.
      
      
          try {
            var line = '';
      
            if (_this.state === 'INITIAL') {
              // We can't start parsing until we have the first line.
              if (!/\r\n|\n/.test(_this.buffer)) {
                return this;
              }
      
              line = collectNextLine(); // strip of UTF-8 BOM if any
              // https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8
      
              var m = line.match(/^()?WEBVTT([ \t].*)?$/);
      
              if (!m || !m[0]) {
                throw new Error('Malformed WebVTT signature.');
              }
      
              _this.state = 'HEADER';
            }
      
            var alreadyCollectedLine = false;
      
            while (_this.buffer) {
              // We can't parse a line until we have the full line.
              if (!/\r\n|\n/.test(_this.buffer)) {
                return this;
              }
      
              if (!alreadyCollectedLine) {
                line = collectNextLine();
              } else {
                alreadyCollectedLine = false;
              }
      
              switch (_this.state) {
                case 'HEADER':
                  // 13-18 - Allow a header (metadata) under the WEBVTT line.
                  if (/:/.test(line)) {
                    parseHeader(line);
                  } else if (!line) {
                    // An empty line terminates the header and starts the body (cues).
                    _this.state = 'ID';
                  }
      
                  continue;
      
                case 'NOTE':
                  // Ignore NOTE blocks.
                  if (!line) {
                    _this.state = 'ID';
                  }
      
                  continue;
      
                case 'ID':
                  // Check for the start of NOTE blocks.
                  if (/^NOTE($|[ \t])/.test(line)) {
                    _this.state = 'NOTE';
                    break;
                  } // 19-29 - Allow any number of line terminators, then initialize new cue values.
      
      
                  if (!line) {
                    continue;
                  }
      
                  _this.cue = new _vttcue__WEBPACK_IMPORTED_MODULE_0__["default"](0, 0, '');
                  _this.state = 'CUE'; // 30-39 - Check if self line contains an optional identifier or timing data.
      
                  if (line.indexOf('-->') === -1) {
                    _this.cue.id = line;
                    continue;
                  }
      
                // Process line as start of a cue.
      
                /* falls through */
      
                case 'CUE':
                  // 40 - Collect cue timings and settings.
                  if (!_this.cue) {
                    _this.state = 'BADCUE';
                    continue;
                  }
      
                  try {
                    parseCue(line, _this.cue, _this.regionList);
                  } catch (e) {
                    // In case of an error ignore rest of the cue.
                    _this.cue = null;
                    _this.state = 'BADCUE';
                    continue;
                  }
      
                  _this.state = 'CUETEXT';
                  continue;
      
                case 'CUETEXT':
                  {
                    var hasSubstring = line.indexOf('-->') !== -1; // 34 - If we have an empty line then report the cue.
                    // 35 - If we have the special substring '-->' then report the cue,
                    // but do not collect the line as we need to process the current
                    // one as a new cue.
      
                    if (!line || hasSubstring && (alreadyCollectedLine = true)) {
                      // We are done parsing self cue.
                      if (_this.oncue && _this.cue) {
                        _this.oncue(_this.cue);
                      }
      
                      _this.cue = null;
                      _this.state = 'ID';
                      continue;
                    }
      
                    if (_this.cue === null) {
                      continue;
                    }
      
                    if (_this.cue.text) {
                      _this.cue.text += '\n';
                    }
      
                    _this.cue.text += line;
                  }
                  continue;
      
                case 'BADCUE':
                  // 54-62 - Collect and discard the remaining cue.
                  if (!line) {
                    _this.state = 'ID';
                  }
      
              }
            }
          } catch (e) {
            // If we are currently parsing a cue, report what we have.
            if (_this.state === 'CUETEXT' && _this.cue && _this.oncue) {
              _this.oncue(_this.cue);
            }
      
            _this.cue = null; // Enter BADWEBVTT state if header was not parsed correctly otherwise
            // another exception occurred so enter BADCUE state.
      
            _this.state = _this.state === 'INITIAL' ? 'BADWEBVTT' : 'BADCUE';
          }
      
          return this;
        };
      
        _proto3.flush = function flush() {
          var _this = this;
      
          try {
            // Finish decoding the stream.
            // _this.buffer += _this.decoder.decode();
            // Synthesize the end of the current cue or region.
            if (_this.cue || _this.state === 'HEADER') {
              _this.buffer += '\n\n';
      
              _this.parse();
            } // If we've flushed, parsed, and we're still on the INITIAL state then
            // that means we don't have enough of the stream to parse the first
            // line.
      
      
            if (_this.state === 'INITIAL' || _this.state === 'BADWEBVTT') {
              throw new Error('Malformed WebVTT signature.');
            }
          } catch (e) {
            if (_this.onparsingerror) {
              _this.onparsingerror(e);
            }
          }
      
          if (_this.onflush) {
            _this.onflush();
          }
      
          return this;
        };
      
        return VTTParser;
      }();
      
      /***/ }),
      
      /***/ "./src/utils/webvtt-parser.ts":
      /*!************************************!*\
        !*** ./src/utils/webvtt-parser.ts ***!
        \************************************/
      /*! exports provided: generateCueId, parseWebVTT */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "generateCueId", function() { return generateCueId; });
      /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseWebVTT", function() { return parseWebVTT; });
      /* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
      /* harmony import */ var _vttparser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./vttparser */ "./src/utils/vttparser.ts");
      /* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
      /* harmony import */ var _timescale_conversion__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./timescale-conversion */ "./src/utils/timescale-conversion.ts");
      /* harmony import */ var _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../remux/mp4-remuxer */ "./src/remux/mp4-remuxer.ts");
      
      
      
      
      
      
      
      
      var LINEBREAKS = /\r\n|\n\r|\n|\r/g; // String.prototype.startsWith is not supported in IE11
      
      var startsWith = function startsWith(inputString, searchString, position) {
        if (position === void 0) {
          position = 0;
        }
      
        return inputString.substr(position, searchString.length) === searchString;
      };
      
      var cueString2millis = function cueString2millis(timeString) {
        var ts = parseInt(timeString.substr(-3));
        var secs = parseInt(timeString.substr(-6, 2));
        var mins = parseInt(timeString.substr(-9, 2));
        var hours = timeString.length > 9 ? parseInt(timeString.substr(0, timeString.indexOf(':'))) : 0;
      
        if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(ts) || !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(secs) || !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(mins) || !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(hours)) {
          throw Error("Malformed X-TIMESTAMP-MAP: Local:" + timeString);
        }
      
        ts += 1000 * secs;
        ts += 60 * 1000 * mins;
        ts += 60 * 60 * 1000 * hours;
        return ts;
      }; // From https://github.com/darkskyapp/string-hash
      
      
      var hash = function hash(text) {
        var hash = 5381;
        var i = text.length;
      
        while (i) {
          hash = hash * 33 ^ text.charCodeAt(--i);
        }
      
        return (hash >>> 0).toString();
      }; // Create a unique hash id for a cue based on start/end times and text.
      // This helps timeline-controller to avoid showing repeated captions.
      
      
      function generateCueId(startTime, endTime, text) {
        return hash(startTime.toString()) + hash(endTime.toString()) + hash(text);
      }
      
      var calculateOffset = function calculateOffset(vttCCs, cc, presentationTime) {
        var currCC = vttCCs[cc];
        var prevCC = vttCCs[currCC.prevCC]; // This is the first discontinuity or cues have been processed since the last discontinuity
        // Offset = current discontinuity time
      
        if (!prevCC || !prevCC.new && currCC.new) {
          vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;
          currCC.new = false;
          return;
        } // There have been discontinuities since cues were last parsed.
        // Offset = time elapsed
      
      
        while ((_prevCC = prevCC) !== null && _prevCC !== void 0 && _prevCC.new) {
          var _prevCC;
      
          vttCCs.ccOffset += currCC.start - prevCC.start;
          currCC.new = false;
          currCC = prevCC;
          prevCC = vttCCs[currCC.prevCC];
        }
      
        vttCCs.presentationOffset = presentationTime;
      };
      
      function parseWebVTT(vttByteArray, initPTS, timescale, vttCCs, cc, timeOffset, callBack, errorCallBack) {
        var parser = new _vttparser__WEBPACK_IMPORTED_MODULE_1__["VTTParser"](); // Convert byteArray into string, replacing any somewhat exotic linefeeds with "\n", then split on that character.
        // Uint8Array.prototype.reduce is not implemented in IE11
      
        var vttLines = Object(_demux_id3__WEBPACK_IMPORTED_MODULE_2__["utf8ArrayToStr"])(new Uint8Array(vttByteArray)).trim().replace(LINEBREAKS, '\n').split('\n');
        var cues = [];
        var initPTS90Hz = Object(_timescale_conversion__WEBPACK_IMPORTED_MODULE_3__["toMpegTsClockFromTimescale"])(initPTS, timescale);
        var cueTime = '00:00.000';
        var timestampMapMPEGTS = 0;
        var timestampMapLOCAL = 0;
        var parsingError;
        var inHeader = true;
        var timestampMap = false;
      
        parser.oncue = function (cue) {
          // Adjust cue timing; clamp cues to start no earlier than - and drop cues that don't end after - 0 on timeline.
          var currCC = vttCCs[cc];
          var cueOffset = vttCCs.ccOffset; // Calculate subtitle PTS offset
      
          var webVttMpegTsMapOffset = (timestampMapMPEGTS - initPTS90Hz) / 90000; // Update offsets for new discontinuities
      
          if (currCC !== null && currCC !== void 0 && currCC.new) {
            if (timestampMapLOCAL !== undefined) {
              // When local time is provided, offset = discontinuity start time - local time
              cueOffset = vttCCs.ccOffset = currCC.start;
            } else {
              calculateOffset(vttCCs, cc, webVttMpegTsMapOffset);
            }
          }
      
          if (webVttMpegTsMapOffset) {
            // If we have MPEGTS, offset = presentation time + discontinuity offset
            cueOffset = webVttMpegTsMapOffset - vttCCs.presentationOffset;
          }
      
          if (timestampMap) {
            var duration = cue.endTime - cue.startTime;
            var startTime = Object(_remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_4__["normalizePts"])((cue.startTime + cueOffset - timestampMapLOCAL) * 90000, timeOffset * 90000) / 90000;
            cue.startTime = startTime;
            cue.endTime = startTime + duration;
          } //trim trailing webvtt block whitespaces
      
      
          var text = cue.text.trim(); // Fix encoding of special characters
      
          cue.text = decodeURIComponent(encodeURIComponent(text)); // If the cue was not assigned an id from the VTT file (line above the content), create one.
      
          if (!cue.id) {
            cue.id = generateCueId(cue.startTime, cue.endTime, text);
          }
      
          if (cue.endTime > 0) {
            cues.push(cue);
          }
        };
      
        parser.onparsingerror = function (error) {
          parsingError = error;
        };
      
        parser.onflush = function () {
          if (parsingError) {
            errorCallBack(parsingError);
            return;
          }
      
          callBack(cues);
        }; // Go through contents line by line.
      
      
        vttLines.forEach(function (line) {
          if (inHeader) {
            // Look for X-TIMESTAMP-MAP in header.
            if (startsWith(line, 'X-TIMESTAMP-MAP=')) {
              // Once found, no more are allowed anyway, so stop searching.
              inHeader = false;
              timestampMap = true; // Extract LOCAL and MPEGTS.
      
              line.substr(16).split(',').forEach(function (timestamp) {
                if (startsWith(timestamp, 'LOCAL:')) {
                  cueTime = timestamp.substr(6);
                } else if (startsWith(timestamp, 'MPEGTS:')) {
                  timestampMapMPEGTS = parseInt(timestamp.substr(7));
                }
              });
      
              try {
                // Convert cue time to seconds
                timestampMapLOCAL = cueString2millis(cueTime) / 1000;
              } catch (error) {
                timestampMap = false;
                parsingError = error;
              } // Return without parsing X-TIMESTAMP-MAP line.
      
      
              return;
            } else if (line === '') {
              inHeader = false;
            }
          } // Parse line by default.
      
      
          parser.parse(line + '\n');
        });
        parser.flush();
      }
      
      /***/ }),
      
      /***/ "./src/utils/xhr-loader.ts":
      /*!*********************************!*\
        !*** ./src/utils/xhr-loader.ts ***!
        \*********************************/
      /*! exports provided: default */
      /***/ (function(module, __webpack_exports__, __webpack_require__) {
      
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      /* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
      /* harmony import */ var _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../loader/load-stats */ "./src/loader/load-stats.ts");
      
      
      var AGE_HEADER_LINE_REGEX = /^age:\s*[\d.]+\s*$/m;
      
      var XhrLoader = /*#__PURE__*/function () {
        function XhrLoader(config
        /* HlsConfig */
        ) {
          this.xhrSetup = void 0;
          this.requestTimeout = void 0;
          this.retryTimeout = void 0;
          this.retryDelay = void 0;
          this.config = null;
          this.callbacks = null;
          this.context = void 0;
          this.loader = null;
          this.stats = void 0;
          this.xhrSetup = config ? config.xhrSetup : null;
          this.stats = new _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__["LoadStats"]();
          this.retryDelay = 0;
        }
      
        var _proto = XhrLoader.prototype;
      
        _proto.destroy = function destroy() {
          this.callbacks = null;
          this.abortInternal();
          this.loader = null;
          this.config = null;
        };
      
        _proto.abortInternal = function abortInternal() {
          var loader = this.loader;
          self.clearTimeout(this.requestTimeout);
          self.clearTimeout(this.retryTimeout);
      
          if (loader) {
            loader.onreadystatechange = null;
            loader.onprogress = null;
      
            if (loader.readyState !== 4) {
              this.stats.aborted = true;
              loader.abort();
            }
          }
        };
      
        _proto.abort = function abort() {
          var _this$callbacks;
      
          this.abortInternal();
      
          if ((_this$callbacks = this.callbacks) !== null && _this$callbacks !== void 0 && _this$callbacks.onAbort) {
            this.callbacks.onAbort(this.stats, this.context, this.loader);
          }
        };
      
        _proto.load = function load(context, config, callbacks) {
          if (this.stats.loading.start) {
            throw new Error('Loader can only be used once.');
          }
      
          this.stats.loading.start = self.performance.now();
          this.context = context;
          this.config = config;
          this.callbacks = callbacks;
          this.retryDelay = config.retryDelay;
          this.loadInternal();
        };
      
        _proto.loadInternal = function loadInternal() {
          var config = this.config,
              context = this.context;
      
          if (!config) {
            return;
          }
      
          var xhr = this.loader = new self.XMLHttpRequest();
          var stats = this.stats;
          stats.loading.first = 0;
          stats.loaded = 0;
          var xhrSetup = this.xhrSetup;
      
          try {
            if (xhrSetup) {
              try {
                xhrSetup(xhr, context.url);
              } catch (e) {
                // fix xhrSetup: (xhr, url) => {xhr.setRequestHeader("Content-Language", "test");}
                // not working, as xhr.setRequestHeader expects xhr.readyState === OPEN
                xhr.open('GET', context.url, true);
                xhrSetup(xhr, context.url);
              }
            }
      
            if (!xhr.readyState) {
              xhr.open('GET', context.url, true);
            }
      
            var headers = this.context.headers;
      
            if (headers) {
              for (var header in headers) {
                xhr.setRequestHeader(header, headers[header]);
              }
            }
          } catch (e) {
            // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
            this.callbacks.onError({
              code: xhr.status,
              text: e.message
            }, context, xhr);
            return;
          }
      
          if (context.rangeEnd) {
            xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1));
          }
      
          xhr.onreadystatechange = this.readystatechange.bind(this);
          xhr.onprogress = this.loadprogress.bind(this);
          xhr.responseType = context.responseType; // setup timeout before we perform request
      
          self.clearTimeout(this.requestTimeout);
          this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout);
          xhr.send();
        };
      
        _proto.readystatechange = function readystatechange() {
          var context = this.context,
              xhr = this.loader,
              stats = this.stats;
      
          if (!context || !xhr) {
            return;
          }
      
          var readyState = xhr.readyState;
          var config = this.config; // don't proceed if xhr has been aborted
      
          if (stats.aborted) {
            return;
          } // >= HEADERS_RECEIVED
      
      
          if (readyState >= 2) {
            // clear xhr timeout and rearm it if readyState less than 4
            self.clearTimeout(this.requestTimeout);
      
            if (stats.loading.first === 0) {
              stats.loading.first = Math.max(self.performance.now(), stats.loading.start);
            }
      
            if (readyState === 4) {
              xhr.onreadystatechange = null;
              xhr.onprogress = null;
              var status = xhr.status; // http status between 200 to 299 are all successful
      
              if (status >= 200 && status < 300) {
                stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
                var data;
                var len;
      
                if (context.responseType === 'arraybuffer') {
                  data = xhr.response;
                  len = data.byteLength;
                } else {
                  data = xhr.responseText;
                  len = data.length;
                }
      
                stats.loaded = stats.total = len;
      
                if (!this.callbacks) {
                  return;
                }
      
                var onProgress = this.callbacks.onProgress;
      
                if (onProgress) {
                  onProgress(stats, context, data, xhr);
                }
      
                if (!this.callbacks) {
                  return;
                }
      
                var response = {
                  url: xhr.responseURL,
                  data: data
                };
                this.callbacks.onSuccess(response, stats, context, xhr);
              } else {
                // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error
                if (stats.retry >= config.maxRetry || status >= 400 && status < 499) {
                  _utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].error(status + " while loading " + context.url);
                  this.callbacks.onError({
                    code: status,
                    text: xhr.statusText
                  }, context, xhr);
                } else {
                  // retry
                  _utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].warn(status + " while loading " + context.url + ", retrying in " + this.retryDelay + "..."); // abort and reset internal state
      
                  this.abortInternal();
                  this.loader = null; // schedule retry
      
                  self.clearTimeout(this.retryTimeout);
                  this.retryTimeout = self.setTimeout(this.loadInternal.bind(this), this.retryDelay); // set exponential backoff
      
                  this.retryDelay = Math.min(2 * this.retryDelay, config.maxRetryDelay);
                  stats.retry++;
                }
              }
            } else {
              // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet
              self.clearTimeout(this.requestTimeout);
              this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout);
            }
          }
        };
      
        _proto.loadtimeout = function loadtimeout() {
          _utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].warn("timeout while loading " + this.context.url);
          var callbacks = this.callbacks;
      
          if (callbacks) {
            this.abortInternal();
            callbacks.onTimeout(this.stats, this.context, this.loader);
          }
        };
      
        _proto.loadprogress = function loadprogress(event) {
          var stats = this.stats;
          stats.loaded = event.loaded;
      
          if (event.lengthComputable) {
            stats.total = event.total;
          }
        };
      
        _proto.getCacheAge = function getCacheAge() {
          var result = null;
      
          if (this.loader && AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())) {
            var ageHeader = this.loader.getResponseHeader('age');
            result = ageHeader ? parseFloat(ageHeader) : null;
          }
      
          return result;
        };
      
        return XhrLoader;
      }();
      
      /* harmony default export */ __webpack_exports__["default"] = (XhrLoader);
      
      /***/ })
      
      /******/ })["default"];
      });
      //# sourceMappingURL=hls.js.map
      
      /***/ }),
      
      /***/ "vHTk":
      /*!******************************************************!*\
        !*** ./src/components/PreviewAll/index.less?modules ***!
        \******************************************************/
      /*! no static exports found */
      /*! exports used: default */
      /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
      /***/ (function(module, exports, __webpack_require__) {
      
      // extracted by mini-css-extract-plugin
      module.exports = {"wrp":"wrp___z2l1F","bgBlack":"bgBlack___3ezfX","monaco":"monaco___1ypjT","darkBlue":"darkBlue___2ViJc","close":"close___3q-z4","embed":"embed___3dQqc"};
      
      /***/ }),
      
      /***/ "xTzM":
      /*!********************************************************!*\
        !*** ./src/assets/images/problemset/folder-opened.png ***!
        \********************************************************/
      /*! no static exports found */
      /*! exports used: default */
      /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
      /***/ (function(module, exports) {
      
      module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACYAAAAhCAYAAAC1ONkWAAAACXBIWXMAAAsSAAALEgHS3X78AAAAAXNSR0IArs4c6QAAAqRJREFUWEfNmE1o02AYx/9JzJaltHatZRVR5hSRXHYYbCpMmTIRexAsDD0L8+Rphx10DIQddvDowbugCB68iWOKDqeb7tKD+MGKA8vo3Nzch7ZLlsibJjPrkjRvE8hySUiej9/7/PO+b54wmqZx2IMH4wqWv3kIS19HIcTOgVUP1uRX2XmUVl+DxX10vHpX097FwBmMQC3kP4JtSFElYPiKefnLGJrSd+sFdAb70PMQm8o1KiirMR8D5FXv7pzwE5wyjuSJQbQ9KDiDvWwrgIu2eI8ckOXWWhGtvZ3OYONHlYBS0YeJtT52BnueVMAYMTVAvyZnu8N85mS/67kGMAygGQHNa/PcEC+6gCUqFUueBaQRgD9AP3IaD3kR+HQbWHqje9UG63wE7GumSVG/rbIMTF+nAKs/Fb2nd7An9MH9eEz3eaxY11O39dmYEUHNEgBTWY9gp575GT+97/srFrDl0QGo6h1Ai9JH8lFQNQXwJ3cG2Aab7T+CaPNcoEBUwY4Bje3/PSYvGRUjYGIkPDAmDjRdNsBUYBuMfI9968tBbJGoBhqksXgV4Iy3aPKi5R37nB1CJDUcZC6qWEIHIJ6puEx0W8EyEoR0Tt+7nPYwqkyGsdd4wn4gesMGjNwicrKN4cmZ7Af4RFXFCBiRk+PDkzN+oSLnDil1sIwERsjVo1ggPmIKSNyyATPl3PwbnpyHh6qWC3PIRE55Izw501lgZtBmryRylkvhyjn7wmETJ7NzvRienL/m9O5q9xcskXNjPhw5VRlQSsDvgh1YRsLaQnhybpWBP+sOzchU+1toWlfNnaB6ZaddN6zdEfE14ynymH0zMtNzGivfJ8CH1FpGjnc7d0lkhi7m76H8o5e2EL7sGW4E51eG3f/2+Mrgz3nPgv0D9Cc+LoUg84gAAAAASUVORK5CYII="
      
      /***/ })
      
      }]);