build/p__Competitions__Detail.c85...

140097 lines
4.8 MiB
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[8,4],{
/***/ "+KIT":
/*!************************************************************!*\
!*** ./src/pages/Competitions/components/Cla.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 = {"claBox":"claBox___sFYq2","box":"box___38lDe","title":"title___38Fxf","content":"content___1RxZB","rightBox":"rightBox___1UFtV","desc":"desc___1OMuK","formWrap":"formWrap___25Hs1"};
/***/ }),
/***/ "+d4F":
/*!*************************************************************!*\
!*** ./node_modules/@ant-design/icons/PaperClipOutlined.js ***!
\*************************************************************/
/*! no static exports found */
/*! exports used: default */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _PaperClipOutlined = _interopRequireDefault(__webpack_require__(/*! ./lib/icons/PaperClipOutlined */ "y3Yb"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _default = _PaperClipOutlined;
exports.default = _default;
module.exports = _default;
/***/ }),
/***/ "+uyH":
/*!***********************************************************!*\
!*** ./node_modules/@ant-design/react-slick/lib/track.js ***!
\***********************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "TqRt");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Track = void 0;
var _extends2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/extends */ "pVnL"));
var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "lwsE"));
var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "W8MJ"));
var _assertThisInitialized2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "PJYZ"));
var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "7W2i"));
var _createSuper2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createSuper */ "LQ03"));
var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "lSNA"));
var _objectSpread2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/objectSpread2 */ "3tO9"));
var _react = _interopRequireDefault(__webpack_require__(/*! react */ "q1tI"));
var _classnames = _interopRequireDefault(__webpack_require__(/*! classnames */ "TSYQ"));
var _innerSliderUtils = __webpack_require__(/*! ./utils/innerSliderUtils */ "3K4p");
// given specifications/props for a slide, fetch all the classes that need to be applied to the slide
var getSlideClasses = function getSlideClasses(spec) {
var slickActive, slickCenter, slickCloned;
var centerOffset, index;
if (spec.rtl) {
index = spec.slideCount - 1 - spec.index;
} else {
index = spec.index;
}
slickCloned = index < 0 || index >= spec.slideCount;
if (spec.centerMode) {
centerOffset = Math.floor(spec.slidesToShow / 2);
slickCenter = (index - spec.currentSlide) % spec.slideCount === 0;
if (index > spec.currentSlide - centerOffset - 1 && index <= spec.currentSlide + centerOffset) {
slickActive = true;
}
} else {
slickActive = spec.currentSlide <= index && index < spec.currentSlide + spec.slidesToShow;
}
var focusedSlide;
if (spec.targetSlide < 0) {
focusedSlide = spec.targetSlide + spec.slideCount;
} else if (spec.targetSlide >= spec.slideCount) {
focusedSlide = spec.targetSlide - spec.slideCount;
} else {
focusedSlide = spec.targetSlide;
}
var slickCurrent = index === focusedSlide;
return {
"slick-slide": true,
"slick-active": slickActive,
"slick-center": slickCenter,
"slick-cloned": slickCloned,
"slick-current": slickCurrent // dubious in case of RTL
};
};
var getSlideStyle = function getSlideStyle(spec) {
var style = {};
if (spec.variableWidth === undefined || spec.variableWidth === false) {
style.width = spec.slideWidth;
}
if (spec.fade) {
style.position = "relative";
if (spec.vertical) {
style.top = -spec.index * parseInt(spec.slideHeight);
} else {
style.left = -spec.index * parseInt(spec.slideWidth);
}
style.opacity = spec.currentSlide === spec.index ? 1 : 0;
if (spec.useCSS) {
style.transition = "opacity " + spec.speed + "ms " + spec.cssEase + ", " + "visibility " + spec.speed + "ms " + spec.cssEase;
}
}
return style;
};
var getKey = function getKey(child, fallbackKey) {
return child.key + "-" + fallbackKey;
};
var renderSlides = function renderSlides(spec) {
var key;
var slides = [];
var preCloneSlides = [];
var postCloneSlides = [];
var childrenCount = _react["default"].Children.count(spec.children);
var startIndex = (0, _innerSliderUtils.lazyStartIndex)(spec);
var endIndex = (0, _innerSliderUtils.lazyEndIndex)(spec);
_react["default"].Children.forEach(spec.children, function (elem, index) {
var child;
var childOnClickOptions = {
message: "children",
index: index,
slidesToScroll: spec.slidesToScroll,
currentSlide: spec.currentSlide
}; // in case of lazyLoad, whether or not we want to fetch the slide
if (!spec.lazyLoad || spec.lazyLoad && spec.lazyLoadedList.indexOf(index) >= 0) {
child = elem;
} else {
child = /*#__PURE__*/_react["default"].createElement("div", null);
}
var childStyle = getSlideStyle((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, spec), {}, {
index: index
}));
var slideClass = child.props.className || "";
var slideClasses = getSlideClasses((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, spec), {}, {
index: index
})); // push a cloned element of the desired slide
slides.push( /*#__PURE__*/_react["default"].cloneElement(child, {
key: "original" + getKey(child, index),
"data-index": index,
className: (0, _classnames["default"])(slideClasses, slideClass),
tabIndex: "-1",
"aria-hidden": !slideClasses["slick-active"],
style: (0, _objectSpread2["default"])((0, _objectSpread2["default"])({
outline: "none"
}, child.props.style || {}), childStyle),
onClick: function onClick(e) {
child.props && child.props.onClick && child.props.onClick(e);
if (spec.focusOnSelect) {
spec.focusOnSelect(childOnClickOptions);
}
}
})); // if slide needs to be precloned or postcloned
if (spec.infinite && spec.fade === false) {
var preCloneNo = childrenCount - index;
if (preCloneNo <= (0, _innerSliderUtils.getPreClones)(spec) && childrenCount !== spec.slidesToShow) {
key = -preCloneNo;
if (key >= startIndex) {
child = elem;
}
slideClasses = getSlideClasses((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, spec), {}, {
index: key
}));
preCloneSlides.push( /*#__PURE__*/_react["default"].cloneElement(child, {
key: "precloned" + getKey(child, key),
"data-index": key,
tabIndex: "-1",
className: (0, _classnames["default"])(slideClasses, slideClass),
"aria-hidden": !slideClasses["slick-active"],
style: (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, child.props.style || {}), childStyle),
onClick: function onClick(e) {
child.props && child.props.onClick && child.props.onClick(e);
if (spec.focusOnSelect) {
spec.focusOnSelect(childOnClickOptions);
}
}
}));
}
if (childrenCount !== spec.slidesToShow) {
key = childrenCount + index;
if (key < endIndex) {
child = elem;
}
slideClasses = getSlideClasses((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, spec), {}, {
index: key
}));
postCloneSlides.push( /*#__PURE__*/_react["default"].cloneElement(child, {
key: "postcloned" + getKey(child, key),
"data-index": key,
tabIndex: "-1",
className: (0, _classnames["default"])(slideClasses, slideClass),
"aria-hidden": !slideClasses["slick-active"],
style: (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, child.props.style || {}), childStyle),
onClick: function onClick(e) {
child.props && child.props.onClick && child.props.onClick(e);
if (spec.focusOnSelect) {
spec.focusOnSelect(childOnClickOptions);
}
}
}));
}
}
});
if (spec.rtl) {
return preCloneSlides.concat(slides, postCloneSlides).reverse();
} else {
return preCloneSlides.concat(slides, postCloneSlides);
}
};
var Track = /*#__PURE__*/function (_React$PureComponent) {
(0, _inherits2["default"])(Track, _React$PureComponent);
var _super = (0, _createSuper2["default"])(Track);
function Track() {
var _this;
(0, _classCallCheck2["default"])(this, Track);
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));
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "node", null);
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "handleRef", function (ref) {
_this.node = ref;
});
return _this;
}
(0, _createClass2["default"])(Track, [{
key: "render",
value: function render() {
var slides = renderSlides(this.props);
var _this$props = this.props,
onMouseEnter = _this$props.onMouseEnter,
onMouseOver = _this$props.onMouseOver,
onMouseLeave = _this$props.onMouseLeave;
var mouseEvents = {
onMouseEnter: onMouseEnter,
onMouseOver: onMouseOver,
onMouseLeave: onMouseLeave
};
return /*#__PURE__*/_react["default"].createElement("div", (0, _extends2["default"])({
ref: this.handleRef,
className: "slick-track",
style: this.props.trackStyle
}, mouseEvents), slides);
}
}]);
return Track;
}(_react["default"].PureComponent);
exports.Track = Track;
/***/ }),
/***/ "/GNS":
/*!*********************************************!*\
!*** ./src/assets/images/icons/search1.png ***!
\*********************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/search1.c4136dd4.png";
/***/ }),
/***/ "/zsF":
/*!*****************************************************!*\
!*** ./node_modules/antd/es/divider/style/index.js ***!
\*****************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _style_index_less__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../style/index.less */ "cIOH");
/* harmony import */ var _style_index_less__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_style_index_less__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _index_less__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./index.less */ "bE4E");
/* harmony import */ var _index_less__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_index_less__WEBPACK_IMPORTED_MODULE_1__);
/***/ }),
/***/ "0XgM":
/*!******************************************************!*\
!*** ./node_modules/antd/es/layout/style/index.less ***!
\******************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/***/ "19Vz":
/*!**************************************************************!*\
!*** ./node_modules/codemirror/addon/display/placeholder.js ***!
\**************************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (true) // CommonJS
mod(__webpack_require__(/*! ../../lib/codemirror */ "VrN/"));
else {}
})(function(CodeMirror) {
CodeMirror.defineOption("placeholder", "", function(cm, val, old) {
var prev = old && old != CodeMirror.Init;
if (val && !prev) {
cm.on("blur", onBlur);
cm.on("change", onChange);
cm.on("swapDoc", onChange);
CodeMirror.on(cm.getInputField(), "compositionupdate", cm.state.placeholderCompose = function() { onComposition(cm) })
onChange(cm);
} else if (!val && prev) {
cm.off("blur", onBlur);
cm.off("change", onChange);
cm.off("swapDoc", onChange);
CodeMirror.off(cm.getInputField(), "compositionupdate", cm.state.placeholderCompose)
clearPlaceholder(cm);
var wrapper = cm.getWrapperElement();
wrapper.className = wrapper.className.replace(" CodeMirror-empty", "");
}
if (val && !cm.hasFocus()) onBlur(cm);
});
function clearPlaceholder(cm) {
if (cm.state.placeholder) {
cm.state.placeholder.parentNode.removeChild(cm.state.placeholder);
cm.state.placeholder = null;
}
}
function setPlaceholder(cm) {
clearPlaceholder(cm);
var elt = cm.state.placeholder = document.createElement("pre");
elt.style.cssText = "height: 0; overflow: visible";
elt.style.direction = cm.getOption("direction");
elt.className = "CodeMirror-placeholder CodeMirror-line-like";
var placeHolder = cm.getOption("placeholder")
if (typeof placeHolder == "string") placeHolder = document.createTextNode(placeHolder)
elt.appendChild(placeHolder)
cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild);
}
function onComposition(cm) {
setTimeout(function() {
var empty = false, input = cm.getInputField()
if (input.nodeName == "TEXTAREA")
empty = !input.value
else if (cm.lineCount() == 1)
empty = !/[^\u200b]/.test(input.querySelector(".CodeMirror-line").textContent)
if (empty) setPlaceholder(cm)
else clearPlaceholder(cm)
}, 20)
}
function onBlur(cm) {
if (isEmpty(cm)) setPlaceholder(cm);
}
function onChange(cm) {
var wrapper = cm.getWrapperElement(), empty = isEmpty(cm);
wrapper.className = wrapper.className.replace(" CodeMirror-empty", "") + (empty ? " CodeMirror-empty" : "");
if (empty) setPlaceholder(cm);
else clearPlaceholder(cm);
}
function isEmpty(cm) {
return (cm.lineCount() === 1) && (cm.getLine(0) === "");
}
});
/***/ }),
/***/ "1Sn+":
/*!*************************************************!*\
!*** ./src/components/Header/search-input.less ***!
\*************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/***/ "1ZF9":
/*!*****************************************!*\
!*** ./src/assets/images/Authorize.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/Authorize.cc9c212f.png";
/***/ }),
/***/ "1eCo":
/*!*************************************************!*\
!*** ./node_modules/codemirror/mode/xml/xml.js ***!
\*************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (true) // CommonJS
mod(__webpack_require__(/*! ../../lib/codemirror */ "VrN/"));
else {}
})(function(CodeMirror) {
"use strict";
var htmlConfig = {
autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
'track': true, 'wbr': true, 'menuitem': true},
implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
'th': true, 'tr': true},
contextGrabbers: {
'dd': {'dd': true, 'dt': true},
'dt': {'dd': true, 'dt': true},
'li': {'li': true},
'option': {'option': true, 'optgroup': true},
'optgroup': {'optgroup': true},
'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
'rp': {'rp': true, 'rt': true},
'rt': {'rp': true, 'rt': true},
'tbody': {'tbody': true, 'tfoot': true},
'td': {'td': true, 'th': true},
'tfoot': {'tbody': true},
'th': {'td': true, 'th': true},
'thead': {'tbody': true, 'tfoot': true},
'tr': {'tr': true}
},
doNotIndent: {"pre": true},
allowUnquoted: true,
allowMissing: true,
caseFold: true
}
var xmlConfig = {
autoSelfClosers: {},
implicitlyClosed: {},
contextGrabbers: {},
doNotIndent: {},
allowUnquoted: false,
allowMissing: false,
allowMissingTagName: false,
caseFold: false
}
CodeMirror.defineMode("xml", function(editorConf, config_) {
var indentUnit = editorConf.indentUnit
var config = {}
var defaults = config_.htmlMode ? htmlConfig : xmlConfig
for (var prop in defaults) config[prop] = defaults[prop]
for (var prop in config_) config[prop] = config_[prop]
// Return variables for tokenizers
var type, setStyle;
function inText(stream, state) {
function chain(parser) {
state.tokenize = parser;
return parser(stream, state);
}
var ch = stream.next();
if (ch == "<") {
if (stream.eat("!")) {
if (stream.eat("[")) {
if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
else return null;
} else if (stream.match("--")) {
return chain(inBlock("comment", "-->"));
} else if (stream.match("DOCTYPE", true, true)) {
stream.eatWhile(/[\w\._\-]/);
return chain(doctype(1));
} else {
return null;
}
} else if (stream.eat("?")) {
stream.eatWhile(/[\w\._\-]/);
state.tokenize = inBlock("meta", "?>");
return "meta";
} else {
type = stream.eat("/") ? "closeTag" : "openTag";
state.tokenize = inTag;
return "tag bracket";
}
} else if (ch == "&") {
var ok;
if (stream.eat("#")) {
if (stream.eat("x")) {
ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
} else {
ok = stream.eatWhile(/[\d]/) && stream.eat(";");
}
} else {
ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
}
return ok ? "atom" : "error";
} else {
stream.eatWhile(/[^&<]/);
return null;
}
}
inText.isInText = true;
function inTag(stream, state) {
var ch = stream.next();
if (ch == ">" || (ch == "/" && stream.eat(">"))) {
state.tokenize = inText;
type = ch == ">" ? "endTag" : "selfcloseTag";
return "tag bracket";
} else if (ch == "=") {
type = "equals";
return null;
} else if (ch == "<") {
state.tokenize = inText;
state.state = baseState;
state.tagName = state.tagStart = null;
var next = state.tokenize(stream, state);
return next ? next + " tag error" : "tag error";
} else if (/[\'\"]/.test(ch)) {
state.tokenize = inAttribute(ch);
state.stringStartCol = stream.column();
return state.tokenize(stream, state);
} else {
stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);
return "word";
}
}
function inAttribute(quote) {
var closure = function(stream, state) {
while (!stream.eol()) {
if (stream.next() == quote) {
state.tokenize = inTag;
break;
}
}
return "string";
};
closure.isInAttribute = true;
return closure;
}
function inBlock(style, terminator) {
return function(stream, state) {
while (!stream.eol()) {
if (stream.match(terminator)) {
state.tokenize = inText;
break;
}
stream.next();
}
return style;
}
}
function doctype(depth) {
return function(stream, state) {
var ch;
while ((ch = stream.next()) != null) {
if (ch == "<") {
state.tokenize = doctype(depth + 1);
return state.tokenize(stream, state);
} else if (ch == ">") {
if (depth == 1) {
state.tokenize = inText;
break;
} else {
state.tokenize = doctype(depth - 1);
return state.tokenize(stream, state);
}
}
}
return "meta";
};
}
function Context(state, tagName, startOfLine) {
this.prev = state.context;
this.tagName = tagName;
this.indent = state.indented;
this.startOfLine = startOfLine;
if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent))
this.noIndent = true;
}
function popContext(state) {
if (state.context) state.context = state.context.prev;
}
function maybePopContext(state, nextTagName) {
var parentTagName;
while (true) {
if (!state.context) {
return;
}
parentTagName = state.context.tagName;
if (!config.contextGrabbers.hasOwnProperty(parentTagName) ||
!config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
return;
}
popContext(state);
}
}
function baseState(type, stream, state) {
if (type == "openTag") {
state.tagStart = stream.column();
return tagNameState;
} else if (type == "closeTag") {
return closeTagNameState;
} else {
return baseState;
}
}
function tagNameState(type, stream, state) {
if (type == "word") {
state.tagName = stream.current();
setStyle = "tag";
return attrState;
} else if (config.allowMissingTagName && type == "endTag") {
setStyle = "tag bracket";
return attrState(type, stream, state);
} else {
setStyle = "error";
return tagNameState;
}
}
function closeTagNameState(type, stream, state) {
if (type == "word") {
var tagName = stream.current();
if (state.context && state.context.tagName != tagName &&
config.implicitlyClosed.hasOwnProperty(state.context.tagName))
popContext(state);
if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) {
setStyle = "tag";
return closeState;
} else {
setStyle = "tag error";
return closeStateErr;
}
} else if (config.allowMissingTagName && type == "endTag") {
setStyle = "tag bracket";
return closeState(type, stream, state);
} else {
setStyle = "error";
return closeStateErr;
}
}
function closeState(type, _stream, state) {
if (type != "endTag") {
setStyle = "error";
return closeState;
}
popContext(state);
return baseState;
}
function closeStateErr(type, stream, state) {
setStyle = "error";
return closeState(type, stream, state);
}
function attrState(type, _stream, state) {
if (type == "word") {
setStyle = "attribute";
return attrEqState;
} else if (type == "endTag" || type == "selfcloseTag") {
var tagName = state.tagName, tagStart = state.tagStart;
state.tagName = state.tagStart = null;
if (type == "selfcloseTag" ||
config.autoSelfClosers.hasOwnProperty(tagName)) {
maybePopContext(state, tagName);
} else {
maybePopContext(state, tagName);
state.context = new Context(state, tagName, tagStart == state.indented);
}
return baseState;
}
setStyle = "error";
return attrState;
}
function attrEqState(type, stream, state) {
if (type == "equals") return attrValueState;
if (!config.allowMissing) setStyle = "error";
return attrState(type, stream, state);
}
function attrValueState(type, stream, state) {
if (type == "string") return attrContinuedState;
if (type == "word" && config.allowUnquoted) {setStyle = "string"; return attrState;}
setStyle = "error";
return attrState(type, stream, state);
}
function attrContinuedState(type, stream, state) {
if (type == "string") return attrContinuedState;
return attrState(type, stream, state);
}
return {
startState: function(baseIndent) {
var state = {tokenize: inText,
state: baseState,
indented: baseIndent || 0,
tagName: null, tagStart: null,
context: null}
if (baseIndent != null) state.baseIndent = baseIndent
return state
},
token: function(stream, state) {
if (!state.tagName && stream.sol())
state.indented = stream.indentation();
if (stream.eatSpace()) return null;
type = null;
var style = state.tokenize(stream, state);
if ((style || type) && style != "comment") {
setStyle = null;
state.state = state.state(type || style, stream, state);
if (setStyle)
style = setStyle == "error" ? style + " error" : setStyle;
}
return style;
},
indent: function(state, textAfter, fullLine) {
var context = state.context;
// Indent multi-line strings (e.g. css).
if (state.tokenize.isInAttribute) {
if (state.tagStart == state.indented)
return state.stringStartCol + 1;
else
return state.indented + indentUnit;
}
if (context && context.noIndent) return CodeMirror.Pass;
if (state.tokenize != inTag && state.tokenize != inText)
return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
// Indent the starts of attribute names.
if (state.tagName) {
if (config.multilineTagIndentPastTag !== false)
return state.tagStart + state.tagName.length + 2;
else
return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1);
}
if (config.alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
var tagAfter = textAfter && /^<(\/)?([\w_:\.-]*)/.exec(textAfter);
if (tagAfter && tagAfter[1]) { // Closing tag spotted
while (context) {
if (context.tagName == tagAfter[2]) {
context = context.prev;
break;
} else if (config.implicitlyClosed.hasOwnProperty(context.tagName)) {
context = context.prev;
} else {
break;
}
}
} else if (tagAfter) { // Opening tag spotted
while (context) {
var grabbers = config.contextGrabbers[context.tagName];
if (grabbers && grabbers.hasOwnProperty(tagAfter[2]))
context = context.prev;
else
break;
}
}
while (context && context.prev && !context.startOfLine)
context = context.prev;
if (context) return context.indent + indentUnit;
else return state.baseIndent || 0;
},
electricInput: /<\/[\s\w:]+>$/,
blockCommentStart: "<!--",
blockCommentEnd: "-->",
configuration: config.htmlMode ? "html" : "xml",
helperType: config.htmlMode ? "html" : "xml",
skipAttribute: function(state) {
if (state.state == attrValueState)
state.state = attrState
},
xmlCurrentTag: function(state) {
return state.tagName ? {name: state.tagName, close: state.type == "closeTag"} : null
},
xmlCurrentContext: function(state) {
var context = []
for (var cx = state.context; cx; cx = cx.prev)
if (cx.tagName) context.push(cx.tagName)
return context.reverse()
}
};
});
CodeMirror.defineMIME("text/xml", "xml");
CodeMirror.defineMIME("application/xml", "xml");
if (!CodeMirror.mimeModes.hasOwnProperty("text/html"))
CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
});
/***/ }),
/***/ "1uat":
/*!******************************************!*\
!*** ./node_modules/crypto-js/sha512.js ***!
\******************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory, undef) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"), __webpack_require__(/*! ./x64-core */ "MlIO"));
}
else {}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Hasher = C_lib.Hasher;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var X64WordArray = C_x64.WordArray;
var C_algo = C.algo;
function X64Word_create() {
return X64Word.create.apply(X64Word, arguments);
}
// Constants
var K = [
X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd),
X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc),
X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019),
X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118),
X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe),
X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2),
X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1),
X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694),
X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3),
X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65),
X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483),
X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5),
X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210),
X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4),
X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725),
X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70),
X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926),
X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df),
X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8),
X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b),
X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001),
X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30),
X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910),
X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8),
X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53),
X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8),
X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb),
X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3),
X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60),
X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec),
X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9),
X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b),
X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207),
X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178),
X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6),
X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b),
X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493),
X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c),
X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a),
X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817)
];
// Reusable objects
var W = [];
(function () {
for (var i = 0; i < 80; i++) {
W[i] = X64Word_create();
}
}());
/**
* SHA-512 hash algorithm.
*/
var SHA512 = C_algo.SHA512 = Hasher.extend({
_doReset: function () {
this._hash = new X64WordArray.init([
new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b),
new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1),
new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f),
new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179)
]);
},
_doProcessBlock: function (M, offset) {
// Shortcuts
var H = this._hash.words;
var H0 = H[0];
var H1 = H[1];
var H2 = H[2];
var H3 = H[3];
var H4 = H[4];
var H5 = H[5];
var H6 = H[6];
var H7 = H[7];
var H0h = H0.high;
var H0l = H0.low;
var H1h = H1.high;
var H1l = H1.low;
var H2h = H2.high;
var H2l = H2.low;
var H3h = H3.high;
var H3l = H3.low;
var H4h = H4.high;
var H4l = H4.low;
var H5h = H5.high;
var H5l = H5.low;
var H6h = H6.high;
var H6l = H6.low;
var H7h = H7.high;
var H7l = H7.low;
// Working variables
var ah = H0h;
var al = H0l;
var bh = H1h;
var bl = H1l;
var ch = H2h;
var cl = H2l;
var dh = H3h;
var dl = H3l;
var eh = H4h;
var el = H4l;
var fh = H5h;
var fl = H5l;
var gh = H6h;
var gl = H6l;
var hh = H7h;
var hl = H7l;
// Rounds
for (var i = 0; i < 80; i++) {
var Wil;
var Wih;
// Shortcut
var Wi = W[i];
// Extend message
if (i < 16) {
Wih = Wi.high = M[offset + i * 2] | 0;
Wil = Wi.low = M[offset + i * 2 + 1] | 0;
} else {
// Gamma0
var gamma0x = W[i - 15];
var gamma0xh = gamma0x.high;
var gamma0xl = gamma0x.low;
var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7);
var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25));
// Gamma1
var gamma1x = W[i - 2];
var gamma1xh = gamma1x.high;
var gamma1xl = gamma1x.low;
var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6);
var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26));
// W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
var Wi7 = W[i - 7];
var Wi7h = Wi7.high;
var Wi7l = Wi7.low;
var Wi16 = W[i - 16];
var Wi16h = Wi16.high;
var Wi16l = Wi16.low;
Wil = gamma0l + Wi7l;
Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0);
Wil = Wil + gamma1l;
Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0);
Wil = Wil + Wi16l;
Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0);
Wi.high = Wih;
Wi.low = Wil;
}
var chh = (eh & fh) ^ (~eh & gh);
var chl = (el & fl) ^ (~el & gl);
var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch);
var majl = (al & bl) ^ (al & cl) ^ (bl & cl);
var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7));
var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7));
var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9));
var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9));
// t1 = h + sigma1 + ch + K[i] + W[i]
var Ki = K[i];
var Kih = Ki.high;
var Kil = Ki.low;
var t1l = hl + sigma1l;
var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0);
var t1l = t1l + chl;
var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0);
var t1l = t1l + Kil;
var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0);
var t1l = t1l + Wil;
var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0);
// t2 = sigma0 + maj
var t2l = sigma0l + majl;
var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0);
// Update working variables
hh = gh;
hl = gl;
gh = fh;
gl = fl;
fh = eh;
fl = el;
el = (dl + t1l) | 0;
eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0;
dh = ch;
dl = cl;
ch = bh;
cl = bl;
bh = ah;
bl = al;
al = (t1l + t2l) | 0;
ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0;
}
// Intermediate hash value
H0l = H0.low = (H0l + al);
H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0));
H1l = H1.low = (H1l + bl);
H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0));
H2l = H2.low = (H2l + cl);
H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0));
H3l = H3.low = (H3l + dl);
H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0));
H4l = H4.low = (H4l + el);
H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0));
H5l = H5.low = (H5l + fl);
H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0));
H6l = H6.low = (H6l + gl);
H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0));
H7l = H7.low = (H7l + hl);
H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0));
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Convert hash to 32-bit word array before returning
var hash = this._hash.toX32();
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
},
blockSize: 1024/32
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA512('message');
* var hash = CryptoJS.SHA512(wordArray);
*/
C.SHA512 = Hasher._createHelper(SHA512);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA512(message, key);
*/
C.HmacSHA512 = Hasher._createHmacHelper(SHA512);
}());
return CryptoJS.SHA512;
}));
/***/ }),
/***/ "2oIt":
/*!******************************************************************!*\
!*** ./node_modules/@ant-design/icons-svg/lib/asn/UpOutlined.js ***!
\******************************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// This icon file is generated automatically.
Object.defineProperty(exports, "__esModule", { value: true });
var UpOutlined = { "icon": { "tag": "svg", "attrs": { "viewBox": "64 64 896 896", "focusable": "false" }, "children": [{ "tag": "path", "attrs": { "d": "M890.5 755.3L537.9 269.2c-12.8-17.6-39-17.6-51.7 0L133.5 755.3A8 8 0 00140 768h75c5.1 0 9.9-2.5 12.9-6.6L512 369.8l284.1 391.6c3 4.1 7.8 6.6 12.9 6.6h75c6.5 0 10.3-7.4 6.5-12.7z" } }] }, "name": "up", "theme": "outlined" };
exports.default = UpOutlined;
/***/ }),
/***/ "3Fjq":
/*!************************************************************!*\
!*** ./node_modules/@ant-design/react-slick/lib/arrows.js ***!
\************************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "TqRt");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.NextArrow = exports.PrevArrow = void 0;
var _extends2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/extends */ "pVnL"));
var _objectSpread2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/objectSpread2 */ "3tO9"));
var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "lwsE"));
var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "W8MJ"));
var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "7W2i"));
var _createSuper2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createSuper */ "LQ03"));
var _react = _interopRequireDefault(__webpack_require__(/*! react */ "q1tI"));
var _classnames = _interopRequireDefault(__webpack_require__(/*! classnames */ "TSYQ"));
var _innerSliderUtils = __webpack_require__(/*! ./utils/innerSliderUtils */ "3K4p");
var PrevArrow = /*#__PURE__*/function (_React$PureComponent) {
(0, _inherits2["default"])(PrevArrow, _React$PureComponent);
var _super = (0, _createSuper2["default"])(PrevArrow);
function PrevArrow() {
(0, _classCallCheck2["default"])(this, PrevArrow);
return _super.apply(this, arguments);
}
(0, _createClass2["default"])(PrevArrow, [{
key: "clickHandler",
value: function clickHandler(options, e) {
if (e) {
e.preventDefault();
}
this.props.clickHandler(options, e);
}
}, {
key: "render",
value: function render() {
var prevClasses = {
"slick-arrow": true,
"slick-prev": true
};
var prevHandler = this.clickHandler.bind(this, {
message: "previous"
});
if (!this.props.infinite && (this.props.currentSlide === 0 || this.props.slideCount <= this.props.slidesToShow)) {
prevClasses["slick-disabled"] = true;
prevHandler = null;
}
var prevArrowProps = {
key: "0",
"data-role": "none",
className: (0, _classnames["default"])(prevClasses),
style: {
display: "block"
},
onClick: prevHandler
};
var customProps = {
currentSlide: this.props.currentSlide,
slideCount: this.props.slideCount
};
var prevArrow;
if (this.props.prevArrow) {
prevArrow = /*#__PURE__*/_react["default"].cloneElement(this.props.prevArrow, (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, prevArrowProps), customProps));
} else {
prevArrow = /*#__PURE__*/_react["default"].createElement("button", (0, _extends2["default"])({
key: "0",
type: "button"
}, prevArrowProps), " ", "Previous");
}
return prevArrow;
}
}]);
return PrevArrow;
}(_react["default"].PureComponent);
exports.PrevArrow = PrevArrow;
var NextArrow = /*#__PURE__*/function (_React$PureComponent2) {
(0, _inherits2["default"])(NextArrow, _React$PureComponent2);
var _super2 = (0, _createSuper2["default"])(NextArrow);
function NextArrow() {
(0, _classCallCheck2["default"])(this, NextArrow);
return _super2.apply(this, arguments);
}
(0, _createClass2["default"])(NextArrow, [{
key: "clickHandler",
value: function clickHandler(options, e) {
if (e) {
e.preventDefault();
}
this.props.clickHandler(options, e);
}
}, {
key: "render",
value: function render() {
var nextClasses = {
"slick-arrow": true,
"slick-next": true
};
var nextHandler = this.clickHandler.bind(this, {
message: "next"
});
if (!(0, _innerSliderUtils.canGoNext)(this.props)) {
nextClasses["slick-disabled"] = true;
nextHandler = null;
}
var nextArrowProps = {
key: "1",
"data-role": "none",
className: (0, _classnames["default"])(nextClasses),
style: {
display: "block"
},
onClick: nextHandler
};
var customProps = {
currentSlide: this.props.currentSlide,
slideCount: this.props.slideCount
};
var nextArrow;
if (this.props.nextArrow) {
nextArrow = /*#__PURE__*/_react["default"].cloneElement(this.props.nextArrow, (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, nextArrowProps), customProps));
} else {
nextArrow = /*#__PURE__*/_react["default"].createElement("button", (0, _extends2["default"])({
key: "1",
type: "button"
}, nextArrowProps), " ", "Next");
}
return nextArrow;
}
}]);
return NextArrow;
}(_react["default"].PureComponent);
exports.NextArrow = NextArrow;
/***/ }),
/***/ "3I+P":
/*!************************************************!*\
!*** ./node_modules/antd/es/carousel/index.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 Carousel; });
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "lSNA");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/extends */ "pVnL");
/* harmony import */ var _babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "lwsE");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "W8MJ");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "7W2i");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _babel_runtime_helpers_createSuper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/createSuper */ "LQ03");
/* harmony import */ var _babel_runtime_helpers_createSuper__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createSuper__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! react */ "q1tI");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var lodash_debounce__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! lodash/debounce */ "sEfC");
/* harmony import */ var lodash_debounce__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(lodash_debounce__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _ant_design_react_slick__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @ant-design/react-slick */ "N/JB");
/* harmony import */ var _ant_design_react_slick__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_ant_design_react_slick__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! classnames */ "TSYQ");
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(classnames__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _config_provider__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../config-provider */ "H84U");
var Carousel = /*#__PURE__*/function (_React$Component) {
_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default()(Carousel, _React$Component);
var _super = _babel_runtime_helpers_createSuper__WEBPACK_IMPORTED_MODULE_5___default()(Carousel);
function Carousel(props) {
var _this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, Carousel);
_this = _super.call(this, props);
_this.saveSlick = function (node) {
_this.slick = node;
};
_this.onWindowResized = function () {
// Fix https://github.com/ant-design/ant-design/issues/2550
var autoplay = _this.props.autoplay;
if (autoplay && _this.slick && _this.slick.innerSlider && _this.slick.innerSlider.autoPlay) {
_this.slick.innerSlider.autoPlay();
}
};
_this.renderCarousel = function (_ref) {
var _classNames;
var getPrefixCls = _ref.getPrefixCls,
direction = _ref.direction;
var _a;
var props = _babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_1___default()({}, _this.props);
if (props.effect === 'fade') {
props.fade = true;
}
var prefixCls = getPrefixCls('carousel', props.prefixCls);
var dotsClass = 'slick-dots';
var dotPosition = _this.getDotPosition();
props.vertical = dotPosition === 'left' || dotPosition === 'right';
var enableDots = !!props.dots;
var dsClass = classnames__WEBPACK_IMPORTED_MODULE_9___default()(dotsClass, "".concat(dotsClass, "-").concat(dotPosition || 'bottom'), typeof props.dots === 'boolean' ? false : (_a = props.dots) === null || _a === void 0 ? void 0 : _a.className);
var className = classnames__WEBPACK_IMPORTED_MODULE_9___default()(prefixCls, (_classNames = {}, _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default()(_classNames, "".concat(prefixCls, "-rtl"), direction === 'rtl'), _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default()(_classNames, "".concat(prefixCls, "-vertical"), props.vertical), _classNames));
return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6__["createElement"]("div", {
className: className
}, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6__["createElement"](_ant_design_react_slick__WEBPACK_IMPORTED_MODULE_8___default.a, _babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_1___default()({
ref: _this.saveSlick
}, props, {
dots: enableDots,
dotsClass: dsClass
})));
};
_this.onWindowResized = lodash_debounce__WEBPACK_IMPORTED_MODULE_7___default()(_this.onWindowResized, 500, {
leading: false
});
return _this;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(Carousel, [{
key: "componentDidMount",
value: function componentDidMount() {
var autoplay = this.props.autoplay;
if (autoplay) {
window.addEventListener('resize', this.onWindowResized);
} // https://github.com/ant-design/ant-design/issues/7191
this.innerSlider = this.slick && this.slick.innerSlider;
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (react__WEBPACK_IMPORTED_MODULE_6__["Children"].count(this.props.children) !== react__WEBPACK_IMPORTED_MODULE_6__["Children"].count(prevProps.children)) {
this.goTo(this.props.initialSlide || 0, false);
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
var autoplay = this.props.autoplay;
if (autoplay) {
window.removeEventListener('resize', this.onWindowResized);
this.onWindowResized.cancel();
}
}
}, {
key: "getDotPosition",
value: function getDotPosition() {
var _this$props$dotPositi = this.props.dotPosition,
dotPosition = _this$props$dotPositi === void 0 ? 'bottom' : _this$props$dotPositi;
return dotPosition;
}
}, {
key: "next",
value: function next() {
this.slick.slickNext();
}
}, {
key: "prev",
value: function prev() {
this.slick.slickPrev();
}
}, {
key: "goTo",
value: function goTo(slide) {
var dontAnimate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
this.slick.slickGoTo(slide, dontAnimate);
}
}, {
key: "render",
value: function render() {
return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6__["createElement"](_config_provider__WEBPACK_IMPORTED_MODULE_10__[/* ConfigConsumer */ "a"], null, this.renderCarousel);
}
}]);
return Carousel;
}(react__WEBPACK_IMPORTED_MODULE_6__["Component"]);
Carousel.defaultProps = {
dots: true,
arrows: false,
draggable: false
};
/***/ }),
/***/ "3K4p":
/*!****************************************************************************!*\
!*** ./node_modules/@ant-design/react-slick/lib/utils/innerSliderUtils.js ***!
\****************************************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "TqRt");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.clamp = clamp;
exports.canUseDOM = exports.slidesOnLeft = exports.slidesOnRight = exports.siblingDirection = exports.getTotalSlides = exports.getPostClones = exports.getPreClones = exports.getTrackLeft = exports.getTrackAnimateCSS = exports.getTrackCSS = exports.checkSpecKeys = exports.getSlideCount = exports.checkNavigable = exports.getNavigableIndexes = exports.swipeEnd = exports.swipeMove = exports.swipeStart = exports.keyHandler = exports.changeSlide = exports.slideHandler = exports.initializedState = exports.extractObject = exports.canGoNext = exports.getSwipeDirection = exports.getHeight = exports.getWidth = exports.lazySlidesOnRight = exports.lazySlidesOnLeft = exports.lazyEndIndex = exports.lazyStartIndex = exports.getRequiredLazySlides = exports.getOnDemandLazySlides = void 0;
var _objectSpread2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/objectSpread2 */ "3tO9"));
var _react = _interopRequireDefault(__webpack_require__(/*! react */ "q1tI"));
function clamp(number, lowerBound, upperBound) {
return Math.max(lowerBound, Math.min(number, upperBound));
}
var getOnDemandLazySlides = function getOnDemandLazySlides(spec) {
var onDemandSlides = [];
var startIndex = lazyStartIndex(spec);
var endIndex = lazyEndIndex(spec);
for (var slideIndex = startIndex; slideIndex < endIndex; slideIndex++) {
if (spec.lazyLoadedList.indexOf(slideIndex) < 0) {
onDemandSlides.push(slideIndex);
}
}
return onDemandSlides;
}; // return list of slides that need to be present
exports.getOnDemandLazySlides = getOnDemandLazySlides;
var getRequiredLazySlides = function getRequiredLazySlides(spec) {
var requiredSlides = [];
var startIndex = lazyStartIndex(spec);
var endIndex = lazyEndIndex(spec);
for (var slideIndex = startIndex; slideIndex < endIndex; slideIndex++) {
requiredSlides.push(slideIndex);
}
return requiredSlides;
}; // startIndex that needs to be present
exports.getRequiredLazySlides = getRequiredLazySlides;
var lazyStartIndex = function lazyStartIndex(spec) {
return spec.currentSlide - lazySlidesOnLeft(spec);
};
exports.lazyStartIndex = lazyStartIndex;
var lazyEndIndex = function lazyEndIndex(spec) {
return spec.currentSlide + lazySlidesOnRight(spec);
};
exports.lazyEndIndex = lazyEndIndex;
var lazySlidesOnLeft = function lazySlidesOnLeft(spec) {
return spec.centerMode ? Math.floor(spec.slidesToShow / 2) + (parseInt(spec.centerPadding) > 0 ? 1 : 0) : 0;
};
exports.lazySlidesOnLeft = lazySlidesOnLeft;
var lazySlidesOnRight = function lazySlidesOnRight(spec) {
return spec.centerMode ? Math.floor((spec.slidesToShow - 1) / 2) + 1 + (parseInt(spec.centerPadding) > 0 ? 1 : 0) : spec.slidesToShow;
}; // get width of an element
exports.lazySlidesOnRight = lazySlidesOnRight;
var getWidth = function getWidth(elem) {
return elem && elem.offsetWidth || 0;
};
exports.getWidth = getWidth;
var getHeight = function getHeight(elem) {
return elem && elem.offsetHeight || 0;
};
exports.getHeight = getHeight;
var getSwipeDirection = function getSwipeDirection(touchObject) {
var verticalSwiping = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var xDist, yDist, r, swipeAngle;
xDist = touchObject.startX - touchObject.curX;
yDist = touchObject.startY - touchObject.curY;
r = Math.atan2(yDist, xDist);
swipeAngle = Math.round(r * 180 / Math.PI);
if (swipeAngle < 0) {
swipeAngle = 360 - Math.abs(swipeAngle);
}
if (swipeAngle <= 45 && swipeAngle >= 0 || swipeAngle <= 360 && swipeAngle >= 315) {
return "left";
}
if (swipeAngle >= 135 && swipeAngle <= 225) {
return "right";
}
if (verticalSwiping === true) {
if (swipeAngle >= 35 && swipeAngle <= 135) {
return "up";
} else {
return "down";
}
}
return "vertical";
}; // whether or not we can go next
exports.getSwipeDirection = getSwipeDirection;
var canGoNext = function canGoNext(spec) {
var canGo = true;
if (!spec.infinite) {
if (spec.centerMode && spec.currentSlide >= spec.slideCount - 1) {
canGo = false;
} else if (spec.slideCount <= spec.slidesToShow || spec.currentSlide >= spec.slideCount - spec.slidesToShow) {
canGo = false;
}
}
return canGo;
}; // given an object and a list of keys, return new object with given keys
exports.canGoNext = canGoNext;
var extractObject = function extractObject(spec, keys) {
var newObject = {};
keys.forEach(function (key) {
return newObject[key] = spec[key];
});
return newObject;
}; // get initialized state
exports.extractObject = extractObject;
var initializedState = function initializedState(spec) {
// spec also contains listRef, trackRef
var slideCount = _react["default"].Children.count(spec.children);
var listNode = spec.listRef;
var listWidth = Math.ceil(getWidth(listNode));
var trackNode = spec.trackRef && spec.trackRef.node;
var trackWidth = Math.ceil(getWidth(trackNode));
var slideWidth;
if (!spec.vertical) {
var centerPaddingAdj = spec.centerMode && parseInt(spec.centerPadding) * 2;
if (typeof spec.centerPadding === "string" && spec.centerPadding.slice(-1) === "%") {
centerPaddingAdj *= listWidth / 100;
}
slideWidth = Math.ceil((listWidth - centerPaddingAdj) / spec.slidesToShow);
} else {
slideWidth = listWidth;
}
var slideHeight = listNode && getHeight(listNode.querySelector('[data-index="0"]'));
var listHeight = slideHeight * spec.slidesToShow;
var currentSlide = spec.currentSlide === undefined ? spec.initialSlide : spec.currentSlide;
if (spec.rtl && spec.currentSlide === undefined) {
currentSlide = slideCount - 1 - spec.initialSlide;
}
var lazyLoadedList = spec.lazyLoadedList || [];
var slidesToLoad = getOnDemandLazySlides((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, spec), {}, {
currentSlide: currentSlide,
lazyLoadedList: lazyLoadedList
}));
lazyLoadedList.concat(slidesToLoad);
var state = {
slideCount: slideCount,
slideWidth: slideWidth,
listWidth: listWidth,
trackWidth: trackWidth,
currentSlide: currentSlide,
slideHeight: slideHeight,
listHeight: listHeight,
lazyLoadedList: lazyLoadedList
};
if (spec.autoplaying === null && spec.autoplay) {
state["autoplaying"] = "playing";
}
return state;
};
exports.initializedState = initializedState;
var slideHandler = function slideHandler(spec) {
var waitForAnimate = spec.waitForAnimate,
animating = spec.animating,
fade = spec.fade,
infinite = spec.infinite,
index = spec.index,
slideCount = spec.slideCount,
lazyLoadedList = spec.lazyLoadedList,
lazyLoad = spec.lazyLoad,
currentSlide = spec.currentSlide,
centerMode = spec.centerMode,
slidesToScroll = spec.slidesToScroll,
slidesToShow = spec.slidesToShow,
useCSS = spec.useCSS;
if (waitForAnimate && animating) return {};
var animationSlide = index,
finalSlide,
animationLeft,
finalLeft;
var state = {},
nextState = {};
var targetSlide = infinite ? index : clamp(index, 0, slideCount - 1);
if (fade) {
if (!infinite && (index < 0 || index >= slideCount)) return {};
if (index < 0) {
animationSlide = index + slideCount;
} else if (index >= slideCount) {
animationSlide = index - slideCount;
}
if (lazyLoad && lazyLoadedList.indexOf(animationSlide) < 0) {
lazyLoadedList.push(animationSlide);
}
state = {
animating: true,
currentSlide: animationSlide,
lazyLoadedList: lazyLoadedList,
targetSlide: animationSlide
};
nextState = {
animating: false,
targetSlide: animationSlide
};
} else {
finalSlide = animationSlide;
if (animationSlide < 0) {
finalSlide = animationSlide + slideCount;
if (!infinite) finalSlide = 0;else if (slideCount % slidesToScroll !== 0) finalSlide = slideCount - slideCount % slidesToScroll;
} else if (!canGoNext(spec) && animationSlide > currentSlide) {
animationSlide = finalSlide = currentSlide;
} else if (centerMode && animationSlide >= slideCount) {
animationSlide = infinite ? slideCount : slideCount - 1;
finalSlide = infinite ? 0 : slideCount - 1;
} else if (animationSlide >= slideCount) {
finalSlide = animationSlide - slideCount;
if (!infinite) finalSlide = slideCount - slidesToShow;else if (slideCount % slidesToScroll !== 0) finalSlide = 0;
}
if (!infinite && animationSlide + slidesToShow >= slideCount) {
finalSlide = slideCount - slidesToShow;
}
animationLeft = getTrackLeft((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, spec), {}, {
slideIndex: animationSlide
}));
finalLeft = getTrackLeft((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, spec), {}, {
slideIndex: finalSlide
}));
if (!infinite) {
if (animationLeft === finalLeft) animationSlide = finalSlide;
animationLeft = finalLeft;
}
lazyLoad && lazyLoadedList.concat(getOnDemandLazySlides((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, spec), {}, {
currentSlide: animationSlide
})));
if (!useCSS) {
state = {
currentSlide: finalSlide,
trackStyle: getTrackCSS((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, spec), {}, {
left: finalLeft
})),
lazyLoadedList: lazyLoadedList,
targetSlide: targetSlide
};
} else {
state = {
animating: true,
currentSlide: finalSlide,
trackStyle: getTrackAnimateCSS((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, spec), {}, {
left: animationLeft
})),
lazyLoadedList: lazyLoadedList,
targetSlide: targetSlide
};
nextState = {
animating: false,
currentSlide: finalSlide,
trackStyle: getTrackCSS((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, spec), {}, {
left: finalLeft
})),
swipeLeft: null,
targetSlide: targetSlide
};
}
}
return {
state: state,
nextState: nextState
};
};
exports.slideHandler = slideHandler;
var changeSlide = function changeSlide(spec, options) {
var indexOffset, previousInt, slideOffset, unevenOffset, targetSlide;
var slidesToScroll = spec.slidesToScroll,
slidesToShow = spec.slidesToShow,
slideCount = spec.slideCount,
currentSlide = spec.currentSlide,
previousTargetSlide = spec.targetSlide,
lazyLoad = spec.lazyLoad,
infinite = spec.infinite;
unevenOffset = slideCount % slidesToScroll !== 0;
indexOffset = unevenOffset ? 0 : (slideCount - currentSlide) % slidesToScroll;
if (options.message === "previous") {
slideOffset = indexOffset === 0 ? slidesToScroll : slidesToShow - indexOffset;
targetSlide = currentSlide - slideOffset;
if (lazyLoad && !infinite) {
previousInt = currentSlide - slideOffset;
targetSlide = previousInt === -1 ? slideCount - 1 : previousInt;
}
if (!infinite) {
targetSlide = previousTargetSlide - slidesToScroll;
}
} else if (options.message === "next") {
slideOffset = indexOffset === 0 ? slidesToScroll : indexOffset;
targetSlide = currentSlide + slideOffset;
if (lazyLoad && !infinite) {
targetSlide = (currentSlide + slidesToScroll) % slideCount + indexOffset;
}
if (!infinite) {
targetSlide = previousTargetSlide + slidesToScroll;
}
} else if (options.message === "dots") {
// Click on dots
targetSlide = options.index * options.slidesToScroll;
} else if (options.message === "children") {
// Click on the slides
targetSlide = options.index;
if (infinite) {
var direction = siblingDirection((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, spec), {}, {
targetSlide: targetSlide
}));
if (targetSlide > options.currentSlide && direction === "left") {
targetSlide = targetSlide - slideCount;
} else if (targetSlide < options.currentSlide && direction === "right") {
targetSlide = targetSlide + slideCount;
}
}
} else if (options.message === "index") {
targetSlide = Number(options.index);
}
return targetSlide;
};
exports.changeSlide = changeSlide;
var keyHandler = function keyHandler(e, accessibility, rtl) {
if (e.target.tagName.match("TEXTAREA|INPUT|SELECT") || !accessibility) return "";
if (e.keyCode === 37) return rtl ? "next" : "previous";
if (e.keyCode === 39) return rtl ? "previous" : "next";
return "";
};
exports.keyHandler = keyHandler;
var swipeStart = function swipeStart(e, swipe, draggable) {
e.target.tagName === "IMG" && e.preventDefault();
if (!swipe || !draggable && e.type.indexOf("mouse") !== -1) return "";
return {
dragging: true,
touchObject: {
startX: e.touches ? e.touches[0].pageX : e.clientX,
startY: e.touches ? e.touches[0].pageY : e.clientY,
curX: e.touches ? e.touches[0].pageX : e.clientX,
curY: e.touches ? e.touches[0].pageY : e.clientY
}
};
};
exports.swipeStart = swipeStart;
var swipeMove = function swipeMove(e, spec) {
// spec also contains, trackRef and slideIndex
var scrolling = spec.scrolling,
animating = spec.animating,
vertical = spec.vertical,
swipeToSlide = spec.swipeToSlide,
verticalSwiping = spec.verticalSwiping,
rtl = spec.rtl,
currentSlide = spec.currentSlide,
edgeFriction = spec.edgeFriction,
edgeDragged = spec.edgeDragged,
onEdge = spec.onEdge,
swiped = spec.swiped,
swiping = spec.swiping,
slideCount = spec.slideCount,
slidesToScroll = spec.slidesToScroll,
infinite = spec.infinite,
touchObject = spec.touchObject,
swipeEvent = spec.swipeEvent,
listHeight = spec.listHeight,
listWidth = spec.listWidth;
if (scrolling) return;
if (animating) return e.preventDefault();
if (vertical && swipeToSlide && verticalSwiping) e.preventDefault();
var swipeLeft,
state = {};
var curLeft = getTrackLeft(spec);
touchObject.curX = e.touches ? e.touches[0].pageX : e.clientX;
touchObject.curY = e.touches ? e.touches[0].pageY : e.clientY;
touchObject.swipeLength = Math.round(Math.sqrt(Math.pow(touchObject.curX - touchObject.startX, 2)));
var verticalSwipeLength = Math.round(Math.sqrt(Math.pow(touchObject.curY - touchObject.startY, 2)));
if (!verticalSwiping && !swiping && verticalSwipeLength > 10) {
return {
scrolling: true
};
}
if (verticalSwiping) touchObject.swipeLength = verticalSwipeLength;
var positionOffset = (!rtl ? 1 : -1) * (touchObject.curX > touchObject.startX ? 1 : -1);
if (verticalSwiping) positionOffset = touchObject.curY > touchObject.startY ? 1 : -1;
var dotCount = Math.ceil(slideCount / slidesToScroll);
var swipeDirection = getSwipeDirection(spec.touchObject, verticalSwiping);
var touchSwipeLength = touchObject.swipeLength;
if (!infinite) {
if (currentSlide === 0 && swipeDirection === "right" || currentSlide + 1 >= dotCount && swipeDirection === "left" || !canGoNext(spec) && swipeDirection === "left") {
touchSwipeLength = touchObject.swipeLength * edgeFriction;
if (edgeDragged === false && onEdge) {
onEdge(swipeDirection);
state["edgeDragged"] = true;
}
}
}
if (!swiped && swipeEvent) {
swipeEvent(swipeDirection);
state["swiped"] = true;
}
if (!vertical) {
if (!rtl) {
swipeLeft = curLeft + touchSwipeLength * positionOffset;
} else {
swipeLeft = curLeft - touchSwipeLength * positionOffset;
}
} else {
swipeLeft = curLeft + touchSwipeLength * (listHeight / listWidth) * positionOffset;
}
if (verticalSwiping) {
swipeLeft = curLeft + touchSwipeLength * positionOffset;
}
state = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, state), {}, {
touchObject: touchObject,
swipeLeft: swipeLeft,
trackStyle: getTrackCSS((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, spec), {}, {
left: swipeLeft
}))
});
if (Math.abs(touchObject.curX - touchObject.startX) < Math.abs(touchObject.curY - touchObject.startY) * 0.8) {
return state;
}
if (touchObject.swipeLength > 10) {
state["swiping"] = true;
e.preventDefault();
}
return state;
};
exports.swipeMove = swipeMove;
var swipeEnd = function swipeEnd(e, spec) {
var dragging = spec.dragging,
swipe = spec.swipe,
touchObject = spec.touchObject,
listWidth = spec.listWidth,
touchThreshold = spec.touchThreshold,
verticalSwiping = spec.verticalSwiping,
listHeight = spec.listHeight,
swipeToSlide = spec.swipeToSlide,
scrolling = spec.scrolling,
onSwipe = spec.onSwipe,
targetSlide = spec.targetSlide,
currentSlide = spec.currentSlide,
infinite = spec.infinite;
if (!dragging) {
if (swipe) e.preventDefault();
return {};
}
var minSwipe = verticalSwiping ? listHeight / touchThreshold : listWidth / touchThreshold;
var swipeDirection = getSwipeDirection(touchObject, verticalSwiping); // reset the state of touch related state variables.
var state = {
dragging: false,
edgeDragged: false,
scrolling: false,
swiping: false,
swiped: false,
swipeLeft: null,
touchObject: {}
};
if (scrolling) {
return state;
}
if (!touchObject.swipeLength) {
return state;
}
if (touchObject.swipeLength > minSwipe) {
e.preventDefault();
if (onSwipe) {
onSwipe(swipeDirection);
}
var slideCount, newSlide;
var activeSlide = infinite ? currentSlide : targetSlide;
switch (swipeDirection) {
case "left":
case "up":
newSlide = activeSlide + getSlideCount(spec);
slideCount = swipeToSlide ? checkNavigable(spec, newSlide) : newSlide;
state["currentDirection"] = 0;
break;
case "right":
case "down":
newSlide = activeSlide - getSlideCount(spec);
slideCount = swipeToSlide ? checkNavigable(spec, newSlide) : newSlide;
state["currentDirection"] = 1;
break;
default:
slideCount = activeSlide;
}
state["triggerSlideHandler"] = slideCount;
} else {
// Adjust the track back to it's original position.
var currentLeft = getTrackLeft(spec);
state["trackStyle"] = getTrackAnimateCSS((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, spec), {}, {
left: currentLeft
}));
}
return state;
};
exports.swipeEnd = swipeEnd;
var getNavigableIndexes = function getNavigableIndexes(spec) {
var max = spec.infinite ? spec.slideCount * 2 : spec.slideCount;
var breakpoint = spec.infinite ? spec.slidesToShow * -1 : 0;
var counter = spec.infinite ? spec.slidesToShow * -1 : 0;
var indexes = [];
while (breakpoint < max) {
indexes.push(breakpoint);
breakpoint = counter + spec.slidesToScroll;
counter += Math.min(spec.slidesToScroll, spec.slidesToShow);
}
return indexes;
};
exports.getNavigableIndexes = getNavigableIndexes;
var checkNavigable = function checkNavigable(spec, index) {
var navigables = getNavigableIndexes(spec);
var prevNavigable = 0;
if (index > navigables[navigables.length - 1]) {
index = navigables[navigables.length - 1];
} else {
for (var n in navigables) {
if (index < navigables[n]) {
index = prevNavigable;
break;
}
prevNavigable = navigables[n];
}
}
return index;
};
exports.checkNavigable = checkNavigable;
var getSlideCount = function getSlideCount(spec) {
var centerOffset = spec.centerMode ? spec.slideWidth * Math.floor(spec.slidesToShow / 2) : 0;
if (spec.swipeToSlide) {
var swipedSlide;
var slickList = spec.listRef;
var slides = slickList.querySelectorAll(".slick-slide");
Array.from(slides).every(function (slide) {
if (!spec.vertical) {
if (slide.offsetLeft - centerOffset + getWidth(slide) / 2 > spec.swipeLeft * -1) {
swipedSlide = slide;
return false;
}
} else {
if (slide.offsetTop + getHeight(slide) / 2 > spec.swipeLeft * -1) {
swipedSlide = slide;
return false;
}
}
return true;
});
if (!swipedSlide) {
return 0;
}
var currentIndex = spec.rtl === true ? spec.slideCount - spec.currentSlide : spec.currentSlide;
var slidesTraversed = Math.abs(swipedSlide.dataset.index - currentIndex) || 1;
return slidesTraversed;
} else {
return spec.slidesToScroll;
}
};
exports.getSlideCount = getSlideCount;
var checkSpecKeys = function checkSpecKeys(spec, keysArray) {
return (// eslint-disable-next-line no-prototype-builtins
keysArray.reduce(function (value, key) {
return value && spec.hasOwnProperty(key);
}, true) ? null : console.error("Keys Missing:", spec)
);
};
exports.checkSpecKeys = checkSpecKeys;
var getTrackCSS = function getTrackCSS(spec) {
checkSpecKeys(spec, ["left", "variableWidth", "slideCount", "slidesToShow", "slideWidth"]);
var trackWidth, trackHeight;
var trackChildren = spec.slideCount + 2 * spec.slidesToShow;
if (!spec.vertical) {
trackWidth = getTotalSlides(spec) * spec.slideWidth;
} else {
trackHeight = trackChildren * spec.slideHeight;
}
var style = {
opacity: 1,
transition: "",
WebkitTransition: ""
};
if (spec.useTransform) {
var WebkitTransform = !spec.vertical ? "translate3d(" + spec.left + "px, 0px, 0px)" : "translate3d(0px, " + spec.left + "px, 0px)";
var transform = !spec.vertical ? "translate3d(" + spec.left + "px, 0px, 0px)" : "translate3d(0px, " + spec.left + "px, 0px)";
var msTransform = !spec.vertical ? "translateX(" + spec.left + "px)" : "translateY(" + spec.left + "px)";
style = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, style), {}, {
WebkitTransform: WebkitTransform,
transform: transform,
msTransform: msTransform
});
} else {
if (spec.vertical) {
style["top"] = spec.left;
} else {
style["left"] = spec.left;
}
}
if (spec.fade) style = {
opacity: 1
};
if (trackWidth) style.width = trackWidth;
if (trackHeight) style.height = trackHeight; // Fallback for IE8
if (window && !window.addEventListener && window.attachEvent) {
if (!spec.vertical) {
style.marginLeft = spec.left + "px";
} else {
style.marginTop = spec.left + "px";
}
}
return style;
};
exports.getTrackCSS = getTrackCSS;
var getTrackAnimateCSS = function getTrackAnimateCSS(spec) {
checkSpecKeys(spec, ["left", "variableWidth", "slideCount", "slidesToShow", "slideWidth", "speed", "cssEase"]);
var style = getTrackCSS(spec); // useCSS is true by default so it can be undefined
if (spec.useTransform) {
style.WebkitTransition = "-webkit-transform " + spec.speed + "ms " + spec.cssEase;
style.transition = "transform " + spec.speed + "ms " + spec.cssEase;
} else {
if (spec.vertical) {
style.transition = "top " + spec.speed + "ms " + spec.cssEase;
} else {
style.transition = "left " + spec.speed + "ms " + spec.cssEase;
}
}
return style;
};
exports.getTrackAnimateCSS = getTrackAnimateCSS;
var getTrackLeft = function getTrackLeft(spec) {
if (spec.unslick) {
return 0;
}
checkSpecKeys(spec, ["slideIndex", "trackRef", "infinite", "centerMode", "slideCount", "slidesToShow", "slidesToScroll", "slideWidth", "listWidth", "variableWidth", "slideHeight"]);
var slideIndex = spec.slideIndex,
trackRef = spec.trackRef,
infinite = spec.infinite,
centerMode = spec.centerMode,
slideCount = spec.slideCount,
slidesToShow = spec.slidesToShow,
slidesToScroll = spec.slidesToScroll,
slideWidth = spec.slideWidth,
listWidth = spec.listWidth,
variableWidth = spec.variableWidth,
slideHeight = spec.slideHeight,
fade = spec.fade,
vertical = spec.vertical;
var slideOffset = 0;
var targetLeft;
var targetSlide;
var verticalOffset = 0;
if (fade || spec.slideCount === 1) {
return 0;
}
var slidesToOffset = 0;
if (infinite) {
slidesToOffset = -getPreClones(spec); // bring active slide to the beginning of visual area
// if next scroll doesn't have enough children, just reach till the end of original slides instead of shifting slidesToScroll children
if (slideCount % slidesToScroll !== 0 && slideIndex + slidesToScroll > slideCount) {
slidesToOffset = -(slideIndex > slideCount ? slidesToShow - (slideIndex - slideCount) : slideCount % slidesToScroll);
} // shift current slide to center of the frame
if (centerMode) {
slidesToOffset += parseInt(slidesToShow / 2);
}
} else {
if (slideCount % slidesToScroll !== 0 && slideIndex + slidesToScroll > slideCount) {
slidesToOffset = slidesToShow - slideCount % slidesToScroll;
}
if (centerMode) {
slidesToOffset = parseInt(slidesToShow / 2);
}
}
slideOffset = slidesToOffset * slideWidth;
verticalOffset = slidesToOffset * slideHeight;
if (!vertical) {
targetLeft = slideIndex * slideWidth * -1 + slideOffset;
} else {
targetLeft = slideIndex * slideHeight * -1 + verticalOffset;
}
if (variableWidth === true) {
var targetSlideIndex;
var trackElem = trackRef && trackRef.node;
targetSlideIndex = slideIndex + getPreClones(spec);
targetSlide = trackElem && trackElem.childNodes[targetSlideIndex];
targetLeft = targetSlide ? targetSlide.offsetLeft * -1 : 0;
if (centerMode === true) {
targetSlideIndex = infinite ? slideIndex + getPreClones(spec) : slideIndex;
targetSlide = trackElem && trackElem.children[targetSlideIndex];
targetLeft = 0;
for (var slide = 0; slide < targetSlideIndex; slide++) {
targetLeft -= trackElem && trackElem.children[slide] && trackElem.children[slide].offsetWidth;
}
targetLeft -= parseInt(spec.centerPadding);
targetLeft += targetSlide && (listWidth - targetSlide.offsetWidth) / 2;
}
}
return targetLeft;
};
exports.getTrackLeft = getTrackLeft;
var getPreClones = function getPreClones(spec) {
if (spec.unslick || !spec.infinite) {
return 0;
}
if (spec.variableWidth) {
return spec.slideCount;
}
return spec.slidesToShow + (spec.centerMode ? 1 : 0);
};
exports.getPreClones = getPreClones;
var getPostClones = function getPostClones(spec) {
if (spec.unslick || !spec.infinite) {
return 0;
}
return spec.slideCount;
};
exports.getPostClones = getPostClones;
var getTotalSlides = function getTotalSlides(spec) {
return spec.slideCount === 1 ? 1 : getPreClones(spec) + spec.slideCount + getPostClones(spec);
};
exports.getTotalSlides = getTotalSlides;
var siblingDirection = function siblingDirection(spec) {
if (spec.targetSlide > spec.currentSlide) {
if (spec.targetSlide > spec.currentSlide + slidesOnRight(spec)) {
return "left";
}
return "right";
} else {
if (spec.targetSlide < spec.currentSlide - slidesOnLeft(spec)) {
return "right";
}
return "left";
}
};
exports.siblingDirection = siblingDirection;
var slidesOnRight = function slidesOnRight(_ref) {
var slidesToShow = _ref.slidesToShow,
centerMode = _ref.centerMode,
rtl = _ref.rtl,
centerPadding = _ref.centerPadding;
// returns no of slides on the right of active slide
if (centerMode) {
var right = (slidesToShow - 1) / 2 + 1;
if (parseInt(centerPadding) > 0) right += 1;
if (rtl && slidesToShow % 2 === 0) right += 1;
return right;
}
if (rtl) {
return 0;
}
return slidesToShow - 1;
};
exports.slidesOnRight = slidesOnRight;
var slidesOnLeft = function slidesOnLeft(_ref2) {
var slidesToShow = _ref2.slidesToShow,
centerMode = _ref2.centerMode,
rtl = _ref2.rtl,
centerPadding = _ref2.centerPadding;
// returns no of slides on the left of active slide
if (centerMode) {
var left = (slidesToShow - 1) / 2 + 1;
if (parseInt(centerPadding) > 0) left += 1;
if (!rtl && slidesToShow % 2 === 0) left += 1;
return left;
}
if (rtl) {
return slidesToShow - 1;
}
return 0;
};
exports.slidesOnLeft = slidesOnLeft;
var canUseDOM = function canUseDOM() {
return !!(typeof window !== "undefined" && window.document && window.document.createElement);
};
exports.canUseDOM = canUseDOM;
/***/ }),
/***/ "3wET":
/*!****************************************************!*\
!*** ./src/assets/images/cert/shimingrenzheng.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,iVBORw0KGgoAAAANSUhEUgAAACQAAAAkCAYAAADhAJiYAAAAAXNSR0IArs4c6QAACE5JREFUWAmtWH1snVUZ/533tuvYVreyjGy3Y6srTBo2srI4XbtKgFQxIrKYzeAfk8AfCzHbCkPMjPjBP0aCsjr1D01USCQ6oosyiLF8xMGqc2BHauUj1I2Ntghs7dqytuu99/j7nfOee9/73js+jKd53+d5n3Oe5/zO8zznOafX4EO2ta/bhqlJfM4adFJ1hQWyxiIrM5QNG2CY7EnKei5agMf7V5pR9X3QRv0P1pr77WaO3AGLDoKokZYlY2hBtFqLDHLse9ZE2De41hyoNiYte19AzX22nfPdT8NtnJr6UgkIAl/dTLKXwHupeM9gqzmcBpH8rm6JI7ZYm3nhBfyAQHYlFcr4NL6yTn4kEamPxkxkutevx+5Hjcmnh+u7KqB1fXbR+Az2U195UmyWnjH8E1ULvGgsKDlRghTg8MnhPQvrsPVYqxnziqV3BSCBGZuUe21LMUGUKGx6F42K14rZJ6oWeFG19+w3eGnhPLSlQUVOM34pTGfHsR95tCBPozlOFCh5q++YOj7uqyfUxhqDbAYQjxzB8JFuoJ739qRrZ22L5tKcSQx+KbFk1VN2b8Fa5ky8QvojhEVDAh9C1DAH2NYIdFwMNM3TCIsT5wwOnbH45SlgIufDG8arv+RnsQb0SPe/rzdd0lYrAmr+s23PWzznxdXfyRzK1gEPrgU+cbHBa5MWr07KmsHq+RaXLTAYGAe29wFDMyVb6RC62YmxJjKbBj/td5+rJ1LJzeL+ihWUbHkuzpe5GYM9lwsM8MSbwLcGDMZmqc1cWlhrsOsyi20rgTubDb45YDGl0MZNPio1yS1yec2NdsldDq18jEUvzzqjjVj2UMF9i/JRDpFeMc/ihqUWT71p8fU+i3fO0eisRZ4hOjNl8f1/MWxvG3wha/GxedKVntct0SB3tM1hCIAwix0+YZWEVKRhPYF3SRjLxa+tN6hlGX56hHky7RNXyevHAe/OWPxpyCoUuKpem0F9frGBaqGBd5QYOAI1Kw7aBjuFDuWbckQt0DQfYr5srhuGkXdJ5cG4JZP+P+pjWzIn9gR5Vx746ajrLc3Fc7BDWCJM4EZu0xoXkmJ4OLqMl9HYY6Svj3vgrQ00SI9Z5Y+ewJOua/BjBrjj5IEybzjbmkN2YyoMxBJR0OmF5UreSDAmygmoLHqY5/kb3FlfWgWsJygdAu4giOnVlG39KHCcO63/HfXRd/HkgQZbgcquKaAz85GbvrMTBduEApFqUYGKTz2mIH8D4zMGs+Q/swK4Zhkno+w8vbCEpeCLBPmNq4HFDOuP+4G/vBHblN3UIz1LmajnzShD5e8yHO4BcE4HxAnKX/STE0TUPsyJjjUBG5YC937ccE2hz+DEWYs9PNN/N0hjBc0mo2waIz4ey7xxcznq+pGtYf5wc/oW95eqZcjiosRiOYvebWssNrMOLb7IYHSaRXEUGGMBHJ0G/j5icZS16QTDZQjcY/AzsHw54MKoFrAFvBRla2xeFz3fUgugMED1dDUT9YFrgdalBi++Rf6IxaFTrENTCiHcExblLIYP0lpWvFuvZLjPA799+QLzcd8oZCMEUu+HlCCE70DXLAEeuN5g1SLgJ89b/PwYcPoce90yw6hy/RCSWh6fX+Ex87UNwKkJ4DfMLdcI1EVPwH0bUciGWRdW6ztZR+IBjlzCg/NHvBk1EvZ9h4BH+lmV6bQwXkUyp4RNeMQpckwdD6fbrgJ2f5IX7bME1cMebfVqLcJwZHK8kMfb0m098qJ6pDiHS7j3U8Dliw26/0Yw9EyBVVw6GjOHbtjUaFGrpbp646n4OoZ8+zrgbl5+jzPPup4AnmeIHSDaZrr4UhLzZrZwMioU8GSpcGkSDeJS4wlX8zTvbAaO0NCv/0Exz6zk+C0twE8/b3B7qyE4r6t+VgB8dYNBF8G8+jaw6zHgRR4nwa5bcGoBNh/11GQKOJjPubXRueU+l/0tTMT5LP8PHy1gbJKAKSuGnEw/i+QwQ3F3h/4VsfjZEYMMd9fOjcAdGw3+yR131x+BV1ggK1rZdCYXZfC4s738u/Zp5tG1aYV6LvNXtwDLmcg3/4ITaytzkEC5pjAxqdfw5P/hTbwLXcLb1iGL+XUG2wmoj7Xqrj8Ag6fD8PIrb3Lf89r7zNC3zXX0Clse+1gxCSis30+5gMnc1GDwylvAmQkaUxgJItyZg68Ghgx2/p4Xtpt5B7qGt0CiPnqSYA4wd04HmzEoT/w7rI6U69onIasDz6X7zAEeC71lhx0nj5iw2rITU8AMjwuf6J6K97nk6ctDwM79zBN65a/HPX+ctcrbFE3yRED7ShRRLrRXGIRFGF3L7rHtVHou6QHxlzKpx3gBm2AVDttcVI1QijIn4KuZ9WqaJ//QmDdOGKVJXM2iRJStOFfGbBr+nr/CFgFpQOOd+b08M3cVk0S9CYvvB6iyvwRK9uNzxFMncCHqHnow0xV/+pCFj7aN0W7DrRfqhLs5qlZc8AZJ26pXcn1iC/twSq5weuqvvxrH77j+mELUoznD/KJlHpKgqcsumjlve2mqJeWg0nIrtKSpVqHhxcU3wZTGvFRXa9pO7C3/77WqaYE6P23380rRGaaQzcqQVOZQce73YLhLe+rmmq1pMFJxuyytq4Ht15nP8ljpdpX7QiFRyU+EIIQiUJUJ8aKOp51MIereRNvVwAhHVQ8lAWZv588xBf0cY6v8HJMcSXCxQVG14F1ReqWXpeWe4Yf+x59jnMXEa9k2u5mgdrASdHBqV1BTu7hiExGEfPss6b6Rh/9PP1glMDl2xZdtA8vMjRaFTl7tLqVQN86sOukJnmx8jD3FstpTCxw8+ciH+0nvv4gFlb/v9tJbAAAAAElFTkSuQmCC"
/***/ }),
/***/ "3y9D":
/*!****************************************!*\
!*** ./node_modules/crypto-js/sha1.js ***!
\****************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"));
}
else {}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Reusable object
var W = [];
/**
* SHA-1 hash algorithm.
*/
var SHA1 = C_algo.SHA1 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476,
0xc3d2e1f0
]);
},
_doProcessBlock: function (M, offset) {
// Shortcut
var H = this._hash.words;
// Working variables
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
// Computation
for (var i = 0; i < 80; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
W[i] = (n << 1) | (n >>> 31);
}
var t = ((a << 5) | (a >>> 27)) + e + W[i];
if (i < 20) {
t += ((b & c) | (~b & d)) + 0x5a827999;
} else if (i < 40) {
t += (b ^ c ^ d) + 0x6ed9eba1;
} else if (i < 60) {
t += ((b & c) | (b & d) | (c & d)) - 0x70e44324;
} else /* if (i < 80) */ {
t += (b ^ c ^ d) - 0x359d3e2a;
}
e = d;
d = c;
c = (b << 30) | (b >>> 2);
b = a;
a = t;
}
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
H[4] = (H[4] + e) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Return final computed hash
return this._hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA1('message');
* var hash = CryptoJS.SHA1(wordArray);
*/
C.SHA1 = Hasher._createHelper(SHA1);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA1(message, key);
*/
C.HmacSHA1 = Hasher._createHmacHelper(SHA1);
}());
return CryptoJS.SHA1;
}));
/***/ }),
/***/ 4:
/*!************************!*\
!*** crypto (ignored) ***!
\************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports) {
/* (ignored) */
/***/ }),
/***/ "4i/N":
/*!******************************************************************************!*\
!*** ./node_modules/@ant-design/icons/es/icons/CloseOutlined.js + 1 modules ***!
\******************************************************************************/
/*! exports provided: default */
/*! exports used: default */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/es/components/AntdIcon.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/objectSpread2.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/react/index.js (<- Module is not an ECMAScript module) */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/objectSpread2.js
var objectSpread2 = __webpack_require__("VTBJ");
// EXTERNAL MODULE: ./node_modules/react/index.js
var react = __webpack_require__("q1tI");
// CONCATENATED MODULE: ./node_modules/@ant-design/icons-svg/es/asn/CloseOutlined.js
// This icon file is generated automatically.
var CloseOutlined_CloseOutlined = { "icon": { "tag": "svg", "attrs": { "viewBox": "64 64 896 896", "focusable": "false" }, "children": [{ "tag": "path", "attrs": { "d": "M563.8 512l262.5-312.9c4.4-5.2.7-13.1-6.1-13.1h-79.8c-4.7 0-9.2 2.1-12.3 5.7L511.6 449.8 295.1 191.7c-3-3.6-7.5-5.7-12.3-5.7H203c-6.8 0-10.5 7.9-6.1 13.1L459.4 512 196.9 824.9A7.95 7.95 0 00203 838h79.8c4.7 0 9.2-2.1 12.3-5.7l216.5-258.1 216.5 258.1c3 3.6 7.5 5.7 12.3 5.7h79.8c6.8 0 10.5-7.9 6.1-13.1L563.8 512z" } }] }, "name": "close", "theme": "outlined" };
/* harmony default export */ var asn_CloseOutlined = (CloseOutlined_CloseOutlined);
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/es/components/AntdIcon.js + 5 modules
var AntdIcon = __webpack_require__("6VBw");
// CONCATENATED MODULE: ./node_modules/@ant-design/icons/es/icons/CloseOutlined.js
// GENERATE BY ./scripts/generate.ts
// DON NOT EDIT IT MANUALLY
var icons_CloseOutlined_CloseOutlined = function CloseOutlined(props, ref) {
return /*#__PURE__*/react["createElement"](AntdIcon["a" /* default */], Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, props), {}, {
ref: ref,
icon: asn_CloseOutlined
}));
};
icons_CloseOutlined_CloseOutlined.displayName = 'CloseOutlined';
/* harmony default export */ var icons_CloseOutlined = __webpack_exports__["a"] = (/*#__PURE__*/react["forwardRef"](icons_CloseOutlined_CloseOutlined));
/***/ }),
/***/ "4qgm":
/*!*********************************************!*\
!*** ./src/assets/images/icons/tx-live.png ***!
\*********************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports) {
module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADgAAAAwCAYAAABE1blzAAAIeUlEQVRoQ72aa2wU1xXHf2dm1jYEBClJGgofIFJLU0W04AdQWgJSW0UprZRIpB/aJBTxStIShWchJvbytA2lBCKKeajhQ5s2tGpFK1G1UowqKNjYBkraJCqqiCDEDZSncezdmTnVnd2FxaztmfWaa632w9459/7v75xzz71j4R61ssM6TkrYqMon3qesPjFNLt6LoWWgB5n1ttr/GcMCLKrE5qFgPJf3gRXN5XJgoMcfUIFlR/QxiqgVhyfVA/MxTWKgPuZvL51UtUyTjwdK6IAI/NLbWlQylhctWC0xPuN35Zi+gFUMfpIzoqxsLpffDoTIggssb9KvqLBJYnxD3dvUepq8OIAPquxzfCobJ8v5QgotmMAxDVoyYjAvi81KcRiWk1qPKm/RPIvHqy2T5FeFElkQgeVNWq42m8TmcU0G8ZVXC2ia5vOW47Lq2BQ5m5ehrIf6JbC0WQdbsMSH5ZbNED/R3+mYDHSL5kcqVLZOZB8imq/lvAWWHdWpOGySIqYEwvKk1mtsmtl5/M72WNk4Wf6dj8jIAqce1qGJEparsgSHQVoIar3M3GRadWnDp+rb5eyJi0RaykgCy47q9DS1srDUvLRzme+YFXhg5CY2YD4uf/RdVrROkffCGgk13vQTOrzdZZUKi8SmOCy1pMLUYfCDkfD7T+Cvl1PTckKNereENM1L6rFmaAc/PzRD3L6E9jlUabN+Swj2tfFB6o8Q7h0e/GQMPDcy9djBS7DjPJzthOJ+0lSPvzguyxonyz96E9mjwIpGHeGZ+lFYiEXMpP+ozQhcPgZmj7z95MUE1H8Ef7gIhnCszyXOPWqa5lWUDVcvsu3Mk5KrXsodEhUtOtNT6qwYj0allj2dXAIzvx+5CtvOwT9vQpEFVtTVMzuK8QJT1yY55HssbZ0sLd3N3LF+k47pZ70YcZS5WNj5UAsr0PS74cG+C/DLNrjppYTm0wKaSW7gUxvz2HL0q/Jpxs4tgeVN+rRvUWPF+Hx/qEURmOl7uh1ePweN11Iua+XjtsYLUjSP+BZLW0vlmLEvk07paK+LNWoxWwQxBXKhWm8u2n2MpA+/+S/suQDXvfxc1ti0ioIC/ybK5o5BbJbSJj1pD+HLXnu0DBlmEaIIzNjbfi6VhErydNeAmgX2MPCu8ZxMaNJptlBjSi6zv+VbKOcSHFVgwxXY/CFc6AI7Hzc14kzBni7xPJtFgZnxp/S+WJLFAsvEYWiko04vKMMKbOtK7Y9/+h/4mmchkFWkWz6VxyvkzYBm9vzKjmsFFnX9PfZkbPYl0BSVBy7CzvNwvqsfm3/WMct1WXUy65h1lyNMb9CS9iEsUouVls3w/tDsTeCZDjDxduhqKqHk5ZJpaprgQ/VZleug3KOnl/1dJ6QvjL4Z5uohbAx2+fBWG/ziY7icTFHLp4W96ug1lM3l0eCxvIhQicWIqBu/IbhyLDz7cErCiRup6qX5ej/2u4iXVaFyVdlxfUyFN0UojbJPGlozH4B5o+DAJfh1GxjR+VYs2deNFrx2vELa+qIfSqAxUtqkW61iXvY7+zJ55+/mFGHcsN0FJ8+a89Y1RoL3xWVF85TwF8ahBZY16RtSzEtRBRq5RmTogbqtn6GGh+vDThHiLWVyadYstffvl/Q1cu8LHnrc/giMxjzdOxNrCU6rsry1Qv5sflkQ1x8qjN5VJWvD2C2cQGMpwmG4t8lJUUAtobDds1l3coJcnVulox2LdU4xzyc62berWmbfG4GSKo80SVKK0gfjfIWaGDXFcoJW32dZ6yR5x4hYuEafUaixbcYaX3cT7NlVLfMGXGAmq4nPHlz2YvMjbJ41k4iSbYOSylBz6VThZ+2dbPzga3Jj4Todhcd6FZ4XAd8DJwZucqAF3q4gPgCWZ78GK2/S76nFBonxSKhzZfoc5ydpxGNpy2Q5HFCr0mew2WjZPOJmXZcMuMDgFZiPi1Dv3SRuXmTOqdWhRV28ZHkc3hGXw+VN+rAK67GYjWD1VCAYd/Q9borHZrWpaymTjoWv6igtZh0E59OAWnYbMIGljbrDGc4L3g3eRQNqB83A89bo4zb81HYodV06VKkb+S4b4/slMbFRn7JsaiTGF7JpZu5S/ARH8FjSMkUaja35cZ1lCTUBNXPwzhHLRmAywd7dcZlb2Bhs1C3EGNTlsOr0eLkyZ7kOdYawyoJXRCj2PDArbjvguRxVl1d2rZXGCa36oO2zBmWexLCD+ExwHai91M6WszOkc06Vfi5msc4QNzmrO7VsIbEiSCTYubtaXiiowNJmfcBssumVniGw2XaY6Jl3gN1W2oj0fTrUY9PIf7HB0Cxv0ifUZhF+SlxzuZy4i1ofV5NOyu5ltXiqvlL+VlCBGWNzV+vX7RgHnRj3JXPeRKZ6ZtP0fBbviacugTItoOakY60PasalLTuIx3dIsrh+rZwKIy6YR9iOmX7z6zUmbTwhQq1l82gugtk20zRvqrKJDrZeKaX9/vd42oIay7kzQ+aaS/C8x3WEtZc9tu2PS6TXPZEFZibx4w36YMKl2lRPIti9xY2haQh4LmcQbqBMSBPpcX2zPKDB91m8Oy4no8LIi2D3QRZW6Uxs6sLQtMzhNkfq724zTf2aKutH+rwej0gt217eBLONLKzWh8z/wWgImr1RCKgZ0h4N4rJk59pUIupPK4jAzAQWxPU7QJ3t8MW+YjMXNfW55ivriy+xbfv23C9ToootqEAzeEDTplqV+X3FZibbWqlE0iCwZOdr/adWcBfNtarzqvS7tkWt1QtNE2uGGrAhNpzXty8qDLV7IjBDUy3ioszHwspk2lux5tOgHkt3xaU1quuF7V9wF+2Rpk0dwjhTXypcQ9lYdD9bB4LaPSPYPdOqsAcYh8336yulOSyF/vT7P83Gv9qVBJysAAAAAElFTkSuQmCC"
/***/ }),
/***/ "4u4S":
/*!*********************************************!*\
!*** ./src/assets/images/icons/groups2.png ***!
\*********************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports) {
module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAALoAAABSCAYAAADjGc4eAAASm0lEQVR4Xu2dd5QUVRbGfz3kJDkKCJJBAVFWRUUkGFBQEFRWFhUWmBlAoqCoMGKAVcC8CLKLBEEkKCZMgKjkqIIIKCKiMCAsUfLUntuvi+7pqeqq7q7pcbrrncMfTL10v/f1q/vuu/eWR0vmBaA/bnERiGMEPFoaSaTzLhrt4lhOV7QER8Aj8mtDKMJxlqJxeYLj4Yofpwh4ie4l+wAqcopVaFSJU1ldsRIYgfNE95K9L5dyjq/RuCCBMXFFj0MEMhHdS/ZUbkTjQzTyxqG8rkgJikAWonvJnkIvNCYmKCau2HGIgCHRfWQfg8awOJTZFSkBETAnuoaHFN4GOiUgLq7IcYaAKdG9u3oaBUlnCRpXxZncrjgJhkBIonvJ3o+ynGUlGhcnGDauuHGEgCXRfWbHupxjORol40h2V5QEQsAW0X1kb8FZPgHyJxA+rqhxgoBtovts7N3IYGqcyO6KkUAIhEV0H9nTyGBkAmHkihoHCIRNdJ+NfToaXeNAfleEBEEgMqKnkZ+9fAY0TxCcXDFzOQIREd27qw+kFCdZgUbtXI6BO/0EQCBiovts7DU4w0qgTAJg5YqYixGIiui+w2kzMlgEFMzFODg/9dLVISkPHN0PJw+b91+gGGSchTMnnJ9DcI9FSsNFTeHgL5C+DbRzmWt48mT9m5OzkvFLXAgHdsLJI072bNlX1ET3kf1uMpgFONKf5axzQ4Uxe6B4BXi7Pyx5yXzGveZBo9th21J4sVX0kpW6CA79DhlnsvZ1xT3QYxZoGgwsDqeO+utUuhRSFsCcgfDtgujnYdRDp/HQaqCa3/Cq2fujChrfMWJqyTwMjM4ehCx6HbgESla1P/TLN8P+7ap+gaLw6Df22r4zFDbMs1fXDtGrXw1Dl6v+5g2Bz8fZ69usVlI+GPsH5C8Mb3SDtbL3BJQOz8KND8HerfBE3czP+nwIl7RVP4J3H4FP/xXdXIJb5ysEo3+DIiXh49GwYLiz/Vv05hjRvTt7CpPR6BFTCWSwUT9B2TBccUZdAns2q2kWvACeD6FaBAoz9QFY+YY98ayIXrgUPLwaytZQ/f260Vp9WfwirJttPn6t62HQF+r5o9Xh4M7MdfsvgrotYfVMmHJv5mf5CkP3N6HxHervy6fAjH+ClmFPXqtaV90P901RtUbU9m80Vu0ceu4s0dPISzoL0Wjt0PzsdaMT/dNnYcN84zYeDwxdoZ6ZEX3BY/D7pqztH5gBBYuCEdFLVgHRbYNJFYroeQtCv4VQu4U9+fRaolYsluwkJuWOMXDTMNizBUbVz1pp7EG1o84dDIvGZ33uSQJRL1r6sp+smArTuztD9mGroNrfYPtXMD72VmlHiS7IacMozhGWodEgvFWMorZO9Jkp8NVrJkRPgn/7Dl9mRB/fArYvNSDIAShSKivRWw+BDv+CrYvhpTaZ25kR/YIKkPwuVL9S1V/4NOz+1lx4qdd6kHo+/gbY7tuxjVo8uhEqN4LPxsH8IZlryOH4qR2+fkzk1FvcOhJuS1P/+3oyvNlLVtZ4jqI21rjWevHy+CIzRTXKCDoEW7f21xhWEY7/EU4Lb13Hie4lex8uIsPr2lsh7BlF0iCniC67+Yjv1W7/SlvYvNA/eyOiN7gF7p0EJStDRgbMTIZlr5tLfEFFeGQtlKgEa96C/3Yxr1u8Eoz5TT1/oZX68QWWy+6EXnOVDj6ohLXVo/OL0PJB9XZ4rhmcOGQ89qAvodZ1kaxaZG2GlP3rEN1L9r5cwVlkeywcmURhtMopossUWw2CTuPg983wVCO/JSGQ6GtnQ9fJ0PA2JdSp4zC9B2z7Apo9oHbgYCtJ3gIgu+XFV8PJozCyDhzZYw5Ks+7wj/+ouoNLZ+2v/dNwy3BlVkyrYwNcD7R/Epa8DEfTzetXuQwKlTB/ftV9cPV96vmMXrD/Rxtjh6jy49fGFiWLXrNlR9fH1PpwOxnMRyMpOuksWutEF/1PP2QGNxEd/bre6q9OqS7Sl+jnw9dD5YZqIfUdOpDoSyfAgM+hVnPYtBBmpSj7+uPfqUO0EH5SJzh+QM2vfF11MKzaRL3mp3WHVdNCg9BzDjTpBAd/hdVvZq0rh8wKdWH/T7BuTmTL8et6WB9G28qN1bkoX0H48jUldw6VbCW6yKSlMACN57NVPqesLuHq6LpQjTpA8nw4vBdG1oJTxyBYdSlaFmrfAOslDNdXqjRR+nqpKrB/B0xoD2I5uXMs5C8EJ4/Bf+6BTR+Ghi8pLzy3HwqH2FmdWICV02Cqb3e26k+sWaJ2laulZHuqIZw+7m8lF2W9fabaN+4L/bayGsvG82wnuo/sr6DRx8Z8IquiE/3b92HnauM+ZEdvN8r5Hd3bo0ftzpUawIej4IORWYluJlmxctBzrtJzZfeW21Qp/9sNr94Gv9mw8ctBU9QnsyLPqzRW+vk370aGsbSSN0+oy6/Anv85Gy6/S51Fnm8BP36VeVwxr47zvcEerwF/+A7Kkc8uZMvYEP1t8rCEBWjcmi1y5KSOrgvU9O9K3fh5FTx3DYzebX0zWqE+NO2i/un29DOn4OtJyhoTSjcOB0iddDtWqINldpfmqdDlVTWKkQVI/h6PRPfu6qkUReNLNC5zHOe/AtFFVxdT4A7fTaeR1aVIGWU7r3MD1GmpdGa9CMGXTVa3hod91hMngCpcUr1d8hWAOYNgcfZqkV5fmsFfqfHEYvNMEzh7Mqsk8Up0L9n7UomzrAIqO7GG5/v4KxA9WCAjot/9MrTom7nmrvUgKpeQ/NBu/zOx5jRPgd0b4fXOkcMlfXT5t1JbxL8kcIzIezVuKT/e3u9AIV/qziPpcHSfcV05V1Ssp56JJejsqdCzmXA7HPg54hnHRHUJnJ3Wj0acQRS2YhHPOrihTvR3HoaVJiGtcuun25mdtLqYCWG4o5dWurxO7u8+MN+9dXOgqELPRpFWR7+RPH0CNn0UHuTiYSg3o3aKqG7dpkDe/OpHJWciJ8sT9WHvloh7dHg29uahpdKODN6zV9tGrZy2uhhN0exmVH5wdvxHnCB6xQYwwsClwQak3irH/oCHylrXbjMUOoxR5D5xGOYOUjZ9KVPvhxMGLrkFi8H9vk1pVqqyWAUXsTzJuUdKWj1I/8F6LiY1coboyYijxcCIZ222o9vtMLt3dCHzs+lQtIzfTff6vnBRGN9ZENOj2OaFbLLz60V2eDM3h2D5u89UB129rJ8LPy2zRkns8TWuUW+e0SHmLHLe9aJfHRNLkdwQy6XV0z41w+wm046OLp6lL/hciXMb0bUUuqIx3RrtMGroO/rbA2C5bycJ1fz0n/5dNdB7MVI7euBYYh8Wgum3oLo/eu/50LhDGEKZVJVbVrGtW5ULG4L4vsguK/7f4kYgRHzyUvPrfOmz+IWQ9oNya5jUGTbMNR9J9y+XGr99p0guZ4BS1RKb6FoKl6PxtePRSHYOo2bL5STRZYFT34cLL/GPphP9mp7Klm23VLtSvQGO7MtMtl3rYPl/rXtJeQ8atoPDe+CZy5Xfe+lqxi66gb31eAuuuFu5NMiPwsyZS9qIeVRcjeUtM7GjP5IqkYmuJVMOD2uz5dMxVkQXX4zrU+GTMVn1Y6eILh58smsXKwt/HgLxVREd0yzCyCpsLRodPTCgQwIwVk2Huq2hvyRuQLkUrPD5hgeS/NLb1A9VyuR7Qvu+6+1kLPnxnTvt7ylRia5NJB8bWYRG9ri5hSK66JEjNiubtRx6vpyQeTeMluhCWHGWajsCxBX1wC/wyi0wYLHxhVH+IuqGtt6NMO46czUiUqKL2e6hZcr3+6flMFZcaH0utve+DtdKMIWmfNIDbeoN2qorefFL2fwxvHqrvUOz0bslYYmewgQ0kq3ftxHWsNrRW/SDu19SO6147gXadqMhetmacP90uNhn/pPDmxDkyF5zFwAh+tCVSr3ZugReusnYGy9Sord7Eto+pq7exzQFccTSi4TadZ+hrualLHoB5g2Ghu1Bbk/FNLhjpXLzPfNnhItBYuroWio9yWBS5KjZaGlFdNl1H14DVS+DYMckK6JLiNm4g+qmT5yPAr0Iu0yA5r7fr4SnSYCC7rgUKsKoTA01H4n2kZA1I1t1JESveR0M/AKSkuCricrfPbjIG+7vE9XOLkU8PsUVWN5GopePaw5/HrQBeogqibaja6lIKowl2Z6B14rosiZNOkNPn+egLKbuZGREdLlN1O3d9W+GRu3VqqbVhfSt/hUuWwuGr4M5Yu0JOiBaxYzWvwn6fKRIKbbm4IuucIku55DHvoFSVeH4/5QXpe72a8TJwB+pPJc2cvh0wv3AKaIHBpP8Vc2L3uv+c6yLSZSRGdELFlc+2ld2Ve6v+m2dV3e9Ri2/EdEf/AzqBYW9eq0QAdYUnTzifWh0zW1FdGnfcSy0GawCMcQnZN82PyXDIbocfMXKUv9GpX9P6QprZhpvuXnyw/V9oO3j6o0SWHaugfdHwPcf58yOLq7Mkvfl7Gl1kJd5SmCKXEI9VC7zgTfMGWbLhZHWjwKc4Uvgb2HOJ7LqT+6AMtVBYkY3zlc6Z6M7lKVBVA697PkeRK8WXfSVW2HzR8ZEl2idayVO0hcN9N37IPbrUBE+wTO3Q3Qh6CPr4OAumPZAZm9Fu0QX4kpuGN1u/1Y/WPqKMY6NO6oY13I11XPxdxdLVKVLlEnx/EawTBE+OBzP7upEuqOL6jVYaBNUJEh72v12Rzeslz1ET0ZsV9HNzK5YNZurFA+ySGIzLlZeqQN6kZvFNbOUbr5rLeivbO+t3xUgV9F6uguzCyO7cwmsZ4foUt/sjdDxOWgzRNmozXxdxMIi6ph+ESX5WIS4gUXyqUjiInEmk4glvcgPVywvuqoidnvxaZcbUb3s2qAipuT8ESrbWDA+kRJdDstP71R5aaRIRjGJhhJT6OHfI1mF820cJ7qWzIPAi1HNKpzGElcZnDbi2AHY8qnahcWRKTAes0RlGPWjOnDJRYocHnOS6CKrvLJFffGmpdOU1eLBT6B8bZW+Y9KdxoiISbPdE+qZ+K+/95i/XpmLlfejvJ0kg4Fe5K02u5/5bi1B1Lc/o8bWiziESQideFgGB1AYzUwIq/vX79tunJHLjgtAODywqOso0bW+tOAcn8X0q9PNeqjI+l/WKPuv6JcSZRTKcUoCduUHcGy/seriBMB2d3QZS4I0RDcV/frMSaWf6iXUNXz5OvD4Jlj6qjoQ60VUoqd+huIV/X+ToOLPx6t0c5ZOZR5ocLPSkSVzgf6GFBVLgrSN/MvDxSy3Et2b4uIca2OeWVdezfKqC2VhCLUIVubFcBdQrx8O0SWUrknQrr3vRxX29t7joYklFz3eNBtBeVfE5UD80MWRS5IVyUYQSQl8M8gt7+oZkfSStU1uJLqWRmHSvUmLwnDmcAav6Hvx+Hc+0ecDr7Kj6bxcbRAdWi6PrOzS8mMTTz29SOxotGF0Yh4V85xTgRayocjbJpTvSzh4yd2G7vsj2dGsAi/C6dugriOqi5bCLDRsuNRFOVu3uYtAhAhETXQtlaFk4HDq1QilcZu5CJggEBXRtWRuwsNH2Z6gyF0+F4EoEYiY6FoqNdFY7X5NOsoVcJvHBIGIiO5LXSFJRGOXMTcmcLiDxCsCYRNd0/CQ6s2n6MsYH6/QuHLFEwLhEz3Z+9VoX/LseILClSWeEQiL6N7suOd4J7vyqscz0K5sOYuAbaJrqdQjw5tly7nEQzkruzt6AiFgi+jaAEpwEklTWyuBsHFFjSMELImupZFEOh+gcUscye2KkmAIWBM9ldFkeL8h6hYXgVyLQEiia324i3OE+LBlrpXbnXiCIWBKdF/WW0n2nf0f20ow0F1xY4+AIdG1PpT2+ZZXi/2U3BFdBJxHIAvRNfX150/QaOn8cG6PLgI5g0BWoicj3+D2fSM7Zybljuoi4DQCmYiupdKNDEw+GeH00G5/LgKxQ+A80bVUmpLhzcVSMHbDuyO5CMQGAS/Rtf6U55Q3sNnZj2jFRgZ3FBcBSwQ83pTOG7z5EQMy11i2cyu4COQqBDxaMq8BvXPVrN3JugiEiYClC0CY/bnVXQRii0DHWkEJbYKG95ABnmSX6LFdFnc0pxEISXTPWTxaN+Ztn+US3Wng3f5ii4A50U/hydOZeT94P8rkEj22y+KO5jQCRkT3eI6T5GnPHH/ea5foTgPv9hdbBLIS/RD58t7C7C0rAyfiEj22y+KO5jQCmYm+j3yeG5m97ZvgYVyiOw28219sEfATfTd5klozZ2vAR6b8U3GJHttlcUdzGgFF9J8gbyvmb/nFrHuX6E4D7/YXWwTurLWJQnnbMGPLnlADu0SP7bK4ozmNQLe6pZn2wwGrbv8PSygpSs9Cw9cAAAAASUVORK5CYII="
/***/ }),
/***/ "5D2P":
/*!*******************************************!*\
!*** ./src/assets/images/icons/done3.png ***!
\*******************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports) {
module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAFTklEQVRoQ91aS4xURRQ993UzUUZcqFEc4meh0cQFSlwgrvAHSgQWhOhCk4GZqmdw+ERUWDkrBMUBnIzzqqYjcTaaGBLFxA8MjIk/3PhZCCa6UAyKC11ARnDo6Wvu+HrS0/R7r96nWVBJpxfv3nPPrbp169aHUEAzxsxl5gcB3AdgAREtkH8AXSH87wBOMfMp+QfwFREd0Vr/k9c8ZQUwxixi5mWe5y1l5qUAyimxqkQ0XqvVxonoE631Nyn1p8VTO7B///75Fy5c2MzMWwB0ZDHaQmeSiPbMmTNnb3d39+k0mKkcMMZsBiC/W9IYSSH7K4C9Wuu9rjpODoyMjNxQq9VGADzuCpxT7gPP83p7e3v/TMJJdCAIgoVEdBDAzUlgBX8/ycwrfd//Pg431gFr7RPM/HbBxFLBEdGTSql3opQiHQiCoI+IXk9lrU3CzLzR9/3BVvAtHbDWPsrMH7aJTyZYInpMKfVRs/JFDlQqlduq1eoxIro2k6U2KTHzX+VyeXFPT8/PjSYucsBae4iZH24Tj1ywRHRYKfVIpANhnt+Ty0r7lbc0rhMzI2CMuRHAlwBubT+HXBZ+AbBEa/3HrFLCWruTmV/MBZ1N+TiAdyNUX2qZeYh2KaW2zThQqVTumZqaOlZgbePqynEiWquU+qFZwRjzBoBnIoAmS6WSTOhvp0PIGPMcgN2uVguSiyQfBIFPRMMJdrZqrV+bdsBa+x4zryqImAtMJHlr7RJmPgxgbhwQEb2vlFpNAwMDV3Z2dp7JUM+7EG0lE0l+dHS089y5c4dkkjqAVycmJq4ma+0yZv7YQaEIkUjyAh4EwTAR+a6GiGg5BUGwg4i2uyrlkEsi7xL3s8wz88syAm8x89M5iLmoxpIP4348bRYkolEyxowBkA25S1sLQJbyHhfhUCaWvMT9+fPnx5h5cQrMuugRceAEgDsdlKfTVph2rwMgC4mk37gWSz5L3DcZ+1EckAw0L44FM4/4vq+aZfr7+zu6urq2MbPMoSuavieSt9b6zJyU7+OonXVygIjWKKUOxCGFhaA4cj0AF/KS7z8D4DmMfpTIGdcQOgtgldZaJlpss9auA/B1q/Kgrhjm+08B3JuEF/ediE44T2IikiOP1Uqp7/IYDePeElFvXhwAY2nTqJCXkTiZ1XgBcT9jmplHxYEd4SR04kRER0ul0ur169dLWKVqYb7/IpVSjHB9IctSShzQWq9JQySMeyG/MI1ewhxYnqeYq2itnePYGPMmgO6iyAP4v5gTwBzl9Cta68RdnDHmWQAtz3WyOjRTTodZYSsRvZoRbLvWemeU7vDw8P2e532eETtSjZmf931/d31HtkguHdIWUw3oWmttm60NDQ1dVS6XZat6V8EOTMplitwpNJ5K7ALwQg5Da7XWszbnxphRAE/lwIxSnQnd5mMVGYWsZ///MvMK3/ePiFVjjFyADLSBvCyo0vuzj1VCo3J5kflgi5lPE9EKIprHzFIqtKO1PtiqWzLGyIb6oRyW5ZynBOCOHBhRqmNa61nHnhedjQZBcDsRycS7pg0E8kD+LZse3/d/agS5/I7XG0JpI4B9ebqsQN1NWuuWly2X7xVTvfestXfXarWDRHRTgT2aCMXMv3metzJp/5F4SymWhoaG5pfLZVlpL9k1a7VaVRs2bEi89HZyIOwu2b1tukQX3TL3OHGYsjw1GBwc7Oro6Kg7UthTA7mhn5yc3NfX1ycPQ5xbmhGYBSqPPYhINkMPAJDHHrJ4pWlTAOShx1FmvnSPPVoxbHxu43neAmauP7eRf2nTz2yI6FStViv0uc1/ndZCH8rgOooAAAAASUVORK5CYII="
/***/ }),
/***/ "5Uyt":
/*!********************************************************!*\
!*** ./node_modules/@ant-design/icons/FilterFilled.js ***!
\********************************************************/
/*! no static exports found */
/*! exports used: default */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _FilterFilled = _interopRequireDefault(__webpack_require__(/*! ./lib/icons/FilterFilled */ "KmBX"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _default = _FilterFilled;
exports.default = _default;
module.exports = _default;
/***/ }),
/***/ "5YOS":
/*!********************************************************!*\
!*** ./node_modules/@ant-design/icons/RedoOutlined.js ***!
\********************************************************/
/*! no static exports found */
/*! exports used: default */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _RedoOutlined = _interopRequireDefault(__webpack_require__(/*! ./lib/icons/RedoOutlined */ "xb2K"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _default = _RedoOutlined;
exports.default = _default;
module.exports = _default;
/***/ }),
/***/ "5hvy":
/*!****************************************!*\
!*** ./node_modules/crypto-js/sha3.js ***!
\****************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory, undef) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"), __webpack_require__(/*! ./x64-core */ "MlIO"));
}
else {}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var C_algo = C.algo;
// Constants tables
var RHO_OFFSETS = [];
var PI_INDEXES = [];
var ROUND_CONSTANTS = [];
// Compute Constants
(function () {
// Compute rho offset constants
var x = 1, y = 0;
for (var t = 0; t < 24; t++) {
RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64;
var newX = y % 5;
var newY = (2 * x + 3 * y) % 5;
x = newX;
y = newY;
}
// Compute pi index constants
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5;
}
}
// Compute round constants
var LFSR = 0x01;
for (var i = 0; i < 24; i++) {
var roundConstantMsw = 0;
var roundConstantLsw = 0;
for (var j = 0; j < 7; j++) {
if (LFSR & 0x01) {
var bitPosition = (1 << j) - 1;
if (bitPosition < 32) {
roundConstantLsw ^= 1 << bitPosition;
} else /* if (bitPosition >= 32) */ {
roundConstantMsw ^= 1 << (bitPosition - 32);
}
}
// Compute next LFSR
if (LFSR & 0x80) {
// Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1
LFSR = (LFSR << 1) ^ 0x71;
} else {
LFSR <<= 1;
}
}
ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw);
}
}());
// Reusable objects for temporary values
var T = [];
(function () {
for (var i = 0; i < 25; i++) {
T[i] = X64Word.create();
}
}());
/**
* SHA-3 hash algorithm.
*/
var SHA3 = C_algo.SHA3 = Hasher.extend({
/**
* Configuration options.
*
* @property {number} outputLength
* The desired number of bits in the output hash.
* Only values permitted are: 224, 256, 384, 512.
* Default: 512
*/
cfg: Hasher.cfg.extend({
outputLength: 512
}),
_doReset: function () {
var state = this._state = []
for (var i = 0; i < 25; i++) {
state[i] = new X64Word.init();
}
this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32;
},
_doProcessBlock: function (M, offset) {
// Shortcuts
var state = this._state;
var nBlockSizeLanes = this.blockSize / 2;
// Absorb
for (var i = 0; i < nBlockSizeLanes; i++) {
// Shortcuts
var M2i = M[offset + 2 * i];
var M2i1 = M[offset + 2 * i + 1];
// Swap endian
M2i = (
(((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) |
(((M2i << 24) | (M2i >>> 8)) & 0xff00ff00)
);
M2i1 = (
(((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) |
(((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00)
);
// Absorb message into state
var lane = state[i];
lane.high ^= M2i1;
lane.low ^= M2i;
}
// Rounds
for (var round = 0; round < 24; round++) {
// Theta
for (var x = 0; x < 5; x++) {
// Mix column lanes
var tMsw = 0, tLsw = 0;
for (var y = 0; y < 5; y++) {
var lane = state[x + 5 * y];
tMsw ^= lane.high;
tLsw ^= lane.low;
}
// Temporary values
var Tx = T[x];
Tx.high = tMsw;
Tx.low = tLsw;
}
for (var x = 0; x < 5; x++) {
// Shortcuts
var Tx4 = T[(x + 4) % 5];
var Tx1 = T[(x + 1) % 5];
var Tx1Msw = Tx1.high;
var Tx1Lsw = Tx1.low;
// Mix surrounding columns
var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31));
var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31));
for (var y = 0; y < 5; y++) {
var lane = state[x + 5 * y];
lane.high ^= tMsw;
lane.low ^= tLsw;
}
}
// Rho Pi
for (var laneIndex = 1; laneIndex < 25; laneIndex++) {
var tMsw;
var tLsw;
// Shortcuts
var lane = state[laneIndex];
var laneMsw = lane.high;
var laneLsw = lane.low;
var rhoOffset = RHO_OFFSETS[laneIndex];
// Rotate lanes
if (rhoOffset < 32) {
tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset));
tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset));
} else /* if (rhoOffset >= 32) */ {
tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset));
tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset));
}
// Transpose lanes
var TPiLane = T[PI_INDEXES[laneIndex]];
TPiLane.high = tMsw;
TPiLane.low = tLsw;
}
// Rho pi at x = y = 0
var T0 = T[0];
var state0 = state[0];
T0.high = state0.high;
T0.low = state0.low;
// Chi
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
// Shortcuts
var laneIndex = x + 5 * y;
var lane = state[laneIndex];
var TLane = T[laneIndex];
var Tx1Lane = T[((x + 1) % 5) + 5 * y];
var Tx2Lane = T[((x + 2) % 5) + 5 * y];
// Mix rows
lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high);
lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low);
}
}
// Iota
var lane = state[0];
var roundConstant = ROUND_CONSTANTS[round];
lane.high ^= roundConstant.high;
lane.low ^= roundConstant.low;
}
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
var blockSizeBits = this.blockSize * 32;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32);
dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Shortcuts
var state = this._state;
var outputLengthBytes = this.cfg.outputLength / 8;
var outputLengthLanes = outputLengthBytes / 8;
// Squeeze
var hashWords = [];
for (var i = 0; i < outputLengthLanes; i++) {
// Shortcuts
var lane = state[i];
var laneMsw = lane.high;
var laneLsw = lane.low;
// Swap endian
laneMsw = (
(((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) |
(((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00)
);
laneLsw = (
(((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) |
(((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00)
);
// Squeeze state to retrieve hash
hashWords.push(laneLsw);
hashWords.push(laneMsw);
}
// Return final computed hash
return new WordArray.init(hashWords, outputLengthBytes);
},
clone: function () {
var clone = Hasher.clone.call(this);
var state = clone._state = this._state.slice(0);
for (var i = 0; i < 25; i++) {
state[i] = state[i].clone();
}
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA3('message');
* var hash = CryptoJS.SHA3(wordArray);
*/
C.SHA3 = Hasher._createHelper(SHA3);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA3(message, key);
*/
C.HmacSHA3 = Hasher._createHmacHelper(SHA3);
}(Math));
return CryptoJS.SHA3;
}));
/***/ }),
/***/ "5yev":
/*!********************************************************************!*\
!*** ./node_modules/@ant-design/icons-svg/lib/asn/RedoOutlined.js ***!
\********************************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// This icon file is generated automatically.
Object.defineProperty(exports, "__esModule", { value: true });
var RedoOutlined = { "icon": { "tag": "svg", "attrs": { "viewBox": "64 64 896 896", "focusable": "false" }, "children": [{ "tag": "path", "attrs": { "d": "M758.2 839.1C851.8 765.9 912 651.9 912 523.9 912 303 733.5 124.3 512.6 124 291.4 123.7 112 302.8 112 523.9c0 125.2 57.5 236.9 147.6 310.2 3.5 2.8 8.6 2.2 11.4-1.3l39.4-50.5c2.7-3.4 2.1-8.3-1.2-11.1-8.1-6.6-15.9-13.7-23.4-21.2a318.64 318.64 0 01-68.6-101.7C200.4 609 192 567.1 192 523.9s8.4-85.1 25.1-124.5c16.1-38.1 39.2-72.3 68.6-101.7 29.4-29.4 63.6-52.5 101.7-68.6C426.9 212.4 468.8 204 512 204s85.1 8.4 124.5 25.1c38.1 16.1 72.3 39.2 101.7 68.6 29.4 29.4 52.5 63.6 68.6 101.7 16.7 39.4 25.1 81.3 25.1 124.5s-8.4 85.1-25.1 124.5a318.64 318.64 0 01-68.6 101.7c-9.3 9.3-19.1 18-29.3 26L668.2 724a8 8 0 00-14.1 3l-39.6 162.2c-1.2 5 2.6 9.9 7.7 9.9l167 .8c6.7 0 10.5-7.7 6.3-12.9l-37.3-47.9z" } }] }, "name": "redo", "theme": "outlined" };
exports.default = RedoOutlined;
/***/ }),
/***/ "6/k+":
/*!********************************************************!*\
!*** ./node_modules/antd/es/carousel/style/index.less ***!
\********************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/***/ "6Fuo":
/*!******************************************************************!*\
!*** ./src/components/Header/components/Join/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___3p8A0","flex_space_between":"flex_space_between___2wMwo","flex_box_vertical_center":"flex_box_vertical_center___2fKhV","flex_box_center_end":"flex_box_center_end___27Yk8","flex_box_column":"flex_box_column___3Khbo","dropdownFlex":"dropdownFlex___A4YIX","joinModal":"joinModal___VuDUK","rightMenu":"rightMenu___20Eel","joinMenu":"joinMenu___2blJt","joinBoard":"joinBoard___2XUXK","joinCol":"joinCol___3o5gp"};
/***/ }),
/***/ "6SEX":
/*!*************************************************************!*\
!*** ./node_modules/@ant-design/icons/CaretDownOutlined.js ***!
\*************************************************************/
/*! no static exports found */
/*! exports used: default */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _CaretDownOutlined = _interopRequireDefault(__webpack_require__(/*! ./lib/icons/CaretDownOutlined */ "qWUW"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _default = _CaretDownOutlined;
exports.default = _default;
module.exports = _default;
/***/ }),
/***/ "6VBw":
/*!******************************************************************************!*\
!*** ./node_modules/@ant-design/icons/es/components/AntdIcon.js + 5 modules ***!
\******************************************************************************/
/*! exports provided: default */
/*! exports used: default */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/node_modules/@ant-design/colors/dist/index.esm.js (<- Module is referenced from these modules with unsupported syntax: ./node_modules/@ant-design/icons/lib/utils.js (referenced with cjs require)) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/defineProperty.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-util/es/Dom/canUseDom.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/warning.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/react/index.js (<- Module is not an ECMAScript module) */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/objectSpread2.js
var objectSpread2 = __webpack_require__("VTBJ");
// 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/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/react/index.js
var react = __webpack_require__("q1tI");
var react_default = /*#__PURE__*/__webpack_require__.n(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/@ant-design/icons/es/components/Context.js
var IconContext = /*#__PURE__*/Object(react["createContext"])({});
/* harmony default export */ var Context = (IconContext);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/typeof.js
var esm_typeof = __webpack_require__("U8pU");
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/node_modules/@ant-design/colors/dist/index.esm.js + 4 modules
var index_esm = __webpack_require__("u3cA");
// EXTERNAL MODULE: ./node_modules/rc-util/es/warning.js
var warning = __webpack_require__("Kwbf");
// EXTERNAL MODULE: ./node_modules/rc-util/es/Dom/canUseDom.js
var canUseDom = __webpack_require__("MNnm");
// CONCATENATED MODULE: ./node_modules/rc-util/es/Dom/dynamicCSS.js
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["a" /* default */])()) {
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;
}
// CONCATENATED MODULE: ./node_modules/@ant-design/icons/es/utils.js
function utils_warning(valid, message) {
Object(warning["a" /* default */])(valid, "[@ant-design/icons] ".concat(message));
}
function isIconDefinition(target) {
return Object(esm_typeof["a" /* default */])(target) === 'object' && typeof target.name === 'string' && typeof target.theme === 'string' && (Object(esm_typeof["a" /* default */])(target.icon) === 'object' || typeof target.icon === 'function');
}
function normalizeAttrs() {
var attrs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return Object.keys(attrs).reduce(function (acc, key) {
var val = attrs[key];
switch (key) {
case 'class':
acc.className = val;
delete acc.class;
break;
default:
acc[key] = val;
}
return acc;
}, {});
}
function generate(node, key, rootProps) {
if (!rootProps) {
return /*#__PURE__*/react_default.a.createElement(node.tag, Object(objectSpread2["a" /* default */])({
key: key
}, normalizeAttrs(node.attrs)), (node.children || []).map(function (child, index) {
return generate(child, "".concat(key, "-").concat(node.tag, "-").concat(index));
}));
}
return /*#__PURE__*/react_default.a.createElement(node.tag, Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({
key: key
}, normalizeAttrs(node.attrs)), rootProps), (node.children || []).map(function (child, index) {
return generate(child, "".concat(key, "-").concat(node.tag, "-").concat(index));
}));
}
function getSecondaryColor(primaryColor) {
// choose the second color
return Object(index_esm["generate"])(primaryColor)[0];
}
function normalizeTwoToneColors(twoToneColor) {
if (!twoToneColor) {
return [];
}
return Array.isArray(twoToneColor) ? twoToneColor : [twoToneColor];
} // These props make sure that the SVG behaviours like general text.
// Reference: https://blog.prototypr.io/align-svg-icons-to-text-and-say-goodbye-to-font-icons-d44b3d7b26b4
var svgBaseProps = {
width: '1em',
height: '1em',
fill: 'currentColor',
'aria-hidden': 'true',
focusable: 'false'
};
var iconStyles = "\n.anticon {\n display: inline-block;\n color: inherit;\n font-style: normal;\n line-height: 0;\n text-align: center;\n text-transform: none;\n vertical-align: -0.125em;\n text-rendering: optimizeLegibility;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n\n.anticon > * {\n line-height: 1;\n}\n\n.anticon svg {\n display: inline-block;\n}\n\n.anticon::before {\n display: none;\n}\n\n.anticon .anticon-icon {\n display: block;\n}\n\n.anticon[tabindex] {\n cursor: pointer;\n}\n\n.anticon-spin::before,\n.anticon-spin {\n display: inline-block;\n -webkit-animation: loadingCircle 1s infinite linear;\n animation: loadingCircle 1s infinite linear;\n}\n\n@-webkit-keyframes loadingCircle {\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n\n@keyframes loadingCircle {\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n";
var utils_useInsertStyles = function useInsertStyles() {
var styleStr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : iconStyles;
var _useContext = Object(react["useContext"])(Context),
csp = _useContext.csp;
Object(react["useEffect"])(function () {
updateCSS(styleStr, '@ant-design-icons', {
prepend: true,
csp: csp
});
}, []);
};
// CONCATENATED MODULE: ./node_modules/@ant-design/icons/es/components/IconBase.js
var _excluded = ["icon", "className", "onClick", "style", "primaryColor", "secondaryColor"];
var twoToneColorPalette = {
primaryColor: '#333',
secondaryColor: '#E6E6E6',
calculated: false
};
function setTwoToneColors(_ref) {
var primaryColor = _ref.primaryColor,
secondaryColor = _ref.secondaryColor;
twoToneColorPalette.primaryColor = primaryColor;
twoToneColorPalette.secondaryColor = secondaryColor || getSecondaryColor(primaryColor);
twoToneColorPalette.calculated = !!secondaryColor;
}
function getTwoToneColors() {
return Object(objectSpread2["a" /* default */])({}, twoToneColorPalette);
}
var IconBase_IconBase = function IconBase(props) {
var icon = props.icon,
className = props.className,
onClick = props.onClick,
style = props.style,
primaryColor = props.primaryColor,
secondaryColor = props.secondaryColor,
restProps = Object(objectWithoutProperties["a" /* default */])(props, _excluded);
var colors = twoToneColorPalette;
if (primaryColor) {
colors = {
primaryColor: primaryColor,
secondaryColor: secondaryColor || getSecondaryColor(primaryColor)
};
}
utils_useInsertStyles();
utils_warning(isIconDefinition(icon), "icon should be icon definiton, but got ".concat(icon));
if (!isIconDefinition(icon)) {
return null;
}
var target = icon;
if (target && typeof target.icon === 'function') {
target = Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, target), {}, {
icon: target.icon(colors.primaryColor, colors.secondaryColor)
});
}
return generate(target.icon, "svg-".concat(target.name), Object(objectSpread2["a" /* default */])({
className: className,
onClick: onClick,
style: style,
'data-icon': target.name,
width: '1em',
height: '1em',
fill: 'currentColor',
'aria-hidden': 'true'
}, restProps));
};
IconBase_IconBase.displayName = 'IconReact';
IconBase_IconBase.getTwoToneColors = getTwoToneColors;
IconBase_IconBase.setTwoToneColors = setTwoToneColors;
/* harmony default export */ var components_IconBase = (IconBase_IconBase);
// CONCATENATED MODULE: ./node_modules/@ant-design/icons/es/components/twoTonePrimaryColor.js
function setTwoToneColor(twoToneColor) {
var _normalizeTwoToneColo = normalizeTwoToneColors(twoToneColor),
_normalizeTwoToneColo2 = Object(slicedToArray["a" /* default */])(_normalizeTwoToneColo, 2),
primaryColor = _normalizeTwoToneColo2[0],
secondaryColor = _normalizeTwoToneColo2[1];
return components_IconBase.setTwoToneColors({
primaryColor: primaryColor,
secondaryColor: secondaryColor
});
}
function getTwoToneColor() {
var colors = components_IconBase.getTwoToneColors();
if (!colors.calculated) {
return colors.primaryColor;
}
return [colors.primaryColor, colors.secondaryColor];
}
// CONCATENATED MODULE: ./node_modules/@ant-design/icons/es/components/AntdIcon.js
var AntdIcon_excluded = ["className", "icon", "spin", "rotate", "tabIndex", "onClick", "twoToneColor"];
// Initial setting
// should move it to antd main repo?
setTwoToneColor('#1890ff');
var Icon = /*#__PURE__*/react["forwardRef"](function (props, ref) {
var _classNames;
var className = props.className,
icon = props.icon,
spin = props.spin,
rotate = props.rotate,
tabIndex = props.tabIndex,
onClick = props.onClick,
twoToneColor = props.twoToneColor,
restProps = Object(objectWithoutProperties["a" /* default */])(props, AntdIcon_excluded);
var _React$useContext = react["useContext"](Context),
_React$useContext$pre = _React$useContext.prefixCls,
prefixCls = _React$useContext$pre === void 0 ? 'anticon' : _React$useContext$pre;
var classString = classnames_default()(prefixCls, (_classNames = {}, Object(defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-").concat(icon.name), !!icon.name), Object(defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-spin"), !!spin || icon.name === 'loading'), _classNames), className);
var iconTabIndex = tabIndex;
if (iconTabIndex === undefined && onClick) {
iconTabIndex = -1;
}
var svgStyle = rotate ? {
msTransform: "rotate(".concat(rotate, "deg)"),
transform: "rotate(".concat(rotate, "deg)")
} : undefined;
var _normalizeTwoToneColo = normalizeTwoToneColors(twoToneColor),
_normalizeTwoToneColo2 = Object(slicedToArray["a" /* default */])(_normalizeTwoToneColo, 2),
primaryColor = _normalizeTwoToneColo2[0],
secondaryColor = _normalizeTwoToneColo2[1];
return /*#__PURE__*/react["createElement"]("span", Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({
role: "img",
"aria-label": icon.name
}, restProps), {}, {
ref: ref,
tabIndex: iconTabIndex,
onClick: onClick,
className: classString
}), /*#__PURE__*/react["createElement"](components_IconBase, {
icon: icon,
primaryColor: primaryColor,
secondaryColor: secondaryColor,
style: svgStyle
}));
});
Icon.displayName = 'AntdIcon';
Icon.getTwoToneColor = getTwoToneColor;
Icon.setTwoToneColor = setTwoToneColor;
/* harmony default export */ var AntdIcon = __webpack_exports__["a"] = (Icon);
/***/ }),
/***/ "6xvX":
/*!*******************************************************!*\
!*** ./node_modules/@ant-design/icons/FileTwoTone.js ***!
\*******************************************************/
/*! no static exports found */
/*! exports used: default */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _FileTwoTone = _interopRequireDefault(__webpack_require__(/*! ./lib/icons/FileTwoTone */ "V7ic"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _default = _FileTwoTone;
exports.default = _default;
module.exports = _default;
/***/ }),
/***/ "7Kak":
/*!***************************************************!*\
!*** ./node_modules/antd/es/radio/style/index.js ***!
\***************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _style_index_less__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../style/index.less */ "cIOH");
/* harmony import */ var _style_index_less__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_style_index_less__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _index_less__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./index.less */ "KPFz");
/* harmony import */ var _index_less__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_index_less__WEBPACK_IMPORTED_MODULE_1__);
/***/ }),
/***/ "7ZXX":
/*!**********************************************!*\
!*** ./src/assets/images/classrooms/err.png ***!
\**********************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/err.6e7c5817.png";
/***/ }),
/***/ "7v3h":
/*!**************************************!*\
!*** ./src/assets/images/empty2.png ***!
\**************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/empty2.dd73f390.png";
/***/ }),
/***/ "8/bI":
/*!*************************************!*\
!*** ./src/assets/images/empty.png ***!
\*************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/empty.8918e228.png";
/***/ }),
/***/ "8EBN":
/*!**********************************************!*\
!*** ./node_modules/codemirror/mode/meta.js ***!
\**********************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (true) // CommonJS
mod(__webpack_require__(/*! ../lib/codemirror */ "VrN/"));
else {}
})(function(CodeMirror) {
"use strict";
CodeMirror.modeInfo = [
{name: "APL", mime: "text/apl", mode: "apl", ext: ["dyalog", "apl"]},
{name: "PGP", mimes: ["application/pgp", "application/pgp-encrypted", "application/pgp-keys", "application/pgp-signature"], mode: "asciiarmor", ext: ["asc", "pgp", "sig"]},
{name: "ASN.1", mime: "text/x-ttcn-asn", mode: "asn.1", ext: ["asn", "asn1"]},
{name: "Asterisk", mime: "text/x-asterisk", mode: "asterisk", file: /^extensions\.conf$/i},
{name: "Brainfuck", mime: "text/x-brainfuck", mode: "brainfuck", ext: ["b", "bf"]},
{name: "C", mime: "text/x-csrc", mode: "clike", ext: ["c", "h", "ino"]},
{name: "C++", mime: "text/x-c++src", mode: "clike", ext: ["cpp", "c++", "cc", "cxx", "hpp", "h++", "hh", "hxx"], alias: ["cpp"]},
{name: "Cobol", mime: "text/x-cobol", mode: "cobol", ext: ["cob", "cpy"]},
{name: "C#", mime: "text/x-csharp", mode: "clike", ext: ["cs"], alias: ["csharp", "cs"]},
{name: "Clojure", mime: "text/x-clojure", mode: "clojure", ext: ["clj", "cljc", "cljx"]},
{name: "ClojureScript", mime: "text/x-clojurescript", mode: "clojure", ext: ["cljs"]},
{name: "Closure Stylesheets (GSS)", mime: "text/x-gss", mode: "css", ext: ["gss"]},
{name: "CMake", mime: "text/x-cmake", mode: "cmake", ext: ["cmake", "cmake.in"], file: /^CMakeLists\.txt$/},
{name: "CoffeeScript", mimes: ["application/vnd.coffeescript", "text/coffeescript", "text/x-coffeescript"], mode: "coffeescript", ext: ["coffee"], alias: ["coffee", "coffee-script"]},
{name: "Common Lisp", mime: "text/x-common-lisp", mode: "commonlisp", ext: ["cl", "lisp", "el"], alias: ["lisp"]},
{name: "Cypher", mime: "application/x-cypher-query", mode: "cypher", ext: ["cyp", "cypher"]},
{name: "Cython", mime: "text/x-cython", mode: "python", ext: ["pyx", "pxd", "pxi"]},
{name: "Crystal", mime: "text/x-crystal", mode: "crystal", ext: ["cr"]},
{name: "CSS", mime: "text/css", mode: "css", ext: ["css"]},
{name: "CQL", mime: "text/x-cassandra", mode: "sql", ext: ["cql"]},
{name: "D", mime: "text/x-d", mode: "d", ext: ["d"]},
{name: "Dart", mimes: ["application/dart", "text/x-dart"], mode: "dart", ext: ["dart"]},
{name: "diff", mime: "text/x-diff", mode: "diff", ext: ["diff", "patch"]},
{name: "Django", mime: "text/x-django", mode: "django"},
{name: "Dockerfile", mime: "text/x-dockerfile", mode: "dockerfile", file: /^Dockerfile$/},
{name: "DTD", mime: "application/xml-dtd", mode: "dtd", ext: ["dtd"]},
{name: "Dylan", mime: "text/x-dylan", mode: "dylan", ext: ["dylan", "dyl", "intr"]},
{name: "EBNF", mime: "text/x-ebnf", mode: "ebnf"},
{name: "ECL", mime: "text/x-ecl", mode: "ecl", ext: ["ecl"]},
{name: "edn", mime: "application/edn", mode: "clojure", ext: ["edn"]},
{name: "Eiffel", mime: "text/x-eiffel", mode: "eiffel", ext: ["e"]},
{name: "Elm", mime: "text/x-elm", mode: "elm", ext: ["elm"]},
{name: "Embedded Javascript", mime: "application/x-ejs", mode: "htmlembedded", ext: ["ejs"]},
{name: "Embedded Ruby", mime: "application/x-erb", mode: "htmlembedded", ext: ["erb"]},
{name: "Erlang", mime: "text/x-erlang", mode: "erlang", ext: ["erl"]},
{name: "Esper", mime: "text/x-esper", mode: "sql"},
{name: "Factor", mime: "text/x-factor", mode: "factor", ext: ["factor"]},
{name: "FCL", mime: "text/x-fcl", mode: "fcl"},
{name: "Forth", mime: "text/x-forth", mode: "forth", ext: ["forth", "fth", "4th"]},
{name: "Fortran", mime: "text/x-fortran", mode: "fortran", ext: ["f", "for", "f77", "f90", "f95"]},
{name: "F#", mime: "text/x-fsharp", mode: "mllike", ext: ["fs"], alias: ["fsharp"]},
{name: "Gas", mime: "text/x-gas", mode: "gas", ext: ["s"]},
{name: "Gherkin", mime: "text/x-feature", mode: "gherkin", ext: ["feature"]},
{name: "GitHub Flavored Markdown", mime: "text/x-gfm", mode: "gfm", file: /^(readme|contributing|history)\.md$/i},
{name: "Go", mime: "text/x-go", mode: "go", ext: ["go"]},
{name: "Groovy", mime: "text/x-groovy", mode: "groovy", ext: ["groovy", "gradle"], file: /^Jenkinsfile$/},
{name: "HAML", mime: "text/x-haml", mode: "haml", ext: ["haml"]},
{name: "Haskell", mime: "text/x-haskell", mode: "haskell", ext: ["hs"]},
{name: "Haskell (Literate)", mime: "text/x-literate-haskell", mode: "haskell-literate", ext: ["lhs"]},
{name: "Haxe", mime: "text/x-haxe", mode: "haxe", ext: ["hx"]},
{name: "HXML", mime: "text/x-hxml", mode: "haxe", ext: ["hxml"]},
{name: "ASP.NET", mime: "application/x-aspx", mode: "htmlembedded", ext: ["aspx"], alias: ["asp", "aspx"]},
{name: "HTML", mime: "text/html", mode: "htmlmixed", ext: ["html", "htm", "handlebars", "hbs"], alias: ["xhtml"]},
{name: "HTTP", mime: "message/http", mode: "http"},
{name: "IDL", mime: "text/x-idl", mode: "idl", ext: ["pro"]},
{name: "Pug", mime: "text/x-pug", mode: "pug", ext: ["jade", "pug"], alias: ["jade"]},
{name: "Java", mime: "text/x-java", mode: "clike", ext: ["java"]},
{name: "Java Server Pages", mime: "application/x-jsp", mode: "htmlembedded", ext: ["jsp"], alias: ["jsp"]},
{name: "JavaScript", mimes: ["text/javascript", "text/ecmascript", "application/javascript", "application/x-javascript", "application/ecmascript"],
mode: "javascript", ext: ["js"], alias: ["ecmascript", "js", "node"]},
{name: "JSON", mimes: ["application/json", "application/x-json"], mode: "javascript", ext: ["json", "map"], alias: ["json5"]},
{name: "JSON-LD", mime: "application/ld+json", mode: "javascript", ext: ["jsonld"], alias: ["jsonld"]},
{name: "JSX", mime: "text/jsx", mode: "jsx", ext: ["jsx"]},
{name: "Jinja2", mime: "text/jinja2", mode: "jinja2", ext: ["j2", "jinja", "jinja2"]},
{name: "Julia", mime: "text/x-julia", mode: "julia", ext: ["jl"]},
{name: "Kotlin", mime: "text/x-kotlin", mode: "clike", ext: ["kt"]},
{name: "LESS", mime: "text/x-less", mode: "css", ext: ["less"]},
{name: "LiveScript", mime: "text/x-livescript", mode: "livescript", ext: ["ls"], alias: ["ls"]},
{name: "Lua", mime: "text/x-lua", mode: "lua", ext: ["lua"]},
{name: "Markdown", mime: "text/x-markdown", mode: "markdown", ext: ["markdown", "md", "mkd"]},
{name: "mIRC", mime: "text/mirc", mode: "mirc"},
{name: "MariaDB SQL", mime: "text/x-mariadb", mode: "sql"},
{name: "Mathematica", mime: "text/x-mathematica", mode: "mathematica", ext: ["m", "nb", "wl", "wls"]},
{name: "Modelica", mime: "text/x-modelica", mode: "modelica", ext: ["mo"]},
{name: "MUMPS", mime: "text/x-mumps", mode: "mumps", ext: ["mps"]},
{name: "MS SQL", mime: "text/x-mssql", mode: "sql"},
{name: "mbox", mime: "application/mbox", mode: "mbox", ext: ["mbox"]},
{name: "MySQL", mime: "text/x-mysql", mode: "sql"},
{name: "Nginx", mime: "text/x-nginx-conf", mode: "nginx", file: /nginx.*\.conf$/i},
{name: "NSIS", mime: "text/x-nsis", mode: "nsis", ext: ["nsh", "nsi"]},
{name: "NTriples", mimes: ["application/n-triples", "application/n-quads", "text/n-triples"],
mode: "ntriples", ext: ["nt", "nq"]},
{name: "Objective-C", mime: "text/x-objectivec", mode: "clike", ext: ["m"], alias: ["objective-c", "objc"]},
{name: "Objective-C++", mime: "text/x-objectivec++", mode: "clike", ext: ["mm"], alias: ["objective-c++", "objc++"]},
{name: "OCaml", mime: "text/x-ocaml", mode: "mllike", ext: ["ml", "mli", "mll", "mly"]},
{name: "Octave", mime: "text/x-octave", mode: "octave", ext: ["m"]},
{name: "Oz", mime: "text/x-oz", mode: "oz", ext: ["oz"]},
{name: "Pascal", mime: "text/x-pascal", mode: "pascal", ext: ["p", "pas"]},
{name: "PEG.js", mime: "null", mode: "pegjs", ext: ["jsonld"]},
{name: "Perl", mime: "text/x-perl", mode: "perl", ext: ["pl", "pm"]},
{name: "PHP", mimes: ["text/x-php", "application/x-httpd-php", "application/x-httpd-php-open"], mode: "php", ext: ["php", "php3", "php4", "php5", "php7", "phtml"]},
{name: "Pig", mime: "text/x-pig", mode: "pig", ext: ["pig"]},
{name: "Plain Text", mime: "text/plain", mode: "null", ext: ["txt", "text", "conf", "def", "list", "log"]},
{name: "PLSQL", mime: "text/x-plsql", mode: "sql", ext: ["pls"]},
{name: "PostgreSQL", mime: "text/x-pgsql", mode: "sql"},
{name: "PowerShell", mime: "application/x-powershell", mode: "powershell", ext: ["ps1", "psd1", "psm1"]},
{name: "Properties files", mime: "text/x-properties", mode: "properties", ext: ["properties", "ini", "in"], alias: ["ini", "properties"]},
{name: "ProtoBuf", mime: "text/x-protobuf", mode: "protobuf", ext: ["proto"]},
{name: "Python", mime: "text/x-python", mode: "python", ext: ["BUILD", "bzl", "py", "pyw"], file: /^(BUCK|BUILD)$/},
{name: "Puppet", mime: "text/x-puppet", mode: "puppet", ext: ["pp"]},
{name: "Q", mime: "text/x-q", mode: "q", ext: ["q"]},
{name: "R", mime: "text/x-rsrc", mode: "r", ext: ["r", "R"], alias: ["rscript"]},
{name: "reStructuredText", mime: "text/x-rst", mode: "rst", ext: ["rst"], alias: ["rst"]},
{name: "RPM Changes", mime: "text/x-rpm-changes", mode: "rpm"},
{name: "RPM Spec", mime: "text/x-rpm-spec", mode: "rpm", ext: ["spec"]},
{name: "Ruby", mime: "text/x-ruby", mode: "ruby", ext: ["rb"], alias: ["jruby", "macruby", "rake", "rb", "rbx"]},
{name: "Rust", mime: "text/x-rustsrc", mode: "rust", ext: ["rs"]},
{name: "SAS", mime: "text/x-sas", mode: "sas", ext: ["sas"]},
{name: "Sass", mime: "text/x-sass", mode: "sass", ext: ["sass"]},
{name: "Scala", mime: "text/x-scala", mode: "clike", ext: ["scala"]},
{name: "Scheme", mime: "text/x-scheme", mode: "scheme", ext: ["scm", "ss"]},
{name: "SCSS", mime: "text/x-scss", mode: "css", ext: ["scss"]},
{name: "Shell", mimes: ["text/x-sh", "application/x-sh"], mode: "shell", ext: ["sh", "ksh", "bash"], alias: ["bash", "sh", "zsh"], file: /^PKGBUILD$/},
{name: "Sieve", mime: "application/sieve", mode: "sieve", ext: ["siv", "sieve"]},
{name: "Slim", mimes: ["text/x-slim", "application/x-slim"], mode: "slim", ext: ["slim"]},
{name: "Smalltalk", mime: "text/x-stsrc", mode: "smalltalk", ext: ["st"]},
{name: "Smarty", mime: "text/x-smarty", mode: "smarty", ext: ["tpl"]},
{name: "Solr", mime: "text/x-solr", mode: "solr"},
{name: "SML", mime: "text/x-sml", mode: "mllike", ext: ["sml", "sig", "fun", "smackspec"]},
{name: "Soy", mime: "text/x-soy", mode: "soy", ext: ["soy"], alias: ["closure template"]},
{name: "SPARQL", mime: "application/sparql-query", mode: "sparql", ext: ["rq", "sparql"], alias: ["sparul"]},
{name: "Spreadsheet", mime: "text/x-spreadsheet", mode: "spreadsheet", alias: ["excel", "formula"]},
{name: "SQL", mime: "text/x-sql", mode: "sql", ext: ["sql"]},
{name: "SQLite", mime: "text/x-sqlite", mode: "sql"},
{name: "Squirrel", mime: "text/x-squirrel", mode: "clike", ext: ["nut"]},
{name: "Stylus", mime: "text/x-styl", mode: "stylus", ext: ["styl"]},
{name: "Swift", mime: "text/x-swift", mode: "swift", ext: ["swift"]},
{name: "sTeX", mime: "text/x-stex", mode: "stex"},
{name: "LaTeX", mime: "text/x-latex", mode: "stex", ext: ["text", "ltx", "tex"], alias: ["tex"]},
{name: "SystemVerilog", mime: "text/x-systemverilog", mode: "verilog", ext: ["v", "sv", "svh"]},
{name: "Tcl", mime: "text/x-tcl", mode: "tcl", ext: ["tcl"]},
{name: "Textile", mime: "text/x-textile", mode: "textile", ext: ["textile"]},
{name: "TiddlyWiki", mime: "text/x-tiddlywiki", mode: "tiddlywiki"},
{name: "Tiki wiki", mime: "text/tiki", mode: "tiki"},
{name: "TOML", mime: "text/x-toml", mode: "toml", ext: ["toml"]},
{name: "Tornado", mime: "text/x-tornado", mode: "tornado"},
{name: "troff", mime: "text/troff", mode: "troff", ext: ["1", "2", "3", "4", "5", "6", "7", "8", "9"]},
{name: "TTCN", mime: "text/x-ttcn", mode: "ttcn", ext: ["ttcn", "ttcn3", "ttcnpp"]},
{name: "TTCN_CFG", mime: "text/x-ttcn-cfg", mode: "ttcn-cfg", ext: ["cfg"]},
{name: "Turtle", mime: "text/turtle", mode: "turtle", ext: ["ttl"]},
{name: "TypeScript", mime: "application/typescript", mode: "javascript", ext: ["ts"], alias: ["ts"]},
{name: "TypeScript-JSX", mime: "text/typescript-jsx", mode: "jsx", ext: ["tsx"], alias: ["tsx"]},
{name: "Twig", mime: "text/x-twig", mode: "twig"},
{name: "Web IDL", mime: "text/x-webidl", mode: "webidl", ext: ["webidl"]},
{name: "VB.NET", mime: "text/x-vb", mode: "vb", ext: ["vb"]},
{name: "VBScript", mime: "text/vbscript", mode: "vbscript", ext: ["vbs"]},
{name: "Velocity", mime: "text/velocity", mode: "velocity", ext: ["vtl"]},
{name: "Verilog", mime: "text/x-verilog", mode: "verilog", ext: ["v"]},
{name: "VHDL", mime: "text/x-vhdl", mode: "vhdl", ext: ["vhd", "vhdl"]},
{name: "Vue.js Component", mimes: ["script/x-vue", "text/x-vue"], mode: "vue", ext: ["vue"]},
{name: "XML", mimes: ["application/xml", "text/xml"], mode: "xml", ext: ["xml", "xsl", "xsd", "svg"], alias: ["rss", "wsdl", "xsd"]},
{name: "XQuery", mime: "application/xquery", mode: "xquery", ext: ["xy", "xquery"]},
{name: "Yacas", mime: "text/x-yacas", mode: "yacas", ext: ["ys"]},
{name: "YAML", mimes: ["text/x-yaml", "text/yaml"], mode: "yaml", ext: ["yaml", "yml"], alias: ["yml"]},
{name: "Z80", mime: "text/x-z80", mode: "z80", ext: ["z80"]},
{name: "mscgen", mime: "text/x-mscgen", mode: "mscgen", ext: ["mscgen", "mscin", "msc"]},
{name: "xu", mime: "text/x-xu", mode: "mscgen", ext: ["xu"]},
{name: "msgenny", mime: "text/x-msgenny", mode: "mscgen", ext: ["msgenny"]},
{name: "WebAssembly", mime: "text/webassembly", mode: "wast", ext: ["wat", "wast"]},
];
// Ensure all modes have a mime property for backwards compatibility
for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
var info = CodeMirror.modeInfo[i];
if (info.mimes) info.mime = info.mimes[0];
}
CodeMirror.findModeByMIME = function(mime) {
mime = mime.toLowerCase();
for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
var info = CodeMirror.modeInfo[i];
if (info.mime == mime) return info;
if (info.mimes) for (var j = 0; j < info.mimes.length; j++)
if (info.mimes[j] == mime) return info;
}
if (/\+xml$/.test(mime)) return CodeMirror.findModeByMIME("application/xml")
if (/\+json$/.test(mime)) return CodeMirror.findModeByMIME("application/json")
};
CodeMirror.findModeByExtension = function(ext) {
ext = ext.toLowerCase();
for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
var info = CodeMirror.modeInfo[i];
if (info.ext) for (var j = 0; j < info.ext.length; j++)
if (info.ext[j] == ext) return info;
}
};
CodeMirror.findModeByFileName = function(filename) {
for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
var info = CodeMirror.modeInfo[i];
if (info.file && info.file.test(filename)) return info;
}
var dot = filename.lastIndexOf(".");
var ext = dot > -1 && filename.substring(dot + 1, filename.length);
if (ext) return CodeMirror.findModeByExtension(ext);
};
CodeMirror.findModeByName = function(name) {
name = name.toLowerCase();
for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
var info = CodeMirror.modeInfo[i];
if (info.name.toLowerCase() == name) return info;
if (info.alias) for (var j = 0; j < info.alias.length; j++)
if (info.alias[j].toLowerCase() == name) return info;
}
};
});
/***/ }),
/***/ "9Bee":
/*!*********************************************************!*\
!*** ./src/components/RenderHtml/index.tsx + 6 modules ***!
\*********************************************************/
/*! exports provided: default */
/*! exports used: default */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/es/components/AntdIcon.js */
/*! ModuleConcatenation bailout: Cannot concat with ./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/createForOfIteratorHelper.js because of ./src/components/markdown-editor/index.tsx */
/*! 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 ./src/utils/env.ts */
/*! ModuleConcatenation bailout: Cannot concat with ./src/utils/util.tsx */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/button/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/button/style/index.js */
/*! 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/antd/es/tooltip/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/tooltip/style/index.js */
/*! 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 ./src/components/PreviewAll/index.less?modules (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/react/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)) */
/***/ (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: ./node_modules/react/index.js
var react = __webpack_require__("q1tI");
var react_default = /*#__PURE__*/__webpack_require__.n(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 = ["<ul>"];
var renderer = new marked_default.a.Renderer();
var headingRegex = /^ *(#{1,6}) *([^\n]+?) *(?:#+ *)?(?:\n+|$)/;
function cleanToc() {
toc.length = 0;
ctx = ["<ul>"];
}
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("<li><a href='#" + node.anchor + "'>" + node.text + "</a>");
k++;
var childCtx = [];
k = buildToc(coll, k, node.level, childCtx);
if (childCtx.length > 0) {
ctx.push("<ul>");
childCtx.forEach(function (idm) {
ctx.push(idm);
});
ctx.push("</ul>");
}
ctx.push("</li>");
k = buildToc(coll, k, level, ctx);
return k;
}
function getTocContent() {
buildToc(toc, 0, 0, ctx);
ctx.push("</ul>");
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 '<pre class="prettyprint linenums"><code>' + (escaped ? code : Object(helpers["escape"])(code, true)) + '</code></pre>';
}
if (['latex', 'katex', 'math'].indexOf(lang) >= 0) {
return "<p class='editormd-tex'>".concat(code, "</p>");
} else {
return "<pre class=\"prettyprint linenums\"><code class=\"language-".concat(infostring, "\">").concat(escaped ? code : Object(helpers["escape"])(code, true), "</code></pre>\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 '<h' + level + ' id="' + anchor + '">' + text + '</h' + level + '>';
};
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: ./node_modules/antd/es/button/style/index.js
var button_style = __webpack_require__("+L6B");
// EXTERNAL MODULE: ./node_modules/antd/es/button/index.js
var es_button = __webpack_require__("2/Rp");
// EXTERNAL MODULE: ./node_modules/antd/es/tooltip/style/index.js
var tooltip_style = __webpack_require__("5Dmo");
// EXTERNAL MODULE: ./node_modules/antd/es/tooltip/index.js + 5 modules
var tooltip = __webpack_require__("3S7+");
// EXTERNAL MODULE: ./src/components/PreviewAll/index.less?modules
var PreviewAllmodules = __webpack_require__("vHTk");
var PreviewAllmodules_default = /*#__PURE__*/__webpack_require__.n(PreviewAllmodules);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/objectSpread2.js
var esm_objectSpread2 = __webpack_require__("VTBJ");
// CONCATENATED MODULE: ./node_modules/@ant-design/icons-svg/es/asn/ArrowDownOutlined.js
// This icon file is generated automatically.
var ArrowDownOutlined_ArrowDownOutlined = { "icon": { "tag": "svg", "attrs": { "viewBox": "64 64 896 896", "focusable": "false" }, "children": [{ "tag": "path", "attrs": { "d": "M862 465.3h-81c-4.6 0-9 2-12.1 5.5L550 723.1V160c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8v563.1L255.1 470.8c-3-3.5-7.4-5.5-12.1-5.5h-81c-6.8 0-10.5 8.1-6 13.2L487.9 861a31.96 31.96 0 0048.3 0L868 478.5c4.5-5.2.8-13.2-6-13.2z" } }] }, "name": "arrow-down", "theme": "outlined" };
/* harmony default export */ var asn_ArrowDownOutlined = (ArrowDownOutlined_ArrowDownOutlined);
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/es/components/AntdIcon.js + 5 modules
var AntdIcon = __webpack_require__("6VBw");
// CONCATENATED MODULE: ./node_modules/@ant-design/icons/es/icons/ArrowDownOutlined.js
// GENERATE BY ./scripts/generate.ts
// DON NOT EDIT IT MANUALLY
var icons_ArrowDownOutlined_ArrowDownOutlined = function ArrowDownOutlined(props, ref) {
return /*#__PURE__*/react["createElement"](AntdIcon["a" /* default */], Object(esm_objectSpread2["a" /* default */])(Object(esm_objectSpread2["a" /* default */])({}, props), {}, {
ref: ref,
icon: asn_ArrowDownOutlined
}));
};
icons_ArrowDownOutlined_ArrowDownOutlined.displayName = 'ArrowDownOutlined';
/* harmony default export */ var icons_ArrowDownOutlined = (/*#__PURE__*/react["forwardRef"](icons_ArrowDownOutlined_ArrowDownOutlined));
// 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/objectWithoutProperties.js + 1 modules
var objectWithoutProperties = __webpack_require__("PpiC");
// EXTERNAL MODULE: ./node_modules/resize-observer-polyfill/dist/ResizeObserver.es.js
var ResizeObserver_es = __webpack_require__("bdgK");
// CONCATENATED MODULE: ./src/components/monaco-editor/monaco-suggest-config.tsx
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) {
var ifelse = {
label: 'ifelse',
kind: monaco.languages.CompletionItemKind.Method,
insertText: ['if (${1:condition}) {', '\t$0', '} else {', '\t', '}'].join('\n'),
insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet
};
var cKeywords = ['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', 'inline', 'restrict', '_Bool', '_Complex', '_Imaginary', '_Alignas', '_Alignof', '_Atomic', '_Static_assert', '_Noreturn', '_Thread_local', '_Generic'];
monaco.languages.registerCompletionItemProvider('cpp', {
provideCompletionItems: function provideCompletionItems(model, position) {
var suggestions = getSuggestions(monaco, model, position, cKeywords, [ifelse]);
return {
suggestions: suggestions
};
}
});
var pythonkeywords = ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'];
monaco.languages.registerCompletionItemProvider('python', {
provideCompletionItems: function provideCompletionItems(model, position) {
var snippets = [{
label: 'print',
kind: monaco.languages.CompletionItemKind.Snippet,
insertText: ['print($0)'].join('\n'),
insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet
}];
var suggestions = getSuggestions(monaco, model, position, pythonkeywords, snippets);
return {
suggestions: suggestions
};
}
});
var javaKeywords = ['abstract', 'assert', 'boolean', 'break', 'byte', 'case', 'catch', 'char', 'class', 'const', 'continue', 'default', 'do', 'double', 'else', 'enum', 'extends', 'final', 'finally', 'float', 'for', 'goto', 'if', 'implements', 'import', 'instance of', 'int', 'interface', 'long', 'native', 'new', 'package', 'private', 'protected', 'public', 'return', 'strictfp', 'short', 'static', 'super', 'switch', 'synchronized', 'this', 'throw', 'throws', 'transient', 'try', 'void', 'volatile', 'while'];
monaco.languages.registerCompletionItemProvider('java', {
provideCompletionItems: function provideCompletionItems(model, position) {
var snippets = [ifelse, {
label: 'main',
kind: monaco.languages.CompletionItemKind.Snippet,
insertText: ['public static void main(String[] args) {', '\t$0', '}'].join('\n'),
insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet
}, {
label: 'System.out.print',
kind: monaco.languages.CompletionItemKind.Snippet,
insertText: ['System.out.print($0)'].join('\n'),
insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet
}];
var suggestions = getSuggestions(monaco, model, position, javaKeywords, snippets);
return {
suggestions: suggestions
};
}
});
});
var tipTxt = '该任务关卡设置了禁止复制粘贴,请手动输入代码。';
// EXTERNAL MODULE: ./node_modules/lodash/lodash.js
var lodash = __webpack_require__("LvDl");
// 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 monaco_editor = (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,
props = Object(objectWithoutProperties["a" /* default */])(_ref, ["width", "height", "value", "language", "style", "options", "overrideServices", "theme", "onEditBlur", "onSave", "autoHeight", "forbidCopy", "onChange", "editorDidMount", "onFocus", "filename"]);
var editorEl = Object(react["useRef"])();
var editor = Object(react["useRef"])({});
var timeRef = Object(react["useRef"])();
var inputLock = Object(react["useRef"])(false);
var inputLockTime = Object(react["useRef"])();
var _useState = Object(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(react["useEffect"])(function () {
if (timeRef.current) clearTimeout(timeRef.current);
timeRef.current = setTimeout(function () {
setCodeValue();
}, 500);
}, [value, init, editor.current]);
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);
}
Object(react["useEffect"])(function () {
autoCalcHeight();
}, [autoCalcHeight]);
Object(react["useEffect"])(function () {
if (editorEl.current && !init) {
undefined;
undefined;
__webpack_require__.e(/*! import() | monaco-editor */ 15).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;
if (!window.Monaco) monaco_suggest_config(monaco_editor_monaco);
window.Monaco = monaco_editor_monaco;
editor.current.instance = monaco_editor_monaco.editor.create(editorEl.current, Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({
value: value,
language: getLanguageByMirrorName(language),
theme: theme,
requireConfig: {
'vs/nls': {
availableLanguages: {
'*': 'zh-cn'
}
}
}
}, options), {}, {
wordWrap: true
}), overrideServices);
var instance = editor.current.instance;
editorDidMount(instance, 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', instance.getValue());
}
});
}, 500);
editor.current.subscription = instance.onDidChangeModelContent(function (event) {
if (!inputLock.current) {
autoCalcHeight();
onChange(instance.getValue(), event);
} else {
clearTimeout(inputLockTime.current);
}
inputLockTime.current = setTimeout(function () {
inputLock.current = false;
}, 500);
});
if (forbidCopy) {
instance.addCommand(monaco_editor_monaco.KeyMod.CtrlCmd | monaco_editor_monaco.KeyMod.Shift | monaco_editor_monaco.KeyCode.KEY_V, function () {
tipWarn();
return null;
});
instance.addCommand(monaco_editor_monaco.KeyMod.CtrlCmd | monaco_editor_monaco.KeyCode.KEY_C, function () {
tipWarn();
return null;
});
}
if (onEditBlur) {
instance.onDidBlurEditorWidget(function () {
onEditBlur(instance.getValue());
});
}
if (onFocus) {
instance.onDidFocusEditorText(function () {
onFocus(instance.getValue());
});
}
if (forbidCopy) {
instance.addCommand(monaco_editor_monaco.KeyMod.CtrlCmd | monaco_editor_monaco.KeyCode.KEY_V, function () {
tipWarn();
return null;
});
instance.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(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(react["useEffect"])(function () {
var instance = editor.current.instance;
if (instance && init) {
var lang = getLanguageByMirrorName(language);
monaco_editor_monaco.editor.setModelLanguage(instance.getModel(), lang);
console.log('language:', language, instance.getModel(), lang);
}
}, [language, init]);
Object(react["useEffect"])(function () {
var instance = editor.current.instance;
if (instance && init) {
monaco_editor_monaco.editor.setTheme(theme);
}
}, [theme, init]);
Object(react["useEffect"])(function () {
var instance = editor.current.instance;
if (instance && init) {
instance.updateOptions(options);
}
}, [JSON.stringify(options), init]);
Object(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(react["useState"])(processSize(width)),
_useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
fixedWidth = _useState4[0],
setFixedWidth = _useState4[1];
var _useState5 = Object(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__*/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(react["useRef"])();
var _useState7 = Object(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(react["useEffect"])(function () {
if (editorEl.current) {
__webpack_require__.e(/*! import() | monaco-editor */ 15).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,
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(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__*/react_default.a.createElement("div", {
className: "my-diff-editor",
ref: editorEl,
style: style
});
}
// EXTERNAL MODULE: ./src/utils/util.tsx + 6 modules
var util = __webpack_require__("1vsH");
// CONCATENATED MODULE: ./src/components/PreviewAll/index.tsx
/* harmony default export */ var PreviewAll = (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;
var _useState = Object(react["useState"])('https://view.officeapps.live.com/op/view.aspx?src=http://testgs.educoder.net//rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBCZz09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--03541f6234b93d7ac3b2d84e7eb0e6594a952945/1.ppt'),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
src = _useState2[0],
setSrc = _useState2[1];
var _useState3 = Object(react["useState"])(""),
_useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
token = _useState4[0],
setToken = _useState4[1];
var closeRef = Object(react["useRef"])();
if (filename) monacoEditor.filename = filename;
Object(react["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")) {
handleDown();
return;
}
Object(util["g" /* downloadFile */])(filename || 'educoder', data, filename);
};
var handleDown = function handleDown() {
Object(util["f" /* downLoadLink */])('', data);
};
return /*#__PURE__*/react_default.a.createElement("div", {
style: Object(objectSpread2["a" /* default */])({}, style || {}),
className: "".concat(PreviewAllmodules_default.a.wrp, " ").concat(!!type ? "" : "hide")
}, close && /*#__PURE__*/react_default.a.createElement("div", {
className: PreviewAllmodules_default.a.close,
ref: closeRef
}, /*#__PURE__*/react_default.a.createElement(tooltip["a" /* default */], {
title: "\u70B9\u51FB\u4E0B\u8F7D\u6B64\u6587\u4EF6",
getPopupContainer: function getPopupContainer() {
return closeRef.current;
}
}, /*#__PURE__*/react_default.a.createElement("span", {
onClick: handleDown
}, /*#__PURE__*/react_default.a.createElement("i", {
className: "icon-quxiaozhiding"
}))), /*#__PURE__*/react_default.a.createElement(tooltip["a" /* default */], {
title: "\u5173\u95ED",
getPopupContainer: function getPopupContainer() {
return closeRef.current;
}
}, /*#__PURE__*/react_default.a.createElement("span", {
className: "",
onClick: onClose
}, /*#__PURE__*/react_default.a.createElement("i", {
className: "icon-guanbi1"
})))), /*#__PURE__*/react_default.a.createElement("div", {
className: "".concat(PreviewAllmodules_default.a[className], " ").concat(className, " ").concat(PreviewAllmodules_default.a.monaco, " ").concat(type === "txt" ? "show" : "hide")
}, filename && /*#__PURE__*/react_default.a.createElement(monaco_editor, monacoEditor)), type === "audio" && /*#__PURE__*/react_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_default.a.createElement(react_default.a.Fragment, null, (data === null || data === void 0 ? void 0 : data.indexOf("http")) > -1 ? /*#__PURE__*/react_default.a.createElement("video", {
controls: true,
src: "".concat(data),
autoPlay: true
}) : /*#__PURE__*/react_default.a.createElement("video", {
controls: true,
src: "data:video/mp4;base64,".concat(data),
autoPlay: true
})), type === 'office' && /*#__PURE__*/react_default.a.createElement("iframe", {
src: "https://view.officeapps.live.com/op/embed.aspx?src=".concat(data, "?disposition=office&token=").concat(token)
}), type === "image" && /*#__PURE__*/react_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_default.a.createElement("div", null, /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
type: "primary",
size: "large",
onClick: handleClick
}, /*#__PURE__*/react_default.a.createElement(icons_ArrowDownOutlined, null), "\u70B9\u51FB\u4E0B\u8F7D")), type === "download" && /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
type: "primary",
size: "large",
onClick: handleClick
}, /*#__PURE__*/react_default.a.createElement(icons_ArrowDownOutlined, null), "\u70B9\u51FB\u4E0B\u8F7D"));
});
// CONCATENATED MODULE: ./src/components/RenderHtml/index.tsx
var preRegex = /<pre[^>]*>/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;
var str = String(value);
var _useState = Object(react["useState"])(""),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
data = _useState2[0],
setData = _useState2[1];
var html = Object(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("(?<!\\n)\\n(?!\\n)", "g"), " \n");
} catch (e) {}
;
var rs = utils_marked(str);
var math_expressions = getMathExpressions();
if (str.match(/\[TOC\]/)) {
rs = rs.replace('<p>[TOC]</p>', 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(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);
} 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(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__*/react_default.a.createElement(react_default.a.Fragment, null, /*#__PURE__*/react_default.a.createElement("div", {
ref: el,
style: Object(objectSpread2["a" /* default */])({}, style),
className: "".concat(className ? className : '', " markdown-body "),
dangerouslySetInnerHTML: {
__html: html
}
}), /*#__PURE__*/react_default.a.createElement(PreviewAll, {
data: data,
type: !!(data === null || data === void 0 ? void 0 : data.length) ? "office" : "",
onClose: function onClose() {
return setData("");
}
}));
});
/***/ }),
/***/ "9OqN":
/*!********************************************!*\
!*** ./node_modules/crypto-js/mode-ctr.js ***!
\********************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory, undef) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"), __webpack_require__(/*! ./cipher-core */ "OLod"));
}
else {}
}(this, function (CryptoJS) {
/**
* Counter block mode.
*/
CryptoJS.mode.CTR = (function () {
var CTR = CryptoJS.lib.BlockCipherMode.extend();
var Encryptor = CTR.Encryptor = CTR.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var counter = this._counter;
// Generate keystream
if (iv) {
counter = this._counter = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
var keystream = counter.slice(0);
cipher.encryptBlock(keystream, 0);
// Increment counter
counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
CTR.Decryptor = Encryptor;
return CTR;
}());
return CryptoJS.mode.CTR;
}));
/***/ }),
/***/ "9ama":
/*!****************************************************!*\
!*** ./node_modules/antd/es/tabs/style/index.less ***!
\****************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/***/ "9yH6":
/*!*********************************************************!*\
!*** ./node_modules/antd/es/radio/index.js + 5 modules ***!
\*********************************************************/
/*! exports provided: Button, Group, default */
/*! exports used: default */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/defineProperty.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/extends.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/slicedToArray.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/typeof.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/_util/devWarning.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/config-provider/SizeContext.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/config-provider/context.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-checkbox/es/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/hooks/useMergedState.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/react/index.js (<- Module is not an ECMAScript module) */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// UNUSED EXPORTS: Button, Group
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/defineProperty.js
var defineProperty = __webpack_require__("lSNA");
var defineProperty_default = /*#__PURE__*/__webpack_require__.n(defineProperty);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/extends.js
var helpers_extends = __webpack_require__("pVnL");
var extends_default = /*#__PURE__*/__webpack_require__.n(helpers_extends);
// EXTERNAL MODULE: ./node_modules/react/index.js
var react = __webpack_require__("q1tI");
// EXTERNAL MODULE: ./node_modules/rc-checkbox/es/index.js
var es = __webpack_require__("x1Ya");
// EXTERNAL MODULE: ./node_modules/classnames/index.js
var classnames = __webpack_require__("TSYQ");
var classnames_default = /*#__PURE__*/__webpack_require__.n(classnames);
// EXTERNAL MODULE: ./node_modules/antd/es/config-provider/context.js + 1 modules
var config_provider_context = __webpack_require__("H84U");
// CONCATENATED MODULE: ./node_modules/antd/es/radio/context.js
var RadioGroupContext = /*#__PURE__*/react["createContext"](null);
var RadioGroupContextProvider = RadioGroupContext.Provider;
/* harmony default export */ var radio_context = (RadioGroupContext);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/typeof.js
var helpers_typeof = __webpack_require__("cDf5");
var typeof_default = /*#__PURE__*/__webpack_require__.n(helpers_typeof);
// CONCATENATED MODULE: ./node_modules/antd/es/_util/ref.js
function fillRef(ref, node) {
if (typeof ref === 'function') {
ref(node);
} else if (typeof_default()(ref) === 'object' && ref && 'current' in ref) {
ref.current = node;
}
}
function composeRef() {
for (var _len = arguments.length, refs = new Array(_len), _key = 0; _key < _len; _key++) {
refs[_key] = arguments[_key];
}
return function (node) {
refs.forEach(function (ref) {
fillRef(ref, node);
});
};
}
// EXTERNAL MODULE: ./node_modules/antd/es/_util/devWarning.js
var devWarning = __webpack_require__("uaoM");
// CONCATENATED MODULE: ./node_modules/antd/es/radio/radio.js
var __rest = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
var radio_InternalRadio = function InternalRadio(props, ref) {
var _classNames;
var context = react["useContext"](radio_context);
var _React$useContext = react["useContext"](config_provider_context["b" /* ConfigContext */]),
getPrefixCls = _React$useContext.getPrefixCls,
direction = _React$useContext.direction;
var innerRef = react["useRef"]();
var mergedRef = composeRef(ref, innerRef);
react["useEffect"](function () {
Object(devWarning["a" /* default */])(!('optionType' in props), 'Radio', '`optionType` is only support in Radio.Group.');
}, []);
var onChange = function onChange(e) {
if (props.onChange) {
props.onChange(e);
}
if (context === null || context === void 0 ? void 0 : context.onChange) {
context.onChange(e);
}
};
var customizePrefixCls = props.prefixCls,
className = props.className,
children = props.children,
style = props.style,
restProps = __rest(props, ["prefixCls", "className", "children", "style"]);
var prefixCls = getPrefixCls('radio', customizePrefixCls);
var radioProps = extends_default()({}, restProps);
if (context) {
radioProps.name = context.name;
radioProps.onChange = onChange;
radioProps.checked = props.value === context.value;
radioProps.disabled = props.disabled || context.disabled;
}
var wrapperClassString = classnames_default()(className, (_classNames = {}, defineProperty_default()(_classNames, "".concat(prefixCls, "-wrapper"), true), defineProperty_default()(_classNames, "".concat(prefixCls, "-wrapper-checked"), radioProps.checked), defineProperty_default()(_classNames, "".concat(prefixCls, "-wrapper-disabled"), radioProps.disabled), defineProperty_default()(_classNames, "".concat(prefixCls, "-wrapper-rtl"), direction === 'rtl'), _classNames));
return (
/*#__PURE__*/
// eslint-disable-next-line jsx-a11y/label-has-associated-control
react["createElement"]("label", {
className: wrapperClassString,
style: style,
onMouseEnter: props.onMouseEnter,
onMouseLeave: props.onMouseLeave
}, /*#__PURE__*/react["createElement"](es["a" /* default */], extends_default()({}, radioProps, {
prefixCls: prefixCls,
ref: mergedRef
})), children !== undefined ? /*#__PURE__*/react["createElement"]("span", null, children) : null)
);
};
var Radio = /*#__PURE__*/react["forwardRef"](radio_InternalRadio);
Radio.displayName = 'Radio';
Radio.defaultProps = {
type: 'radio'
};
/* harmony default export */ var radio_radio = (Radio);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/slicedToArray.js
var slicedToArray = __webpack_require__("J4zp");
var slicedToArray_default = /*#__PURE__*/__webpack_require__.n(slicedToArray);
// EXTERNAL MODULE: ./node_modules/rc-util/es/hooks/useMergedState.js
var useMergedState = __webpack_require__("6cGi");
// EXTERNAL MODULE: ./node_modules/antd/es/config-provider/SizeContext.js
var SizeContext = __webpack_require__("3Nzz");
// CONCATENATED MODULE: ./node_modules/antd/es/radio/group.js
var RadioGroup = /*#__PURE__*/react["forwardRef"](function (props, ref) {
var _React$useContext = react["useContext"](config_provider_context["b" /* ConfigContext */]),
getPrefixCls = _React$useContext.getPrefixCls,
direction = _React$useContext.direction;
var size = react["useContext"](SizeContext["b" /* default */]);
var _useMergedState = Object(useMergedState["a" /* default */])(props.defaultValue, {
value: props.value
}),
_useMergedState2 = slicedToArray_default()(_useMergedState, 2),
value = _useMergedState2[0],
setValue = _useMergedState2[1];
var onRadioChange = function onRadioChange(ev) {
var lastValue = value;
var val = ev.target.value;
if (!('value' in props)) {
setValue(val);
}
var onChange = props.onChange;
if (onChange && val !== lastValue) {
onChange(ev);
}
};
var renderGroup = function renderGroup() {
var _classNames;
var customizePrefixCls = props.prefixCls,
_props$className = props.className,
className = _props$className === void 0 ? '' : _props$className,
options = props.options,
optionType = props.optionType,
buttonStyle = props.buttonStyle,
disabled = props.disabled,
children = props.children,
customizeSize = props.size,
style = props.style,
id = props.id,
onMouseEnter = props.onMouseEnter,
onMouseLeave = props.onMouseLeave;
var prefixCls = getPrefixCls('radio', customizePrefixCls);
var groupPrefixCls = "".concat(prefixCls, "-group");
var childrenToRender = children; // 如果存在 options, 优先使用
if (options && options.length > 0) {
var optionsPrefixCls = optionType === 'button' ? "".concat(prefixCls, "-button") : prefixCls;
childrenToRender = options.map(function (option) {
if (typeof option === 'string') {
// 此处类型自动推导为 string
return /*#__PURE__*/react["createElement"](radio_radio, {
ref: ref,
key: option,
prefixCls: optionsPrefixCls,
disabled: disabled,
value: option,
checked: value === option
}, option);
} // 此处类型自动推导为 { label: string value: string }
return /*#__PURE__*/react["createElement"](radio_radio, {
ref: ref,
key: "radio-group-value-options-".concat(option.value),
prefixCls: optionsPrefixCls,
disabled: option.disabled || disabled,
value: option.value,
checked: value === option.value,
style: option.style
}, option.label);
});
}
var mergedSize = customizeSize || size;
var classString = classnames_default()(groupPrefixCls, "".concat(groupPrefixCls, "-").concat(buttonStyle), (_classNames = {}, defineProperty_default()(_classNames, "".concat(groupPrefixCls, "-").concat(mergedSize), mergedSize), defineProperty_default()(_classNames, "".concat(groupPrefixCls, "-rtl"), direction === 'rtl'), _classNames), className);
return /*#__PURE__*/react["createElement"]("div", {
className: classString,
style: style,
onMouseEnter: onMouseEnter,
onMouseLeave: onMouseLeave,
id: id
}, childrenToRender);
};
return /*#__PURE__*/react["createElement"](RadioGroupContextProvider, {
value: {
onChange: onRadioChange,
value: value,
disabled: props.disabled,
name: props.name
}
}, renderGroup());
});
RadioGroup.defaultProps = {
buttonStyle: 'outline'
};
/* harmony default export */ var group = (/*#__PURE__*/react["memo"](RadioGroup));
// CONCATENATED MODULE: ./node_modules/antd/es/radio/radioButton.js
var radioButton_rest = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
var radioButton_RadioButton = function RadioButton(props, ref) {
var radioGroupContext = react["useContext"](radio_context);
var _React$useContext = react["useContext"](config_provider_context["b" /* ConfigContext */]),
getPrefixCls = _React$useContext.getPrefixCls;
var customizePrefixCls = props.prefixCls,
radioProps = radioButton_rest(props, ["prefixCls"]);
var prefixCls = getPrefixCls('radio-button', customizePrefixCls);
if (radioGroupContext) {
radioProps.checked = props.value === radioGroupContext.value;
radioProps.disabled = props.disabled || radioGroupContext.disabled;
}
return /*#__PURE__*/react["createElement"](radio_radio, extends_default()({
prefixCls: prefixCls
}, radioProps, {
type: "radio",
ref: ref
}));
};
/* harmony default export */ var radioButton = (/*#__PURE__*/react["forwardRef"](radioButton_RadioButton));
// CONCATENATED MODULE: ./node_modules/antd/es/radio/index.js
var radio_Radio = radio_radio;
radio_Radio.Button = radioButton;
radio_Radio.Group = group;
/* harmony default export */ var es_radio = __webpack_exports__["a"] = (radio_Radio);
/***/ }),
/***/ "A/g1":
/*!*******************************************!*\
!*** ./src/assets/images/icons/done1.png ***!
\*******************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports) {
module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAAsTAAALEwEAmpwYAAAF92lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgNi4wLWMwMDMgNzkuMTY0NTI3LCAyMDIwLzEwLzE1LTE3OjQ4OjMyICAgICAgICAiPiA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPiA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgeG1sbnM6cGhvdG9zaG9wPSJodHRwOi8vbnMuYWRvYmUuY29tL3Bob3Rvc2hvcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RFdnQ9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZUV2ZW50IyIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgMjIuMSAoTWFjaW50b3NoKSIgeG1wOkNyZWF0ZURhdGU9IjIwMjEtMDctMDJUMTk6Mzg6MjMrMDg6MDAiIHhtcDpNb2RpZnlEYXRlPSIyMDIxLTA3LTAyVDE5OjQxOjQ2KzA4OjAwIiB4bXA6TWV0YWRhdGFEYXRlPSIyMDIxLTA3LTAyVDE5OjQxOjQ2KzA4OjAwIiBkYzpmb3JtYXQ9ImltYWdlL3BuZyIgcGhvdG9zaG9wOkNvbG9yTW9kZT0iMyIgcGhvdG9zaG9wOklDQ1Byb2ZpbGU9InNSR0IgSUVDNjE5NjYtMi4xIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOmVkYzRhODM0LTVjNWQtNDQ1My04MDYzLWNkNzcwODQyODg5ZSIgeG1wTU06RG9jdW1lbnRJRD0iYWRvYmU6ZG9jaWQ6cGhvdG9zaG9wOjQ4MTE0OTVlLTVkMDctZTk0YS1iNWEwLWYxOWJmZmM0NGUyNyIgeG1wTU06T3JpZ2luYWxEb2N1bWVudElEPSJ4bXAuZGlkOmMwNjQyYzA1LTg5MzQtNDdlYy04MTFiLTlkYjdhZGNkYjFiMCI+IDx4bXBNTTpIaXN0b3J5PiA8cmRmOlNlcT4gPHJkZjpsaSBzdEV2dDphY3Rpb249ImNyZWF0ZWQiIHN0RXZ0Omluc3RhbmNlSUQ9InhtcC5paWQ6YzA2NDJjMDUtODkzNC00N2VjLTgxMWItOWRiN2FkY2RiMWIwIiBzdEV2dDp3aGVuPSIyMDIxLTA3LTAyVDE5OjM4OjIzKzA4OjAwIiBzdEV2dDpzb2Z0d2FyZUFnZW50PSJBZG9iZSBQaG90b3Nob3AgMjIuMSAoTWFjaW50b3NoKSIvPiA8cmRmOmxpIHN0RXZ0OmFjdGlvbj0ic2F2ZWQiIHN0RXZ0Omluc3RhbmNlSUQ9InhtcC5paWQ6ZWRjNGE4MzQtNWM1ZC00NDUzLTgwNjMtY2Q3NzA4NDI4ODllIiBzdEV2dDp3aGVuPSIyMDIxLTA3LTAyVDE5OjQxOjQ2KzA4OjAwIiBzdEV2dDpzb2Z0d2FyZUFnZW50PSJBZG9iZSBQaG90b3Nob3AgMjIuMSAoTWFjaW50b3NoKSIgc3RFdnQ6Y2hhbmdlZD0iLyIvPiA8L3JkZjpTZXE+IDwveG1wTU06SGlzdG9yeT4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz5fJkpyAAAGoElEQVRogc2abWxbVxnH/8+59/rdTpx2GW3UNWJJV7Ylaxp3LUFsWgJDiI5R8bK2GppAmsgQLKQthS8IEJ9okibrREf3gX2Y1K2bxAoDtog60RBSVxKnWUO7kpSppXJZK2ja2HFi33vPw4cmpbN9r++1k8Lv2znnf577f+zje95Mhw4dQqUkwljpF7kuv0EdHkm1HklRr6TQq2tn5xcklwhIMnMSQJIJxykTiSce+1am0mer5XacqM7uDJjiqbAuWlvSygrBnmKyxcoIA+tBBAAgAAikjNZ47zCIh8E8mOjYO1aOD3L7DYzXZJurs8qhuzLqFsH22hcbUs6CMudAol8Ic2Dkkb0fuvEj3IinwvobjTOeRP1safOuIPIA/AMpxbsb4z3fc9PVUQLvRY37L/vMDxtT2peCBpU97BywlkD9sXjvbzcfG7jTSYeSCZyK6l9tTCkn75xXHAVcChh4zCDzLy1DfQ+U0tomcDaSO9A8rb0WWN5P3QK+SzCPx471bLdTWSYwFdZfXz/j+e7SG3MHE73SGu+19FE0gTNV+o8aU9pXls+Waw7E4r2fL9ZQkMB4jd5xd1r96fJ7cgeDX944vL8hv74ggdUZccRrLsw4/1fQCpLyYH7tRxKYCutv1M4rK26fKdd8Nn+euJnAySp9w+o5dettt+QSItHV+nb/qsXyzddj1KAXlnmSsuIMgV8v1sCgHxdWcj002QXgh8BCAqdq9B33T2tbltOlBWcEia+NtO86nd/QOtR3EGyxXmHZHXun78jow7tPCgAI6NixpGsbZ1ibj/d2gvkZy55EHpbcDiz8BkK62LRsNotjaX5TvK8NzH0lI5j0aQAQ4z69pjarfGwZTFphab55sCdogntAFCgZhfgLn3xtv19oPnTexuFjaR4ANJV6CWhzGEvNrpQPiYBOt+vVaWu+Nd7bCaDTTUCS9LDwSNQuiT17bM3fGPd4zn1YWSc8kqJO5e9H9P6LAeNvLp9ia755sCcoiftAKLqptoOI6oRXUsiJ+FxIf/MTM9quNRl1/XhN7p7zQWPUQTdb88CNcQ9GWXMQA3XCb5JWSngxYJxtSGtfXCxvuOqZrJ9VN53wpcMfhIxhs8jSb0aT2VLmyxn3edQ52hOnNf5dsfrN86H0x9Nqu8KgqbBxdF5hCdwwfyFkPmFnflO8rw3AL8qy/V9YzCmsl1I1pNTdp6N6t52mMaVu85mkTEb0ly6EzCeaprXfWGmbB3uCTHgOLk9FCqGkmhWcBlBjJ9MkUX1K3TcRzV5qmvYesdOum9G+Weqxmop+Zo65dFsAEydFTvC0E3HQIHVNWnvpvRVGRYu+G+Oenq4kxiIk+ZLIKbjitEO1Lvyr0/SHieD8qtLqQhbG/Qvl9C2OSIqMWvwHasUdWSW6Umojbh/VPNgTlOCCLWElsOB3hO7BL6XLHfCqOaXuYsA466aPR6XnAZQ8qHKB4fWJP4kNV7SrV3ymqwNVAFiTUe85HzLedaKNxfd/h4FvuPdoA9Hvj7ftmhMAkFbZyaxaQH1a3XwurL9tp4kN7fsUQz5fTnxbGH8GFt7DcwpecTuMFmlIaZ+bjOgvF2u7d/gnIWZR+Q1KPowcIIaAhQSarqmH/xE0TpQbb92M9uT7kdz+/HqfDB0EcF/ZRi1ggYFER/cYcMtMOO3jzlmVjXKDrkt5uv9are9ZLJ8L6UcJ+HplVotygVRlYLFwM4GWf2njl/ymq1fqrSgM3J1Sfz5Rnd15ulp/tiGtPV6h0aIwaCDxUPc/F8sfOQdqTKnbrvjMf9fOK7ZLCyv8Jom1s9qvsHANttQw4dhY++6BW+sKFlNJr7E9K6wOZEoT0YU3ogvXm5OSMK5KQ347v7oggZbr3j/+PWwUnoj9jyHCk+OP7p3Kry+6nL33uvazqbD+6+W35RDmrtGOPW8Va7JcjzemtC+frTKWfgJyCQmxI/GZ7x+warfdUKy/rj47UZXdnlHZXHprJWBcFKZsGX1k16t2spI7oqbr3iOTkdzGyz7z8tK5s4eAN4UiHxx5dO94Ka2jLd2Gq95TI/e9tXoqbBytZLJzwAUGdY+273nc6Y294z3p1sRW2ZhSt02Gsg+eDxknyl07FYWRY8I+aZptYx27B0Bw/Bp3faHRcs13EsCWiWpjZ8DEU+Ecxe7IKjVl5GMy8zAJMQSIwbH27rL+7FH2jUzTNfUwgMMAkFiFlf5MrstviA4PU61HIuo1KQRCdkGeJCDJoCQkkkzyOFVF4mOxyv9u8x8opnU6UeBF0wAAAABJRU5ErkJggg=="
/***/ }),
/***/ "ALsQ":
/*!********************************************!*\
!*** ./node_modules/crypto-js/mode-cfb.js ***!
\********************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory, undef) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"), __webpack_require__(/*! ./cipher-core */ "OLod"));
}
else {}
}(this, function (CryptoJS) {
/**
* Cipher Feedback block mode.
*/
CryptoJS.mode.CFB = (function () {
var CFB = CryptoJS.lib.BlockCipherMode.extend();
CFB.Encryptor = CFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
CFB.Decryptor = CFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// Remember this block to use with next block
var thisBlock = words.slice(offset, offset + blockSize);
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) {
var keystream;
// Shortcut
var iv = this._iv;
// Generate keystream
if (iv) {
keystream = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
keystream = this._prevBlock;
}
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
return CFB;
}());
return CryptoJS.mode.CFB;
}));
/***/ }),
/***/ "AOa7":
/*!**********************************************************!*\
!*** ./node_modules/antd/es/breadcrumb/style/index.less ***!
\**********************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/***/ "BJfS":
/*!*****************************************************!*\
!*** ./node_modules/string-convert/camel2hyphen.js ***!
\*****************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports) {
var camel2hyphen = function (str) {
return str
.replace(/[A-Z]/g, function (match) {
return '-' + match.toLowerCase();
})
.toLowerCase();
};
module.exports = camel2hyphen;
/***/ }),
/***/ "Bd2K":
/*!********************************************************!*\
!*** ./node_modules/codemirror/addon/edit/closetag.js ***!
\********************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
/**
* Tag-closer extension for CodeMirror.
*
* This extension adds an "autoCloseTags" option that can be set to
* either true to get the default behavior, or an object to further
* configure its behavior.
*
* These are supported options:
*
* `whenClosing` (default true)
* Whether to autoclose when the '/' of a closing tag is typed.
* `whenOpening` (default true)
* Whether to autoclose the tag when the final '>' of an opening
* tag is typed.
* `dontCloseTags` (default is empty tags for HTML, none for XML)
* An array of tag names that should not be autoclosed.
* `indentTags` (default is block tags for HTML, none for XML)
* An array of tag names that should, when opened, cause a
* blank line to be added inside the tag, and the blank line and
* closing line to be indented.
* `emptyTags` (default is none)
* An array of XML tag names that should be autoclosed with '/>'.
*
* See demos/closetag.html for a usage example.
*/
(function(mod) {
if (true) // CommonJS
mod(__webpack_require__(/*! ../../lib/codemirror */ "VrN/"), __webpack_require__(/*! ../fold/xml-fold */ "osHv"));
else {}
})(function(CodeMirror) {
CodeMirror.defineOption("autoCloseTags", false, function(cm, val, old) {
if (old != CodeMirror.Init && old)
cm.removeKeyMap("autoCloseTags");
if (!val) return;
var map = {name: "autoCloseTags"};
if (typeof val != "object" || val.whenClosing !== false)
map["'/'"] = function(cm) { return autoCloseSlash(cm); };
if (typeof val != "object" || val.whenOpening !== false)
map["'>'"] = function(cm) { return autoCloseGT(cm); };
cm.addKeyMap(map);
});
var htmlDontClose = ["area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param",
"source", "track", "wbr"];
var htmlIndent = ["applet", "blockquote", "body", "button", "div", "dl", "fieldset", "form", "frameset", "h1", "h2", "h3", "h4",
"h5", "h6", "head", "html", "iframe", "layer", "legend", "object", "ol", "p", "select", "table", "ul"];
function autoCloseGT(cm) {
if (cm.getOption("disableInput")) return CodeMirror.Pass;
var ranges = cm.listSelections(), replacements = [];
var opt = cm.getOption("autoCloseTags");
for (var i = 0; i < ranges.length; i++) {
if (!ranges[i].empty()) return CodeMirror.Pass;
var pos = ranges[i].head, tok = cm.getTokenAt(pos);
var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state;
var tagInfo = inner.mode.xmlCurrentTag && inner.mode.xmlCurrentTag(state)
var tagName = tagInfo && tagInfo.name
if (!tagName) return CodeMirror.Pass
var html = inner.mode.configuration == "html";
var dontCloseTags = (typeof opt == "object" && opt.dontCloseTags) || (html && htmlDontClose);
var indentTags = (typeof opt == "object" && opt.indentTags) || (html && htmlIndent);
if (tok.end > pos.ch) tagName = tagName.slice(0, tagName.length - tok.end + pos.ch);
var lowerTagName = tagName.toLowerCase();
// Don't process the '>' at the end of an end-tag or self-closing tag
if (!tagName ||
tok.type == "string" && (tok.end != pos.ch || !/[\"\']/.test(tok.string.charAt(tok.string.length - 1)) || tok.string.length == 1) ||
tok.type == "tag" && tagInfo.close ||
tok.string.indexOf("/") == (pos.ch - tok.start - 1) || // match something like <someTagName />
dontCloseTags && indexOf(dontCloseTags, lowerTagName) > -1 ||
closingTagExists(cm, inner.mode.xmlCurrentContext && inner.mode.xmlCurrentContext(state) || [], tagName, pos, true))
return CodeMirror.Pass;
var emptyTags = typeof opt == "object" && opt.emptyTags;
if (emptyTags && indexOf(emptyTags, tagName) > -1) {
replacements[i] = { text: "/>", newPos: CodeMirror.Pos(pos.line, pos.ch + 2) };
continue;
}
var indent = indentTags && indexOf(indentTags, lowerTagName) > -1;
replacements[i] = {indent: indent,
text: ">" + (indent ? "\n\n" : "") + "</" + tagName + ">",
newPos: indent ? CodeMirror.Pos(pos.line + 1, 0) : CodeMirror.Pos(pos.line, pos.ch + 1)};
}
var dontIndentOnAutoClose = (typeof opt == "object" && opt.dontIndentOnAutoClose);
for (var i = ranges.length - 1; i >= 0; i--) {
var info = replacements[i];
cm.replaceRange(info.text, ranges[i].head, ranges[i].anchor, "+insert");
var sel = cm.listSelections().slice(0);
sel[i] = {head: info.newPos, anchor: info.newPos};
cm.setSelections(sel);
if (!dontIndentOnAutoClose && info.indent) {
cm.indentLine(info.newPos.line, null, true);
cm.indentLine(info.newPos.line + 1, null, true);
}
}
}
function autoCloseCurrent(cm, typingSlash) {
var ranges = cm.listSelections(), replacements = [];
var head = typingSlash ? "/" : "</";
var opt = cm.getOption("autoCloseTags");
var dontIndentOnAutoClose = (typeof opt == "object" && opt.dontIndentOnSlash);
for (var i = 0; i < ranges.length; i++) {
if (!ranges[i].empty()) return CodeMirror.Pass;
var pos = ranges[i].head, tok = cm.getTokenAt(pos);
var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state;
if (typingSlash && (tok.type == "string" || tok.string.charAt(0) != "<" ||
tok.start != pos.ch - 1))
return CodeMirror.Pass;
// Kludge to get around the fact that we are not in XML mode
// when completing in JS/CSS snippet in htmlmixed mode. Does not
// work for other XML embedded languages (there is no general
// way to go from a mixed mode to its current XML state).
var replacement, mixed = inner.mode.name != "xml" && cm.getMode().name == "htmlmixed"
if (mixed && inner.mode.name == "javascript") {
replacement = head + "script";
} else if (mixed && inner.mode.name == "css") {
replacement = head + "style";
} else {
var context = inner.mode.xmlCurrentContext && inner.mode.xmlCurrentContext(state)
if (!context || (context.length && closingTagExists(cm, context, context[context.length - 1], pos)))
return CodeMirror.Pass;
replacement = head + context[context.length - 1]
}
if (cm.getLine(pos.line).charAt(tok.end) != ">") replacement += ">";
replacements[i] = replacement;
}
cm.replaceSelections(replacements);
ranges = cm.listSelections();
if (!dontIndentOnAutoClose) {
for (var i = 0; i < ranges.length; i++)
if (i == ranges.length - 1 || ranges[i].head.line < ranges[i + 1].head.line)
cm.indentLine(ranges[i].head.line);
}
}
function autoCloseSlash(cm) {
if (cm.getOption("disableInput")) return CodeMirror.Pass;
return autoCloseCurrent(cm, true);
}
CodeMirror.commands.closeTag = function(cm) { return autoCloseCurrent(cm); };
function indexOf(collection, elt) {
if (collection.indexOf) return collection.indexOf(elt);
for (var i = 0, e = collection.length; i < e; ++i)
if (collection[i] == elt) return i;
return -1;
}
// If xml-fold is loaded, we use its functionality to try and verify
// whether a given tag is actually unclosed.
function closingTagExists(cm, context, tagName, pos, newTag) {
if (!CodeMirror.scanForClosingTag) return false;
var end = Math.min(cm.lastLine() + 1, pos.line + 500);
var nextClose = CodeMirror.scanForClosingTag(cm, pos, null, end);
if (!nextClose || nextClose.tag != tagName) return false;
// If the immediate wrapping context contains onCx instances of
// the same tag, a closing tag only exists if there are at least
// that many closing tags of that type following.
var onCx = newTag ? 1 : 0
for (var i = context.length - 1; i >= 0; i--) {
if (context[i] == tagName) ++onCx
else break
}
pos = nextClose.to;
for (var i = 1; i < onCx; i++) {
var next = CodeMirror.scanForClosingTag(cm, pos, null, end);
if (!next || next.tag != tagName) return false;
pos = next.to;
}
return true;
}
});
/***/ }),
/***/ "C+DQ":
/*!*********************************************************!*\
!*** ./src/components/markdown-editor/css/iconfont.css ***!
\*********************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/***/ "CP8R":
/*!********************************************************************!*\
!*** ./node_modules/@ant-design/icons-svg/lib/asn/FilterFilled.js ***!
\********************************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// This icon file is generated automatically.
Object.defineProperty(exports, "__esModule", { value: true });
var FilterFilled = { "icon": { "tag": "svg", "attrs": { "viewBox": "64 64 896 896", "focusable": "false" }, "children": [{ "tag": "path", "attrs": { "d": "M349 838c0 17.7 14.2 32 31.8 32h262.4c17.6 0 31.8-14.3 31.8-32V642H349v196zm531.1-684H143.9c-24.5 0-39.8 26.7-27.5 48l221.3 376h348.8l221.3-376c12.1-21.3-3.2-48-27.7-48z" } }] }, "name": "filter", "theme": "filled" };
exports.default = FilterFilled;
/***/ }),
/***/ "Cs+z":
/*!******************************************!*\
!*** ./src/components/HomeModal/jqr.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/jqr.b801d45b.png";
/***/ }),
/***/ "Ct/S":
/*!*****************************************************!*\
!*** ./src/components/AuthModal/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 = {"tilte":"tilte___1Tz7i","flexRow":"flexRow___3w9_D","flexColumn":"flexColumn___2HzC_","footerWrap":"footerWrap___12F5M","img":"img___3ED9Z","content":"content___rqPDY","modalContent":"modalContent___2h4ne"};
/***/ }),
/***/ "DL4k":
/*!*************************************************************************!*\
!*** ./node_modules/@ant-design/icons-svg/lib/asn/CaretDownOutlined.js ***!
\*************************************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// This icon file is generated automatically.
Object.defineProperty(exports, "__esModule", { value: true });
var CaretDownOutlined = { "icon": { "tag": "svg", "attrs": { "viewBox": "0 0 1024 1024", "focusable": "false" }, "children": [{ "tag": "path", "attrs": { "d": "M840.4 300H183.6c-19.7 0-30.7 20.8-18.5 35l328.4 380.8c9.4 10.9 27.5 10.9 37 0L858.9 335c12.2-14.2 1.2-35-18.5-35z" } }] }, "name": "caret-down", "theme": "outlined" };
exports.default = CaretDownOutlined;
/***/ }),
/***/ "DO2E":
/*!**********************************************************************!*\
!*** ./node_modules/@ant-design/icons-svg/lib/asn/DeleteOutlined.js ***!
\**********************************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// This icon file is generated automatically.
Object.defineProperty(exports, "__esModule", { value: true });
var DeleteOutlined = { "icon": { "tag": "svg", "attrs": { "viewBox": "64 64 896 896", "focusable": "false" }, "children": [{ "tag": "path", "attrs": { "d": "M360 184h-8c4.4 0 8-3.6 8-8v8h304v-8c0 4.4 3.6 8 8 8h-8v72h72v-80c0-35.3-28.7-64-64-64H352c-35.3 0-64 28.7-64 64v80h72v-72zm504 72H160c-17.7 0-32 14.3-32 32v32c0 4.4 3.6 8 8 8h60.4l24.7 523c1.6 34.1 29.8 61 63.9 61h454c34.2 0 62.3-26.8 63.9-61l24.7-523H888c4.4 0 8-3.6 8-8v-32c0-17.7-14.3-32-32-32zM731.3 840H292.7l-24.2-512h487l-24.2 512z" } }] }, "name": "delete", "theme": "outlined" };
exports.default = DeleteOutlined;
/***/ }),
/***/ "Dgm7":
/*!********************************************!*\
!*** ./src/assets/images/account/auth.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/auth.ea067b42.png";
/***/ }),
/***/ "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 = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;'
};
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 && /^<a /i.test(cap[0])) {
inLink = true;
} else if (inLink && /^<\/a>/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]*?(?:</\\1>[^\\n]*\\n+|$)' // (1)
+ '|comment[^\\n]*(\\n+|$)' // (2)
+ '|<\\?[\\s\\S]*?\\?>\\n*' // (3)
+ '|<![A-Z][\\s\\S]*?>\\n*' // (4)
+ '|<!\\[CDATA\\[[\\s\\S]*?\\]\\]>\\n*' // (5)
+ '|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:\\n{2,}|$)' // (6)
+ '|<(?!script|pre|style)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$)' // (7) open tag
+ '|</(?!script|pre|style)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$)' // (7) closing tag
+ ')',
def: /^ {0,3}\[(label)\]: *\n? *<?([^\s>]+)>?(?:(?: +\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 = /<!--(?!-?>)[\s\S]*?-->/;
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', '</?(?:tag)(?: +|\\n|/?>)|<(?: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', '</?(?:tag)(?: +|\\n|/?>)|<(?: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', '</?(?:tag)(?: +|\\n|/?>)|<(?: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]+?</\\1> *(?:\\n{2,}|\\s*$)' // closed tag
+ '|<tag(?:"[^"]*"|\'[^\']*\'|\\s[^\'"/>\\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: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\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' + '|^</[a-zA-Z][\\w:-]*\\s*>' // self-closing tag
+ '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag
+ '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. <?php ?>
+ '|^<![a-zA-Z]+\\s[\\s\\S]*?>' // declaration, e.g. <!DOCTYPE html>
+ '|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>',
// 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]*?(?:(?=[\\<!\[`*]|\b_|$)|[^ ](?= {2,}\n))|(?= {2,}\n))/,
punctuation: /^([\s*punctuation])/
}; // list of punctuation marks from common mark spec
// without * and _ to workaround cases with double emphasis
inline._punctuation = '!"#$%&\'()+\\-.,/:;<=>?@\\[\\]`^{|}~';
inline.punctuation = edit$1(inline.punctuation).replace(/punctuation/g, inline._punctuation).getRegex(); // sequences em should skip over [title](link), `code`, <html>
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]*?(?:(?=[\\<!\[`*~]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))|(?= {2,}\n|[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))/
});
inline.gfm.url = edit$1(inline.gfm.url, 'i').replace('email', inline.gfm._extended_email).getRegex();
/**
* GFM + Line Breaks Inline Grammar
*/
inline.breaks = merge$1({}, inline.gfm, {
br: edit$1(inline.br).replace('{2,}', '*').getRegex(),
text: edit$1(inline.gfm.text).replace('\\b_', '\\b_| {2,}\\n').replace(/\{2,\}/g, '*').getRegex()
});
var rules = {
block: block,
inline: inline
};
var defaults$2 = defaults.defaults;
var block$1 = rules.block,
inline$1 = rules.inline;
/**
* smartypants text replacement
*/
function smartypants(text) {
return text // em-dashes
.replace(/---/g, "\u2014") // en-dashes
.replace(/--/g, "\u2013") // opening singles
.replace(/(^|[-\u2014/(\[{"\s])'/g, "$1\u2018") // closing singles & apostrophes
.replace(/'/g, "\u2019") // opening doubles
.replace(/(^|[-\u2014/(\[{\u2018\s])"/g, "$1\u201C") // closing doubles
.replace(/"/g, "\u201D") // ellipses
.replace(/\.{3}/g, "\u2026");
}
/**
* mangle email addresses
*/
function mangle(text) {
var out = '',
i,
ch;
var l = text.length;
for (i = 0; i < l; i++) {
ch = text.charCodeAt(i);
if (Math.random() > 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 '<pre><code>' + (escaped ? _code : escape$1(_code, true)) + '</code></pre>\n';
}
return '<pre><code class="' + this.options.langPrefix + escape$1(lang, true) + '">' + (escaped ? _code : escape$1(_code, true)) + '</code></pre>\n';
};
_proto.blockquote = function blockquote(quote) {
return '<blockquote>\n' + quote + '</blockquote>\n';
};
_proto.html = function html(_html) {
return _html;
};
_proto.heading = function heading(text, level, raw, slugger) {
if (this.options.headerIds) {
return '<h' + level + ' id="' + this.options.headerPrefix + slugger.slug(raw) + '">' + text + '</h' + level + '>\n';
} // ignore IDs
return '<h' + level + '>' + text + '</h' + level + '>\n';
};
_proto.hr = function hr() {
return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
};
_proto.list = function list(body, ordered, start) {
var type = ordered ? 'ol' : 'ul',
startatt = ordered && start !== 1 ? ' start="' + start + '"' : '';
return '<' + type + startatt + '>\n' + body + '</' + type + '>\n';
};
_proto.listitem = function listitem(text) {
return '<li>' + text + '</li>\n';
};
_proto.checkbox = function checkbox(checked) {
return '<input ' + (checked ? 'checked="" ' : '') + 'disabled="" type="checkbox"' + (this.options.xhtml ? ' /' : '') + '> ';
};
_proto.paragraph = function paragraph(text) {
return '<p>' + text + '</p>\n';
};
_proto.table = function table(header, body) {
if (body) body = '<tbody>' + body + '</tbody>';
return '<table>\n' + '<thead>\n' + header + '</thead>\n' + body + '</table>\n';
};
_proto.tablerow = function tablerow(content) {
return '<tr>\n' + content + '</tr>\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 + '</' + type + '>\n';
} // span level renderer
;
_proto.strong = function strong(text) {
return '<strong>' + text + '</strong>';
};
_proto.em = function em(text) {
return '<em>' + text + '</em>';
};
_proto.codespan = function codespan(text) {
return '<code>' + text + '</code>';
};
_proto.br = function br() {
return this.options.xhtml ? '<br/>' : '<br>';
};
_proto.del = function del(text) {
return '<del>' + text + '</del>';
};
_proto.link = function link(href, title, text) {
href = cleanUrl$1(this.options.sanitize, this.options.baseUrl, href);
if (href === null) {
return text;
}
var out = '<a href="' + escape$1(href) + '"';
if (title) {
out += ' title="' + title + '"';
}
out += '>' + text + '</a>';
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 = '<img src="' + href + '" alt="' + text + '"';
if (title) {
out += ' title="' + title + '"';
}
out += this.options.xhtml ? '/>' : '>';
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 '<p>An error occurred:</p><pre>' + escape$2(e.message + '', true) + '</pre>';
}
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;
})));
/***/ }),
/***/ "E4JC":
/*!******************************************!*\
!*** ./node_modules/crypto-js/rabbit.js ***!
\******************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory, undef) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"), __webpack_require__(/*! ./enc-base64 */ "ETIr"), __webpack_require__(/*! ./md5 */ "cv67"), __webpack_require__(/*! ./evpkdf */ "K3mO"), __webpack_require__(/*! ./cipher-core */ "OLod"));
}
else {}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
// Reusable objects
var S = [];
var C_ = [];
var G = [];
/**
* Rabbit stream cipher algorithm
*/
var Rabbit = C_algo.Rabbit = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var K = this._key.words;
var iv = this.cfg.iv;
// Swap endian
for (var i = 0; i < 4; i++) {
K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) |
(((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00);
}
// Generate initial state values
var X = this._X = [
K[0], (K[3] << 16) | (K[2] >>> 16),
K[1], (K[0] << 16) | (K[3] >>> 16),
K[2], (K[1] << 16) | (K[0] >>> 16),
K[3], (K[2] << 16) | (K[1] >>> 16)
];
// Generate initial counter values
var C = this._C = [
(K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
(K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
(K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
(K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
];
// Carry bit
this._b = 0;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
// Modify the counters
for (var i = 0; i < 8; i++) {
C[i] ^= X[(i + 4) & 7];
}
// IV setup
if (iv) {
// Shortcuts
var IV = iv.words;
var IV_0 = IV[0];
var IV_1 = IV[1];
// Generate four subvectors
var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
var i3 = (i2 << 16) | (i0 & 0x0000ffff);
// Modify counter values
C[0] ^= i0;
C[1] ^= i1;
C[2] ^= i2;
C[3] ^= i3;
C[4] ^= i0;
C[5] ^= i1;
C[6] ^= i2;
C[7] ^= i3;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
}
},
_doProcessBlock: function (M, offset) {
// Shortcut
var X = this._X;
// Iterate the system
nextState.call(this);
// Generate four keystream words
S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
for (var i = 0; i < 4; i++) {
// Swap endian
S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
(((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
// Encrypt
M[offset + i] ^= S[i];
}
},
blockSize: 128/32,
ivSize: 64/32
});
function nextState() {
// Shortcuts
var X = this._X;
var C = this._C;
// Save old counter values
for (var i = 0; i < 8; i++) {
C_[i] = C[i];
}
// Calculate new counter values
C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
// Calculate the g-values
for (var i = 0; i < 8; i++) {
var gx = X[i] + C[i];
// Construct high and low argument for squaring
var ga = gx & 0xffff;
var gb = gx >>> 16;
// Calculate high and low result of squaring
var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
// High XOR low
G[i] = gh ^ gl;
}
// Calculate new state values
X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg);
* var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg);
*/
C.Rabbit = StreamCipher._createHelper(Rabbit);
}());
return CryptoJS.Rabbit;
}));
/***/ }),
/***/ "E7E6":
/*!********************************************!*\
!*** ./src/assets/images/icons/search.png ***!
\********************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports) {
module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADUCAYAAADZTGx+AAAgAElEQVR4Xu2dC3BU13nHv7MrIQkQQoCEtAIEAmxig4GACxhogpM6NY7jOKZO4nimwcFot23SNNNO02napJN0JjN9TNMm5eG3x4+YSeI3ftUGjCDGQMBgG4wxb+0u4mEeQhJI2tP539WR7i77uPfuvXfvar8zs7Mr7bnn8Z3vt9/5zlMQB5aAQQmsW7fO397eHujp6Rkfi8XGExFeDX2vABHVSSlrhBDDiKhdSnlOCBGWUu4mol1lZWWv3nfffccNZueJaMITpeBCeEICjz/++LCOjo5GIpogpWwUQjT2vU/A/wCClNJvtbBCCCml3CaEeGzChAmPLF269LLVtNx6jgFxS9IeyOehhx6q7OnpmSilnEhE2gsA4L0PhjHZillRUUHl5WUUf6+giopyKi+Pv8rKyrSX3++nnp4e7XXpUgedP3+ezp37lE6ebKPe3l4tCyFEhIj+UwjxaHNz8+ls+ebrewYkX5J3IN9169YNv3DhwsRYLIbXJAWBDoZRmbKFYkPRhw4dqgEwdCgAwOfyPiDKyefzWS454Dh58iQdPPiJBk0fKN1E9KyU8gehUKjVcuIOPciAOCRYJ5J95JFHyq9cuaJZACHEJCklIOgHQUqZ0QIAACg/FB+//niPwxD/H3793QqwJkePHqW2tjaSUsKinCOibwWDwfVulcFIPgyIESm5FGfDhg0lBw8ehOM7qbe3dxIggCXAe58VgBOcts0AgP6XfwCACho2bBgNGTLEpZoYz6arq4vee2+PBooQosvv999y//33bzaegrMxGRBn5ZuQOpR77dq1dVB4BQCsQB8AgGB8JicY3RsAgNewYQO//EOHDnPdAtgttr1736cjR44g2VPl5eXXLF++HBYl74EBsbkJHnnkkZFQ/p6eHk3xdd2gpj6nuDxTlvAB8GufDAH+h+8Ga0A365133qHTp8/AkvwiGAx+3wt1ZUBMtsL69evLTpw4gZEfKH+THoC+z9WZkkQ3RwEQ7wLFf/2VY5yLE2yyKp6LfuHCBdq06W0A0j1kyJCG++6771S+C8mAJLUAukEPP/xw/ZUrVyb5/f4m+AAAgYia+iwCJsTSDuUMOMJD+7tB8e5Q3A/A9xzSS2DHjh0UiUQxWvY3zc3N/5VvWRUlIE888cSI9vZ2TfH7+v8AAD5A1m6QEKLPEcbIT/yl/AG8e9ERzreSmck/Go3S9u078MjOUCg018yzTsQdlIBgNOjw4cMTYAWSfv2VFcg4HBrvBsWdYLzHQYh3hWAJAAkHZyQQi8Xo1Vdfw4RirLKysvree++94ExOxlIt2JZes2bNmL5hUK37owehb6lE2r6M6gYpRxjKz90gYwpjNhac766uy9TRcYk6O7u09+7uborFpDYBWVVVRaNHj06YgNyyZSudPXsWP0S3BIPBN8zmaWd8zwICZzgSiUzs7e3VlL8PANUNwt+VRkaDBrpAcR8Af7s5IWZnY3k1LcxldHZ2UkdHh/bCZywxUf8DJNkGLhobJ9DUqVM1H+2DDz6kQ4cO4ZEfhUKhf81nvT0DyNq1a2+MxWJfIaIFRDSNiAKZJsVKS0v7h0KVBdDPChfzaJDdCnX5MixAJ3V2dmiK39UVB0DBgG5RuqB8tsrKSs1a4F11UzFq1draSqdPx5di4f9z5syhixcvaJOHRPRgKBS63+76mEkv74A8+OCDs7u7u39JRDfpC64mxdTSiEQIKtgZNtPKWeJeuXKlX/HjVgDW4FIfFJ39CwzTJQPFhuKPGDFCe1efhw8frv0v248VZtFbWlq02XRYkGuvvYY+/HAfulhvBIPBW2ysqumk8grImjVrvheLxf6DiEpgEcaPH081NWMIgmVn2HRbpn0AAMS7O3ErgPdLl+ATxLtFaoVtugQwQakUX1kCtJH6nA0AIzVBN2zTpk20f/9+gi7ATxFC7A8Gg58x8rxTcfIGyOrVq38gpQQcNG7cOLrhhhk8R2CxlaFMeuUf8AXiXaJsAMAnS7YA+r9LSkoslsz8Y6+++qpacoKHw6FQCBuy8hbyAsgDDzywuLe3dwPWHV133XU0eTIGojikkwD2Vaj+frIVwP/xfaaAYet0FgBdIPxieyXA4X/yySeVBTkfDAZH5rNsrgMCx3vNmjXvSSlnTJzYSDNmzMhn/T2RN37hVd9fdYGUD4D/w0IYAUD1+fUwAIBCm7zcunUr7dmjOek9oVAor/S6DsiaNWtui8ViL6HRliz5fME1nhWiAIDq7ytfYGA49BLBR8gU8Auv+vypukKDbREjRrZefPFF+CAyGAxa36FlpbGSnnEdkFWrVj1ARCumTZtGU6dOsaEK+U8Cw5z6ro8aDlXWAMOkmQL6+AoA/UiQsgQYsCimgB+Mhx9+uDgBWb169T4p5bTPfe6PtSHAQggAAL/8A5Nh8dEf9Tf6zZkChi4zWQAMZXNIlMDq1auLE5BVq1ZhM/KIW2/9U3JzdCSTAmKIMXkYVO8DGAEAs/T6OQC9H4DvOJiTAABBCIVCrvdy9CV1PfNVq1Zp6w5uv/3L5iSWQ+z4eiCsAxr41U+cGe7S9kWnCxjnzwQArAMHeyXAgNgMCIY6sXRBr/jKB4B1yAQAlkPoAUh2hAEAr+C1F4BsqTEgNgCC0aFjx47RsWPHNTjSBSg3+vnpukAAwI7Z4GyNzt8blwADkiMgODZm7969mu+AAEcYy6bVKFDyaBADYFw5vRCTAckBkMOHD9P773+gtWNtbS199rOfpQkTJrAV8IJm21QGBsQiIJhE+sMfdmnNcP3119PChQsZDJuU0kvJMCAWAMFI1IYNG7W1RwsWLKCZM2d6qU25LDZKgAGxAMiePXu14yrHjh1Ld955p43NwUl5TQIMiElA1GZ+vC9btkxzyDkMXgkwICYBuXjxIm3cuImtx+BlIqFmDIhJQM6cOUNbt/5e8zvgf3AY3BJgQEwCgnsl3n13Ozvng5uL/toxICYBiUZP0vbt22nRokU0ffr0IlGT4q0mA8KAFK/2G6g5A8KAGFCT4o3CgDAgxav9BmrOgDAgBtSkeKMwIAxI8Wq/gZozIAyIATUp3igMCANSvNpvoOYMCANiQE2KNwoDwoAUr/YbqDkDwoAYUJPijcKAMCDFq/0Gas6AMCAG1KR4ozAgDEjxar+BmjMgDIgBNSneKAwIA1K82m+g5gwIA2JATYo3CgPCgBSv9huoOQPCgBhQk+KNwoAwIMWr/QZqzoAwIAbUpHijMCAMSPFqv4GaMyAMiAE1Kd4oDAgDUrzab6DmDAgDYkBNijcKA8KAFK/2G6g5A8KAGFCT4o3CgDAgxav9BmrOgDAgBtTEu1FwrXZ3d7f2unLlivaO/6nbhHMtOQPCgOSqQ44/j8uKlPInw4Br8NKF6upqqqmpyal8DAgDkpMC2fUwFF0pv94a4DPuobcScC99U1OTdjW31cCAMCBWdcf0c+kAwP9hJZwIjY2NVFZWZjlpBoQBsaw8yQ+m8geUNYCFwPduBlgOWBBYEquBAWFATOmOVX/AVCY2RPb5fFRfX0/Dhg3LKTUGhAG5SoGc8Ady0tIMD8M6lJSUUGlpKQ0ZMqT/HaNYuVgOlSUDUqSA5MMfsAoJrAEgUAAABj0QVtM18hwDMkgB8Zo/kE0Z4S8oxU8GAHDkKzAgBQxIofgDSrlVV0j/669gyGUo1kl4GBCPA1Lo/oDeGtjhEzgJQ6q0GRCPAdLR0UHnz5/vnzl2an7AqqLl0x+wWuZcnmNAPATIxYsXKRqNuj5fkKxAgCCdQ5xPfyAXRbf6LAPiIUCOHDmiWQ43QiH6A27IJTkPBsRDgHzyySeW1x0lN2yq+YFC9wcYEBclsGrVKm3dw+0eAiQSiRC6WUYDIEg1IqS6R0bT4XjpJcAWxEOAYNVqa2srdXV19bcY+wP5xZcB8RAgShXgh2CiD36CV+cH8qu27uXOgHgQEPean3PKJgEGhAHJpiNF/T0DwoAUNQDZKs+AMCDZdKSov2dAGJCiBiBb5RkQBiSbjhT19wwIA1LUAGSrPAPCgGTTkaL+ngFhQIoagGyVZ0AYkGw6UlDfY/8MViHYtQKBAWFACgoAVVh13haW5ehf6hRGHBaHY3+wcDOXwIAwILnoj6PPqj336lxePQhGDqHDSudJkyblVEYGhAHJSYHseBj77pMtAf7OdDC10Xz56FGjkkqK58X9IBarUhCP4Rc/FQROnssLwcCCwJJYDWxB2IJY1Z2UzyVbA/1J7bZmZCCx4cOHUyAQMBAzfRQGhAExrUDKGqRylPN9Cgt2WcIxBxyjRo3K+fhRBoQBSQsIRoTS+QZGnGTT5Jl4AMO4ACH5lUt3KlX2DAgDchUEyjJYvbjGhJ5njKrfc68HARDYNc+RrawMSJEAAmVP1SVSd/plUxQnv9dbA3UIhQLCyXyNpM2ADDJAsk2gGVEKJ+KoY4hSdYvcsgZW6sWAFCAg+gk0vY/gBWugTmFJ5Rvw2bxWEI0/Y/2OLIt5FsI8iH6IVA+CHRNoFsUWb6y+S2sUBPpu0WA7mpQtiMcsCA6uVodX53vIFNYg2SdQUBSiNbDyo8CAeAiQc+fOUVtbm5V2zOkZdXtTcrdosFkDK0JiQDwEyOHDh7WRJieCmkBL1S2CpeCQWgIMiIcAsePwarcm0IoFKAbEQ4Cge4VuVraQbgIN1oGtQTbpmfueAfEQIFi+gQt02tvb+3fFubGcwpzKFFdsBsRDgCjVAyh4sTXIP4wMiAcByb9acAmUBBgQBoRpyCABBoQBYUAYkKslUAhLTVhz8y8BtiBsQfKvhR4uAQPCgHhYPZ0tGhaAYlj91KlT2vo3vDo6OrTVDGpFg9o0JoTYRkQHhRAfE9GOIUOGbFm+fHn2SSubqsCreW0SJCeTWQKAACsWDh06RGfOnNGG0y2GGBG9J4T4HRE9EwwGAY5jgQFxTLScMCSA24N37NhBuGrbiSCEaCGinwSDwTcdSd+JRDOlyU662xLPT37hcJi2b9/uGBgparXZ5/P9uLm5eYOdNWYLYqc0OS2t+7R161bNcmQKlZWVNGHCBKqpqaERI0YQ/sa5vmqpPzanXb58mS5evEgXLlzQtiMcP35c+ztTEEJsLCkp+cGKFSt22dEcDIgdUuQ0NAns27ePWlpaKN2pLA0NDRoUeFVXV1uS2qeffkrHjh3TXhkgvOzz+b7X3Ny81lImuocYkFwlWIDPY8ckfp3xwoiSesdqZfyajxkzxlSt8Gu/efNm+uijj1I+h2NI586dS6NHjzaVbrbIsFbwb7CfJ1UQQjwuhAg1Nzd3ZEsr3fcMiFXJFcBz6iTGZBiy7a3HyYhGIcHo1GuvvUZnz569SiITJ06kG2+80XYwkjMCKPB3jhw5kqpV3vf7/XetXLnygJUmY0CsSM2Dz2D+IBkEq6etwA9oamrKWkv4A88++6w2h6EP2CqwZMmSnK9AyFqApAiwJBs2bNCsYlKIEtGCUCiUkqBM+TAgZlshz/HVIdXJ3SM7D5owAgjyf+655wg+gT7A8txyyy1aVy0fAQ7966+/TqdPn07IXgixv6SkZOGKFSuuNnUZCsqA5KMVDeSp/AS9jwCldONY0mxdLJThpZdeumoId9q0abR48WLXjidNJ0aUDz7R/v37kyHZUlZW9sXly5d3GWgCLQoDYlRSDsXT39+h7yI5dYhEpmpgX31VVVVW/wO/0JgR14drrrmGbr75ZoekZC3Zt956iw4cSHQ9MAPf3Nz8Z0IIzMhnDQxIVhHZF0H5CcoqAAirfkIupVJ76zHvgBd8BrwbOaF97969tGXLloTsx48fT7feeqvndmLCCr/yyiva/Ik+CCG+HwwGf2FEhgyIESmZjAMTr/cR1Gc7/QSjRVIH0OlBABBWDqCDU75u3bqEI5Iw0XfHHXf0T/AZLZdb8eCzPf/889rCSBWEEJf8fv+M+++/P/X4sK5wDEgOLaXO6k2GwQ0/IbnY6tihZKtg5/56DOfq5xwA3ze+8Q0aNmxYDlJ0/tFLly7Rr3/96wSwhRDPB4PBr2bLnQHJJqG+7/XdIvU5H36C/pBqPQxOn8aIpR6/+x0W0A6E+fPn06xZswxKML/Rdu/eTe+8805CIfx+/x+tXLlye6aSMSBJ0lEHV+sdZgCRw/JsS5qh9xOUj2DUT7CUYZaH0Jc/evRofyw481//+tc953ekqwas/TPPPKPtPdF1tdYHg8HbGBADGoNxcwgvH90j/Pond42s+gkGqmo6CnyPp556KuFHYunSpdqaqkIKWL+1fv16fZExkjU50wQiWxAibVIp1VIJuxtf7yforYKdfoLdZUZ6WMaxc+fO/qQxGbhs2TInsnI8zd/85jfJk4g/DYVC/5wuYwaESBvTz7Y+yUzLqesLkq2C036CmTKaiYuuiX7GfN68eTR79mwzSXgm7q5du2jbNuzijQfMsAeDwc8wIBmayCog+rN69TDAOgyWgONYn3jiiYTq3HPPPXlbSpKrXLEUBd1FffD5fI3Nzc3HUqXNFoRI2+SDV6ag7vJItgpW5hNybWQ3n8cSdiwAVAHzHnfddZebRbA9r9/+9rcJ8yJ+v/87K1eufJgBySBqAAInHaNV6uBqPQxevvDSdg3SJYjdgXv27On/D5avz5kzx8ksHU8b/hT8Kl036xfBYPD7DIjjoh98Gbz88ssJSzW+9KUvub6M3W6pYrITk546QN4IBoO3MCB2S7oI0nv66acT5g4wcz5y5MiCrjnugsHMug6QT4LB4BQGpKCbNT+Ff+yxx6izs7M/829/+9tUXl6en8LYlGtXVxc9+uijekBOB4PBGgbEJgEXUzIPPPBAwuTpypUrC2b2PF07YVZ97dqB8xyEEFeCwWAZA1JMmm1TXRkQmwRpNBk+OM6opLwRj7tYLrcDA+KywHPMjp30HAVo5HEpZXk0Gv5mLEbffeGFF7Q1Crfz6e5GRJf3ODzM62ATnDlzZtzly50hIrFSSqmdRvbCCy9qOTIgDgrexqR5otBGYaqkotHopFis5ydE4h4pZYk+CwbEAYE7mCQvNbFRuKdOnQp0d3f/iCi2QkoqTZU0A2KjwF1Iihcr2iDkcDg8Rkr590TyL4moIlOSDIgNAnc5CV7ublHgUkpfJBL5KyL5MyllpZFkGBAjUvJWHN4wZaE9otHo9Fis50EpaZ6ZxxkQM9LyRlzecmuiHaSUQ8Lh8D8KIf8hnZ/BXSwTAi2QqHxog4GGiluN3nVSyrRbFLMlwxYkm4S8+f1gPPaHiOaFQqF3M0nc8I7CcDj8NSL5mJRyeC5NyIDkIr38PssHx6WQv5RSRCKRfyGSP8LnXJuIAclVgvl7frAcPVpSUiLnz5//y+nTp/+1ECLjfdQZFb6trW14d3f3k0TyK3Y1CwNilyTzk85gOLx6+vTr+y4IEi+UlpZ+q7a2tj2dNNMCgvVTkUjrK1LS5+1sCgbETmnmJ61Cvv6gvr6ebrxxbr/ghKCN9fUNtwohUt4ZkhIQLA8Jh8PPEskv290EDIjdEnU/vUK9QAcXAy1YMD/FBT/ipUAgcKcQoidZmlcBEp/8Cz8hpfymE6JnQJyQqvtp4uxi3E+I/d364NUr2IYPH0aLFi3STqxJFYQQT9fXB+5NvljnKkBaW1v/jUj+rVMiZ0Cckqz76RbKJZ44vmnx4kU0dOjQLEIS/97Q0PB3+kgJgLS2ti4SgjbBijglbgbEKcnmJ12vXwNdWVmpXUUNC5ItwHpISZ9raGhoUXH7AZFSVoTD4d1E8ppsCeXyPQOSi/S8+SzONX777bevug9QlXbSpEk0d+5c2+9Lx2F/O3bsSLjURy8hXA13ww0zTF4qKg4EAoFZQgjtKJd+QJzuWqmCMyDeVHI7SrVv3z5qaWlJe4VEQ0ODdmUCXtXV1ZayxCHauMYAr9bW1pRp4PDwGTOmU2Njo6U8iAa6WhogbW1tU3p6uvdLKf0WUzT8GANiWFQFGRG/6rjkMxwOZyw//AFYFpz1izvV0RWCr6BOwIdVwkAA/BwcOI07BgEF/s4URo8eTdOnT6eqKuv3tAshektKSqfV1tYe1AAJh8OrpIwF3WgRBsQNKec/DwCCZfKRSMSVwmAId9q0a7NeYW20MEL4VgcCgZCA7xGJhE9JKbN7MUZTzxCPAbFBiAWUBLpB8BOcAgVgXHvttVRTox15YFvATbj19YEaEQ6H75Qylng7o23ZXJ0QA+KgcD2aNEa6sCvRrmuw0X2qrw9QIFBPw4fntHY2o8SE8H1NtLa2/rJvq6wr4mVAXBGzpzJJXpqCa6MnT55M0WhUu5dFfy+kuo4O103AH8E5wIiP18iRVQSLgeun3QniVwBkK5Fc4E6GfOyPW3L2Qj6wGAcOHKCNGzdmLA4gaGpqokmTJpocknW6luL3IhxujUgp65zOSqXPFsQtSbubD0adcBkqLAJGnNTFqKm6Vcoa4CppLE3x6nUKQoioaG09gQkR186zZ0DcVVwncsO98QBA/8L8hJG75OfPn0+1tSlvGnCiqLmm2cWA5CrCQf487tJQICjLAKc7OcB3qKwcTrAKVVUjtbkN3Cjb0dHRHzV5qXkBiK6Lu1gF0EpuFRHKnAxDqok5ONAAAKNJAAJdJEz06e97P3jwE/rwww/7i47vliz5vOZsF0ro62Kxk14oDWZnOXFiorIIgAKf9b/2Ki+MJMVhiIMAKABDptt9r1zppjfffJO6u7v7iwwnHDv5CiuIrTzMW1gtZqm06BLpLQNgwDKO5IDh0zgI6CbFu0pGVsEmp7N37/sJCwiR7he+cHPavRiWKuXKQ+JXPFHoiqDdyQROMjYwKYugoIBTnRyw7ikOwQAQ2fdLZK8HLNPGjZsSJgWvv/56mjy5KfvDHoshhO9OXmrisUYxWhwMn2LkSHWT8I4hVgy3JoeKioo+fwFdJEAxgvA/J8L27YnLSgDdzTcvKbh7DfuXmkBIbi5WfPnl9drM6dKlt5qaFIpGT2qL37BtEqs1iylAXlB+vWU4e/ZsymXlUEjlK8Tfq1zr2qBMLS1bEppmzpw51NAQKLjm6l+siJK7udz9zTffokuXLmm/KmZGNIoFEDi2+sk2WAZ0m1JNuGEdkt55xmf3lmFcrfObN7doVk0F7PnAVtdCC1ctd0cF3Now9e677xKUfebMG7SNM0bDYAQEjnKqOYbkCTeMGGHkaMB5jvsOGG71SsCq3Z07/5BQHFj7UaOsbYzKb72SNkyhMG5tuT127Djt3r1b2355003Gl4DhbNht294lzMTOmjUrv/KzkHtnZ2dCFwmWIdUcA+YL1LAqfAV0k/C3fo7BQvaOPgLr9tZbGxKGiQOBAM2dO8fRfJ1JPM2W2z4r4vihDehCoJuFkRUc4FVXZ2wZGLodW7f+nmbMmEELFy50RjY2pYoupN55hpXA/5IDLEB8sm3AeQYMmeYYbCqirckMhklBCCTjoQ1KYm50tQ4fPkI4whJnFC1ceJOhNf1QMPxKYXHbsmXLbG3gXBLDdtDkYVVYi+Sg5hj0s89O7mXIpU5mnh08k4IaIpmP/enrajl6cJwSvhoOxHj87NmztL3JmQL65a+99ro2O3v33Xdr+wLcDnCWk4dVU024AfyBOYb47LOZAQm365VLfoNlUtDwwXF9kDh29KhqDAxdAhL4FghTpkymadOmZexefPDBh3To0CHCcS633XZbLu2a8Vk1x6B3oNHF0y+dUAlgL4PyFdTsc0WFa4ujHZOBkYQHz6SgiaNHlWCcOrw6WfAHDx6kffv2a0ulq6tH0nXXXZfWOij/Be84DAxj7LkG/RyDAiJ5l5vKA3MMybPPsIDFGgbDpKClw6tVgztx/UEqZTp79lPauXMnqb47xs+bmiYRlkcnO6zo4mA0C0DNnDmT5s2bZ3iER23q0VsGjNtn3tQz4ECnO9e1GAEZHJOCOVx/oLMktl6gk06ZYBUOHTqsLXJTa4fQfRk7dqw2lg6fQ60VOnGild577z1NsfGLPnv2bJo4caK2f1kF/aYe5TfAh0g1xzBkSCmNHFmtnYyhhlXV+UzFqPxG6vz225sTDq4upEnB+KU54mf19fU/zukCHb2g7LqCLZvw0eXBpBOGDtHH1Yd4f79KO2AM8WAJlJMMSwOA8B0sUaqRJKSFoVXEw2gYTsUAEF6acMsmHy98X8iTgkKIdiLx54FAwNBJPqauVLPjEk8zDYzuD7pf8Alg0lOtSs2UHqABVJhbqKsbq3XZuJtkpgWujgurjXks/Q9QoUwKCiH2+Xz+u+vq6t43KgVTgCBRXAMdiUR+RBT7oZVroI0WLFW89vZL1N5+kTD2DljQLevuxnuPZgUw2xyfbxhB1dWjqFhGk3KRqdlnjx8/Trt27e5/rBB2CgpB3US+n9fX1/9MCHH12v8MQjANiEorbk16HpSS5pkVMscvXAmoSV5VA6/vFBSCtvl8JSvMWA1961gGpM+a+CKRyHeJ5E+llJWF2+xccqMSgNXetm2b1vXFwMn8+fP6D5w2moYb8YQQF4nEP9XX1/9P8q1RZvLPCRCVUTgcHiOl/CGR/AsicmYnjplacVzHJYAhc4+O9HUSif8VQvw8EAiczlUQtgCiCnHq1KlAd3f3PxHFvuO2f5KrIPj5wpZAn5/xUGlp6U9ramoy371goqq2AqLyPXnyZFNvb/ePicQ9uDHXRHk4KkvAlATiN9PKp3y+kp/U1dUdNvWwgciOAKLyPXPmzLjLlztDRGKllNLe8+kNVI6jDF4JCCFOE8m1ZWUVq0aPHn3CqZo6CogqNNZ1RaPhb8Zi9D0iWXi7nZySPqdrQQJit89H/11XF3haCNFlIQFTj7gCiL5E4XB4MZEMEdEdUsps9/KaqgxHHpwSEELg/NLnicSqQCCw2c1aug6IqhwWQvb09HyVSH6LiL7Ivoqbze79vOK+Bf0fkXiypKTkudra2sR1Ry5VIW+A6OsXjUZre3t778DBmPAAAAI6SURBVO6DZb5LdedsvCmBdwCF3+9fV1dXF98slMfgCUCSumCNQsgvSymXSklLeF4lj9rhTtadQtAGIcR6KbWNS0fdydZYLp4DRF9snLQSjUZvjsViS4Wg26SUVi++NiYNjuWKBIQQR6Wkl30+3/q6urq3hBBXb+J3pSTZM/E0IMnFj0Qi10kp/4QotphILJJSjs1eRY6RbwkIIU4SyRYi32YhxBv19fUD9yLku3BZ8i8oQJLrcurUiWt6e8Wi3l7CyBiO8JvicXkXS/EOEokWv582+/2ypaZm3IFCrXhBA5Is9La2trqenp6biGi2lJhv0eZcxhVq4xRIuU8Qid1CCKyB31VSUrK1trY2WiBlz1rMQQVIqtpeuHBidEcHzZIy/iLSXtfyWrGsupEQIb7WiT4iot1CxF9Dh9LuESPGnTGXUmHFHvSApGoOzLm0tbU19vb2TpVSThGCphLJKVLSVCFoYrHCAwikpCNC0MdE4qCU9LEQ4qDf7/+4trb2aN/cRGFpeI6lLUpAMslMSulva2ub2NPT0+TzyUAsJup9PgpIKQNSinohtM/1RFRo5/1cFkJEpKSwEDIihAjHYhT2+WQkFhPhkpKSQ7W1tUdwsnmOOjWoHmdALDbn+fPnR3V2dgKW0ULEqmIxUSWlHCmErJJSVAlBVVIS3kcS4X9ULoQolVKWZnpHcaSU3UKI7szv1EUkzuNSKSEI7+eFkOelFOeFEOd8Pnz24fOZioqKcFVV1VmLVS3qx/4fQLyzKIIkCJoAAAAASUVORK5CYII="
/***/ }),
/***/ "ELLl":
/*!*************************************************************!*\
!*** ./node_modules/codemirror/addon/edit/closebrackets.js ***!
\*************************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (true) // CommonJS
mod(__webpack_require__(/*! ../../lib/codemirror */ "VrN/"));
else {}
})(function(CodeMirror) {
var defaults = {
pairs: "()[]{}''\"\"",
closeBefore: ")]}'\":;>",
triples: "",
explode: "[]{}"
};
var Pos = CodeMirror.Pos;
CodeMirror.defineOption("autoCloseBrackets", false, function(cm, val, old) {
if (old && old != CodeMirror.Init) {
cm.removeKeyMap(keyMap);
cm.state.closeBrackets = null;
}
if (val) {
ensureBound(getOption(val, "pairs"))
cm.state.closeBrackets = val;
cm.addKeyMap(keyMap);
}
});
function getOption(conf, name) {
if (name == "pairs" && typeof conf == "string") return conf;
if (typeof conf == "object" && conf[name] != null) return conf[name];
return defaults[name];
}
var keyMap = {Backspace: handleBackspace, Enter: handleEnter};
function ensureBound(chars) {
for (var i = 0; i < chars.length; i++) {
var ch = chars.charAt(i), key = "'" + ch + "'"
if (!keyMap[key]) keyMap[key] = handler(ch)
}
}
ensureBound(defaults.pairs + "`")
function handler(ch) {
return function(cm) { return handleChar(cm, ch); };
}
function getConfig(cm) {
var deflt = cm.state.closeBrackets;
if (!deflt || deflt.override) return deflt;
var mode = cm.getModeAt(cm.getCursor());
return mode.closeBrackets || deflt;
}
function handleBackspace(cm) {
var conf = getConfig(cm);
if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass;
var pairs = getOption(conf, "pairs");
var ranges = cm.listSelections();
for (var i = 0; i < ranges.length; i++) {
if (!ranges[i].empty()) return CodeMirror.Pass;
var around = charsAround(cm, ranges[i].head);
if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass;
}
for (var i = ranges.length - 1; i >= 0; i--) {
var cur = ranges[i].head;
cm.replaceRange("", Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1), "+delete");
}
}
function handleEnter(cm) {
var conf = getConfig(cm);
var explode = conf && getOption(conf, "explode");
if (!explode || cm.getOption("disableInput")) return CodeMirror.Pass;
var ranges = cm.listSelections();
for (var i = 0; i < ranges.length; i++) {
if (!ranges[i].empty()) return CodeMirror.Pass;
var around = charsAround(cm, ranges[i].head);
if (!around || explode.indexOf(around) % 2 != 0) return CodeMirror.Pass;
}
cm.operation(function() {
var linesep = cm.lineSeparator() || "\n";
cm.replaceSelection(linesep + linesep, null);
cm.execCommand("goCharLeft");
ranges = cm.listSelections();
for (var i = 0; i < ranges.length; i++) {
var line = ranges[i].head.line;
cm.indentLine(line, null, true);
cm.indentLine(line + 1, null, true);
}
});
}
function contractSelection(sel) {
var inverted = CodeMirror.cmpPos(sel.anchor, sel.head) > 0;
return {anchor: new Pos(sel.anchor.line, sel.anchor.ch + (inverted ? -1 : 1)),
head: new Pos(sel.head.line, sel.head.ch + (inverted ? 1 : -1))};
}
function handleChar(cm, ch) {
var conf = getConfig(cm);
if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass;
var pairs = getOption(conf, "pairs");
var pos = pairs.indexOf(ch);
if (pos == -1) return CodeMirror.Pass;
var closeBefore = getOption(conf,"closeBefore");
var triples = getOption(conf, "triples");
var identical = pairs.charAt(pos + 1) == ch;
var ranges = cm.listSelections();
var opening = pos % 2 == 0;
var type;
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i], cur = range.head, curType;
var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1));
if (opening && !range.empty()) {
curType = "surround";
} else if ((identical || !opening) && next == ch) {
if (identical && stringStartsAfter(cm, cur))
curType = "both";
else if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch)
curType = "skipThree";
else
curType = "skip";
} else if (identical && cur.ch > 1 && triples.indexOf(ch) >= 0 &&
cm.getRange(Pos(cur.line, cur.ch - 2), cur) == ch + ch) {
if (cur.ch > 2 && /\bstring/.test(cm.getTokenTypeAt(Pos(cur.line, cur.ch - 2)))) return CodeMirror.Pass;
curType = "addFour";
} else if (identical) {
var prev = cur.ch == 0 ? " " : cm.getRange(Pos(cur.line, cur.ch - 1), cur)
if (!CodeMirror.isWordChar(next) && prev != ch && !CodeMirror.isWordChar(prev)) curType = "both";
else return CodeMirror.Pass;
} else if (opening && (next.length === 0 || /\s/.test(next) || closeBefore.indexOf(next) > -1)) {
curType = "both";
} else {
return CodeMirror.Pass;
}
if (!type) type = curType;
else if (type != curType) return CodeMirror.Pass;
}
var left = pos % 2 ? pairs.charAt(pos - 1) : ch;
var right = pos % 2 ? ch : pairs.charAt(pos + 1);
cm.operation(function() {
if (type == "skip") {
cm.execCommand("goCharRight");
} else if (type == "skipThree") {
for (var i = 0; i < 3; i++)
cm.execCommand("goCharRight");
} else if (type == "surround") {
var sels = cm.getSelections();
for (var i = 0; i < sels.length; i++)
sels[i] = left + sels[i] + right;
cm.replaceSelections(sels, "around");
sels = cm.listSelections().slice();
for (var i = 0; i < sels.length; i++)
sels[i] = contractSelection(sels[i]);
cm.setSelections(sels);
} else if (type == "both") {
cm.replaceSelection(left + right, null);
cm.triggerElectric(left + right);
cm.execCommand("goCharLeft");
} else if (type == "addFour") {
cm.replaceSelection(left + left + left + left, "before");
cm.execCommand("goCharRight");
}
});
}
function charsAround(cm, pos) {
var str = cm.getRange(Pos(pos.line, pos.ch - 1),
Pos(pos.line, pos.ch + 1));
return str.length == 2 ? str : null;
}
function stringStartsAfter(cm, pos) {
var token = cm.getTokenAt(Pos(pos.line, pos.ch + 1))
return /\bstring/.test(token.type) && token.start == pos.ch &&
(pos.ch == 0 || !/\bstring/.test(cm.getTokenTypeAt(pos)))
}
});
/***/ }),
/***/ "ELcG":
/*!*********************************************!*\
!*** ./node_modules/crypto-js/ripemd160.js ***!
\*********************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"));
}
else {}
}(this, function (CryptoJS) {
/** @preserve
(c) 2012 by Cédric Mesnil. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- 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.
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.
*/
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Constants table
var _zl = WordArray.create([
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]);
var _zr = WordArray.create([
5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]);
var _sl = WordArray.create([
11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]);
var _sr = WordArray.create([
8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]);
var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]);
var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]);
/**
* RIPEMD160 hash algorithm.
*/
var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({
_doReset: function () {
this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]);
},
_doProcessBlock: function (M, offset) {
// Swap endian
for (var i = 0; i < 16; i++) {
// Shortcuts
var offset_i = offset + i;
var M_offset_i = M[offset_i];
// Swap
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Shortcut
var H = this._hash.words;
var hl = _hl.words;
var hr = _hr.words;
var zl = _zl.words;
var zr = _zr.words;
var sl = _sl.words;
var sr = _sr.words;
// Working variables
var al, bl, cl, dl, el;
var ar, br, cr, dr, er;
ar = al = H[0];
br = bl = H[1];
cr = cl = H[2];
dr = dl = H[3];
er = el = H[4];
// Computation
var t;
for (var i = 0; i < 80; i += 1) {
t = (al + M[offset+zl[i]])|0;
if (i<16){
t += f1(bl,cl,dl) + hl[0];
} else if (i<32) {
t += f2(bl,cl,dl) + hl[1];
} else if (i<48) {
t += f3(bl,cl,dl) + hl[2];
} else if (i<64) {
t += f4(bl,cl,dl) + hl[3];
} else {// if (i<80) {
t += f5(bl,cl,dl) + hl[4];
}
t = t|0;
t = rotl(t,sl[i]);
t = (t+el)|0;
al = el;
el = dl;
dl = rotl(cl, 10);
cl = bl;
bl = t;
t = (ar + M[offset+zr[i]])|0;
if (i<16){
t += f5(br,cr,dr) + hr[0];
} else if (i<32) {
t += f4(br,cr,dr) + hr[1];
} else if (i<48) {
t += f3(br,cr,dr) + hr[2];
} else if (i<64) {
t += f2(br,cr,dr) + hr[3];
} else {// if (i<80) {
t += f1(br,cr,dr) + hr[4];
}
t = t|0;
t = rotl(t,sr[i]) ;
t = (t+er)|0;
ar = er;
er = dr;
dr = rotl(cr, 10);
cr = br;
br = t;
}
// Intermediate hash value
t = (H[1] + cl + dr)|0;
H[1] = (H[2] + dl + er)|0;
H[2] = (H[3] + el + ar)|0;
H[3] = (H[4] + al + br)|0;
H[4] = (H[0] + bl + cr)|0;
H[0] = t;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) |
(((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00)
);
data.sigBytes = (dataWords.length + 1) * 4;
// Hash final blocks
this._process();
// Shortcuts
var hash = this._hash;
var H = hash.words;
// Swap endian
for (var i = 0; i < 5; i++) {
// Shortcut
var H_i = H[i];
// Swap
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
}
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
function f1(x, y, z) {
return ((x) ^ (y) ^ (z));
}
function f2(x, y, z) {
return (((x)&(y)) | ((~x)&(z)));
}
function f3(x, y, z) {
return (((x) | (~(y))) ^ (z));
}
function f4(x, y, z) {
return (((x) & (z)) | ((y)&(~(z))));
}
function f5(x, y, z) {
return ((x) ^ ((y) |(~(z))));
}
function rotl(x,n) {
return (x<<n) | (x>>>(32-n));
}
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.RIPEMD160('message');
* var hash = CryptoJS.RIPEMD160(wordArray);
*/
C.RIPEMD160 = Hasher._createHelper(RIPEMD160);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacRIPEMD160(message, key);
*/
C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160);
}(Math));
return CryptoJS.RIPEMD160;
}));
/***/ }),
/***/ "ETIr":
/*!**********************************************!*\
!*** ./node_modules/crypto-js/enc-base64.js ***!
\**********************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"));
}
else {}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* Base64 encoding strategy.
*/
var Base64 = C_enc.Base64 = {
/**
* Converts a word array to a Base64 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Base64 string.
*
* @static
*
* @example
*
* var base64String = CryptoJS.enc.Base64.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
var map = this._map;
// Clamp excess bits
wordArray.clamp();
// Convert
var base64Chars = [];
for (var i = 0; i < sigBytes; i += 3) {
var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;
var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;
var triplet = (byte1 << 16) | (byte2 << 8) | byte3;
for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {
base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));
}
}
// Add padding
var paddingChar = map.charAt(64);
if (paddingChar) {
while (base64Chars.length % 4) {
base64Chars.push(paddingChar);
}
}
return base64Chars.join('');
},
/**
* Converts a Base64 string to a word array.
*
* @param {string} base64Str The Base64 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Base64.parse(base64String);
*/
parse: function (base64Str) {
// Shortcuts
var base64StrLength = base64Str.length;
var map = this._map;
var reverseMap = this._reverseMap;
if (!reverseMap) {
reverseMap = this._reverseMap = [];
for (var j = 0; j < map.length; j++) {
reverseMap[map.charCodeAt(j)] = j;
}
}
// Ignore padding
var paddingChar = map.charAt(64);
if (paddingChar) {
var paddingIndex = base64Str.indexOf(paddingChar);
if (paddingIndex !== -1) {
base64StrLength = paddingIndex;
}
}
// Convert
return parseLoop(base64Str, base64StrLength, reverseMap);
},
_map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
};
function parseLoop(base64Str, base64StrLength, reverseMap) {
var words = [];
var nBytes = 0;
for (var i = 0; i < base64StrLength; i++) {
if (i % 4) {
var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2);
var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2);
var bitsCombined = bits1 | bits2;
words[nBytes >>> 2] |= bitsCombined << (24 - (nBytes % 4) * 8);
nBytes++;
}
}
return WordArray.create(words, nBytes);
}
}());
return CryptoJS.enc.Base64;
}));
/***/ }),
/***/ "F+F2":
/*!***************************************************!*\
!*** ./node_modules/crypto-js/lib-typedarrays.js ***!
\***************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"));
}
else {}
}(this, function (CryptoJS) {
(function () {
// Check if typed arrays are supported
if (typeof ArrayBuffer != 'function') {
return;
}
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
// Reference original init
var superInit = WordArray.init;
// Augment WordArray.init to handle typed arrays
var subInit = WordArray.init = function (typedArray) {
// Convert buffers to uint8
if (typedArray instanceof ArrayBuffer) {
typedArray = new Uint8Array(typedArray);
}
// Convert other array views to uint8
if (
typedArray instanceof Int8Array ||
(typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) ||
typedArray instanceof Int16Array ||
typedArray instanceof Uint16Array ||
typedArray instanceof Int32Array ||
typedArray instanceof Uint32Array ||
typedArray instanceof Float32Array ||
typedArray instanceof Float64Array
) {
typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
}
// Handle Uint8Array
if (typedArray instanceof Uint8Array) {
// Shortcut
var typedArrayByteLength = typedArray.byteLength;
// Extract bytes
var words = [];
for (var i = 0; i < typedArrayByteLength; i++) {
words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8);
}
// Initialize this word array
superInit.call(this, words, typedArrayByteLength);
} else {
// Else call normal init
superInit.apply(this, arguments);
}
};
subInit.prototype = WordArray;
}());
return CryptoJS.lib.WordArray;
}));
/***/ }),
/***/ "F1Ou":
/*!*******************************************************************!*\
!*** ./node_modules/@ant-design/react-slick/lib/initial-state.js ***!
\*******************************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var initialState = {
animating: false,
autoplaying: null,
currentDirection: 0,
currentLeft: null,
currentSlide: 0,
direction: 1,
dragging: false,
edgeDragged: false,
initialized: false,
lazyLoadedList: [],
listHeight: null,
listWidth: null,
scrolling: false,
slideCount: null,
slideHeight: null,
slideWidth: null,
swipeLeft: null,
swiped: false,
// used by swipeEvent. differentites between touch and swipe.
swiping: false,
touchObject: {
startX: 0,
startY: 0,
curX: 0,
curY: 0
},
trackStyle: {},
trackWidth: 0,
targetSlide: 0
};
var _default = initialState;
exports["default"] = _default;
/***/ }),
/***/ "FH2Y":
/*!******************************************************!*\
!*** ./node_modules/@ant-design/icons/UpOutlined.js ***!
\******************************************************/
/*! no static exports found */
/*! exports used: default */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _UpOutlined = _interopRequireDefault(__webpack_require__(/*! ./lib/icons/UpOutlined */ "ZMnZ"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _default = _UpOutlined;
exports.default = _default;
module.exports = _default;
/***/ }),
/***/ "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) {
module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFsAAABKCAYAAADUvCinAAAAAXNSR0IArs4c6QAAFq9JREFUeAHdnAl4VFWWx6sqlYWEkIRsJCRkJQECCXsIS0gAWWwQl1YQxQ2nRx0/u9We8etvpmf87LFt7XHs7mmXbhVEFESQdWRfwiKGXRYhkI0sQAIBAmQnqZrfKfMyZVGVqldLjL7vu9997757zz33/84995xzb5VG8xO/Fi1aNPTDDz/M7w7D1HcHJjzFAyCPNxgMi/V6/YOe6kMNXZ2ayj+mugsXLhSAFxqNxtmPPvroge7A+09Osj///HOvmzdvvoZET/D19Z04f/78i90BaOHhJwU20hx748aNZVqt9kR0dHTOnXfe2dxdgBY+tN2JGVd4QT8/gsp4GRovPfnkkytcoeWptj96ycbaiEdl/BWgEWjt+AULFlzwFFiu0v3RSvaGDRt8L168+CIALNDpdL99/PHHl7oKhqfbe3m6A3fTR4J1/fr1m88iuBxJPs8iOBdr45C7+/EEvR+NZIuVUVdX9wBg/wYgTnp7e//rI488UuoqKCyqv4FmK+rnj67Sste+2+vsjz/+OODWrVsiyb9iMIcAZh4L4El7A3PkPUA/Db2ZERERdzhS39U63RbsDz74YDBq4qmWlpZZ5GtIdz7xxBMlrg5YaY/18iuAnhsYGDht1qxZDUq5J/NuBTZSnIAUzwGEOYB7i/R3pO5f3AkGtHVI9BuAmkG644EHHrjpSYDNaf+gOvvQoUPe33zzTRYMTSVNB1xf0mfo4+V4fkXmjMr9p59+GtLU1CSSPpzHvcQ8NqK36y3r2Xpub7+M92UZGRnPjhw58patup4o71KwkahwgBqFXTyawUgS6RI9vBngNj/22GPFloNkukfTZjZ17iXl8L5jNlLexPMW8lU9e/Zcj5RetWyvPKOWsrl/HzPxTdTR35XyrszdBjZAaD/66KMgBh4KmGGkKAaSzHN/yXkv96IbD5If8PLyOpCWlnbUmnQtWbIkGV19jwBM3Uyh7efnp+nfv3/lmTNnYnx8fE7OnDkzrKioSFdYWBhx/fp1wayVurvIV/Ph1mAOnpfC9evX+1+6dOkVaEzmcb67FlehrfZyC9hI3wEG04/B1sLAFVINqYrnYsoLJfXq1asYyWu0xaDEndva2u6hjYA8ROohrW0pKSmlgCz3iRTpli1bpgHMvPvvvz9H6siFaqkuKSlp40NEX716VQMNI8US6dsCrQd5/gS18XtrH1bad9XlFrCdYRYQdIsXL84CYFEP90AjQegEBQU1p6amliYnJ/v06NFDyr7HozWwpZ1yNTc31+zZs6e1rKysj1IG2CfpYxWzaTWe5jdKeVfn3xuIpzuXBfH48eOTUDEC7t2kSOkzJCSkftCgQaXx8fGBqIs4KbN1dQK2ob6+fu+uXbt8/f39/bKysvwANxzQa8+ePdv3woULvkIT4M+RrSKtRnfv49nAfZdcHge73SmZzmhEPcwkD5KRhYeHXwPgsri4uFCsj1gpc+SyAnbNlStXjiDN0aGhoY1jxowJhN4AS1rMoNrz58/XnD59Ooo8AF6kSjVgr2XRXB0QELADNddi2c6dzw6DjbvcE3f5CZiMcZQB6qYwmKnkPaRNnz59qgcPHnw+JiYmCqmTBVT1JWADzm5sb92xY8dakdhE9HFlQkJCDDT7OUKQmXWTINbFgoKCyPLy8iCepZmssl8K8GpNSkf6lDoOgd2++5EPaCMdJWwirtVq+vbtW4bVcZlgfj8GEqGmvVndNgApQIIvbdy4MRcpbQLgIwMHDgxAr6dTz6FxmNHruIVuw+XLl8sBPrS0tDQc2qJqHDYpOwg5cOMQk1gKQ2DiuAP0hFFNfHz8WQCuxfsTc6+3I+3M6rTwUauwMCqR2pvo3J7V1dVxYWFhtUT7bh44cCAL0y9vzpw5OWZt3HXbxAc9h6rpiXUTgzcrdMWk3E2+ytykdKZDh8BeunRpWENDQyUdmBYZy45goo1pfAqAG9Gbqbw36WXLepbPqKV8pnH9tWvXfGtrawNZ4EKpo8dMvI5OvwS4BhbPSOgnS7m0b1cjngJbulCuFvgqYXH1wZ5P4OODucmkFOBnESVU7eZ3eGNKD9byefPm1SDdTzDl3kTqOkwqpS7T+Tg2bChqwmQfK+X2cnSsP/pbg5kni1oogxE1Izv+0od8tB/y8uFDJ2LjF7KveQ2h6M3YRTgnwufL5LJxoepySLLNKQL6HUjdFlb9OhhYcuTIEYlrJEkdQD82YsQIPwL6HgOqKyQbW73s1KlTLaRkkWjWhSYW9pPY/z2J5YSfPHkyCEEZjs1+whwbe/cOSbZCZOfOnfri4uK3ANqIuuhJenrYsGHHmGpvfvXVV+PQdWNIGqZ/0dixY+sxpyT28aO4mLXXEZ4LgBmP3o4DTJlxZ4YMGdKEozWIQZiMg9GjR9eBgZ6P8A6Snt2uWhwaoyqwWTR+ifucBsjmxDMok3QWa+rVzZs3D4bpWSQd9arHjx9/nsVNLAZVfZl34MH7Ntz7khMnTgQztnAAD8J6quIIRAFmqizut81QynpOnDjxwqZNm8Yzyx+Bt8WO8uewGpHoGwtVATEJMbdEr9q6ylnsFhEAimY1f5iv34MAfR0e3Rn080CY9bfV0JFyd6gRpPIicZTmb7/9Nr6xsVE82Ib09PRiFvkIJNrk1drjBaFqxjm6gceb+tBDD12zV1/eq5G2/4KhQIC2R7dfcHDwfxCPrmZQb6xdu1aP1fGLLVu2jICxVnT6MWZBLIupWpPQXr+dvkdq6wHnIo5QLKZkFOMw4sEWooe9uY+nsarFPTc3tx4rLZyP9Sptn+m08/aXDkk20yUHoHYi1Qa+fGdSba3Pawz07TVr1lxB4p9C0lNFH/LhCnBMenEfba2RrTKVkm0k/FpGPCYIPRsiNJOSkqro+wZ6WBZ1l04XMDOu5ufnBzNbMzEF7e7w6wnoxwLAW6ShdG4VSMAKY2EwOgG0jC8EKf63e++9t47799B1ryFhC44ePTqBJDHqCmi38jETpLI7Lon8EecWNdGXWRWP+qqbOnXqWfRwDLyIWXmb+epMv8yMXqgjHUL0LvhlAnqnQS09lZaQJnbWGQucJjEx0RS56ayenXc9ef/r6dOnN5Mv3Ldv35u4yPNwGO4DGC8AuYKVcwWJS7FDx+prxtCEx1mNFEeTh/Xu3bsNS6kUvoNYa0RlOUXXamfthYCrnzRpUs0XX3wxEqH9BcXvdVqfhe8GjAZ2Vmn27NmtAK5Gv3dGTnnXys1SzMaP9+7dexf3C+AjAAumAdDLxRqg7LY+LdUIDscF7N5APpo4Rhp0cBX2vgE9rEo9KUw5kyM4TZi8jcyaVMK2l23R8AJIUR9ptiogGRrccKvqxVYbB8uFZgbgPowEViLZv0TCCwkLZJAlAJ4RwIpYbP2RIG+FJsBqiNMgrPqmvLy8AMy2QKyJlnHjxl1CHQVGRUUJ6J0Kj0LLXTlBtlvM0sDW1tbwdevWrbVFV9seb36BCsOQLHNQk9HRaRLjJRjvY4uAm8s3wvDr7EEmsk6IO5xG0EmDBSNbY8FE5xq3bt0aLZE57OE2hOAiuWwi+7qZD9Xk8Ctqt23bJnuw/wSOVQoB7o0IxgnZzLZqjbR7it8MHTp0EAO1Wkch5qF8N3RfRQ+KtfAi/E5W+snMzKwaMGCAPwPopZR1lxzb21hZWWkNLwMf4SlzSe7gGW/qOaZwGmCLXv0hrmw63Yz+ex6TagqMfqEwwWzb1h2BFv4Ixl1Q+LTIdQjM726zM1ErEUzhVXh8OhbFDl1p0birHlcTnziJ2niXDk28Ijn9MbkE8P5dxYSdflrh70vi7Kzze+OpG2yjfu1tqz0No/kKAcQMdLjbrSw2t9WxQczdxWKzvs35kefgR1kzqrmPxNTqQ9i3gvcO7126mznolYHRpu3bt4diEc3iubN1o5nZ+aI1/aJBVw5Hul9lcZqOpaBBkgyYNVZVjgcGoZBcs2LFCjm9WgHAYqPLR1+ekBAfVVp6Lhu9vRgLZD5lXcmXCMAmXP4iQsvZYCSWnOxOFZDEsTkiz+YXak9+ElHAoaErVsFWKmODj+f+VQ7IZKOPxLFRXnVFPpmPns4A3sLm3l5VVSWL5PIZM6ZP3rFjZzMS3wev9BNMw0e7gJkqTNLVWBv6mpqa++FJVIVsl60lvcPassMRHjoFWyEA6FO5/090+CisAWNkZKRD7ZT2TuQnkeqhSHUxbaMmT550eNu27XIAU8CeQ/CH4yG7s5lsRUjMDQY8wok+7DURj3kHNv8hdPFQAJZTAsq436DPP7N421oQrdK+bYG0VgtDvZj0/pQpU2SjIANdFY4zYiSeoXRurZkrZb8lwJMMgQXh4aH/GxsbOwUnR+h9279/8mDWkXiOfXxJkD+LOMsuvEaZcopel3quXDXEVhYhxbu5JrDh/DNAltj2HlIthCWu8hBnBivVdqJq8aODNZwG7Q0DH1ZUVMgxMb/hw4e7G3SJDX9C2s3gjBkZw6wuPCkp/TPh4QyHJh+En7c47PO82sFb1N+NpbODKxXH6h8A2If+b6Jz/zZq1KjS3r2D79uwYdO3tHF690kV2ObMTZyYXVleXrGW6T6HraMYkkQF3SHpH6CrM+lrBLvseT4+3jJ9zbs23VMWzi7QUayBRKRQfsS0HnNQrAI1l4R/l6KTqjkzch80X5bGgHyKgNjirKzMQFQVMRtNVDsLhe3Et6Na5USunHVQ0lXuP0a1dPgE7XU7MqfBRoUkI10vpqam7C0oOGMCHSkPY2NAkHEW9Dbavs2g3xEOhw3LqOfeprUhH4LZtZQw57yVK1ca586de55mfaWtnSsfFbSGAz8xqAyxaIJI4sCtGDAgZUtiYvJ4o9HwCs++Vr4zxZok+JLc8roLQclhwdxl+UKenQZbIUan4wFc0leAvoYd6QewXHoRWFKqqMnXsVERgGTNwIM93qOH/x32GiclJU5BjRzkzMldhw8ffo3wwku0sfaBbogUf/3113ybMzPh+w9Cm74uIL1/YpZUBgT4y6+E3wdoe93afE/7XF56BmyzXscNGJA6jud9p08XlAD6fQy8BwupWRW7t3+hhsRCtEOHZojTkm6vBXUjJkyYcBBVUs/O+DMEp/7GrHvarN1hPsQytueCsGIep/yp9nd5RAsXEyns4+Wlk1+N9SOZNXP6dp+tli5LthXCYwcOHDAWxvMx/CsZ+GzUizfHGqxU/V7RCX65UEC7hzl3Uo79nOPo4PV6r58Rw36PD/wU8e5BnOfYDeWzgH8AaRf7/DWSN1Issfu/8kG2xMXFcqJWKyrL39F+FG6hs5N7UXneZqkBOqKztyj1LHNPgG3qA4bGpKUN0sDAfqbuFaRoGouoF16pJQ/K8/8QKniOBx/AOEW76coLR/L4+Lh7WeS2IL1T0Zuf0mYMNJ6UtvBygvTu5Mk5l/V633/UaIzPfifEzkkypudj/HCq3BG+zOt4DGylEwaZOWjQQA368iA7GvU4RBNZ1LToSaWK5FcJ5KwiL2Qg1yIjI0abv3TkHmAjsrOzGwhz1nD/EG3ESljODFnEgaEBGo0B9SQnt5wD2BEe7NXxONgKA4A7CutFdlkOA7qRBXQkp11Nr9kw3cDmrAAUggraTi5TX/Wl02nvRge/dPDgwRbCw/lRUX0ehMgKFrxA1cQ80KDLwFZ4xxYfkZiYoMFxOLp//34/AB/IZoUc5vk5H6S5b99om1t0Co3O8tDQ3q/MmDHtGMrjv6Gp7axuV7/73lzuys5xQIbFxsYMbGlpOobzchxg/DAf+YWX1tVjBmIbj+5uQAu2qiUb6WtB/2pY6c9zsrMV0OJc+UheXvoMzDxNRkZ6GbSzAMkVcp5uK56tzEqnmFQt2RwXXsWi915VVXWfrVu3xeEgFAD+RVdHCc04gFb98V3t15H2HKNrOn78hFg1idRfimkpnqrqS/XgMjOHpfDrh6zr12v/ed++/CklJaV3lpWVG7EwDsbF9WO113TpGT7VI1bRAFe+pbCwyIcAlQ+xkg0cyGnipMHrgO6Ui6lqAeEoQSBBeyJfxth2nvOLi0s+Jeb7JFKZgdkmh8YPYQVI/Fd2V9x2bdy4SWiZ4tluI2qDECDf4mygd0VFpSE4uNcGPGGDt7ePhFq9ALpcr/dO4/dCcpxO1aVKsgH612ZAS0djkpISSUnL8dQ+4WM8z/m98adP+9WwnXY4JCQIT9LkZali6oeqjC5uRZL1SLKORXvt5Mm5unaQZXfcxBZ5P/ZmwUHzslo+VYEN8bnWOzDOGTFi+N1arebtHTvyEIzm5/AaJ7KdVjxy5IgKpt5EmFQ1i6z345nS1ta2Vvk1AQdtNIC8Oicnx5uI4ix47gDZomex31+2KLP7qBJsY79OKIrJ9cKkSbmXm5ubfpeXtzuFE6SP5eXtSurdO+Qg8ZFbqJmxnbTv8lc4WG2ckfE6d67MCMgrOXPtx2EC+bsNWyC389gpDjbHoQpsJPcCgMqKbPOC0XAfH98/TJs29fTlyzXP8nv1u69evTZ1+/YdRs7hbR4yJC1Cp/MaZpNAF7zAejIQR9EBchsgr8rNzfFHEGTzQEuyy4HgYLeSlQqqwIYX4hdG0Vd2L5geGBYW+g4btFsJuT5z7ty5ZzjKO43f3TSyS78S130IRFLtEnJjBXgC5HM6gL6FdbGa3SY5hPlzyh0CWWHlOxyUJ8dzVXqUn0dEtrW1yt9JhDnehSnqZmCci/bvP1jADzklXt0HB+YS0b3NMTF9c6Fld6fBFWsEQTayX6ktKSnll1+9VuFEBeNMzRCQ1YxD6mKN1NB2MAG1atVt1Taorj4/BQdqPe381LaF0TqDoe0t9Lk3foKEU/2JlRSwiO7j8PrdPNu00Z0BGzBNBx0xTxsx4Vamp2eE85FVhW4txtik12tnRUb23WZR7tCj6i8rVDk+wHaVcTm3IQ71cnulyvr6hj9yVGA4r2QPUMeGwa6xY8cUsRX2IBjd9osylWAD8nkkuaRBFj5+Q8M6oXUFZBkBu/7aORxR3ioPzlxOgS0doXs5u2FYDDDZznQsbZD0QzgO73HAfR50JlFkYEdn5dixWc3oUgG9Y01xBGzoGREEURd1QocfSEUB8jRn+VPaQZdjFbpHWeDPKWXO5E6DrXTGoodkGl8BmHilTG3OYFYTe9gIUC9AZwDPjZy+Woi5yP+S6ORPYbSdgS0g8/G1RUXFN/nN5Yr09MGxgMPsc+2C7jlE4t/5ZcES1yh919plsIUMYHhXV1+Y39ZmFD3s1CEWzCnZWXl7z56vKrHPX4JmOM/VnIb6gEOUOfziYBzPt7nr1dWXNDgkN3CgPsesjAfkKdRz9TrGEZi/REZGLwFw4cstl1vANueEA5BjDIbWOUiEOAcJ5u8cvL+K8fC6HMXF55DjwrIQl5PEodqEKWnSvRxw1OBaXw8MDFg+ePAQCYA5tbtDO9MFqKWIzTqdTv8ZBznzlXJ35m4H25w5gB8M8LMpuwvwhwNchw42r2fjvrCurv4N/vspFyBEf5t4HT16lAZ1UYskf8aGcgptRdervqDJoRzTEV8BeB0An1BNRGUDj4Jtzgtg9cBOz0BaRzLQkayFnDzVDqTcy7ye5T3qZVdJSfH7BQWFv+edN2plDfY5el2Ta1nX1jP9tQHsaYyew/R3CHPzEHbyMcobbbXxRHmXgW2NeQbuS6Qwlg9AyLaNQzLySwKtqAt+dSxHwsQE1PYAWAM5Z+hM/1F1B+344ar8+6URsP4/p9512lZQXs49uVc5wFaw4VEBsLT5Ya//AzDfafkdei4SAAAAAElFTkSuQmCC"
/***/ }),
/***/ "FPkq":
/*!**************************************!*\
!*** ./src/assets/images/qrCode.png ***!
\**************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/qrCode.dd0fe9b2.png";
/***/ }),
/***/ "Fm1+":
/*!*********************************************************************!*\
!*** ./node_modules/@ant-design/icons/lib/icons/CaretUpOutlined.js ***!
\*********************************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireWildcard = __webpack_require__(/*! @babel/runtime/helpers/interopRequireWildcard */ "284h");
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "TqRt");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/objectSpread2 */ "3tO9"));
var React = _interopRequireWildcard(__webpack_require__(/*! react */ "q1tI"));
var _CaretUpOutlined = _interopRequireDefault(__webpack_require__(/*! @ant-design/icons-svg/lib/asn/CaretUpOutlined */ "a7Wl"));
var _AntdIcon = _interopRequireDefault(__webpack_require__(/*! ../components/AntdIcon */ "KQxl"));
// GENERATE BY ./scripts/generate.ts
// DON NOT EDIT IT MANUALLY
var CaretUpOutlined = function CaretUpOutlined(props, ref) {
return /*#__PURE__*/React.createElement(_AntdIcon.default, (0, _objectSpread2.default)((0, _objectSpread2.default)({}, props), {}, {
ref: ref,
icon: _CaretUpOutlined.default
}));
};
CaretUpOutlined.displayName = 'CaretUpOutlined';
var _default = /*#__PURE__*/React.forwardRef(CaretUpOutlined);
exports.default = _default;
/***/ }),
/***/ "GABl":
/*!********************************************!*\
!*** ./src/assets/images/icons/chrome.png ***!
\********************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports) {
module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADQAAAA0CAYAAADFeBvrAAAKi0lEQVRoQ71ae3BU1Rn//e7dzYuioNRsHlSqRiUB2eUx0hbaKAHEAMWxiQ6PTUAUGCuIQNVOZ0xnrHUE5GHHIqOwCag8BlQiQnnUokgt5AEIK5GnBpIFXwjkAdl7vs7dkJCETXLvEj3/5d7v9/u+337nfN8554bowBHo16+3YRh3K7IPBHcRSIDI9QJ0AWkA8h0E3xM8DWAvde5x6Pqe+D17jnVUGLxWogqPp78SGSeC3wP4ZUR8pJ+Ct50O7e344uKjEXFcBkUkSERY6e43RkE9JcCgawngaiw3O6A/l7CvaHckvLYFhTKi5B8C3B2JQ6sYEhvpcMxKKioqs4ox7SwLkvT0mFNnz82HqKkCaHacRGxL1gDybHJp6WKSYoXHkqBytzuF4FoR6WOFtKNtCP4b0c7s5N27v22Pu11B5e7+6ZTgBgE6t0f2Y74n8IUjOuo+1+7dx9vy06agcrf7fgjXARLzYwZrnZsB6BzevaRkf2uYVgWdcruHKnAjRJzWHf4ElmSl5nTcnbRnT3k4b2EFVfTt29NQ8l+zKf4EIUbi4kAnhz7ohuLiH1qCwwo62cf9ccf3l0jibh1DckPy3lKzmTcbYQWV9+k7HlArOjaEjmejRm9yaWmzOMMKMncCp9x9dwlkYEeEQUCBrO0IrqYcApx1xsV6XLt2nWl43kyQqyB38dQJPZ7MY56qdLsHGIL/iY3m24R0p2jc6BDZrkVHf3XTiBFfMy9PdbSgNotCYv6kDAPGVhCTT3vz3zCNT7o9PhHJsRoIwUJN518TS0qKrWI62q4xQ/H5uTsB+Q3I0521zrcfGf/KuTMDBrguXar7or2mSuCCRm1q4t6SN5sGOGZBTQ9DsRdgJEFpQeo8pRvRJe/MYeMUMe2lYlQczl4cBki7jT78DyCVTN32qfkuRJC8Mrd3nSGNzYoa5wYm+P5kvivv43kakBdbbWTk1zqRnlBa6jdt8j4UR1Fx9WQAUyG4aqtEUIHYBWJh4ay4dQ28ciBjJiAvR5Qx8jtEOROZsuliSFBCQc4LSvBs4xogLjmjolPLH156VLKyok4ePuKHyK1XOSN/0Bz6PUlFRaXmuzELLrmNYHCVQO6wEhjBT5zReHj99LiToUwdGPIYgNesYMPE8hDTtq0JCYovyD0KkVuaGZHvnfb6xpjPTnk8o5WS91qSNC2bo+fWZiqq1RDpZDOggMPhHPHuzKi99aIy8gHx2uQwJ9t69tr2IBPfyr3TqJPPwxE4dGScGp+//XKB2CIiQ6/YcXP3faUjGjITNII7IxBTT0eeitJjB6yfyUr5MrMrLtT6IXDZFHUWaTd0Y8LKieOVEb6JkjgwOCbTvTY726j0eFINwT4RcYRi0LVfJZeUfGqumeKimgNWp1kbQX7w/pxOmaEsHRw6BaKW2BRkBjWQCQUTFylR01td9ODjgRzfq6Gp18ezSEGmEyxJ3lfaz3w2en7VNKUQen+tQ9O0ezfMiv1QjmZcj1oJQGBvl09tKl0Fuf8Rkd+1Koj4NkqPS/lq3D+/PztoUNcLF6oOQ7AweV/p8yZm5LyqveGqWSTiSK4pnB33UH2WMtZAJMsWD7HIFHRQRFLbBnLR6Rzfk6G15PFM05R2NHFf8RazzwSDqs0Dl52ACJ6PuTm229psXhJ/xjQosZl5vs/4/NxKQNpegERQd7B3xVjfIcnK0iuPHYtOLC6uHjW/dqQoo9BO0O3ZRkfpt6+bEXNY/BmZUPJ+e/bN3pM76crPrRVIdHtAkpsDXl+oqjWMUfOrpoiC/cXbhjPqWnrhU7E75NB9dyFYt6+9uFq838/4gpwfILjOCpBkZsDr+6DBduTcmomAWmYFa9VGc3DQhplxn4h/aAqU+sIqLmRHfkZXQU6ZCG63AiRZlpQa1bu4/9K6UEGYXzMESm2zgrVqQ2i3FM6JPS7+jIEwT832xi668nN2CPBbqziN2lOV3uULTPusl6uTahTKIZFuKpt7JXGm36y4hDxSiX/YI1DG61bjupyhzaag1QJkWwfyrO6MSqkYu/QbEzNqXvV2EbnXOr51S2p4o3BWJ3Nja5btAohMsMfLV80qtxCQGXaAJJcEvL5pJmb0vJpxStRKO/hwtuYunE7ds+HJ6P1yfEwXVJ+vgCDWFi8xg64Vk7JFGattAg2nw9n35NjX92etEb32qxpzn3dNWSKxvHB2p0n12RkyHYJFtmIyjXUtnT3eye1Sc16+gUC3Q0CyJCk1aqBZIB6YKzfVsdrcMSTY4WiwJbC/C+J+vWIOq0TyHPDvNI8rKba4iBpERXUNHR9cBTkfi9j/LEJqLwW8y582OR6Ye7FXHYx3gTDnpjYiM8U4o5nZeCbyD50BpRbaEmMaE1uZtn3Y5fPQxGch6gXbJKDSdW1ExfhlW0zsmAXSxQjW+ARy1X1ZS+76k6vkd5G4J8zMhKZa2ahuqKs+DPOLn91BPsK0bctCghJXTLrDUMoPiO3PJAQvApwSyFme3xDD6PmXPCJ1MwA+KCI/axqbWZpBFFJ3LDYLQNN3cnDIEgim2NWC+unmYsqmc42XEq6C3FUiEtrpRjIIzBscm/mMeXZqih+9UOIhNbeFMhBkRb/ZMV+afaalDykb3gdBowRi/0cFtcVM2xqq1FcErZyYKoZ8FkmWGoMjjwGy6MaYTsv82a9eaOuHue2DJ6KP3P/KxQYbOThkB8R6g2/i8xwcsbfyjsJQX2x50XhNWboigGcBrKam7RKRMqce+vodYwiSIOihREYAPN5wJJGDGdkQsdc6Gpxp/AtTt/2t4c9mghIKJvcU1O0VQVQk084yhjgHxKac9i45I+VZsTj3/SGI/MIyvjF6VqBrbAoTC6vDCjIfulZM/KMo9YptchsAEk8HvPkvhdbVwYznIJJnA97EVBvLXlvfblZ0whG58nPWCvCHyJy0gyKPde7WOdVcP3JkWHfUqkOAxNn2Rcxn2vbZLXFhr15vW/nEdeeNcyUArr5ctO25OUAjH6z0+tZfzs4qRFJZiU1IHTySvPoDQKt3yeb1cFDJNhHcdI0amhQk7gh4fen1YoYPhgQ/ss/NzxHtHGj2nHDYNi/Hk9/MTQka2CoiN9t3fNVkUDr0/hU5b5SK5Gnw7yyCiMcWL+GH5sxkz80nWsO1e9uftHJysqHqtoigpy3nLYxJLgt4fY+EsnMg41FAltriIzciyjm2tcy0WuXCOUnKf/xGg1VvishwW0Fc8XIhNoYpJ7J9gfpLRByGyM8tc5FzkTromXBrxlJRaM2ReW0sSi0QQTfLwZiG1P582rv876Hs+DNehpKZFvEnoWE2U7dbbrrtTrmWjhPfeqybEby0ECLjrARF8ETML9DzxD2+WikbdifqDHND2vb/PpDm5/oXcV3XRey+tsaKH1tTLhyh661H0xCsmyaQCW1dg1HTHwpMWLbmcpneBJH7Wg+QVdCwFKI/z7R/fWdHyDULaiCIL5jdScM3Y6X+m04/aXIPQGJnwJs/OCTm8yEjYSDMLSurQPkI5CrcoK2ja0vobBTpsD3l2nKU/mGe43DFiV5Ksb8SNUCj9lrlhOUl5r8JwG9evjMBhDmdjkJYBp2luLPHHrL+nq8jxv8BV2A7FHmr6w0AAAAASUVORK5CYII="
/***/ }),
/***/ "GRO8":
/*!**************************************************************!*\
!*** ./src/pages/Competitions/Detail/index.tsx + 91 modules ***!
\**************************************************************/
/*! exports provided: default */
/*! all exports used */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/CheckCircleFilled.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/CheckOutlined.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/CloseCircleFilled.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/CloseOutlined.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/DeleteOutlined.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/DownOutlined.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/DownloadOutlined.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/EyeOutlined.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/FileTwoTone.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/LeftOutlined.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/LoadingOutlined.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/PaperClipOutlined.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/PictureTwoTone.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/RedoOutlined.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/RightOutlined.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/UpOutlined.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/es/components/AntdIcon.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/assertThisInitialized.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/classCallCheck.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/createClass.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/createSuper.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/defineProperty.js (<- Module is not an ECMAScript module) */
/*! 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/defineProperty.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/getPrototypeOf.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/possibleConstructorReturn.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/extends.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/inherits.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/slicedToArray.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/toConsumableArray.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/typeof.js (<- Module is not an ECMAScript module) */
/*! 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/classCallCheck.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/createClass.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/createSuper.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/defineProperty.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/extends.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/inherits.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 ./src/.umi-production/core/umiExports.ts */
/*! ModuleConcatenation bailout: Cannot concat with ./src/components/AuthenticationModel/index.tsx */
/*! ModuleConcatenation bailout: Cannot concat with ./src/components/Header/index.tsx */
/*! ModuleConcatenation bailout: Cannot concat with ./src/components/RenderHtml/index.tsx */
/*! ModuleConcatenation bailout: Cannot concat with ./src/pages/Competitions/Entered/Enteredmodel/Addteams.tsx */
/*! ModuleConcatenation bailout: Cannot concat with ./src/pages/Competitions/Entered/Enteredmodel/JoinModel.tsx */
/*! ModuleConcatenation bailout: Cannot concat with ./src/pages/Competitions/components/ClaModal.tsx */
/*! ModuleConcatenation bailout: Cannot concat with ./src/pages/Competitions/components/PhoneModal.tsx */
/*! ModuleConcatenation bailout: Cannot concat with ./src/service/competitions.ts */
/*! ModuleConcatenation bailout: Cannot concat with ./src/utils/authority.ts */
/*! ModuleConcatenation bailout: Cannot concat with ./src/utils/env.ts */
/*! ModuleConcatenation bailout: Cannot concat with ./src/utils/fetch.ts */
/*! ModuleConcatenation bailout: Cannot concat with ./src/utils/util.tsx */
/*! ModuleConcatenation bailout: Cannot concat with ./src/utils/verifyLogin.tsx */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/ali-oss/dist/aliyun-oss-sdk.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/_util/devWarning.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/_util/hooks/useForceUpdate.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/_util/hooks/useSyncState.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/_util/reactNode.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/_util/type.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/breadcrumb/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/breadcrumb/style/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/button/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/button/style/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/carousel/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/carousel/style/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/col/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/col/style/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/config-provider/SizeContext.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/config-provider/context.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/divider/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/divider/style/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/empty/style/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/form/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/form/style/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/input/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/input/style/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/locale-provider/LocaleReceiver.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/locale/default.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/menu/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/menu/style/index.js */
/*! 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/antd/es/modal/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/modal/style/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/pagination/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/pagination/style/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/radio/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/radio/style/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/row/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/row/style/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/select/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/select/style/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/spin/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/spin/style/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/table/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/table/style/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/tabs/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/tabs/style/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/tooltip/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/tooltip/style/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/node_modules/rc-animate/es/Animate.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/array-tree-filter/lib/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/codemirror/lib/codemirror.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/crypto-js/index.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/md5/md5.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./src/pages/Competitions/Detail/component/index.less?modules (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./src/pages/Competitions/Detail/components/AppplyDepartmentModal/index.less?modules (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./src/pages/Competitions/Detail/components/AppplySchoolModal/index.less?modules (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./src/pages/Competitions/Detail/components/InitGitLink/index.less?modules (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./src/pages/Competitions/Detail/index.less?modules (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/moment/moment.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/omit.js/es/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-trigger/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/KeyCode.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/react-dom/index.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/react-router-dom/esm/react-router-dom.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/react-router/esm/react-router.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/react/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 ./node_modules/tinycolor2/tinycolor.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./src/assets/images/account/auth.png (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./src/assets/images/account/job.png (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/warning/warning.js (<- Module is not an ECMAScript module) */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// 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/regenerator/index.js
var regenerator = __webpack_require__("WmNS");
var regenerator_default = /*#__PURE__*/__webpack_require__.n(regenerator);
// EXTERNAL MODULE: ./node_modules/antd/es/modal/style/index.js
var modal_style = __webpack_require__("2qtc");
// EXTERNAL MODULE: ./node_modules/antd/es/modal/index.js + 19 modules
var es_modal = __webpack_require__("kLXV");
// EXTERNAL MODULE: ./node_modules/antd/es/menu/style/index.js
var menu_style = __webpack_require__("lUTK");
// EXTERNAL MODULE: ./node_modules/antd/es/menu/index.js + 16 modules
var menu = __webpack_require__("BvKs");
// EXTERNAL MODULE: ./node_modules/antd/es/button/style/index.js
var button_style = __webpack_require__("+L6B");
// EXTERNAL MODULE: ./node_modules/antd/es/button/index.js
var es_button = __webpack_require__("2/Rp");
// EXTERNAL MODULE: ./node_modules/antd/es/spin/style/index.js
var spin_style = __webpack_require__("T2oS");
// EXTERNAL MODULE: ./node_modules/antd/es/spin/index.js
var spin = __webpack_require__("W9HT");
// EXTERNAL MODULE: ./node_modules/antd/es/breadcrumb/style/index.js
var breadcrumb_style = __webpack_require__("sPJy");
// EXTERNAL MODULE: ./node_modules/antd/es/breadcrumb/index.js + 3 modules
var breadcrumb = __webpack_require__("bE4q");
// 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 es_message = __webpack_require__("tsqr");
// 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/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: ./node_modules/react/index.js
var react = __webpack_require__("q1tI");
var react_default = /*#__PURE__*/__webpack_require__.n(react);
// EXTERNAL MODULE: ./node_modules/react-router/esm/react-router.js
var react_router = __webpack_require__("Ty5D");
// EXTERNAL MODULE: ./node_modules/react-router-dom/esm/react-router-dom.js
var react_router_dom = __webpack_require__("55Ip");
// EXTERNAL MODULE: ./src/.umi-production/core/umiExports.ts + 19 modules
var umiExports = __webpack_require__("9kvl");
// EXTERNAL MODULE: ./src/pages/Competitions/Detail/index.less?modules
var Detailmodules = __webpack_require__("KeDT");
var Detailmodules_default = /*#__PURE__*/__webpack_require__.n(Detailmodules);
// EXTERNAL MODULE: ./src/components/AuthenticationModel/index.tsx
var AuthenticationModel = __webpack_require__("zrhs");
// EXTERNAL MODULE: ./node_modules/antd/es/style/index.less
var es_style = __webpack_require__("cIOH");
// EXTERNAL MODULE: ./node_modules/antd/es/upload/style/index.less
var upload_style = __webpack_require__("JGo8");
// EXTERNAL MODULE: ./node_modules/antd/es/progress/style/index.less
var progress_style = __webpack_require__("Kvyg");
// CONCATENATED MODULE: ./node_modules/antd/es/progress/style/index.js
// EXTERNAL MODULE: ./node_modules/antd/es/tooltip/style/index.js
var tooltip_style = __webpack_require__("5Dmo");
// CONCATENATED MODULE: ./node_modules/antd/es/upload/style/index.js
// style dependencies
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/defineProperty.js
var defineProperty = __webpack_require__("lSNA");
var defineProperty_default = /*#__PURE__*/__webpack_require__.n(defineProperty);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/toConsumableArray.js
var toConsumableArray = __webpack_require__("RIqP");
var toConsumableArray_default = /*#__PURE__*/__webpack_require__.n(toConsumableArray);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/extends.js
var helpers_extends = __webpack_require__("pVnL");
var extends_default = /*#__PURE__*/__webpack_require__.n(helpers_extends);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/slicedToArray.js
var helpers_slicedToArray = __webpack_require__("J4zp");
var slicedToArray_default = /*#__PURE__*/__webpack_require__.n(helpers_slicedToArray);
// 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-upload/es/request.js
function getError(option, xhr) {
var msg = 'cannot ' + option.method + ' ' + option.action + ' ' + xhr.status + '\'';
var err = new Error(msg);
err.status = xhr.status;
err.method = option.method;
err.url = option.action;
return err;
}
function getBody(xhr) {
var text = xhr.responseText || xhr.response;
if (!text) {
return text;
}
try {
return JSON.parse(text);
} catch (e) {
return text;
}
}
// option {
// onProgress: (event: { percent: number }): void,
// onError: (event: Error, body?: Object): void,
// onSuccess: (body: Object): void,
// data: Object,
// filename: String,
// file: File,
// withCredentials: Boolean,
// action: String,
// headers: Object,
// }
function request_upload(option) {
// eslint-disable-next-line no-undef
var xhr = new XMLHttpRequest();
if (option.onProgress && xhr.upload) {
xhr.upload.onprogress = function progress(e) {
if (e.total > 0) {
e.percent = e.loaded / e.total * 100;
}
option.onProgress(e);
};
}
// eslint-disable-next-line no-undef
var formData = new FormData();
if (option.data) {
Object.keys(option.data).forEach(function (key) {
var value = option.data[key];
// support key-value array data
if (Array.isArray(value)) {
value.forEach(function (item) {
// { list: [ 11, 22 ] }
// formData.append('list[]', 11);
formData.append(key + '[]', item);
});
return;
}
formData.append(key, option.data[key]);
});
}
// eslint-disable-next-line no-undef
if (option.file instanceof Blob) {
formData.append(option.filename, option.file, option.file.name);
} else {
formData.append(option.filename, option.file);
}
xhr.onerror = function error(e) {
option.onError(e);
};
xhr.onload = function onload() {
// allow success when 2xx status
// see https://github.com/react-component/upload/issues/34
if (xhr.status < 200 || xhr.status >= 300) {
return option.onError(getError(option, xhr), getBody(xhr));
}
return option.onSuccess(getBody(xhr), xhr);
};
xhr.open(option.method, option.action, true);
// Has to be after `.open()`. See https://github.com/enyo/dropzone/issues/179
if (option.withCredentials && 'withCredentials' in xhr) {
xhr.withCredentials = true;
}
var headers = option.headers || {};
// when set headers['X-Requested-With'] = null , can close default XHR header
// see https://github.com/react-component/upload/issues/33
if (headers['X-Requested-With'] !== null) {
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
}
Object.keys(headers).forEach(function (h) {
if (headers[h] !== null) {
xhr.setRequestHeader(h, headers[h]);
}
});
xhr.send(formData);
return {
abort: function abort() {
xhr.abort();
}
};
}
// CONCATENATED MODULE: ./node_modules/rc-upload/es/uid.js
var now = +new Date();
var uid_index = 0;
function uid_uid() {
return "rc-upload-" + now + "-" + ++uid_index;
}
// CONCATENATED MODULE: ./node_modules/rc-upload/es/attr-accept.js
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
/* harmony default export */ var attr_accept = (function (file, acceptedFiles) {
if (file && acceptedFiles) {
var acceptedFilesArray = Array.isArray(acceptedFiles) ? acceptedFiles : acceptedFiles.split(',');
var fileName = file.name || '';
var mimeType = file.type || '';
var baseMimeType = mimeType.replace(/\/.*$/, '');
return acceptedFilesArray.some(function (type) {
var validType = type.trim();
if (validType.charAt(0) === '.') {
return endsWith(fileName.toLowerCase(), validType.toLowerCase());
} else if (/\/\*$/.test(validType)) {
// This is something like a image/* mime type
return baseMimeType === validType.replace(/\/.*$/, '');
}
return mimeType === validType;
});
}
return true;
});
// CONCATENATED MODULE: ./node_modules/rc-upload/es/traverseFileTree.js
function loopFiles(item, callback) {
var dirReader = item.createReader();
var fileList = [];
function sequence() {
dirReader.readEntries(function (entries) {
var entryList = Array.prototype.slice.apply(entries);
fileList = fileList.concat(entryList);
// Check if all the file has been viewed
var isFinished = !entryList.length;
if (isFinished) {
callback(fileList);
} else {
sequence();
}
});
}
sequence();
}
var traverseFileTree = function traverseFileTree(files, callback, isAccepted) {
var _traverseFileTree = function _traverseFileTree(item, path) {
path = path || '';
if (item.isFile) {
item.file(function (file) {
if (isAccepted(file)) {
// https://github.com/ant-design/ant-design/issues/16426
if (item.fullPath && !file.webkitRelativePath) {
Object.defineProperties(file, {
webkitRelativePath: {
writable: true
}
});
file.webkitRelativePath = item.fullPath.replace(/^\//, '');
Object.defineProperties(file, {
webkitRelativePath: {
writable: false
}
});
}
callback([file]);
}
});
} else if (item.isDirectory) {
loopFiles(item, function (entries) {
entries.forEach(function (entryItem) {
_traverseFileTree(entryItem, '' + path + item.name + '/');
});
});
}
};
files.forEach(function (file) {
_traverseFileTree(file.webkitGetAsEntry());
});
};
/* harmony default export */ var es_traverseFileTree = (traverseFileTree);
// CONCATENATED MODULE: ./node_modules/rc-upload/es/AjaxUploader.js
var _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; };
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _createClass = function () { 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
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; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/* eslint react/no-is-mounted:0,react/sort-comp:0,react/prop-types:0 */
var AjaxUploader_dataOrAriaAttributeProps = function dataOrAriaAttributeProps(props) {
return Object.keys(props).reduce(function (acc, key) {
if (key.substr(0, 5) === 'data-' || key.substr(0, 5) === 'aria-' || key === 'role') {
acc[key] = props[key];
}
return acc;
}, {});
};
var AjaxUploader_AjaxUploader = function (_Component) {
_inherits(AjaxUploader, _Component);
function AjaxUploader() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, AjaxUploader);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = AjaxUploader.__proto__ || Object.getPrototypeOf(AjaxUploader)).call.apply(_ref, [this].concat(args))), _this), _this.state = { uid: uid_uid() }, _this.reqs = {}, _this.onChange = function (e) {
var files = e.target.files;
_this.uploadFiles(files);
_this.reset();
}, _this.onClick = function (e) {
var el = _this.fileInput;
if (!el) {
return;
}
var _this$props = _this.props,
children = _this$props.children,
onClick = _this$props.onClick;
if (children && children.type === 'button') {
el.parentNode.focus();
el.parentNode.querySelector('button').blur();
}
el.click();
if (onClick) {
onClick(e);
}
}, _this.onKeyDown = function (e) {
if (e.key === 'Enter') {
_this.onClick();
}
}, _this.onFileDrop = function (e) {
var multiple = _this.props.multiple;
e.preventDefault();
if (e.type === 'dragover') {
return;
}
if (_this.props.directory) {
es_traverseFileTree(Array.prototype.slice.call(e.dataTransfer.items), _this.uploadFiles, function (_file) {
return attr_accept(_file, _this.props.accept);
});
} else {
var files = Array.prototype.slice.call(e.dataTransfer.files).filter(function (file) {
return attr_accept(file, _this.props.accept);
});
if (multiple === false) {
files = files.slice(0, 1);
}
_this.uploadFiles(files);
}
}, _this.uploadFiles = function (files) {
var postFiles = Array.prototype.slice.call(files);
postFiles.map(function (file) {
file.uid = uid_uid();
return file;
}).forEach(function (file) {
_this.upload(file, postFiles);
});
}, _this.saveFileInput = function (node) {
_this.fileInput = node;
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(AjaxUploader, [{
key: 'componentDidMount',
value: function componentDidMount() {
this._isMounted = true;
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this._isMounted = false;
this.abort();
}
}, {
key: 'upload',
value: function upload(file, fileList) {
var _this2 = this;
var props = this.props;
if (!props.beforeUpload) {
// always async in case use react state to keep fileList
return setTimeout(function () {
return _this2.post(file);
}, 0);
}
var before = props.beforeUpload(file, fileList);
if (before && before.then) {
before.then(function (processedFile) {
var processedFileType = Object.prototype.toString.call(processedFile);
if (processedFileType === '[object File]' || processedFileType === '[object Blob]') {
return _this2.post(processedFile);
}
return _this2.post(file);
})['catch'](function (e) {
// eslint-disable-next-line no-console
console.log(e);
});
} else if (before !== false) {
setTimeout(function () {
return _this2.post(file);
}, 0);
}
return undefined;
}
}, {
key: 'post',
value: function post(file) {
var _this3 = this;
if (!this._isMounted) {
return;
}
var props = this.props;
var onStart = props.onStart,
onProgress = props.onProgress,
_props$transformFile = props.transformFile,
transformFile = _props$transformFile === undefined ? function (originFile) {
return originFile;
} : _props$transformFile;
new Promise(function (resolve) {
var action = props.action;
if (typeof action === 'function') {
action = action(file);
}
return resolve(action);
}).then(function (action) {
var uid = file.uid;
var request = props.customRequest || request_upload;
var transform = Promise.resolve(transformFile(file)).then(function (transformedFile) {
var data = props.data;
if (typeof data === 'function') {
data = data(transformedFile);
}
return Promise.all([transformedFile, data]);
})['catch'](function (e) {
console.error(e); // eslint-disable-line no-console
});
transform.then(function (_ref2) {
var _ref3 = _slicedToArray(_ref2, 2),
transformedFile = _ref3[0],
data = _ref3[1];
var requestOption = {
action: action,
filename: props.name,
data: data,
file: transformedFile,
headers: props.headers,
withCredentials: props.withCredentials,
method: props.method || 'post',
onProgress: onProgress ? function (e) {
onProgress(e, file);
} : null,
onSuccess: function onSuccess(ret, xhr) {
delete _this3.reqs[uid];
props.onSuccess(ret, file, xhr);
},
onError: function onError(err, ret) {
delete _this3.reqs[uid];
props.onError(err, ret, file);
}
};
onStart(file);
_this3.reqs[uid] = request(requestOption);
});
});
}
}, {
key: 'reset',
value: function reset() {
this.setState({
uid: uid_uid()
});
}
}, {
key: 'abort',
value: function abort(file) {
var reqs = this.reqs;
if (file) {
var uid = file;
if (file && file.uid) {
uid = file.uid;
}
if (reqs[uid] && reqs[uid].abort) {
reqs[uid].abort();
}
delete reqs[uid];
} else {
Object.keys(reqs).forEach(function (uid) {
if (reqs[uid] && reqs[uid].abort) {
reqs[uid].abort();
}
delete reqs[uid];
});
}
}
}, {
key: 'render',
value: function render() {
var _classNames;
var _props = this.props,
Tag = _props.component,
prefixCls = _props.prefixCls,
className = _props.className,
disabled = _props.disabled,
id = _props.id,
style = _props.style,
multiple = _props.multiple,
accept = _props.accept,
children = _props.children,
directory = _props.directory,
openFileDialogOnClick = _props.openFileDialogOnClick,
onMouseEnter = _props.onMouseEnter,
onMouseLeave = _props.onMouseLeave,
otherProps = _objectWithoutProperties(_props, ['component', 'prefixCls', 'className', 'disabled', 'id', 'style', 'multiple', 'accept', 'children', 'directory', 'openFileDialogOnClick', 'onMouseEnter', 'onMouseLeave']);
var cls = classnames_default()((_classNames = {}, _defineProperty(_classNames, prefixCls, true), _defineProperty(_classNames, prefixCls + '-disabled', disabled), _defineProperty(_classNames, className, className), _classNames));
var events = disabled ? {} : {
onClick: openFileDialogOnClick ? this.onClick : function () {},
onKeyDown: openFileDialogOnClick ? this.onKeyDown : function () {},
onMouseEnter: onMouseEnter,
onMouseLeave: onMouseLeave,
onDrop: this.onFileDrop,
onDragOver: this.onFileDrop,
tabIndex: '0'
};
return react_default.a.createElement(
Tag,
_extends({}, events, {
className: cls,
role: 'button',
style: style
}),
react_default.a.createElement('input', _extends({}, AjaxUploader_dataOrAriaAttributeProps(otherProps), {
id: id,
type: 'file',
ref: this.saveFileInput,
onClick: function onClick(e) {
return e.stopPropagation();
} // https://github.com/ant-design/ant-design/issues/19948
, key: this.state.uid,
style: { display: 'none' },
accept: accept,
directory: directory ? 'directory' : null,
webkitdirectory: directory ? 'webkitdirectory' : null,
multiple: multiple,
onChange: this.onChange
})),
children
);
}
}]);
return AjaxUploader;
}(react["Component"]);
/* harmony default export */ var es_AjaxUploader = (AjaxUploader_AjaxUploader);
// CONCATENATED MODULE: ./node_modules/rc-upload/es/Upload.js
var Upload_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; };
var Upload_createClass = function () { 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function Upload_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function Upload_possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function Upload_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/* eslint react/prop-types:0 */
function empty() {}
var Upload_Upload = function (_Component) {
Upload_inherits(Upload, _Component);
function Upload() {
var _ref;
var _temp, _this, _ret;
Upload_classCallCheck(this, Upload);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = Upload_possibleConstructorReturn(this, (_ref = Upload.__proto__ || Object.getPrototypeOf(Upload)).call.apply(_ref, [this].concat(args))), _this), _this.saveUploader = function (node) {
_this.uploader = node;
}, _temp), Upload_possibleConstructorReturn(_this, _ret);
}
Upload_createClass(Upload, [{
key: 'abort',
value: function abort(file) {
this.uploader.abort(file);
}
}, {
key: 'render',
value: function render() {
return react_default.a.createElement(es_AjaxUploader, Upload_extends({}, this.props, { ref: this.saveUploader }));
}
}]);
return Upload;
}(react["Component"]);
Upload_Upload.defaultProps = {
component: 'span',
prefixCls: 'rc-upload',
data: {},
headers: {},
name: 'file',
multipart: false,
onStart: empty,
onError: empty,
onSuccess: empty,
multiple: false,
beforeUpload: null,
customRequest: null,
withCredentials: false,
openFileDialogOnClick: true
};
/* harmony default export */ var es_Upload = (Upload_Upload);
// CONCATENATED MODULE: ./node_modules/rc-upload/es/index.js
// export this package's api
/* harmony default export */ var es = (es_Upload);
// CONCATENATED MODULE: ./node_modules/antd/es/upload/Dragger.js
var __rest = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
var Dragger_InternalDragger = function InternalDragger(_a, ref) {
var style = _a.style,
height = _a.height,
restProps = __rest(_a, ["style", "height"]);
return /*#__PURE__*/react["createElement"](upload_Upload, extends_default()({
ref: ref
}, restProps, {
type: "drag",
style: extends_default()(extends_default()({}, style), {
height: height
})
}));
};
var Dragger = /*#__PURE__*/react["forwardRef"](Dragger_InternalDragger);
Dragger.displayName = 'Dragger';
/* harmony default export */ var upload_Dragger = (Dragger);
// EXTERNAL MODULE: ./node_modules/antd/node_modules/rc-animate/es/Animate.js + 4 modules
var Animate = __webpack_require__("UmKh");
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/LoadingOutlined.js
var LoadingOutlined = __webpack_require__("gZBC");
var LoadingOutlined_default = /*#__PURE__*/__webpack_require__.n(LoadingOutlined);
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/PaperClipOutlined.js
var PaperClipOutlined = __webpack_require__("+d4F");
var PaperClipOutlined_default = /*#__PURE__*/__webpack_require__.n(PaperClipOutlined);
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/PictureTwoTone.js
var PictureTwoTone = __webpack_require__("XAae");
var PictureTwoTone_default = /*#__PURE__*/__webpack_require__.n(PictureTwoTone);
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/FileTwoTone.js
var FileTwoTone = __webpack_require__("6xvX");
var FileTwoTone_default = /*#__PURE__*/__webpack_require__.n(FileTwoTone);
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/EyeOutlined.js
var EyeOutlined = __webpack_require__("qPY4");
var EyeOutlined_default = /*#__PURE__*/__webpack_require__.n(EyeOutlined);
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/DeleteOutlined.js
var DeleteOutlined = __webpack_require__("QB+1");
var DeleteOutlined_default = /*#__PURE__*/__webpack_require__.n(DeleteOutlined);
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/DownloadOutlined.js
var DownloadOutlined = __webpack_require__("Qs3X");
var DownloadOutlined_default = /*#__PURE__*/__webpack_require__.n(DownloadOutlined);
// EXTERNAL MODULE: ./node_modules/antd/es/_util/reactNode.js
var reactNode = __webpack_require__("0n0R");
// CONCATENATED MODULE: ./node_modules/antd/es/upload/utils.js
function T() {
return true;
} // Fix IE file.status problem
// via coping a new Object
function fileToObject(file) {
return extends_default()(extends_default()({}, file), {
lastModified: file.lastModified,
lastModifiedDate: file.lastModifiedDate,
name: file.name,
size: file.size,
type: file.type,
uid: file.uid,
percent: 0,
originFileObj: file
});
}
function getFileItem(file, fileList) {
var matchKey = file.uid !== undefined ? 'uid' : 'name';
return fileList.filter(function (item) {
return item[matchKey] === file[matchKey];
})[0];
}
function removeFileItem(file, fileList) {
var matchKey = file.uid !== undefined ? 'uid' : 'name';
var removed = fileList.filter(function (item) {
return item[matchKey] !== file[matchKey];
});
if (removed.length === fileList.length) {
return null;
}
return removed;
} // ==================== Default Image Preview ====================
var extname = function extname() {
var url = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var temp = url.split('/');
var filename = temp[temp.length - 1];
var filenameWithoutSuffix = filename.split(/#|\?/)[0];
return (/\.[^./\\]*$/.exec(filenameWithoutSuffix) || [''])[0];
};
var isImageFileType = function isImageFileType(type) {
return type.indexOf('image/') === 0;
};
var utils_isImageUrl = function isImageUrl(file) {
if (file.type && !file.thumbUrl) {
return isImageFileType(file.type);
}
var url = file.thumbUrl || file.url;
var extension = extname(url);
if (/^data:image\//.test(url) || /(webp|svg|png|gif|jpg|jpeg|jfif|bmp|dpg|ico)$/i.test(extension)) {
return true;
}
if (/^data:/.test(url)) {
// other file types of base64
return false;
}
if (extension) {
// other file types which have extension
return false;
}
return true;
};
var MEASURE_SIZE = 200;
function previewImage(file) {
return new Promise(function (resolve) {
if (!file.type || !isImageFileType(file.type)) {
resolve('');
return;
}
var canvas = document.createElement('canvas');
canvas.width = MEASURE_SIZE;
canvas.height = MEASURE_SIZE;
canvas.style.cssText = "position: fixed; left: 0; top: 0; width: ".concat(MEASURE_SIZE, "px; height: ").concat(MEASURE_SIZE, "px; z-index: 9999; display: none;");
document.body.appendChild(canvas);
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function () {
var width = img.width,
height = img.height;
var drawWidth = MEASURE_SIZE;
var drawHeight = MEASURE_SIZE;
var offsetX = 0;
var offsetY = 0;
if (width < height) {
drawHeight = height * (MEASURE_SIZE / width);
offsetY = -(drawHeight - drawWidth) / 2;
} else {
drawWidth = width * (MEASURE_SIZE / height);
offsetX = -(drawWidth - drawHeight) / 2;
}
ctx.drawImage(img, offsetX, offsetY, drawWidth, drawHeight);
var dataURL = canvas.toDataURL();
document.body.removeChild(canvas);
resolve(dataURL);
};
img.src = window.URL.createObjectURL(file);
});
}
// EXTERNAL MODULE: ./node_modules/antd/es/tooltip/index.js + 5 modules
var tooltip = __webpack_require__("3S7+");
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/classCallCheck.js
var classCallCheck = __webpack_require__("lwsE");
var classCallCheck_default = /*#__PURE__*/__webpack_require__.n(classCallCheck);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/createClass.js
var createClass = __webpack_require__("W8MJ");
var createClass_default = /*#__PURE__*/__webpack_require__.n(createClass);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/assertThisInitialized.js
var assertThisInitialized = __webpack_require__("PJYZ");
var assertThisInitialized_default = /*#__PURE__*/__webpack_require__.n(assertThisInitialized);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/inherits.js
var inherits = __webpack_require__("7W2i");
var inherits_default = /*#__PURE__*/__webpack_require__.n(inherits);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/createSuper.js
var createSuper = __webpack_require__("LQ03");
var createSuper_default = /*#__PURE__*/__webpack_require__.n(createSuper);
// EXTERNAL MODULE: ./node_modules/omit.js/es/index.js
var omit_js_es = __webpack_require__("BGR+");
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/CloseOutlined.js
var CloseOutlined = __webpack_require__("V/uB");
var CloseOutlined_default = /*#__PURE__*/__webpack_require__.n(CloseOutlined);
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/CheckOutlined.js
var CheckOutlined = __webpack_require__("NAnI");
var CheckOutlined_default = /*#__PURE__*/__webpack_require__.n(CheckOutlined);
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/CheckCircleFilled.js
var icons_CheckCircleFilled = __webpack_require__("J84W");
var CheckCircleFilled_default = /*#__PURE__*/__webpack_require__.n(icons_CheckCircleFilled);
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/CloseCircleFilled.js
var icons_CloseCircleFilled = __webpack_require__("kbBi");
var CloseCircleFilled_default = /*#__PURE__*/__webpack_require__.n(icons_CloseCircleFilled);
// EXTERNAL MODULE: ./node_modules/antd/es/config-provider/context.js + 1 modules
var context = __webpack_require__("H84U");
// EXTERNAL MODULE: ./node_modules/antd/es/_util/type.js
var _util_type = __webpack_require__("CWQg");
// EXTERNAL MODULE: ./node_modules/antd/es/_util/devWarning.js
var devWarning = __webpack_require__("uaoM");
// EXTERNAL MODULE: ./node_modules/tinycolor2/tinycolor.js
var tinycolor = __webpack_require__("Zss7");
var tinycolor_default = /*#__PURE__*/__webpack_require__.n(tinycolor);
// CONCATENATED MODULE: ./node_modules/@ant-design/colors/dist/index.esm.js
var hueStep = 2; // 色相阶梯
var saturationStep = 0.16; // 饱和度阶梯,浅色部分
var saturationStep2 = 0.05; // 饱和度阶梯,深色部分
var brightnessStep1 = 0.05; // 亮度阶梯,浅色部分
var brightnessStep2 = 0.15; // 亮度阶梯,深色部分
var lightColorCount = 5; // 浅色数量,主色上
var darkColorCount = 4; // 深色数量,主色下
// 暗色主题颜色映射关系表
var darkColorMap = [{
index: 7,
opacity: 0.15
}, {
index: 6,
opacity: 0.25
}, {
index: 5,
opacity: 0.3
}, {
index: 5,
opacity: 0.45
}, {
index: 5,
opacity: 0.65
}, {
index: 5,
opacity: 0.85
}, {
index: 4,
opacity: 0.9
}, {
index: 3,
opacity: 0.95
}, {
index: 2,
opacity: 0.97
}, {
index: 1,
opacity: 0.98
}];
function getHue(hsv, i, light) {
var hue; // 根据色相不同,色相转向不同
if (Math.round(hsv.h) >= 60 && Math.round(hsv.h) <= 240) {
hue = light ? Math.round(hsv.h) - hueStep * i : Math.round(hsv.h) + hueStep * i;
} else {
hue = light ? Math.round(hsv.h) + hueStep * i : Math.round(hsv.h) - hueStep * i;
}
if (hue < 0) {
hue += 360;
} else if (hue >= 360) {
hue -= 360;
}
return hue;
}
function getSaturation(hsv, i, light) {
// grey color don't change saturation
if (hsv.h === 0 && hsv.s === 0) {
return hsv.s;
}
var saturation;
if (light) {
saturation = hsv.s - saturationStep * i;
} else if (i === darkColorCount) {
saturation = hsv.s + saturationStep;
} else {
saturation = hsv.s + saturationStep2 * i;
} // 边界值修正
if (saturation > 1) {
saturation = 1;
} // 第一格的 s 限制在 0.06-0.1 之间
if (light && i === lightColorCount && saturation > 0.1) {
saturation = 0.1;
}
if (saturation < 0.06) {
saturation = 0.06;
}
return Number(saturation.toFixed(2));
}
function getValue(hsv, i, light) {
var value;
if (light) {
value = hsv.v + brightnessStep1 * i;
} else {
value = hsv.v - brightnessStep2 * i;
}
if (value > 1) {
value = 1;
}
return Number(value.toFixed(2));
}
function generate(color) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var patterns = [];
var pColor = tinycolor_default()(color);
for (var i = lightColorCount; i > 0; i -= 1) {
var hsv = pColor.toHsv();
var colorString = tinycolor_default()({
h: getHue(hsv, i, true),
s: getSaturation(hsv, i, true),
v: getValue(hsv, i, true)
}).toHexString();
patterns.push(colorString);
}
patterns.push(pColor.toHexString());
for (var _i = 1; _i <= darkColorCount; _i += 1) {
var _hsv = pColor.toHsv();
var _colorString = tinycolor_default()({
h: getHue(_hsv, _i),
s: getSaturation(_hsv, _i),
v: getValue(_hsv, _i)
}).toHexString();
patterns.push(_colorString);
} // dark theme patterns
if (opts.theme === 'dark') {
return darkColorMap.map(function (_ref) {
var index = _ref.index,
opacity = _ref.opacity;
var darkColorString = tinycolor_default.a.mix(opts.backgroundColor || '#141414', patterns[index], opacity * 100).toHexString();
return darkColorString;
});
}
return patterns;
}
var presetPrimaryColors = {
red: '#F5222D',
volcano: '#FA541C',
orange: '#FA8C16',
gold: '#FAAD14',
yellow: '#FADB14',
lime: '#A0D911',
green: '#52C41A',
cyan: '#13C2C2',
blue: '#1890FF',
geekblue: '#2F54EB',
purple: '#722ED1',
magenta: '#EB2F96',
grey: '#666666'
};
var presetPalettes = {};
var presetDarkPalettes = {};
Object.keys(presetPrimaryColors).forEach(function (key) {
presetPalettes[key] = generate(presetPrimaryColors[key]);
presetPalettes[key].primary = presetPalettes[key][5]; // dark presetPalettes
presetDarkPalettes[key] = generate(presetPrimaryColors[key], {
theme: 'dark',
backgroundColor: '#141414'
});
presetDarkPalettes[key].primary = presetDarkPalettes[key][5];
});
var red = presetPalettes.red;
var volcano = presetPalettes.volcano;
var gold = presetPalettes.gold;
var orange = presetPalettes.orange;
var yellow = presetPalettes.yellow;
var lime = presetPalettes.lime;
var green = presetPalettes.green;
var cyan = presetPalettes.cyan;
var blue = presetPalettes.blue;
var geekblue = presetPalettes.geekblue;
var purple = presetPalettes.purple;
var magenta = presetPalettes.magenta;
var grey = presetPalettes.grey;
// CONCATENATED MODULE: ./node_modules/antd/es/progress/utils.js
function validProgress(progress) {
if (!progress || progress < 0) {
return 0;
}
if (progress > 100) {
return 100;
}
return progress;
}
function getSuccessPercent(_ref) {
var success = _ref.success,
successPercent = _ref.successPercent;
var percent = successPercent;
/** @deprecated Use `percent` instead */
if (success && 'progress' in success) {
Object(devWarning["a" /* default */])(false, 'Progress', '`success.progress` is deprecated. Please use `success.percent` instead.');
percent = success.progress;
}
if (success && 'percent' in success) {
percent = success.percent;
}
return percent;
}
// CONCATENATED MODULE: ./node_modules/antd/es/progress/Line.js
var Line_rest = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
/**
* {
* '0%': '#afc163',
* '75%': '#009900',
* '50%': 'green', ====> '#afc163 0%, #66FF00 25%, #00CC00 50%, #009900 75%, #ffffff 100%'
* '25%': '#66FF00',
* '100%': '#ffffff'
* }
*/
var sortGradient = function sortGradient(gradients) {
var tempArr = [];
Object.keys(gradients).forEach(function (key) {
var formattedKey = parseFloat(key.replace(/%/g, ''));
if (!isNaN(formattedKey)) {
tempArr.push({
key: formattedKey,
value: gradients[key]
});
}
});
tempArr = tempArr.sort(function (a, b) {
return a.key - b.key;
});
return tempArr.map(function (_ref) {
var key = _ref.key,
value = _ref.value;
return "".concat(value, " ").concat(key, "%");
}).join(', ');
};
/**
* {
* '0%': '#afc163',
* '25%': '#66FF00',
* '50%': '#00CC00', ====> linear-gradient(to right, #afc163 0%, #66FF00 25%,
* '75%': '#009900', #00CC00 50%, #009900 75%, #ffffff 100%)
* '100%': '#ffffff'
* }
*
* Then this man came to realize the truth:
* Besides six pence, there is the moon.
* Besides bread and butter, there is the bug.
* And...
* Besides women, there is the code.
*/
var Line_handleGradient = function handleGradient(strokeColor) {
var _strokeColor$from = strokeColor.from,
from = _strokeColor$from === void 0 ? presetPrimaryColors.blue : _strokeColor$from,
_strokeColor$to = strokeColor.to,
to = _strokeColor$to === void 0 ? presetPrimaryColors.blue : _strokeColor$to,
_strokeColor$directio = strokeColor.direction,
direction = _strokeColor$directio === void 0 ? 'to right' : _strokeColor$directio,
rest = Line_rest(strokeColor, ["from", "to", "direction"]);
if (Object.keys(rest).length !== 0) {
var sortedGradients = sortGradient(rest);
return {
backgroundImage: "linear-gradient(".concat(direction, ", ").concat(sortedGradients, ")")
};
}
return {
backgroundImage: "linear-gradient(".concat(direction, ", ").concat(from, ", ").concat(to, ")")
};
};
var Line_Line = function Line(props) {
var prefixCls = props.prefixCls,
percent = props.percent,
strokeWidth = props.strokeWidth,
size = props.size,
strokeColor = props.strokeColor,
strokeLinecap = props.strokeLinecap,
children = props.children,
trailColor = props.trailColor,
success = props.success;
var backgroundProps = strokeColor && typeof strokeColor !== 'string' ? Line_handleGradient(strokeColor) : {
background: strokeColor
};
var trailStyle = trailColor ? {
backgroundColor: trailColor
} : undefined;
var percentStyle = extends_default()({
width: "".concat(validProgress(percent), "%"),
height: strokeWidth || (size === 'small' ? 6 : 8),
borderRadius: strokeLinecap === 'square' ? 0 : ''
}, backgroundProps);
var successPercent = getSuccessPercent(props);
var successPercentStyle = {
width: "".concat(validProgress(successPercent), "%"),
height: strokeWidth || (size === 'small' ? 6 : 8),
borderRadius: strokeLinecap === 'square' ? 0 : '',
backgroundColor: success === null || success === void 0 ? void 0 : success.strokeColor
};
var successSegment = successPercent !== undefined ? /*#__PURE__*/react["createElement"]("div", {
className: "".concat(prefixCls, "-success-bg"),
style: successPercentStyle
}) : null;
return /*#__PURE__*/react["createElement"](react["Fragment"], null, /*#__PURE__*/react["createElement"]("div", {
className: "".concat(prefixCls, "-outer")
}, /*#__PURE__*/react["createElement"]("div", {
className: "".concat(prefixCls, "-inner"),
style: trailStyle
}, /*#__PURE__*/react["createElement"]("div", {
className: "".concat(prefixCls, "-bg"),
style: percentStyle
}), successSegment)), children);
};
/* harmony default export */ var progress_Line = (Line_Line);
// CONCATENATED MODULE: ./node_modules/rc-progress/es/common.js
var defaultProps = {
className: '',
percent: 0,
prefixCls: 'rc-progress',
strokeColor: '#2db7f5',
strokeLinecap: 'round',
strokeWidth: 1,
style: {},
trailColor: '#D9D9D9',
trailWidth: 1
};
var common_useTransitionDuration = function useTransitionDuration(percentList) {
var paths = percentList.map(function () {
return Object(react["useRef"])();
});
var prevTimeStamp = Object(react["useRef"])();
Object(react["useEffect"])(function () {
var now = Date.now();
var updated = false;
Object.keys(paths).forEach(function (key) {
var path = paths[key].current;
if (!path) {
return;
}
updated = true;
var pathStyle = path.style;
pathStyle.transitionDuration = '.3s, .3s, .3s, .06s';
if (prevTimeStamp.current && now - prevTimeStamp.current < 100) {
pathStyle.transitionDuration = '0s, 0s';
}
});
if (updated) {
prevTimeStamp.current = Date.now();
}
});
return [paths];
};
// CONCATENATED MODULE: ./node_modules/rc-progress/es/Line.js
function Line_extends() { Line_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 Line_extends.apply(this, arguments); }
function Line_slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure 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 _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function Line_objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
/* eslint react/prop-types: 0 */
var es_Line_Line = function Line(_ref) {
var className = _ref.className,
percent = _ref.percent,
prefixCls = _ref.prefixCls,
strokeColor = _ref.strokeColor,
strokeLinecap = _ref.strokeLinecap,
strokeWidth = _ref.strokeWidth,
style = _ref.style,
trailColor = _ref.trailColor,
trailWidth = _ref.trailWidth,
transition = _ref.transition,
restProps = Line_objectWithoutProperties(_ref, ["className", "percent", "prefixCls", "strokeColor", "strokeLinecap", "strokeWidth", "style", "trailColor", "trailWidth", "transition"]);
delete restProps.gapPosition;
var percentList = Array.isArray(percent) ? percent : [percent];
var strokeColorList = Array.isArray(strokeColor) ? strokeColor : [strokeColor];
var _useTransitionDuratio = common_useTransitionDuration(percentList),
_useTransitionDuratio2 = Line_slicedToArray(_useTransitionDuratio, 1),
paths = _useTransitionDuratio2[0];
var center = strokeWidth / 2;
var right = 100 - strokeWidth / 2;
var pathString = "M ".concat(strokeLinecap === 'round' ? center : 0, ",").concat(center, "\n L ").concat(strokeLinecap === 'round' ? right : 100, ",").concat(center);
var viewBoxString = "0 0 100 ".concat(strokeWidth);
var stackPtg = 0;
return /*#__PURE__*/react_default.a.createElement("svg", Line_extends({
className: classnames_default()("".concat(prefixCls, "-line"), className),
viewBox: viewBoxString,
preserveAspectRatio: "none",
style: style
}, restProps), /*#__PURE__*/react_default.a.createElement("path", {
className: "".concat(prefixCls, "-line-trail"),
d: pathString,
strokeLinecap: strokeLinecap,
stroke: trailColor,
strokeWidth: trailWidth || strokeWidth,
fillOpacity: "0"
}), percentList.map(function (ptg, index) {
var pathStyle = {
strokeDasharray: "".concat(ptg, "px, 100px"),
strokeDashoffset: "-".concat(stackPtg, "px"),
transition: transition || 'stroke-dashoffset 0.3s ease 0s, stroke-dasharray .3s ease 0s, stroke 0.3s linear'
};
var color = strokeColorList[index] || strokeColorList[strokeColorList.length - 1];
stackPtg += ptg;
return /*#__PURE__*/react_default.a.createElement("path", {
key: index,
className: "".concat(prefixCls, "-line-path"),
d: pathString,
strokeLinecap: strokeLinecap,
stroke: color,
strokeWidth: strokeWidth,
fillOpacity: "0",
ref: paths[index],
style: pathStyle
});
}));
};
es_Line_Line.defaultProps = defaultProps;
/* harmony default export */ var es_Line = (es_Line_Line);
// CONCATENATED MODULE: ./node_modules/rc-progress/es/Circle.js
function Circle_extends() { Circle_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 Circle_extends.apply(this, arguments); }
function Circle_slicedToArray(arr, i) { return Circle_arrayWithHoles(arr) || Circle_iterableToArrayLimit(arr, i) || Circle_unsupportedIterableToArray(arr, i) || Circle_nonIterableRest(); }
function Circle_nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function Circle_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return Circle_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 Circle_arrayLikeToArray(o, minLen); }
function Circle_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 Circle_iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function Circle_arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function Circle_objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = Circle_objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function Circle_objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
/* eslint react/prop-types: 0 */
var gradientSeed = 0;
function stripPercentToNumber(percent) {
return +percent.replace('%', '');
}
function toArray(symArray) {
return Array.isArray(symArray) ? symArray : [symArray];
}
function getPathStyles(offset, percent, strokeColor, strokeWidth) {
var gapDegree = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;
var gapPosition = arguments.length > 5 ? arguments[5] : undefined;
var radius = 50 - strokeWidth / 2;
var beginPositionX = 0;
var beginPositionY = -radius;
var endPositionX = 0;
var endPositionY = -2 * radius;
switch (gapPosition) {
case 'left':
beginPositionX = -radius;
beginPositionY = 0;
endPositionX = 2 * radius;
endPositionY = 0;
break;
case 'right':
beginPositionX = radius;
beginPositionY = 0;
endPositionX = -2 * radius;
endPositionY = 0;
break;
case 'bottom':
beginPositionY = radius;
endPositionY = 2 * radius;
break;
default:
}
var pathString = "M 50,50 m ".concat(beginPositionX, ",").concat(beginPositionY, "\n a ").concat(radius, ",").concat(radius, " 0 1 1 ").concat(endPositionX, ",").concat(-endPositionY, "\n a ").concat(radius, ",").concat(radius, " 0 1 1 ").concat(-endPositionX, ",").concat(endPositionY);
var len = Math.PI * 2 * radius;
var pathStyle = {
stroke: strokeColor,
strokeDasharray: "".concat(percent / 100 * (len - gapDegree), "px ").concat(len, "px"),
strokeDashoffset: "-".concat(gapDegree / 2 + offset / 100 * (len - gapDegree), "px"),
transition: 'stroke-dashoffset .3s ease 0s, stroke-dasharray .3s ease 0s, stroke .3s, stroke-width .06s ease .3s' // eslint-disable-line
};
return {
pathString: pathString,
pathStyle: pathStyle
};
}
var Circle_Circle = function Circle(_ref) {
var prefixCls = _ref.prefixCls,
strokeWidth = _ref.strokeWidth,
trailWidth = _ref.trailWidth,
gapDegree = _ref.gapDegree,
gapPosition = _ref.gapPosition,
trailColor = _ref.trailColor,
strokeLinecap = _ref.strokeLinecap,
style = _ref.style,
className = _ref.className,
strokeColor = _ref.strokeColor,
percent = _ref.percent,
restProps = Circle_objectWithoutProperties(_ref, ["prefixCls", "strokeWidth", "trailWidth", "gapDegree", "gapPosition", "trailColor", "strokeLinecap", "style", "className", "strokeColor", "percent"]);
var gradientId = Object(react["useMemo"])(function () {
gradientSeed += 1;
return gradientSeed;
}, []);
var _getPathStyles = getPathStyles(0, 100, trailColor, strokeWidth, gapDegree, gapPosition),
pathString = _getPathStyles.pathString,
pathStyle = _getPathStyles.pathStyle;
var percentList = toArray(percent);
var strokeColorList = toArray(strokeColor);
var gradient = strokeColorList.find(function (color) {
return Object.prototype.toString.call(color) === '[object Object]';
});
var _useTransitionDuratio = common_useTransitionDuration(percentList),
_useTransitionDuratio2 = Circle_slicedToArray(_useTransitionDuratio, 1),
paths = _useTransitionDuratio2[0];
var getStokeList = function getStokeList() {
var stackPtg = 0;
return percentList.map(function (ptg, index) {
var color = strokeColorList[index] || strokeColorList[strokeColorList.length - 1];
var stroke = Object.prototype.toString.call(color) === '[object Object]' ? "url(#".concat(prefixCls, "-gradient-").concat(gradientId, ")") : '';
var pathStyles = getPathStyles(stackPtg, ptg, color, strokeWidth, gapDegree, gapPosition);
stackPtg += ptg;
return /*#__PURE__*/react_default.a.createElement("path", {
key: index,
className: "".concat(prefixCls, "-circle-path"),
d: pathStyles.pathString,
stroke: stroke,
strokeLinecap: strokeLinecap,
strokeWidth: strokeWidth,
opacity: ptg === 0 ? 0 : 1,
fillOpacity: "0",
style: pathStyles.pathStyle,
ref: paths[index]
});
});
};
return /*#__PURE__*/react_default.a.createElement("svg", Circle_extends({
className: classnames_default()("".concat(prefixCls, "-circle"), className),
viewBox: "0 0 100 100",
style: style
}, restProps), gradient && /*#__PURE__*/react_default.a.createElement("defs", null, /*#__PURE__*/react_default.a.createElement("linearGradient", {
id: "".concat(prefixCls, "-gradient-").concat(gradientId),
x1: "100%",
y1: "0%",
x2: "0%",
y2: "0%"
}, Object.keys(gradient).sort(function (a, b) {
return stripPercentToNumber(a) - stripPercentToNumber(b);
}).map(function (key, index) {
return /*#__PURE__*/react_default.a.createElement("stop", {
key: index,
offset: key,
stopColor: gradient[key]
});
}))), /*#__PURE__*/react_default.a.createElement("path", {
className: "".concat(prefixCls, "-circle-trail"),
d: pathString,
stroke: trailColor,
strokeLinecap: strokeLinecap,
strokeWidth: trailWidth || strokeWidth,
fillOpacity: "0",
style: pathStyle
}), getStokeList().reverse());
};
Circle_Circle.defaultProps = defaultProps;
/* harmony default export */ var es_Circle = (Circle_Circle);
// CONCATENATED MODULE: ./node_modules/rc-progress/es/index.js
/* harmony default export */ var rc_progress_es = ({
Line: es_Line,
Circle: es_Circle
});
// CONCATENATED MODULE: ./node_modules/antd/es/progress/Circle.js
function getPercentage(_ref) {
var percent = _ref.percent,
success = _ref.success,
successPercent = _ref.successPercent;
var ptg = validProgress(percent);
var realSuccessPercent = getSuccessPercent({
success: success,
successPercent: successPercent
});
if (!realSuccessPercent) {
return ptg;
}
return [validProgress(realSuccessPercent), validProgress(ptg - validProgress(realSuccessPercent))];
}
function getStrokeColor(_ref2) {
var success = _ref2.success,
strokeColor = _ref2.strokeColor,
successPercent = _ref2.successPercent;
var color = strokeColor || null;
var realSuccessPercent = getSuccessPercent({
success: success,
successPercent: successPercent
});
if (!realSuccessPercent) {
return color;
}
return [presetPrimaryColors.green, color];
}
var progress_Circle_Circle = function Circle(props) {
var prefixCls = props.prefixCls,
width = props.width,
strokeWidth = props.strokeWidth,
trailColor = props.trailColor,
strokeLinecap = props.strokeLinecap,
gapPosition = props.gapPosition,
gapDegree = props.gapDegree,
type = props.type,
children = props.children;
var circleSize = width || 120;
var circleStyle = {
width: circleSize,
height: circleSize,
fontSize: circleSize * 0.15 + 6
};
var circleWidth = strokeWidth || 6;
var gapPos = gapPosition || type === 'dashboard' && 'bottom' || 'top';
var getGapDegree = function getGapDegree() {
// Support gapDeg = 0 when type = 'dashboard'
if (gapDegree || gapDegree === 0) {
return gapDegree;
}
if (type === 'dashboard') {
return 75;
}
return undefined;
}; // using className to style stroke color
var strokeColor = getStrokeColor(props);
var isGradient = Object.prototype.toString.call(strokeColor) === '[object Object]';
var wrapperClassName = classnames_default()("".concat(prefixCls, "-inner"), defineProperty_default()({}, "".concat(prefixCls, "-circle-gradient"), isGradient));
return /*#__PURE__*/react["createElement"]("div", {
className: wrapperClassName,
style: circleStyle
}, /*#__PURE__*/react["createElement"](es_Circle, {
percent: getPercentage(props),
strokeWidth: circleWidth,
trailWidth: circleWidth,
strokeColor: strokeColor,
strokeLinecap: strokeLinecap,
trailColor: trailColor,
prefixCls: prefixCls,
gapDegree: getGapDegree(),
gapPosition: gapPos
}), children);
};
/* harmony default export */ var progress_Circle = (progress_Circle_Circle);
// CONCATENATED MODULE: ./node_modules/antd/es/progress/Steps.js
var Steps_Steps = function Steps(props) {
var size = props.size,
steps = props.steps,
_props$percent = props.percent,
percent = _props$percent === void 0 ? 0 : _props$percent,
_props$strokeWidth = props.strokeWidth,
strokeWidth = _props$strokeWidth === void 0 ? 8 : _props$strokeWidth,
strokeColor = props.strokeColor,
trailColor = props.trailColor,
prefixCls = props.prefixCls,
children = props.children;
var current = Math.floor(steps * (percent / 100));
var stepWidth = size === 'small' ? 2 : 14;
var styledSteps = [];
for (var i = 0; i < steps; i += 1) {
styledSteps.push( /*#__PURE__*/react["createElement"]("div", {
key: i,
className: classnames_default()("".concat(prefixCls, "-steps-item"), defineProperty_default()({}, "".concat(prefixCls, "-steps-item-active"), i <= current - 1)),
style: {
backgroundColor: i <= current - 1 ? strokeColor : trailColor,
width: stepWidth,
height: strokeWidth
}
}));
}
return /*#__PURE__*/react["createElement"]("div", {
className: "".concat(prefixCls, "-steps-outer")
}, styledSteps, children);
};
/* harmony default export */ var progress_Steps = (Steps_Steps);
// CONCATENATED MODULE: ./node_modules/antd/es/progress/progress.js
var progress_rest = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
var ProgressTypes = Object(_util_type["a" /* tuple */])('line', 'circle', 'dashboard');
var ProgressStatuses = Object(_util_type["a" /* tuple */])('normal', 'exception', 'active', 'success');
var progress_Progress = /*#__PURE__*/function (_React$Component) {
inherits_default()(Progress, _React$Component);
var _super = createSuper_default()(Progress);
function Progress() {
var _this;
classCallCheck_default()(this, Progress);
_this = _super.apply(this, arguments);
_this.renderProgress = function (_ref) {
var _classNames;
var getPrefixCls = _ref.getPrefixCls,
direction = _ref.direction;
var _assertThisInitialize = assertThisInitialized_default()(_this),
props = _assertThisInitialize.props;
var customizePrefixCls = props.prefixCls,
className = props.className,
size = props.size,
type = props.type,
steps = props.steps,
showInfo = props.showInfo,
strokeColor = props.strokeColor,
restProps = progress_rest(props, ["prefixCls", "className", "size", "type", "steps", "showInfo", "strokeColor"]);
var prefixCls = getPrefixCls('progress', customizePrefixCls);
var progressStatus = _this.getProgressStatus();
var progressInfo = _this.renderProcessInfo(prefixCls, progressStatus);
Object(devWarning["a" /* default */])(!('successPercent' in props), 'Progress', '`successPercent` is deprecated. Please use `success.percent` instead.');
var progress; // Render progress shape
if (type === 'line') {
progress = steps ? /*#__PURE__*/react["createElement"](progress_Steps, extends_default()({}, _this.props, {
strokeColor: typeof strokeColor === 'string' ? strokeColor : undefined,
prefixCls: prefixCls,
steps: steps
}), progressInfo) : /*#__PURE__*/react["createElement"](progress_Line, extends_default()({}, _this.props, {
prefixCls: prefixCls
}), progressInfo);
} else if (type === 'circle' || type === 'dashboard') {
progress = /*#__PURE__*/react["createElement"](progress_Circle, extends_default()({}, _this.props, {
prefixCls: prefixCls,
progressStatus: progressStatus
}), progressInfo);
}
var classString = classnames_default()(prefixCls, (_classNames = {}, defineProperty_default()(_classNames, "".concat(prefixCls, "-").concat(type === 'dashboard' && 'circle' || steps && 'steps' || type), true), defineProperty_default()(_classNames, "".concat(prefixCls, "-status-").concat(progressStatus), true), defineProperty_default()(_classNames, "".concat(prefixCls, "-show-info"), showInfo), defineProperty_default()(_classNames, "".concat(prefixCls, "-").concat(size), size), defineProperty_default()(_classNames, "".concat(prefixCls, "-rtl"), direction === 'rtl'), _classNames), className);
return /*#__PURE__*/react["createElement"]("div", extends_default()({}, Object(omit_js_es["a" /* default */])(restProps, ['status', 'format', 'trailColor', 'strokeWidth', 'width', 'gapDegree', 'gapPosition', 'strokeColor', 'strokeLinecap', 'percent', 'steps', 'success', 'successPercent']), {
className: classString
}), progress);
};
return _this;
}
createClass_default()(Progress, [{
key: "getPercentNumber",
value: function getPercentNumber() {
var _this$props$percent = this.props.percent,
percent = _this$props$percent === void 0 ? 0 : _this$props$percent;
var successPercent = getSuccessPercent(this.props);
return parseInt(successPercent !== undefined ? successPercent.toString() : percent.toString(), 10);
}
}, {
key: "getProgressStatus",
value: function getProgressStatus() {
var status = this.props.status;
if (ProgressStatuses.indexOf(status) < 0 && this.getPercentNumber() >= 100) {
return 'success';
}
return status || 'normal';
}
}, {
key: "renderProcessInfo",
value: function renderProcessInfo(prefixCls, progressStatus) {
var _this$props = this.props,
showInfo = _this$props.showInfo,
format = _this$props.format,
type = _this$props.type,
percent = _this$props.percent;
var successPercent = getSuccessPercent(this.props);
if (!showInfo) return null;
var text;
var textFormatter = format || function (percentNumber) {
return "".concat(percentNumber, "%");
};
var isLineType = type === 'line';
if (format || progressStatus !== 'exception' && progressStatus !== 'success') {
text = textFormatter(validProgress(percent), validProgress(successPercent));
} else if (progressStatus === 'exception') {
text = isLineType ? /*#__PURE__*/react["createElement"](CloseCircleFilled_default.a, null) : /*#__PURE__*/react["createElement"](CloseOutlined_default.a, null);
} else if (progressStatus === 'success') {
text = isLineType ? /*#__PURE__*/react["createElement"](CheckCircleFilled_default.a, null) : /*#__PURE__*/react["createElement"](CheckOutlined_default.a, null);
}
return /*#__PURE__*/react["createElement"]("span", {
className: "".concat(prefixCls, "-text"),
title: typeof text === 'string' ? text : undefined
}, text);
}
}, {
key: "render",
value: function render() {
return /*#__PURE__*/react["createElement"](context["a" /* ConfigConsumer */], null, this.renderProgress);
}
}]);
return Progress;
}(react["Component"]);
progress_Progress.defaultProps = {
type: 'line',
percent: 0,
showInfo: true,
// null for different theme definition
trailColor: null,
size: 'default',
gapDegree: undefined,
strokeLinecap: 'round'
};
// CONCATENATED MODULE: ./node_modules/antd/es/progress/index.js
/* harmony default export */ var es_progress = (progress_Progress);
// EXTERNAL MODULE: ./node_modules/antd/es/_util/hooks/useForceUpdate.js
var useForceUpdate = __webpack_require__("hkKa");
// CONCATENATED MODULE: ./node_modules/antd/es/upload/UploadList.js
var UploadList_InternalUploadList = function InternalUploadList(_ref, ref) {
var _classNames6;
var listType = _ref.listType,
previewFile = _ref.previewFile,
onPreview = _ref.onPreview,
onDownload = _ref.onDownload,
onRemove = _ref.onRemove,
locale = _ref.locale,
iconRender = _ref.iconRender,
isImgUrl = _ref.isImageUrl,
customizePrefixCls = _ref.prefixCls,
_ref$items = _ref.items,
items = _ref$items === void 0 ? [] : _ref$items,
showPreviewIcon = _ref.showPreviewIcon,
showRemoveIcon = _ref.showRemoveIcon,
showDownloadIcon = _ref.showDownloadIcon,
customRemoveIcon = _ref.removeIcon,
customDownloadIcon = _ref.downloadIcon,
progressProps = _ref.progress;
var forceUpdate = Object(useForceUpdate["a" /* default */])();
react["useEffect"](function () {
if (listType !== 'picture' && listType !== 'picture-card') {
return;
}
(items || []).forEach(function (file) {
if (typeof document === 'undefined' || typeof window === 'undefined' || !window.FileReader || !window.File || !(file.originFileObj instanceof File || file.originFileObj instanceof Blob) || file.thumbUrl !== undefined) {
return;
}
file.thumbUrl = '';
if (previewFile) {
previewFile(file.originFileObj).then(function (previewDataUrl) {
// Need append '' to avoid dead loop
file.thumbUrl = previewDataUrl || '';
forceUpdate();
});
}
});
}, [listType, items, previewFile]);
var handlePreview = function handlePreview(file, e) {
if (!onPreview) {
return;
}
e.preventDefault();
return onPreview(file);
};
var handleDownload = function handleDownload(file) {
if (typeof onDownload === 'function') {
onDownload(file);
} else if (file.url) {
window.open(file.url);
}
};
var handleClose = function handleClose(file) {
if (onRemove) {
onRemove(file);
}
};
var handleIconRender = function handleIconRender(file) {
if (iconRender) {
return iconRender(file, listType);
}
var isLoading = file.status === 'uploading';
var fileIcon = isImgUrl && isImgUrl(file) ? /*#__PURE__*/react["createElement"](PictureTwoTone_default.a, null) : /*#__PURE__*/react["createElement"](FileTwoTone_default.a, null);
var icon = isLoading ? /*#__PURE__*/react["createElement"](LoadingOutlined_default.a, null) : /*#__PURE__*/react["createElement"](PaperClipOutlined_default.a, null);
if (listType === 'picture') {
icon = isLoading ? /*#__PURE__*/react["createElement"](LoadingOutlined_default.a, null) : fileIcon;
} else if (listType === 'picture-card') {
icon = isLoading ? locale.uploading : fileIcon;
}
return icon;
};
var handleActionIconRender = function handleActionIconRender(customIcon, callback, prefixCls, title) {
var btnProps = {
type: 'text',
size: 'small',
title: title,
onClick: function onClick(e) {
callback();
if (Object(reactNode["b" /* isValidElement */])(customIcon) && customIcon.props.onClick) {
customIcon.props.onClick(e);
}
},
className: "".concat(prefixCls, "-list-item-card-actions-btn")
};
if (Object(reactNode["b" /* isValidElement */])(customIcon)) {
var btnIcon = Object(reactNode["a" /* cloneElement */])(customIcon, extends_default()(extends_default()({}, customIcon.props), {
onClick: function onClick() {}
}));
return /*#__PURE__*/react["createElement"](es_button["a" /* default */], extends_default()({}, btnProps, {
icon: btnIcon
}));
}
return /*#__PURE__*/react["createElement"](es_button["a" /* default */], btnProps, /*#__PURE__*/react["createElement"]("span", null, customIcon));
}; // Test needs
react["useImperativeHandle"](ref, function () {
return {
handlePreview: handlePreview,
handleDownload: handleDownload
};
});
var _React$useContext = react["useContext"](context["b" /* ConfigContext */]),
getPrefixCls = _React$useContext.getPrefixCls,
direction = _React$useContext.direction;
var prefixCls = getPrefixCls('upload', customizePrefixCls);
var list = items.map(function (file) {
var _classNames3, _classNames4;
var progress;
var iconNode = handleIconRender(file);
var icon = /*#__PURE__*/react["createElement"]("div", {
className: "".concat(prefixCls, "-text-icon")
}, iconNode);
if (listType === 'picture' || listType === 'picture-card') {
if (file.status === 'uploading' || !file.thumbUrl && !file.url) {
var _classNames;
var uploadingClassName = classnames_default()((_classNames = {}, defineProperty_default()(_classNames, "".concat(prefixCls, "-list-item-thumbnail"), true), defineProperty_default()(_classNames, "".concat(prefixCls, "-list-item-file"), file.status !== 'uploading'), _classNames));
icon = /*#__PURE__*/react["createElement"]("div", {
className: uploadingClassName
}, iconNode);
} else {
var _classNames2;
var thumbnail = isImgUrl && isImgUrl(file) ? /*#__PURE__*/react["createElement"]("img", {
src: file.thumbUrl || file.url,
alt: file.name,
className: "".concat(prefixCls, "-list-item-image")
}) : iconNode;
var aClassName = classnames_default()((_classNames2 = {}, defineProperty_default()(_classNames2, "".concat(prefixCls, "-list-item-thumbnail"), true), defineProperty_default()(_classNames2, "".concat(prefixCls, "-list-item-file"), isImgUrl && !isImgUrl(file)), _classNames2));
icon = /*#__PURE__*/react["createElement"]("a", {
className: aClassName,
onClick: function onClick(e) {
return handlePreview(file, e);
},
href: file.url || file.thumbUrl,
target: "_blank",
rel: "noopener noreferrer"
}, thumbnail);
}
}
if (file.status === 'uploading') {
// show loading icon if upload progress listener is disabled
var loadingProgress = 'percent' in file ? /*#__PURE__*/react["createElement"](es_progress, extends_default()({}, progressProps, {
type: "line",
percent: file.percent
})) : null;
progress = /*#__PURE__*/react["createElement"]("div", {
className: "".concat(prefixCls, "-list-item-progress"),
key: "progress"
}, loadingProgress);
}
var infoUploadingClass = classnames_default()((_classNames3 = {}, defineProperty_default()(_classNames3, "".concat(prefixCls, "-list-item"), true), defineProperty_default()(_classNames3, "".concat(prefixCls, "-list-item-").concat(file.status), true), defineProperty_default()(_classNames3, "".concat(prefixCls, "-list-item-list-type-").concat(listType), true), _classNames3));
var linkProps = typeof file.linkProps === 'string' ? JSON.parse(file.linkProps) : file.linkProps;
var removeIcon = showRemoveIcon ? handleActionIconRender(customRemoveIcon || /*#__PURE__*/react["createElement"](DeleteOutlined_default.a, null), function () {
return handleClose(file);
}, prefixCls, locale.removeFile) : null;
var downloadIcon = showDownloadIcon && file.status === 'done' ? handleActionIconRender(customDownloadIcon || /*#__PURE__*/react["createElement"](DownloadOutlined_default.a, null), function () {
return handleDownload(file);
}, prefixCls, locale.downloadFile) : null;
var downloadOrDelete = listType !== 'picture-card' && /*#__PURE__*/react["createElement"]("span", {
key: "download-delete",
className: "".concat(prefixCls, "-list-item-card-actions ").concat(listType === 'picture' ? 'picture' : '')
}, downloadIcon, removeIcon);
var listItemNameClass = classnames_default()((_classNames4 = {}, defineProperty_default()(_classNames4, "".concat(prefixCls, "-list-item-name"), true), defineProperty_default()(_classNames4, "".concat(prefixCls, "-list-item-name-icon-count-").concat([downloadIcon, removeIcon].filter(function (x) {
return x;
}).length), true), _classNames4));
var preview = file.url ? [/*#__PURE__*/react["createElement"]("a", extends_default()({
key: "view",
target: "_blank",
rel: "noopener noreferrer",
className: listItemNameClass,
title: file.name
}, linkProps, {
href: file.url,
onClick: function onClick(e) {
return handlePreview(file, e);
}
}), file.name), downloadOrDelete] : [/*#__PURE__*/react["createElement"]("span", {
key: "view",
className: listItemNameClass,
onClick: function onClick(e) {
return handlePreview(file, e);
},
title: file.name
}, file.name), downloadOrDelete];
var style = {
pointerEvents: 'none',
opacity: 0.5
};
var previewIcon = showPreviewIcon ? /*#__PURE__*/react["createElement"]("a", {
href: file.url || file.thumbUrl,
target: "_blank",
rel: "noopener noreferrer",
style: file.url || file.thumbUrl ? undefined : style,
onClick: function onClick(e) {
return handlePreview(file, e);
},
title: locale.previewFile
}, /*#__PURE__*/react["createElement"](EyeOutlined_default.a, null)) : null;
var actions = listType === 'picture-card' && file.status !== 'uploading' && /*#__PURE__*/react["createElement"]("span", {
className: "".concat(prefixCls, "-list-item-actions")
}, previewIcon, file.status === 'done' && downloadIcon, removeIcon);
var message;
if (file.response && typeof file.response === 'string') {
message = file.response;
} else {
message = file.error && file.error.statusText || locale.uploadError;
}
var iconAndPreview = /*#__PURE__*/react["createElement"]("span", null, icon, preview);
var dom = /*#__PURE__*/react["createElement"]("div", {
className: infoUploadingClass
}, /*#__PURE__*/react["createElement"]("div", {
className: "".concat(prefixCls, "-list-item-info")
}, iconAndPreview), actions, /*#__PURE__*/react["createElement"](Animate["a" /* default */], {
transitionName: "fade",
component: ""
}, progress));
var listContainerNameClass = classnames_default()(defineProperty_default()({}, "".concat(prefixCls, "-list-picture-card-container"), listType === 'picture-card'));
return /*#__PURE__*/react["createElement"]("div", {
key: file.uid,
className: listContainerNameClass
}, file.status === 'error' ? /*#__PURE__*/react["createElement"](tooltip["a" /* default */], {
title: message,
getPopupContainer: function getPopupContainer(node) {
return node.parentNode;
}
}, dom) : /*#__PURE__*/react["createElement"]("span", null, dom));
});
var listClassNames = classnames_default()((_classNames6 = {}, defineProperty_default()(_classNames6, "".concat(prefixCls, "-list"), true), defineProperty_default()(_classNames6, "".concat(prefixCls, "-list-").concat(listType), true), defineProperty_default()(_classNames6, "".concat(prefixCls, "-list-rtl"), direction === 'rtl'), _classNames6));
var animationDirection = listType === 'picture-card' ? 'animate-inline' : 'animate';
return /*#__PURE__*/react["createElement"](Animate["a" /* default */], {
transitionName: "".concat(prefixCls, "-").concat(animationDirection),
component: "div",
className: listClassNames
}, list);
};
var UploadList = /*#__PURE__*/react["forwardRef"](UploadList_InternalUploadList);
UploadList.displayName = 'UploadList';
UploadList.defaultProps = {
listType: 'text',
progress: {
strokeWidth: 2,
showInfo: false
},
showRemoveIcon: true,
showDownloadIcon: false,
showPreviewIcon: true,
previewFile: previewImage,
isImageUrl: utils_isImageUrl
};
/* harmony default export */ var upload_UploadList = (UploadList);
// EXTERNAL MODULE: ./node_modules/antd/es/locale-provider/LocaleReceiver.js + 1 modules
var LocaleReceiver = __webpack_require__("YMnH");
// EXTERNAL MODULE: ./node_modules/antd/es/locale/default.js + 4 modules
var locale_default = __webpack_require__("ZvpZ");
// EXTERNAL MODULE: ./node_modules/antd/es/_util/hooks/useSyncState.js
var useSyncState = __webpack_require__("sPtV");
// CONCATENATED MODULE: ./node_modules/antd/es/upload/Upload.js
var Upload_InternalUpload = function InternalUpload(props, ref) {
var _classNames2;
var fileListProp = props.fileList,
defaultFileList = props.defaultFileList,
onRemove = props.onRemove,
showUploadList = props.showUploadList,
listType = props.listType,
onPreview = props.onPreview,
onDownload = props.onDownload,
previewFile = props.previewFile,
disabled = props.disabled,
propLocale = props.locale,
iconRender = props.iconRender,
isImageUrl = props.isImageUrl,
progress = props.progress,
customizePrefixCls = props.prefixCls,
className = props.className,
type = props.type,
children = props.children,
style = props.style;
var _useSyncState = Object(useSyncState["a" /* default */])(fileListProp || defaultFileList || []),
_useSyncState2 = slicedToArray_default()(_useSyncState, 2),
getFileList = _useSyncState2[0],
setFileList = _useSyncState2[1];
var _React$useState = react["useState"]('drop'),
_React$useState2 = slicedToArray_default()(_React$useState, 2),
dragState = _React$useState2[0],
setDragState = _React$useState2[1];
var upload = react["useRef"]();
react["useEffect"](function () {
setFileList(fileListProp || defaultFileList || []);
Object(devWarning["a" /* default */])('fileList' in props || !('value' in props), 'Upload', '`value` is not a valid prop, do you mean `fileList`?');
}, []);
react["useEffect"](function () {
if ('fileList' in props) {
setFileList(fileListProp || []);
}
}, [fileListProp]);
var onChange = function onChange(info) {
if (!('fileList' in props)) {
setFileList(info.fileList);
}
var onChangeProp = props.onChange;
if (onChangeProp) {
onChangeProp(extends_default()(extends_default()({}, info), {
fileList: toConsumableArray_default()(info.fileList)
}));
}
};
var onStart = function onStart(file) {
var targetItem = fileToObject(file);
targetItem.status = 'uploading';
var nextFileList = getFileList().concat();
var fileIndex = nextFileList.findIndex(function (_ref) {
var uid = _ref.uid;
return uid === targetItem.uid;
});
if (fileIndex === -1) {
nextFileList.push(targetItem);
} else {
nextFileList[fileIndex] = targetItem;
}
onChange({
file: targetItem,
fileList: nextFileList
});
};
var onSuccess = function onSuccess(response, file, xhr) {
try {
if (typeof response === 'string') {
response = JSON.parse(response);
}
} catch (e) {
/* do nothing */
}
var targetItem = getFileItem(file, getFileList()); // removed
if (!targetItem) {
return;
}
targetItem.status = 'done';
targetItem.response = response;
targetItem.xhr = xhr;
onChange({
file: extends_default()({}, targetItem),
fileList: getFileList().concat()
});
};
var onProgress = function onProgress(e, file) {
var targetItem = getFileItem(file, getFileList()); // removed
if (!targetItem) {
return;
}
targetItem.percent = e.percent;
onChange({
event: e,
file: extends_default()({}, targetItem),
fileList: getFileList().concat()
});
};
var onError = function onError(error, response, file) {
var targetItem = getFileItem(file, getFileList()); // removed
if (!targetItem) {
return;
}
targetItem.error = error;
targetItem.response = response;
targetItem.status = 'error';
onChange({
file: extends_default()({}, targetItem),
fileList: getFileList().concat()
});
};
var handleRemove = function handleRemove(file) {
Promise.resolve(typeof onRemove === 'function' ? onRemove(file) : onRemove).then(function (ret) {
// Prevent removing file
if (ret === false) {
return;
}
var removedFileList = removeFileItem(file, getFileList());
if (removedFileList) {
file.status = 'removed';
if (upload.current) {
upload.current.abort(file);
}
onChange({
file: file,
fileList: removedFileList
});
}
});
};
var onFileDrop = function onFileDrop(e) {
setDragState(e.type);
};
var beforeUpload = function beforeUpload(file, fileListArgs) {
var beforeUploadProp = props.beforeUpload;
if (!beforeUploadProp) {
return true;
}
var result = beforeUploadProp(file, fileListArgs);
if (result === false) {
// Get unique file list
var uniqueList = [];
getFileList().concat(fileListArgs.map(fileToObject)).forEach(function (f) {
if (uniqueList.every(function (uf) {
return uf.uid !== f.uid;
})) {
uniqueList.push(f);
}
});
onChange({
file: file,
fileList: uniqueList
});
return false;
}
if (result && result.then) {
return result;
}
return true;
}; // Test needs
var forceUpdate = Object(useForceUpdate["a" /* default */])();
react["useImperativeHandle"](ref, function () {
return {
onStart: onStart,
onSuccess: onSuccess,
onProgress: onProgress,
onError: onError,
fileList: getFileList(),
upload: upload.current,
forceUpdate: forceUpdate
};
});
var renderUploadList = function renderUploadList(locale) {
var showRemoveIcon = showUploadList.showRemoveIcon,
showPreviewIcon = showUploadList.showPreviewIcon,
showDownloadIcon = showUploadList.showDownloadIcon,
removeIcon = showUploadList.removeIcon,
downloadIcon = showUploadList.downloadIcon;
return /*#__PURE__*/react["createElement"](upload_UploadList, {
listType: listType,
items: getFileList(),
previewFile: previewFile,
onPreview: onPreview,
onDownload: onDownload,
onRemove: handleRemove,
showRemoveIcon: !disabled && showRemoveIcon,
showPreviewIcon: showPreviewIcon,
showDownloadIcon: showDownloadIcon,
removeIcon: removeIcon,
downloadIcon: downloadIcon,
iconRender: iconRender,
locale: extends_default()(extends_default()({}, locale), propLocale),
isImageUrl: isImageUrl,
progress: progress
});
};
var _React$useContext = react["useContext"](context["b" /* ConfigContext */]),
getPrefixCls = _React$useContext.getPrefixCls,
direction = _React$useContext.direction;
var prefixCls = getPrefixCls('upload', customizePrefixCls);
var rcUploadProps = extends_default()(extends_default()({
onStart: onStart,
onError: onError,
onProgress: onProgress,
onSuccess: onSuccess
}, props), {
prefixCls: prefixCls,
beforeUpload: beforeUpload
});
delete rcUploadProps.className;
delete rcUploadProps.style; // Remove id to avoid open by label when trigger is hidden
// !children: https://github.com/ant-design/ant-design/issues/14298
// disabled: https://github.com/ant-design/ant-design/issues/16478
// https://github.com/ant-design/ant-design/issues/24197
if (!children || disabled) {
delete rcUploadProps.id;
}
var uploadList = showUploadList ? /*#__PURE__*/react["createElement"](LocaleReceiver["a" /* default */], {
componentName: "Upload",
defaultLocale: locale_default["a" /* default */].Upload
}, renderUploadList) : null;
if (type === 'drag') {
var _classNames;
var dragCls = classnames_default()(prefixCls, (_classNames = {}, defineProperty_default()(_classNames, "".concat(prefixCls, "-drag"), true), defineProperty_default()(_classNames, "".concat(prefixCls, "-drag-uploading"), getFileList().some(function (file) {
return file.status === 'uploading';
})), defineProperty_default()(_classNames, "".concat(prefixCls, "-drag-hover"), dragState === 'dragover'), defineProperty_default()(_classNames, "".concat(prefixCls, "-disabled"), disabled), defineProperty_default()(_classNames, "".concat(prefixCls, "-rtl"), direction === 'rtl'), _classNames), className);
return /*#__PURE__*/react["createElement"]("span", null, /*#__PURE__*/react["createElement"]("div", {
className: dragCls,
onDrop: onFileDrop,
onDragOver: onFileDrop,
onDragLeave: onFileDrop,
style: style
}, /*#__PURE__*/react["createElement"](es, extends_default()({}, rcUploadProps, {
ref: upload,
className: "".concat(prefixCls, "-btn")
}), /*#__PURE__*/react["createElement"]("div", {
className: "".concat(prefixCls, "-drag-container")
}, children))), uploadList);
}
var uploadButtonCls = classnames_default()(prefixCls, (_classNames2 = {}, defineProperty_default()(_classNames2, "".concat(prefixCls, "-select"), true), defineProperty_default()(_classNames2, "".concat(prefixCls, "-select-").concat(listType), true), defineProperty_default()(_classNames2, "".concat(prefixCls, "-disabled"), disabled), defineProperty_default()(_classNames2, "".concat(prefixCls, "-rtl"), direction === 'rtl'), _classNames2));
var uploadButton = /*#__PURE__*/react["createElement"]("div", {
className: uploadButtonCls,
style: children ? undefined : {
display: 'none'
}
}, /*#__PURE__*/react["createElement"](es, extends_default()({}, rcUploadProps, {
ref: upload
})));
if (listType === 'picture-card') {
return /*#__PURE__*/react["createElement"]("span", {
className: classnames_default()(className, "".concat(prefixCls, "-picture-card-wrapper"))
}, uploadList, uploadButton);
}
return /*#__PURE__*/react["createElement"]("span", {
className: className
}, uploadButton, uploadList);
};
var upload_Upload_Upload = /*#__PURE__*/react["forwardRef"](Upload_InternalUpload);
upload_Upload_Upload.Dragger = upload_Dragger;
upload_Upload_Upload.displayName = 'Upload';
upload_Upload_Upload.defaultProps = {
type: 'select',
multiple: false,
action: '',
data: {},
accept: '',
beforeUpload: T,
showUploadList: true,
listType: 'text',
className: '',
disabled: false,
supportServerRender: true
};
/* harmony default export */ var upload_Upload = (upload_Upload_Upload);
// CONCATENATED MODULE: ./node_modules/antd/es/upload/index.js
upload_Upload.Dragger = upload_Dragger;
/* harmony default export */ var es_upload = (upload_Upload);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/objectSpread2.js
var esm_objectSpread2 = __webpack_require__("VTBJ");
// CONCATENATED MODULE: ./node_modules/@ant-design/icons-svg/es/asn/InboxOutlined.js
// This icon file is generated automatically.
var InboxOutlined_InboxOutlined = { "icon": { "tag": "svg", "attrs": { "viewBox": "0 0 1024 1024", "focusable": "false" }, "children": [{ "tag": "path", "attrs": { "d": "M885.2 446.3l-.2-.8-112.2-285.1c-5-16.1-19.9-27.2-36.8-27.2H281.2c-17 0-32.1 11.3-36.9 27.6L139.4 443l-.3.7-.2.8c-1.3 4.9-1.7 9.9-1 14.8-.1 1.6-.2 3.2-.2 4.8V830a60.9 60.9 0 0060.8 60.8h627.2c33.5 0 60.8-27.3 60.9-60.8V464.1c0-1.3 0-2.6-.1-3.7.4-4.9 0-9.6-1.3-14.1zm-295.8-43l-.3 15.7c-.8 44.9-31.8 75.1-77.1 75.1-22.1 0-41.1-7.1-54.8-20.6S436 441.2 435.6 419l-.3-15.7H229.5L309 210h399.2l81.7 193.3H589.4zm-375 76.8h157.3c24.3 57.1 76 90.8 140.4 90.8 33.7 0 65-9.4 90.3-27.2 22.2-15.6 39.5-37.4 50.7-63.6h156.5V814H214.4V480.1z" } }] }, "name": "inbox", "theme": "outlined" };
/* harmony default export */ var asn_InboxOutlined = (InboxOutlined_InboxOutlined);
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/es/components/AntdIcon.js + 5 modules
var AntdIcon = __webpack_require__("6VBw");
// CONCATENATED MODULE: ./node_modules/@ant-design/icons/es/icons/InboxOutlined.js
// GENERATE BY ./scripts/generate.ts
// DON NOT EDIT IT MANUALLY
var icons_InboxOutlined_InboxOutlined = function InboxOutlined(props, ref) {
return /*#__PURE__*/react["createElement"](AntdIcon["a" /* default */], Object(esm_objectSpread2["a" /* default */])(Object(esm_objectSpread2["a" /* default */])({}, props), {}, {
ref: ref,
icon: asn_InboxOutlined
}));
};
icons_InboxOutlined_InboxOutlined.displayName = 'InboxOutlined';
/* harmony default export */ var icons_InboxOutlined = (/*#__PURE__*/react["forwardRef"](icons_InboxOutlined_InboxOutlined));
// EXTERNAL MODULE: ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/extends.js
var esm_extends = __webpack_require__("0Owb");
// EXTERNAL MODULE: ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/toConsumableArray.js + 2 modules
var esm_toConsumableArray = __webpack_require__("oBTY");
// EXTERNAL MODULE: ./src/utils/fetch.ts
var fetch = __webpack_require__("ErOA");
// EXTERNAL MODULE: ./node_modules/crypto-js/index.js
var crypto_js = __webpack_require__("NFKh");
var crypto_js_default = /*#__PURE__*/__webpack_require__.n(crypto_js);
// CONCATENATED MODULE: ./node_modules/uuid/dist/esm-browser/rng.js
// Unique ID creation requires a high quality random # generator. In the browser we therefore
// require the crypto API and do not support built-in fallback to lower quality random number
// generators (like Math.random()).
// getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
// find the complete implementation of crypto (msCrypto) on IE11.
var getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
var rnds8 = new Uint8Array(16);
function rng() {
if (!getRandomValues) {
throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
}
return getRandomValues(rnds8);
}
// CONCATENATED MODULE: ./node_modules/uuid/dist/esm-browser/regex.js
/* harmony default export */ var regex = (/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i);
// CONCATENATED MODULE: ./node_modules/uuid/dist/esm-browser/validate.js
function validate(uuid) {
return typeof uuid === 'string' && regex.test(uuid);
}
/* harmony default export */ var esm_browser_validate = (validate);
// CONCATENATED MODULE: ./node_modules/uuid/dist/esm-browser/stringify.js
/**
* Convert array of 16 byte values to UUID string format of the form:
* XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
*/
var byteToHex = [];
for (var stringify_i = 0; stringify_i < 256; ++stringify_i) {
byteToHex.push((stringify_i + 0x100).toString(16).substr(1));
}
function stringify(arr) {
var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
// Note: Be careful editing this code! It's been tuned for performance
// and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one
// of the following:
// - One or more input array values don't map to a hex octet (leading to
// "undefined" in the uuid)
// - Invalid input values for the RFC `version` or `variant` fields
if (!esm_browser_validate(uuid)) {
throw TypeError('Stringified UUID is invalid');
}
return uuid;
}
/* harmony default export */ var esm_browser_stringify = (stringify);
// CONCATENATED MODULE: ./node_modules/uuid/dist/esm-browser/v4.js
function v4(options, buf, offset) {
options = options || {};
var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
rnds[6] = rnds[6] & 0x0f | 0x40;
rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
if (buf) {
offset = offset || 0;
for (var i = 0; i < 16; ++i) {
buf[offset + i] = rnds[i];
}
return buf;
}
return esm_browser_stringify(rnds);
}
/* harmony default export */ var esm_browser_v4 = (v4);
// EXTERNAL MODULE: ./node_modules/ali-oss/dist/aliyun-oss-sdk.js
var aliyun_oss_sdk = __webpack_require__("mxV5");
var aliyun_oss_sdk_default = /*#__PURE__*/__webpack_require__.n(aliyun_oss_sdk);
// CONCATENATED MODULE: ./src/components/UploadFile/index.tsx
var UploadFile_Dragger = es_upload.Dragger;
var UploadFile_decrypt = function decrypt(word) {
var ENC_KEY = "bf3c199c2470cb477d907b1e0917c17b";
var IV = "5183666c72eec9e4";
var key = crypto_js_default.a.enc.Utf8.parse(ENC_KEY);
var iv = crypto_js_default.a.enc.Utf8.parse(IV);
var decrypt = crypto_js_default.a.AES.decrypt(word, key, {
iv: iv,
mode: crypto_js_default.a.mode.CBC // padding: CryptoJS.pad.ZeroPadding
});
return decrypt.toString(crypto_js_default.a.enc.Utf8);
};
var tempCheckpoint;
var uploadFile = /*#__PURE__*/function () {
var _ref = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee(file, obj, config) {
var _res$data, _res$data2, _res$data3, _res$data4, _res$data5, _res$data6;
var res, name, client;
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
obj.file_name = file.name;
_context.next = 3;
return Object(fetch["a" /* default */])('/api/buckets/get_upload_token.json', {
method: "get"
});
case 3:
res = _context.sent;
console.log("decrypt(res.data):", UploadFile_decrypt(res.data));
res.data = JSON.parse(UploadFile_decrypt(res.data));
name = esm_browser_v4(); // const name = file.name
client = new aliyun_oss_sdk_default.a({
endpoint: res === null || res === void 0 ? void 0 : (_res$data = res.data) === null || _res$data === void 0 ? void 0 : _res$data.end_point,
region: res === null || res === void 0 ? void 0 : (_res$data2 = res.data) === null || _res$data2 === void 0 ? void 0 : _res$data2.region,
accessKeyId: res === null || res === void 0 ? void 0 : (_res$data3 = res.data) === null || _res$data3 === void 0 ? void 0 : _res$data3.access_key_id,
accessKeySecret: res === null || res === void 0 ? void 0 : (_res$data4 = res.data) === null || _res$data4 === void 0 ? void 0 : _res$data4.access_key_secret,
bucket: res === null || res === void 0 ? void 0 : (_res$data5 = res.data) === null || _res$data5 === void 0 ? void 0 : _res$data5.bucket,
stsToken: res === null || res === void 0 ? void 0 : (_res$data6 = res.data) === null || _res$data6 === void 0 ? void 0 : _res$data6.security_token
});
return _context.abrupt("return", new Promise(function (resolve, reject) {
var _res$data7;
client.multipartUpload("".concat(name), new Blob([file], {
type: file.type
}), Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({
timeout: 200 * 1000,
partSize: 102400
}, config), {}, {
callback: {
url: res === null || res === void 0 ? void 0 : (_res$data7 = res.data) === null || _res$data7 === void 0 ? void 0 : _res$data7.callback_url,
host: res === null || res === void 0 ? void 0 : res.data.bucket_host,
body: 'bucket=${bucket}&object=${object}&etag=${etag}&size=${size}&mimeType=${mimeType}&my_var=${x:my_var}&' + Object(fetch["b" /* parseParams */])(obj) // body: 'bucket=${bucket}&object=${object}&etag=${etag}&size=${size}&mimeType=${mimeType}&my_var=${x:my_var}&login=' + obj.login + '&container_id=' + obj.container_id + '&container_type='+obj.container_type,
}
})).then(function (result) {
var _result$data;
file.response = (_result$data = result.data) === null || _result$data === void 0 ? void 0 : _result$data.data;
resolve(result === null || result === void 0 ? void 0 : result.data);
}).catch(function (err) {
reject(err);
console.log("err:", err);
});
}));
case 9:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function uploadFile(_x, _x2, _x3) {
return _ref.apply(this, arguments);
};
}();
var UploadFile_UploadFile = function UploadFile(_ref2) {
var user = _ref2.user,
cancelUpload = _ref2.cancelUpload,
props = Object(objectWithoutProperties["a" /* default */])(_ref2, ["user", "cancelUpload"]);
var _useState = Object(react["useState"])([]),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
fileList = _useState2[0],
setFileList = _useState2[1];
var _useState3 = Object(react["useState"])(),
_useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
client = _useState4[0],
setClient = _useState4[1];
var _props = {
onRemove: function onRemove(e) {
setFileList(Object(esm_toConsumableArray["a" /* default */])(fileList.filter(function (item) {
return item.name !== e.name;
})));
props.onChange(fileList.filter(function (item) {
return item.name !== e.name;
}));
},
disabled: props.disabled,
multiple: true,
fileList: fileList === null || fileList === void 0 ? void 0 : fileList.map(function (item) {
return item.file;
}),
customRequest: function customRequest() {},
beforeUpload: function () {
var _beforeUpload = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee2(file) {
var fileSize;
return regenerator_default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
fileSize = props.maxSize || 1024 * 1024 * 1024 * 1;
if (!fileList.filter(function (item) {
return item.name === file.name;
}).length) {
_context2.next = 4;
break;
}
es_message["b" /* default */].info("".concat(file.name, "\u5DF2\u5B58\u5728\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9"));
return _context2.abrupt("return");
case 4:
if (!((file === null || file === void 0 ? void 0 : file.size) > fileSize)) {
_context2.next = 7;
break;
}
es_message["b" /* default */].info("\u6587\u4EF6\u8D85\u8FC7".concat(fileSize / 1024 / 1024 / 1024, "GB\uFF0C\u4E0D\u7B26\u5408\u4E0A\u4F20\u8981\u6C42"));
return _context2.abrupt("return", false);
case 7:
fileList.push({
name: file.name,
file: file
});
setFileList(Object(esm_toConsumableArray["a" /* default */])(fileList));
props.onChange(fileList);
return _context2.abrupt("return", false);
case 11:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
function beforeUpload(_x4) {
return _beforeUpload.apply(this, arguments);
}
return beforeUpload;
}()
};
var _uploadFiles = /*#__PURE__*/function () {
var _ref3 = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee3(file, obj) {
var _res$data8, _res$data9, _res$data10, _res$data11, _res$data12, _res$data13;
var name, res, filename;
return regenerator_default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
obj.file_name = file.name;
name = file.name;
_context3.next = 4;
return Object(fetch["a" /* default */])('/api/buckets/get_upload_token_for_big_files.json', {
method: "get"
});
case 4:
res = _context3.sent;
res.data = JSON.parse(UploadFile_decrypt(res.data));
if (!((res === null || res === void 0 ? void 0 : res.status) !== 0)) {
_context3.next = 12;
break;
}
fileList[fileList.findIndex(function (item) {
return item.name === name;
})]['status'] = 'error';
fileList[fileList.findIndex(function (item) {
return item.name === name;
})]['file']['status'] = 'error';
props.onChange(fileList);
es_message["b" /* default */].warn("上传失败,请重新尝试");
return _context3.abrupt("return");
case 12:
client = new aliyun_oss_sdk_default.a({
endpoint: res === null || res === void 0 ? void 0 : (_res$data8 = res.data) === null || _res$data8 === void 0 ? void 0 : _res$data8.end_point,
region: res === null || res === void 0 ? void 0 : (_res$data9 = res.data) === null || _res$data9 === void 0 ? void 0 : _res$data9.region,
accessKeyId: res === null || res === void 0 ? void 0 : (_res$data10 = res.data) === null || _res$data10 === void 0 ? void 0 : _res$data10.access_key_id,
accessKeySecret: res === null || res === void 0 ? void 0 : (_res$data11 = res.data) === null || _res$data11 === void 0 ? void 0 : _res$data11.access_key_secret,
bucket: res === null || res === void 0 ? void 0 : (_res$data12 = res.data) === null || _res$data12 === void 0 ? void 0 : _res$data12.bucket,
stsToken: res === null || res === void 0 ? void 0 : (_res$data13 = res.data) === null || _res$data13 === void 0 ? void 0 : _res$data13.security_token
});
console.log(file, 'file');
setClient(client);
filename = esm_browser_v4();
return _context3.abrupt("return", new Promise(function (resolve, reject) {
try {
var _res$data14;
client.multipartUpload("".concat(props.identifier, "/").concat(filename).concat(name.indexOf(".") > -1 ? '.' + name.split(".").pop() : ""), new Blob([file.file], {
type: file.file.type
}), {
timeout: 3600 * 1000,
partSize: 1002400,
progress: function progress(p, checkpoint, res) {
try {
console.log("进度", p, checkpoint, res);
var index = fileList.findIndex(function (item) {
return item.name === name;
});
fileList[index]['file']['percent'] = p * 100; // if (p === 1) {
// fileList[index]['status'] = 'done'
// fileList[index]['file']['status'] = 'done'
// props.onChange(fileList)
// }
// if (p === 1) {
// fileList[index]['status'] = 'done'
// fileList[index]['file']['status'] = 'done'
// props.onChange(fileList)
// }
fileList[index].tempCheckpoint = checkpoint;
setFileList(Object(esm_toConsumableArray["a" /* default */])(fileList));
} catch (e) {}
},
checkpoint: fileList[fileList.findIndex(function (item) {
return item.name === name;
})].tempCheckpoint,
callback: {
customValue: {
id: name + ''
},
url: res === null || res === void 0 ? void 0 : (_res$data14 = res.data) === null || _res$data14 === void 0 ? void 0 : _res$data14.callback_url,
host: res === null || res === void 0 ? void 0 : res.data.bucket_host,
body: 'bucket=${bucket}&object=${object}&etag=${etag}&size=${size}&mimeType=${mimeType}&my_var=${x:my_var}&' + Object(fetch["b" /* parseParams */])(obj)
}
}).then(function (result) {
var _result$data2;
var index = fileList.findIndex(function (item) {
return item.name === name;
});
var status = 'done';
if (((_result$data2 = result.data) === null || _result$data2 === void 0 ? void 0 : _result$data2.status) === 0) {
var _result$data3;
file.response = (_result$data3 = result.data) === null || _result$data3 === void 0 ? void 0 : _result$data3.data;
var _index = fileList.findIndex(function (item) {
return item.name === name;
});
fileList[_index]['status'] = 'done';
fileList[_index]['file']['status'] = 'done';
} else {
var _result$data4;
es_message["b" /* default */].warn((_result$data4 = result.data) === null || _result$data4 === void 0 ? void 0 : _result$data4.message);
status = 'error';
}
fileList[index]['status'] = status;
fileList[index]['file']['status'] = status;
props.onChange(fileList);
resolve(result === null || result === void 0 ? void 0 : result.data);
}).catch(function (err) {
fileList[fileList.findIndex(function (item) {
return item.name === name;
})]['status'] = 'error';
fileList[fileList.findIndex(function (item) {
return item.name === name;
})]['file']['status'] = 'error';
es_message["b" /* default */].warn("上传失败,请重新尝试");
setFileList(Object(esm_toConsumableArray["a" /* default */])(fileList));
props.onChange(fileList);
reject(err);
console.log("err:", err);
});
} catch (e) {}
}));
case 17:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
return function _uploadFiles(_x5, _x6) {
return _ref3.apply(this, arguments);
};
}();
Object(react["useEffect"])(function () {
if (fileList.every(function (item) {
return item === 'done' || item === 'error';
})) {
props.onComplete(fileList);
}
}, [fileList]);
Object(react["useEffect"])(function () {
if (cancelUpload) {
var _client;
(_client = client) === null || _client === void 0 ? void 0 : _client.cancel();
}
}, [cancelUpload]);
Object(react["useEffect"])(function () {
if (props.uploading) fileList.map( /*#__PURE__*/function () {
var _ref4 = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee4(item) {
var _user$eduUserInfo, res;
return regenerator_default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
if (!((!item.status || item.status === 'error') && !cancelUpload)) {
_context4.next = 6;
break;
}
item.status = 'uploading';
item.file.status = 'uploading';
_context4.next = 5;
return _uploadFiles(item, {
login: user === null || user === void 0 ? void 0 : (_user$eduUserInfo = user.eduUserInfo) === null || _user$eduUserInfo === void 0 ? void 0 : _user$eduUserInfo.login,
container_type: props.container_type,
container_id: props.container_id,
description: props.description
});
case 5:
res = _context4.sent;
case 6:
case "end":
return _context4.stop();
}
}
}, _callee4);
}));
return function (_x7) {
return _ref4.apply(this, arguments);
};
}());
}, [props.uploading]);
return /*#__PURE__*/react_default.a.createElement(UploadFile_Dragger, Object(esm_extends["a" /* default */])({}, _props, {
height: props.height,
className: props.className
}), /*#__PURE__*/react_default.a.createElement("p", {
className: "ant-upload-hint"
}, props.text || '拖拽文件或者点击上传'));
};
/* harmony default export */ var components_UploadFile = (Object(umiExports["a" /* connect */])(function (_ref5) {
var loading = _ref5.loading,
globalSetting = _ref5.globalSetting,
user = _ref5.user;
return {
globalSetting: globalSetting,
loading: loading.models.competitions,
user: user
};
})(UploadFile_UploadFile));
// CONCATENATED MODULE: ./src/pages/Competitions/Detail/AddSubmitModel.tsx
var AddSubmitModel_Dragger = es_upload.Dragger;
var AddSubmitModel_ShixunsListPage = function ShixunsListPage(_ref) {
var user = _ref.user,
dispatch = _ref.dispatch,
classroomList = _ref.classroomList,
shixunsDetail = _ref.shixunsDetail,
getResults = _ref.getResults;
var params = Object(react_router["l" /* useParams */])();
var _useState = Object(react["useState"])(),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
time = _useState2[0],
setTime = _useState2[1];
var _useState3 = Object(react["useState"])([]),
_useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
fileList = _useState4[0],
setFileList = _useState4[1];
var _useState5 = Object(react["useState"])(false),
_useState6 = Object(slicedToArray["a" /* default */])(_useState5, 2),
confirmLoading = _useState6[0],
setConfirmLoading = _useState6[1];
var props = {
onRemove: function onRemove() {
setFileList([]);
},
beforeUpload: function beforeUpload(file) {
console.log(file);
if ((file === null || file === void 0 ? void 0 : file.size) > 1024 * 1024 * 500) {
es_message["b" /* default */].info('文件超过500M不符合上传要求');
return false;
}
var filelist = [];
filelist.push(file);
setFileList([].concat(filelist));
return false;
},
fileList: fileList
};
return /*#__PURE__*/react_default.a.createElement(es_modal["a" /* default */], {
title: "\u63D0\u4EA4\u6587\u4EF6",
visible: shixunsDetail.actionTabs.key === 'md-tab',
confirmLoading: confirmLoading,
onOk: /*#__PURE__*/Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee() {
var _user$eduUserInfo, _fileList$;
var resulr;
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (!((fileList === null || fileList === void 0 ? void 0 : fileList.length) <= 0)) {
_context.next = 3;
break;
}
es_message["b" /* default */].info('请先选择文件');
return _context.abrupt("return");
case 3:
setConfirmLoading(true);
_context.next = 6;
return uploadFile(fileList[0], {
login: (_user$eduUserInfo = user.eduUserInfo) === null || _user$eduUserInfo === void 0 ? void 0 : _user$eduUserInfo.login,
container_type: "Competition",
container_id: shixunsDetail.actionTabs.params.id,
stage_type: shixunsDetail.actionTabs.params.value,
file_name: (_fileList$ = fileList[0]) === null || _fileList$ === void 0 ? void 0 : _fileList$.name
});
case 6:
resulr = _context.sent;
if ((resulr === null || resulr === void 0 ? void 0 : resulr.status) === 0) {
es_message["b" /* default */].info('提交成功');
dispatch({
type: 'shixunsDetail/setActionTabs',
payload: {
key: ''
}
});
setConfirmLoading(false);
setFileList([]);
getResults(shixunsDetail.actionTabs.params.value);
} else {
setConfirmLoading(false);
es_message["b" /* default */].info('提交失败');
}
case 8:
case "end":
return _context.stop();
}
}
}, _callee);
})),
onCancel: function onCancel() {
setFileList([]);
dispatch({
type: 'shixunsDetail/setActionTabs',
payload: {
key: ''
}
});
}
}, /*#__PURE__*/react_default.a.createElement(AddSubmitModel_Dragger, props, /*#__PURE__*/react_default.a.createElement("p", {
className: "ant-upload-drag-icon"
}, /*#__PURE__*/react_default.a.createElement(icons_InboxOutlined, null)), /*#__PURE__*/react_default.a.createElement("p", {
className: "ant-upload-hint"
}, "\u62D6\u62FD\u6587\u4EF6\u6216\u8005\u70B9\u51FB\u4E0A\u4F20")));
};
/* harmony default export */ var AddSubmitModel = (Object(umiExports["a" /* connect */])(function (_ref3) {
var user = _ref3.user,
classroomList = _ref3.classroomList,
shixunsDetail = _ref3.shixunsDetail;
return {
user: user,
classroomList: classroomList,
shixunsDetail: shixunsDetail
};
})(AddSubmitModel_ShixunsListPage));
// EXTERNAL MODULE: ./node_modules/antd/es/row/style/index.js
var row_style = __webpack_require__("14J3");
// EXTERNAL MODULE: ./node_modules/antd/es/row/index.js
var es_row = __webpack_require__("BMrR");
// EXTERNAL MODULE: ./node_modules/antd/es/input/style/index.js
var input_style = __webpack_require__("5NDa");
// EXTERNAL MODULE: ./node_modules/antd/es/input/index.js + 14 modules
var es_input = __webpack_require__("5rEg");
// EXTERNAL MODULE: ./src/components/RenderHtml/index.tsx + 6 modules
var RenderHtml = __webpack_require__("9Bee");
// EXTERNAL MODULE: ./src/utils/env.ts + 1 modules
var env = __webpack_require__("m3rI");
// EXTERNAL MODULE: ./src/utils/verifyLogin.tsx
var verifyLogin = __webpack_require__("NLgs");
// EXTERNAL MODULE: ./node_modules/antd/es/carousel/style/index.js
var carousel_style = __webpack_require__("fV52");
// EXTERNAL MODULE: ./node_modules/antd/es/carousel/index.js
var carousel = __webpack_require__("3I+P");
// EXTERNAL MODULE: ./node_modules/antd/es/select/style/index.js
var select_style = __webpack_require__("OaEy");
// EXTERNAL MODULE: ./node_modules/antd/es/select/index.js + 45 modules
var es_select = __webpack_require__("2fM7");
// CONCATENATED MODULE: ./node_modules/@ant-design/icons-svg/es/asn/LeftOutlined.js
// This icon file is generated automatically.
var LeftOutlined_LeftOutlined = { "icon": { "tag": "svg", "attrs": { "viewBox": "64 64 896 896", "focusable": "false" }, "children": [{ "tag": "path", "attrs": { "d": "M724 218.3V141c0-6.7-7.7-10.4-12.9-6.3L260.3 486.8a31.86 31.86 0 000 50.3l450.8 352.1c5.3 4.1 12.9.4 12.9-6.3v-77.3c0-4.9-2.3-9.6-6.1-12.6l-360-281 360-281.1c3.8-3 6.1-7.7 6.1-12.6z" } }] }, "name": "left", "theme": "outlined" };
/* harmony default export */ var asn_LeftOutlined = (LeftOutlined_LeftOutlined);
// CONCATENATED MODULE: ./node_modules/@ant-design/icons/es/icons/LeftOutlined.js
// GENERATE BY ./scripts/generate.ts
// DON NOT EDIT IT MANUALLY
var icons_LeftOutlined_LeftOutlined = function LeftOutlined(props, ref) {
return /*#__PURE__*/react["createElement"](AntdIcon["a" /* default */], Object(esm_objectSpread2["a" /* default */])(Object(esm_objectSpread2["a" /* default */])({}, props), {}, {
ref: ref,
icon: asn_LeftOutlined
}));
};
icons_LeftOutlined_LeftOutlined.displayName = 'LeftOutlined';
/* harmony default export */ var icons_LeftOutlined = (/*#__PURE__*/react["forwardRef"](icons_LeftOutlined_LeftOutlined));
// CONCATENATED MODULE: ./node_modules/@ant-design/icons-svg/es/asn/RightOutlined.js
// This icon file is generated automatically.
var RightOutlined_RightOutlined = { "icon": { "tag": "svg", "attrs": { "viewBox": "64 64 896 896", "focusable": "false" }, "children": [{ "tag": "path", "attrs": { "d": "M765.7 486.8L314.9 134.7A7.97 7.97 0 00302 141v77.3c0 4.9 2.3 9.6 6.1 12.6l360 281.1-360 281.1c-3.9 3-6.1 7.7-6.1 12.6V883c0 6.7 7.7 10.4 12.9 6.3l450.8-352.1a31.96 31.96 0 000-50.4z" } }] }, "name": "right", "theme": "outlined" };
/* harmony default export */ var asn_RightOutlined = (RightOutlined_RightOutlined);
// CONCATENATED MODULE: ./node_modules/@ant-design/icons/es/icons/RightOutlined.js
// GENERATE BY ./scripts/generate.ts
// DON NOT EDIT IT MANUALLY
var icons_RightOutlined_RightOutlined = function RightOutlined(props, ref) {
return /*#__PURE__*/react["createElement"](AntdIcon["a" /* default */], Object(esm_objectSpread2["a" /* default */])(Object(esm_objectSpread2["a" /* default */])({}, props), {}, {
ref: ref,
icon: asn_RightOutlined
}));
};
icons_RightOutlined_RightOutlined.displayName = 'RightOutlined';
/* harmony default export */ var icons_RightOutlined = (/*#__PURE__*/react["forwardRef"](icons_RightOutlined_RightOutlined));
// CONCATENATED MODULE: ./src/pages/Competitions/Detail/Competitionbonus.tsx
//代金劵
var Option = es_select["a" /* default */].Option;
function Bonus(_ref) {
var rewarddata = _ref.rewarddata,
getlistdatas = _ref.getlistdatas,
is_signed = _ref.is_signed,
dispatch = _ref.dispatch,
userlist = _ref.userlist;
var Carousels = Object(react["useRef"])(null);
var _useState = Object(react["useState"])(false),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
isshow = _useState2[0],
SetIsshow = _useState2[1];
var _useState3 = Object(react["useState"])(undefined),
_useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
className = _useState4[0],
SetClassname = _useState4[1];
var _useState5 = Object(react["useState"])(''),
_useState6 = Object(slicedToArray["a" /* default */])(_useState5, 2),
id = _useState6[0],
SetId = _useState6[1];
var _useState7 = Object(react["useState"])(undefined),
_useState8 = Object(slicedToArray["a" /* default */])(_useState7, 2),
name = _useState8[0],
SetName = _useState8[1];
var _useState9 = Object(react["useState"])(undefined),
_useState10 = Object(slicedToArray["a" /* default */])(_useState9, 2),
email = _useState10[0],
SetEmail = _useState10[1];
var _useState11 = Object(react["useState"])(undefined),
_useState12 = Object(slicedToArray["a" /* default */])(_useState11, 2),
phone = _useState12[0],
SetPhone = _useState12[1];
function receive(_x) {
return _receive.apply(this, arguments);
}
function _receive() {
_receive = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee(item) {
var result;
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (!item.user_received) {
_context.next = 3;
break;
}
window.open(item.click_info);
return _context.abrupt("return");
case 3:
if (Object(verifyLogin["c" /* handleVerifyLogin */])(dispatch)) {
_context.next = 5;
break;
}
return _context.abrupt("return");
case 5:
if (!(is_signed === false)) {
_context.next = 8;
break;
}
es_message["b" /* default */].info('您尚未报名参赛,请报名参赛后领取');
return _context.abrupt("return");
case 8:
if (!(item.click_event === "Pop")) {
_context.next = 14;
break;
}
SetId(item.id);
SetIsshow(true);
return _context.abrupt("return");
case 14:
SetClassname(undefined);
case 15:
_context.next = 17;
return dispatch({
type: 'competitions/Reward',
payload: {
competition_module_setting_id: item.id
}
});
case 17:
result = _context.sent;
if (result && result.status === 0) {
getlistdatas();
if (item.click_event === "Link") {
es_message["b" /* default */].info('领取成功');
window.open(item.click_info);
} else {
es_message["b" /* default */].info(item.click_info);
}
}
case 19:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return _receive.apply(this, arguments);
}
function submitreceive() {
return _submitreceive.apply(this, arguments);
}
function _submitreceive() {
_submitreceive = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee2() {
var result;
return regenerator_default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (!(userlist && !userlist.real_name)) {
_context2.next = 4;
break;
}
if (name) {
_context2.next = 4;
break;
}
es_message["b" /* default */].info('姓名不能为空');
return _context2.abrupt("return");
case 4:
if (!(userlist && !userlist.email)) {
_context2.next = 8;
break;
}
if (email) {
_context2.next = 8;
break;
}
es_message["b" /* default */].info('邮箱不能为空');
return _context2.abrupt("return");
case 8:
if (!(userlist && !userlist.phone)) {
_context2.next = 12;
break;
}
if (phone) {
_context2.next = 12;
break;
}
es_message["b" /* default */].info('手机号码不能为空');
return _context2.abrupt("return");
case 12:
if (className) {
_context2.next = 15;
break;
}
es_message["b" /* default */].info('请选择你的年级');
return _context2.abrupt("return");
case 15:
_context2.next = 17;
return dispatch({
type: 'competitions/Reward',
payload: {
competition_module_setting_id: id,
className: className,
name: name,
mail: email,
phone: phone
}
});
case 17:
result = _context2.sent;
if (result && result.status === 0) {
SetIsshow(false);
getlistdatas();
es_message["b" /* default */].info('HCIA认证考试代金劵将由Educoder平台统一发放请及时关注邮箱或站内短信查收');
}
case 19:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
return _submitreceive.apply(this, arguments);
}
return /*#__PURE__*/react_default.a.createElement("div", null, /*#__PURE__*/react_default.a.createElement(es_modal["a" /* default */], {
visible: isshow,
title: '完善信息',
onCancel: function onCancel() {
return SetIsshow(false);
},
onOk: function onOk() {
submitreceive();
}
}, /*#__PURE__*/react_default.a.createElement("p", null, "\u60A8\u7684\u59D3\u540D\uFF1A", /*#__PURE__*/react_default.a.createElement(es_input["a" /* default */], {
className: userlist && userlist.real_name ? '' : Detailmodules_default.a.bkfff,
style: {
width: '300px',
marginLeft: '14px',
background: userlist && userlist.phone ? '' : '#ffffff!important'
},
value: userlist && userlist.real_name || name,
disabled: userlist && userlist.real_name || false,
onChange: function onChange(e) {
return SetName(e.target.value);
}
})), /*#__PURE__*/react_default.a.createElement("p", {
style: {
marginTop: '1em'
}
}, "\u60A8\u7684\u90AE\u7BB1\uFF1A", /*#__PURE__*/react_default.a.createElement(es_input["a" /* default */], {
className: userlist && userlist.email ? '' : "bkfff",
style: {
width: '300px',
marginLeft: '14px',
background: userlist && userlist.phone ? '' : '#ffffff!important'
},
value: userlist && userlist.email || email,
disabled: userlist && userlist.email || false,
onChange: function onChange(e) {
return SetEmail(e.target.value);
}
})), /*#__PURE__*/react_default.a.createElement("p", {
style: {
marginTop: '1em'
}
}, "\u60A8\u7684\u624B\u673A\u53F7\uFF1A", /*#__PURE__*/react_default.a.createElement(es_input["a" /* default */], {
style: {
width: '300px'
},
className: userlist && userlist.phone ? '' : "bkfff",
value: userlist && userlist.phone || phone,
disabled: userlist && userlist.phone || false,
onChange: function onChange(e) {
return SetPhone(e.target.value);
}
})), "\u60A8\u7684\u5E74\u7EA7\uFF1A", /*#__PURE__*/react_default.a.createElement(es_select["a" /* default */], {
style: {
width: '300px',
marginTop: '1em',
marginLeft: '14px'
},
onChange: function onChange(e) {
SetClassname(e);
}
}, /*#__PURE__*/react_default.a.createElement(Option, {
value: "\u5927\u4E00"
}, "\u5927\u4E00"), /*#__PURE__*/react_default.a.createElement(Option, {
value: "\u5927\u4E8C"
}, "\u5927\u4E8C"), /*#__PURE__*/react_default.a.createElement(Option, {
value: "\u5927\u4E09"
}, "\u5927\u4E09"), /*#__PURE__*/react_default.a.createElement(Option, {
value: "\u5927\u56DB"
}, "\u5927\u56DB"), /*#__PURE__*/react_default.a.createElement(Option, {
value: "\u5927\u4E94"
}, "\u5927\u4E94"), /*#__PURE__*/react_default.a.createElement(Option, {
value: "\u7855\u4E00"
}, "\u7855\u4E00"), /*#__PURE__*/react_default.a.createElement(Option, {
value: "\u7855\u4E8C"
}, "\u7855\u4E8C"), /*#__PURE__*/react_default.a.createElement(Option, {
value: "\u7855\u4E09"
}, "\u7855\u4E09"), /*#__PURE__*/react_default.a.createElement(Option, {
value: "\u535A\u4E00"
}, "\u535A\u4E00"), /*#__PURE__*/react_default.a.createElement(Option, {
value: "\u535A\u4E8C"
}, "\u535A\u4E8C"), /*#__PURE__*/react_default.a.createElement(Option, {
value: "\u535A\u4E09"
}, "\u535A\u4E09"), /*#__PURE__*/react_default.a.createElement(Option, {
value: "\u535A\u56DB"
}, "\u535A\u56DB"), /*#__PURE__*/react_default.a.createElement(Option, {
value: "\u535A\u4E94"
}, "\u535A\u4E94")), /*#__PURE__*/react_default.a.createElement("p", {
style: {
marginTop: '1em'
}
}, "\u63D0\u9192\uFF1A\u5982\u65E0\u534E\u4E3A\u4E91\u8D26\u53F7\uFF0C\u8BF7\u5C3D\u5FEB\u6CE8\u518C\u534E\u4E3A\u4E91\uFF01")), rewarddata && rewarddata.length > 3 ? /*#__PURE__*/react_default.a.createElement("div", {
style: {
position: 'relative',
marginBottom: '10px',
marginTop: '10px'
}
}, /*#__PURE__*/react_default.a.createElement("span", {
className: Detailmodules_default.a.spanprev,
onClick: function onClick() {
Carousels.current.prev();
}
}, /*#__PURE__*/react_default.a.createElement(icons_LeftOutlined, {
style: {
color: '#fff',
fontSize: '20px',
marginLeft: "15px"
}
})), /*#__PURE__*/react_default.a.createElement(carousel["a" /* default */], {
ref: Carousels,
className: Detailmodules_default.a.divwidth,
slidesToShow: 3,
slidesToScroll: 1
}, rewarddata && rewarddata.map(function (item, index) {
return /*#__PURE__*/react_default.a.createElement("div", {
style: {
textAlign: 'center',
position: 'relative'
}
}, /*#__PURE__*/react_default.a.createElement("img", {
src: env["a" /* default */].IMG_SERVER + "/".concat(item.image_url)
}), item.user_received === false || item.click_event === "Link" ? /*#__PURE__*/react_default.a.createElement("p", {
className: Detailmodules_default.a.receiveclick,
onClick: function onClick() {
return receive(item);
}
}, "\u70B9\u51FB\u9886\u53D6") : /*#__PURE__*/react_default.a.createElement("p", {
className: Detailmodules_default.a.receivealready
}, "\u5DF2\u7ECF\u9886\u53D6"));
})), /*#__PURE__*/react_default.a.createElement("span", {
className: Detailmodules_default.a.spannext,
onClick: function onClick() {
Carousels.current.next();
}
}, /*#__PURE__*/react_default.a.createElement(icons_RightOutlined, {
style: {
color: '#fff',
fontSize: '20px',
marginLeft: "5px"
}
}))) : /*#__PURE__*/react_default.a.createElement("div", {
className: Detailmodules_default.a.divwidth,
style: {
justifyContent: 'space-around',
marginBottom: '10px',
marginTop: '10px'
}
}, rewarddata && rewarddata.map(function (item, index) {
return /*#__PURE__*/react_default.a.createElement("div", {
style: {
textAlign: 'center',
position: 'relative'
}
}, /*#__PURE__*/react_default.a.createElement("img", {
src: env["a" /* default */].IMG_SERVER + "/".concat(item.image_url)
}), item.user_received === false || item.click_event === "Link" ? /*#__PURE__*/react_default.a.createElement("p", {
className: Detailmodules_default.a.receiveclick,
onClick: function onClick() {
return receive(item);
}
}, "\u70B9\u51FB\u9886\u53D6") : /*#__PURE__*/react_default.a.createElement("p", {
className: Detailmodules_default.a.receivealready
}, "\u5DF2\u7ECF\u9886\u53D6"));
})));
}
/* harmony default export */ var Competitionbonus = (Bonus);
// CONCATENATED MODULE: ./src/pages/Competitions/Detail/SeeItem.tsx
//代金劵
var SeeItem_SeeItem = function SeeItem(_ref, ref) {
var StaffDetail = _ref.StaffDetail,
HeaderDetail = _ref.HeaderDetail,
ItemData = _ref.ItemData,
setIssee = _ref.setIssee,
ModelType = _ref.ModelType,
dispatch = _ref.dispatch,
userinfo = _ref.userinfo,
Editable = _ref.Editable;
var _useState = Object(react["useState"])(false),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
visible = _useState2[0],
setVisible = _useState2[1];
var _useState3 = Object(react["useState"])([]),
_useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
fileList = _useState4[0],
setFileList = _useState4[1];
var _useState5 = Object(react["useState"])(''),
_useState6 = Object(slicedToArray["a" /* default */])(_useState5, 2),
fileId = _useState6[0],
setFileId = _useState6[1];
var _useState7 = Object(react["useState"])(''),
_useState8 = Object(slicedToArray["a" /* default */])(_useState7, 2),
text = _useState8[0],
setText = _useState8[1]; // const [disabled, setDisable] = useState(false)
var _useState9 = Object(react["useState"])(false),
_useState10 = Object(slicedToArray["a" /* default */])(_useState9, 2),
loading = _useState10[0],
setLoading = _useState10[1];
var _useParams = Object(react_router["l" /* useParams */])(),
identifier = _useParams.identifier;
var enrolled = Object(react["useRef"])(null);
var dom = Object(react["useRef"])(null);
enrolled.current = StaffDetail === null || StaffDetail === void 0 ? void 0 : StaffDetail.enrolled;
Object(react["useEffect"])(function () {
var _dom$current;
(_dom$current = dom.current) === null || _dom$current === void 0 ? void 0 : _dom$current.addEventListener("click", modal);
return function () {
var _dom$current2;
(_dom$current2 = dom.current) === null || _dom$current2 === void 0 ? void 0 : _dom$current2.removeEventListener("click", modal);
};
}, []); // useEffect(() => {
// if (visible || fileList.length) {
// setDisable(true)
// }
// }, [visible])
var modal = function modal(e) {
var _e$target;
// 检查事件源e.targe是否为Li
if ((e === null || e === void 0 ? void 0 : (_e$target = e.target) === null || _e$target === void 0 ? void 0 : _e$target.id) === 'modal-upload') {
if (!Object(verifyLogin["b" /* handleVerify */])(dispatch)) {
return;
}
if (!enrolled.current) {
es_modal["a" /* default */].info({
title: '提示',
centered: true,
okText: '我知道了',
content: '请先报名,再提交作品'
});
return;
}
setVisible(true);
}
};
Object(react["useEffect"])(function () {
if (HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.upload_file) {
var _HeaderDetail$upload_, _HeaderDetail$upload_2, _HeaderDetail$upload_3;
setFileList([{
name: HeaderDetail === null || HeaderDetail === void 0 ? void 0 : (_HeaderDetail$upload_ = HeaderDetail.upload_file) === null || _HeaderDetail$upload_ === void 0 ? void 0 : _HeaderDetail$upload_.title,
status: 'done',
uid: '123456789'
}]);
setText(HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.upload_file_url);
setFileId(HeaderDetail === null || HeaderDetail === void 0 ? void 0 : (_HeaderDetail$upload_2 = HeaderDetail.upload_file) === null || _HeaderDetail$upload_2 === void 0 ? void 0 : (_HeaderDetail$upload_3 = _HeaderDetail$upload_2.url) === null || _HeaderDetail$upload_3 === void 0 ? void 0 : _HeaderDetail$upload_3.split('/')[3]);
}
}, [HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.upload_file]);
var uploadProps = {
name: 'file',
multiple: false,
withCredentials: true,
// accept: ".doc, .docx, .pdf",
// action: '/api/attachments.json',
action: env["a" /* default */].API_SERVER + '/api/attachments.json',
showUploadList: {
showRemoveIcon: false
},
fileList: fileList,
onChange: function onChange(info) {
var status = info.file.status;
var newFileList = [Object(objectSpread2["a" /* default */])({}, info.file)];
setFileList(newFileList);
if (info.file.status === 'uploading') {
setLoading(true);
}
if (status === 'done') {
var _newFileList$, _newFileList$$respons;
setFileId((_newFileList$ = newFileList[0]) === null || _newFileList$ === void 0 ? void 0 : (_newFileList$$respons = _newFileList$.response) === null || _newFileList$$respons === void 0 ? void 0 : _newFileList$$respons.id);
setLoading(false); // setDisable(false)
}
if (status === 'error') {
setFileList([]);
setLoading(false);
}
},
beforeUpload: function beforeUpload(file) {
var isLt10M = file.size / 1024 / 1024 < 1000;
if (!isLt10M) {
es_message["b" /* default */].info("文件大小必须小于1000MB");
return Promise.reject();
} // if (!/\.(doc|docx|pdf|DOC|DOCX|PDF)$/.test(file.name)) {
// message.warn('只能上传Word或PDF文件')
// return Promise.reject();
// }
return Promise.resolve();
}
};
var handleVisible = function handleVisible() {
setVisible(true);
};
Object(react["useImperativeHandle"])(ref, function () {
return {
handleVisible: handleVisible
};
});
return /*#__PURE__*/react_default.a.createElement("div", {
ref: dom
}, ModelType === "reward" ? /*#__PURE__*/react_default.a.createElement(Competitionbonus, {
userlist: userinfo,
dispatch: dispatch,
rewarddata: ItemData.reward_setting,
is_signed: ItemData.is_signed
}) : null, /*#__PURE__*/react_default.a.createElement("div", {
style: {
textAlign: 'right'
}
}, ((userinfo === null || userinfo === void 0 ? void 0 : userinfo.admin) || (userinfo === null || userinfo === void 0 ? void 0 : userinfo.business) || Editable) && /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
onClick: function onClick() {
return setIssee(false);
}
}, "\u7F16\u8F91")), /*#__PURE__*/react_default.a.createElement(RenderHtml["a" /* default */], {
value: ItemData.md_content
}), ItemData && ItemData.attachments && ItemData.attachments.map(function (item, index) {
return /*#__PURE__*/react_default.a.createElement("div", null, /*#__PURE__*/react_default.a.createElement("a", {
href: (env["a" /* default */] === null || env["a" /* default */] === void 0 ? void 0 : env["a" /* default */].API_SERVER) + item.url,
target: "_self",
download: item.title
}, /*#__PURE__*/react_default.a.createElement("i", {
style: {
color: '#29BD8B'
},
className: "font-14 color-green iconfont icon-fujian mr8"
}), /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#000000'
}
}, item.title), /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#000000',
marginLeft: '10px'
}
}, item.filesize)));
}), /*#__PURE__*/react_default.a.createElement(es_modal["a" /* default */], {
centered: true,
title: "\u4E0A\u4F20\u4F5C\u54C1",
visible: visible,
okText: "\u63D0\u4EA4\u4F5C\u54C1",
cancelText: "\u53D6\u6D88",
confirmLoading: loading,
onCancel: function onCancel() {
return setVisible(false);
},
onOk: /*#__PURE__*/Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee() {
var res;
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (!(!fileId && !text)) {
_context.next = 3;
break;
}
setVisible(false);
return _context.abrupt("return");
case 3:
// if (disabled) {
// setVisible(false)
// return;
// }
setLoading(true);
_context.next = 6;
return Object(fetch["a" /* default */])("/api/competitions/".concat(identifier, "/upload_file.json"), {
method: 'post',
body: {
attachment_id: fileId,
upload_file_url: text
}
});
case 6:
res = _context.sent;
if (res.status === 0) {
setVisible(false);
setLoading(false);
}
case 8:
case "end":
return _context.stop();
}
}
}, _callee);
}))
}, /*#__PURE__*/react_default.a.createElement("div", null, /*#__PURE__*/react_default.a.createElement(es_row["a" /* default */], {
align: "middle",
className: "mb20"
}, /*#__PURE__*/react_default.a.createElement("span", null, "\u4F5C\u54C1\u94FE\u63A5\uFF1A"), /*#__PURE__*/react_default.a.createElement(es_input["a" /* default */], {
style: {
width: 416
},
value: text,
onChange: function onChange(e) {
var _e$target2;
return setText((_e$target2 = e.target) === null || _e$target2 === void 0 ? void 0 : _e$target2.value);
}
})), /*#__PURE__*/react_default.a.createElement(es_row["a" /* default */], {
align: "top"
}, /*#__PURE__*/react_default.a.createElement("span", {
style: {
lineHeight: '28px'
}
}, "\u4F5C\u54C1\u6587\u4EF6\uFF1A"), /*#__PURE__*/react_default.a.createElement(es_upload, uploadProps, /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
type: "primary",
className: "mb10"
}, "\u4E0A\u4F20\u4F5C\u54C1"))))));
};
/* harmony default export */ var Detail_SeeItem = (/*#__PURE__*/Object(react["forwardRef"])(SeeItem_SeeItem));
// 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/defineProperty.js
var esm_defineProperty = __webpack_require__("jrin");
// EXTERNAL MODULE: ./node_modules/codemirror/lib/codemirror.js
var codemirror = __webpack_require__("VrN/");
var codemirror_default = /*#__PURE__*/__webpack_require__.n(codemirror);
// EXTERNAL MODULE: ./node_modules/resize-observer-polyfill/dist/ResizeObserver.es.js
var ResizeObserver_es = __webpack_require__("bdgK");
// EXTERNAL MODULE: ./node_modules/codemirror/lib/codemirror.css
var lib_codemirror = __webpack_require__("p77/");
// EXTERNAL MODULE: ./node_modules/codemirror/addon/edit/closetag.js
var closetag = __webpack_require__("Bd2K");
// EXTERNAL MODULE: ./node_modules/codemirror/addon/edit/closebrackets.js
var closebrackets = __webpack_require__("ELLl");
// EXTERNAL MODULE: ./node_modules/codemirror/addon/display/placeholder.js
var display_placeholder = __webpack_require__("19Vz");
// EXTERNAL MODULE: ./node_modules/codemirror/mode/markdown/markdown.js
var markdown = __webpack_require__("lZu9");
// EXTERNAL MODULE: ./src/components/markdown-editor/index.less
var markdown_editor = __webpack_require__("kSUc");
// EXTERNAL MODULE: ./src/components/markdown-editor/toolbar/index.less
var toolbar = __webpack_require__("dejd");
// EXTERNAL MODULE: ./src/components/markdown-editor/css/iconfont.css
var iconfont = __webpack_require__("C+DQ");
// CONCATENATED MODULE: ./src/components/markdown-editor/toolbar/index.tsx
var DEFAULTICONS = [{
title: '粗体',
icon: 'icon-bold',
actionName: 'bold'
}, {
title: '斜体',
icon: 'icon-italic',
actionName: 'italic'
}, '|', {
title: '无序列表',
icon: 'icon-unorder-list',
actionName: 'list-ul'
}, {
title: '有序列表',
icon: 'icon-order-list',
actionName: 'list-ol'
}, '|', {
title: '行内代码',
icon: 'icon-code',
actionName: 'code'
}, {
title: '代码块(多语言风格)',
icon: 'icon-file-code',
actionName: 'code-block'
}, {
title: '链接',
icon: 'icon-link',
actionName: 'link'
}, '|', {
title: '行内公式',
icon: 'icon-sum',
actionName: 'inline-latex'
}, {
title: '多行公式',
icon: 'icon-formula',
actionName: 'latex'
}, '|', {
title: '添加图片',
icon: 'icon-picture',
actionName: 'upload-image'
}, {
title: '表格',
icon: 'icon-table',
actionName: 'add-table'
}, '|', {
title: '换行',
icon: 'icon-minus',
actionName: 'line-break'
}, {
title: '清空',
icon: 'icon-eraser',
actionName: 'eraser'
}];
function AButton(_ref) {
var onActionCallback = _ref.onActionCallback,
title = _ref.title,
icon = _ref.icon,
actionName = _ref.actionName,
_ref$className = _ref.className,
className = _ref$className === void 0 ? '' : _ref$className,
children = _ref.children;
function onAction() {
onActionCallback(actionName);
}
return /*#__PURE__*/react_default.a.createElement("a", {
title: title,
className: className,
onClick: onAction
}, /*#__PURE__*/react_default.a.createElement("i", {
className: "md-iconfont ".concat(icon)
}), children);
}
/* harmony default export */ var markdown_editor_toolbar = (function (_ref2) {
var watch = _ref2.watch,
showNullButton = _ref2.showNullButton,
onActionCallback = _ref2.onActionCallback,
fullScreen = _ref2.fullScreen,
insertTemp = _ref2.insertTemp,
hidetoolBar = _ref2.hidetoolBar;
var icons = [].concat(DEFAULTICONS, [{
title: "".concat(watch ? '关闭实时预览' : '开启实时预览'),
icon: "".concat(watch ? 'icon-eye-slash' : 'icon-eye'),
actionName: 'trigger-watch'
}]);
return /*#__PURE__*/react_default.a.createElement("ul", {
className: "markdown-toolbar-container"
}, !hidetoolBar && icons.map(function (item, index) {
return /*#__PURE__*/react_default.a.createElement("li", {
key: index
}, item.actionName ? /*#__PURE__*/react_default.a.createElement(AButton, Object(esm_extends["a" /* default */])({}, item, {
onActionCallback: onActionCallback
})) : /*#__PURE__*/react_default.a.createElement("span", {
className: "v-line"
}));
}), showNullButton ? /*#__PURE__*/react_default.a.createElement("li", null, /*#__PURE__*/react_default.a.createElement(AButton, {
icon: "icon-edit",
className: "btn-null",
title: "\u589E\u52A0\u586B\u7A7A",
actionName: "add-null-ch",
onActionCallback: onActionCallback
}, /*#__PURE__*/react_default.a.createElement("span", {
className: "fill-tip"
}, "\u70B9\u51FB\u63D2\u5165\b\u586B\u7A7A\u9879"))) : null, insertTemp && /*#__PURE__*/react_default.a.createElement("li", null, /*#__PURE__*/react_default.a.createElement(AButton, {
icon: "icon-edit",
className: "btn-null",
title: "\u63D2\u5165\u6A21\u677F",
actionName: "inster-template-".concat(insertTemp),
onActionCallback: onActionCallback
}, /*#__PURE__*/react_default.a.createElement("span", {
className: "fill-tip"
}, "\u63D2\u5165\u6A21\u677F"))), /*#__PURE__*/react_default.a.createElement("li", {
className: "btn-full-screen"
}, /*#__PURE__*/react_default.a.createElement(AButton, {
icon: "".concat(fullScreen ? 'icon-shrink' : 'icon-enlarge'),
title: fullScreen ? '关闭全屏' : '开启全屏',
actionName: "trigger-full-screen",
onActionCallback: onActionCallback
})));
});
// EXTERNAL MODULE: ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/classCallCheck.js
var esm_classCallCheck = __webpack_require__("fWQN");
// EXTERNAL MODULE: ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/createClass.js
var esm_createClass = __webpack_require__("mtLc");
// EXTERNAL MODULE: ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/inherits.js + 1 modules
var esm_inherits = __webpack_require__("yKVA");
// EXTERNAL MODULE: ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/createSuper.js + 5 modules
var esm_createSuper = __webpack_require__("879j");
// EXTERNAL MODULE: ./node_modules/react-dom/index.js
var react_dom = __webpack_require__("i8i4");
// CONCATENATED MODULE: ./src/components/modal.tsx
var modal_Dialog = /*#__PURE__*/function (_React$Component) {
Object(esm_inherits["a" /* default */])(Dialog, _React$Component);
var _super = Object(esm_createSuper["a" /* default */])(Dialog);
function Dialog(props) {
var _this;
Object(esm_classCallCheck["a" /* default */])(this, Dialog);
_this = _super.call(this, props);
var doc = window.document;
_this.node = doc.createElement('div');
doc.body.appendChild(_this.node);
return _this;
}
Object(esm_createClass["a" /* default */])(Dialog, [{
key: "render",
value: function render() {
var children = this.props.children;
return /*#__PURE__*/Object(react_dom["createPortal"])(children, this.node);
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
window.document.body.removeChild(this.node);
}
}]);
return Dialog;
}(react_default.a.Component);
// EXTERNAL MODULE: ./node_modules/antd/es/form/style/index.js
var form_style = __webpack_require__("y8nQ");
// EXTERNAL MODULE: ./node_modules/antd/es/form/index.js + 13 modules
var es_form = __webpack_require__("Vl3Y");
// CONCATENATED MODULE: ./src/components/markdown-editor/link/index.tsx
var formItemLayout = {
labelCol: {
span: 4
},
wrapperCol: {
span: 20
}
};
/* harmony default export */ var markdown_editor_link = (function (_ref) {
var callback = _ref.callback,
onCancel = _ref.onCancel;
function onSubmit(values) {
callback(values);
}
return /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */], Object(esm_extends["a" /* default */])({}, formItemLayout, {
initialValues: {
link: 'http://',
title: ''
},
className: "link-panel",
onFinish: onSubmit
}), /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
label: "\u94FE\u63A5\u5730\u5740",
name: "link",
rules: [{
required: true,
message: '请输入链接地址'
}]
}, /*#__PURE__*/react_default.a.createElement(es_input["a" /* default */], null)), /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
label: "\u94FE\u63A5\u6807\u9898",
name: "title",
rules: [{
required: true,
message: '请输入链接标题'
}]
}, /*#__PURE__*/react_default.a.createElement(es_input["a" /* default */], null)), /*#__PURE__*/react_default.a.createElement("div", {
className: "flex-container flex-end"
}, /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
type: "primary",
htmlType: "submit",
style: {
marginRight: 10
}
}, "\u786E\u5B9A"), /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
type: "ghost",
onClick: onCancel
}, "\u53D6\u6D88")));
});
// EXTERNAL MODULE: ./node_modules/codemirror/theme/blackboard.css
var blackboard = __webpack_require__("c5Ni");
// CONCATENATED MODULE: ./src/components/markdown-editor/code-block/index.tsx
var code_block_Option = es_select["a" /* default */].Option; //https://github.com/codemirror/CodeMirror/issues/4838
var code_block_formItemLayout = {
labelCol: {
span: 4
},
wrapperCol: {
span: 20
}
};
var LanguageDesc = {
asp: ['ASP', 'vbscript'],
actionscript: ['ActionScript(3.0)/Flash/Flex', 'clike'],
bash: ['Bash/Bat', 'shell'],
css: ['CSS', 'css'],
c: ['C', 'clike'],
cpp: ['C++', 'clike'],
csharp: ['C#', 'clike'],
coffeescript: ['CoffeeScript', 'coffeescript'],
d: ['D', 'd'],
dart: ['Dart', 'dart'],
delphi: ['Delphi/Pascal', 'pascal'],
erlang: ['Erlang', 'erlang'],
go: ['Golang', 'go'],
groovy: ['Groovy', 'groovy'],
html: ['HTML', 'text/html'],
java: ['Java', 'clike'],
json: ['JSON', 'text/json'],
javascript: ['Javascript', 'javascript'],
lua: ['Lua', 'lua'],
less: ['LESS', 'css'],
markdown: ['Markdown', 'gfm'],
'objective-c': ['Objective-C', 'clike'],
php: ['PHP', 'php'],
perl: ['Perl', 'perl'],
python: ['Python', 'python'],
r: ['R', 'r'],
rst: ['reStructedText', 'rst'],
ruby: ['Ruby', 'ruby'],
sql: ['SQL', 'sql'],
sass: ['SASS/SCSS', 'sass'],
shell: ['Shell', 'shell'],
scala: ['Scala', 'clike'],
swift: ['Swift', 'clike'],
vb: ['VB/VBScript', 'vb'],
xml: ['XML', 'text/xml'],
yaml: ['YAML', 'yaml']
};
/* harmony default export */ var code_block = (function (_ref) {
var callback = _ref.callback,
onCancel = _ref.onCancel;
var _useState = Object(react["useState"])('python'),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
mode = _useState2[0],
setMode = _useState2[1];
function onSetMode(value) {
setMode(LanguageDesc[value][1]);
}
function onSubmit(values) {
callback(values);
}
return /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */], Object(esm_extends["a" /* default */])({}, code_block_formItemLayout, {
className: "code-block-panel",
initialValues: {
language: 'python',
content: ''
},
onFinish: onSubmit
}), /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
label: "\u4EE3\u7801\u8BED\u8A00",
name: "language"
}, /*#__PURE__*/react_default.a.createElement(es_select["a" /* default */], {
onChange: onSetMode
}, Object.keys(LanguageDesc).map(function (item) {
return /*#__PURE__*/react_default.a.createElement(code_block_Option, {
key: item,
value: item
}, LanguageDesc[item][0]);
}))), /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
label: "\u4EE3\u7801\u5185\u5BB9",
name: "content",
rules: [{
required: true,
message: '请输入代码内容'
}]
}, /*#__PURE__*/react_default.a.createElement(MyCodeMirror, {
mode: mode
})), /*#__PURE__*/react_default.a.createElement("div", {
className: "flex-container flex-end"
}, /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
type: "primary",
htmlType: "submit",
style: {
marginRight: 10
}
}, "\u786E\u5B9A"), /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
type: "ghost",
onClick: onCancel
}, "\u53D6\u6D88")));
});
function MyCodeMirror(_ref2) {
var value = _ref2.value,
onChange = _ref2.onChange,
mode = _ref2.mode,
_ref2$options = _ref2.options,
options = _ref2$options === void 0 ? {} : _ref2$options;
var el = Object(react["useRef"])();
var _useState3 = Object(react["useState"])(),
_useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
cm = _useState4[0],
setCm = _useState4[1];
Object(react["useEffect"])(function () {
if (cm) {
function onChangeHandler(cm) {
var content = cm.getValue();
onChange && onChange(content);
}
cm.on('change', onChangeHandler);
return function () {
cm.off('change', onChangeHandler);
};
}
}, [cm, onChange]);
Object(react["useEffect"])(function () {
if (cm) {
cm.setOption('mode', mode);
}
}, [cm, mode]);
Object(react["useEffect"])(function () {
if (cm) {
if (value !== cm.getValue() || value === '') {
setTimeout(function () {
cm.setValue(value || ' ');
}, 300);
}
}
}, [cm, value]);
Object(react["useEffect"])(function () {
if (el.current && !cm) {
var instance = codemirror_default.a.fromTextArea(el.current, Object(objectSpread2["a" /* default */])({
mode: mode,
lineNumbers: true,
lineWrapping: true,
autoCloseBrackets: true,
tabSize: 4,
autofocus: true,
autoCloseTags: true,
matchBrackets: true,
styleActiveLine: true
}, options));
setCm(instance);
}
}, [el.current, cm]);
return /*#__PURE__*/react_default.a.createElement("div", {
className: "my-codemirror-container"
}, /*#__PURE__*/react_default.a.createElement("textarea", {
ref: el
}));
}
// EXTERNAL MODULE: ./src/components/markdown-editor/upload-image/index.less
var upload_image = __webpack_require__("HmJG");
// CONCATENATED MODULE: ./src/pages/tasks/util.js
function isCompileOk(rs) {
var flag = true;
if (rs.length > 0) {
for (var i = 0; i < rs.length; i++) {
if (rs[i].compile_success == 0 || !rs[i].compile_success) {
flag = false;
break;
}
}
} else {
flag = false;
}
return flag;
}
function getTreeData(data) {
var parentKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var result = [];
for (var i = 0; i < data.length; i++) {
var item = data[i];
var key = parentKey ? "".concat(parentKey, "/").concat(item.name) : "".concat(item.name);
result.push({
title: item.name,
isLeaf: item.type === 'tree' ? false : true,
key: key
});
}
return result;
}
function processTreeData(repos, key, newData) {
for (var i = 0; i < repos.length; i++) {
var item = repos[i];
if (item.key === key) {
item.children = newData;
break;
}
if (item.children) {
processTreeData(item.children, key, newData);
}
}
return repos;
}
function debounce(func, wait, immediate) {
var timeout;
return function () {
var context = this,
args = arguments;
var later = function later() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
var isProd = true;
var apiPref = env["a" /* default */].API_SERVER; // export const isProd =
// window.location.href.indexOf('test-') > 0 ||
// window.location.href.indexOf('localhost') > 0
// ? false
// : true;
// export const apiPref = isProd
// ? 'https://www.educoder.net'
// : 'https://test-newweb.educoder.net';
// CONCATENATED MODULE: ./src/components/markdown-editor/upload-image/index.tsx
var useForm = es_form["a" /* default */].useForm;
var upload_image_style = {
width: 280,
marginRight: 10
};
var upload_image_formItemLayout = {
labelCol: {
span: 5
},
wrapperCol: {
span: 19
}
};
/* harmony default export */ var markdown_editor_upload_image = (function (_ref) {
var callback = _ref.callback,
onCancel = _ref.onCancel;
var _useForm = useForm(),
_useForm2 = Object(slicedToArray["a" /* default */])(_useForm, 1),
form = _useForm2[0];
function onSubmit(values) {
callback(values);
}
function onAddUrl(data, file) {
form.setFieldsValue({
src: "/api/attachments/".concat(data.id),
type: file.type
});
}
function onFileChange(e) {
var file = e.target.files[0];
uploadImage(file, onAddUrl);
}
return /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */], Object(esm_extends["a" /* default */])({
form: form
}, upload_image_formItemLayout, {
className: "upload-image-panel",
onFinish: onSubmit
}), /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
label: "\u56FE\u7247\u5730\u5740",
required: true
}, /*#__PURE__*/react_default.a.createElement("div", {
className: "flex-container"
}, /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
noStyle: true,
name: "src",
rules: [{
required: true,
message: '请输入图片地址'
}]
}, /*#__PURE__*/react_default.a.createElement(es_input["a" /* default */], {
style: upload_image_style
})), /*#__PURE__*/react_default.a.createElement(UploadButton, {
onFileChange: onFileChange
}))), /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
label: "\u56FE\u7247\u63CF\u8FF0",
name: "alt",
rules: [{
required: true,
message: '请输入图片描述'
}]
}, /*#__PURE__*/react_default.a.createElement(es_input["a" /* default */], {
style: {
width: 264
}
})), /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
style: {
textAlign: "right"
}
}, /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
type: "primary",
htmlType: "submit",
style: {
marginRight: 10
}
}, "\u786E\u5B9A"), /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
type: "ghost",
onClick: onCancel
}, "\u53D6\u6D88")));
});
function UploadButton(_ref2) {
var onFileChange = _ref2.onFileChange;
return /*#__PURE__*/react_default.a.createElement("a", {
className: "upload-button"
}, "\u672C\u5730\u4E0A\u4F20", /*#__PURE__*/react_default.a.createElement("input", {
type: "file",
onChange: onFileChange
}));
}
function uploadImage(file, callback) {
if (!file) {
throw new String('没有文件');
return;
}
var formData = new FormData();
formData.append('editormd-image-file', file);
formData.append('file_param_name', 'editormd-image-file');
formData.append('byxhr', 'true');
var xhr = new window.XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener('load', function (response) {
callback(JSON.parse(response.target.responseText), file);
}, false);
xhr.addEventListener('error', function (error) {
console.error(error);
}, false);
xhr.open('POST', "".concat(apiPref, "/api/attachments.json"));
xhr.send(formData);
}
// EXTERNAL MODULE: ./node_modules/antd/es/input-number/style/index.less
var input_number_style = __webpack_require__("QbM5");
// CONCATENATED MODULE: ./node_modules/antd/es/input-number/style/index.js
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js
var esm_objectWithoutProperties = __webpack_require__("Ff2n");
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/defineProperty.js
var helpers_esm_defineProperty = __webpack_require__("rePB");
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/classCallCheck.js
var helpers_esm_classCallCheck = __webpack_require__("1OyB");
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/createClass.js
var helpers_esm_createClass = __webpack_require__("vuIU");
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/inherits.js
var helpers_esm_inherits = __webpack_require__("Ji7U");
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js
var possibleConstructorReturn = __webpack_require__("md7G");
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js
var getPrototypeOf = __webpack_require__("foSv");
// EXTERNAL MODULE: ./node_modules/rc-util/es/KeyCode.js
var KeyCode = __webpack_require__("4IlW");
// CONCATENATED MODULE: ./node_modules/rc-input-number/es/InputNumber.js
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) { Object(helpers_esm_defineProperty["a" /* default */])(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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = Object(getPrototypeOf["a" /* default */])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = Object(getPrototypeOf["a" /* default */])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return Object(possibleConstructorReturn["a" /* default */])(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
/* eslint-disable react/prop-types */
function noop() {}
function preventDefault(e) {
e.preventDefault();
}
var defaultParser = function defaultParser(input) {
return input.replace(/[^\w.-]+/g, '');
};
/**
* When click and hold on a button - the speed of auto changin the value.
*/
var SPEED = 200;
/**
* When click and hold on a button - the delay before auto changin the value.
*/
var DELAY = 600;
/**
* Max Safe Integer -- on IE this is not available, so manually set the number in that case.
* The reason this is used, instead of Infinity is because numbers above the MSI are unstable
*/
var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1;
var isValidProps = function isValidProps(value) {
return value !== undefined && value !== null;
};
var isEqual = function isEqual(oldValue, newValue) {
return newValue === oldValue || typeof newValue === 'number' && typeof oldValue === 'number' && isNaN(newValue) && isNaN(oldValue);
};
var InputNumber_InputNumber = /*#__PURE__*/function (_React$Component) {
Object(helpers_esm_inherits["a" /* default */])(InputNumber, _React$Component);
var _super = _createSuper(InputNumber);
function InputNumber(props) {
var _this;
Object(helpers_esm_classCallCheck["a" /* default */])(this, InputNumber);
_this = _super.call(this, props);
_this.onKeyDown = function (e) {
var _this$props = _this.props,
onKeyDown = _this$props.onKeyDown,
onPressEnter = _this$props.onPressEnter;
if (e.keyCode === KeyCode["a" /* default */].UP) {
var ratio = _this.getRatio(e);
_this.up(e, ratio, null);
_this.stop();
} else if (e.keyCode === KeyCode["a" /* default */].DOWN) {
var _ratio = _this.getRatio(e);
_this.down(e, _ratio, null);
_this.stop();
} else if (e.keyCode === KeyCode["a" /* default */].ENTER && onPressEnter) {
onPressEnter(e);
} // Trigger user key down
_this.recordCursorPosition();
_this.lastKeyCode = e.keyCode;
if (onKeyDown) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
onKeyDown.apply(void 0, [e].concat(args));
}
};
_this.onKeyUp = function (e) {
var onKeyUp = _this.props.onKeyUp;
_this.stop();
_this.recordCursorPosition(); // Trigger user key up
if (onKeyUp) {
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
onKeyUp.apply(void 0, [e].concat(args));
}
};
_this.onChange = function (e) {
var onChange = _this.props.onChange;
if (_this.state.focused) {
_this.inputting = true;
}
_this.rawInput = _this.props.parser(_this.getValueFromEvent(e));
_this.setState({
inputValue: _this.rawInput
});
onChange(_this.toNumber(_this.rawInput)); // valid number or invalid string
};
_this.onMouseUp = function () {
var onMouseUp = _this.props.onMouseUp;
_this.recordCursorPosition();
if (onMouseUp) {
onMouseUp.apply(void 0, arguments);
}
};
_this.onFocus = function () {
var _this$props2;
_this.setState({
focused: true
});
(_this$props2 = _this.props).onFocus.apply(_this$props2, arguments);
};
_this.onBlur = function () {
var onBlur = _this.props.onBlur;
_this.inputting = false;
_this.setState({
focused: false
});
var value = _this.getCurrentValidValue(_this.state.inputValue);
var newValue = _this.setValue(value, noop);
if (onBlur) {
var originValue = _this.input.value;
var displayValue = _this.getInputDisplayValue({
focus: false,
value: newValue
});
_this.input.value = displayValue ? Number(displayValue) : displayValue;
onBlur.apply(void 0, arguments);
_this.input.value = originValue;
}
};
_this.getRatio = function (e) {
var ratio = 1;
if (e.metaKey || e.ctrlKey) {
ratio = 0.1;
} else if (e.shiftKey) {
ratio = 10;
}
return ratio;
};
_this.getFullNum = function (num) {
if (isNaN(num)) {
return num;
}
if (!/e/i.test(String(num))) {
return num;
}
return Number(num).toFixed(18).replace(/\.?0+$/, '');
};
_this.getPrecision = function (value) {
if (isValidProps(_this.props.precision)) {
return _this.props.precision;
}
var valueString = String(value);
if (valueString.indexOf('e-') >= 0) {
return parseInt(valueString.slice(valueString.indexOf('e-') + 2), 10);
}
var precision = 0;
if (valueString.indexOf('.') >= 0) {
precision = valueString.length - valueString.indexOf('.') - 1;
}
return precision;
};
_this.getInputDisplayValue = function (state) {
var _ref = state || _this.state,
focused = _ref.focused,
inputValue = _ref.inputValue,
value = _ref.value;
var inputDisplayValue;
if (focused) {
inputDisplayValue = inputValue;
} else {
inputDisplayValue = _this.toPrecisionAsStep(value);
}
if (inputDisplayValue === undefined || inputDisplayValue === null) {
inputDisplayValue = '';
}
var inputDisplayValueFormat = _this.formatWrapper(inputDisplayValue);
if (isValidProps(_this.props.decimalSeparator)) {
inputDisplayValueFormat = inputDisplayValueFormat.toString().replace('.', _this.props.decimalSeparator);
}
return inputDisplayValueFormat;
};
_this.recordCursorPosition = function () {
// Record position
try {
_this.cursorStart = _this.input.selectionStart;
_this.cursorEnd = _this.input.selectionEnd;
_this.currentValue = _this.input.value;
_this.cursorBefore = _this.input.value.substring(0, _this.cursorStart);
_this.cursorAfter = _this.input.value.substring(_this.cursorEnd);
} catch (e) {// Fix error in Chrome:
// Failed to read the 'selectionStart' property from 'HTMLInputElement'
// http://stackoverflow.com/q/21177489/3040605
}
};
_this.restoreByAfter = function (str) {
if (str === undefined) return false;
var fullStr = _this.input.value;
var index = fullStr.lastIndexOf(str);
if (index === -1) return false;
var prevCursorPos = _this.cursorBefore.length;
if (_this.lastKeyCode === KeyCode["a" /* default */].DELETE && _this.cursorBefore.charAt(prevCursorPos - 1) === str[0]) {
_this.fixCaret(prevCursorPos, prevCursorPos);
return true;
}
if (index + str.length === fullStr.length) {
_this.fixCaret(index, index);
return true;
}
return false;
};
_this.partRestoreByAfter = function (str) {
if (str === undefined) return false; // For loop from full str to the str with last char to map. e.g. 123
// -> 123
// -> 23
// -> 3
return Array.prototype.some.call(str, function (_, start) {
var partStr = str.substring(start);
return _this.restoreByAfter(partStr);
});
}; // '1.' '1x' 'xx' '' => are not complete numbers
_this.isNotCompleteNumber = function (num) {
return isNaN(num) || num === '' || num === null || num && num.toString().indexOf('.') === num.toString().length - 1;
};
_this.stop = function () {
if (_this.autoStepTimer) {
clearTimeout(_this.autoStepTimer);
}
};
_this.down = function (e, ratio, recursive) {
_this.pressingUpOrDown = true;
_this.step('down', e, ratio, recursive);
};
_this.up = function (e, ratio, recursive) {
_this.pressingUpOrDown = true;
_this.step('up', e, ratio, recursive);
};
_this.saveInput = function (node) {
_this.input = node;
};
var value = props.value;
if (value === undefined) {
value = props.defaultValue;
}
_this.state = {
focused: props.autoFocus
};
var validValue = _this.getValidValue(_this.toNumber(value));
_this.state = _objectSpread(_objectSpread({}, _this.state), {}, {
inputValue: _this.toPrecisionAsStep(validValue),
value: validValue
});
return _this;
}
Object(helpers_esm_createClass["a" /* default */])(InputNumber, [{
key: "componentDidMount",
value: function componentDidMount() {
this.componentDidUpdate(null);
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
var _this$props3 = this.props,
value = _this$props3.value,
onChange = _this$props3.onChange,
max = _this$props3.max,
min = _this$props3.min;
var focused = this.state.focused; // Don't trigger in componentDidMount
if (prevProps) {
if (!isEqual(prevProps.value, value) || !isEqual(prevProps.max, max) || !isEqual(prevProps.min, min)) {
var validValue = focused ? value : this.getValidValue(value);
var nextInputValue;
if (this.pressingUpOrDown) {
nextInputValue = validValue;
} else if (this.inputting) {
nextInputValue = this.rawInput;
} else {
nextInputValue = this.toPrecisionAsStep(validValue);
}
this.setState({
// eslint-disable-line
value: validValue,
inputValue: nextInputValue
});
} // Trigger onChange when max or min change
// https://github.com/ant-design/ant-design/issues/11574
var nextValue = 'value' in this.props ? value : this.state.value; // ref: null < 20 === true
// https://github.com/ant-design/ant-design/issues/14277
if ('max' in this.props && prevProps.max !== max && typeof nextValue === 'number' && nextValue > max && onChange) {
onChange(max);
}
if ('min' in this.props && prevProps.min !== min && typeof nextValue === 'number' && nextValue < min && onChange) {
onChange(min);
}
} // Restore cursor
try {
// Firefox set the input cursor after it get focused.
// This caused that if an input didn't init with the selection,
// set will cause cursor not correct when first focus.
// Safari will focus input if set selection. We need skip this.
if (this.cursorStart !== undefined && this.state.focused) {
// In most cases, the string after cursor is stable.
// We can move the cursor before it
if ( // If not match full str, try to match part of str
!this.partRestoreByAfter(this.cursorAfter) && this.state.value !== this.props.value) {
// If not match any of then, let's just keep the position
// TODO: Logic should not reach here, need check if happens
var pos = this.cursorStart + 1; // If not have last string, just position to the end
if (!this.cursorAfter) {
pos = this.input.value.length;
} else if (this.lastKeyCode === KeyCode["a" /* default */].BACKSPACE) {
pos = this.cursorStart - 1;
} else if (this.lastKeyCode === KeyCode["a" /* default */].DELETE) {
pos = this.cursorStart;
}
this.fixCaret(pos, pos);
} else if (this.currentValue === this.input.value) {
// Handle some special key code
switch (this.lastKeyCode) {
case KeyCode["a" /* default */].BACKSPACE:
this.fixCaret(this.cursorStart - 1, this.cursorStart - 1);
break;
case KeyCode["a" /* default */].DELETE:
this.fixCaret(this.cursorStart + 1, this.cursorStart + 1);
break;
default: // Do nothing
}
}
}
} catch (e) {// Do nothing
} // Reset last key
this.lastKeyCode = null; // pressingUpOrDown is true means that someone just click up or down button
if (!this.pressingUpOrDown) {
return;
}
if (this.props.focusOnUpDown && this.state.focused) {
if (document.activeElement !== this.input) {
this.focus();
}
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.stop();
}
}, {
key: "getCurrentValidValue",
value: function getCurrentValidValue(value) {
var val = value;
if (val === '') {
val = '';
} else if (!this.isNotCompleteNumber(parseFloat(val))) {
val = this.getValidValue(val);
} else {
val = this.state.value;
}
return this.toNumber(val);
}
}, {
key: "getValueFromEvent",
value: function getValueFromEvent(e) {
// optimize for chinese input expierence
// https://github.com/ant-design/ant-design/issues/8196
var value = e.target.value.trim().replace(/。/g, '.');
if (isValidProps(this.props.decimalSeparator)) {
value = value.replace(this.props.decimalSeparator, '.');
}
return value;
}
}, {
key: "getValidValue",
value: function getValidValue(value) {
var min = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.props.min;
var max = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.props.max;
var val = parseFloat(value); // https://github.com/ant-design/ant-design/issues/7358
if (isNaN(val)) {
return value;
}
if (val < min) {
val = min;
}
if (val > max) {
val = max;
}
return val;
}
}, {
key: "setValue",
value: function setValue(v, callback) {
// trigger onChange
var precision = this.props.precision;
var newValue = this.isNotCompleteNumber(parseFloat(v)) ? null : parseFloat(v);
var _this$state$value = this.state.value,
value = _this$state$value === void 0 ? null : _this$state$value;
var _this$state$inputValu = this.state.inputValue,
inputValue = _this$state$inputValu === void 0 ? null : _this$state$inputValu; // https://github.com/ant-design/ant-design/issues/7363
// https://github.com/ant-design/ant-design/issues/16622
var newValueInString = typeof newValue === 'number' ? newValue.toFixed(precision) : "".concat(newValue);
var changed = newValue !== value || newValueInString !== "".concat(inputValue);
if (!('value' in this.props)) {
this.setState({
value: newValue,
inputValue: this.toPrecisionAsStep(v)
}, callback);
} else {
// always set input value same as value
inputValue = this.toPrecisionAsStep(this.state.value);
this.setState({
inputValue: inputValue
}, callback);
}
if (changed) {
this.props.onChange(newValue);
}
return newValue;
} // step={1.0} value={1.51}
// press +
// then value should be 2.51, rather than 2.5
// if this.props.precision is undefined
// https://github.com/react-component/input-number/issues/39
}, {
key: "getMaxPrecision",
value: function getMaxPrecision(currentValue) {
var ratio = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
var _this$props4 = this.props,
precision = _this$props4.precision,
step = _this$props4.step;
if (isValidProps(precision)) {
return precision;
}
var ratioPrecision = this.getPrecision(ratio);
var stepPrecision = this.getPrecision(step);
var currentValuePrecision = this.getPrecision(currentValue);
if (!currentValue) {
return ratioPrecision + stepPrecision;
}
return Math.max(currentValuePrecision, ratioPrecision + stepPrecision);
}
}, {
key: "getPrecisionFactor",
value: function getPrecisionFactor(currentValue) {
var ratio = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
var precision = this.getMaxPrecision(currentValue, ratio);
return Math.pow(10, precision);
}
}, {
key: "focus",
value: function focus() {
this.input.focus();
this.recordCursorPosition();
}
}, {
key: "blur",
value: function blur() {
this.input.blur();
}
}, {
key: "select",
value: function select() {
this.input.select();
}
}, {
key: "formatWrapper",
value: function formatWrapper(num) {
// http://2ality.com/2012/03/signedzero.html
// https://github.com/ant-design/ant-design/issues/9439
if (this.props.formatter) {
return this.props.formatter(num);
}
return num;
}
}, {
key: "toPrecisionAsStep",
value: function toPrecisionAsStep(num) {
if (this.isNotCompleteNumber(num) || num === '') {
return num;
}
var precision = Math.abs(this.getMaxPrecision(num));
if (!isNaN(precision)) {
return Number(num).toFixed(precision);
}
return num.toString();
}
}, {
key: "toNumber",
value: function toNumber(num) {
var precision = this.props.precision;
var focused = this.state.focused; // num.length > 16 => This is to prevent input of large numbers
var numberIsTooLarge = num && num.length > 16 && focused;
if (this.isNotCompleteNumber(num) || numberIsTooLarge) {
return num;
}
if (isValidProps(precision)) {
return Math.round(num * Math.pow(10, precision)) / Math.pow(10, precision);
}
return Number(num);
}
}, {
key: "upStep",
value: function upStep(val, rat) {
var step = this.props.step;
var precisionFactor = this.getPrecisionFactor(val, rat);
var precision = Math.abs(this.getMaxPrecision(val, rat));
var result = ((precisionFactor * val + precisionFactor * step * rat) / precisionFactor).toFixed(precision);
return this.toNumber(result);
}
}, {
key: "downStep",
value: function downStep(val, rat) {
var step = this.props.step;
var precisionFactor = this.getPrecisionFactor(val, rat);
var precision = Math.abs(this.getMaxPrecision(val, rat));
var result = ((precisionFactor * val - precisionFactor * step * rat) / precisionFactor).toFixed(precision);
return this.toNumber(result);
}
}, {
key: "step",
value: function step(type, e) {
var _this2 = this;
var ratio = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
var recursive = arguments.length > 3 ? arguments[3] : undefined;
this.stop();
if (e) {
e.persist();
e.preventDefault();
}
var props = this.props;
if (props.disabled) {
return;
}
var value = this.getCurrentValidValue(this.state.inputValue) || 0;
if (this.isNotCompleteNumber(value)) {
return;
}
var val = this["".concat(type, "Step")](value, ratio);
var outOfRange = val > props.max || val < props.min;
if (val > props.max) {
val = props.max;
} else if (val < props.min) {
val = props.min;
}
this.setValue(val, null);
this.setState({
focused: true
}, function () {
_this2.pressingUpOrDown = false;
});
if (outOfRange) {
return;
}
this.autoStepTimer = setTimeout(function () {
_this2[type](e, ratio, true);
}, recursive ? SPEED : DELAY);
}
}, {
key: "fixCaret",
value: function fixCaret(start, end) {
if (start === undefined || end === undefined || !this.input || !this.input.value) {
return;
}
try {
var currentStart = this.input.selectionStart;
var currentEnd = this.input.selectionEnd;
if (start !== currentStart || end !== currentEnd) {
this.input.setSelectionRange(start, end);
}
} 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() {
var _classNames;
var _this$props5 = this.props,
prefixCls = _this$props5.prefixCls,
disabled = _this$props5.disabled,
readOnly = _this$props5.readOnly,
useTouch = _this$props5.useTouch,
autoComplete = _this$props5.autoComplete,
upHandler = _this$props5.upHandler,
downHandler = _this$props5.downHandler,
className = _this$props5.className,
max = _this$props5.max,
min = _this$props5.min,
style = _this$props5.style,
title = _this$props5.title,
onMouseEnter = _this$props5.onMouseEnter,
onMouseLeave = _this$props5.onMouseLeave,
onMouseOver = _this$props5.onMouseOver,
onMouseOut = _this$props5.onMouseOut,
required = _this$props5.required,
onClick = _this$props5.onClick,
tabIndex = _this$props5.tabIndex,
type = _this$props5.type,
placeholder = _this$props5.placeholder,
id = _this$props5.id,
inputMode = _this$props5.inputMode,
pattern = _this$props5.pattern,
step = _this$props5.step,
maxLength = _this$props5.maxLength,
autoFocus = _this$props5.autoFocus,
name = _this$props5.name,
onPaste = _this$props5.onPaste,
onInput = _this$props5.onInput,
rest = Object(esm_objectWithoutProperties["a" /* default */])(_this$props5, ["prefixCls", "disabled", "readOnly", "useTouch", "autoComplete", "upHandler", "downHandler", "className", "max", "min", "style", "title", "onMouseEnter", "onMouseLeave", "onMouseOver", "onMouseOut", "required", "onClick", "tabIndex", "type", "placeholder", "id", "inputMode", "pattern", "step", "maxLength", "autoFocus", "name", "onPaste", "onInput"]);
var _this$state = this.state,
value = _this$state.value,
focused = _this$state.focused;
var classes = classnames_default()(prefixCls, (_classNames = {}, Object(helpers_esm_defineProperty["a" /* default */])(_classNames, className, !!className), Object(helpers_esm_defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-disabled"), disabled), Object(helpers_esm_defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-focused"), focused), _classNames));
var dataOrAriaAttributeProps = {};
Object.keys(rest).forEach(function (key) {
if (key.substr(0, 5) === 'data-' || key.substr(0, 5) === 'aria-' || key === 'role') {
dataOrAriaAttributeProps[key] = rest[key];
}
});
var editable = !readOnly && !disabled; // focus state, show input value
// unfocus state, show valid value
var inputDisplayValue = this.getInputDisplayValue(null);
var upDisabled = (value || value === 0) && (isNaN(value) || Number(value) >= max);
var downDisabled = (value || value === 0) && (isNaN(value) || Number(value) <= min);
var isUpDisabled = upDisabled || disabled || readOnly;
var isDownDisabled = downDisabled || disabled || readOnly;
var upClassName = classnames_default()("".concat(prefixCls, "-handler"), "".concat(prefixCls, "-handler-up"), Object(helpers_esm_defineProperty["a" /* default */])({}, "".concat(prefixCls, "-handler-up-disabled"), isUpDisabled));
var downClassName = classnames_default()("".concat(prefixCls, "-handler"), "".concat(prefixCls, "-handler-down"), Object(helpers_esm_defineProperty["a" /* default */])({}, "".concat(prefixCls, "-handler-down-disabled"), isDownDisabled));
var upEvents = useTouch ? {
onTouchStart: isUpDisabled ? noop : this.up,
onTouchEnd: this.stop
} : {
onMouseDown: isUpDisabled ? noop : this.up,
onMouseUp: this.stop,
onMouseLeave: this.stop
};
var downEvents = useTouch ? {
onTouchStart: isDownDisabled ? noop : this.down,
onTouchEnd: this.stop
} : {
onMouseDown: isDownDisabled ? noop : this.down,
onMouseUp: this.stop,
onMouseLeave: this.stop
};
return react_default.a.createElement("div", {
className: classes,
style: style,
title: title,
onMouseEnter: onMouseEnter,
onMouseLeave: onMouseLeave,
onMouseOver: onMouseOver,
onMouseOut: onMouseOut,
onFocus: function onFocus() {
return null;
},
onBlur: function onBlur() {
return null;
}
}, react_default.a.createElement("div", {
className: "".concat(prefixCls, "-handler-wrap")
}, react_default.a.createElement("span", Object.assign({
unselectable: "on"
}, upEvents, {
role: "button",
"aria-label": "Increase Value",
"aria-disabled": isUpDisabled,
className: upClassName
}), upHandler || react_default.a.createElement("span", {
unselectable: "on",
className: "".concat(prefixCls, "-handler-up-inner"),
onClick: preventDefault
})), react_default.a.createElement("span", Object.assign({
unselectable: "on"
}, downEvents, {
role: "button",
"aria-label": "Decrease Value",
"aria-disabled": isDownDisabled,
className: downClassName
}), downHandler || react_default.a.createElement("span", {
unselectable: "on",
className: "".concat(prefixCls, "-handler-down-inner"),
onClick: preventDefault
}))), react_default.a.createElement("div", {
className: "".concat(prefixCls, "-input-wrap")
}, react_default.a.createElement("input", Object.assign({
role: "spinbutton",
"aria-valuemin": min,
"aria-valuemax": max,
"aria-valuenow": value,
required: required,
type: type,
placeholder: placeholder,
onPaste: onPaste,
onClick: onClick,
onMouseUp: this.onMouseUp,
className: "".concat(prefixCls, "-input"),
tabIndex: tabIndex,
autoComplete: autoComplete,
onFocus: this.onFocus,
onBlur: this.onBlur,
onKeyDown: editable ? this.onKeyDown : noop,
onKeyUp: editable ? this.onKeyUp : noop,
autoFocus: autoFocus,
maxLength: maxLength,
readOnly: readOnly,
disabled: disabled,
max: max,
min: min,
step: step,
name: name,
title: title,
id: id,
onChange: this.onChange,
ref: this.saveInput,
value: this.getFullNum(inputDisplayValue),
pattern: pattern,
inputMode: inputMode,
onInput: onInput
}, dataOrAriaAttributeProps))));
}
}]);
return InputNumber;
}(react_default.a.Component);
InputNumber_InputNumber.defaultProps = {
focusOnUpDown: true,
useTouch: false,
prefixCls: 'rc-input-number',
max: MAX_SAFE_INTEGER,
min: -MAX_SAFE_INTEGER,
step: 1,
style: {},
onChange: noop,
onKeyDown: noop,
onPressEnter: noop,
onFocus: noop,
onBlur: noop,
parser: defaultParser,
required: false,
autoComplete: 'off'
};
/* harmony default export */ var es_InputNumber = (InputNumber_InputNumber);
// CONCATENATED MODULE: ./node_modules/rc-input-number/es/index.js
/* harmony default export */ var rc_input_number_es = (es_InputNumber);
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/UpOutlined.js
var UpOutlined = __webpack_require__("FH2Y");
var UpOutlined_default = /*#__PURE__*/__webpack_require__.n(UpOutlined);
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/DownOutlined.js
var DownOutlined = __webpack_require__("HQEm");
var DownOutlined_default = /*#__PURE__*/__webpack_require__.n(DownOutlined);
// EXTERNAL MODULE: ./node_modules/antd/es/config-provider/SizeContext.js
var SizeContext = __webpack_require__("3Nzz");
// CONCATENATED MODULE: ./node_modules/antd/es/input-number/index.js
var input_number_rest = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
var input_number_InputNumber = /*#__PURE__*/react["forwardRef"](function (props, ref) {
var renderInputNumber = function renderInputNumber(_ref) {
var getPrefixCls = _ref.getPrefixCls,
direction = _ref.direction;
var className = props.className,
customizeSize = props.size,
customizePrefixCls = props.prefixCls,
readOnly = props.readOnly,
others = input_number_rest(props, ["className", "size", "prefixCls", "readOnly"]);
var prefixCls = getPrefixCls('input-number', customizePrefixCls);
var upIcon = /*#__PURE__*/react["createElement"](UpOutlined_default.a, {
className: "".concat(prefixCls, "-handler-up-inner")
});
var downIcon = /*#__PURE__*/react["createElement"](DownOutlined_default.a, {
className: "".concat(prefixCls, "-handler-down-inner")
});
return /*#__PURE__*/react["createElement"](SizeContext["b" /* default */].Consumer, null, function (size) {
var _classNames;
var mergeSize = customizeSize || size;
var inputNumberClass = classnames_default()((_classNames = {}, defineProperty_default()(_classNames, "".concat(prefixCls, "-lg"), mergeSize === 'large'), defineProperty_default()(_classNames, "".concat(prefixCls, "-sm"), mergeSize === 'small'), defineProperty_default()(_classNames, "".concat(prefixCls, "-rtl"), direction === 'rtl'), defineProperty_default()(_classNames, "".concat(prefixCls, "-readonly"), readOnly), _classNames), className);
return /*#__PURE__*/react["createElement"](rc_input_number_es, extends_default()({
ref: ref,
className: inputNumberClass,
upHandler: upIcon,
downHandler: downIcon,
prefixCls: prefixCls,
readOnly: readOnly
}, others));
});
};
return /*#__PURE__*/react["createElement"](context["a" /* ConfigConsumer */], null, renderInputNumber);
});
input_number_InputNumber.defaultProps = {
step: 1
};
/* harmony default export */ var input_number = (input_number_InputNumber);
// EXTERNAL MODULE: ./node_modules/antd/es/radio/style/index.js
var radio_style = __webpack_require__("7Kak");
// EXTERNAL MODULE: ./node_modules/antd/es/radio/index.js + 5 modules
var es_radio = __webpack_require__("9yH6");
// CONCATENATED MODULE: ./src/components/markdown-editor/add-table-panel/index.tsx
var RadioGroup = es_radio["a" /* default */].Group;
var add_table_panel_style = {
margin: '0 8px'
};
/* harmony default export */ var add_table_panel = (function (_ref) {
var callback = _ref.callback,
onCancel = _ref.onCancel;
function onSubmit(values) {
callback(values);
}
return /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */], {
className: "add-table-panel",
initialValues: {
row: 3,
col: 2,
align: 'default'
},
onFinish: onSubmit
}, /*#__PURE__*/react_default.a.createElement("div", {
className: "flex-container"
}, /*#__PURE__*/react_default.a.createElement("span", {
style: add_table_panel_style
}, "\u5355\u5143\u683C\u6570\uFF1A"), /*#__PURE__*/react_default.a.createElement("span", {
style: add_table_panel_style
}, "\u884C\u6570"), /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
name: "row",
rules: [{
required: true,
message: '请输入行数'
}]
}, /*#__PURE__*/react_default.a.createElement(input_number, null)), /*#__PURE__*/react_default.a.createElement("span", {
style: add_table_panel_style
}, "\u5217\u6570"), /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
name: "col",
rules: [{
required: true,
message: '请输入列数'
}]
}, /*#__PURE__*/react_default.a.createElement(input_number, null))), /*#__PURE__*/react_default.a.createElement("div", {
className: "flex-container",
style: {
marginTop: 12
}
}, /*#__PURE__*/react_default.a.createElement("span", {
style: add_table_panel_style
}, "\u5BF9\u9F50\u65B9\u5F0F\uFF1A"), /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
name: "align"
}, /*#__PURE__*/react_default.a.createElement(RadioGroup, null, /*#__PURE__*/react_default.a.createElement(es_radio["a" /* default */], {
value: "default"
}, /*#__PURE__*/react_default.a.createElement("i", {
className: "fa fa-align-justify"
})), /*#__PURE__*/react_default.a.createElement(es_radio["a" /* default */], {
value: "left"
}, /*#__PURE__*/react_default.a.createElement("i", {
className: "fa fa-align-left"
})), /*#__PURE__*/react_default.a.createElement(es_radio["a" /* default */], {
value: "center"
}, /*#__PURE__*/react_default.a.createElement("i", {
className: "fa fa-align-center"
})), /*#__PURE__*/react_default.a.createElement(es_radio["a" /* default */], {
value: "right"
}, /*#__PURE__*/react_default.a.createElement("i", {
className: "fa fa-align-right"
}))))), /*#__PURE__*/react_default.a.createElement("div", {
className: "flex-container flex-end"
}, /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
type: "primary",
htmlType: "submit",
style: {
marginRight: 10
}
}, "\u786E\u5B9A"), /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
type: "ghost",
onClick: onCancel
}, "\u53D6\u6D88")));
});
// CONCATENATED MODULE: ./src/components/markdown-editor/constant.ts
var LINK = 'link';
var UPLOAD_IMAGE = 'upload-image';
var CODE_BLOCK = 'code-block';
var ADD_TABLE = 'add-table';
var HRLINE = '------------';
var ALIGNSIGN = {
default: HRLINE,
left: ":".concat(HRLINE),
center: ":".concat(HRLINE, ":"),
right: "".concat(HRLINE, ":")
};
// CONCATENATED MODULE: ./src/components/useInterval.tsx
function useInterval(callback, delay) {
var savedCallback = Object(react["useRef"])(); // 保存新回调
Object(react["useEffect"])(function () {
savedCallback.current = callback;
}); // 建立 interval
Object(react["useEffect"])(function () {
function tick() {
savedCallback.current();
}
if (delay !== null) {
var id = setInterval(tick, delay);
return function () {
return clearInterval(id);
};
}
}, [delay]);
}
// CONCATENATED MODULE: ./src/components/markdown-editor/index.tsx
var _DEFAULTKEYMAP, _TitleDesc;
function markdown_editor_noop() {}
var pending = 0;
var StorageTimeTicket = 10000;
var NULL_CH = '▁';
var TEMP1 = '\n**模板标题**\n模板正文内容可输入文本内容和粘贴图片等操作'; //课程须知模板
function processSize(size) {
return !/^\d+$/.test(size) ? size : "".concat(size, "px");
}
var isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;
var markdown_editor_key = isMac ? 'Cmd' : 'Ctrl';
var DEFAULTKEYMAP = (_DEFAULTKEYMAP = {}, Object(esm_defineProperty["a" /* default */])(_DEFAULTKEYMAP, markdown_editor_key + '-B', 'bold'), Object(esm_defineProperty["a" /* default */])(_DEFAULTKEYMAP, markdown_editor_key + '-I', 'italic'), _DEFAULTKEYMAP);
var TitleDesc = (_TitleDesc = {}, Object(esm_defineProperty["a" /* default */])(_TitleDesc, LINK, '添加链接'), Object(esm_defineProperty["a" /* default */])(_TitleDesc, CODE_BLOCK, '添加代码块'), Object(esm_defineProperty["a" /* default */])(_TitleDesc, UPLOAD_IMAGE, '添加图片'), Object(esm_defineProperty["a" /* default */])(_TitleDesc, ADD_TABLE, '添加表格'), _TitleDesc); //https://codemirror.net/demo
//The height can be set through CSS (by giving the .CodeMirror class a height property), or by calling the cm's setSize method.
/* harmony default export */ var components_markdown_editor = (function (_ref) {
var _ref$defaultValue = _ref.defaultValue,
defaultValue = _ref$defaultValue === void 0 ? '' : _ref$defaultValue,
onChange = _ref.onChange,
_ref$width = _ref.width,
width = _ref$width === void 0 ? '100%' : _ref$width,
_ref$height = _ref.height,
height = _ref$height === void 0 ? 400 : _ref$height,
_ref$miniToolbar = _ref.miniToolbar,
miniToolbar = _ref$miniToolbar === void 0 ? false : _ref$miniToolbar,
_ref$isFocus = _ref.isFocus,
isFocus = _ref$isFocus === void 0 ? false : _ref$isFocus,
watch = _ref.watch,
insertTemp = _ref.insertTemp,
_ref$id = _ref.id,
id = _ref$id === void 0 ? 'markdown-editor-id' : _ref$id,
_ref$showResizeBar = _ref.showResizeBar,
showResizeBar = _ref$showResizeBar === void 0 ? false : _ref$showResizeBar,
_ref$noStorage = _ref.noStorage,
noStorage = _ref$noStorage === void 0 ? false : _ref$noStorage,
_ref$showNullButton = _ref.showNullButton,
showNullButton = _ref$showNullButton === void 0 ? false : _ref$showNullButton,
_ref$hidetoolBar = _ref.hidetoolBar,
hidetoolBar = _ref$hidetoolBar === void 0 ? false : _ref$hidetoolBar,
_ref$fullScreen = _ref.fullScreen,
fullScreen = _ref$fullScreen === void 0 ? false : _ref$fullScreen,
onBlur = _ref.onBlur,
onCMBeforeChange = _ref.onCMBeforeChange,
onFullScreen = _ref.onFullScreen,
_ref$className = _ref.className,
className = _ref$className === void 0 ? '' : _ref$className,
_ref$disablePaste = _ref.disablePaste,
disablePaste = _ref$disablePaste === void 0 ? false : _ref$disablePaste,
_ref$placeholder = _ref.placeholder,
placeholder = _ref$placeholder === void 0 ? '' : _ref$placeholder,
_ref$values = _ref.values,
values = _ref$values === void 0 ? '' : _ref$values;
var _useState = Object(react["useState"])(null),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
cm = _useState2[0],
setCm = _useState2[1];
var _useState3 = Object(react["useState"])(defaultValue),
_useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
value = _useState4[0],
setValue = _useState4[1];
var _useState5 = Object(react["useState"])(watch),
_useState6 = Object(slicedToArray["a" /* default */])(_useState5, 2),
preview = _useState6[0],
setPreview = _useState6[1];
var _useState7 = Object(react["useState"])(fullScreen),
_useState8 = Object(slicedToArray["a" /* default */])(_useState7, 2),
isFull = _useState8[0],
setIsFull = _useState8[1];
var _useState9 = Object(react["useState"])(''),
_useState10 = Object(slicedToArray["a" /* default */])(_useState9, 2),
action = _useState10[0],
setAction = _useState10[1];
var _useState11 = Object(react["useState"])(0),
_useState12 = Object(slicedToArray["a" /* default */])(_useState11, 2),
lastedUpdateTime = _useState12[0],
setLastedUpdateTime = _useState12[1];
var _useState13 = Object(react["useState"])(height),
_useState14 = Object(slicedToArray["a" /* default */])(_useState13, 2),
h = _useState14[0],
setH = _useState14[1];
var _useState15 = Object(react["useState"])(false),
_useState16 = Object(slicedToArray["a" /* default */])(_useState15, 2),
tip = _useState16[0],
setTip = _useState16[1];
var cmEl = Object(react["useRef"])();
var containerEl = Object(react["useRef"])();
var resizeBarEl = Object(react["useRef"])();
var previewEl = Object(react["useRef"])(); // useEffect(() => {
// setValue(defaultValue)
// cm?.setValue(defaultValue)
// },[])
Object(react["useEffect"])(function () {
setValue(values);
cm === null || cm === void 0 ? void 0 : cm.setValue(values);
}, [values]);
Object(react["useEffect"])(function () {
onFullScreen === null || onFullScreen === void 0 ? void 0 : onFullScreen(isFull);
}, [isFull]);
Object(react["useEffect"])(function () {
if (cmEl.current) {
var instance = codemirror_default.a.fromTextArea(cmEl.current, {
mode: 'markdown',
// inputStyle: 'contenteditable',
lineNumbers: miniToolbar ? false : true,
lineWrapping: true,
value: defaultValue,
autoCloseTags: true,
autoCloseBrackets: true
});
isFocus && instance.focus();
function onPaste(_, e) {
if (disablePaste) {
e.preventDefault();
return;
}
var clipboardData = e.clipboardData;
if (clipboardData) {
var types = clipboardData.types.toString();
var items = clipboardData.items;
var officeSix = ["pptm", "pptx", "ppt", "pot", "pps", "ppa", "potx", "ppsx", "ppam", "pptm", "potm", "ppsm", "doc", "docx", "dot", "dotx", "docm", "dotm", "xls", "xlsx", "csv", "xlt", "xla", "xltx", "xlsm", "xltm", "xlam", "xlsb"];
if (types === 'Files' || clipboardData.types.indexOf("Files") > -1) {
e.preventDefault();
try {
var _items$;
var item = items[1];
if (((_items$ = items[0]) === null || _items$ === void 0 ? void 0 : _items$.kind) === 'file') {
item = items[0];
}
var file = item.getAsFile();
var fileSix = file.name.split(".").pop(); // console.log("item:", item, file, item?.type?.match(/^video\//i))
uploadImage(file, function (data) {
if (data.id) {
var _file$type, _file$type2, _file$type3;
if ((file === null || file === void 0 ? void 0 : (_file$type = file.type) === null || _file$type === void 0 ? void 0 : _file$type.indexOf("image")) > -1) {
instance.replaceSelection("![,](/api/attachments/".concat(data.id, "?type=").concat(data.content_type, ")"));
} else if ((file === null || file === void 0 ? void 0 : (_file$type2 = file.type) === null || _file$type2 === void 0 ? void 0 : _file$type2.indexOf("video")) > -1) {
instance.replaceSelection("<video width=\"100%\" controls src=\"".concat(env["a" /* default */].API_SERVER, "/api/attachments/").concat(data.id, "\"></video>"));
} else if ((file === null || file === void 0 ? void 0 : (_file$type3 = file.type) === null || _file$type3 === void 0 ? void 0 : _file$type3.indexOf("pdf")) > -1) {
instance.replaceSelection("<a href=\"".concat(env["a" /* default */].API_SERVER, "/api/attachments/").concat(data.id, "?type=").concat(file.type, "&disposition=inline\" target=\"_blank\">").concat(file.name, "</a>"));
} else if (officeSix.includes(fileSix)) {
instance.replaceSelection("<a href=\"".concat(env["a" /* default */].API_SERVER, "/api/attachments/").concat(data.id, "?type=office&disposition=inline\" target=\"_blank\">").concat(file.name, "</a>"));
} else {
instance.replaceSelection("[".concat(file.name, "](").concat(env["a" /* default */].API_SERVER, "/api/attachments/").concat(data.id, "?type=").concat(data.content_type, ")"));
}
} else {
if ((data === null || data === void 0 ? void 0 : data.status) === 401) document.location.href = '/user/login';
}
});
} catch (e) {
es_message["b" /* default */].warn("请使用chrome浏览器粘贴");
}
return true;
} else {
//toMarkdown ?
// let html = clipboardData.getData('text/html')
return true;
}
}
return true;
}
instance.on('paste', onPaste);
setCm(instance);
return function () {
instance.off('paste', onPaste);
};
}
}, []);
var resizeEditorBodyHeight = Object(react["useCallback"])(function () {
if (containerEl.current) {
try {
var toolH = containerEl.current.getElementsByClassName('markdown-toolbar-container')[0].offsetHeight;
var mdBody = containerEl.current.getElementsByClassName('markdown-editor-body')[0];
if (!isFull) {
mdBody.style.height = "".concat(h - toolH, "px");
} else {
mdBody.style.height = "calc(100vh - ".concat(toolH, "px)");
}
} catch (error) {
console.log(error, '---- to set md editor body height');
}
}
}, [h, containerEl, isFull]);
Object(react["useEffect"])(function () {
function onLayout() {
var 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) {
resizeEditorBodyHeight();
cm.setSize('100%', '100%');
cm.refresh();
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
});
ro.observe(cmEl.current.parentElement);
return ro;
}
if (cm) {
var ro = onLayout();
return function () {
ro.unobserve(cmEl.current.parentElement);
};
}
}, [cm, resizeEditorBodyHeight]); //keymap
Object(react["useEffect"])(function () {
if (cm) {
var keymap = [];
var _loop = function _loop() {
var _ref2 = _Object$entries[_i];
_ref3 = Object(slicedToArray["a" /* default */])(_ref2, 2);
var k = _ref3[0];
var value = _ref3[1];
var map = Object(esm_defineProperty["a" /* default */])({}, k, function () {
onActionCallback(value);
});
keymap.push(map);
cm.addKeyMap(map);
};
for (var _i = 0, _Object$entries = Object.entries(DEFAULTKEYMAP); _i < _Object$entries.length; _i++) {
var _ref3;
_loop();
}
return function () {
var _iterator2 = Object(createForOfIteratorHelper["a" /* default */])(keymap),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var m = _step2.value;
cm.removeKeyMap(m);
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
};
}
}, [cm]);
Object(react["useEffect"])(function () {
if (fullScreen !== isFull) {
setIsFull(fullScreen);
}
}, [fullScreen]);
useInterval(function () {
if (!noStorage && lastedUpdateTime > 0) {
var currentTime = new Date().getTime();
var lastedValue = window.sessionStorage.getItem(id);
if (currentTime >= lastedUpdateTime + StorageTimeTicket && (!lastedValue || lastedValue !== value)) {
window.sessionStorage.setItem(id, value);
setTip(true);
}
}
}, StorageTimeTicket);
Object(react["useEffect"])(function () {
setPreview(watch);
}, [cm, watch]);
Object(react["useEffect"])(function () {
if (cm) {
isFocus && cm.focus();
}
}, [cm, isFocus]);
Object(react["useEffect"])(function () {
if (preview && cm) {
var scrollEl = cm.getScrollerElement();
function syncScroll(e) {
var target = e.target;
if (previewEl.current) {
var ratio = target.scrollTop / target.scrollHeight;
previewEl.current.scrollTop = previewEl.current.scrollHeight * ratio;
}
}
scrollEl.addEventListener('scroll', syncScroll);
return function () {
scrollEl.removeEventListener('scroll', syncScroll);
};
}
}, [cm, preview]);
Object(react["useEffect"])(function () {
if (cm && onCMBeforeChange) {
function onChangeHandler(cm, change) {
onCMBeforeChange(cm, change);
}
cm.on('beforeChange', onChangeHandler);
return function () {
cm.off('beforeChange', onChangeHandler);
};
}
}, [cm, onCMBeforeChange]);
Object(react["useEffect"])(function () {
if (cm && onBlur) {
function onBlurHandler() {
onBlur(cm.getValue());
}
cm.on('blur', onBlurHandler);
return function () {
cm.off('blur', onBlurHandler);
};
}
}, [cm, onBlur]);
Object(react["useEffect"])(function () {
if (cm) {
function onChangeHandler(cm) {
var content = cm.getValue();
setValue(content);
setLastedUpdateTime(new Date().getTime());
cm.getScrollerElement().dispatchEvent(new CustomEvent('scroll'));
onChange && onChange(content);
}
cm.on('change', onChangeHandler);
return function () {
cm.off('change', onChangeHandler);
};
}
}, [cm, onChange]);
Object(react["useEffect"])(function () {
if (cm) {
// isFocus && cm.focus()
if (defaultValue === null || defaultValue === undefined) {
cm.setValue('');
setValue('');
} else {
if (defaultValue !== cm.getValue()) {
cm.setValue(defaultValue);
setValue(defaultValue);
cm.setCursor(cm.lineCount(), 0);
}
}
}
}, [cm, defaultValue]);
var onActionCallback = Object(react["useCallback"])(function (actionName) {
var cursor = cm.getCursor();
var selection = cm.getSelection();
var selectionText = selection.split('\n');
switch (actionName) {
case 'bold':
cm.replaceSelection('**' + selection + '**');
if (selection === '') {
cm.setCursor(cursor.line, cursor.ch + 2);
}
return cm.focus();
case 'italic':
cm.replaceSelection('*' + selection + '*');
if (selection === '') {
cm.setCursor(cursor.line, cursor.ch + 1);
}
return cm.focus();
case 'code':
cm.replaceSelection('`' + selection + '`');
if (selection === '') {
cm.setCursor(cursor.line, cursor.ch + 1);
}
return cm.focus();
case 'inline-latex':
cm.replaceSelection('`$$' + selection + '$$`');
if (selection === '') {
cm.setCursor(cursor.line, cursor.ch + 3);
}
return cm.focus();
case 'latex':
cm.replaceSelection("```latex\n" + selection + "\n```");
cm.setCursor(cursor.line + 1, selection.length + 1);
return cm.focus();
case 'line-break':
cm.replaceSelection('<br/>\n');
return cm.focus();
case 'list-ul':
if (selection === '') {
cm.replaceSelection('- ' + selection);
} else {
cm.replaceSelection(selectionText.map(function (item) {
return item === '' ? '' : "- ".concat(item);
}).join('\n'));
}
return cm.focus();
case 'list-ol':
if (selection === '') {
cm.replaceSelection('1. ' + selection);
} else {
cm.replaceSelection(selectionText.map(function (item, index) {
return item === '' ? '' : "".concat(index + 1, ". ").concat(item);
}).join('\n'));
}
return cm.focus();
case 'add-null-ch':
if (selection === '') {
cm.setCursor(cursor.line, cursor.ch + 1);
}
cm.replaceSelection(NULL_CH);
return cm.focus();
case 'inster-template-1':
if (selection === '') {
cm.setCursor(cursor.line, cursor.ch);
}
cm.replaceSelection(TEMP1);
return cm.focus();
case 'eraser':
cm.setValue('');
return cm.focus();
case 'trigger-watch':
setPreview(!preview);
return cm.focus();
case 'trigger-full-screen':
setIsFull(!isFull);
return cm.focus();
case LINK:
setAction(LINK);
return;
case CODE_BLOCK:
setAction(CODE_BLOCK);
return;
case UPLOAD_IMAGE:
setAction(UPLOAD_IMAGE);
return;
case ADD_TABLE:
setAction(ADD_TABLE);
return;
default:
throw new Error();
}
}, [cm, preview, isFull]);
var ExecutePluginAction = Object(react["useCallback"])(function (values) {
setAction('');
switch (action) {
case LINK:
var title = values.title,
link = values.link;
cm.replaceSelection("[".concat(title, "](").concat(link, ")"));
return cm.focus();
case CODE_BLOCK:
var language = values.language,
content = values.content;
cm.replaceSelection(['```' + language, content, '```'].join('\n'));
return cm.focus();
case UPLOAD_IMAGE:
var src = values.src,
alt = values.alt;
cm.replaceSelection("![ ".concat(alt, " ]( ").concat(src, " \"").concat(alt, "\" )"));
return cm.focus();
case ADD_TABLE:
var row = values.row,
col = values.col,
align = values.align;
var table = '\n';
for (var r = 0; r < row; r++) {
var rows = [];
var heads = [];
for (var c = 0; c < col; c++) {
if (r === 1) {
heads.push(ALIGNSIGN[align]);
}
rows.push(' ');
}
if (r === 1) {
table += "| ".concat(heads.join(' | '), " |\n");
}
table += "| ".concat(rows.join(col === 1 ? '' : ' | '), " |\n");
}
cm.replaceSelection(table + '\n');
return cm.focus();
default:
throw new Error();
}
}, [cm, action]);
var PluginEl = Object(react["useMemo"])(function () {
switch (action) {
case LINK:
return /*#__PURE__*/react_default.a.createElement(markdown_editor_link, {
callback: ExecutePluginAction,
onCancel: onCancel
});
case CODE_BLOCK:
return /*#__PURE__*/react_default.a.createElement(code_block, {
callback: ExecutePluginAction,
onCancel: onCancel
});
case UPLOAD_IMAGE:
return /*#__PURE__*/react_default.a.createElement(markdown_editor_upload_image, {
callback: ExecutePluginAction,
onCancel: onCancel
});
case ADD_TABLE:
return /*#__PURE__*/react_default.a.createElement(add_table_panel, {
callback: ExecutePluginAction,
onCancel: onCancel
});
default:
return null;
}
}, [action]);
function onCancel() {
setAction('');
}
Object(react["useEffect"])(function () {
if (resizeBarEl.current) {
var resizeBar = resizeBarEl.current;
var dragging = false;
var startY = 0;
function onMouseDown(e) {
dragging = true;
startY = e.pageY;
}
function onMouseUp() {
dragging = false;
}
function onMouseMove(e) {
if (dragging) {
var delta = e.pageY - startY;
if (delta < 0) {
delta = 0;
}
if (delta > 300) {
delta = 300;
}
var resizeH = height + delta + 'px';
setH(resizeH);
}
}
resizeBar.addEventListener('mousedown', onMouseDown);
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
return function () {
resizeBar.removeEventListener('mousedown', onMouseDown);
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
};
}
}, [cm, resizeBarEl]);
Object(react["useEffect"])(function () {
setH(height);
}, [height]);
var fixedWidth = processSize(width);
var fixedHeight = processSize(h);
var style = {
width: fixedWidth,
height: fixedHeight
};
var saveTime = Object(react["useMemo"])(function () {
if (lastedUpdateTime) {
var d = new Date(lastedUpdateTime);
var _h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
_h = _h < 10 ? '0' + _h : _h;
m = m < 10 ? '0' + m : m;
s = s < 10 ? '0' + s : s;
return "".concat(_h, ":").concat(m, ":").concat(s);
}
return 0;
}, [lastedUpdateTime]);
function onCancelStorage() {
window.sessionStorage.removeItem(id);
setTip(false);
setLastedUpdateTime(0);
}
function onReset() {
setTip(false);
setLastedUpdateTime(0);
cm.setValue(window.sessionStorage.getItem(id));
}
return /*#__PURE__*/react_default.a.createElement(react["Fragment"], null, /*#__PURE__*/react_default.a.createElement("div", {
className: "markdown-editor-wrapper",
ref: containerEl
}, /*#__PURE__*/react_default.a.createElement("div", {
className: "markdown-editor-container ".concat(className, " ").concat(preview ? 'on-preview' : '', " ").concat(miniToolbar ? 'mini' : '', " ").concat(isFull ? 'full-screen' : ''),
style: style
}, /*#__PURE__*/react_default.a.createElement(markdown_editor_toolbar, {
insertTemp: insertTemp,
watch: preview,
fullScreen: isFull,
showNullButton: showNullButton,
onActionCallback: onActionCallback,
hidetoolBar: hidetoolBar
}), /*#__PURE__*/react_default.a.createElement("div", {
className: "markdown-editor-body"
}, /*#__PURE__*/react_default.a.createElement("div", {
className: "codemirror-container"
}, /*#__PURE__*/react_default.a.createElement("textarea", {
ref: cmEl,
placeholder: placeholder
})), preview ? /*#__PURE__*/react_default.a.createElement("div", {
ref: previewEl,
className: "preview-container"
}, /*#__PURE__*/react_default.a.createElement(RenderHtml["a" /* default */], {
value: value
})) : null))), showResizeBar ? /*#__PURE__*/react_default.a.createElement("a", {
ref: resizeBarEl,
className: "editor-resize"
}) : null, /*#__PURE__*/react_default.a.createElement(modal_Dialog, null, TitleDesc[action] ? /*#__PURE__*/react_default.a.createElement(es_modal["a" /* default */], {
centered: true,
title: TitleDesc[action],
visible: true,
onCancel: onCancel,
footer: null
}, PluginEl) : null));
});
// EXTERNAL MODULE: ./src/service/competitions.ts
var competitions = __webpack_require__("hJwl");
// CONCATENATED MODULE: ./src/pages/Competitions/Detail/Update.tsx
function Update_SeeItem(_ref) {
var ItemData = _ref.ItemData,
setIssee = _ref.setIssee,
MenuItem = _ref.MenuItem,
dispatch = _ref.dispatch,
identifier = _ref.identifier,
ModelType = _ref.ModelType,
userinfo = _ref.userinfo,
getrightdatas = _ref.getrightdatas;
var _useState = Object(react["useState"])([]),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
defaultFileList = _useState2[0],
setDefaultFileList = _useState2[1];
var _useState3 = Object(react["useState"])(ItemData.md_content),
_useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
defaultcontent = _useState4[0],
setDefaultcontent = _useState4[1];
Object(react["useEffect"])(function () {
var _ItemData$attachments;
var data = [];
ItemData === null || ItemData === void 0 ? void 0 : (_ItemData$attachments = ItemData.attachments) === null || _ItemData$attachments === void 0 ? void 0 : _ItemData$attachments.map(function (item) {
var tt = {
uid: item.id,
name: item.title,
response: {
id: item.id
}
};
data.push(tt);
});
setDefaultFileList(data);
}, [ItemData === null || ItemData === void 0 ? void 0 : ItemData.attachments]);
function getdata() {
var _ItemData$attachments2;
var data = [];
ItemData === null || ItemData === void 0 ? void 0 : (_ItemData$attachments2 = ItemData.attachments) === null || _ItemData$attachments2 === void 0 ? void 0 : _ItemData$attachments2.map(function (item) {
var tt = {
uid: item === null || item === void 0 ? void 0 : item.id,
name: item.title,
response: {
id: item.id
}
};
data.push(tt);
});
return data;
}
var uploadProps = {
name: 'file',
multiple: true,
withCredentials: true,
action: env["a" /* default */].API_SERVER + '/api/attachments.json',
defaultFileList: getdata(),
onRemove: function onRemove(e) {
Object(competitions["v" /* deletAttachments */])({
id: e.uid
});
},
onChange: function onChange(info) {
var status = info.file.status;
if (status !== 'uploading') {}
if (status === 'removed') {
setDefaultFileList(info.fileList);
}
if (status === 'done') {
setDefaultFileList(info.fileList);
es_message["b" /* default */].success("".concat(info.file.name, " \u6587\u4EF6\u4E0A\u4F20\u6210\u529F"));
} else if (status === 'error') {
es_message["b" /* default */].error("".concat(info.file.name, " \u6587\u4EF6\u4E0A\u4F20\u5931\u8D25"));
}
},
beforeUpload: function beforeUpload(file) {
var isLt150M = file.size / 1024 / 1024 < 150;
if (!isLt150M) {
es_message["b" /* default */].info("文件大小必须小于150MB");
}
return isLt150M;
}
}; //修改内容回调接口
function updateItem() {
return _updateItem.apply(this, arguments);
} //获取对应文件列表
function _updateItem() {
_updateItem = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee() {
var data;
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return dispatch({
type: 'competitions/updateMdContent',
payload: {
attachment_ids: getitemid(defaultFileList),
competition_module_id: ItemData.id,
md_content_id: ItemData.md_id,
content: defaultcontent,
identifier: identifier
}
});
case 2:
data = _context.sent;
if (data) {
es_message["b" /* default */].info('提交成功');
setIssee(true); //刷新
getrightdatas(MenuItem);
}
case 4:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return _updateItem.apply(this, arguments);
}
function getitemid(itemlist) {
var data = [];
itemlist && itemlist.map(function (item) {
data.push(item.response.id);
});
return data;
}
return /*#__PURE__*/react_default.a.createElement("div", null, ModelType === "reward" ? /*#__PURE__*/react_default.a.createElement(Competitionbonus, {
userlist: userinfo,
dispatch: dispatch,
rewarddata: ItemData.reward_setting,
is_signed: ItemData.is_signed
}) : null, /*#__PURE__*/react_default.a.createElement(components_markdown_editor, {
defaultValue: defaultcontent,
onChange: function onChange(e) {
return setDefaultcontent(e);
}
}), /*#__PURE__*/react_default.a.createElement(es_upload, uploadProps, /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
className: "uploadBtn"
}, "\u4E0A\u4F20\u9644\u4EF6"), "(\u5355\u4E2A\u6587\u4EF6150M\u4EE5\u5185)"), /*#__PURE__*/react_default.a.createElement("p", {
style: {
marginTop: '10px'
}
}, /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
style: {
width: '90px'
},
type: "primary",
onClick: function onClick() {
return updateItem();
}
}, "\u63D0\u4EA4"), /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
style: {
marginLeft: '30px',
width: '90px'
},
onClick: function onClick() {
return setIssee(true);
}
}, "\u53D6\u6D88")));
}
/* harmony default export */ var Update = (Update_SeeItem);
// EXTERNAL MODULE: ./node_modules/antd/es/table/style/index.js
var table_style = __webpack_require__("g9YV");
// EXTERNAL MODULE: ./node_modules/antd/es/table/index.js + 53 modules
var es_table = __webpack_require__("wCAj");
// EXTERNAL MODULE: ./node_modules/antd/es/tabs/style/index.js
var tabs_style = __webpack_require__("Znn+");
// EXTERNAL MODULE: ./node_modules/antd/es/tabs/index.js + 51 modules
var es_tabs = __webpack_require__("ZTPi");
// CONCATENATED MODULE: ./src/pages/Competitions/Detail/RankingNuLL.tsx
//排行榜没有数据
function RankNull() {
return /*#__PURE__*/react_default.a.createElement("div", null, /*#__PURE__*/react_default.a.createElement("p", {
style: {
fontSize: '24px',
color: '#05101a'
}
}, "\u603B\u6392\u884C"), /*#__PURE__*/react_default.a.createElement("div", {
style: {
textAlign: 'center'
}
}, /*#__PURE__*/react_default.a.createElement("img", {
src: env["a" /* default */].IMG_SERVER + "/images/educoder/competitions/trophy.png"
}), /*#__PURE__*/react_default.a.createElement("p", null, "\u8981\u6293\u4F4F\u4E00\u5207\u673A\u4F1A\uFF0C\u5411\u6240\u6709\u4EBA\u8BC1\u660E\u81EA\u5DF1\uFF0C\u8BC1\u660E\u4F60\u80FD\u591F\u8FCE\u63A5\u8363\u8000")));
}
/* harmony default export */ var RankingNuLL = (RankNull);
// EXTERNAL MODULE: ./node_modules/antd/es/col/style/index.js
var col_style = __webpack_require__("jCWc");
// EXTERNAL MODULE: ./node_modules/antd/es/col/index.js
var es_col = __webpack_require__("kPKH");
// EXTERNAL MODULE: ./node_modules/antd/es/card/style/index.less
var card_style = __webpack_require__("lnY3");
// CONCATENATED MODULE: ./node_modules/antd/es/card/style/index.js
// style dependencies
// CONCATENATED MODULE: ./node_modules/antd/es/card/Grid.js
var Grid_rest = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
var Grid_Grid = function Grid(props) {
return /*#__PURE__*/react["createElement"](context["a" /* ConfigConsumer */], null, function (_ref) {
var getPrefixCls = _ref.getPrefixCls;
var customizePrefixCls = props.prefixCls,
className = props.className,
_props$hoverable = props.hoverable,
hoverable = _props$hoverable === void 0 ? true : _props$hoverable,
others = Grid_rest(props, ["prefixCls", "className", "hoverable"]);
var prefixCls = getPrefixCls('card', customizePrefixCls);
var classString = classnames_default()("".concat(prefixCls, "-grid"), className, defineProperty_default()({}, "".concat(prefixCls, "-grid-hoverable"), hoverable));
return /*#__PURE__*/react["createElement"]("div", extends_default()({}, others, {
className: classString
}));
});
};
/* harmony default export */ var card_Grid = (Grid_Grid);
// CONCATENATED MODULE: ./node_modules/antd/es/card/Meta.js
var Meta_rest = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
var Meta_Meta = function Meta(props) {
return /*#__PURE__*/react["createElement"](context["a" /* ConfigConsumer */], null, function (_ref) {
var getPrefixCls = _ref.getPrefixCls;
var customizePrefixCls = props.prefixCls,
className = props.className,
avatar = props.avatar,
title = props.title,
description = props.description,
others = Meta_rest(props, ["prefixCls", "className", "avatar", "title", "description"]);
var prefixCls = getPrefixCls('card', customizePrefixCls);
var classString = classnames_default()("".concat(prefixCls, "-meta"), className);
var avatarDom = avatar ? /*#__PURE__*/react["createElement"]("div", {
className: "".concat(prefixCls, "-meta-avatar")
}, avatar) : null;
var titleDom = title ? /*#__PURE__*/react["createElement"]("div", {
className: "".concat(prefixCls, "-meta-title")
}, title) : null;
var descriptionDom = description ? /*#__PURE__*/react["createElement"]("div", {
className: "".concat(prefixCls, "-meta-description")
}, description) : null;
var MetaDetail = titleDom || descriptionDom ? /*#__PURE__*/react["createElement"]("div", {
className: "".concat(prefixCls, "-meta-detail")
}, titleDom, descriptionDom) : null;
return /*#__PURE__*/react["createElement"]("div", extends_default()({}, others, {
className: classString
}), avatarDom, MetaDetail);
});
};
/* harmony default export */ var card_Meta = (Meta_Meta);
// CONCATENATED MODULE: ./node_modules/antd/es/card/index.js
var card_rest = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
function getAction(actions) {
var actionList = actions.map(function (action, index) {
return (
/*#__PURE__*/
// eslint-disable-next-line react/no-array-index-key
react["createElement"]("li", {
style: {
width: "".concat(100 / actions.length, "%")
},
key: "action-".concat(index)
}, /*#__PURE__*/react["createElement"]("span", null, action))
);
});
return actionList;
}
var card_Card = function Card(props) {
var _extends2, _classNames;
var _React$useContext = react["useContext"](context["b" /* ConfigContext */]),
getPrefixCls = _React$useContext.getPrefixCls,
direction = _React$useContext.direction;
var size = react["useContext"](SizeContext["b" /* default */]);
var onTabChange = function onTabChange(key) {
if (props.onTabChange) {
props.onTabChange(key);
}
};
var isContainGrid = function isContainGrid() {
var containGrid;
react["Children"].forEach(props.children, function (element) {
if (element && element.type && element.type === card_Grid) {
containGrid = true;
}
});
return containGrid;
};
var customizePrefixCls = props.prefixCls,
className = props.className,
extra = props.extra,
_props$headStyle = props.headStyle,
headStyle = _props$headStyle === void 0 ? {} : _props$headStyle,
_props$bodyStyle = props.bodyStyle,
bodyStyle = _props$bodyStyle === void 0 ? {} : _props$bodyStyle,
title = props.title,
loading = props.loading,
_props$bordered = props.bordered,
bordered = _props$bordered === void 0 ? true : _props$bordered,
customizeSize = props.size,
type = props.type,
cover = props.cover,
actions = props.actions,
tabList = props.tabList,
children = props.children,
activeTabKey = props.activeTabKey,
defaultActiveTabKey = props.defaultActiveTabKey,
tabBarExtraContent = props.tabBarExtraContent,
hoverable = props.hoverable,
_props$tabProps = props.tabProps,
tabProps = _props$tabProps === void 0 ? {} : _props$tabProps,
others = card_rest(props, ["prefixCls", "className", "extra", "headStyle", "bodyStyle", "title", "loading", "bordered", "size", "type", "cover", "actions", "tabList", "children", "activeTabKey", "defaultActiveTabKey", "tabBarExtraContent", "hoverable", "tabProps"]);
var prefixCls = getPrefixCls('card', customizePrefixCls);
var loadingBlockStyle = bodyStyle.padding === 0 || bodyStyle.padding === '0px' ? {
padding: 24
} : undefined;
var block = /*#__PURE__*/react["createElement"]("div", {
className: "".concat(prefixCls, "-loading-block")
});
var loadingBlock = /*#__PURE__*/react["createElement"]("div", {
className: "".concat(prefixCls, "-loading-content"),
style: loadingBlockStyle
}, /*#__PURE__*/react["createElement"](es_row["a" /* default */], {
gutter: 8
}, /*#__PURE__*/react["createElement"](es_col["a" /* default */], {
span: 22
}, block)), /*#__PURE__*/react["createElement"](es_row["a" /* default */], {
gutter: 8
}, /*#__PURE__*/react["createElement"](es_col["a" /* default */], {
span: 8
}, block), /*#__PURE__*/react["createElement"](es_col["a" /* default */], {
span: 15
}, block)), /*#__PURE__*/react["createElement"](es_row["a" /* default */], {
gutter: 8
}, /*#__PURE__*/react["createElement"](es_col["a" /* default */], {
span: 6
}, block), /*#__PURE__*/react["createElement"](es_col["a" /* default */], {
span: 18
}, block)), /*#__PURE__*/react["createElement"](es_row["a" /* default */], {
gutter: 8
}, /*#__PURE__*/react["createElement"](es_col["a" /* default */], {
span: 13
}, block), /*#__PURE__*/react["createElement"](es_col["a" /* default */], {
span: 9
}, block)), /*#__PURE__*/react["createElement"](es_row["a" /* default */], {
gutter: 8
}, /*#__PURE__*/react["createElement"](es_col["a" /* default */], {
span: 4
}, block), /*#__PURE__*/react["createElement"](es_col["a" /* default */], {
span: 3
}, block), /*#__PURE__*/react["createElement"](es_col["a" /* default */], {
span: 16
}, block)));
var hasActiveTabKey = activeTabKey !== undefined;
var extraProps = extends_default()(extends_default()({}, tabProps), (_extends2 = {}, defineProperty_default()(_extends2, hasActiveTabKey ? 'activeKey' : 'defaultActiveKey', hasActiveTabKey ? activeTabKey : defaultActiveTabKey), defineProperty_default()(_extends2, "tabBarExtraContent", tabBarExtraContent), _extends2));
var head;
var tabs = tabList && tabList.length ? /*#__PURE__*/react["createElement"](es_tabs["a" /* default */], extends_default()({
size: "large"
}, extraProps, {
className: "".concat(prefixCls, "-head-tabs"),
onChange: onTabChange
}), tabList.map(function (item) {
return /*#__PURE__*/react["createElement"](es_tabs["a" /* default */].TabPane, {
tab: item.tab,
disabled: item.disabled,
key: item.key
});
})) : null;
if (title || extra || tabs) {
head = /*#__PURE__*/react["createElement"]("div", {
className: "".concat(prefixCls, "-head"),
style: headStyle
}, /*#__PURE__*/react["createElement"]("div", {
className: "".concat(prefixCls, "-head-wrapper")
}, title && /*#__PURE__*/react["createElement"]("div", {
className: "".concat(prefixCls, "-head-title")
}, title), extra && /*#__PURE__*/react["createElement"]("div", {
className: "".concat(prefixCls, "-extra")
}, extra)), tabs);
}
var coverDom = cover ? /*#__PURE__*/react["createElement"]("div", {
className: "".concat(prefixCls, "-cover")
}, cover) : null;
var body = /*#__PURE__*/react["createElement"]("div", {
className: "".concat(prefixCls, "-body"),
style: bodyStyle
}, loading ? loadingBlock : children);
var actionDom = actions && actions.length ? /*#__PURE__*/react["createElement"]("ul", {
className: "".concat(prefixCls, "-actions")
}, getAction(actions)) : null;
var divProps = Object(omit_js_es["a" /* default */])(others, ['onTabChange']);
var mergedSize = customizeSize || size;
var classString = classnames_default()(prefixCls, className, (_classNames = {}, defineProperty_default()(_classNames, "".concat(prefixCls, "-loading"), loading), defineProperty_default()(_classNames, "".concat(prefixCls, "-bordered"), bordered), defineProperty_default()(_classNames, "".concat(prefixCls, "-hoverable"), hoverable), defineProperty_default()(_classNames, "".concat(prefixCls, "-contain-grid"), isContainGrid()), defineProperty_default()(_classNames, "".concat(prefixCls, "-contain-tabs"), tabList && tabList.length), defineProperty_default()(_classNames, "".concat(prefixCls, "-").concat(mergedSize), mergedSize), defineProperty_default()(_classNames, "".concat(prefixCls, "-type-").concat(type), !!type), defineProperty_default()(_classNames, "".concat(prefixCls, "-rtl"), direction === 'rtl'), _classNames));
return /*#__PURE__*/react["createElement"]("div", extends_default()({}, divProps, {
className: classString
}), head, coverDom, body, actionDom);
};
card_Card.Grid = card_Grid;
card_Card.Meta = card_Meta;
/* harmony default export */ var card = (card_Card);
// CONCATENATED MODULE: ./src/pages/Competitions/Detail/RankingItem.tsx
//1 2 3 排名数据样式
function RankingItem(_ref) {
var oneItem = _ref.oneItem,
towItem = _ref.towItem,
threeItem = _ref.threeItem;
return /*#__PURE__*/react_default.a.createElement("div", {
style: {
textAlign: "center"
}
}, /*#__PURE__*/react_default.a.createElement(es_row["a" /* default */], {
gutter: 16,
style: {
justifyContent: 'center'
}
}, /*#__PURE__*/react_default.a.createElement(es_col["a" /* default */], {
span: 6,
style: {
marginTop: '30px',
marginRight: '20px'
}
}, /*#__PURE__*/react_default.a.createElement(card, {
title: /*#__PURE__*/react_default.a.createElement("div", {
className: Detailmodules_default.a.towtop
}, /*#__PURE__*/react_default.a.createElement("img", {
style: {
marginTop: '20px'
},
src: env["a" /* default */].IMG_SERVER + "/images/educoder/huangguan-two.png"
}), /*#__PURE__*/react_default.a.createElement("p", {
style: {
marginTop: '10px'
}
}, /*#__PURE__*/react_default.a.createElement(react_router_dom["a" /* Link */], {
to: "/users/".concat(towItem === null || towItem === void 0 ? void 0 : towItem.user_login, "/classrooms")
}, /*#__PURE__*/react_default.a.createElement("img", {
className: Detailmodules_default.a.imgradius,
src: env["a" /* default */].IMG_SERVER + "/images/".concat(towItem === null || towItem === void 0 ? void 0 : towItem.user_image)
}), (towItem === null || towItem === void 0 ? void 0 : towItem.competition_prize) && /*#__PURE__*/react_default.a.createElement("p", {
className: Detailmodules_default.a.prize
}, towItem === null || towItem === void 0 ? void 0 : towItem.competition_prize), /*#__PURE__*/react_default.a.createElement("p", {
style: {
color: '#05101a',
fontSize: '16px',
marginTop: '10px'
}
}, towItem === null || towItem === void 0 ? void 0 : towItem.record_user_name)))),
className: Detailmodules_default.a.towdiv,
bordered: false
}, /*#__PURE__*/react_default.a.createElement("p", {
style: {
fontSize: '14px'
}
}, towItem === null || towItem === void 0 ? void 0 : towItem.school_name), /*#__PURE__*/react_default.a.createElement("p", {
style: {
fontSize: '18px'
}
}, towItem === null || towItem === void 0 ? void 0 : towItem.spend_time), /*#__PURE__*/react_default.a.createElement("p", {
style: {
fontSize: '26px',
color: '#a55b29'
}
}, parseFloat(towItem === null || towItem === void 0 ? void 0 : towItem.extra_score) + parseFloat(towItem === null || towItem === void 0 ? void 0 : towItem.score), "\u5206"))), /*#__PURE__*/react_default.a.createElement(es_col["a" /* default */], {
span: 6
}, /*#__PURE__*/react_default.a.createElement(card, {
title: /*#__PURE__*/react_default.a.createElement("div", {
className: Detailmodules_default.a.onetop
}, /*#__PURE__*/react_default.a.createElement("img", {
style: {
marginTop: '20px'
},
src: env["a" /* default */].IMG_SERVER + "/images/educoder/huangguan.png"
}), /*#__PURE__*/react_default.a.createElement("p", {
style: {
marginTop: '10px'
}
}, /*#__PURE__*/react_default.a.createElement(react_router_dom["a" /* Link */], {
to: "/users/".concat(oneItem === null || oneItem === void 0 ? void 0 : oneItem.user_login, "/classrooms")
}, /*#__PURE__*/react_default.a.createElement("img", {
className: Detailmodules_default.a.imgradius,
src: env["a" /* default */].IMG_SERVER + "/images/".concat(oneItem === null || oneItem === void 0 ? void 0 : oneItem.user_image)
}), (oneItem === null || oneItem === void 0 ? void 0 : oneItem.competition_prize) && /*#__PURE__*/react_default.a.createElement("p", {
className: Detailmodules_default.a.prize
}, oneItem === null || oneItem === void 0 ? void 0 : oneItem.competition_prize), /*#__PURE__*/react_default.a.createElement("p", {
style: {
color: '#05101a',
fontSize: '16px',
marginTop: '10px'
}
}, oneItem === null || oneItem === void 0 ? void 0 : oneItem.record_user_name)))),
className: Detailmodules_default.a.onediv,
bordered: false
}, /*#__PURE__*/react_default.a.createElement("p", {
style: {
fontSize: '14px'
}
}, oneItem === null || oneItem === void 0 ? void 0 : oneItem.school_name), /*#__PURE__*/react_default.a.createElement("p", {
style: {
fontSize: '18px'
}
}, oneItem === null || oneItem === void 0 ? void 0 : oneItem.spend_time), /*#__PURE__*/react_default.a.createElement("p", {
style: {
fontSize: '26px',
color: '#a55b29'
}
}, parseFloat(oneItem === null || oneItem === void 0 ? void 0 : oneItem.extra_score) + parseFloat(oneItem === null || oneItem === void 0 ? void 0 : oneItem.score), "\u5206"))), /*#__PURE__*/react_default.a.createElement(es_col["a" /* default */], {
span: 6,
style: {
marginTop: '40px',
marginLeft: '20px'
}
}, /*#__PURE__*/react_default.a.createElement(card, {
title: /*#__PURE__*/react_default.a.createElement("div", {
className: Detailmodules_default.a.threetop
}, /*#__PURE__*/react_default.a.createElement("img", {
style: {
marginTop: '20px'
},
src: env["a" /* default */].IMG_SERVER + "/images/educoder/huangguan-three.png"
}), /*#__PURE__*/react_default.a.createElement("p", {
style: {
marginTop: '10px'
}
}, /*#__PURE__*/react_default.a.createElement(react_router_dom["a" /* Link */], {
to: "/users/".concat(threeItem === null || threeItem === void 0 ? void 0 : threeItem.user_login, "/classrooms")
}, /*#__PURE__*/react_default.a.createElement("img", {
className: Detailmodules_default.a.imgradius,
src: env["a" /* default */].IMG_SERVER + "/images/".concat(threeItem === null || threeItem === void 0 ? void 0 : threeItem.user_image)
}), (threeItem === null || threeItem === void 0 ? void 0 : threeItem.competition_prize) && /*#__PURE__*/react_default.a.createElement("p", {
className: Detailmodules_default.a.prize
}, threeItem === null || threeItem === void 0 ? void 0 : threeItem.competition_prize), /*#__PURE__*/react_default.a.createElement("p", {
style: {
color: '#05101a',
fontSize: '16px',
marginTop: '10px'
}
}, threeItem === null || threeItem === void 0 ? void 0 : threeItem.record_user_name)))),
className: Detailmodules_default.a.threediv,
bordered: false
}, /*#__PURE__*/react_default.a.createElement("p", {
style: {
fontSize: '14px'
}
}, threeItem === null || threeItem === void 0 ? void 0 : threeItem.school_name), /*#__PURE__*/react_default.a.createElement("p", {
style: {
fontSize: '18px'
}
}, threeItem === null || threeItem === void 0 ? void 0 : threeItem.spend_time), /*#__PURE__*/react_default.a.createElement("p", {
style: {
fontSize: '26px',
color: '#a55b29'
}
}, parseFloat(threeItem === null || threeItem === void 0 ? void 0 : threeItem.extra_score) + parseFloat(threeItem === null || threeItem === void 0 ? void 0 : threeItem.score), "\u5206")))));
}
/* harmony default export */ var Detail_RankingItem = (RankingItem);
// CONCATENATED MODULE: ./src/pages/Competitions/Detail/RankingList.tsx
function RanKingList(_ref) {
var _ItemData$user_ranks, _ItemData$user_ranks2, _ItemData$user_ranks3, _ItemData$user_ranks4, _ItemData$user_ranks5, _ItemData$user_ranks6, _ItemData$user_ranks7, _ItemData$user_ranks8, _ItemData$user_ranks9, _ItemData$user_ranks10, _ItemData$user_ranks11, _ItemData$user_ranks12, _ItemData$user_ranks13, _ItemData$user_ranks14, _ItemData$user_ranks15, _ItemData$user_ranks16, _ItemData$user_ranks17, _ItemData$user_ranks18, _ItemData$user_ranks19, _ItemData$user_ranks20, _ItemData$user_ranks21, _ItemData$user_ranks22, _ItemData$user_ranks23, _ItemData$user_ranks24, _ItemData$user_ranks25, _ItemData$user_ranks26, _ItemData$user_ranks27, _ItemData$user_ranks28, _ItemData$user_ranks29, _ItemData$teams;
var ItemData = _ref.ItemData;
return /*#__PURE__*/react_default.a.createElement("div", null, /*#__PURE__*/react_default.a.createElement("p", {
style: {
fontSize: '24px',
color: '#05101a'
}
}, "\u603B\u6392\u884C"), /*#__PURE__*/react_default.a.createElement(Detail_RankingItem, {
oneItem: ItemData === null || ItemData === void 0 ? void 0 : ItemData.teams[0],
towItem: ItemData === null || ItemData === void 0 ? void 0 : ItemData.teams[1],
threeItem: ItemData === null || ItemData === void 0 ? void 0 : ItemData.teams[2]
}), (ItemData === null || ItemData === void 0 ? void 0 : (_ItemData$user_ranks = ItemData.user_ranks) === null || _ItemData$user_ranks === void 0 ? void 0 : _ItemData$user_ranks.length) > 0 && /*#__PURE__*/react_default.a.createElement("div", {
className: Detailmodules_default.a.myTeam
}, (ItemData === null || ItemData === void 0 ? void 0 : (_ItemData$user_ranks2 = ItemData.user_ranks) === null || _ItemData$user_ranks2 === void 0 ? void 0 : (_ItemData$user_ranks3 = _ItemData$user_ranks2[0]) === null || _ItemData$user_ranks3 === void 0 ? void 0 : _ItemData$user_ranks3.success) === false ? /*#__PURE__*/react_default.a.createElement("span", {
style: {
marginRight: '70px',
padding: '10px'
}
}, /*#__PURE__*/react_default.a.createElement("p", {
style: {
marginBottom: '0px'
}
}, " \u662F\u5426\u664B\u7EA7\uFF1A", /*#__PURE__*/react_default.a.createElement("span", {
style: {
"color": (ItemData === null || ItemData === void 0 ? void 0 : (_ItemData$user_ranks4 = ItemData.user_ranks) === null || _ItemData$user_ranks4 === void 0 ? void 0 : (_ItemData$user_ranks5 = _ItemData$user_ranks4[0]) === null || _ItemData$user_ranks5 === void 0 ? void 0 : _ItemData$user_ranks5.success) === false ? 'red' : 'green'
}
}, (ItemData === null || ItemData === void 0 ? void 0 : (_ItemData$user_ranks6 = ItemData.user_ranks) === null || _ItemData$user_ranks6 === void 0 ? void 0 : (_ItemData$user_ranks7 = _ItemData$user_ranks6[0]) === null || _ItemData$user_ranks7 === void 0 ? void 0 : _ItemData$user_ranks7.success) === false ? '否' : (ItemData === null || ItemData === void 0 ? void 0 : (_ItemData$user_ranks8 = ItemData.user_ranks) === null || _ItemData$user_ranks8 === void 0 ? void 0 : (_ItemData$user_ranks9 = _ItemData$user_ranks8[0]) === null || _ItemData$user_ranks9 === void 0 ? void 0 : _ItemData$user_ranks9.success) ? '是' : '')), (ItemData === null || ItemData === void 0 ? void 0 : (_ItemData$user_ranks10 = ItemData.user_ranks) === null || _ItemData$user_ranks10 === void 0 ? void 0 : (_ItemData$user_ranks11 = _ItemData$user_ranks10[0]) === null || _ItemData$user_ranks11 === void 0 ? void 0 : _ItemData$user_ranks11.awards) && /*#__PURE__*/react_default.a.createElement("p", {
style: {
marginBottom: '0px'
}
}, " \u662F\u5426\u83B7\u5956\uFF1A", /*#__PURE__*/react_default.a.createElement("span", null, (ItemData === null || ItemData === void 0 ? void 0 : (_ItemData$user_ranks12 = ItemData.user_ranks) === null || _ItemData$user_ranks12 === void 0 ? void 0 : (_ItemData$user_ranks13 = _ItemData$user_ranks12[0]) === null || _ItemData$user_ranks13 === void 0 ? void 0 : _ItemData$user_ranks13.awards) === 'percent_20' ? '二等奖' : (ItemData === null || ItemData === void 0 ? void 0 : (_ItemData$user_ranks14 = ItemData.user_ranks) === null || _ItemData$user_ranks14 === void 0 ? void 0 : (_ItemData$user_ranks15 = _ItemData$user_ranks14[0]) === null || _ItemData$user_ranks15 === void 0 ? void 0 : _ItemData$user_ranks15.awards) === 'percent_30' ? '三等奖' : '没有获得奖项'))) : /*#__PURE__*/react_default.a.createElement("span", {
style: {
marginRight: '70px'
}
}, "\u6211\u7684\u6392\u540D\uFF1A", ItemData === null || ItemData === void 0 ? void 0 : (_ItemData$user_ranks16 = ItemData.user_ranks) === null || _ItemData$user_ranks16 === void 0 ? void 0 : (_ItemData$user_ranks17 = _ItemData$user_ranks16[0]) === null || _ItemData$user_ranks17 === void 0 ? void 0 : _ItemData$user_ranks17.rank), /*#__PURE__*/react_default.a.createElement("span", {
style: {
flex: 1
}
}, /*#__PURE__*/react_default.a.createElement(tooltip["a" /* default */], {
title: "\u6218\u961F\u540D"
}, ItemData === null || ItemData === void 0 ? void 0 : (_ItemData$user_ranks18 = ItemData.user_ranks) === null || _ItemData$user_ranks18 === void 0 ? void 0 : (_ItemData$user_ranks19 = _ItemData$user_ranks18[0]) === null || _ItemData$user_ranks19 === void 0 ? void 0 : _ItemData$user_ranks19.team_name)), /*#__PURE__*/react_default.a.createElement("span", {
style: {
flex: 1
}
}, /*#__PURE__*/react_default.a.createElement(tooltip["a" /* default */], {
title: "\u65F6\u95F4"
}, ItemData === null || ItemData === void 0 ? void 0 : (_ItemData$user_ranks20 = ItemData.user_ranks) === null || _ItemData$user_ranks20 === void 0 ? void 0 : (_ItemData$user_ranks21 = _ItemData$user_ranks20[0]) === null || _ItemData$user_ranks21 === void 0 ? void 0 : _ItemData$user_ranks21.cost_time)), /*#__PURE__*/react_default.a.createElement("span", {
style: {
flex: 1,
textAlign: 'center'
}
}, /*#__PURE__*/react_default.a.createElement(tooltip["a" /* default */], {
title: "\u8D4B\u80FD\u8D5B\u52A0\u5206"
}, ItemData === null || ItemData === void 0 ? void 0 : (_ItemData$user_ranks22 = ItemData.user_ranks) === null || _ItemData$user_ranks22 === void 0 ? void 0 : (_ItemData$user_ranks23 = _ItemData$user_ranks22[0]) === null || _ItemData$user_ranks23 === void 0 ? void 0 : _ItemData$user_ranks23.extra_score)), /*#__PURE__*/react_default.a.createElement("span", {
style: {
flex: 1
}
}, /*#__PURE__*/react_default.a.createElement(tooltip["a" /* default */], {
title: "\u6BD4\u8D5B\u6210\u7EE9"
}, ItemData === null || ItemData === void 0 ? void 0 : (_ItemData$user_ranks24 = ItemData.user_ranks) === null || _ItemData$user_ranks24 === void 0 ? void 0 : (_ItemData$user_ranks25 = _ItemData$user_ranks24[0]) === null || _ItemData$user_ranks25 === void 0 ? void 0 : _ItemData$user_ranks25.score)), /*#__PURE__*/react_default.a.createElement("span", null, /*#__PURE__*/react_default.a.createElement(tooltip["a" /* default */], {
title: "\u603B\u5206"
}, parseFloat(ItemData === null || ItemData === void 0 ? void 0 : (_ItemData$user_ranks26 = ItemData.user_ranks) === null || _ItemData$user_ranks26 === void 0 ? void 0 : (_ItemData$user_ranks27 = _ItemData$user_ranks26[0]) === null || _ItemData$user_ranks27 === void 0 ? void 0 : _ItemData$user_ranks27.extra_score) + parseFloat(ItemData === null || ItemData === void 0 ? void 0 : (_ItemData$user_ranks28 = ItemData.user_ranks) === null || _ItemData$user_ranks28 === void 0 ? void 0 : (_ItemData$user_ranks29 = _ItemData$user_ranks28[0]) === null || _ItemData$user_ranks29 === void 0 ? void 0 : _ItemData$user_ranks29.score) || 0))), ItemData === null || ItemData === void 0 ? void 0 : (_ItemData$teams = ItemData.teams) === null || _ItemData$teams === void 0 ? void 0 : _ItemData$teams.map(function (item, index) {
return /*#__PURE__*/react_default.a.createElement("div", {
className: Detailmodules_default.a.bottomItem
}, /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#4CACFF',
marginRight: '20px'
}
}, index + 1), /*#__PURE__*/react_default.a.createElement(react_router_dom["a" /* Link */], {
to: "/users/".concat(item === null || item === void 0 ? void 0 : item.user_login, "/classrooms"),
style: {
marginRight: '80px',
position: 'relative'
}
}, /*#__PURE__*/react_default.a.createElement("img", {
className: Detailmodules_default.a.imgradius,
src: env["a" /* default */].IMG_SERVER + "/images/".concat(item === null || item === void 0 ? void 0 : item.user_image)
}), (item === null || item === void 0 ? void 0 : item.competition_prize) && /*#__PURE__*/react_default.a.createElement("span", {
className: Detailmodules_default.a.spanrightradius
}, item === null || item === void 0 ? void 0 : item.competition_prize)), /*#__PURE__*/react_default.a.createElement("span", {
style: {
flex: 1
}
}, /*#__PURE__*/react_default.a.createElement(tooltip["a" /* default */], {
title: "\u6218\u961F\u540D"
}, item === null || item === void 0 ? void 0 : item.team_name)), /*#__PURE__*/react_default.a.createElement("span", {
style: {
flex: 1
}
}, /*#__PURE__*/react_default.a.createElement(tooltip["a" /* default */], {
title: "\u5355\u4F4D/\u5B66\u6821\u540D"
}, item.school_name)), /*#__PURE__*/react_default.a.createElement("span", {
style: {
flex: 1,
textAlign: 'center'
}
}, /*#__PURE__*/react_default.a.createElement(tooltip["a" /* default */], {
title: "\u8D4B\u80FD\u8D5B\u52A0\u5206"
}, item.extra_score)), /*#__PURE__*/react_default.a.createElement("span", {
style: {
flex: 1
}
}, /*#__PURE__*/react_default.a.createElement(tooltip["a" /* default */], {
title: "\u6BD4\u8D5B\u6210\u7EE9"
}, item.score)), /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#4CACFF'
}
}, /*#__PURE__*/react_default.a.createElement(tooltip["a" /* default */], {
title: "\u603B\u5206"
}, parseFloat(item.extra_score) + parseFloat(item.score))));
}));
}
/* harmony default export */ var RankingList = (RanKingList);
// CONCATENATED MODULE: ./src/pages/Competitions/Detail/Ranking.tsx
var TabPane = es_tabs["a" /* default */].TabPane;
function Ranking(_ref) {
var _ChartRules$stages2, _ChartRules$stages3, _item$children, _item$children3, _ItemData$teams, _ItemData$teams2;
var ChartRules = _ref.ChartRules,
ItemData = _ref.ItemData,
getCharts = _ref.getCharts,
Selectkey = _ref.Selectkey,
getChartRules = _ref.getChartRules,
userinfo = _ref.userinfo,
Editable = _ref.Editable,
HeaderDetail = _ref.HeaderDetail;
var _useState = Object(react["useState"])(false),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
isUpdate = _useState2[0],
setIsupdate = _useState2[1];
var _useState3 = Object(react["useState"])(''),
_useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
defaultValue = _useState4[0],
setDefaultValue = _useState4[1];
var _useState5 = Object(react["useState"])(true),
_useState6 = Object(slicedToArray["a" /* default */])(_useState5, 2),
ClickButton = _useState6[0],
setClickButton = _useState6[1];
var _useState7 = Object(react["useState"])(),
_useState8 = Object(slicedToArray["a" /* default */])(_useState7, 2),
item = _useState8[0],
setItem = _useState8[1];
var _useState9 = Object(react["useState"])(),
_useState10 = Object(slicedToArray["a" /* default */])(_useState9, 2),
items = _useState10[0],
setItems = _useState10[1];
var _useParams = Object(react_router["l" /* useParams */])(),
identifier = _useParams.identifier;
Object(react["useEffect"])(function () {
//进入初始化状态为第一个
if (ClickButton) {
var _ChartRules$stages;
var data = ChartRules === null || ChartRules === void 0 ? void 0 : (_ChartRules$stages = ChartRules.stages) === null || _ChartRules$stages === void 0 ? void 0 : _ChartRules$stages[0];
setItem(data);
if (data === null || data === void 0 ? void 0 : data.id) {
var _ChartRules$rule_cont, _ChartRules$rule_cont2, _ChartRules$rule_cont3;
if ((HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.task) === 'mAP' || (HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.task) === 'dog') {
getCharts(data === null || data === void 0 ? void 0 : data.id);
}
setDefaultValue(((_ChartRules$rule_cont = ChartRules.rule_contents) === null || _ChartRules$rule_cont === void 0 ? void 0 : (_ChartRules$rule_cont2 = _ChartRules$rule_cont.filter(function (item) {
return parseInt(item.competition_stage_id) === parseInt(data === null || data === void 0 ? void 0 : data.id);
})) === null || _ChartRules$rule_cont2 === void 0 ? void 0 : (_ChartRules$rule_cont3 = _ChartRules$rule_cont2[0]) === null || _ChartRules$rule_cont3 === void 0 ? void 0 : _ChartRules$rule_cont3['content']) || '');
} else {
var _ChartRules$rule_cont4, _ChartRules$rule_cont5, _ChartRules$rule_cont6;
if ((HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.task) === 'mAP' || (HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.task) === 'dog') {}
setDefaultValue(((_ChartRules$rule_cont4 = ChartRules.rule_contents) === null || _ChartRules$rule_cont4 === void 0 ? void 0 : (_ChartRules$rule_cont5 = _ChartRules$rule_cont4.filter(function (item) {
return parseInt(item.competition_stage_id) === 0;
})) === null || _ChartRules$rule_cont5 === void 0 ? void 0 : (_ChartRules$rule_cont6 = _ChartRules$rule_cont5[0]) === null || _ChartRules$rule_cont6 === void 0 ? void 0 : _ChartRules$rule_cont6['content']) || '');
}
}
}, [ChartRules]);
function updateitem() {
return _updateitem.apply(this, arguments);
}
function _updateitem() {
_updateitem = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee() {
var id, _ChartRules$rule_cont10, _ChartRules$rule_cont11, _ChartRules$rule_cont12, res, _ChartRules$rule_cont13, _ChartRules$rule_cont14, _ChartRules$rule_cont15, _res;
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (defaultValue) {
_context.next = 3;
break;
}
es_message["b" /* default */].info('内容不能为空');
return _context.abrupt("return");
case 3:
setClickButton(false);
id = item === null || item === void 0 ? void 0 : item.id;
if (!id) {
_context.next = 12;
break;
}
_context.next = 8;
return Object(fetch["a" /* default */])("/api/competitions/".concat(identifier, "/update_md_content.json"), {
method: 'post',
body: {
competition_module_id: Selectkey,
content: defaultValue,
md_content_id: (_ChartRules$rule_cont10 = ChartRules.rule_contents) === null || _ChartRules$rule_cont10 === void 0 ? void 0 : (_ChartRules$rule_cont11 = _ChartRules$rule_cont10.filter(function (item) {
return parseInt(item.competition_stage_id) === parseInt(id);
})) === null || _ChartRules$rule_cont11 === void 0 ? void 0 : (_ChartRules$rule_cont12 = _ChartRules$rule_cont11[0]) === null || _ChartRules$rule_cont12 === void 0 ? void 0 : _ChartRules$rule_cont12['id'],
stage_id: item === null || item === void 0 ? void 0 : item.id
}
});
case 8:
res = _context.sent;
if (res.status === 0) {
es_message["b" /* default */].info('更新成功');
setIsupdate(false);
getChartRules();
}
_context.next = 16;
break;
case 12:
_context.next = 14;
return Object(fetch["a" /* default */])("/api/competitions/".concat(identifier, "/update_md_content.json"), {
method: 'post',
body: {
competition_module_id: Selectkey,
content: defaultValue,
md_content_id: (_ChartRules$rule_cont13 = ChartRules.rule_contents) === null || _ChartRules$rule_cont13 === void 0 ? void 0 : (_ChartRules$rule_cont14 = _ChartRules$rule_cont13.filter(function (item) {
return parseInt(item.competition_stage_id) === 0;
})) === null || _ChartRules$rule_cont14 === void 0 ? void 0 : (_ChartRules$rule_cont15 = _ChartRules$rule_cont14[0]) === null || _ChartRules$rule_cont15 === void 0 ? void 0 : _ChartRules$rule_cont15['id'],
stage_id: item === null || item === void 0 ? void 0 : item.id
}
});
case 14:
_res = _context.sent;
if (_res.status === 0) {
es_message["b" /* default */].info('更新成功');
setIsupdate(false);
getChartRules();
}
case 16:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return _updateitem.apply(this, arguments);
}
var columns = [{
title: '排名',
dataIndex: 'name',
align: 'center',
key: 'name',
render: function render(a, b, c) {
return /*#__PURE__*/react_default.a.createElement("span", null, c + 1);
}
}, {
title: '头像',
dataIndex: 'user_image',
align: 'center',
key: 'user_image',
render: function render(text) {
return /*#__PURE__*/react_default.a.createElement("img", {
className: Detailmodules_default.a.imgradius,
src: env["a" /* default */].IMG_SERVER + "/images/".concat(text)
});
}
}, {
title: '战队名称',
dataIndex: 'team_name',
key: 'team_name',
// width:120,
render: function render(text) {
return /*#__PURE__*/react_default.a.createElement("span", {
title: text
}, text && (text === null || text === void 0 ? void 0 : text.length) >= 15 ? (text === null || text === void 0 ? void 0 : text.substr(0, 15)) + '...' : text || '--');
} // align:'center',
}, {
title: '单位',
dataIndex: 'school_name',
key: 'school_name',
align: 'center',
render: function render(a) {
return /*#__PURE__*/react_default.a.createElement("span", null, a || '--');
}
}, {
title: (HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.task) === 'mAP' ? 'mAP指标' : (HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.task) === 'Jittor-3' ? '总分' : 'top1指标',
dataIndex: 'score',
key: 'score',
render: function render(text) {
return /*#__PURE__*/react_default.a.createElement("span", null, text || '--');
}
}];
return /*#__PURE__*/react_default.a.createElement("div", null, (ChartRules === null || ChartRules === void 0 ? void 0 : (_ChartRules$stages2 = ChartRules.stages) === null || _ChartRules$stages2 === void 0 ? void 0 : _ChartRules$stages2.length) > 0 ? null : /*#__PURE__*/react_default.a.createElement(RankingNuLL, null), (ChartRules === null || ChartRules === void 0 ? void 0 : (_ChartRules$stages3 = ChartRules.stages) === null || _ChartRules$stages3 === void 0 ? void 0 : _ChartRules$stages3.length) > 0 && /*#__PURE__*/react_default.a.createElement(es_tabs["a" /* default */], {
animated: true,
tabBarExtraContent: ((userinfo === null || userinfo === void 0 ? void 0 : userinfo.admin) || (userinfo === null || userinfo === void 0 ? void 0 : userinfo.business) || Editable) && /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
onClick: function onClick() {
setIsupdate(true);
}
}, "\u7F16\u8F91"),
onChange: function onChange(e) {
var _ChartRules$stages4, _data$children, _ChartRules$rule_cont7, _ChartRules$rule_cont8, _ChartRules$rule_cont9;
setIsupdate(false);
var data = ChartRules === null || ChartRules === void 0 ? void 0 : (_ChartRules$stages4 = ChartRules.stages) === null || _ChartRules$stages4 === void 0 ? void 0 : _ChartRules$stages4.filter(function (item) {
return parseInt(e) === parseInt(item === null || item === void 0 ? void 0 : item.id);
})[0];
setItem(data);
var datas = data === null || data === void 0 ? void 0 : (_data$children = data.children) === null || _data$children === void 0 ? void 0 : _data$children[0];
setItems(datas);
setDefaultValue(((_ChartRules$rule_cont7 = ChartRules.rule_contents) === null || _ChartRules$rule_cont7 === void 0 ? void 0 : (_ChartRules$rule_cont8 = _ChartRules$rule_cont7.filter(function (item) {
return parseInt(item.competition_stage_id) === parseInt(data === null || data === void 0 ? void 0 : data.id);
})) === null || _ChartRules$rule_cont8 === void 0 ? void 0 : (_ChartRules$rule_cont9 = _ChartRules$rule_cont8[0]) === null || _ChartRules$rule_cont9 === void 0 ? void 0 : _ChartRules$rule_cont9['content']) || '');
getCharts((datas === null || datas === void 0 ? void 0 : datas.id) || e);
}
}, ChartRules && ChartRules.stages.map(function (item, index) {
return /*#__PURE__*/react_default.a.createElement(TabPane, {
tab: item.name,
key: item.id === null ? 0 : item.id
}, isUpdate === false && ChartRules && ChartRules.rule_contents.map(function (items, keys) {
if (item.id === items.competition_stage_id) {
return /*#__PURE__*/react_default.a.createElement(RenderHtml["a" /* default */], {
key: keys,
value: items.content === undefined || items.content === null ? "" : items.content
});
} else if (item.id === null && items.competition_stage_id === 0) {
return /*#__PURE__*/react_default.a.createElement(RenderHtml["a" /* default */], {
key: keys,
value: items.content === undefined || items.content === null ? "" : items.content
});
}
}));
})), (item === null || item === void 0 ? void 0 : (_item$children = item.children) === null || _item$children === void 0 ? void 0 : _item$children.length) > 0 && /*#__PURE__*/react_default.a.createElement(es_tabs["a" /* default */], {
activeKey: (items === null || items === void 0 ? void 0 : items.id) + '',
onChange: function onChange(e) {
var _item$children2;
var data = item === null || item === void 0 ? void 0 : (_item$children2 = item.children) === null || _item$children2 === void 0 ? void 0 : _item$children2.filter(function (item) {
return parseInt(e) === parseInt(item === null || item === void 0 ? void 0 : item.id);
})[0];
setItems(data);
getCharts(e); //获取参数
}
}, item === null || item === void 0 ? void 0 : (_item$children3 = item.children) === null || _item$children3 === void 0 ? void 0 : _item$children3.map(function (item, index) {
return /*#__PURE__*/react_default.a.createElement(TabPane, {
tab: item.name,
key: item.id === null ? 0 : item.id
});
})), isUpdate && /*#__PURE__*/react_default.a.createElement("div", null, /*#__PURE__*/react_default.a.createElement(components_markdown_editor, {
defaultValue: defaultValue,
onChange: function onChange(e) {
setDefaultValue(e);
}
}), /*#__PURE__*/react_default.a.createElement("p", {
style: {
marginTop: '10px'
}
}, /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
style: {
width: '90px'
},
type: "primary",
onClick: function onClick() {
return updateitem();
}
}, "\u63D0\u4EA4"), /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
style: {
marginLeft: '30px',
width: '90px'
},
onClick: function onClick() {
return setIsupdate(false);
}
}, "\u53D6\u6D88"))), (ItemData === null || ItemData === void 0 ? void 0 : (_ItemData$teams = ItemData.teams) === null || _ItemData$teams === void 0 ? void 0 : _ItemData$teams.length) > 0 && ((HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.task) === 'mAP' || (HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.task) === 'dog' || (HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.task) === 'Jittor-3') ? /*#__PURE__*/react_default.a.createElement(es_table["a" /* default */], {
dataSource: ItemData === null || ItemData === void 0 ? void 0 : ItemData.teams,
columns: columns,
pagination: false
}) : (ItemData === null || ItemData === void 0 ? void 0 : (_ItemData$teams2 = ItemData.teams) === null || _ItemData$teams2 === void 0 ? void 0 : _ItemData$teams2.length) > 0 && /*#__PURE__*/react_default.a.createElement(RankingList, {
ItemData: ItemData
}));
}
/* harmony default export */ var Detail_Ranking = (Ranking);
// EXTERNAL MODULE: ./node_modules/antd/es/divider/style/index.js
var divider_style = __webpack_require__("/zsF");
// EXTERNAL MODULE: ./node_modules/antd/es/divider/index.js
var divider = __webpack_require__("PArb");
// CONCATENATED MODULE: ./src/pages/Competitions/Detail/Downloadpdf.tsx
//下载页
function downpdf(_ref) {
var _Prize$personal_certi, _Prize$personal_certi2, _Prize$team_certifica, _Prize$team_certifica2, _Prize$teams, _Prize$teams$, _Prize$teams$2;
var Prize = _ref.Prize;
var params = Object(react_router["l" /* useParams */])();
var _useState = Object(react["useState"])([{
type: 1,
name: "团体奖证书"
}, {
type: 2,
name: "个人奖证书"
}, {
type: 3,
name: "优秀指导教师证书"
}]),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
certData = _useState2[0],
setCertData = _useState2[1];
var handleClick = /*#__PURE__*/function () {
var _ref2 = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee(item) {
var res;
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return Object(competitions["w" /* getCertificateInfo */])({
type: item.type,
id: params.identifier
});
case 2:
res = _context.sent;
if ((res === null || res === void 0 ? void 0 : res.status) === 0) location.href = "/competitions/exports?id=".concat(params.identifier, "&type=").concat(item.type);
case 4:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function handleClick(_x) {
return _ref2.apply(this, arguments);
};
}();
return /*#__PURE__*/react_default.a.createElement("div", null, /*#__PURE__*/react_default.a.createElement("p", {
className: Detailmodules_default.a.downloadpdf
}, "\u6E29\u99A8\u63D0\u793A\uFF1A\u586B\u5199\u7684\u4E2A\u4EBA\u4FE1\u606F\u7ECF\u5BA1\u6279\u540E\uFF0C\u5C06\u63D0\u4F9B\u4E2A\u4EBA\u83B7\u5956\u8BC1\u4E66\u4E0B\u8F7D\uFF1B\u56E2\u961F\u961F\u5458\u4FE1\u606F\u5168\u90E8\u5BA1\u6279\u540E\uFF0C\u5C06\u63D0\u4F9B\u56E2\u961F\u83B7\u5956\u8BC1\u4E66\u4E0B\u8F7D\u3002"), /*#__PURE__*/react_default.a.createElement("p", {
style: {
marginTop: '30px',
fontSize: '16px',
color: '#000'
}
}, "\u8BC1\u4E66\u60C5\u51B5"), (Prize === null || Prize === void 0 ? void 0 : (_Prize$personal_certi = Prize.personal_certifications) === null || _Prize$personal_certi === void 0 ? void 0 : _Prize$personal_certi.length) > 0 ? /*#__PURE__*/react_default.a.createElement("p", null, /*#__PURE__*/react_default.a.createElement("span", null, "\u4E2A\u4EBA\u8BC1\u4E66\uFF1A"), /*#__PURE__*/react_default.a.createElement("img", {
src: env["a" /* default */].IMG_SERVER + "/images/educoder/pdfs.png"
}), /*#__PURE__*/react_default.a.createElement("a", {
style: {
marginLeft: '5px'
},
href: env["a" /* default */].API_SERVER + "".concat(Prize === null || Prize === void 0 ? void 0 : (_Prize$personal_certi2 = Prize.personal_certifications[0]) === null || _Prize$personal_certi2 === void 0 ? void 0 : _Prize$personal_certi2.url)
}, "\u7ACB\u5373\u4E0B\u8F7D")) : /*#__PURE__*/react_default.a.createElement("p", null, /*#__PURE__*/react_default.a.createElement("span", null, "\u4E2A\u4EBA\u8BC1\u4E66\uFF1A"), " ", /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#000'
}
}, "\u6682\u672A\u751F\u6210"), /*#__PURE__*/react_default.a.createElement("span", {
style: {
marginLeft: '20px'
}
}, "\u539F\u56E0\uFF1A"), " ", /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#000'
}
}, "\u7EC4\u59D4\u4F1A\u672A\u5B8C\u6210\u8BC1\u4E66\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E")), (Prize === null || Prize === void 0 ? void 0 : (_Prize$team_certifica = Prize.team_certifications) === null || _Prize$team_certifica === void 0 ? void 0 : _Prize$team_certifica.length) > 0 ? /*#__PURE__*/react_default.a.createElement("p", null, /*#__PURE__*/react_default.a.createElement("span", null, "\u56E2\u961F\u8BC1\u4E66\uFF1A"), /*#__PURE__*/react_default.a.createElement("img", {
src: env["a" /* default */].IMG_SERVER + "/images/educoder/pdfs.png"
}), /*#__PURE__*/react_default.a.createElement("a", {
style: {
marginLeft: '5px'
},
href: env["a" /* default */].API_SERVER + "".concat(Prize === null || Prize === void 0 ? void 0 : (_Prize$team_certifica2 = Prize.team_certifications[0]) === null || _Prize$team_certifica2 === void 0 ? void 0 : _Prize$team_certifica2.url)
}, "\u7ACB\u5373\u4E0B\u8F7D")) : /*#__PURE__*/react_default.a.createElement("p", null, /*#__PURE__*/react_default.a.createElement("span", null, "\u56E2\u961F\u8BC1\u4E66\uFF1A"), " ", /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#000'
}
}, "\u6682\u672A\u751F\u6210")), /*#__PURE__*/react_default.a.createElement(divider["a" /* default */], null), (Prize === null || Prize === void 0 ? void 0 : (_Prize$teams = Prize.teams) === null || _Prize$teams === void 0 ? void 0 : _Prize$teams.length) > 0 ? /*#__PURE__*/react_default.a.createElement("div", null, /*#__PURE__*/react_default.a.createElement("p", null, (Prize === null || Prize === void 0 ? void 0 : Prize.teams) && (Prize === null || Prize === void 0 ? void 0 : (_Prize$teams$ = Prize.teams[0]) === null || _Prize$teams$ === void 0 ? void 0 : _Prize$teams$.name), "\u6218\u961F\u4FE1\u606F\u586B\u62A5\u6982\u51B5"), /*#__PURE__*/react_default.a.createElement("p", {
style: {
display: 'flex',
height: '50px',
background: '#f5f5f5',
alignItems: 'center',
justifyContent: 'space-around'
}
}, /*#__PURE__*/react_default.a.createElement("span", {
style: {
width: '5%'
}
}, "\u89D2\u8272"), /*#__PURE__*/react_default.a.createElement("span", {
style: {
width: '5%'
}
}, "\u59D3\u540D"), /*#__PURE__*/react_default.a.createElement("span", {
style: {
width: '10%'
}
}, "\u5B9E\u540D\u8BA4\u8BC1"), /*#__PURE__*/react_default.a.createElement("span", {
style: {
width: '10%'
}
}, "\u804C\u4E1A\u8BA4\u8BC1"), /*#__PURE__*/react_default.a.createElement("span", {
style: {
width: '10%'
}
}, "\u624B\u673A\u7ED1\u5B9A"), /*#__PURE__*/react_default.a.createElement("span", {
style: {
width: '10%'
}
}, "\u90AE\u7BB1\u7ED1\u5B9A"), /*#__PURE__*/react_default.a.createElement("span", {
style: {
width: '50%',
textAlign: 'center'
}
}, "\u5F00\u6237\u884C\u53CA\u94F6\u884C\u5361\u53F7\u4FE1\u606F\uFF08\u961F\u957F\u586B\u5199\uFF09")), (Prize === null || Prize === void 0 ? void 0 : Prize.teams) && (Prize === null || Prize === void 0 ? void 0 : (_Prize$teams$2 = Prize.teams[0]) === null || _Prize$teams$2 === void 0 ? void 0 : _Prize$teams$2.team_members.map(function (item, index) {
var _Prize$teams$3, _Prize$teams$3$bank_a, _Prize$teams$4, _Prize$teams$4$bank_a, _Prize$teams$5, _Prize$teams$5$bank_a;
return /*#__PURE__*/react_default.a.createElement("p", {
className: Detailmodules_default.a.teamItem
}, /*#__PURE__*/react_default.a.createElement("span", {
style: {
width: '5%'
}
}, item === null || item === void 0 ? void 0 : item.role), /*#__PURE__*/react_default.a.createElement("span", {
style: {
width: '5%'
}
}, item === null || item === void 0 ? void 0 : item.name), /*#__PURE__*/react_default.a.createElement("span", {
style: {
width: '10%'
}
}, (item === null || item === void 0 ? void 0 : item.real_name_auth) === "authed" ? '已认证' : (item === null || item === void 0 ? void 0 : item.real_name_auth) === "authing" ? '待审核' : '未认证'), /*#__PURE__*/react_default.a.createElement("span", {
style: {
width: '10%'
}
}, (item === null || item === void 0 ? void 0 : item.professional_auth) === "authed" ? '已认证' : (item === null || item === void 0 ? void 0 : item.professional_auth) === "authing" ? '待审核' : '未认证'), /*#__PURE__*/react_default.a.createElement("span", {
style: {
width: '10%'
}
}, (item === null || item === void 0 ? void 0 : item.phone_binded) ? '已绑定' : '未绑定'), /*#__PURE__*/react_default.a.createElement("span", {
style: {
width: '10%'
}
}, (item === null || item === void 0 ? void 0 : item.email_binded) ? '已绑定' : '未绑定'), (item === null || item === void 0 ? void 0 : item.role) === '队长' ? /*#__PURE__*/react_default.a.createElement("span", {
style: {
width: '50%',
textAlign: 'center'
}
}, (Prize === null || Prize === void 0 ? void 0 : Prize.teams) && (Prize === null || Prize === void 0 ? void 0 : (_Prize$teams$3 = Prize.teams[0]) === null || _Prize$teams$3 === void 0 ? void 0 : (_Prize$teams$3$bank_a = _Prize$teams$3.bank_account) === null || _Prize$teams$3$bank_a === void 0 ? void 0 : _Prize$teams$3$bank_a.bank), (Prize === null || Prize === void 0 ? void 0 : Prize.teams) && (Prize === null || Prize === void 0 ? void 0 : (_Prize$teams$4 = Prize.teams[0]) === null || _Prize$teams$4 === void 0 ? void 0 : (_Prize$teams$4$bank_a = _Prize$teams$4.bank_account) === null || _Prize$teams$4$bank_a === void 0 ? void 0 : _Prize$teams$4$bank_a.second_bank), (Prize === null || Prize === void 0 ? void 0 : Prize.teams) && (Prize === null || Prize === void 0 ? void 0 : (_Prize$teams$5 = Prize.teams[0]) === null || _Prize$teams$5 === void 0 ? void 0 : (_Prize$teams$5$bank_a = _Prize$teams$5.bank_account) === null || _Prize$teams$5$bank_a === void 0 ? void 0 : _Prize$teams$5$bank_a.card_no)) : /*#__PURE__*/react_default.a.createElement("span", {
style: {
width: '50%'
}
}));
}))) : null, /*#__PURE__*/react_default.a.createElement(es_row["a" /* default */], {
gutter: [20, 20]
}, certData.map(function (item, key) {
return /*#__PURE__*/react_default.a.createElement(es_col["a" /* default */], {
key: key
}, /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
type: "primary",
onClick: function onClick() {
return handleClick(item);
}
}, item.name));
})));
}
/* harmony default export */ var Downloadpdf = (downpdf);
// EXTERNAL MODULE: ./src/utils/util.tsx + 6 modules
var util = __webpack_require__("1vsH");
// EXTERNAL MODULE: ./src/assets/images/account/auth.png
var auth = __webpack_require__("Dgm7");
var auth_default = /*#__PURE__*/__webpack_require__.n(auth);
// EXTERNAL MODULE: ./src/pages/Competitions/Detail/component/index.less?modules
var componentmodules = __webpack_require__("NnUe");
var componentmodules_default = /*#__PURE__*/__webpack_require__.n(componentmodules);
// CONCATENATED MODULE: ./src/pages/Competitions/Detail/component/RealNameAuthModal.tsx
var RealNameAuthModal_Dragger = es_upload.Dragger;
var MAX_NAME_LENGTH = 10;
var RealNameAuthModal_RealNameAuthModal = function RealNameAuthModal(_ref) {
var user = _ref.user,
account = _ref.account,
globalSetting = _ref.globalSetting,
loading = _ref.loading,
dispatch = _ref.dispatch,
props = Object(objectWithoutProperties["a" /* default */])(_ref, ["user", "account", "globalSetting", "loading", "dispatch"]);
var _Form$useForm = es_form["a" /* default */].useForm(),
_Form$useForm2 = Object(slicedToArray["a" /* default */])(_Form$useForm, 1),
form = _Form$useForm2[0];
var _useState = Object(react["useState"])({}),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
formValue = _useState2[0],
setFormValue = _useState2[1];
var _useState3 = Object(react["useState"])(true),
_useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
showRealName = _useState4[0],
setShowRealName = _useState4[1];
var _useState5 = Object(react["useState"])(),
_useState6 = Object(slicedToArray["a" /* default */])(_useState5, 2),
realName = _useState6[0],
setRealName = _useState6[1];
var _useState7 = Object(react["useState"])(),
_useState8 = Object(slicedToArray["a" /* default */])(_useState7, 2),
image = _useState8[0],
setImage = _useState8[1];
var _useState9 = Object(react["useState"])(),
_useState10 = Object(slicedToArray["a" /* default */])(_useState9, 2),
fileId = _useState10[0],
setFileId = _useState10[1];
var _useState11 = Object(react["useState"])(),
_useState12 = Object(slicedToArray["a" /* default */])(_useState11, 2),
isLoading = _useState12[0],
setIsLoading = _useState12[1];
Object(react["useEffect"])(function () {
if (!account.basicInfo) {
return;
}
var basicInfo = account.basicInfo;
var formData = {
name: basicInfo.show_realname ? basicInfo.name : Object(util["j" /* getHiddenName */])(basicInfo.name),
gender: basicInfo.gender
};
setRealName(basicInfo.name);
setShowRealName(basicInfo.show_realname);
form.setFieldsValue(formData);
setFormValue(formData);
}, [account.basicInfo]);
var handleUploadChange = function handleUploadChange(info) {
if (info.file.status === 'uploading') {
setIsLoading(true);
return;
}
if (info.file.status === 'done') {
var _info$file$response;
console.log(info.file, info.file.response);
setFileId((_info$file$response = info.file.response) === null || _info$file$response === void 0 ? void 0 : _info$file$response.id);
Object(util["h" /* getBase64 */])(info.file.originFileObj, function (base64Img) {
setImage(base64Img);
setIsLoading(false);
});
}
};
var handleValuesChange = function handleValuesChange(changedValues) {
setFormValue(Object(objectSpread2["a" /* default */])({}, form.getFieldsValue()));
if ('name' in changedValues) {
setRealName(changedValues.name);
}
};
var handleSetShowRealName = function handleSetShowRealName() {
var nextRealNameStatus = !showRealName;
setShowRealName(nextRealNameStatus);
var nextName = nextRealNameStatus ? realName : Object(util["j" /* getHiddenName */])(realName);
form.setFieldsValue({
name: nextName
});
};
var handleFinish = /*#__PURE__*/function () {
var _ref2 = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee(values) {
var _account$basicInfo, _user$userInfo;
var _ref3, name, gender, id_number, res, _user$userInfo2;
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_ref3 = values || {}, name = _ref3.name, gender = _ref3.gender, id_number = _ref3.idNumber;
if (image) {
_context.next = 4;
break;
}
es_message["b" /* default */].info('请先上传照片!');
return _context.abrupt("return");
case 4:
_context.next = 6;
return dispatch({
type: 'account/applyRealNameAuth',
payload: {
id: ((_account$basicInfo = account.basicInfo) === null || _account$basicInfo === void 0 ? void 0 : _account$basicInfo.id) || ((_user$userInfo = user.userInfo) === null || _user$userInfo === void 0 ? void 0 : _user$userInfo.login),
name: name,
gender: gender,
id_number: id_number,
show_realname: showRealName,
attachment_ids: [fileId]
}
});
case 6:
res = _context.sent;
handleClose();
if (res) {
es_message["b" /* default */].info("申请已提交,请等待审核!");
dispatch({
type: 'account/getBasicInfo',
payload: {
login: (_user$userInfo2 = user.userInfo) === null || _user$userInfo2 === void 0 ? void 0 : _user$userInfo2.login
}
});
}
case 9:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function handleFinish(_x) {
return _ref2.apply(this, arguments);
};
}();
var handleClose = function handleClose() {
dispatch({
type: 'account/setActionTabs',
payload: {}
});
};
var uploadProps = {
data: {
type: "real_name"
},
multiple: true,
showUploadList: false,
action: "".concat(env["a" /* default */].API_SERVER, "/api/attachments.json"),
className: componentmodules_default.a.uploader,
onChange: handleUploadChange,
beforeUpload: function beforeUpload(file) {
var isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/bmp';
if (!isJpgOrPng) {
es_message["b" /* default */].info('请上传正确文件格式');
}
return isJpgOrPng;
}
};
return /*#__PURE__*/react_default.a.createElement(es_modal["a" /* default */], {
centered: true,
keyboard: false,
closable: false,
destroyOnClose: true,
visible: account.actionTabs.key === 'Account-RealNameAuth',
title: "\u4FEE\u6539\u5B9E\u540D\u4FE1\u606F",
width: "600px",
footer: null
}, /*#__PURE__*/react_default.a.createElement(spin["a" /* default */], {
spinning: !!isLoading
}, /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */], {
className: componentmodules_default.a.formWrap,
form: form,
layout: "horizontal",
onValuesChange: handleValuesChange,
onFinish: handleFinish
}, /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
label: "\u59D3\u540D",
name: "name",
labelCol: {
span: 3
},
wrapperCol: {
span: 12
},
rules: [{
required: true,
message: "\u8BF7\u8F93\u5165\u771F\u5B9E\u59D3\u540D\uFF0C\u6700\u5927\u9650\u5236".concat(MAX_NAME_LENGTH, "\u4E2A\u5B57\u7B26")
}, {
validator: util["l" /* handleValidatorName */]
}],
extra: /*#__PURE__*/react_default.a.createElement("span", null, showRealName ? '(显示:平台将显示您的真实姓名)' : '(隐藏:平台将显示你的昵称)')
}, /*#__PURE__*/react_default.a.createElement(es_input["a" /* default */], {
disabled: !showRealName,
placeholder: "\u8BF7\u8F93\u5165\u771F\u5B9E\u59D3\u540D\uFF0C\u6700\u5927\u9650\u5236".concat(MAX_NAME_LENGTH, "\u4E2A\u5B57\u7B26"),
maxLength: MAX_NAME_LENGTH,
addonAfter: /*#__PURE__*/react_default.a.createElement("i", {
className: "iconfont ".concat(showRealName ? 'icon-xianshi' : 'icon-yincang', " font18 ").concat(componentmodules_default.a.color4CACFF),
onClick: handleSetShowRealName
})
})), /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
label: "\u6027\u522B\uFF1A",
name: "gender",
labelCol: {
span: 3
},
wrapperCol: {
span: 12
},
rules: [{
required: true,
message: '请选择性别'
}]
}, /*#__PURE__*/react_default.a.createElement(es_radio["a" /* default */].Group, null, /*#__PURE__*/react_default.a.createElement(es_radio["a" /* default */], {
value: 0
}, "\u7537"), /*#__PURE__*/react_default.a.createElement(es_radio["a" /* default */], {
value: 1
}, "\u5973"))), /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
label: "\u8BC1\u4EF6\u53F7\uFF1A",
labelCol: {
span: 3
},
name: "idNumber",
rules: [{
required: true,
message: '请输入证件号'
}]
}, /*#__PURE__*/react_default.a.createElement(es_input["a" /* default */], {
placeholder: "\u8BF7\u8F93\u5165\u8BC1\u4EF6\u53F7"
})), /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
label: "\u8EAB\u4EFD\u8BC1\u4E0A\u4F20",
labelCol: {
span: 3
}
}, /*#__PURE__*/react_default.a.createElement("div", {
className: componentmodules_default.a.flexRow
}, /*#__PURE__*/react_default.a.createElement("div", {
className: "".concat(componentmodules_default.a.flexColumn, " ").concat(componentmodules_default.a.example)
}, /*#__PURE__*/react_default.a.createElement("span", {
className: componentmodules_default.a.exampleImg
}, /*#__PURE__*/react_default.a.createElement("img", {
src: auth_default.a
})), /*#__PURE__*/react_default.a.createElement("span", {
className: "tc"
}, /*#__PURE__*/react_default.a.createElement("p", null, "\u793A\u4F8B\u56FE\u7247"), /*#__PURE__*/react_default.a.createElement("p", {
className: "".concat(componentmodules_default.a.colorOrange, " font12")
}, "\uFF08png/jpg/bmp\u683C\u5F0F\uFF0C\u4E0D\u8D85\u8FC72MB\uFF09"))), /*#__PURE__*/react_default.a.createElement("div", {
className: componentmodules_default.a.flexColumn
}, /*#__PURE__*/react_default.a.createElement(RealNameAuthModal_Dragger, Object(esm_extends["a" /* default */])({}, uploadProps, {
accept: ".png,.jpg,.bmp,.jpeg"
}), image ? /*#__PURE__*/react_default.a.createElement("img", {
src: image,
className: componentmodules_default.a.uploadImg
}) : /*#__PURE__*/react_default.a.createElement("div", {
className: componentmodules_default.a.imageTip
}, /*#__PURE__*/react_default.a.createElement("p", null, /*#__PURE__*/react_default.a.createElement("i", {
className: "iconfont icon-cuban2shangchuanyunduan ".concat(componentmodules_default.a.uploadTipIcon)
})), /*#__PURE__*/react_default.a.createElement("p", {
className: componentmodules_default.a.uploadTip
}, /*#__PURE__*/react_default.a.createElement("a", {
className: componentmodules_default.a.color05101a
}, "\u70B9\u51FB\u6216\u62D6\u62FD\u4E0A\u4F20\u56FE\u7247")))), /*#__PURE__*/react_default.a.createElement("span", {
className: "tc"
}, /*#__PURE__*/react_default.a.createElement("p", {
className: componentmodules_default.a.viewLargerImg
}, "\u67E5\u770B\u5927\u56FE"))))), /*#__PURE__*/react_default.a.createElement("div", {
className: componentmodules_default.a.footerWrap
}, /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, null, /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
className: "mr5",
size: "large",
onClick: handleClose
}, "\u53D6\u6D88"), /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
size: "large",
type: "primary",
htmlType: "submit",
loading: loading['account/applyRealNameAuth']
}, "\u4FDD\u5B58"))), /*#__PURE__*/react_default.a.createElement("div", {
className: componentmodules_default.a.note
}, /*#__PURE__*/react_default.a.createElement("p", null, "\u8BA4\u8BC1\u987B\u77E5\uFF1A"), /*#__PURE__*/react_default.a.createElement("p", null, "1.\u4F60\u9700\u8981\u51C6\u5907\u6709\u6548\u7684\u8EAB\u4EFD\u8BC1\u6B63\u9762\uFF08\u4EBA\u50CF\u9762\uFF09\u7684\u8BC1\u4EF6\u7167\u7167\u7247\uFF0C\u8BF7\u786E\u4FDD\u8BC1\u4EF6\u7167\u7247\u6E05\u6670\u53EF\u89C1\uFF0C\u4E25\u7981PS\uFF1B"), /*#__PURE__*/react_default.a.createElement("p", null, "2.\u6211\u4EEC\u5C06\u5728\u4F60\u63D0\u4EA4\u8BA4\u8BC1\u4FE1\u606F\u540E\u768424\u5C0F\u65F6\uFF08\u4E0D\u5305\u542B\u8282\u5047\u65E5\uFF09\u5185\u5B8C\u6210\u5BA1\u6838\uFF0C\u5BA1\u6838\u7ED3\u679C\u5C06\u4F1A\u4EE5\u7CFB\u7EDF\u6D88\u606F\u7684\u5F62\u5F0F\u53D1\u9001\u7ED9\u4F60\uFF1B"), /*#__PURE__*/react_default.a.createElement("p", null, "3.\u5B9E\u540D\u8BA4\u8BC1\u5BA1\u6838\u5B8C\u6210\u540E\uFF0C\u65E0\u6CD5\u5220\u9664\uFF0C\u8BF7\u8C28\u614E\u586B\u5199\uFF1B"), /*#__PURE__*/react_default.a.createElement("p", null, "4.\u5B9E\u540D\u8BA4\u8BC1\u5BA1\u6838\u5B8C\u6210\u540E\uFF0C\u7CFB\u7EDF\u5C06\u81EA\u52A8\u53D1\u653E500\u4E2A\u91D1\u5E01\u4F5C\u4E3A\u5956\u52B1\uFF1B"), /*#__PURE__*/react_default.a.createElement("p", null, "5.\u6211\u4EEC\u4F1A\u786E\u4FDD\u4F60\u6240\u63D0\u4F9B\u7684\u4FE1\u606F\u5747\u5904\u4E8E\u4E25\u683C\u7684\u4FDD\u5BC6\u72B6\u6001\uFF0C\u4E0D\u4F1A\u6CC4\u9732\uFF1B"), /*#__PURE__*/react_default.a.createElement("p", null, "6.\u5982\u5B58\u5728\u6076\u610F\u4E71\u586B\u5199\u59D3\u540D\uFF0C\u8BC1\u4EF6\u53F7\uFF0C\u53CA\u4E0A\u4F20\u4E0E\u5B9E\u540D\u8BA4\u8BC1\u8BC1\u4EF6\u65E0\u5173\u56FE\u7247\u8005\uFF0C\u4E00\u7ECF\u53D1\u73B0\u5C06\u51BB\u7ED3EduCoder\u8D26\u53F7\u3002"), /*#__PURE__*/react_default.a.createElement("p", null, "7.\u63D0\u4EA4\u5B9E\u540D\u8BA4\u8BC1\u540E\u7CFB\u7EDF\u4F1A\u81EA\u52A8\u5C06\u72B6\u6001\u6539\u4E3A\u5DF2\u8BA4\u8BC1\uFF0C\u4F60\u5C06\u53EF\u4EE5\u4F53\u9A8C\u5E73\u53F0\u9700\u8981\u5B9E\u540D\u8BA4\u8BC1\u7684\u529F\u80FD\uFF1B\u5982\u679C\u5728\u8BA4\u8BC1\u540E\u7684\u4F7F\u7528\u8FC7\u7A0B\u4E2D\u672A\u901A\u8FC7\u5BA1\u6838\uFF0C\u4F60\u5C06\u4E0D\u80FD\u7EE7\u7EED\u4F53\u9A8C\u9700\u8981\u8BA4\u8BC1\u7684\u529F\u80FD\u3002")))));
};
/* harmony default export */ var component_RealNameAuthModal = (Object(umiExports["a" /* connect */])(function (_ref4) {
var user = _ref4.user,
account = _ref4.account,
loading = _ref4.loading,
globalSetting = _ref4.globalSetting;
return {
user: user,
account: account,
globalSetting: globalSetting,
loading: loading.effects
};
})(RealNameAuthModal_RealNameAuthModal));
// EXTERNAL MODULE: ./node_modules/antd/es/auto-complete/style/index.less
var auto_complete_style = __webpack_require__("O/iA");
// CONCATENATED MODULE: ./node_modules/antd/es/auto-complete/style/index.js
// style dependencies
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/typeof.js
var helpers_typeof = __webpack_require__("cDf5");
var typeof_default = /*#__PURE__*/__webpack_require__.n(helpers_typeof);
// EXTERNAL MODULE: ./node_modules/rc-util/es/Children/toArray.js
var Children_toArray = __webpack_require__("Zm9Q");
// CONCATENATED MODULE: ./node_modules/antd/es/auto-complete/index.js
/**
* TODO: 4.0
* - remove `dataSource`
* - `size` not work with customizeInput
* - customizeInput not feedback `ENTER` key since accessibility enhancement
*/
var auto_complete_Option = es_select["a" /* default */].Option;
var InternalSelect = es_select["a" /* default */];
function isSelectOptionOrSelectOptGroup(child) {
return child && child.type && (child.type.isSelectOption || child.type.isSelectOptGroup);
}
var auto_complete_AutoComplete = function AutoComplete(props, ref) {
var customizePrefixCls = props.prefixCls,
className = props.className,
children = props.children,
dataSource = props.dataSource;
var childNodes = Object(Children_toArray["a" /* default */])(children);
var selectRef = react["useRef"]();
react["useImperativeHandle"](ref, function () {
return selectRef.current;
}); // ============================= Input =============================
var customizeInput;
if (childNodes.length === 1 && Object(reactNode["b" /* isValidElement */])(childNodes[0]) && !isSelectOptionOrSelectOptGroup(childNodes[0])) {
var _childNodes = slicedToArray_default()(childNodes, 1);
customizeInput = _childNodes[0];
}
var getInputElement = function getInputElement() {
return customizeInput;
}; // ============================ Options ============================
var optionChildren; // [Legacy] convert `children` or `dataSource` into option children
if (childNodes.length && isSelectOptionOrSelectOptGroup(childNodes[0])) {
optionChildren = children;
} else {
optionChildren = dataSource ? dataSource.map(function (item) {
if (Object(reactNode["b" /* isValidElement */])(item)) {
return item;
}
switch (typeof_default()(item)) {
case 'string':
return /*#__PURE__*/react["createElement"](auto_complete_Option, {
key: item,
value: item
}, item);
case 'object':
{
var optionValue = item.value;
return /*#__PURE__*/react["createElement"](auto_complete_Option, {
key: optionValue,
value: optionValue
}, item.text);
}
default:
throw new Error('AutoComplete[dataSource] only supports type `string[] | Object[]`.');
}
}) : [];
} // ============================ Warning ============================
react["useEffect"](function () {
Object(devWarning["a" /* default */])(!('dataSource' in props), 'AutoComplete', '`dataSource` is deprecated, please use `options` instead.');
Object(devWarning["a" /* default */])(!customizeInput || !('size' in props), 'AutoComplete', 'You need to control style self instead of setting `size` when using customize input.');
}, []);
return /*#__PURE__*/react["createElement"](context["a" /* ConfigConsumer */], null, function (_ref) {
var getPrefixCls = _ref.getPrefixCls;
var prefixCls = getPrefixCls('select', customizePrefixCls);
return /*#__PURE__*/react["createElement"](InternalSelect, extends_default()({
ref: selectRef
}, Object(omit_js_es["a" /* default */])(props, ['dataSource']), {
prefixCls: prefixCls,
className: classnames_default()(className, "".concat(prefixCls, "-auto-complete")),
mode: es_select["a" /* default */].SECRET_COMBOBOX_MODE_DO_NOT_USE,
getInputElement: getInputElement
}), optionChildren);
});
};
var RefAutoComplete = /*#__PURE__*/react["forwardRef"](auto_complete_AutoComplete);
RefAutoComplete.Option = auto_complete_Option;
/* harmony default export */ var auto_complete = (RefAutoComplete);
// EXTERNAL MODULE: ./src/assets/images/account/job.png
var job = __webpack_require__("KXlV");
var job_default = /*#__PURE__*/__webpack_require__.n(job);
// EXTERNAL MODULE: ./src/pages/Competitions/Detail/components/AppplyDepartmentModal/index.less?modules
var AppplyDepartmentModalmodules = __webpack_require__("Sjjz");
var AppplyDepartmentModalmodules_default = /*#__PURE__*/__webpack_require__.n(AppplyDepartmentModalmodules);
// CONCATENATED MODULE: ./src/pages/Competitions/Detail/components/AppplyDepartmentModal/index.tsx
var TextArea = es_input["a" /* default */].TextArea;
var AppplyDepartmentModal_AppplyDepartmentModal = function AppplyDepartmentModal(_ref) {
var account = _ref.account,
globalSetting = _ref.globalSetting,
loading = _ref.loading,
dispatch = _ref.dispatch,
schoolName = _ref.schoolName,
departmentName = _ref.departmentName,
visible = _ref.visible,
_ref$onClose = _ref.onClose,
onClose = _ref$onClose === void 0 ? function () {} : _ref$onClose,
_ref$onSuccess = _ref.onSuccess,
onSuccess = _ref$onSuccess === void 0 ? function () {} : _ref$onSuccess,
props = Object(objectWithoutProperties["a" /* default */])(_ref, ["account", "globalSetting", "loading", "dispatch", "schoolName", "departmentName", "visible", "onClose", "onSuccess"]);
var _Form$useForm = es_form["a" /* default */].useForm(),
_Form$useForm2 = Object(slicedToArray["a" /* default */])(_Form$useForm, 1),
form = _Form$useForm2[0];
var schoolId = Object(react["useRef"])();
Object(react["useEffect"])(function () {
schoolId.current = props.schoolId;
}, [props.schoolId]);
Object(react["useEffect"])(function () {
form.setFieldsValue({
department: departmentName
});
}, [departmentName]);
var handleFinish = /*#__PURE__*/function () {
var _ref2 = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee(values) {
var _ref3, department, remarks, res;
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_ref3 = values || {}, department = _ref3.department, remarks = _ref3.remarks;
_context.next = 3;
return dispatch({
type: 'account/appplyDepartment',
payload: {
school_id: schoolId.current,
name: department,
remarks: remarks
}
});
case 3:
res = _context.sent;
onClose();
if (res) {
es_message["b" /* default */].success("新增院系/部门成功!");
onSuccess(department);
}
case 6:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function handleFinish(_x) {
return _ref2.apply(this, arguments);
};
}();
return /*#__PURE__*/react_default.a.createElement(es_modal["a" /* default */], {
centered: true,
keyboard: false,
closable: false,
destroyOnClose: true,
visible: visible,
title: "\u7533\u8BF7\u6DFB\u52A0\u5B50\u5355\u4F4D\u540D\u79F0",
width: "600px",
footer: null
}, /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */], {
className: AppplyDepartmentModalmodules_default.a.formWrap,
form: form,
labelCol: {
span: 4
},
wrapperCol: {
span: 20
},
onFinish: handleFinish
}, /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
label: "\u5355\u4F4D\u540D\u79F0\uFF1A"
}, schoolName), /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
label: "\u90E8\u95E8\u540D\u79F0\uFF1A",
name: "department",
rules: [{
required: true,
message: '请输入部门或者学院名称'
}]
}, /*#__PURE__*/react_default.a.createElement(es_input["a" /* default */], {
placeholder: "\u8BF7\u8F93\u5165\u90E8\u95E8\u6216\u8005\u5B66\u9662\u540D\u79F0"
})), /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
label: "\u8BF4\u660E\uFF1A",
name: "remarks"
}, /*#__PURE__*/react_default.a.createElement(TextArea, {
placeholder: "\u518D\u6B21\u8BF4\u660E\u7279\u522B\u60C5\u51B5\uFF08\u9009\u586B\uFF09"
})), /*#__PURE__*/react_default.a.createElement("div", {
className: AppplyDepartmentModalmodules_default.a.footerWrap
}, /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, null, /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
className: "mr5",
size: "large",
onClick: function onClick() {
onClose();
}
}, "\u53D6\u6D88"), /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
size: "large",
type: "primary",
htmlType: "submit",
loading: loading['account/appplyDepartment']
}, "\u4FDD\u5B58")))));
};
/* harmony default export */ var components_AppplyDepartmentModal = (Object(umiExports["a" /* connect */])(function (_ref4) {
var account = _ref4.account,
loading = _ref4.loading,
globalSetting = _ref4.globalSetting;
return {
account: account,
globalSetting: globalSetting,
loading: loading.effects
};
})(AppplyDepartmentModal_AppplyDepartmentModal));
// EXTERNAL MODULE: ./node_modules/antd/es/cascader/style/index.less
var cascader_style = __webpack_require__("v56E");
// EXTERNAL MODULE: ./node_modules/antd/es/empty/style/index.js
var empty_style = __webpack_require__("R9oj");
// CONCATENATED MODULE: ./node_modules/antd/es/cascader/style/index.js
// style dependencies
// EXTERNAL MODULE: ./node_modules/rc-trigger/es/index.js + 5 modules
var rc_trigger_es = __webpack_require__("uciX");
// EXTERNAL MODULE: ./node_modules/warning/warning.js
var warning = __webpack_require__("2W6z");
var warning_default = /*#__PURE__*/__webpack_require__.n(warning);
// EXTERNAL MODULE: ./node_modules/array-tree-filter/lib/index.js
var lib = __webpack_require__("uK0f");
var lib_default = /*#__PURE__*/__webpack_require__.n(lib);
// CONCATENATED MODULE: ./node_modules/rc-cascader/es/utils.js
function isEqualArrays(arrA, arrB) {
if (arrA === arrB) {
return true;
}
if (!arrA || !arrB) {
return false;
}
var len = arrA.length;
if (arrB.length !== len) {
return false;
} // eslint-disable-next-line no-plusplus
for (var i = 0; i < len; i++) {
if (arrA[i] !== arrB[i]) {
return false;
}
}
return true;
}
// CONCATENATED MODULE: ./node_modules/rc-cascader/es/Menus.js
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function Menus_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
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 Menus_createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function Menus_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function Menus_createSuper(Derived) { var hasNativeReflectConstruct = Menus_isNativeReflectConstruct(); return function () { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return Menus_possibleConstructorReturn(this, result); }; }
function Menus_possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function Menus_isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
var Menus_Menus =
/** @class */
function () {
var Menus = /*#__PURE__*/function (_React$Component) {
Menus_inherits(Menus, _React$Component);
var _super = Menus_createSuper(Menus);
function Menus() {
var _this;
Menus_classCallCheck(this, Menus);
_this = _super.apply(this, arguments);
_this.menuItems = {};
_this.saveMenuItem = function (index) {
return function (node) {
_this.menuItems[index] = node;
};
};
return _this;
}
Menus_createClass(Menus, [{
key: "componentDidMount",
value: function componentDidMount() {
this.scrollActiveItemToView();
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (!prevProps.visible && this.props.visible) {
this.scrollActiveItemToView();
}
}
}, {
key: "getFieldName",
value: function getFieldName(name) {
var _this$props = this.props,
fieldNames = _this$props.fieldNames,
defaultFieldNames = _this$props.defaultFieldNames; // 防止只设置单个属性的名字
return fieldNames[name] || defaultFieldNames[name];
}
}, {
key: "getOption",
value: function getOption(option, menuIndex) {
var _this$props2 = this.props,
prefixCls = _this$props2.prefixCls,
expandTrigger = _this$props2.expandTrigger,
expandIcon = _this$props2.expandIcon,
loadingIcon = _this$props2.loadingIcon;
var onSelect = this.props.onSelect.bind(this, option, menuIndex);
var onItemDoubleClick = this.props.onItemDoubleClick.bind(this, option, menuIndex);
var expandProps = {
onClick: onSelect,
onDoubleClick: onItemDoubleClick
};
var menuItemCls = "".concat(prefixCls, "-menu-item");
var expandIconNode = null;
var hasChildren = option[this.getFieldName('children')] && option[this.getFieldName('children')].length > 0;
if (hasChildren || option.isLeaf === false) {
menuItemCls += " ".concat(prefixCls, "-menu-item-expand");
if (!option.loading) {
expandIconNode = react["createElement"]("span", {
className: "".concat(prefixCls, "-menu-item-expand-icon")
}, expandIcon);
}
}
if (expandTrigger === 'hover' && (hasChildren || option.isLeaf === false)) {
expandProps = {
onMouseEnter: this.delayOnSelect.bind(this, onSelect),
onMouseLeave: this.delayOnSelect.bind(this),
onClick: onSelect
};
}
if (this.isActiveOption(option, menuIndex)) {
menuItemCls += " ".concat(prefixCls, "-menu-item-active");
expandProps.ref = this.saveMenuItem(menuIndex);
}
if (option.disabled) {
menuItemCls += " ".concat(prefixCls, "-menu-item-disabled");
}
var loadingIconNode = null;
if (option.loading) {
menuItemCls += " ".concat(prefixCls, "-menu-item-loading");
loadingIconNode = loadingIcon || null;
}
var title = '';
if ('title' in option) {
// eslint-disable-next-line prefer-destructuring
title = option.title;
} else if (typeof option[this.getFieldName('label')] === 'string') {
title = option[this.getFieldName('label')];
}
return react["createElement"]("li", Object.assign({
key: option[this.getFieldName('value')],
className: menuItemCls,
title: title
}, expandProps, {
role: "menuitem",
onMouseDown: function onMouseDown(e) {
return e.preventDefault();
}
}), option[this.getFieldName('label')], expandIconNode, loadingIconNode);
}
}, {
key: "getActiveOptions",
value: function getActiveOptions(values) {
var _this2 = this;
var options = this.props.options;
var activeValue = values || this.props.activeValue;
return lib_default()(options, function (o, level) {
return o[_this2.getFieldName('value')] === activeValue[level];
}, {
childrenKeyName: this.getFieldName('children')
});
}
}, {
key: "getShowOptions",
value: function getShowOptions() {
var _this3 = this;
var options = this.props.options;
var result = this.getActiveOptions().map(function (activeOption) {
return activeOption[_this3.getFieldName('children')];
}).filter(function (activeOption) {
return !!activeOption;
});
result.unshift(options);
return result;
}
}, {
key: "delayOnSelect",
value: function delayOnSelect(onSelect) {
var _this4 = this;
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
if (this.delayTimer) {
clearTimeout(this.delayTimer);
this.delayTimer = null;
}
if (typeof onSelect === 'function') {
this.delayTimer = window.setTimeout(function () {
onSelect(args);
_this4.delayTimer = null;
}, 150);
}
}
}, {
key: "scrollActiveItemToView",
value: function scrollActiveItemToView() {
// scroll into view
var optionsLength = this.getShowOptions().length; // eslint-disable-next-line no-plusplus
for (var i = 0; i < optionsLength; i++) {
var itemComponent = this.menuItems[i];
if (itemComponent && itemComponent.parentElement) {
itemComponent.parentElement.scrollTop = itemComponent.offsetTop;
}
}
}
}, {
key: "isActiveOption",
value: function isActiveOption(option, menuIndex) {
var _this$props$activeVal = this.props.activeValue,
activeValue = _this$props$activeVal === void 0 ? [] : _this$props$activeVal;
return activeValue[menuIndex] === option[this.getFieldName('value')];
}
}, {
key: "render",
value: function render() {
var _this5 = this;
var _this$props3 = this.props,
prefixCls = _this$props3.prefixCls,
dropdownMenuColumnStyle = _this$props3.dropdownMenuColumnStyle;
return react["createElement"]("div", null, this.getShowOptions().map(function (options, menuIndex) {
return react["createElement"]("ul", {
className: "".concat(prefixCls, "-menu"),
key: menuIndex,
style: dropdownMenuColumnStyle
}, options.map(function (option) {
return _this5.getOption(option, menuIndex);
}));
}));
}
}]);
return Menus;
}(react["Component"]);
Menus.defaultProps = {
options: [],
value: [],
activeValue: [],
onSelect: function onSelect() {},
prefixCls: 'rc-cascader-menus',
visible: false,
expandTrigger: 'click'
};
return Menus;
}();
/* harmony default export */ var es_Menus = (Menus_Menus);
// CONCATENATED MODULE: ./node_modules/rc-cascader/es/placements.js
var BUILT_IN_PLACEMENTS = {
bottomLeft: {
points: ['tl', 'bl'],
offset: [0, 4],
overflow: {
adjustX: 1,
adjustY: 1
}
},
topLeft: {
points: ['bl', 'tl'],
offset: [0, -4],
overflow: {
adjustX: 1,
adjustY: 1
}
},
bottomRight: {
points: ['tr', 'br'],
offset: [0, 4],
overflow: {
adjustX: 1,
adjustY: 1
}
},
topRight: {
points: ['br', 'tr'],
offset: [0, -4],
overflow: {
adjustX: 1,
adjustY: 1
}
}
};
/* harmony default export */ var placements = (BUILT_IN_PLACEMENTS);
// CONCATENATED MODULE: ./node_modules/rc-cascader/es/Cascader.js
function Cascader_typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { Cascader_typeof = function _typeof(obj) { return typeof obj; }; } else { Cascader_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return Cascader_typeof(obj); }
function Cascader_objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = Cascader_objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function Cascader_objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || Cascader_unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function Cascader_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return Cascader_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 Cascader_arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return Cascader_arrayLikeToArray(arr); }
function Cascader_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 Cascader_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function Cascader_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 Cascader_createClass(Constructor, protoProps, staticProps) { if (protoProps) Cascader_defineProperties(Constructor.prototype, protoProps); if (staticProps) Cascader_defineProperties(Constructor, staticProps); return Constructor; }
function Cascader_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) Cascader_setPrototypeOf(subClass, superClass); }
function Cascader_setPrototypeOf(o, p) { Cascader_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return Cascader_setPrototypeOf(o, p); }
function Cascader_createSuper(Derived) { var hasNativeReflectConstruct = Cascader_isNativeReflectConstruct(); return function () { var Super = Cascader_getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = Cascader_getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return Cascader_possibleConstructorReturn(this, result); }; }
function Cascader_possibleConstructorReturn(self, call) { if (call && (Cascader_typeof(call) === "object" || typeof call === "function")) { return call; } return Cascader_assertThisInitialized(self); }
function Cascader_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function Cascader_isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
function Cascader_getPrototypeOf(o) { Cascader_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return Cascader_getPrototypeOf(o); }
var Cascader_Cascader =
/** @class */
function () {
var Cascader = /*#__PURE__*/function (_React$Component) {
Cascader_inherits(Cascader, _React$Component);
var _super = Cascader_createSuper(Cascader);
function Cascader(props) {
var _this;
Cascader_classCallCheck(this, Cascader);
_this = _super.call(this, props);
_this.setPopupVisible = function (popupVisible) {
var value = _this.state.value;
if (!('popupVisible' in _this.props)) {
_this.setState({
popupVisible: popupVisible
});
} // sync activeValue with value when panel open
if (popupVisible && !_this.state.popupVisible) {
_this.setState({
activeValue: value
});
}
_this.props.onPopupVisibleChange(popupVisible);
};
_this.handleChange = function (options, _ref, e) {
var visible = _ref.visible;
if (e.type !== 'keydown' || e.keyCode === KeyCode["a" /* default */].ENTER) {
_this.props.onChange(options.map(function (o) {
return o[_this.getFieldName('value')];
}), options);
_this.setPopupVisible(visible);
}
};
_this.handlePopupVisibleChange = function (popupVisible) {
_this.setPopupVisible(popupVisible);
};
_this.handleMenuSelect = function (targetOption, menuIndex, e) {
// Keep focused state for keyboard support
var triggerNode = _this.trigger.getRootDomNode();
if (triggerNode && triggerNode.focus) {
triggerNode.focus();
}
var _this$props = _this.props,
changeOnSelect = _this$props.changeOnSelect,
loadData = _this$props.loadData,
expandTrigger = _this$props.expandTrigger;
if (!targetOption || targetOption.disabled) {
return;
}
var activeValue = _this.state.activeValue;
activeValue = activeValue.slice(0, menuIndex + 1);
activeValue[menuIndex] = targetOption[_this.getFieldName('value')];
var activeOptions = _this.getActiveOptions(activeValue);
if (targetOption.isLeaf === false && !targetOption[_this.getFieldName('children')] && loadData) {
if (changeOnSelect) {
_this.handleChange(activeOptions, {
visible: true
}, e);
}
_this.setState({
activeValue: activeValue
});
loadData(activeOptions);
return;
}
var newState = {};
if (!targetOption[_this.getFieldName('children')] || !targetOption[_this.getFieldName('children')].length) {
_this.handleChange(activeOptions, {
visible: false
}, e); // set value to activeValue when select leaf option
newState.value = activeValue; // add e.type judgement to prevent `onChange` being triggered by mouseEnter
} else if (changeOnSelect && (e.type === 'click' || e.type === 'keydown')) {
if (expandTrigger === 'hover') {
_this.handleChange(activeOptions, {
visible: false
}, e);
} else {
_this.handleChange(activeOptions, {
visible: true
}, e);
} // set value to activeValue on every select
newState.value = activeValue;
}
newState.activeValue = activeValue; // not change the value by keyboard
if ('value' in _this.props || e.type === 'keydown' && e.keyCode !== KeyCode["a" /* default */].ENTER) {
delete newState.value;
}
_this.setState(newState);
};
_this.handleItemDoubleClick = function () {
var changeOnSelect = _this.props.changeOnSelect;
if (changeOnSelect) {
_this.setPopupVisible(false);
}
};
_this.handleKeyDown = function (e) {
var children = _this.props.children; // https://github.com/ant-design/ant-design/issues/6717
// Don't bind keyboard support when children specify the onKeyDown
if (children && children.props.onKeyDown) {
children.props.onKeyDown(e);
return;
}
var activeValue = _toConsumableArray(_this.state.activeValue);
var currentLevel = activeValue.length - 1 < 0 ? 0 : activeValue.length - 1;
var currentOptions = _this.getCurrentLevelOptions();
var currentIndex = currentOptions.map(function (o) {
return o[_this.getFieldName('value')];
}).indexOf(activeValue[currentLevel]);
if (e.keyCode !== KeyCode["a" /* default */].DOWN && e.keyCode !== KeyCode["a" /* default */].UP && e.keyCode !== KeyCode["a" /* default */].LEFT && e.keyCode !== KeyCode["a" /* default */].RIGHT && e.keyCode !== KeyCode["a" /* default */].ENTER && e.keyCode !== KeyCode["a" /* default */].SPACE && e.keyCode !== KeyCode["a" /* default */].BACKSPACE && e.keyCode !== KeyCode["a" /* default */].ESC && e.keyCode !== KeyCode["a" /* default */].TAB) {
return;
} // Press any keys above to reopen menu
if (!_this.state.popupVisible && e.keyCode !== KeyCode["a" /* default */].BACKSPACE && e.keyCode !== KeyCode["a" /* default */].LEFT && e.keyCode !== KeyCode["a" /* default */].RIGHT && e.keyCode !== KeyCode["a" /* default */].ESC && e.keyCode !== KeyCode["a" /* default */].TAB) {
_this.setPopupVisible(true);
return;
}
if (e.keyCode === KeyCode["a" /* default */].DOWN || e.keyCode === KeyCode["a" /* default */].UP) {
e.preventDefault();
var nextIndex = currentIndex;
if (nextIndex !== -1) {
if (e.keyCode === KeyCode["a" /* default */].DOWN) {
nextIndex += 1;
nextIndex = nextIndex >= currentOptions.length ? 0 : nextIndex;
} else {
nextIndex -= 1;
nextIndex = nextIndex < 0 ? currentOptions.length - 1 : nextIndex;
}
} else {
nextIndex = 0;
}
activeValue[currentLevel] = currentOptions[nextIndex][_this.getFieldName('value')];
} else if (e.keyCode === KeyCode["a" /* default */].LEFT || e.keyCode === KeyCode["a" /* default */].BACKSPACE) {
e.preventDefault();
activeValue.splice(activeValue.length - 1, 1);
} else if (e.keyCode === KeyCode["a" /* default */].RIGHT) {
e.preventDefault();
if (currentOptions[currentIndex] && currentOptions[currentIndex][_this.getFieldName('children')]) {
activeValue.push(currentOptions[currentIndex][_this.getFieldName('children')][0][_this.getFieldName('value')]);
}
} else if (e.keyCode === KeyCode["a" /* default */].ESC || e.keyCode === KeyCode["a" /* default */].TAB) {
_this.setPopupVisible(false);
return;
}
if (!activeValue || activeValue.length === 0) {
_this.setPopupVisible(false);
}
var activeOptions = _this.getActiveOptions(activeValue);
var targetOption = activeOptions[activeOptions.length - 1];
_this.handleMenuSelect(targetOption, activeOptions.length - 1, e);
if (_this.props.onKeyDown) {
_this.props.onKeyDown(e);
}
};
_this.saveTrigger = function (node) {
_this.trigger = node;
};
var initialValue = [];
if ('value' in props) {
initialValue = props.value || [];
} else if ('defaultValue' in props) {
initialValue = props.defaultValue || [];
}
warning_default()(!('filedNames' in props), '`filedNames` of Cascader is a typo usage and deprecated, please use `fieldNames` instead.');
_this.state = {
popupVisible: props.popupVisible,
activeValue: initialValue,
value: initialValue,
prevProps: props
};
_this.defaultFieldNames = {
label: 'label',
value: 'value',
children: 'children'
};
return _this;
}
Cascader_createClass(Cascader, [{
key: "getPopupDOMNode",
value: function getPopupDOMNode() {
return this.trigger.getPopupDomNode();
}
}, {
key: "getFieldName",
value: function getFieldName(name) {
var defaultFieldNames = this.defaultFieldNames;
var _this$props2 = this.props,
fieldNames = _this$props2.fieldNames,
filedNames = _this$props2.filedNames;
if ('filedNames' in this.props) {
return filedNames[name] || defaultFieldNames[name]; // For old compatibility
}
return fieldNames[name] || defaultFieldNames[name];
}
}, {
key: "getFieldNames",
value: function getFieldNames() {
var _this$props3 = this.props,
fieldNames = _this$props3.fieldNames,
filedNames = _this$props3.filedNames;
if ('filedNames' in this.props) {
return filedNames; // For old compatibility
}
return fieldNames;
}
}, {
key: "getCurrentLevelOptions",
value: function getCurrentLevelOptions() {
var _this2 = this;
var _this$props$options = this.props.options,
options = _this$props$options === void 0 ? [] : _this$props$options;
var _this$state$activeVal = this.state.activeValue,
activeValue = _this$state$activeVal === void 0 ? [] : _this$state$activeVal;
var result = lib_default()(options, function (o, level) {
return o[_this2.getFieldName('value')] === activeValue[level];
}, {
childrenKeyName: this.getFieldName('children')
});
if (result[result.length - 2]) {
return result[result.length - 2][this.getFieldName('children')];
}
return _toConsumableArray(options).filter(function (o) {
return !o.disabled;
});
}
}, {
key: "getActiveOptions",
value: function getActiveOptions(activeValue) {
var _this3 = this;
return lib_default()(this.props.options || [], function (o, level) {
return o[_this3.getFieldName('value')] === activeValue[level];
}, {
childrenKeyName: this.getFieldName('children')
});
}
}, {
key: "render",
value: function render() {
var _this$props4 = this.props,
prefixCls = _this$props4.prefixCls,
transitionName = _this$props4.transitionName,
popupClassName = _this$props4.popupClassName,
_this$props4$options = _this$props4.options,
options = _this$props4$options === void 0 ? [] : _this$props4$options,
disabled = _this$props4.disabled,
builtinPlacements = _this$props4.builtinPlacements,
popupPlacement = _this$props4.popupPlacement,
children = _this$props4.children,
dropdownRender = _this$props4.dropdownRender,
restProps = Cascader_objectWithoutProperties(_this$props4, ["prefixCls", "transitionName", "popupClassName", "options", "disabled", "builtinPlacements", "popupPlacement", "children", "dropdownRender"]); // Did not show popup when there is no options
var menus = react["createElement"]("div", null);
var emptyMenuClassName = '';
if (options && options.length > 0) {
menus = react["createElement"](es_Menus, Object.assign({}, this.props, {
fieldNames: this.getFieldNames(),
defaultFieldNames: this.defaultFieldNames,
activeValue: this.state.activeValue,
onSelect: this.handleMenuSelect,
onItemDoubleClick: this.handleItemDoubleClick,
visible: this.state.popupVisible
}));
} else {
emptyMenuClassName = " ".concat(prefixCls, "-menus-empty");
}
var popupNode = menus;
if (dropdownRender) {
popupNode = dropdownRender(menus);
}
return react["createElement"](rc_trigger_es["a" /* default */], Object.assign({
ref: this.saveTrigger
}, restProps, {
popupPlacement: popupPlacement,
builtinPlacements: builtinPlacements,
popupTransitionName: transitionName,
action: disabled ? [] : ['click'],
popupVisible: disabled ? false : this.state.popupVisible,
onPopupVisibleChange: this.handlePopupVisibleChange,
prefixCls: "".concat(prefixCls, "-menus"),
popupClassName: popupClassName + emptyMenuClassName,
popup: popupNode
}), react["cloneElement"](children, {
onKeyDown: this.handleKeyDown,
tabIndex: disabled ? undefined : 0
}));
}
}], [{
key: "getDerivedStateFromProps",
value: function getDerivedStateFromProps(nextProps, prevState) {
var _prevState$prevProps = prevState.prevProps,
prevProps = _prevState$prevProps === void 0 ? {} : _prevState$prevProps;
var newState = {
prevProps: nextProps
};
if ('value' in nextProps && !isEqualArrays(prevProps.value, nextProps.value)) {
newState.value = nextProps.value || []; // allow activeValue diff from value
// https://github.com/ant-design/ant-design/issues/2767
if (!('loadData' in nextProps)) {
newState.activeValue = nextProps.value || [];
}
}
if ('popupVisible' in nextProps) {
newState.popupVisible = nextProps.popupVisible;
}
return newState;
}
}]);
return Cascader;
}(react["Component"]);
Cascader.defaultProps = {
onChange: function onChange() {},
onPopupVisibleChange: function onPopupVisibleChange() {},
disabled: false,
transitionName: '',
prefixCls: 'rc-cascader',
popupClassName: '',
popupPlacement: 'bottomLeft',
builtinPlacements: placements,
expandTrigger: 'click',
fieldNames: {
label: 'label',
value: 'value',
children: 'children'
},
expandIcon: '>'
};
return Cascader;
}();
/* harmony default export */ var es_Cascader = (Cascader_Cascader);
// CONCATENATED MODULE: ./node_modules/rc-cascader/es/index.js
/* harmony default export */ var rc_cascader_es = (es_Cascader);
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/RightOutlined.js
var _ant_design_icons_RightOutlined = __webpack_require__("fEPi");
var RightOutlined_default = /*#__PURE__*/__webpack_require__.n(_ant_design_icons_RightOutlined);
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/RedoOutlined.js
var RedoOutlined = __webpack_require__("5YOS");
var RedoOutlined_default = /*#__PURE__*/__webpack_require__.n(RedoOutlined);
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/LeftOutlined.js
var _ant_design_icons_LeftOutlined = __webpack_require__("DFhj");
var LeftOutlined_default = /*#__PURE__*/__webpack_require__.n(_ant_design_icons_LeftOutlined);
// CONCATENATED MODULE: ./node_modules/antd/es/cascader/index.js
var cascader_rest = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
// We limit the filtered item count by default
var defaultLimit = 50;
function highlightKeyword(str, keyword, prefixCls) {
return str.split(keyword).map(function (node, index) {
return index === 0 ? node : [/*#__PURE__*/react["createElement"]("span", {
className: "".concat(prefixCls, "-menu-item-keyword"),
key: "seperator"
}, keyword), node];
});
}
function defaultFilterOption(inputValue, path, names) {
return path.some(function (option) {
return option[names.label].indexOf(inputValue) > -1;
});
}
function defaultRenderFilteredOption(inputValue, path, prefixCls, names) {
return path.map(function (option, index) {
var label = option[names.label];
var node = label.indexOf(inputValue) > -1 ? highlightKeyword(label, inputValue, prefixCls) : label;
return index === 0 ? node : [' / ', node];
});
}
function defaultSortFilteredOption(a, b, inputValue, names) {
function callback(elem) {
return elem[names.label].indexOf(inputValue) > -1;
}
return a.findIndex(callback) - b.findIndex(callback);
}
function getFieldNames(_ref) {
var fieldNames = _ref.fieldNames;
return fieldNames;
}
function getFilledFieldNames(props) {
var fieldNames = getFieldNames(props) || {};
var names = {
children: fieldNames.children || 'children',
label: fieldNames.label || 'label',
value: fieldNames.value || 'value'
};
return names;
}
function flattenTree(options, props) {
var ancestor = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
var names = getFilledFieldNames(props);
var flattenOptions = [];
var childrenName = names.children;
options.forEach(function (option) {
var path = ancestor.concat(option);
if (props.changeOnSelect || !option[childrenName] || !option[childrenName].length) {
flattenOptions.push(path);
}
if (option[childrenName]) {
flattenOptions = flattenOptions.concat(flattenTree(option[childrenName], props, path));
}
});
return flattenOptions;
}
var defaultDisplayRender = function defaultDisplayRender(label) {
return label.join(' / ');
};
function warningValueNotExist(list) {
var fieldNames = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
(list || []).forEach(function (item) {
var valueFieldName = fieldNames.value || 'value';
Object(devWarning["a" /* default */])(valueFieldName in item, 'Cascader', 'Not found `value` in `options`.');
warningValueNotExist(item[fieldNames.children || 'children'], fieldNames);
});
}
var cascader_Cascader = /*#__PURE__*/function (_React$Component) {
inherits_default()(Cascader, _React$Component);
var _super = createSuper_default()(Cascader);
function Cascader(props) {
var _this;
classCallCheck_default()(this, Cascader);
_this = _super.call(this, props);
_this.cachedOptions = [];
_this.setValue = function (value) {
var selectedOptions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
if (!('value' in _this.props)) {
_this.setState({
value: value
});
}
var onChange = _this.props.onChange;
if (onChange) {
onChange(value, selectedOptions);
}
};
_this.saveInput = function (node) {
_this.input = node;
};
_this.handleChange = function (value, selectedOptions) {
_this.setState({
inputValue: ''
});
if (selectedOptions[0].__IS_FILTERED_OPTION) {
var unwrappedValue = value[0];
var unwrappedSelectedOptions = selectedOptions[0].path;
_this.setValue(unwrappedValue, unwrappedSelectedOptions);
return;
}
_this.setValue(value, selectedOptions);
};
_this.handlePopupVisibleChange = function (popupVisible) {
if (!('popupVisible' in _this.props)) {
_this.setState(function (state) {
return {
popupVisible: popupVisible,
inputFocused: popupVisible,
inputValue: popupVisible ? state.inputValue : ''
};
});
}
var onPopupVisibleChange = _this.props.onPopupVisibleChange;
if (onPopupVisibleChange) {
onPopupVisibleChange(popupVisible);
}
};
_this.handleInputBlur = function () {
_this.setState({
inputFocused: false
});
};
_this.handleInputClick = function (e) {
var _this$state = _this.state,
inputFocused = _this$state.inputFocused,
popupVisible = _this$state.popupVisible; // Prevent `Trigger` behaviour.
if (inputFocused || popupVisible) {
e.stopPropagation();
}
};
_this.handleKeyDown = function (e) {
// SPACE => https://github.com/ant-design/ant-design/issues/16871
if (e.keyCode === KeyCode["a" /* default */].BACKSPACE || e.keyCode === KeyCode["a" /* default */].SPACE) {
e.stopPropagation();
}
};
_this.handleInputChange = function (e) {
var popupVisible = _this.state.popupVisible;
var inputValue = e.target.value;
if (!popupVisible) {
_this.handlePopupVisibleChange(true);
}
_this.setState({
inputValue: inputValue
});
};
_this.clearSelection = function (e) {
var inputValue = _this.state.inputValue;
e.preventDefault();
e.stopPropagation();
if (!inputValue) {
_this.handlePopupVisibleChange(false);
_this.clearSelectionTimeout = setTimeout(function () {
_this.setValue([]);
}, 200);
} else {
_this.setState({
inputValue: ''
});
}
};
_this.renderCascader = function (_ref2, locale) {
var getContextPopupContainer = _ref2.getPopupContainer,
getPrefixCls = _ref2.getPrefixCls,
renderEmpty = _ref2.renderEmpty,
direction = _ref2.direction;
return /*#__PURE__*/react["createElement"](SizeContext["b" /* default */].Consumer, null, function (size) {
var _classNames, _classNames2, _classNames3, _classNames5;
var _assertThisInitialize = assertThisInitialized_default()(_this),
props = _assertThisInitialize.props,
state = _assertThisInitialize.state;
var customizePrefixCls = props.prefixCls,
customizeInputPrefixCls = props.inputPrefixCls,
children = props.children,
_props$placeholder = props.placeholder,
placeholder = _props$placeholder === void 0 ? locale.placeholder || 'Please select' : _props$placeholder,
customizeSize = props.size,
disabled = props.disabled,
className = props.className,
style = props.style,
allowClear = props.allowClear,
_props$showSearch = props.showSearch,
showSearch = _props$showSearch === void 0 ? false : _props$showSearch,
suffixIcon = props.suffixIcon,
expandIcon = props.expandIcon,
notFoundContent = props.notFoundContent,
popupClassName = props.popupClassName,
bordered = props.bordered,
dropdownRender = props.dropdownRender,
otherProps = cascader_rest(props, ["prefixCls", "inputPrefixCls", "children", "placeholder", "size", "disabled", "className", "style", "allowClear", "showSearch", "suffixIcon", "expandIcon", "notFoundContent", "popupClassName", "bordered", "dropdownRender"]);
var mergedSize = customizeSize || size;
var value = state.value,
inputFocused = state.inputFocused;
var isRtlLayout = direction === 'rtl';
var prefixCls = getPrefixCls('cascader', customizePrefixCls);
var inputPrefixCls = getPrefixCls('input', customizeInputPrefixCls);
var sizeCls = classnames_default()((_classNames = {}, defineProperty_default()(_classNames, "".concat(inputPrefixCls, "-lg"), mergedSize === 'large'), defineProperty_default()(_classNames, "".concat(inputPrefixCls, "-sm"), mergedSize === 'small'), _classNames));
var clearIcon = allowClear && !disabled && value.length > 0 || state.inputValue ? /*#__PURE__*/react["createElement"](CloseCircleFilled_default.a, {
className: "".concat(prefixCls, "-picker-clear"),
onClick: _this.clearSelection
}) : null;
var arrowCls = classnames_default()((_classNames2 = {}, defineProperty_default()(_classNames2, "".concat(prefixCls, "-picker-arrow"), true), defineProperty_default()(_classNames2, "".concat(prefixCls, "-picker-arrow-expand"), state.popupVisible), _classNames2));
var pickerCls = classnames_default()(className, "".concat(prefixCls, "-picker"), (_classNames3 = {}, defineProperty_default()(_classNames3, "".concat(prefixCls, "-picker-rtl"), isRtlLayout), defineProperty_default()(_classNames3, "".concat(prefixCls, "-picker-with-value"), state.inputValue), defineProperty_default()(_classNames3, "".concat(prefixCls, "-picker-disabled"), disabled), defineProperty_default()(_classNames3, "".concat(prefixCls, "-picker-").concat(mergedSize), !!mergedSize), defineProperty_default()(_classNames3, "".concat(prefixCls, "-picker-show-search"), !!showSearch), defineProperty_default()(_classNames3, "".concat(prefixCls, "-picker-focused"), inputFocused), defineProperty_default()(_classNames3, "".concat(prefixCls, "-picker-borderless"), !bordered), _classNames3)); // Fix bug of https://github.com/facebook/react/pull/5004
// and https://fb.me/react-unknown-prop
var inputProps = Object(omit_js_es["a" /* default */])(otherProps, ['onChange', 'options', 'popupPlacement', 'transitionName', 'displayRender', 'onPopupVisibleChange', 'changeOnSelect', 'expandTrigger', 'popupVisible', 'getPopupContainer', 'loadData', 'popupClassName', 'filterOption', 'renderFilteredOption', 'sortFilteredOption', 'notFoundContent', 'fieldNames', 'bordered']);
var options = props.options;
var names = getFilledFieldNames(_this.props);
if (options && options.length > 0) {
if (state.inputValue) {
options = _this.generateFilteredOptions(prefixCls, renderEmpty);
}
} else {
var _ref3;
options = [(_ref3 = {}, defineProperty_default()(_ref3, names.label, notFoundContent || renderEmpty('Cascader')), defineProperty_default()(_ref3, names.value, 'ANT_CASCADER_NOT_FOUND'), _ref3)];
} // Dropdown menu should keep previous status until it is fully closed.
if (!state.popupVisible) {
options = _this.cachedOptions;
} else {
_this.cachedOptions = options;
}
var dropdownMenuColumnStyle = {};
var isNotFound = (options || []).length === 1 && options[0].isEmptyNode;
if (isNotFound) {
dropdownMenuColumnStyle.height = 'auto'; // Height of one row.
} // The default value of `matchInputWidth` is `true`
var resultListMatchInputWidth = showSearch.matchInputWidth !== false;
if (resultListMatchInputWidth && (state.inputValue || isNotFound) && _this.input) {
dropdownMenuColumnStyle.width = _this.input.input.offsetWidth;
}
var inputIcon;
if (suffixIcon) {
inputIcon = Object(reactNode["c" /* replaceElement */])(suffixIcon, /*#__PURE__*/react["createElement"]("span", {
className: "".concat(prefixCls, "-picker-arrow")
}, suffixIcon), function () {
var _classNames4;
return {
className: classnames_default()((_classNames4 = {}, defineProperty_default()(_classNames4, suffixIcon.props.className, suffixIcon.props.className), defineProperty_default()(_classNames4, "".concat(prefixCls, "-picker-arrow"), true), _classNames4))
};
});
} else {
inputIcon = /*#__PURE__*/react["createElement"](DownOutlined_default.a, {
className: arrowCls
});
}
var input = children || /*#__PURE__*/react["createElement"]("span", {
style: style,
className: pickerCls
}, /*#__PURE__*/react["createElement"]("span", {
className: "".concat(prefixCls, "-picker-label")
}, _this.getLabel()), /*#__PURE__*/react["createElement"](es_input["a" /* default */], extends_default()({}, inputProps, {
tabIndex: "-1",
ref: _this.saveInput,
prefixCls: inputPrefixCls,
placeholder: value && value.length > 0 ? undefined : placeholder,
className: "".concat(prefixCls, "-input ").concat(sizeCls),
value: state.inputValue,
disabled: disabled,
readOnly: !showSearch,
autoComplete: inputProps.autoComplete || 'off',
onClick: showSearch ? _this.handleInputClick : undefined,
onBlur: showSearch ? _this.handleInputBlur : undefined,
onKeyDown: _this.handleKeyDown,
onChange: showSearch ? _this.handleInputChange : undefined
})), clearIcon, inputIcon);
var expandIconNode;
if (expandIcon) {
expandIconNode = expandIcon;
} else {
expandIconNode = isRtlLayout ? /*#__PURE__*/react["createElement"](LeftOutlined_default.a, null) : /*#__PURE__*/react["createElement"](RightOutlined_default.a, null);
}
var loadingIcon = /*#__PURE__*/react["createElement"]("span", {
className: "".concat(prefixCls, "-menu-item-loading-icon")
}, /*#__PURE__*/react["createElement"](RedoOutlined_default.a, {
spin: true
}));
var getPopupContainer = props.getPopupContainer || getContextPopupContainer;
var rest = Object(omit_js_es["a" /* default */])(props, ['inputIcon', 'expandIcon', 'loadingIcon', 'bordered']);
var rcCascaderPopupClassName = classnames_default()(popupClassName, (_classNames5 = {}, defineProperty_default()(_classNames5, "".concat(prefixCls, "-menu-").concat(direction), direction === 'rtl'), defineProperty_default()(_classNames5, "".concat(prefixCls, "-menu-empty"), options.length === 1 && options[0].value === 'ANT_CASCADER_NOT_FOUND'), _classNames5));
return /*#__PURE__*/react["createElement"](rc_cascader_es, extends_default()({}, rest, {
prefixCls: prefixCls,
getPopupContainer: getPopupContainer,
options: options,
value: value,
popupVisible: state.popupVisible,
onPopupVisibleChange: _this.handlePopupVisibleChange,
onChange: _this.handleChange,
dropdownMenuColumnStyle: dropdownMenuColumnStyle,
expandIcon: expandIconNode,
loadingIcon: loadingIcon,
popupClassName: rcCascaderPopupClassName,
popupPlacement: _this.getPopupPlacement(direction),
dropdownRender: dropdownRender
}), input);
});
};
_this.state = {
value: props.value || props.defaultValue || [],
inputValue: '',
inputFocused: false,
popupVisible: props.popupVisible,
flattenOptions: props.showSearch ? flattenTree(props.options, props) : undefined,
prevProps: props
};
return _this;
}
createClass_default()(Cascader, [{
key: "componentWillUnmount",
value: function componentWillUnmount() {
if (this.clearSelectionTimeout) {
clearTimeout(this.clearSelectionTimeout);
}
}
}, {
key: "getLabel",
value: function getLabel() {
var _this$props = this.props,
options = _this$props.options,
_this$props$displayRe = _this$props.displayRender,
displayRender = _this$props$displayRe === void 0 ? defaultDisplayRender : _this$props$displayRe;
var names = getFilledFieldNames(this.props);
var value = this.state.value;
var unwrappedValue = Array.isArray(value[0]) ? value[0] : value;
var selectedOptions = lib_default()(options, function (o, level) {
return o[names.value] === unwrappedValue[level];
}, {
childrenKeyName: names.children
});
var label = selectedOptions.length ? selectedOptions.map(function (o) {
return o[names.label];
}) : value;
return displayRender(label, selectedOptions);
}
}, {
key: "generateFilteredOptions",
value: function generateFilteredOptions(prefixCls, renderEmpty) {
var _this2 = this,
_ref5;
var _this$props2 = this.props,
showSearch = _this$props2.showSearch,
notFoundContent = _this$props2.notFoundContent;
var names = getFilledFieldNames(this.props);
var _showSearch$filter = showSearch.filter,
filter = _showSearch$filter === void 0 ? defaultFilterOption : _showSearch$filter,
_showSearch$render = showSearch.render,
render = _showSearch$render === void 0 ? defaultRenderFilteredOption : _showSearch$render,
_showSearch$sort = showSearch.sort,
sort = _showSearch$sort === void 0 ? defaultSortFilteredOption : _showSearch$sort,
_showSearch$limit = showSearch.limit,
limit = _showSearch$limit === void 0 ? defaultLimit : _showSearch$limit;
var _this$state2 = this.state,
_this$state2$flattenO = _this$state2.flattenOptions,
flattenOptions = _this$state2$flattenO === void 0 ? [] : _this$state2$flattenO,
inputValue = _this$state2.inputValue; // Limit the filter if needed
var filtered;
if (limit > 0) {
filtered = [];
var matchCount = 0; // Perf optimization to filter items only below the limit
flattenOptions.some(function (path) {
var match = filter(_this2.state.inputValue, path, names);
if (match) {
filtered.push(path);
matchCount += 1;
}
return matchCount >= limit;
});
} else {
Object(devWarning["a" /* default */])(typeof limit !== 'number', 'Cascader', "'limit' of showSearch should be positive number or false.");
filtered = flattenOptions.filter(function (path) {
return filter(_this2.state.inputValue, path, names);
});
}
filtered = filtered.sort(function (a, b) {
return sort(a, b, inputValue, names);
});
if (filtered.length > 0) {
return filtered.map(function (path) {
var _ref4;
return _ref4 = {
__IS_FILTERED_OPTION: true,
path: path
}, defineProperty_default()(_ref4, names.value, path.map(function (o) {
return o[names.value];
})), defineProperty_default()(_ref4, names.label, render(inputValue, path, prefixCls, names)), defineProperty_default()(_ref4, "disabled", path.some(function (o) {
return !!o.disabled;
})), defineProperty_default()(_ref4, "isEmptyNode", true), _ref4;
});
}
return [(_ref5 = {}, defineProperty_default()(_ref5, names.value, 'ANT_CASCADER_NOT_FOUND'), defineProperty_default()(_ref5, names.label, notFoundContent || renderEmpty('Cascader')), defineProperty_default()(_ref5, "disabled", true), defineProperty_default()(_ref5, "isEmptyNode", true), _ref5)];
}
}, {
key: "focus",
value: function focus() {
this.input.focus();
}
}, {
key: "blur",
value: function blur() {
this.input.blur();
}
}, {
key: "getPopupPlacement",
value: function getPopupPlacement() {
var direction = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'ltr';
var popupPlacement = this.props.popupPlacement;
if (popupPlacement !== undefined) {
return popupPlacement;
}
return direction === 'rtl' ? 'bottomRight' : 'bottomLeft';
}
}, {
key: "render",
value: function render() {
var _this3 = this;
return /*#__PURE__*/react["createElement"](context["a" /* ConfigConsumer */], null, function (configArgument) {
return /*#__PURE__*/react["createElement"](LocaleReceiver["a" /* default */], null, function (locale) {
return _this3.renderCascader(configArgument, locale);
});
});
}
}], [{
key: "getDerivedStateFromProps",
value: function getDerivedStateFromProps(nextProps, _ref6) {
var prevProps = _ref6.prevProps;
var newState = {
prevProps: nextProps
};
if ('value' in nextProps) {
newState.value = nextProps.value || [];
}
if ('popupVisible' in nextProps) {
newState.popupVisible = nextProps.popupVisible;
}
if (nextProps.showSearch && prevProps.options !== nextProps.options) {
newState.flattenOptions = flattenTree(nextProps.options, nextProps);
}
if (false) {}
return newState;
}
}]);
return Cascader;
}(react["Component"]);
cascader_Cascader.defaultProps = {
transitionName: 'slide-up',
options: [],
disabled: false,
allowClear: true,
bordered: true
};
/* harmony default export */ var cascader = (cascader_Cascader);
// CONCATENATED MODULE: ./node_modules/@ant-design/icons-svg/es/asn/CheckCircleFilled.js
// This icon file is generated automatically.
var CheckCircleFilled_CheckCircleFilled = { "icon": { "tag": "svg", "attrs": { "viewBox": "64 64 896 896", "focusable": "false" }, "children": [{ "tag": "path", "attrs": { "d": "M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm193.5 301.7l-210.6 292a31.8 31.8 0 01-51.7 0L318.5 484.9c-3.8-5.3 0-12.7 6.5-12.7h46.9c10.2 0 19.9 4.9 25.9 13.3l71.2 98.8 157.2-218c6-8.3 15.6-13.3 25.9-13.3H699c6.5 0 10.3 7.4 6.5 12.7z" } }] }, "name": "check-circle", "theme": "filled" };
/* harmony default export */ var asn_CheckCircleFilled = (CheckCircleFilled_CheckCircleFilled);
// CONCATENATED MODULE: ./node_modules/@ant-design/icons/es/icons/CheckCircleFilled.js
// GENERATE BY ./scripts/generate.ts
// DON NOT EDIT IT MANUALLY
var icons_CheckCircleFilled_CheckCircleFilled = function CheckCircleFilled(props, ref) {
return /*#__PURE__*/react["createElement"](AntdIcon["a" /* default */], Object(esm_objectSpread2["a" /* default */])(Object(esm_objectSpread2["a" /* default */])({}, props), {}, {
ref: ref,
icon: asn_CheckCircleFilled
}));
};
icons_CheckCircleFilled_CheckCircleFilled.displayName = 'CheckCircleFilled';
/* harmony default export */ var es_icons_CheckCircleFilled = (/*#__PURE__*/react["forwardRef"](icons_CheckCircleFilled_CheckCircleFilled));
// CONCATENATED MODULE: ./node_modules/@ant-design/icons-svg/es/asn/CloseCircleFilled.js
// This icon file is generated automatically.
var CloseCircleFilled_CloseCircleFilled = { "icon": { "tag": "svg", "attrs": { "viewBox": "64 64 896 896", "focusable": "false" }, "children": [{ "tag": "path", "attrs": { "d": "M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm165.4 618.2l-66-.3L512 563.4l-99.3 118.4-66.1.3c-4.4 0-8-3.5-8-8 0-1.9.7-3.7 1.9-5.2l130.1-155L340.5 359a8.32 8.32 0 01-1.9-5.2c0-4.4 3.6-8 8-8l66.1.3L512 464.6l99.3-118.4 66-.3c4.4 0 8 3.5 8 8 0 1.9-.7 3.7-1.9 5.2L553.5 514l130 155c1.2 1.5 1.9 3.3 1.9 5.2 0 4.4-3.6 8-8 8z" } }] }, "name": "close-circle", "theme": "filled" };
/* harmony default export */ var asn_CloseCircleFilled = (CloseCircleFilled_CloseCircleFilled);
// CONCATENATED MODULE: ./node_modules/@ant-design/icons/es/icons/CloseCircleFilled.js
// GENERATE BY ./scripts/generate.ts
// DON NOT EDIT IT MANUALLY
var icons_CloseCircleFilled_CloseCircleFilled = function CloseCircleFilled(props, ref) {
return /*#__PURE__*/react["createElement"](AntdIcon["a" /* default */], Object(esm_objectSpread2["a" /* default */])(Object(esm_objectSpread2["a" /* default */])({}, props), {}, {
ref: ref,
icon: asn_CloseCircleFilled
}));
};
icons_CloseCircleFilled_CloseCircleFilled.displayName = 'CloseCircleFilled';
/* harmony default export */ var es_icons_CloseCircleFilled = (/*#__PURE__*/react["forwardRef"](icons_CloseCircleFilled_CloseCircleFilled));
// CONCATENATED MODULE: ./src/utils/cityData.ts
var CityData = [{
value: '北京',
label: '北京',
children: [{
value: "东城",
label: '东城'
}, {
value: "西城",
label: "西城"
}, {
value: "朝阳",
label: "朝阳"
}, {
value: "丰台",
label: "丰台"
}, {
value: "石景山",
label: "石景山"
}, {
value: "海淀",
label: "海淀"
}, {
value: "门头沟",
label: "门头沟"
}, {
value: "房山",
label: "房山"
}, {
value: "通州",
label: "通州"
}, {
value: "顺义",
label: "顺义"
}, {
value: "昌平",
label: "昌平"
}, {
value: "大兴",
label: "大兴"
}, {
value: "平谷",
label: "平谷"
}, {
value: "怀柔",
label: "怀柔"
}, {
value: "密云",
label: "密云"
}, {
value: "延庆",
label: "延庆"
}]
}, {
value: '上海',
label: '上海',
children: [{
value: "崇明",
label: '崇明'
}, {
value: '黄浦',
label: '黄浦'
}, {
value: '卢湾',
label: '卢湾'
}, {
value: '徐汇',
label: '徐汇'
}, {
value: '长宁',
label: '长宁'
}, {
value: '静安',
label: '静安'
}, {
value: '普陀',
label: '普陀'
}, {
value: '闸北',
label: '闸北'
}, {
value: '虹口',
label: '虹口'
}, {
value: '杨浦',
label: '杨浦'
}, {
value: '闵行',
label: '闵行'
}, {
value: '宝山',
label: '宝山'
}, {
value: '嘉定',
label: '嘉定'
}, {
value: '浦东',
label: '浦东'
}, {
value: '金山',
label: '金山'
}, {
value: '松江',
label: '松江'
}, {
value: '青浦',
label: '青浦'
}, {
value: '南汇',
label: '南汇'
}, {
value: '奉贤',
label: '奉贤'
}]
}, {
value: '广东',
label: '广东',
children: [{
value: "广州",
label: '广州'
}, {
value: '深圳',
label: '深圳'
}, {
value: '珠海',
label: '珠海'
}, {
value: '东莞',
label: '东莞'
}, {
value: '中山',
label: '中山'
}, {
value: '佛山',
label: '佛山'
}, {
value: '惠州',
label: '惠州'
}, {
value: '河源',
label: '河源'
}, {
value: '潮州',
label: '潮州'
}, {
value: '江门',
label: '江门'
}, {
value: '揭阳',
label: '揭阳'
}, {
value: '茂名',
label: '茂名'
}, {
value: '梅州',
label: '梅州'
}, {
value: '清远',
label: '清远'
}, {
value: '汕头',
label: '汕头'
}, {
value: '汕尾',
label: '汕尾'
}, {
value: '韶关',
label: '韶关'
}, {
value: '顺德',
label: '顺德'
}, {
value: '阳江',
label: '阳江'
}, {
value: '云浮',
label: '云浮'
}, {
value: '湛江',
label: '湛江'
}, {
value: '肇庆',
label: '肇庆'
}]
}, {
value: '江苏',
label: '江苏',
children: [{
value: "南京",
label: '南京'
}, {
value: '常熟',
label: '常熟'
}, {
value: '常州',
label: '常州'
}, {
value: '海门',
label: '海门'
}, {
value: '淮安',
label: '淮安'
}, {
value: '江都',
label: '江都'
}, {
value: '江阴',
label: '江阴'
}, {
value: '昆山',
label: '昆山'
}, {
value: '连云港',
label: '连云港'
}, {
value: '南通',
label: '南通'
}, {
value: '启东',
label: '启东'
}, {
value: '沭阳',
label: '沭阳'
}, {
value: '宿迁',
label: '宿迁'
}, {
value: '苏州',
label: '苏州'
}, {
value: '太仓',
label: '太仓'
}, {
value: '泰州',
label: '泰州'
}, {
value: '同里',
label: '同里'
}, {
value: '无锡',
label: '无锡'
}, {
value: '徐州',
label: '徐州'
}, {
value: '盐城',
label: '盐城'
}, {
value: '扬州',
label: '扬州'
}, {
value: '宜兴',
label: '宜兴'
}, {
value: '仪征',
label: '仪征'
}, {
value: '张家港',
label: '张家港'
}, {
value: '镇江',
label: '镇江'
}]
}, {
value: '重庆',
label: '重庆',
children: [{
value: "万州",
label: '万州'
}, {
value: '涪陵',
label: '涪陵'
}, {
value: '渝中',
label: '渝中'
}, {
value: '大渡口',
label: '大渡口'
}, {
value: '江北',
label: '江北'
}, {
value: '沙坪坝',
label: '沙坪坝'
}, {
value: '九龙坡',
label: '九龙坡'
}, {
value: '南岸',
label: '南岸'
}, {
value: '北碚',
label: '北碚'
}, {
value: '万盛',
label: '万盛'
}, {
value: '双挢',
label: '双挢'
}, {
value: '渝北',
label: '渝北'
}, {
value: '巴南',
label: '巴南'
}, {
value: '黔江',
label: '黔江'
}, {
value: '长寿',
label: '长寿'
}, {
value: '綦江',
label: '綦江'
}, {
value: '潼南',
label: '潼南'
}, {
value: '铜梁',
label: '铜梁'
}, {
value: '大足',
label: '大足'
}, {
value: '荣昌',
label: '荣昌'
}, {
value: '壁山',
label: '壁山'
}, {
value: '梁平',
label: '梁平'
}, {
value: '城口',
label: '城口'
}, {
value: '丰都',
label: '丰都'
}, {
value: '垫江',
label: '垫江'
}, {
value: '武隆',
label: '武隆'
}, {
value: '忠县',
label: '忠县'
}, {
value: '开县',
label: '开县'
}, {
value: '云阳',
label: '云阳'
}, {
value: '奉节',
label: '奉节'
}, {
value: '巫山',
label: '巫山'
}, {
value: '巫溪',
label: '巫溪'
}, {
value: '石柱',
label: '石柱'
}, {
value: '秀山',
label: '秀山'
}, {
value: '酉阳',
label: '酉阳'
}, {
value: '彭水',
label: '彭水'
}, {
value: '江津',
label: '江津'
}, {
value: '合川',
label: '合川'
}, {
value: '永川',
label: '永川'
}, {
value: '南川',
label: '南川'
}]
}, {
value: '安徽',
label: '安徽',
children: [{
value: "合肥",
label: '合肥'
}, {
value: '安庆',
label: '安庆'
}, {
value: '蚌埠',
label: '蚌埠'
}, {
value: '亳州',
label: '亳州'
}, {
value: '巢湖',
label: '巢湖'
}, {
value: '滁州',
label: '滁州'
}, {
value: '阜阳',
label: '阜阳'
}, {
value: '贵池',
label: '贵池'
}, {
value: '淮北',
label: '淮北'
}, {
value: '淮化',
label: '淮化'
}, {
value: '淮南',
label: '淮南'
}, {
value: '黄山',
label: '黄山'
}, {
value: '九华山',
label: '九华山'
}, {
value: '六安',
label: '六安'
}, {
value: '马鞍山',
label: '马鞍山'
}, {
value: '宿州',
label: '宿州'
}, {
value: '铜陵',
label: '铜陵'
}, {
value: '屯溪',
label: '屯溪'
}, {
value: '芜湖',
label: '芜湖'
}, {
value: '宣城',
label: '宣城'
}]
}, {
value: '福建',
label: '福建',
children: [{
value: "福州",
label: '福州'
}, {
value: '厦门',
label: '厦门'
}, {
value: '泉州',
label: '泉州'
}, {
value: '漳州',
label: '漳州'
}, {
value: '龙岩',
label: '龙岩'
}, {
value: '南平',
label: '南平'
}, {
value: '宁德',
label: '宁德'
}, {
value: '莆田',
label: '莆田'
}, {
value: '三明',
label: '三明'
}]
}, {
value: '甘肃',
label: '甘肃',
children: [{
value: "兰州",
label: '兰州'
}, {
value: "嘉峪关",
label: '嘉峪关'
}, {
value: '白银',
label: '白银'
}, {
value: '定西',
label: '定西'
}, {
value: '敦煌',
label: '敦煌'
}, {
value: '甘南',
label: '甘南'
}, {
value: '金昌',
label: '金昌'
}, {
value: '酒泉',
label: '酒泉'
}, {
value: '临夏',
label: '临夏'
}, {
value: '平凉',
label: '平凉'
}, {
value: '天水',
label: '天水'
}, {
value: '陇南',
label: '陇南'
}, {
value: '武威',
label: '武威'
}, {
value: '西峰',
label: '西峰'
}, {
value: '张掖',
label: '张掖'
}]
}, {
value: '广西',
label: '广西',
children: [{
value: "南宁",
label: '南宁'
}, {
value: "来宾",
label: '来宾'
}, {
value: '百色',
label: '百色'
}, {
value: '北海',
label: '北海'
}, {
value: '桂林',
label: '桂林'
}, {
value: '防城港',
label: '防城港'
}, {
value: '贵港',
label: '贵港'
}, {
value: '河池',
label: '河池'
}, {
value: '贺州',
label: '贺州'
}, {
value: '柳州',
label: '柳州'
}, {
value: '钦州',
label: '钦州'
}, {
value: '梧州',
label: '梧州'
}, {
value: '玉林',
label: '玉林'
}]
}, {
value: '贵州',
label: '贵州',
children: [{
value: "贵阳",
label: '贵阳'
}, {
value: '安顺',
label: '安顺'
}, {
value: '毕节',
label: '毕节'
}, {
value: '都匀',
label: '都匀'
}, {
value: '凯里',
label: '凯里'
}, {
value: '六盘水',
label: '六盘水'
}, {
value: '铜仁',
label: '铜仁'
}, {
value: '兴义',
label: '兴义'
}, {
value: '玉屏',
label: '玉屏'
}, {
value: '遵义',
label: '遵义'
}]
}, {
value: '海南',
label: '海南',
children: [{
value: "海口",
label: '海口'
}, {
value: '儋县',
label: '儋县'
}, {
value: '陵水',
label: '陵水'
}, {
value: '琼海',
label: '琼海'
}, {
value: '三亚',
label: '三亚'
}, {
value: '通什',
label: '通什'
}, {
value: '万宁',
label: '万宁'
}]
}, {
value: '河北',
label: '河北',
children: [{
value: "石家庄",
label: '石家庄'
}, {
value: '保定',
label: '保定'
}, {
value: '北戴河',
label: '北戴河'
}, {
value: '沧州',
label: '沧州'
}, {
value: '承德',
label: '承德'
}, {
value: '丰润',
label: '丰润'
}, {
value: '邯郸',
label: '邯郸'
}, {
value: '衡水',
label: '衡水'
}, {
value: '廊坊',
label: '廊坊'
}, {
value: '南戴河',
label: '南戴河'
}, {
value: '秦皇岛',
label: '秦皇岛'
}, {
value: '唐山',
label: '唐山'
}, {
value: '新城',
label: '新城'
}, {
value: '邢台',
label: '邢台'
}, {
value: '张家口',
label: '张家口'
}]
}, {
value: '黑龙江',
label: '黑龙江',
children: [{
value: "哈尔滨",
label: '哈尔滨'
}, {
value: '北安',
label: '北安'
}, {
value: '大庆',
label: '大庆'
}, {
value: '大兴安岭',
label: '大兴安岭'
}, {
value: '鹤岗',
label: '鹤岗'
}, {
value: '黑河',
label: '黑河'
}, {
value: '佳木斯',
label: '佳木斯'
}, {
value: '鸡西',
label: '鸡西'
}, {
value: '牡丹江',
label: '牡丹江'
}, {
value: '齐齐哈尔',
label: '齐齐哈尔'
}, {
value: '七台河',
label: '七台河'
}, {
value: '双鸭山',
label: '双鸭山'
}, {
value: '绥化',
label: '绥化'
}, {
value: '伊春',
label: '伊春'
}]
}, {
value: '河南',
label: '河南',
children: [{
value: "郑州",
label: '郑州'
}, {
value: '安阳',
label: '安阳'
}, {
value: '鹤壁',
label: '鹤壁'
}, {
value: '潢川',
label: '潢川'
}, {
value: '焦作',
label: '焦作'
}, {
value: '济源',
label: '济源'
}, {
value: '开封',
label: '开封'
}, {
value: '漯河',
label: '漯河'
}, {
value: '洛阳',
label: '洛阳'
}, {
value: '南阳',
label: '南阳'
}, {
value: '平顶山',
label: '平顶山'
}, {
value: '濮阳',
label: '濮阳'
}, {
value: '三门峡',
label: '三门峡'
}, {
value: '商丘',
label: '商丘'
}, {
value: '新乡',
label: '新乡'
}, {
value: '信阳',
label: '信阳'
}, {
value: '许昌',
label: '许昌'
}, {
value: '周口',
label: '周口'
}, {
value: '驻马店',
label: '驻马店'
}]
}, {
value: '香港',
label: '香港',
children: [{
value: "香港",
label: '香港'
}, {
value: '九龙',
label: '九龙'
}, {
value: '新界',
label: '新界'
}]
}, {
value: '湖北',
label: '湖北',
children: [{
value: "武汉",
label: '武汉'
}, {
value: "天门",
label: '天门'
}, {
value: '恩施',
label: '恩施'
}, {
value: '鄂州',
label: '鄂州'
}, {
value: '黄冈',
label: '黄冈'
}, {
value: '黄石',
label: '黄石'
}, {
value: '荆门',
label: '荆门'
}, {
value: '荆州',
label: '荆州'
}, {
value: '潜江',
label: '潜江'
}, {
value: '十堰',
label: '十堰'
}, {
value: '随州',
label: '随州'
}, {
value: '武穴',
label: '武穴'
}, {
value: '仙桃',
label: '仙桃'
}, {
value: '咸宁',
label: '咸宁'
}, {
value: '襄阳',
label: '襄阳'
}, {
value: '襄樊',
label: '襄樊'
}, {
value: '孝感',
label: '孝感'
}, {
value: '宜昌',
label: '宜昌'
}]
}, {
value: '湖南',
label: '湖南',
children: [{
value: "长沙",
label: '长沙'
}, {
value: '常德',
label: '常德'
}, {
value: '郴州',
label: '郴州'
}, {
value: '衡阳',
label: '衡阳'
}, {
value: '怀化',
label: '怀化'
}, {
value: '吉首',
label: '吉首'
}, {
value: '娄底',
label: '娄底'
}, {
value: '邵阳',
label: '邵阳'
}, {
value: '湘潭',
label: '湘潭'
}, {
value: '益阳',
label: '益阳'
}, {
value: '岳阳',
label: '岳阳'
}, {
value: '永州',
label: '永州'
}, {
value: '张家界',
label: '张家界'
}, {
value: '株洲',
label: '株洲'
}]
}, {
value: '江西',
label: '江西',
children: [{
value: "南昌",
label: '南昌'
}, {
value: '抚州',
label: '抚州'
}, {
value: '赣州',
label: '赣州'
}, {
value: '吉安',
label: '吉安'
}, {
value: '景德镇',
label: '景德镇'
}, {
value: '井冈山',
label: '井冈山'
}, {
value: '九江',
label: '九江'
}, {
value: '庐山',
label: '庐山'
}, {
value: '萍乡',
label: '萍乡'
}, {
value: '上饶',
label: '上饶'
}, {
value: '新余',
label: '新余'
}, {
value: '宜春',
label: '宜春'
}, {
value: '鹰潭',
label: '鹰潭'
}]
}, {
value: '吉林',
label: '吉林',
children: [{
value: "长春",
label: '长春'
}, {
value: '吉林',
label: '吉林'
}, {
value: '白城',
label: '白城'
}, {
value: '白山',
label: '白山'
}, {
value: '珲春',
label: '珲春'
}, {
value: '辽源',
label: '辽源'
}, {
value: '梅河',
label: '梅河'
}, {
value: '四平',
label: '四平'
}, {
value: '松原',
label: '松原'
}, {
value: '通化',
label: '通化'
}, {
value: '延吉',
label: '延吉'
}]
}, {
value: '辽宁',
label: '辽宁',
children: [{
value: "沈阳",
label: '沈阳'
}, {
value: '鞍山',
label: '鞍山'
}, {
value: '本溪',
label: '本溪'
}, {
value: '朝阳',
label: '朝阳'
}, {
value: '大连',
label: '大连'
}, {
value: '丹东',
label: '丹东'
}, {
value: '抚顺',
label: '抚顺'
}, {
value: '阜新',
label: '阜新'
}, {
value: '葫芦岛',
label: '葫芦岛'
}, {
value: '锦州',
label: '锦州'
}, {
value: '辽阳',
label: '辽阳'
}, {
value: '盘锦',
label: '盘锦'
}, {
value: '铁岭',
label: '铁岭'
}, {
value: '营口',
label: '营口'
}]
}, {
value: '澳门',
label: '澳门',
children: [{
value: '澳门',
label: '澳门'
}]
}, {
value: '内蒙古',
label: '内蒙古',
children: [{
value: "呼和浩特",
label: '呼和浩特'
}, {
value: '阿拉善盟',
label: '阿拉善盟'
}, {
value: '包头',
label: '包头'
}, {
value: '赤峰',
label: '赤峰'
}, {
value: '东胜',
label: '东胜'
}, {
value: '海拉尔',
label: '海拉尔'
}, {
value: '集宁',
label: '集宁'
}, {
value: '临河',
label: '临河'
}, {
value: '通辽',
label: '通辽'
}, {
value: '乌海',
label: '乌海'
}, {
value: '乌兰浩特',
label: '乌兰浩特'
}, {
value: '锡林浩特',
label: '锡林浩特'
}]
}, {
value: '宁夏',
label: '宁夏',
children: [{
value: "银川",
label: '银川'
}, {
value: '固源',
label: '固源'
}, {
value: '石嘴山',
label: '石嘴山'
}, {
value: '吴忠',
label: '吴忠'
}]
}, {
value: '青海',
label: '青海',
children: [{
value: "西宁",
label: '西宁'
}, {
value: '德令哈',
label: '德令哈'
}, {
value: '格尔木',
label: '格尔木'
}, {
value: '共和',
label: '共和'
}, {
value: '海东',
label: '海东'
}, {
value: '海晏',
label: '海晏'
}, {
value: '玛沁',
label: '玛沁'
}, {
value: '同仁',
label: '同仁'
}, {
value: '玉树',
label: '玉树'
}]
}, {
value: '山东',
label: '山东',
children: [{
value: "济南",
label: '济南'
}, {
value: '滨州',
label: '滨州'
}, {
value: '兖州',
label: '兖州'
}, {
value: '德州',
label: '德州'
}, {
value: '东营',
label: '东营'
}, {
value: '菏泽',
label: '菏泽'
}, {
value: '济宁',
label: '济宁'
}, {
value: '莱芜',
label: '莱芜'
}, {
value: '聊城',
label: '聊城'
}, {
value: '临沂',
label: '临沂'
}, {
value: '蓬莱',
label: '蓬莱'
}, {
value: '青岛',
label: '青岛'
}, {
value: '曲阜',
label: '曲阜'
}, {
value: '日照',
label: '日照'
}, {
value: '泰安',
label: '泰安'
}, {
value: '潍坊',
label: '潍坊'
}, {
value: '威海',
label: '威海'
}, {
value: '烟台',
label: '烟台'
}, {
value: '枣庄',
label: '枣庄'
}, {
value: '淄博',
label: '淄博'
}]
}, {
value: '山西',
label: '山西',
children: [{
value: "太原",
label: '太原'
}, {
value: "吕梁",
label: '吕梁'
}, {
value: '长治',
label: '长治'
}, {
value: '大同',
label: '大同'
}, {
value: '候马',
label: '候马'
}, {
value: '晋城',
label: '晋城'
}, {
value: '离石',
label: '离石'
}, {
value: '临汾',
label: '临汾'
}, {
value: '宁武',
label: '宁武'
}, {
value: '朔州',
label: '朔州'
}, {
value: '忻州',
label: '忻州'
}, {
value: '阳泉',
label: '阳泉'
}, {
value: '榆次',
label: '榆次'
}, {
value: '晋中',
label: '晋中'
}, {
value: '运城',
label: '运城'
}]
}, {
value: '陕西',
label: '陕西',
children: [{
value: "西安",
label: '西安'
}, {
value: '安康',
label: '安康'
}, {
value: '宝鸡',
label: '宝鸡'
}, {
value: '汉中',
label: '汉中'
}, {
value: '渭南',
label: '渭南'
}, {
value: '商州',
label: '商州'
}, {
value: '绥德',
label: '绥德'
}, {
value: '铜川',
label: '铜川'
}, {
value: '咸阳',
label: '咸阳'
}, {
value: '延安',
label: '延安'
}, {
value: '榆林',
label: '榆林'
}]
}, {
value: '四川',
label: '四川',
children: [{
value: "成都",
label: '成都'
}, {
value: '巴中',
label: '巴中'
}, {
value: '达川',
label: '达川'
}, {
value: '德阳',
label: '德阳'
}, {
value: '都江堰',
label: '都江堰'
}, {
value: '峨眉山',
label: '峨眉山'
}, {
value: '涪陵',
label: '涪陵'
}, {
value: '广安',
label: '广安'
}, {
value: '广元',
label: '广元'
}, {
value: '九寨沟',
label: '九寨沟'
}, {
value: '康定',
label: '康定'
}, {
value: '乐山',
label: '乐山'
}, {
value: '泸州',
label: '泸州'
}, {
value: '马尔康',
label: '马尔康'
}, {
value: '绵阳',
label: '绵阳'
}, {
value: '眉山',
label: '眉山'
}, {
value: '南充',
label: '南充'
}, {
value: '内江',
label: '内江'
}, {
value: '攀枝花',
label: '攀枝花'
}, {
value: '遂宁',
label: '遂宁'
}, {
value: '汶川',
label: '汶川'
}, {
value: '西昌',
label: '西昌'
}, {
value: '雅安',
label: '雅安'
}, {
value: '宜宾',
label: '宜宾'
}, {
value: '自贡',
label: '自贡'
}, {
value: '资阳',
label: '资阳'
}]
}, {
value: '台湾',
label: '台湾',
children: [{
value: "台北",
label: '台北'
}, {
value: '基隆',
label: '基隆'
}, {
value: '台南',
label: '台南'
}, {
value: '台中',
label: '台中'
}, {
value: '高雄',
label: '高雄'
}, {
value: '屏东',
label: '屏东'
}, {
value: '南投',
label: '南投'
}, {
value: '云林',
label: '云林'
}, {
value: '新竹',
label: '新竹'
}, {
value: '彰化',
label: '彰化'
}, {
value: '苗栗',
label: '苗栗'
}, {
value: '嘉义',
label: '嘉义'
}, {
value: '桃园',
label: '桃园'
}, {
value: '宜兰',
label: '宜兰'
}, {
value: '台东',
label: '台东'
}, {
value: '金门',
label: '金门'
}, {
value: '马祖',
label: '马祖'
}, {
value: '澎湖',
label: '澎湖'
}]
}, {
value: '天津',
label: '天津',
children: [{
value: "天津",
label: '天津'
}, {
value: '和平',
label: '和平'
}, {
value: '东丽',
label: '东丽'
}, {
value: '河东',
label: '河东'
}, {
value: '西青',
label: '西青'
}, {
value: '河西',
label: '河西'
}, {
value: '津南',
label: '津南'
}, {
value: '南开',
label: '南开'
}, {
value: '北辰',
label: '北辰'
}, {
value: '河北',
label: '河北'
}, {
value: '武清',
label: '武清'
}, {
value: '红挢',
label: '红挢'
}, {
value: '塘沽',
label: '塘沽'
}, {
value: '汉沽',
label: '汉沽'
}, {
value: '大港',
label: '大港'
}, {
value: '宁河',
label: '宁河'
}, {
value: '静海',
label: '静海'
}, {
value: '宝坻',
label: '宝坻'
}, {
value: '蓟县',
label: '蓟县'
}]
}, {
value: '新疆',
label: '新疆',
children: [{
value: "乌鲁木齐",
label: '乌鲁木齐'
}, {
value: '阿克苏',
label: '阿克苏'
}, {
value: '阿勒泰',
label: '阿勒泰'
}, {
value: '阿图什',
label: '阿图什'
}, {
value: '博乐',
label: '博乐'
}, {
value: '昌吉',
label: '昌吉'
}, {
value: '东山',
label: '东山'
}, {
value: '哈密',
label: '哈密'
}, {
value: '和田',
label: '和田'
}, {
value: '喀什',
label: '喀什'
}, {
value: '克拉玛依',
label: '克拉玛依'
}, {
value: '库车',
label: '库车'
}, {
value: '库尔勒',
label: '库尔勒'
}, {
value: '奎屯',
label: '奎屯'
}, {
value: '石河子',
label: '石河子'
}, {
value: '塔城',
label: '塔城'
}, {
value: '吐鲁番',
label: '吐鲁番'
}, {
value: '伊宁',
label: '伊宁'
}]
}, {
value: '西藏',
label: '西藏',
children: [{
value: "拉萨",
label: '拉萨'
}, {
value: '阿里',
label: '阿里'
}, {
value: '昌都',
label: '昌都'
}, {
value: '林芝',
label: '林芝'
}, {
value: '那曲',
label: '那曲'
}, {
value: '日喀则',
label: '日喀则'
}, {
value: '山南',
label: '山南'
}]
}, {
value: '云南',
label: '云南',
children: [{
value: "昆明",
label: '昆明'
}, {
value: '大理',
label: '大理'
}, {
value: '保山',
label: '保山'
}, {
value: '楚雄',
label: '楚雄'
}, {
value: '大理',
label: '大理'
}, {
value: '东川',
label: '东川'
}, {
value: '个旧',
label: '个旧'
}, {
value: '景洪',
label: '景洪'
}, {
value: '开远',
label: '开远'
}, {
value: '临沧',
label: '临沧'
}, {
value: '丽江',
label: '丽江'
}, {
value: '六库',
label: '六库'
}, {
value: '潞西',
label: '潞西'
}, {
value: '曲靖',
label: '曲靖'
}, {
value: '思茅',
label: '思茅'
}, {
value: '文山',
label: '文山'
}, {
value: '西双版纳',
label: '西双版纳'
}, {
value: '玉溪',
label: '玉溪'
}, {
value: '中甸',
label: '中甸'
}, {
value: '昭通',
label: '昭通'
}]
}, {
value: '浙江',
label: '浙江',
children: [{
value: "杭州",
label: '杭州'
}, {
value: "温州",
label: '温州'
}, {
value: '安吉',
label: '安吉'
}, {
value: '慈溪',
label: '慈溪'
}, {
value: '定海',
label: '定海'
}, {
value: '奉化',
label: '奉化'
}, {
value: '海盐',
label: '海盐'
}, {
value: '黄岩',
label: '黄岩'
}, {
value: '湖州',
label: '湖州'
}, {
value: '嘉兴',
label: '嘉兴'
}, {
value: '金华',
label: '金华'
}, {
value: '临安',
label: '临安'
}, {
value: '临海',
label: '临海'
}, {
value: '丽水',
label: '丽水'
}, {
value: '宁波',
label: '宁波'
}, {
value: '瓯海',
label: '瓯海'
}, {
value: '平湖',
label: '平湖'
}, {
value: '千岛湖',
label: '千岛湖'
}, {
value: '衢州',
label: '衢州'
}, {
value: '江山',
label: '江山'
}, {
value: '瑞安',
label: '瑞安'
}, {
value: '绍兴',
label: '绍兴'
}, {
value: '嵊州',
label: '嵊州'
}, {
value: '台州',
label: '台州'
}, {
value: '温岭',
label: '温岭'
}, {
value: '余姚',
label: '余姚'
}, {
value: '舟山',
label: '舟山'
}]
}, {
value: '海外',
label: '海外',
children: [{
value: "美国",
label: '美国'
}, {
value: '日本',
label: '日本'
}, {
value: '英国',
label: '英国'
}, {
value: '法国',
label: '法国'
}, {
value: '德国',
label: '德国'
}, {
value: '其他',
label: '其他'
}]
}];
// EXTERNAL MODULE: ./src/pages/Competitions/Detail/components/AppplySchoolModal/index.less?modules
var AppplySchoolModalmodules = __webpack_require__("jwmR");
var AppplySchoolModalmodules_default = /*#__PURE__*/__webpack_require__.n(AppplySchoolModalmodules);
// CONCATENATED MODULE: ./src/pages/Competitions/Detail/components/AppplySchoolModal/index.tsx
var AppplySchoolModal_filter = function filter(inputValue, path) {
return path.some(function (option) {
return option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1;
});
};
var AppplySchoolModal_TextArea = es_input["a" /* default */].TextArea;
var AppplySchoolModal_AppplySchoolModal = function AppplySchoolModal(_ref) {
var account = _ref.account,
globalSetting = _ref.globalSetting,
loading = _ref.loading,
dispatch = _ref.dispatch,
schoolName = _ref.schoolName,
visible = _ref.visible,
_ref$onClose = _ref.onClose,
onClose = _ref$onClose === void 0 ? function () {} : _ref$onClose,
_ref$onSuccess = _ref.onSuccess,
onSuccess = _ref$onSuccess === void 0 ? function () {} : _ref$onSuccess,
props = Object(objectWithoutProperties["a" /* default */])(_ref, ["account", "globalSetting", "loading", "dispatch", "schoolName", "visible", "onClose", "onSuccess"]);
var _Form$useForm = es_form["a" /* default */].useForm(),
_Form$useForm2 = Object(slicedToArray["a" /* default */])(_Form$useForm, 1),
form = _Form$useForm2[0];
Object(react["useEffect"])(function () {
form.setFieldsValue({
name: schoolName
});
}, [schoolName]);
var handleFinish = /*#__PURE__*/function () {
var _ref2 = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee(values) {
var _ref3, name, _ref3$city, city, address, remarks, res;
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_ref3 = values || {}, name = _ref3.name, _ref3$city = _ref3.city, city = _ref3$city === void 0 ? [] : _ref3$city, address = _ref3.address, remarks = _ref3.remarks;
_context.next = 3;
return dispatch({
type: 'account/appplySchool',
payload: {
name: name,
province: city[0],
city: city[1],
address: address,
remarks: remarks
}
});
case 3:
res = _context.sent;
onClose();
if (res) {
es_message["b" /* default */].success("新增学校/单位成功!");
onSuccess(name);
}
case 6:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function handleFinish(_x) {
return _ref2.apply(this, arguments);
};
}();
return /*#__PURE__*/react_default.a.createElement(es_modal["a" /* default */], {
centered: true,
keyboard: false,
closable: false,
destroyOnClose: true,
visible: visible,
title: "\u7533\u8BF7\u6DFB\u52A0\u5355\u4F4D\u540D\u79F0",
width: "600px",
footer: null
}, /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */], {
className: AppplySchoolModalmodules_default.a.formWrap,
form: form,
labelCol: {
span: 4
},
wrapperCol: {
span: 20
},
onFinish: handleFinish
}, /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
label: "\u5355\u4F4D\u5168\u79F0\uFF1A",
name: "name",
rules: [{
required: true,
message: '请输入学校或工作单位'
}]
}, /*#__PURE__*/react_default.a.createElement(es_input["a" /* default */], {
placeholder: "\u5B66\u6821\u6216\u5DE5\u4F5C\u5355\u4F4D"
})), /*#__PURE__*/react_default.a.createElement("div", {
className: "".concat(AppplySchoolModalmodules_default.a.flexRow, " ").concat(AppplySchoolModalmodules_default.a.example)
}, /*#__PURE__*/react_default.a.createElement("div", null, "\u793A\u4F8B\uFF1A"), /*#__PURE__*/react_default.a.createElement("div", {
className: AppplySchoolModalmodules_default.a.flexColumn
}, /*#__PURE__*/react_default.a.createElement("div", null, /*#__PURE__*/react_default.a.createElement(es_icons_CheckCircleFilled, {
style: {
color: "rgb(82, 196, 26)"
}
}), /*#__PURE__*/react_default.a.createElement("span", {
className: "font14 ml5"
}, "\u6B63\u786E\u793A\u4F8B\uFF1A\u6570\u636E\u7ED3\u6784")), /*#__PURE__*/react_default.a.createElement("div", null, /*#__PURE__*/react_default.a.createElement(es_icons_CloseCircleFilled, {
style: {
color: "red"
}
}), /*#__PURE__*/react_default.a.createElement("span", {
className: "font14 ml5"
}, "\u9519\u8BEF\u793A\u4F8B\uFF1A\u6570\u636E\u7ED3\u67842019\u6625")))), /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
label: "\u5730\u533A\uFF1A",
name: "city"
}, /*#__PURE__*/react_default.a.createElement(cascader, {
allowClear: true,
size: "large",
options: CityData,
placeholder: "\u8BF7\u9009\u62E9\u6240\u5728\u5730",
showSearch: {
matchInputWidth: true,
filter: AppplySchoolModal_filter
}
})), /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
label: "\u8BE6\u7EC6\u5730\u5740\uFF1A",
name: "address"
}, /*#__PURE__*/react_default.a.createElement(es_input["a" /* default */], {
placeholder: "\u8BF7\u586B\u5199\u5B8C\u6574\u7684\u5730\u5740\u4FE1\u606F"
})), /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
label: "\u8BF4\u660E\uFF1A",
name: "remarks"
}, /*#__PURE__*/react_default.a.createElement(AppplySchoolModal_TextArea, {
placeholder: "\u518D\u6B21\u8BF4\u660E\u7279\u522B\u60C5\u51B5\uFF08\u9009\u586B\uFF09"
})), /*#__PURE__*/react_default.a.createElement("div", {
className: AppplySchoolModalmodules_default.a.footerWrap
}, /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, null, /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
className: "mr5",
size: "large",
onClick: function onClick() {
onClose();
}
}, "\u53D6\u6D88"), /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
size: "large",
type: "primary",
htmlType: "submit",
loading: loading['account/appplySchool']
}, "\u4FDD\u5B58")))));
};
/* harmony default export */ var components_AppplySchoolModal = (Object(umiExports["a" /* connect */])(function (_ref4) {
var account = _ref4.account,
loading = _ref4.loading,
globalSetting = _ref4.globalSetting;
return {
account: account,
globalSetting: globalSetting,
loading: loading.effects
};
})(AppplySchoolModal_AppplySchoolModal));
// CONCATENATED MODULE: ./src/pages/Competitions/Detail/component/ProfessionalAuthModal.tsx
var ProfessionalAuthModal_Option = es_select["a" /* default */].Option;
var ProfessionalAuthModal_Dragger = es_upload.Dragger;
var ProfessionalAuthModal_ProfessionalAuthModal = function ProfessionalAuthModal(_ref) {
var _globalSetting$settin, _schoolList$find3;
var user = _ref.user,
account = _ref.account,
globalSetting = _ref.globalSetting,
loading = _ref.loading,
dispatch = _ref.dispatch,
Scoid = _ref.Scoid,
props = Object(objectWithoutProperties["a" /* default */])(_ref, ["user", "account", "globalSetting", "loading", "dispatch", "Scoid"]);
var _Form$useForm = es_form["a" /* default */].useForm(),
_Form$useForm2 = Object(slicedToArray["a" /* default */])(_Form$useForm, 1),
form = _Form$useForm2[0];
var _useState = Object(react["useState"])({}),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
formValue = _useState2[0],
setFormValue = _useState2[1];
var _useState3 = Object(react["useState"])([]),
_useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
schoolList = _useState4[0],
setSchoolList = _useState4[1];
var _useState5 = Object(react["useState"])([]),
_useState6 = Object(slicedToArray["a" /* default */])(_useState5, 2),
filterSchoolList = _useState6[0],
setFilterSchoolList = _useState6[1];
var _useState7 = Object(react["useState"])([]),
_useState8 = Object(slicedToArray["a" /* default */])(_useState7, 2),
departmentList = _useState8[0],
setDepartmentList = _useState8[1];
var _useState9 = Object(react["useState"])([]),
_useState10 = Object(slicedToArray["a" /* default */])(_useState9, 2),
filterDepartmentList = _useState10[0],
setFilterDepartmentList = _useState10[1];
var _useState11 = Object(react["useState"])(),
_useState12 = Object(slicedToArray["a" /* default */])(_useState11, 2),
image = _useState12[0],
setImage = _useState12[1];
var _useState13 = Object(react["useState"])(),
_useState14 = Object(slicedToArray["a" /* default */])(_useState13, 2),
fileId = _useState14[0],
setFileId = _useState14[1];
var _useState15 = Object(react["useState"])(),
_useState16 = Object(slicedToArray["a" /* default */])(_useState15, 2),
isLoading = _useState16[0],
setIsLoading = _useState16[1];
var _useState17 = Object(react["useState"])(),
_useState18 = Object(slicedToArray["a" /* default */])(_useState17, 2),
visibleAppplySchool = _useState18[0],
setVisibleAppplySchool = _useState18[1];
var _useState19 = Object(react["useState"])(),
_useState20 = Object(slicedToArray["a" /* default */])(_useState19, 2),
visibleAppplyDepartment = _useState20[0],
setVisibleAppplyDepartment = _useState20[1];
;
Object(react["useEffect"])(function () {
getSchoolOption();
}, []);
Object(react["useEffect"])(function () {
Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee() {
var res;
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (Scoid) {
_context.next = 2;
break;
}
return _context.abrupt("return");
case 2:
_context.next = 4;
return getDepartmentOption(Scoid);
case 4:
res = _context.sent;
setDepartmentList(res === null || res === void 0 ? void 0 : res.departments);
case 6:
case "end":
return _context.stop();
}
}
}, _callee);
}))();
}, [Scoid]);
var getSchoolOption = /*#__PURE__*/function () {
var _ref3 = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee2() {
var res;
return regenerator_default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return dispatch({
type: 'account/getSchoolOption'
});
case 2:
res = _context2.sent;
setSchoolList(res === null || res === void 0 ? void 0 : res.schools);
case 4:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
return function getSchoolOption() {
return _ref3.apply(this, arguments);
};
}();
var getDepartmentOption = function getDepartmentOption(schoolId) {
return dispatch({
type: 'account/getDepartmentOption',
payload: {
id: schoolId
}
});
};
Object(react["useEffect"])(function () {
if (!account.basicInfo) {
return;
}
var basicInfo = account.basicInfo;
var formData = {
identity: basicInfo.identity,
school: basicInfo.school_name,
department: basicInfo.department_name,
studentNo: basicInfo.student_id,
jobTitle: basicInfo.identity == "teacher" ? basicInfo.technical_title : "教授",
manager: basicInfo.identity == "professional" ? basicInfo.technical_title : "企业管理者"
};
form.setFieldsValue(formData);
setFormValue(formData);
}, [account.basicInfo]);
var handleApplySchool = function handleApplySchool() {
setVisibleAppplySchool(true);
};
var handleApplyDepartment = function handleApplyDepartment() {
if (!schoolList.find(function (item) {
return item.name === formValue.school;
})) {
es_message["b" /* default */].info('请先选择正确的单位或者学校!');
return;
}
setVisibleAppplyDepartment(true);
};
var handleValuesChange = function handleValuesChange(changedValues) {
setFormValue(Object(objectSpread2["a" /* default */])({}, form.getFieldsValue()));
if ('school' in changedValues) {
setFilterSchoolList(schoolList.filter(function (item) {
return item.name.includes(changedValues.school);
}));
var findSchoolId = (schoolList.find(function (item) {
return item.name === changedValues.school;
}) || {}).id;
if (findSchoolId) {
handleSetDepartment(changedValues.school);
} else {
form.setFieldsValue({
department: ''
});
setFormValue(Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, formValue), {
school: changedValues.school,
department: ''
}));
}
}
};
var handleSetDepartment = /*#__PURE__*/function () {
var _ref4 = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee3(school, departmentName) {
var _schoolList$find, _res$departments, _res$departments$;
var findSchoolId, res, name;
return regenerator_default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
findSchoolId = (_schoolList$find = schoolList.find(function (item) {
return item.name === school;
})) === null || _schoolList$find === void 0 ? void 0 : _schoolList$find.id;
_context3.next = 3;
return getDepartmentOption(findSchoolId);
case 3:
_context3.t0 = _context3.sent;
if (_context3.t0) {
_context3.next = 6;
break;
}
_context3.t0 = {};
case 6:
res = _context3.t0;
setDepartmentList(res === null || res === void 0 ? void 0 : res.departments);
name = departmentName || (res === null || res === void 0 ? void 0 : (_res$departments = res.departments) === null || _res$departments === void 0 ? void 0 : (_res$departments$ = _res$departments[0]) === null || _res$departments$ === void 0 ? void 0 : _res$departments$.name);
form.setFieldsValue({
department: name
});
setFormValue(Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, formValue), {
school: school,
department: name
}));
case 11:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
return function handleSetDepartment(_x, _x2) {
return _ref4.apply(this, arguments);
};
}();
var handleSchoolSuccess = /*#__PURE__*/function () {
var _ref5 = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee4(schoolName) {
return regenerator_default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
_context4.next = 2;
return getSchoolOption();
case 2:
form.setFieldsValue({
school: schoolName,
department: ''
});
setFormValue(Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, formValue), {
school: schoolName,
department: ''
}));
case 4:
case "end":
return _context4.stop();
}
}
}, _callee4);
}));
return function handleSchoolSuccess(_x3) {
return _ref5.apply(this, arguments);
};
}();
var handleUploadChange = function handleUploadChange(info) {
if (info.file.status === 'uploading') {
setIsLoading(true);
return;
}
if (info.file.status === 'done') {
var _info$file$response;
console.log(info.file, info.file.response);
setFileId((_info$file$response = info.file.response) === null || _info$file$response === void 0 ? void 0 : _info$file$response.id);
Object(util["h" /* getBase64 */])(info.file.originFileObj, function (base64Img) {
setImage(base64Img);
setIsLoading(false);
});
}
};
var handleFinish = /*#__PURE__*/function () {
var _ref6 = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee5(values) {
var _schoolList$find2, _departmentList$find, _account$basicInfo, _user$userInfo;
var _ref7, school, department, identity, studentNo, jobTitle, manager, school_id, department_id, extra, res, _user$userInfo2;
return regenerator_default.a.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
_ref7 = values || {}, school = _ref7.school, department = _ref7.department, identity = _ref7.identity, studentNo = _ref7.studentNo, jobTitle = _ref7.jobTitle, manager = _ref7.manager;
if (image) {
_context5.next = 4;
break;
}
es_message["b" /* default */].info('请先上传照片!');
return _context5.abrupt("return");
case 4:
school_id = (_schoolList$find2 = schoolList.find(function (item) {
return item.name === school;
})) === null || _schoolList$find2 === void 0 ? void 0 : _schoolList$find2.id;
department_id = (_departmentList$find = departmentList.find(function (item) {
return item.name === department;
})) === null || _departmentList$find === void 0 ? void 0 : _departmentList$find.id;
if (identity === 'student') {
extra = studentNo;
} else if (identity === 'teacher') {
extra = jobTitle;
} else {
extra = manager;
}
_context5.next = 9;
return dispatch({
type: 'account/applyProfessionalAuth',
payload: {
id: ((_account$basicInfo = account.basicInfo) === null || _account$basicInfo === void 0 ? void 0 : _account$basicInfo.id) || ((_user$userInfo = user.userInfo) === null || _user$userInfo === void 0 ? void 0 : _user$userInfo.login),
school_id: school_id,
department_id: department_id,
identity: identity,
extra: extra,
attachment_ids: [fileId]
}
});
case 9:
res = _context5.sent;
handleClose();
if (res) {
es_message["b" /* default */].info("申请已提交,请等待审核!");
dispatch({
type: 'account/getBasicInfo',
payload: {
login: (_user$userInfo2 = user.userInfo) === null || _user$userInfo2 === void 0 ? void 0 : _user$userInfo2.login
}
});
}
case 12:
case "end":
return _context5.stop();
}
}
}, _callee5);
}));
return function handleFinish(_x4) {
return _ref6.apply(this, arguments);
};
}();
var handleClose = function handleClose() {
dispatch({
type: 'account/setActionTabs',
payload: {}
});
};
var uploadProps = {
data: {
type: "professional"
},
multiple: true,
showUploadList: false,
action: "".concat(env["a" /* default */].API_SERVER, "/api/attachments.json"),
className: componentmodules_default.a.uploader,
onChange: handleUploadChange,
beforeUpload: function beforeUpload(file) {
var isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/bmp';
if (!isJpgOrPng) {
es_message["b" /* default */].info('请上传正确文件格式');
}
return isJpgOrPng;
}
};
return /*#__PURE__*/react_default.a.createElement(es_modal["a" /* default */], {
centered: true,
keyboard: false,
closable: false,
destroyOnClose: true,
className: componentmodules_default.a.modal,
visible: account.actionTabs.key === 'Account-ProfessionalAuth',
title: /*#__PURE__*/react_default.a.createElement("div", null, /*#__PURE__*/react_default.a.createElement("i", {
className: "iconfont icon-zhiyerenzheng font18 mr5 ".concat(componentmodules_default.a.colorBlue)
}), "\u804C\u4E1A\u8BA4\u8BC1"),
width: "660px",
footer: null
}, /*#__PURE__*/react_default.a.createElement(spin["a" /* default */], {
spinning: !!isLoading
}, /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */], {
className: componentmodules_default.a.formWrap,
form: form,
layout: "horizontal",
onValuesChange: handleValuesChange,
onFinish: handleFinish
}, /*#__PURE__*/react_default.a.createElement(es_row["a" /* default */], {
gutter: [10, 0]
}, /*#__PURE__*/react_default.a.createElement(es_col["a" /* default */], {
flex: '300px'
}, /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
label: "\u804C\u4E1A",
name: "identity",
rules: [{
required: true,
message: '请先选择职业'
}]
}, /*#__PURE__*/react_default.a.createElement(es_select["a" /* default */], null, /*#__PURE__*/react_default.a.createElement(ProfessionalAuthModal_Option, {
value: "teacher"
}, "\u6559\u5E08"), /*#__PURE__*/react_default.a.createElement(ProfessionalAuthModal_Option, {
value: "student"
}, "\u5B66\u751F"), /*#__PURE__*/react_default.a.createElement(ProfessionalAuthModal_Option, {
value: "professional"
}, "\u4E13\u4E1A\u4EBA\u58EB")))), formValue.identity === 'student' && /*#__PURE__*/react_default.a.createElement(es_col["a" /* default */], {
flex: '200px'
}, /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
initialValue: formValue.studentNo,
name: "studentNo",
rules: [{
required: true,
message: '请先输入学号'
}]
}, /*#__PURE__*/react_default.a.createElement(es_input["a" /* default */], {
type: "text",
placeholder: "\u8BF7\u8F93\u5165\u5B66\u53F7"
}))), formValue.identity === 'teacher' && /*#__PURE__*/react_default.a.createElement(es_col["a" /* default */], {
flex: '200px'
}, /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
initialValue: formValue.jobTitle,
name: "jobTitle",
rules: [{
required: true,
message: '请先选择职称'
}]
}, /*#__PURE__*/react_default.a.createElement(es_select["a" /* default */], null, /*#__PURE__*/react_default.a.createElement(ProfessionalAuthModal_Option, {
value: "\u6559\u6388"
}, "\u6559\u6388"), /*#__PURE__*/react_default.a.createElement(ProfessionalAuthModal_Option, {
value: "\u526F\u6559\u6388"
}, "\u526F\u6559\u6388"), /*#__PURE__*/react_default.a.createElement(ProfessionalAuthModal_Option, {
value: "\u8BB2\u5E08"
}, "\u8BB2\u5E08"), /*#__PURE__*/react_default.a.createElement(ProfessionalAuthModal_Option, {
value: "\u52A9\u6559"
}, "\u52A9\u6559")))), formValue.identity === 'professional' && /*#__PURE__*/react_default.a.createElement(es_col["a" /* default */], {
flex: '200px'
}, /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
initialValue: formValue.manager,
name: "manager",
rules: [{
required: true,
message: '请先选择职称'
}]
}, /*#__PURE__*/react_default.a.createElement(es_select["a" /* default */], null, /*#__PURE__*/react_default.a.createElement(ProfessionalAuthModal_Option, {
value: "\u4F01\u4E1A\u7BA1\u7406\u8005"
}, "\u4F01\u4E1A\u7BA1\u7406\u8005"), /*#__PURE__*/react_default.a.createElement(ProfessionalAuthModal_Option, {
value: "\u90E8\u95E8\u7BA1\u7406\u8005"
}, "\u90E8\u95E8\u7BA1\u7406\u8005"), /*#__PURE__*/react_default.a.createElement(ProfessionalAuthModal_Option, {
value: "\u9AD8\u7EA7\u5DE5\u7A0B\u5E08"
}, "\u9AD8\u7EA7\u5DE5\u7A0B\u5E08"), /*#__PURE__*/react_default.a.createElement(ProfessionalAuthModal_Option, {
value: "\u5DE5\u7A0B\u5E08"
}, "\u5DE5\u7A0B\u5E08"), /*#__PURE__*/react_default.a.createElement(ProfessionalAuthModal_Option, {
value: "\u52A9\u7406\u5DE5\u7A0B\u5E08"
}, "\u52A9\u7406\u5DE5\u7A0B\u5E08"))))), /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
label: "\u5B66\u6821/\u5355\u4F4D",
name: "school",
extra: formValue.school && !(schoolList === null || schoolList === void 0 ? void 0 : schoolList.find(function (item) {
return item.name === formValue.school;
})) && /*#__PURE__*/react_default.a.createElement("div", {
className: componentmodules_default.a.schoolHintWrap
}, /*#__PURE__*/react_default.a.createElement("span", {
className: componentmodules_default.a.colorCDCDCD
}, "\u672A\u627E\u5230\u5305\u542B\u201C", formValue.school, "\u201D\u7684\u9AD8\u6821\uFF0C"), /*#__PURE__*/react_default.a.createElement("span", {
className: "".concat(componentmodules_default.a.color4CACFF, " current"),
onClick: handleApplySchool
}, "\u7533\u8BF7\u65B0\u589E")),
rules: [{
required: true,
message: '请先选择学校/单位'
}]
}, /*#__PURE__*/react_default.a.createElement(auto_complete, {
showSearch: true,
options: filterSchoolList === null || filterSchoolList === void 0 ? void 0 : filterSchoolList.map(function (item) {
return {
value: item.name
};
})
})), /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
label: "\u9662\u7CFB/\u90E8\u95E8",
name: "department",
extra: formValue.department && !(departmentList === null || departmentList === void 0 ? void 0 : departmentList.find(function (item) {
return item.name === formValue.department;
})) && /*#__PURE__*/react_default.a.createElement("div", {
className: componentmodules_default.a.schoolHintWrap
}, /*#__PURE__*/react_default.a.createElement("span", {
className: componentmodules_default.a.colorCDCDCD
}, formValue.department ? "\u672A\u627E\u5230\u5305\u542B\u201C".concat(formValue.department, "\u201D\u7684\u9AD8\u6821\uFF0C") : '未找到院系,'), /*#__PURE__*/react_default.a.createElement("span", {
className: "".concat(componentmodules_default.a.color4CACFF, " current"),
onClick: handleApplyDepartment
}, "\u7533\u8BF7\u65B0\u589E")),
rules: [{
required: true,
message: '请先选择院系/部门'
}]
}, /*#__PURE__*/react_default.a.createElement(auto_complete, {
showSearch: true,
onChange: function onChange(value) {
return setFilterDepartmentList(departmentList.filter(function (item) {
return item.name.includes(value);
}));
},
options: filterDepartmentList === null || filterDepartmentList === void 0 ? void 0 : filterDepartmentList.map(function (item) {
return {
value: item.name
};
})
})), /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
label: "\u804C\u4E1A\u8BC1\u4E0A\u4F20"
}, /*#__PURE__*/react_default.a.createElement("div", {
className: componentmodules_default.a.flexRow
}, /*#__PURE__*/react_default.a.createElement("div", {
className: "".concat(componentmodules_default.a.flexColumn, " ").concat(componentmodules_default.a.example)
}, /*#__PURE__*/react_default.a.createElement("span", {
className: componentmodules_default.a.exampleImg
}, /*#__PURE__*/react_default.a.createElement("img", {
src: job_default.a
})), /*#__PURE__*/react_default.a.createElement("span", {
className: "tc"
}, /*#__PURE__*/react_default.a.createElement("p", null, "\u793A\u4F8B\u56FE\u7247"), /*#__PURE__*/react_default.a.createElement("p", {
className: "".concat(componentmodules_default.a.colorOrange, " font12")
}, "\uFF08png/jpg/bmp\u683C\u5F0F\uFF0C\u4E0D\u8D85\u8FC72MB\uFF09"))), /*#__PURE__*/react_default.a.createElement("div", {
className: componentmodules_default.a.flexColumn
}, /*#__PURE__*/react_default.a.createElement(ProfessionalAuthModal_Dragger, Object(esm_extends["a" /* default */])({}, uploadProps, {
accept: ".png,.jpg,.bmp,.jpeg"
}), image ? /*#__PURE__*/react_default.a.createElement("img", {
src: image,
className: componentmodules_default.a.uploadImg
}) : /*#__PURE__*/react_default.a.createElement("div", {
className: componentmodules_default.a.imageTip
}, /*#__PURE__*/react_default.a.createElement("p", null, /*#__PURE__*/react_default.a.createElement("i", {
className: "iconfont icon-cuban2shangchuanyunduan ".concat(componentmodules_default.a.uploadTipIcon)
})), /*#__PURE__*/react_default.a.createElement("p", {
className: componentmodules_default.a.uploadTip
}, /*#__PURE__*/react_default.a.createElement("a", {
className: componentmodules_default.a.color05101a
}, "\u70B9\u51FB\u6216\u62D6\u62FD\u4E0A\u4F20\u56FE\u7247")))), /*#__PURE__*/react_default.a.createElement("span", {
className: "tc"
}, /*#__PURE__*/react_default.a.createElement("p", {
className: componentmodules_default.a.viewLargerImg
}, "\u67E5\u770B\u5927\u56FE"))))), /*#__PURE__*/react_default.a.createElement("div", {
className: componentmodules_default.a.footerWrap
}, /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, null, /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
className: "mr5",
size: "large",
onClick: handleClose
}, "\u53D6\u6D88"), /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
size: "large",
type: "primary",
htmlType: "submit",
loading: loading['account/applyProfessionalAuth']
}, "\u4FDD\u5B58"))), /*#__PURE__*/react_default.a.createElement("div", {
className: componentmodules_default.a.note
}, /*#__PURE__*/react_default.a.createElement("p", null, "\u8BA4\u8BC1\u987B\u77E5\uFF1A"), /*#__PURE__*/react_default.a.createElement("p", null, "1.\u6839\u636E\u804C\u4E1A\u4E0A\u4F20\u76F8\u5E94\u7684\u8BC1\u4EF6\u7167\uFF1A\u6559\u5E08\uFF08\u6559\u5E08\u8BC1\uFF09\uFF0C\u4E13\u4E1A\u4EBA\u58EB\uFF08\u5458\u5DE5\u8BC1\uFF09\u3001\u5B66\u751F\uFF08\u5B66\u751F\u8BC1\uFF09\uFF0C\u8BF7\u786E\u4FDD\u8BC1\u4EF6\u7167\u5185\u5BB9\u5B8C\u6574\u5E76\u4E14\u6E05\u6670\u53EF\u89C1\uFF0C\u4E25\u7981PS\uFF1B"), /*#__PURE__*/react_default.a.createElement("p", null, "2.\u6211\u4EEC\u5C06\u5728\u4F60\u63D0\u4EA4\u804C\u4E1A\u8BC1\u4FE1\u606F\u540E\u768424\u5C0F\u65F6\uFF08\u4E0D\u5305\u542B\u8282\u5047\u65E5\uFF09\u5185\u5B8C\u6210\u5BA1\u6838\uFF0C\u5BA1\u6838\u7ED3\u679C\u5C06\u4F1A\u4EE5\u7CFB\u7EDF\u6D88\u606F\u7684\u5F62\u5F0F\u53D1\u9001\u7ED9\u4F60\uFF1B"), /*#__PURE__*/react_default.a.createElement("p", null, "3.\u804C\u4E1A\u8BA4\u8BC1\u5BA1\u6838\u5B8C\u6210\u540E\uFF0C\u65E0\u6CD5\u5220\u9664\uFF0C\u8BF7\u8C28\u614E\u586B\u5199\uFF1B\u804C\u4E1A\u53D8\u66F4\u8BF7\u9009\u62E9\u91CD\u65B0\u8BA4\u8BC1\uFF1B"), /*#__PURE__*/react_default.a.createElement("p", null, "4.\u804C\u4E1A\u8BA4\u8BC1\u5BA1\u6838\u5B8C\u6210\u540E\uFF0C\u7CFB\u7EDF\u5C06\u81EA\u52A8\u53D1\u653E500\u4E2A\u91D1\u5E01\u4F5C\u4E3A\u5956\u52B1\uFF1B"), /*#__PURE__*/react_default.a.createElement("p", null, "5.\u6211\u4EEC\u4F1A\u786E\u4FDD\u4F60\u6240\u63D0\u4F9B\u7684\u4FE1\u606F\u5747\u5904\u4E8E\u4E25\u683C\u7684\u4FDD\u5BC6\u72B6\u6001\uFF0C\u4E0D\u4F1A\u6CC4\u9732\uFF1B"), /*#__PURE__*/react_default.a.createElement("p", null, "6.\u5982\u5B58\u5728\u6076\u610F\u4E71\u586B\u5199\u59D3\u540D\uFF0C\u5B66\u53F7\uFF0C\u53CA\u4E0A\u4F20\u4E0E\u804C\u4E1A\u8BC1\u4EF6\u65E0\u5173\u56FE\u7247\u8005\uFF0C\u4E00\u7ECF\u53D1\u73B0\u5C06\u51BB\u7ED3", !(globalSetting === null || globalSetting === void 0 ? void 0 : (_globalSetting$settin = globalSetting.setting) === null || _globalSetting$settin === void 0 ? void 0 : _globalSetting$settin.is_local) && 'EduCoder', "\u8D26\u53F7\u3002"), /*#__PURE__*/react_default.a.createElement("p", null, "7.\u975E\u8001\u5E08\u8EAB\u4EFD\u63D0\u4EA4\u804C\u4E1A\u8BA4\u8BC1\u540E\u7CFB\u7EDF\u4F1A\u81EA\u52A8\u5C06\u72B6\u6001\u6539\u4E3A\u5DF2\u8BA4\u8BC1\uFF0C\u4F60\u5C06\u53EF\u4EE5\u4F53\u9A8C\u5E73\u53F0\u9700\u8981\u804C\u4E1A\u8BA4\u8BC1\u7684\u529F\u80FD\uFF1B\u5982\u679C\u5728\u8BA4\u8BC1\u540E\u7684\u4F7F\u7528\u8FC7\u7A0B\u4E2D\u672A\u901A\u8FC7\u5BA1\u6838\uFF0C\u4F60\u5C06\u4E0D\u80FD\u7EE7\u7EED\u4F53\u9A8C\u9700\u8981\u8BA4\u8BC1\u7684\u529F\u80FD\u3002")))), /*#__PURE__*/react_default.a.createElement(components_AppplySchoolModal, {
visible: visibleAppplySchool,
onClose: function onClose() {
return setVisibleAppplySchool(false);
},
schoolName: formValue.school,
onSuccess: handleSchoolSuccess
}), /*#__PURE__*/react_default.a.createElement(components_AppplyDepartmentModal, {
visible: visibleAppplyDepartment,
onClose: function onClose() {
return setVisibleAppplyDepartment(false);
},
schoolId: (_schoolList$find3 = schoolList.find(function (item) {
return item.name === formValue.school;
})) === null || _schoolList$find3 === void 0 ? void 0 : _schoolList$find3.id,
schoolName: formValue.school,
departmentName: formValue.department,
onSuccess: function onSuccess(departmentName) {
return handleSetDepartment(formValue.school, departmentName);
}
}));
};
/* harmony default export */ var component_ProfessionalAuthModal = (Object(umiExports["a" /* connect */])(function (_ref8) {
var user = _ref8.user,
account = _ref8.account,
loading = _ref8.loading,
globalSetting = _ref8.globalSetting;
return {
user: user,
account: account,
globalSetting: globalSetting,
loading: loading.effects
};
})(ProfessionalAuthModal_ProfessionalAuthModal));
// EXTERNAL MODULE: ./node_modules/md5/md5.js
var md5 = __webpack_require__("aCH8");
var md5_default = /*#__PURE__*/__webpack_require__.n(md5);
// CONCATENATED MODULE: ./src/pages/Competitions/Detail/UpdataPhone.tsx
//修改手机号or邮箱地址
//type 3 手机 4邮箱
function UpdataPhone(_ref) {
var type = _ref.type,
dispatch = _ref.dispatch,
userid = _ref.userid,
isshow = _ref.isshow,
setPhoneshow = _ref.setPhoneshow,
setEmailshow = _ref.setEmailshow;
var opens = "79e33abd4b6588941ab7622aed1e67e8";
var _useState = Object(react["useState"])(''),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
login = _useState2[0],
setLogin = _useState2[1];
var _useState3 = Object(react["useState"])('获取验证码'),
_useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
yzm = _useState4[0],
setYzm = _useState4[1];
var _useState5 = Object(react["useState"])(60),
_useState6 = Object(slicedToArray["a" /* default */])(_useState5, 2),
seconds = _useState6[0],
setseconds = _useState6[1];
var _useState7 = Object(react["useState"])(false),
_useState8 = Object(slicedToArray["a" /* default */])(_useState7, 2),
secondsFlag = _useState8[0],
setsecondsFlag = _useState8[1];
var _useState9 = Object(react["useState"])(''),
_useState10 = Object(slicedToArray["a" /* default */])(_useState9, 2),
code = _useState10[0],
setCode = _useState10[1]; //获取验证码
function getversion() {
return _getversion.apply(this, arguments);
} // 获取验证码倒计时
function _getversion() {
_getversion = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee() {
var data;
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (login) {
_context.next = 3;
break;
}
if (type === 3) {
es_message["b" /* default */].info('手机号不能为空');
} else {
es_message["b" /* default */].info('邮箱地址不能为空');
}
return _context.abrupt("return");
case 3:
_context.next = 5;
return dispatch({
type: 'competitions/getVerification',
payload: {
type: type,
login: login,
smscode: md5_default()(opens + login) //user_id:39416
}
});
case 5:
data = _context.sent;
if (data.status === 1) {
es_message["b" /* default */].info('获取验证码成功');
remainTime();
setsecondsFlag(true);
}
case 7:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return _getversion.apply(this, arguments);
}
function remainTime() {
setseconds(60);
var aa = setInterval(function () {
--seconds;
if (seconds > -1) {
setseconds(seconds);
} else {
clearInterval(aa);
setsecondsFlag(false);
}
}, 1000);
} //绑定手机号
function PhoneBind() {
return _PhoneBind.apply(this, arguments);
} //绑定邮箱
function _PhoneBind() {
_PhoneBind = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee2() {
var data;
return regenerator_default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return dispatch({
type: 'competitions/PhoneBind',
payload: {
userid: userid,
code: code,
phone: login
}
});
case 2:
data = _context2.sent;
if (data.status === 0) {
es_message["b" /* default */].info('绑定成功');
setPhoneshow("none");
}
case 4:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
return _PhoneBind.apply(this, arguments);
}
function EmailBind() {
return _EmailBind.apply(this, arguments);
}
function _EmailBind() {
_EmailBind = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee3() {
var data;
return regenerator_default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.next = 2;
return dispatch({
type: 'competitions/EmailBind',
payload: {
userid: userid,
code: code,
email: login
}
});
case 2:
data = _context3.sent;
if (data.status === 0) {
es_message["b" /* default */].info('绑定成功');
setEmailshow('none');
}
case 4:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
return _EmailBind.apply(this, arguments);
}
return /*#__PURE__*/react_default.a.createElement("div", {
style: {
display: isshow
}
}, /*#__PURE__*/react_default.a.createElement("p", null, /*#__PURE__*/react_default.a.createElement(es_input["a" /* default */], {
value: login,
onChange: function onChange(e) {
return setLogin(e.target.value);
},
placeholder: type === 3 ? '请输入手机号' : '请输入邮箱地址',
style: {
width: '370px'
}
})), /*#__PURE__*/react_default.a.createElement("span", null, /*#__PURE__*/react_default.a.createElement(es_input["a" /* default */], {
value: code,
onChange: function onChange(e) {
return setCode(e.target.value);
},
placeholder: type === 3 ? '请输入手机获取的验证码' : '请输入邮箱获取的验证码',
style: {
width: '250px'
}
})), " ", /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
disabled: secondsFlag,
onClick: function onClick() {
return getversion();
},
type: "primary",
style: {
marginLeft: '20px',
width: '100px'
}
}, secondsFlag ? "\u91CD\u65B0\u53D1\u9001".concat(seconds, "s") : yzm), /*#__PURE__*/react_default.a.createElement("p", {
style: {
marginTop: '30px',
width: '370px',
textAlign: 'center'
}
}, /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
type: "primary",
style: {
marginRight: '15px'
},
onClick: function onClick() {
if (!code) {
es_message["b" /* default */].info('验证码不能为空');
return;
}
if (type === 3) {
PhoneBind();
} else {
EmailBind();
}
}
}, "\u786E\u8BA4"), /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
style: {
marginLeft: '20px'
},
onClick: function onClick() {
if (type === 3) {
setPhoneshow("none");
} else {
setEmailshow('none');
}
}
}, "\u53D6\u6D88")));
}
/* harmony default export */ var Detail_UpdataPhone = (UpdataPhone);
// CONCATENATED MODULE: ./src/pages/Competitions/Detail/Addleader.tsx
//填写银行卡号等信息
function Addleader(_ref) {
var dispatch = _ref.dispatch,
userid = _ref.userid;
var tailLayout = {
wrapperCol: {
offset: 3,
span: 21
}
};
var _Form$useForm = es_form["a" /* default */].useForm(),
_Form$useForm2 = Object(slicedToArray["a" /* default */])(_Form$useForm, 1),
form = _Form$useForm2[0];
var _useParams = Object(react_router["l" /* useParams */])(),
identifier = _useParams.identifier;
return /*#__PURE__*/react_default.a.createElement("div", {
style: {
width: '500px'
}
}, /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */], {
form: form,
name: "basic"
}, /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, Object(esm_extends["a" /* default */])({}, tailLayout, {
label: /*#__PURE__*/react_default.a.createElement("div", {
style: {
width: "30px"
}
}, "\u5F00\u6237\u884C"),
name: "bank",
rules: [{
required: true,
message: '请输入开户行'
}]
}), /*#__PURE__*/react_default.a.createElement(es_input["a" /* default */], null)), /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, Object(esm_extends["a" /* default */])({}, tailLayout, {
label: /*#__PURE__*/react_default.a.createElement("div", {
style: {
width: "30px"
}
}, "\u652F\u884C"),
name: "second_bank",
rules: [{
required: true,
message: '请输入支行'
}]
}), /*#__PURE__*/react_default.a.createElement(es_input["a" /* default */], null)), /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, Object(esm_extends["a" /* default */])({}, tailLayout, {
label: /*#__PURE__*/react_default.a.createElement("div", {
style: {
width: "30px"
}
}, "\u8D26\u53F7"),
name: "card_no",
rules: [{
required: true,
message: '请输入账号'
}]
}), /*#__PURE__*/react_default.a.createElement(es_input["a" /* default */], null)), /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, null, /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
type: "primary",
htmlType: "submit",
onClick: /*#__PURE__*/Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee2() {
return regenerator_default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
form.validateFields().then( /*#__PURE__*/function () {
var _ref3 = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee(vaule) {
var data;
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return dispatch({
type: 'competitions/setleader',
payload: Object(objectSpread2["a" /* default */])({
identifier: identifier,
user_id: userid
}, vaule)
});
case 2:
data = _context.sent;
if (data.status === 0) {
es_message["b" /* default */].info('提交成功');
}
case 4:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function (_x) {
return _ref3.apply(this, arguments);
};
}());
case 1:
case "end":
return _context2.stop();
}
}
}, _callee2);
}))
}, "\u63D0\u4EA4"))));
}
/* harmony default export */ var Detail_Addleader = (Addleader);
// CONCATENATED MODULE: ./src/pages/Competitions/Detail/PerfectuserInfon.tsx
//完善个人信息
var identityMap = {
"teacher": "教师",
"student": "学生",
"professional": "专业人士"
};
function PerfectUser(_ref) {
var _Prize$teams$, _Prize$teams$$bank_ac, _Prize$teams$2, _Prize$teams$2$bank_a, _Prize$teams$3, _Prize$teams$3$bank_a, _Prize$teams$4, _Prize$teams$4$bank_a;
var Prize = _ref.Prize,
Accounts = _ref.Accounts,
dispatch = _ref.dispatch,
userid = _ref.userid;
var _useState = Object(react["useState"])('none'),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
phoneshow = _useState2[0],
setPhoneshow = _useState2[1];
var _useState3 = Object(react["useState"])('none'),
_useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
emailshow = _useState4[0],
setEmailshow = _useState4[1];
function update(_x) {
return _update.apply(this, arguments);
}
function _update() {
_update = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee(type) {
var data;
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (!(type === "1")) {
_context.next = 6;
break;
}
_context.next = 3;
return dispatch({
type: 'competitions/Authentication'
});
case 3:
data = _context.sent;
_context.next = 9;
break;
case 6:
_context.next = 8;
return dispatch({
type: 'competitions/Professional'
});
case 8:
data = _context.sent;
case 9:
if (data.status === 0) {
es_message["b" /* default */].info('撤销成功');
}
case 10:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return _update.apply(this, arguments);
}
return /*#__PURE__*/react_default.a.createElement("div", null, /*#__PURE__*/react_default.a.createElement("p", null, /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: 'red'
}
}, "*"), /*#__PURE__*/react_default.a.createElement("span", {
style: {
fontSize: '16px'
}
}, "\u5B9E\u540D\u4FE1\u606F"), (Accounts === null || Accounts === void 0 ? void 0 : Accounts.authentication) === "uncertified" ? /*#__PURE__*/react_default.a.createElement("span", {
style: {
fontSize: '14px',
marginLeft: '20px'
}
}, "\u901A\u8FC7\u5B9E\u540D\u8BA4\u8BC1\u540E\u624D\u80FD\u83B7\u5F97\u8BC1\u4E66") : null, (Accounts === null || Accounts === void 0 ? void 0 : Accounts.authentication) === "uncertified" ? /*#__PURE__*/react_default.a.createElement("span", {
style: {
fontSize: '14px',
marginLeft: '20px',
color: "#4cacff",
cursor: 'pointer'
},
onClick: function onClick() {
dispatch({
type: 'account/setActionTabs',
payload: {
key: 'Account-RealNameAuth'
}
});
}
}, "\u7ACB\u5373\u8BA4\u8BC1") : null), /*#__PURE__*/react_default.a.createElement("div", {
style: {
padding: '20px'
}
}, /*#__PURE__*/react_default.a.createElement("p", null, "\u59D3\u540D\uFF1A", /*#__PURE__*/react_default.a.createElement("span", null, Accounts === null || Accounts === void 0 ? void 0 : Accounts.name), (Accounts === null || Accounts === void 0 ? void 0 : Accounts.authentication) === "uncertified" ? null : (Accounts === null || Accounts === void 0 ? void 0 : Accounts.authentication) === "applying" ? /*#__PURE__*/react_default.a.createElement("span", null, /*#__PURE__*/react_default.a.createElement("span", null, "\u5F85\u5BA1\u6838"), /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
type: "primary",
onClick: function onClick() {
return update("1");
},
ghost: true,
style: {
marginLeft: '20px'
}
}, "\u64A4\u9500\u8BA4\u8BC1")) : /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#6ec76e'
}
}, /*#__PURE__*/react_default.a.createElement("span", {
className: "iconfont icon-wancheng font-14 ml20"
}), " \u5DF2\u8BA4\u8BC1")), /*#__PURE__*/react_default.a.createElement("p", null, "\u6027\u522B\uFF1A", /*#__PURE__*/react_default.a.createElement("span", null, (Accounts === null || Accounts === void 0 ? void 0 : Accounts.gender) === 0 ? '男' : '女'))), /*#__PURE__*/react_default.a.createElement("p", null, /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: 'red'
}
}, "*"), /*#__PURE__*/react_default.a.createElement("span", {
style: {
fontSize: '16px'
}
}, "\u804C\u4E1A\u4FE1\u606F"), (Accounts === null || Accounts === void 0 ? void 0 : Accounts.authentication) === "uncertified" ? /*#__PURE__*/react_default.a.createElement("span", {
style: {
fontSize: '14px',
marginLeft: '20px'
}
}, "\u901A\u8FC7\u5B9E\u540D\u8BA4\u8BC1\u540E\u624D\u80FD\u83B7\u5F97\u8BC1\u4E66") : null, (Accounts === null || Accounts === void 0 ? void 0 : Accounts.authentication) === "uncertified" ? /*#__PURE__*/react_default.a.createElement("span", {
style: {
fontSize: '14px',
marginLeft: '20px',
color: "#4cacff"
},
onClick: function onClick() {
dispatch({
type: 'account/setActionTabs',
payload: {
key: 'Account-ProfessionalAuth'
}
});
}
}, "\u7ACB\u5373\u8BA4\u8BC1") : null), /*#__PURE__*/react_default.a.createElement("div", {
style: {
padding: '20px'
}
}, /*#__PURE__*/react_default.a.createElement("p", null, "\u804C\u4E1A\uFF1A", /*#__PURE__*/react_default.a.createElement("span", null, Accounts && Accounts.identity && identityMap[Accounts.identity]), (Accounts === null || Accounts === void 0 ? void 0 : Accounts.authentication) === "uncertified" ? null : (Accounts === null || Accounts === void 0 ? void 0 : Accounts.authentication) === "applying" ? /*#__PURE__*/react_default.a.createElement("span", null, /*#__PURE__*/react_default.a.createElement("span", null, "\u5F85\u5BA1\u6838"), /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
type: "primary",
onClick: function onClick() {
return update("2");
},
ghost: true,
style: {
marginLeft: '20px'
}
}, "\u64A4\u9500\u8BA4\u8BC1")) : /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#6ec76e'
}
}, /*#__PURE__*/react_default.a.createElement("span", {
className: "iconfont icon-wancheng font-12 ml20"
}), /*#__PURE__*/react_default.a.createElement("span", null, "\u5DF2\u8BA4\u8BC1"), /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
type: "primary",
onClick: function onClick() {
dispatch({
type: 'account/setActionTabs',
payload: {
key: 'Account-ProfessionalAuth'
}
});
},
ghost: true,
style: {
marginLeft: '20px'
}
}, "\u91CD\u65B0\u8BA4\u8BC1"))), /*#__PURE__*/react_default.a.createElement("p", null, "\u5B66\u53F7\uFF1A", /*#__PURE__*/react_default.a.createElement("span", null, (Accounts === null || Accounts === void 0 ? void 0 : Accounts.student_id) || '--')), /*#__PURE__*/react_default.a.createElement("p", null, "\u5B66\u6821\uFF1A", /*#__PURE__*/react_default.a.createElement("span", null, (Accounts === null || Accounts === void 0 ? void 0 : Accounts.school_name) || '--')), /*#__PURE__*/react_default.a.createElement("p", null, "\u9662\u7CFB\uFF1A", /*#__PURE__*/react_default.a.createElement("span", null, (Accounts === null || Accounts === void 0 ? void 0 : Accounts.department_name) || '--'))), /*#__PURE__*/react_default.a.createElement("p", null, /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: 'red'
}
}, "*"), /*#__PURE__*/react_default.a.createElement("span", {
style: {
fontSize: '16px'
}
}, "\u8054\u7CFB\u65B9\u5F0F")), /*#__PURE__*/react_default.a.createElement("div", {
style: {
padding: '20px'
}
}, /*#__PURE__*/react_default.a.createElement("p", {
style: {
display: 'flex'
}
}, /*#__PURE__*/react_default.a.createElement("span", {
style: {
width: '60px',
textAlign: 'right'
}
}, "\u624B\u673A\u53F7\uFF1A"), /*#__PURE__*/react_default.a.createElement("span", {
style: {
width: '150px'
}
}, (Accounts === null || Accounts === void 0 ? void 0 : Accounts.phone) || '--'), phoneshow === 'none' ? /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#4cacff',
marginLeft: '20px',
cursor: 'pointer'
},
onClick: function onClick() {
setPhoneshow('block');
}
}, "\u66F4\u6362") : null), /*#__PURE__*/react_default.a.createElement(Detail_UpdataPhone, {
type: 3,
dispatch: dispatch,
userid: Accounts === null || Accounts === void 0 ? void 0 : Accounts.id,
isshow: phoneshow,
setPhoneshow: setPhoneshow,
setEmailshow: setEmailshow
}), /*#__PURE__*/react_default.a.createElement("p", {
style: {
display: 'flex'
}
}, /*#__PURE__*/react_default.a.createElement("span", {
style: {
width: '60px',
textAlign: 'right'
}
}, "Email\uFF1A"), /*#__PURE__*/react_default.a.createElement("span", {
style: {
width: '150px'
}
}, (Accounts === null || Accounts === void 0 ? void 0 : Accounts.mail) || '--'), emailshow === 'none' ? /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#4cacff',
marginLeft: '20px',
cursor: 'pointer'
},
onClick: function onClick() {
setEmailshow('block');
}
}, "\u66F4\u6362") : null), /*#__PURE__*/react_default.a.createElement(Detail_UpdataPhone, {
type: 4,
dispatch: dispatch,
userid: Accounts === null || Accounts === void 0 ? void 0 : Accounts.id,
isshow: emailshow,
setEmailshow: setEmailshow,
setPhoneshow: setPhoneshow
})), (Prize === null || Prize === void 0 ? void 0 : Prize.leader) && (Prize === null || Prize === void 0 ? void 0 : Prize.teams) && (Prize === null || Prize === void 0 ? void 0 : (_Prize$teams$ = Prize.teams[0]) === null || _Prize$teams$ === void 0 ? void 0 : (_Prize$teams$$bank_ac = _Prize$teams$.bank_account) === null || _Prize$teams$$bank_ac === void 0 ? void 0 : _Prize$teams$$bank_ac.bank) ? /*#__PURE__*/react_default.a.createElement("p", null, /*#__PURE__*/react_default.a.createElement("span", {
style: {
fontSize: '16px'
}
}, "\u7B7E/\u9886/\u5F00\u6237\u884C\u53CA\u94F6\u884C\u5361\u53F7"), /*#__PURE__*/react_default.a.createElement("span", {
style: {
fontSize: '12px',
marginLeft: '20px'
}
}, "\u4E3A\u4FDD\u969C\u5956\u91D1\u7684\u53CA\u65F6\u53D1\u653E\uFF0C\u8BF7\u961F\u957F\u5982\u5B9E\u586B\u5199\u4F60\u540D\u4E0B\u7684\u94F6\u884C\u5361\u4FE1\u606F")) : /*#__PURE__*/react_default.a.createElement("div", null, /*#__PURE__*/react_default.a.createElement("p", null, /*#__PURE__*/react_default.a.createElement("span", {
style: {
fontSize: '16px'
}
}, "\u7B7E/\u9886/\u5F00\u6237\u884C\u53CA\u94F6\u884C\u5361\u53F7"), /*#__PURE__*/react_default.a.createElement("span", {
style: {
fontSize: '12px',
marginLeft: '20px'
}
}, "\u4E3A\u4FDD\u969C\u5956\u91D1\u7684\u53CA\u65F6\u53D1\u653E\uFF0C\u8BF7\u961F\u957F\u5982\u5B9E\u586B\u5199\u4F60\u540D\u4E0B\u7684\u94F6\u884C\u5361\u4FE1\u606F")), /*#__PURE__*/react_default.a.createElement(Detail_Addleader, {
dispatch: dispatch,
userid: userid
})), (Prize === null || Prize === void 0 ? void 0 : Prize.leader) ? /*#__PURE__*/react_default.a.createElement("div", {
style: {
padding: '20px'
}
}, /*#__PURE__*/react_default.a.createElement("p", {
style: {
display: 'flex'
}
}, /*#__PURE__*/react_default.a.createElement("span", {
style: {
width: '60px',
textAlign: 'right'
}
}, "\u5F00\u6237\u884C\uFF1A"), /*#__PURE__*/react_default.a.createElement("span", null, (Prize === null || Prize === void 0 ? void 0 : Prize.teams) && (Prize === null || Prize === void 0 ? void 0 : (_Prize$teams$2 = Prize.teams[0]) === null || _Prize$teams$2 === void 0 ? void 0 : (_Prize$teams$2$bank_a = _Prize$teams$2.bank_account) === null || _Prize$teams$2$bank_a === void 0 ? void 0 : _Prize$teams$2$bank_a.bank) || '--')), /*#__PURE__*/react_default.a.createElement("p", {
style: {
display: 'flex'
}
}, /*#__PURE__*/react_default.a.createElement("span", {
style: {
width: '60px',
textAlign: 'right'
}
}, "\u652F\u884C\uFF1A"), /*#__PURE__*/react_default.a.createElement("span", null, (Prize === null || Prize === void 0 ? void 0 : Prize.teams) && (Prize === null || Prize === void 0 ? void 0 : (_Prize$teams$3 = Prize.teams[0]) === null || _Prize$teams$3 === void 0 ? void 0 : (_Prize$teams$3$bank_a = _Prize$teams$3.bank_account) === null || _Prize$teams$3$bank_a === void 0 ? void 0 : _Prize$teams$3$bank_a.second_bank) || '--')), /*#__PURE__*/react_default.a.createElement("p", {
style: {
display: 'flex'
}
}, /*#__PURE__*/react_default.a.createElement("span", {
style: {
width: '60px',
textAlign: 'right'
}
}, "\u8D26\u53F7\uFF1A"), /*#__PURE__*/react_default.a.createElement("span", null, (Prize === null || Prize === void 0 ? void 0 : Prize.teams) && (Prize === null || Prize === void 0 ? void 0 : (_Prize$teams$4 = Prize.teams[0]) === null || _Prize$teams$4 === void 0 ? void 0 : (_Prize$teams$4$bank_a = _Prize$teams$4.bank_account) === null || _Prize$teams$4$bank_a === void 0 ? void 0 : _Prize$teams$4$bank_a.card_no) || '--'))) : null, /*#__PURE__*/react_default.a.createElement(component_ProfessionalAuthModal, {
Scoid: Accounts === null || Accounts === void 0 ? void 0 : Accounts.school_id
}), /*#__PURE__*/react_default.a.createElement(component_RealNameAuthModal, null));
}
/* harmony default export */ var PerfectuserInfon = (PerfectUser);
// CONCATENATED MODULE: ./src/pages/Competitions/Detail/AwardPdf.tsx
//获奖证书
var AwardPdf_TabPane = es_tabs["a" /* default */].TabPane;
function Awardpdf(_ref) {
var Prize = _ref.Prize,
Accounts = _ref.Accounts,
getAccounts = _ref.getAccounts,
dispatch = _ref.dispatch,
userid = _ref.userid;
return /*#__PURE__*/react_default.a.createElement("div", {
className: "fr"
}, /*#__PURE__*/react_default.a.createElement("div", {
className: "mb100 "
}, /*#__PURE__*/react_default.a.createElement(es_tabs["a" /* default */], {
defaultActiveKey: "1",
onChange: function onChange(e) {
if (e === "2") {
getAccounts();
}
}
}, /*#__PURE__*/react_default.a.createElement(AwardPdf_TabPane, {
tab: "\u83B7\u5956\u8BC1\u4E66\u4E0B\u8F7D",
key: "1"
}, /*#__PURE__*/react_default.a.createElement(Downloadpdf, {
Prize: Prize
})), /*#__PURE__*/react_default.a.createElement(AwardPdf_TabPane, {
tab: "\u5B8C\u5584\u4E2A\u4EBA\u4FE1\u606F",
key: "2"
}, /*#__PURE__*/react_default.a.createElement(PerfectuserInfon, {
userid: userid,
dispatch: dispatch,
Prize: Prize,
Accounts: Accounts
})))));
}
/* harmony default export */ var AwardPdf = (Awardpdf);
// EXTERNAL MODULE: ./src/utils/authority.ts
var authority = __webpack_require__("xKgJ");
// EXTERNAL MODULE: ./node_modules/moment/moment.js
var moment = __webpack_require__("wd/R");
var moment_default = /*#__PURE__*/__webpack_require__.n(moment);
// CONCATENATED MODULE: ./src/pages/Competitions/Detail/SubmitResult.tsx
var SubmitResult_TabPane = es_tabs["a" /* default */].TabPane;
function SubmitResult_Ranking(_ref) {
var _ChartRules$stages3, _ChartRules$stages4, _item$children, _item$children3, _HeaderDetail$competi, _HeaderDetail$competi2;
var ChartRules = _ref.ChartRules,
ItemData = _ref.ItemData,
getCharts = _ref.getCharts,
Selectkey = _ref.Selectkey,
HeaderDetail = _ref.HeaderDetail,
getChartRules = _ref.getChartRules,
userinfo = _ref.userinfo,
Editable = _ref.Editable,
dispatch = _ref.dispatch,
StaffDetail = _ref.StaffDetail;
var _useState = Object(react["useState"])(false),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
isUpdate = _useState2[0],
setIsupdate = _useState2[1];
var _useState3 = Object(react["useState"])(''),
_useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
defaultValue = _useState4[0],
setDefaultValue = _useState4[1];
var _useState5 = Object(react["useState"])(true),
_useState6 = Object(slicedToArray["a" /* default */])(_useState5, 2),
ClickButton = _useState6[0],
setClickButton = _useState6[1];
var _useState7 = Object(react["useState"])(),
_useState8 = Object(slicedToArray["a" /* default */])(_useState7, 2),
item = _useState8[0],
setItem = _useState8[1];
var _useState9 = Object(react["useState"])(),
_useState10 = Object(slicedToArray["a" /* default */])(_useState9, 2),
items = _useState10[0],
setItems = _useState10[1];
var _useParams = Object(react_router["l" /* useParams */])(),
identifier = _useParams.identifier;
Object(react["useEffect"])(function () {
//进入初始化状态为第一个
if (ClickButton) {
var _ChartRules$stages, _ChartRules$stages2, _ChartRules$stages2$, _ChartRules$stages2$$;
var data = ChartRules === null || ChartRules === void 0 ? void 0 : (_ChartRules$stages = ChartRules.stages) === null || _ChartRules$stages === void 0 ? void 0 : _ChartRules$stages[0];
setItem(data);
var datas = ChartRules === null || ChartRules === void 0 ? void 0 : (_ChartRules$stages2 = ChartRules.stages) === null || _ChartRules$stages2 === void 0 ? void 0 : (_ChartRules$stages2$ = _ChartRules$stages2[0]) === null || _ChartRules$stages2$ === void 0 ? void 0 : (_ChartRules$stages2$$ = _ChartRules$stages2$.children) === null || _ChartRules$stages2$$ === void 0 ? void 0 : _ChartRules$stages2$$[0];
setItems(datas);
if (data === null || data === void 0 ? void 0 : data.id) {
var _ChartRules$rule_cont, _ChartRules$rule_cont2, _ChartRules$rule_cont3;
getCharts(data === null || data === void 0 ? void 0 : data.id);
setDefaultValue(((_ChartRules$rule_cont = ChartRules.rule_contents) === null || _ChartRules$rule_cont === void 0 ? void 0 : (_ChartRules$rule_cont2 = _ChartRules$rule_cont.filter(function (item) {
return parseInt(item.competition_stage_id) === parseInt(data === null || data === void 0 ? void 0 : data.id);
})) === null || _ChartRules$rule_cont2 === void 0 ? void 0 : (_ChartRules$rule_cont3 = _ChartRules$rule_cont2[0]) === null || _ChartRules$rule_cont3 === void 0 ? void 0 : _ChartRules$rule_cont3['content']) || '');
} else {
var _ChartRules$rule_cont4, _ChartRules$rule_cont5, _ChartRules$rule_cont6;
getCharts(0);
setDefaultValue(((_ChartRules$rule_cont4 = ChartRules.rule_contents) === null || _ChartRules$rule_cont4 === void 0 ? void 0 : (_ChartRules$rule_cont5 = _ChartRules$rule_cont4.filter(function (item) {
return parseInt(item.competition_stage_id) === 0;
})) === null || _ChartRules$rule_cont5 === void 0 ? void 0 : (_ChartRules$rule_cont6 = _ChartRules$rule_cont5[0]) === null || _ChartRules$rule_cont6 === void 0 ? void 0 : _ChartRules$rule_cont6['content']) || '');
}
}
}, [ChartRules]);
function updateitem() {
return _updateitem.apply(this, arguments);
}
function _updateitem() {
_updateitem = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee() {
var id, _ChartRules$rule_cont10, _ChartRules$rule_cont11, _ChartRules$rule_cont12, res, _ChartRules$rule_cont13, _ChartRules$rule_cont14, _ChartRules$rule_cont15, _res;
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (defaultValue) {
_context.next = 3;
break;
}
es_message["b" /* default */].info('内容不能为空');
return _context.abrupt("return");
case 3:
setClickButton(false);
id = item === null || item === void 0 ? void 0 : item.id;
if (!id) {
_context.next = 12;
break;
}
_context.next = 8;
return Object(fetch["a" /* default */])("/api/competitions/".concat(identifier, "/update_md_content.json"), {
method: 'post',
body: {
competition_module_id: Selectkey,
content: defaultValue,
md_content_id: (_ChartRules$rule_cont10 = ChartRules.rule_contents) === null || _ChartRules$rule_cont10 === void 0 ? void 0 : (_ChartRules$rule_cont11 = _ChartRules$rule_cont10.filter(function (item) {
return parseInt(item.competition_stage_id) === parseInt(id);
})) === null || _ChartRules$rule_cont11 === void 0 ? void 0 : (_ChartRules$rule_cont12 = _ChartRules$rule_cont11[0]) === null || _ChartRules$rule_cont12 === void 0 ? void 0 : _ChartRules$rule_cont12['id'],
stage_id: item === null || item === void 0 ? void 0 : item.id
}
});
case 8:
res = _context.sent;
if (res.status === 0) {
es_message["b" /* default */].info('更新成功');
setIsupdate(false);
getChartRules();
}
_context.next = 16;
break;
case 12:
_context.next = 14;
return Object(fetch["a" /* default */])("/api/competitions/".concat(identifier, "/update_md_content.json"), {
method: 'post',
body: {
competition_module_id: Selectkey,
content: defaultValue,
md_content_id: (_ChartRules$rule_cont13 = ChartRules.rule_contents) === null || _ChartRules$rule_cont13 === void 0 ? void 0 : (_ChartRules$rule_cont14 = _ChartRules$rule_cont13.filter(function (item) {
return parseInt(item.competition_stage_id) === 0;
})) === null || _ChartRules$rule_cont14 === void 0 ? void 0 : (_ChartRules$rule_cont15 = _ChartRules$rule_cont14[0]) === null || _ChartRules$rule_cont15 === void 0 ? void 0 : _ChartRules$rule_cont15['id'],
stage_id: item === null || item === void 0 ? void 0 : item.id
}
});
case 14:
_res = _context.sent;
if (_res.status === 0) {
es_message["b" /* default */].info('更新成功');
setIsupdate(false);
getChartRules();
}
case 16:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return _updateitem.apply(this, arguments);
}
var columns = [{
title: 'request_id',
dataIndex: 'request_id',
width: 120,
align: 'center',
key: 'name',
render: function render(a, b, c) {
return /*#__PURE__*/react_default.a.createElement("span", null, a);
}
}, {
title: '附件',
dataIndex: 'file_name',
align: 'center',
width: 150,
key: 'file_name',
render: function render(text) {
return /*#__PURE__*/react_default.a.createElement(tooltip["a" /* default */], {
title: text
}, /*#__PURE__*/react_default.a.createElement("span", {
title: text
}, text && (text === null || text === void 0 ? void 0 : text.length) >= 10 ? (text === null || text === void 0 ? void 0 : text.substr(0, 10)) + '...' : text || '--'));
}
}, {
title: '提交人',
dataIndex: 'user_name',
key: 'user_name',
width: 100,
render: function render(text) {
return /*#__PURE__*/react_default.a.createElement("span", {
title: text
}, text && (text === null || text === void 0 ? void 0 : text.length) >= 6 ? (text === null || text === void 0 ? void 0 : text.substr(0, 6)) + '...' : text || '--');
} // align:'center',
}, {
title: '提交时间',
dataIndex: 'created_at',
key: 'created_at',
align: 'center'
}, {
title: '状态',
dataIndex: 'status',
key: 'status',
width: 50,
render: function render(text) {
return /*#__PURE__*/react_default.a.createElement("span", null, text === 1 ? '计算中' : text === 2 ? '完成' : text === 0 ? '待计算' : text === 3 && '错误');
}
}, !(item === null || item === void 0 ? void 0 : item.display_four_indicators) && (item === null || item === void 0 ? void 0 : item.name) === '计图挑战热身赛' && {
title: '数据指标1',
dataIndex: 'data_ranking',
key: 'data_ranking',
align: 'center',
render: function render(text) {
return /*#__PURE__*/react_default.a.createElement("span", null, text || '--');
}
}, !(item === null || item === void 0 ? void 0 : item.display_four_indicators) && (item === null || item === void 0 ? void 0 : item.name) === '计图挑战热身赛' && {
title: '数据指标2',
dataIndex: 'data_other',
key: 'data_other',
align: 'left',
render: function render(text) {
if ((text === null || text === void 0 ? void 0 : text.length) > 0) {
return text === null || text === void 0 ? void 0 : text.map(function (item, index) {
return /*#__PURE__*/react_default.a.createElement("span", null, item === null || item === void 0 ? void 0 : item.name, "\uFF1A", item === null || item === void 0 ? void 0 : item.value, " ", /*#__PURE__*/react_default.a.createElement("br", null));
});
} else {
return /*#__PURE__*/react_default.a.createElement("span", null, "--");
}
}
}, (item === null || item === void 0 ? void 0 : item.display_four_indicators) && {
title: 'mask accuary',
dataIndex: 'data_ranking',
key: 'data_ranking',
align: 'left',
render: function render(text) {
return /*#__PURE__*/react_default.a.createElement("span", null, text || '--');
}
}, (item === null || item === void 0 ? void 0 : item.display_one_indicators) && {
title: 'mIoU',
dataIndex: 'data_other',
key: 'data_ranking',
align: 'left',
render: function render(text) {
var _text$find;
return /*#__PURE__*/react_default.a.createElement("span", null, (text === null || text === void 0 ? void 0 : (_text$find = text.find(function (item) {
return (item === null || item === void 0 ? void 0 : item.name) === 'mIoU';
})) === null || _text$find === void 0 ? void 0 : _text$find.value) || '--');
}
}, (item === null || item === void 0 ? void 0 : item.display_four_indicators) && {
title: '美学评分',
dataIndex: 'data_other',
key: 'data_other',
align: 'left',
render: function render(text) {
var _text$find2;
return /*#__PURE__*/react_default.a.createElement("span", null, (text === null || text === void 0 ? void 0 : (_text$find2 = text.find(function (item) {
return (item === null || item === void 0 ? void 0 : item.name) === 'score';
})) === null || _text$find2 === void 0 ? void 0 : _text$find2.value) || '--');
}
}, (item === null || item === void 0 ? void 0 : item.display_four_indicators) && {
title: 'FID',
dataIndex: 'data_other',
key: 'data_other',
align: 'left',
render: function render(text) {
var _text$find3;
return /*#__PURE__*/react_default.a.createElement("span", null, (text === null || text === void 0 ? void 0 : (_text$find3 = text.find(function (item) {
return (item === null || item === void 0 ? void 0 : item.name) === 'fid';
})) === null || _text$find3 === void 0 ? void 0 : _text$find3.value) || '--');
}
}, (item === null || item === void 0 ? void 0 : item.display_four_indicators) && {
title: '风格相似度',
dataIndex: 'data_other',
key: 'data_other',
align: 'left',
render: function render(text) {
var _text$find4;
return /*#__PURE__*/react_default.a.createElement("span", null, (text === null || text === void 0 ? void 0 : (_text$find4 = text.find(function (item) {
return (item === null || item === void 0 ? void 0 : item.name) === 'style_similarity';
})) === null || _text$find4 === void 0 ? void 0 : _text$find4.value) || '--');
}
}, (item === null || item === void 0 ? void 0 : item.display_four_indicators) && {
title: '总分',
dataIndex: 'data_other',
key: 'data_other',
align: 'left',
render: function render(text) {
var _text$find5;
return /*#__PURE__*/react_default.a.createElement("span", null, (text === null || text === void 0 ? void 0 : (_text$find5 = text.find(function (item) {
return (item === null || item === void 0 ? void 0 : item.name) === 'total_score';
})) === null || _text$find5 === void 0 ? void 0 : _text$find5.value) || '--');
}
}, !(item === null || item === void 0 ? void 0 : item.display_four_indicators) && (item === null || item === void 0 ? void 0 : item.name.includes('可微渲染新视角生成赛题')) && {
title: 'Car',
dataIndex: 'data_ranking',
key: 'data_ranking',
align: 'center',
render: function render(text) {
return /*#__PURE__*/react_default.a.createElement("span", null, text || '--');
}
}, !(item === null || item === void 0 ? void 0 : item.display_four_indicators) && (item === null || item === void 0 ? void 0 : item.name.includes('可微渲染新视角生成赛题')) && {
title: 'Coffee',
dataIndex: 'data_other',
key: 'data_other',
align: 'center',
render: function render(text) {
var _text$find6;
return /*#__PURE__*/react_default.a.createElement("span", null, (text === null || text === void 0 ? void 0 : (_text$find6 = text.find(function (item) {
return (item === null || item === void 0 ? void 0 : item.name) === 'Coffee';
})) === null || _text$find6 === void 0 ? void 0 : _text$find6.value) || '--');
}
}, !(item === null || item === void 0 ? void 0 : item.display_four_indicators) && (item === null || item === void 0 ? void 0 : item.name.includes('可微渲染新视角生成赛题')) && {
title: 'Easyship',
dataIndex: 'data_other',
key: 'data_other',
align: 'center',
render: function render(text) {
var _text$find7;
return /*#__PURE__*/react_default.a.createElement("span", null, (text === null || text === void 0 ? void 0 : (_text$find7 = text.find(function (item) {
return (item === null || item === void 0 ? void 0 : item.name) === 'Easyship';
})) === null || _text$find7 === void 0 ? void 0 : _text$find7.value) || '--');
}
}, !(item === null || item === void 0 ? void 0 : item.display_four_indicators) && (item === null || item === void 0 ? void 0 : item.name.includes('可微渲染新视角生成赛题')) && {
title: 'Scar',
dataIndex: 'data_other',
key: 'data_other',
align: 'center',
render: function render(text) {
var _text$find8;
return /*#__PURE__*/react_default.a.createElement("span", null, (text === null || text === void 0 ? void 0 : (_text$find8 = text.find(function (item) {
return (item === null || item === void 0 ? void 0 : item.name) === 'Scar';
})) === null || _text$find8 === void 0 ? void 0 : _text$find8.value) || '--');
}
}, !(item === null || item === void 0 ? void 0 : item.display_four_indicators) && (item === null || item === void 0 ? void 0 : item.name.includes('可微渲染新视角生成赛题')) && {
title: 'Scarf',
dataIndex: 'data_other',
key: 'data_other',
align: 'center',
render: function render(text) {
var _text$find9;
return /*#__PURE__*/react_default.a.createElement("span", null, (text === null || text === void 0 ? void 0 : (_text$find9 = text.find(function (item) {
return (item === null || item === void 0 ? void 0 : item.name) === 'Scarf';
})) === null || _text$find9 === void 0 ? void 0 : _text$find9.value) || '--');
}
}, !(item === null || item === void 0 ? void 0 : item.display_four_indicators) && (item === null || item === void 0 ? void 0 : item.name.includes('可微渲染新视角生成赛题')) && {
title: '总分',
dataIndex: 'data_other',
key: 'data_other',
align: 'center',
render: function render(text) {
var _text$find10;
return /*#__PURE__*/react_default.a.createElement("span", null, (text === null || text === void 0 ? void 0 : (_text$find10 = text.find(function (item) {
return (item === null || item === void 0 ? void 0 : item.name) === 'Total';
})) === null || _text$find10 === void 0 ? void 0 : _text$find10.value) || '--');
}
}, {
title: '操作',
dataIndex: 'result_url',
width: 50,
key: 'result_url',
render: function render(text) {
return /*#__PURE__*/react_default.a.createElement("a", {
href: text,
target: "_blank",
download: "\u9644\u4EF6"
}, "\u4E0B\u8F7D");
}
}].filter(function (item) {
return !!item;
});
;
return /*#__PURE__*/react_default.a.createElement("div", null, (ChartRules === null || ChartRules === void 0 ? void 0 : (_ChartRules$stages3 = ChartRules.stages) === null || _ChartRules$stages3 === void 0 ? void 0 : _ChartRules$stages3.length) > 0 ? null : /*#__PURE__*/react_default.a.createElement(RankingNuLL, null), (ChartRules === null || ChartRules === void 0 ? void 0 : (_ChartRules$stages4 = ChartRules.stages) === null || _ChartRules$stages4 === void 0 ? void 0 : _ChartRules$stages4.length) > 0 && /*#__PURE__*/react_default.a.createElement(es_tabs["a" /* default */], {
animated: true,
tabBarExtraContent: (userinfo === null || userinfo === void 0 ? void 0 : userinfo.admin) || (userinfo === null || userinfo === void 0 ? void 0 : userinfo.business) || Editable ? /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
onClick: function onClick() {
setIsupdate(true);
}
}, "\u7F16\u8F91") : StaffDetail.enrolled && (item === null || item === void 0 ? void 0 : item.start_time) && (item === null || item === void 0 ? void 0 : item.end_time) && /*#__PURE__*/react_default.a.createElement("span", null, "\u63D0\u4EA4\u65F6\u95F4\uFF1A", moment_default()(item === null || item === void 0 ? void 0 : item.start_time).format("YYYY-MM-DD HH:mm:ss"), "\u81F3", moment_default()(item === null || item === void 0 ? void 0 : item.end_time).format("YYYY-MM-DD HH:mm:ss"), /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
style: {
marginLeft: '20px'
},
disabled: moment_default()(item === null || item === void 0 ? void 0 : item.start_time).unix() > moment_default()(moment_default()().format('YYYY-MM-DD HH:mm:s')).unix() || moment_default()(moment_default()().format('YYYY-MM-DD HH:mm:s')).unix() > moment_default()(item === null || item === void 0 ? void 0 : item.end_time).unix(),
onClick: function onClick() {
// <moment(item?.end_time).unix()
dispatch({
type: 'shixunsDetail/setActionTabs',
payload: {
key: 'md-tab',
params: {
value: (items === null || items === void 0 ? void 0 : items.id) || (item === null || item === void 0 ? void 0 : item.id),
id: HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.id
}
}
});
}
}, "\u63D0\u4EA4\u7ED3\u679C")),
onChange: function onChange(e) {
var _ChartRules$stages5, _data$children, _ChartRules$rule_cont7, _ChartRules$rule_cont8, _ChartRules$rule_cont9;
setIsupdate(false);
var data = ChartRules === null || ChartRules === void 0 ? void 0 : (_ChartRules$stages5 = ChartRules.stages) === null || _ChartRules$stages5 === void 0 ? void 0 : _ChartRules$stages5.filter(function (item) {
return parseInt(e) === parseInt(item === null || item === void 0 ? void 0 : item.id);
})[0];
var datas = data === null || data === void 0 ? void 0 : (_data$children = data.children) === null || _data$children === void 0 ? void 0 : _data$children[0];
setItems(datas);
setItem(data);
setDefaultValue(((_ChartRules$rule_cont7 = ChartRules.rule_contents) === null || _ChartRules$rule_cont7 === void 0 ? void 0 : (_ChartRules$rule_cont8 = _ChartRules$rule_cont7.filter(function (item) {
return parseInt(item.competition_stage_id) === parseInt(data === null || data === void 0 ? void 0 : data.id);
})) === null || _ChartRules$rule_cont8 === void 0 ? void 0 : (_ChartRules$rule_cont9 = _ChartRules$rule_cont8[0]) === null || _ChartRules$rule_cont9 === void 0 ? void 0 : _ChartRules$rule_cont9['content']) || '');
getCharts((datas === null || datas === void 0 ? void 0 : datas.id) || e);
}
}, ChartRules && ChartRules.stages.map(function (item, index) {
return /*#__PURE__*/react_default.a.createElement(SubmitResult_TabPane, {
tab: item.name,
key: item.id === null ? 0 : item.id
}, isUpdate === false && ChartRules && ChartRules.rule_contents.map(function (items, keys) {
if (item.id === items.competition_stage_id) {
return /*#__PURE__*/react_default.a.createElement(RenderHtml["a" /* default */], {
key: keys,
value: items.content === undefined || items.content === null ? "" : items.content
});
} else if (item.id === null && items.competition_stage_id === 0) {
return /*#__PURE__*/react_default.a.createElement(RenderHtml["a" /* default */], {
key: keys,
value: items.content === undefined || items.content === null ? "" : items.content
});
}
}));
})), (item === null || item === void 0 ? void 0 : (_item$children = item.children) === null || _item$children === void 0 ? void 0 : _item$children.length) > 0 && /*#__PURE__*/react_default.a.createElement(es_tabs["a" /* default */], {
activeKey: (items === null || items === void 0 ? void 0 : items.id) + '',
onChange: function onChange(e) {
var _item$children2;
var data = item === null || item === void 0 ? void 0 : (_item$children2 = item.children) === null || _item$children2 === void 0 ? void 0 : _item$children2.filter(function (item) {
return parseInt(e) === parseInt(item === null || item === void 0 ? void 0 : item.id);
})[0];
setItems(data);
getCharts(e); //获取参数
}
}, item === null || item === void 0 ? void 0 : (_item$children3 = item.children) === null || _item$children3 === void 0 ? void 0 : _item$children3.map(function (item, index) {
return /*#__PURE__*/react_default.a.createElement(SubmitResult_TabPane, {
tab: item.name,
key: item.id === null ? 0 : item.id
});
})), isUpdate && /*#__PURE__*/react_default.a.createElement("div", null, /*#__PURE__*/react_default.a.createElement(components_markdown_editor, {
defaultValue: defaultValue,
onChange: function onChange(e) {
setDefaultValue(e);
}
}), /*#__PURE__*/react_default.a.createElement("p", {
style: {
marginTop: '10px'
}
}, /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
style: {
width: '90px'
},
type: "primary",
onClick: function onClick() {
return updateitem();
}
}, "\u63D0\u4EA4"), /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
style: {
marginLeft: '30px',
width: '90px'
},
onClick: function onClick() {
return setIsupdate(false);
}
}, "\u53D6\u6D88"))), ((_HeaderDetail$competi = HeaderDetail.competition_modules.filter(function (item) {
return item.id === Selectkey;
})) === null || _HeaderDetail$competi === void 0 ? void 0 : (_HeaderDetail$competi2 = _HeaderDetail$competi[0]) === null || _HeaderDetail$competi2 === void 0 ? void 0 : _HeaderDetail$competi2.show_leaderboard) && /*#__PURE__*/react_default.a.createElement(es_table["a" /* default */], {
dataSource: ItemData === null || ItemData === void 0 ? void 0 : ItemData.results,
columns: columns
}));
}
/* harmony default export */ var SubmitResult = (SubmitResult_Ranking);
// EXTERNAL MODULE: ./node_modules/antd/es/pagination/style/index.js
var pagination_style = __webpack_require__("DjyN");
// EXTERNAL MODULE: ./node_modules/antd/es/pagination/index.js + 7 modules
var pagination = __webpack_require__("NUBc");
// CONCATENATED MODULE: ./src/pages/Competitions/Detail/MakeItem.tsx
var MakeItem_TabPane = es_tabs["a" /* default */].TabPane;
function MakeItem_Ranking(_ref) {
var _ChartRules$stages2, _ChartRules$stages5, _ChartRules$stages6, _item$children, _item$children3, _ItemData$results;
var loading = _ref.loading,
ChartRules = _ref.ChartRules,
ItemData = _ref.ItemData,
getCharts = _ref.getCharts,
Selectkey = _ref.Selectkey,
HeaderDetail = _ref.HeaderDetail,
getChartRules = _ref.getChartRules,
userinfo = _ref.userinfo,
Editable = _ref.Editable,
dispatch = _ref.dispatch,
StaffDetail = _ref.StaffDetail;
var _useState = Object(react["useState"])(false),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
isUpdate = _useState2[0],
setIsupdate = _useState2[1];
var _useState3 = Object(react["useState"])(''),
_useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
defaultValue = _useState4[0],
setDefaultValue = _useState4[1];
var _useState5 = Object(react["useState"])(true),
_useState6 = Object(slicedToArray["a" /* default */])(_useState5, 2),
ClickButton = _useState6[0],
setClickButton = _useState6[1];
var _useState7 = Object(react["useState"])(),
_useState8 = Object(slicedToArray["a" /* default */])(_useState7, 2),
item = _useState8[0],
setItem = _useState8[1];
var _useState9 = Object(react["useState"])(),
_useState10 = Object(slicedToArray["a" /* default */])(_useState9, 2),
items = _useState10[0],
setItems = _useState10[1];
var _useParams = Object(react_router["l" /* useParams */])(),
identifier = _useParams.identifier;
var _useState11 = Object(react["useState"])({
page: 1,
limit: 10,
sort: 'desc'
}),
_useState12 = Object(slicedToArray["a" /* default */])(_useState11, 2),
params = _useState12[0],
setparams = _useState12[1];
Object(react["useEffect"])(function () {
var _ChartRules$stages;
//进入初始化状态为第一个
if (ClickButton && (ChartRules === null || ChartRules === void 0 ? void 0 : (_ChartRules$stages = ChartRules.stages) === null || _ChartRules$stages === void 0 ? void 0 : _ChartRules$stages[0])) {
getDate();
}
}, [ChartRules === null || ChartRules === void 0 ? void 0 : (_ChartRules$stages2 = ChartRules.stages) === null || _ChartRules$stages2 === void 0 ? void 0 : _ChartRules$stages2[0]]);
var getDate = /*#__PURE__*/function () {
var _ref2 = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee() {
var _ChartRules$stages3, _ChartRules$stages4, _ChartRules$stages4$, _ChartRules$stages4$$;
var data, datas;
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
data = ChartRules === null || ChartRules === void 0 ? void 0 : (_ChartRules$stages3 = ChartRules.stages) === null || _ChartRules$stages3 === void 0 ? void 0 : _ChartRules$stages3[0];
setItem(data);
datas = ChartRules === null || ChartRules === void 0 ? void 0 : (_ChartRules$stages4 = ChartRules.stages) === null || _ChartRules$stages4 === void 0 ? void 0 : (_ChartRules$stages4$ = _ChartRules$stages4[0]) === null || _ChartRules$stages4$ === void 0 ? void 0 : (_ChartRules$stages4$$ = _ChartRules$stages4$.children) === null || _ChartRules$stages4$$ === void 0 ? void 0 : _ChartRules$stages4$$[0];
setItems(datas);
params.id = (datas === null || datas === void 0 ? void 0 : datas.id) || (data === null || data === void 0 ? void 0 : data.id), setparams(Object(objectSpread2["a" /* default */])({}, params));
_context.next = 7;
return getCharts(Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, params), {}, {
stage_id: params.id
}));
case 7:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function getDate() {
return _ref2.apply(this, arguments);
};
}();
return /*#__PURE__*/react_default.a.createElement("div", null, (ChartRules === null || ChartRules === void 0 ? void 0 : (_ChartRules$stages5 = ChartRules.stages) === null || _ChartRules$stages5 === void 0 ? void 0 : _ChartRules$stages5.length) > 0 ? null : /*#__PURE__*/react_default.a.createElement(RankingNuLL, null), (ChartRules === null || ChartRules === void 0 ? void 0 : (_ChartRules$stages6 = ChartRules.stages) === null || _ChartRules$stages6 === void 0 ? void 0 : _ChartRules$stages6.length) > 0 && /*#__PURE__*/react_default.a.createElement(es_tabs["a" /* default */], {
tabBarStyle: {
height: 65,
marginLeft: 35,
marginRight: 30
},
animated: true,
onChange: /*#__PURE__*/function () {
var _ref3 = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee2(e) {
var _ChartRules$stages7, _data$children, _ChartRules$rule_cont, _ChartRules$rule_cont2, _ChartRules$rule_cont3;
var data, datas;
return regenerator_default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
setIsupdate(false);
data = ChartRules === null || ChartRules === void 0 ? void 0 : (_ChartRules$stages7 = ChartRules.stages) === null || _ChartRules$stages7 === void 0 ? void 0 : _ChartRules$stages7.filter(function (item) {
return parseInt(e) === parseInt(item === null || item === void 0 ? void 0 : item.id);
})[0];
datas = data === null || data === void 0 ? void 0 : (_data$children = data.children) === null || _data$children === void 0 ? void 0 : _data$children[0];
setItems(datas);
setItem(data);
setDefaultValue(((_ChartRules$rule_cont = ChartRules.rule_contents) === null || _ChartRules$rule_cont === void 0 ? void 0 : (_ChartRules$rule_cont2 = _ChartRules$rule_cont.filter(function (item) {
return parseInt(item.competition_stage_id) === parseInt(data === null || data === void 0 ? void 0 : data.id);
})) === null || _ChartRules$rule_cont2 === void 0 ? void 0 : (_ChartRules$rule_cont3 = _ChartRules$rule_cont2[0]) === null || _ChartRules$rule_cont3 === void 0 ? void 0 : _ChartRules$rule_cont3['content']) || '');
params.page = 1, params.limit = 10, params.id = (datas === null || datas === void 0 ? void 0 : datas.id) || e, setparams(Object(objectSpread2["a" /* default */])({}, params));
_context2.next = 9;
return getCharts(Object(objectSpread2["a" /* default */])({}, params));
case 9:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
return function (_x) {
return _ref3.apply(this, arguments);
};
}()
}, ChartRules && ChartRules.stages.map(function (item, index) {
return /*#__PURE__*/react_default.a.createElement(MakeItem_TabPane, {
tab: item.name,
key: item.id === null ? 0 : item.id
});
})), (item === null || item === void 0 ? void 0 : (_item$children = item.children) === null || _item$children === void 0 ? void 0 : _item$children.length) > 0 && /*#__PURE__*/react_default.a.createElement(es_tabs["a" /* default */], {
activeKey: (items === null || items === void 0 ? void 0 : items.id) + '',
onChange: /*#__PURE__*/function () {
var _ref4 = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee3(e) {
var _item$children2;
var data;
return regenerator_default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
data = item === null || item === void 0 ? void 0 : (_item$children2 = item.children) === null || _item$children2 === void 0 ? void 0 : _item$children2.filter(function (item) {
return parseInt(e) === parseInt(item === null || item === void 0 ? void 0 : item.id);
})[0];
setItems(data);
params.page = 1, params.limit = 10, params.id = e, setparams(Object(objectSpread2["a" /* default */])({}, params));
_context3.next = 5;
return getCharts(Object(objectSpread2["a" /* default */])({}, params));
case 5:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
return function (_x2) {
return _ref4.apply(this, arguments);
};
}()
}, item === null || item === void 0 ? void 0 : (_item$children3 = item.children) === null || _item$children3 === void 0 ? void 0 : _item$children3.map(function (item, index) {
return /*#__PURE__*/react_default.a.createElement(MakeItem_TabPane, {
tab: item.name,
key: item.id === null ? 0 : item.id
});
})), /*#__PURE__*/react_default.a.createElement("div", {
style: {
height: 10,
background: '#F5F5F5'
}
}), /*#__PURE__*/react_default.a.createElement("div", {
style: {
padding: "20px 30px"
}
}, /*#__PURE__*/react_default.a.createElement("span", {
style: {
cursor: 'pointer',
marginRight: 20
},
onClick: function onClick() {
params.page = 1, params.sort = params.sort === 'desc' ? 'asc' : 'desc';
setparams(Object(objectSpread2["a" /* default */])({}, params));
getCharts(Object(objectSpread2["a" /* default */])({}, params));
}
}, "\u6309\u63D0\u4EA4\u65F6\u95F4", params.sort === 'asc' ? '正' : '倒', "\u5E8F\u6392\u5E8F ", /*#__PURE__*/react_default.a.createElement("i", {
className: "iconfont font14 ".concat(params.sort === 'asc' ? 'icon-jiantou9' : 'icon-changyongtubiao-xianxingdaochu-zhuanqu-')
})), " ", /*#__PURE__*/react_default.a.createElement(es_input["a" /* default */].Search, {
onSearch: function onSearch(e) {
params.page = 1, params.search = e, setparams(Object(objectSpread2["a" /* default */])({}, params));
getCharts(Object(objectSpread2["a" /* default */])({}, params));
},
style: {
width: '82%'
},
placeholder: "\u8F93\u5165\u4EBA\u5458/\u6218\u961F\u540D\u79F0\u8FDB\u884C\u641C\u7D22"
}), /*#__PURE__*/react_default.a.createElement(spin["a" /* default */], {
spinning: loading
}, ItemData === null || ItemData === void 0 ? void 0 : (_ItemData$results = ItemData.results) === null || _ItemData$results === void 0 ? void 0 : _ItemData$results.map(function (item, index) {
return /*#__PURE__*/react_default.a.createElement("div", {
style: {
border: '1px solid #E3EFFC',
height: 100,
borderRadius: '2px 2px 0px 0px',
marginTop: index === 0 ? 14 : 30
}
}, /*#__PURE__*/react_default.a.createElement("div", {
style: {
height: 60,
padding: 10,
display: 'flex',
alignItems: 'center'
}
}, /*#__PURE__*/react_default.a.createElement("img", {
src: env["a" /* default */].IMG_SERVER + '/images/' + (item === null || item === void 0 ? void 0 : item.image_url),
style: {
width: 40,
height: 40,
borderRadius: '50%'
}
}), /*#__PURE__*/react_default.a.createElement("div", {
style: {
marginLeft: 10
}
}, /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#333333',
fontWeight: 500,
fontSize: '16px'
}
}, item === null || item === void 0 ? void 0 : item.user_name), /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#999999',
fontWeight: 400,
fontSize: '14px',
marginLeft: 60
}
}, "\u6240\u5C5E\u6218\u961F", /*#__PURE__*/react_default.a.createElement("span", {
style: {
marginLeft: 10,
color: '#333'
}
}, (item === null || item === void 0 ? void 0 : item.team_name) || '- -')), /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#333333',
fontWeight: 400,
fontSize: '14px',
marginLeft: 40
}
}, "\u5B66\u6821 ", /*#__PURE__*/react_default.a.createElement("span", {
style: {
marginLeft: 10,
color: '#333'
}
}, (item === null || item === void 0 ? void 0 : item.school_name) || '- -')))), /*#__PURE__*/react_default.a.createElement("div", {
style: {
background: '#EEF2F8',
height: 40,
borderRadius: '0px 0px 2px 2px',
paddingLeft: 60,
paddingRight: 40,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between'
}
}, /*#__PURE__*/react_default.a.createElement("div", null, /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#666666',
fontSize: '12px'
}
}, "\u63D0\u4EA4\u65F6\u95F4\uFF1A", item === null || item === void 0 ? void 0 : item.created_at), /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#666666',
fontSize: '12px',
margin: '0px 40px'
}
}, "\u6D88\u8017\u5185\u5B58\uFF1A", (item === null || item === void 0 ? void 0 : item.ts_mem) || '- -', "MB"), /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#666666',
fontSize: '12px'
}
}, "\u4EE3\u7801\u6267\u884C\u65F6\u95F4\uFF1A", (item === null || item === void 0 ? void 0 : item.ts_time) || '- -', "\u79D2")), /*#__PURE__*/react_default.a.createElement("a", {
style: {
display: 'flex',
alignItems: 'center'
},
href: "/tasks/".concat(item === null || item === void 0 ? void 0 : item.game_identifier),
target: "_blank"
}, /*#__PURE__*/react_default.a.createElement("i", {
className: "iconfont icon-chakandaima",
style: {
marginRight: 4
}
}), /*#__PURE__*/react_default.a.createElement("span", {
style: {
lineHeight: '14px'
}
}, "\u67E5\u770B\u4EE3\u7801"))));
})), /*#__PURE__*/react_default.a.createElement(pagination["a" /* default */], {
total: ItemData === null || ItemData === void 0 ? void 0 : ItemData.total_count,
pageSize: 10,
hideOnSinglePage: true,
style: {
marginTop: 40,
textAlign: 'center'
},
showSizeChanger: false,
current: params.page,
onChange: function onChange(page, pageSize) {
params.page = page, setparams(Object(objectSpread2["a" /* default */])({}, params));
getCharts(Object(objectSpread2["a" /* default */])({}, params));
}
})));
}
/* harmony default export */ var MakeItem = (MakeItem_Ranking);
// CONCATENATED MODULE: ./src/pages/Competitions/Detail/Challitems.tsx
//1 2 3 排名数据样式
var toChinesNum = function toChinesNum(num) {
var changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']; //changeNum[0] = "零"
var unit = ["", "十", "百", "千", "万"];
num = parseInt(num);
var getWan = function getWan(temp) {
var strArr = temp.toString().split("").reverse();
var newNum = "";
for (var i = 0; i < strArr.length; i++) {
newNum = (i == 0 && strArr[i] == 0 ? "" : i > 0 && strArr[i] == 0 && strArr[i - 1] == 0 ? "" : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i])) + newNum;
}
return newNum;
};
var overWan = Math.floor(num / 10000);
var noWan = num % 10000;
if (noWan.toString().length < 4) noWan = "0" + noWan;
return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);
};
function Challitems_RankingItem(_ref) {
var _item$challenges;
var item = _ref.item,
index = _ref.index,
StaffDetail = _ref.StaffDetail;
var _useState = Object(react["useState"])(true),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
content = _useState2[0],
setcontent = _useState2[1];
var _useState3 = Object(react["useState"])(true),
_useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
isopen = _useState4[0],
setisonen = _useState4[1];
var divcontent = Object(react["useRef"])();
return /*#__PURE__*/react_default.a.createElement("div", {
style: {
border: '1px solid #E3EFFC',
borderRadius: '2px',
marginTop: 20
}
}, /*#__PURE__*/react_default.a.createElement("div", {
style: {
padding: 10,
display: 'flex',
position: 'relative'
}
}, /*#__PURE__*/react_default.a.createElement("img", {
src: env["a" /* default */].IMG_SERVER + '/' + (item === null || item === void 0 ? void 0 : item.pic),
style: {
width: 220,
height: 130,
borderRadius: '4px'
}
}), /*#__PURE__*/react_default.a.createElement("div", {
style: {
marginLeft: 20,
width: '75%'
}
}, /*#__PURE__*/react_default.a.createElement("div", {
style: {
display: 'flex',
justifyContent: 'space-between'
}
}, /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#333333',
fontWeight: 500,
fontSize: '16px'
}
}, "\u4EFB\u52A1", toChinesNum(index + 1), "\uFF1A", /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#333',
fontWeight: '400'
}
}, item === null || item === void 0 ? void 0 : item.name)), /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#9096A3'
}
}, "\u5173\u5361", /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#333333',
marginLeft: 5
}
}, item === null || item === void 0 ? void 0 : item.challenges_count), " ")), /*#__PURE__*/react_default.a.createElement("div", {
ref: divcontent
}, /*#__PURE__*/react_default.a.createElement(RenderHtml["a" /* default */], {
style: {
maxHeight: content && 100
},
value: item === null || item === void 0 ? void 0 : item.description
})), /*#__PURE__*/react_default.a.createElement("div", {
style: {
textAlign: 'center',
color: '#145DFF',
cursor: 'pointer'
},
onClick: function onClick() {
setcontent(!content);
}
}, content ? '阅读全文 ' : '收起全文 ', /*#__PURE__*/react_default.a.createElement("i", {
className: "iconfont font14 ".concat(content ? 'icon-jiantou9' : 'icon-changyongtubiao-xianxingdaochu-zhuanqu-')
})), /*#__PURE__*/react_default.a.createElement("div", {
style: {
marginTop: 14,
maxHeight: isopen && 58,
overflow: 'hidden'
}
}, item === null || item === void 0 ? void 0 : (_item$challenges = item.challenges) === null || _item$challenges === void 0 ? void 0 : _item$challenges.map(function (items, j) {
return /*#__PURE__*/react_default.a.createElement("div", {
style: {
marginTop: j === 0 ? 0 : 12
}
}, /*#__PURE__*/react_default.a.createElement("i", {
className: "iconfont icon-shixunti2 c-light-primary font20"
}), /*#__PURE__*/react_default.a.createElement("span", {
style: {
marginLeft: 10
}
}, "\u7B2C", j + 1, "\u5173", items === null || items === void 0 ? void 0 : items.name));
})), /*#__PURE__*/react_default.a.createElement("div", {
style: {
position: 'absolute',
bottom: 14,
right: 10,
color: '#145DFF',
cursor: 'pointer'
}
}, /*#__PURE__*/react_default.a.createElement("span", {
onClick: function onClick() {
setisonen(!isopen);
}
}, isopen ? '展开' : '收起', " ", /*#__PURE__*/react_default.a.createElement("i", {
className: "iconfont font14 ".concat(isopen ? 'icon-jiantou9' : 'icon-changyongtubiao-xianxingdaochu-zhuanqu-')
})), " ", (StaffDetail === null || StaffDetail === void 0 ? void 0 : StaffDetail.enrolled) && /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
onClick: function onClick() {
window.open("/shixuns/".concat(item === null || item === void 0 ? void 0 : item.identifier, "/challenges"));
},
style: {
marginLeft: 30
},
type: "primary"
}, "\u5F00\u542F\u6311\u6218")))));
}
/* harmony default export */ var Challitems = (Challitems_RankingItem);
// CONCATENATED MODULE: ./src/pages/Competitions/Detail/Entrance.tsx
var Entrance_TabPane = es_tabs["a" /* default */].TabPane;
function Entrance_Ranking(_ref) {
var _ChartRules$stages2, _ChartRules$stages5, _ChartRules$stages6, _item$children, _item$children3, _ItemData$results;
var loading = _ref.loading,
ChartRules = _ref.ChartRules,
ItemData = _ref.ItemData,
getCharts = _ref.getCharts,
Selectkey = _ref.Selectkey,
HeaderDetail = _ref.HeaderDetail,
getChartRules = _ref.getChartRules,
userinfo = _ref.userinfo,
Editable = _ref.Editable,
dispatch = _ref.dispatch,
StaffDetail = _ref.StaffDetail;
var _useState = Object(react["useState"])(false),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
isUpdate = _useState2[0],
setIsupdate = _useState2[1];
var _useState3 = Object(react["useState"])(''),
_useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
defaultValue = _useState4[0],
setDefaultValue = _useState4[1];
var _useState5 = Object(react["useState"])(true),
_useState6 = Object(slicedToArray["a" /* default */])(_useState5, 2),
ClickButton = _useState6[0],
setClickButton = _useState6[1];
var _useState7 = Object(react["useState"])(),
_useState8 = Object(slicedToArray["a" /* default */])(_useState7, 2),
item = _useState8[0],
setItem = _useState8[1];
var _useState9 = Object(react["useState"])(),
_useState10 = Object(slicedToArray["a" /* default */])(_useState9, 2),
items = _useState10[0],
setItems = _useState10[1];
var _useParams = Object(react_router["l" /* useParams */])(),
identifier = _useParams.identifier;
var _useState11 = Object(react["useState"])({
page: 1,
limit: 10
}),
_useState12 = Object(slicedToArray["a" /* default */])(_useState11, 2),
params = _useState12[0],
setparams = _useState12[1];
var _useState13 = Object(react["useState"])(),
_useState14 = Object(slicedToArray["a" /* default */])(_useState13, 2),
openitem = _useState14[0],
setopenitem = _useState14[1];
Object(react["useEffect"])(function () {
var _ChartRules$stages;
//进入初始化状态为第一个
if (ClickButton && (ChartRules === null || ChartRules === void 0 ? void 0 : (_ChartRules$stages = ChartRules.stages) === null || _ChartRules$stages === void 0 ? void 0 : _ChartRules$stages[0])) {
getDate();
}
}, [ChartRules === null || ChartRules === void 0 ? void 0 : (_ChartRules$stages2 = ChartRules.stages) === null || _ChartRules$stages2 === void 0 ? void 0 : _ChartRules$stages2[0]]);
var getDate = /*#__PURE__*/function () {
var _ref2 = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee() {
var _ChartRules$stages3, _ChartRules$stages4, _ChartRules$stages4$, _ChartRules$stages4$$;
var data, datas;
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
data = ChartRules === null || ChartRules === void 0 ? void 0 : (_ChartRules$stages3 = ChartRules.stages) === null || _ChartRules$stages3 === void 0 ? void 0 : _ChartRules$stages3[0];
setItem(data);
datas = ChartRules === null || ChartRules === void 0 ? void 0 : (_ChartRules$stages4 = ChartRules.stages) === null || _ChartRules$stages4 === void 0 ? void 0 : (_ChartRules$stages4$ = _ChartRules$stages4[0]) === null || _ChartRules$stages4$ === void 0 ? void 0 : (_ChartRules$stages4$$ = _ChartRules$stages4$.children) === null || _ChartRules$stages4$$ === void 0 ? void 0 : _ChartRules$stages4$$[0];
setItems(datas);
params.id = (datas === null || datas === void 0 ? void 0 : datas.id) || (data === null || data === void 0 ? void 0 : data.id), setparams(Object(objectSpread2["a" /* default */])({}, params));
_context.next = 7;
return getCharts(Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, params), {}, {
stage_id: params.id
}));
case 7:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function getDate() {
return _ref2.apply(this, arguments);
};
}();
return /*#__PURE__*/react_default.a.createElement("div", null, (ChartRules === null || ChartRules === void 0 ? void 0 : (_ChartRules$stages5 = ChartRules.stages) === null || _ChartRules$stages5 === void 0 ? void 0 : _ChartRules$stages5.length) > 0 ? null : /*#__PURE__*/react_default.a.createElement(RankingNuLL, null), (ChartRules === null || ChartRules === void 0 ? void 0 : (_ChartRules$stages6 = ChartRules.stages) === null || _ChartRules$stages6 === void 0 ? void 0 : _ChartRules$stages6.length) > 0 && /*#__PURE__*/react_default.a.createElement(es_tabs["a" /* default */], {
tabBarStyle: {
height: 65,
marginLeft: 35,
marginRight: 30
},
animated: true,
onChange: /*#__PURE__*/function () {
var _ref3 = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee2(e) {
var _ChartRules$stages7, _data$children, _ChartRules$rule_cont, _ChartRules$rule_cont2, _ChartRules$rule_cont3;
var data, datas;
return regenerator_default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
setIsupdate(false);
data = ChartRules === null || ChartRules === void 0 ? void 0 : (_ChartRules$stages7 = ChartRules.stages) === null || _ChartRules$stages7 === void 0 ? void 0 : _ChartRules$stages7.filter(function (item) {
return parseInt(e) === parseInt(item === null || item === void 0 ? void 0 : item.id);
})[0];
datas = data === null || data === void 0 ? void 0 : (_data$children = data.children) === null || _data$children === void 0 ? void 0 : _data$children[0];
setItems(datas);
setItem(data);
setDefaultValue(((_ChartRules$rule_cont = ChartRules.rule_contents) === null || _ChartRules$rule_cont === void 0 ? void 0 : (_ChartRules$rule_cont2 = _ChartRules$rule_cont.filter(function (item) {
return parseInt(item.competition_stage_id) === parseInt(data === null || data === void 0 ? void 0 : data.id);
})) === null || _ChartRules$rule_cont2 === void 0 ? void 0 : (_ChartRules$rule_cont3 = _ChartRules$rule_cont2[0]) === null || _ChartRules$rule_cont3 === void 0 ? void 0 : _ChartRules$rule_cont3['content']) || '');
params.page = 1, params.limit = 10, params.id = (datas === null || datas === void 0 ? void 0 : datas.id) || e, setparams(Object(objectSpread2["a" /* default */])({}, params));
_context2.next = 9;
return getCharts(Object(objectSpread2["a" /* default */])({}, params));
case 9:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
return function (_x) {
return _ref3.apply(this, arguments);
};
}()
}, ChartRules && ChartRules.stages.map(function (item, index) {
return /*#__PURE__*/react_default.a.createElement(Entrance_TabPane, {
tab: item.name,
key: item.id === null ? 0 : item.id
});
})), (item === null || item === void 0 ? void 0 : (_item$children = item.children) === null || _item$children === void 0 ? void 0 : _item$children.length) > 0 && /*#__PURE__*/react_default.a.createElement(es_tabs["a" /* default */], {
activeKey: (items === null || items === void 0 ? void 0 : items.id) + '',
tabBarStyle: {
height: 65,
marginLeft: 35,
marginRight: 30
},
onChange: /*#__PURE__*/function () {
var _ref4 = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee3(e) {
var _item$children2;
var data;
return regenerator_default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
data = item === null || item === void 0 ? void 0 : (_item$children2 = item.children) === null || _item$children2 === void 0 ? void 0 : _item$children2.filter(function (item) {
return parseInt(e) === parseInt(item === null || item === void 0 ? void 0 : item.id);
})[0];
setItems(data);
params.page = 1, params.limit = 10, params.id = e, setparams(Object(objectSpread2["a" /* default */])({}, params));
_context3.next = 5;
return getCharts(Object(objectSpread2["a" /* default */])({}, params));
case 5:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
return function (_x2) {
return _ref4.apply(this, arguments);
};
}()
}, item === null || item === void 0 ? void 0 : (_item$children3 = item.children) === null || _item$children3 === void 0 ? void 0 : _item$children3.map(function (item, index) {
return /*#__PURE__*/react_default.a.createElement(Entrance_TabPane, {
tab: item.name,
key: item.id === null ? 0 : item.id
});
})), /*#__PURE__*/react_default.a.createElement("div", {
style: {
height: 10,
background: '#F5F5F5'
}
}), /*#__PURE__*/react_default.a.createElement("div", {
style: {
padding: "20px 30px"
}
}, /*#__PURE__*/react_default.a.createElement("div", {
style: {
display: 'flex',
justifyContent: 'space-between'
}
}, /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#9096A3'
}
}, "\u4F5C\u54C1\u63D0\u4EA4\u65F6\u95F4", /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#333333',
marginLeft: 5
}
}, ItemData === null || ItemData === void 0 ? void 0 : ItemData.start_time, "~", ItemData === null || ItemData === void 0 ? void 0 : ItemData.end_time)), /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#9096A3'
}
}, "\u6210\u7EE9\u6765\u6E90", /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#333333',
marginLeft: 5
}
}, (ItemData === null || ItemData === void 0 ? void 0 : ItemData.score_source) === 0 ? '经验值' : '预测准确率'), " ")), /*#__PURE__*/react_default.a.createElement(spin["a" /* default */], {
spinning: loading
}, ItemData === null || ItemData === void 0 ? void 0 : (_ItemData$results = ItemData.results) === null || _ItemData$results === void 0 ? void 0 : _ItemData$results.map(function (item, index) {
return /*#__PURE__*/react_default.a.createElement(Challitems, {
StaffDetail: StaffDetail,
item: item,
index: index
});
})), /*#__PURE__*/react_default.a.createElement(pagination["a" /* default */], {
total: ItemData === null || ItemData === void 0 ? void 0 : ItemData.total_count,
pageSize: 10,
hideOnSinglePage: true,
style: {
marginTop: 40,
textAlign: 'center'
},
showSizeChanger: false,
current: params.page,
onChange: function onChange(page, pageSize) {
params.page = page, setparams(Object(objectSpread2["a" /* default */])({}, params));
getCharts(Object(objectSpread2["a" /* default */])({}, params));
}
})));
}
/* harmony default export */ var Entrance = (Entrance_Ranking);
// EXTERNAL MODULE: ./src/pages/Competitions/Entered/Enteredmodel/JoinModel.tsx
var JoinModel = __webpack_require__("UfjD");
// EXTERNAL MODULE: ./src/pages/Competitions/Entered/Enteredmodel/Addteams.tsx
var Addteams = __webpack_require__("qHvr");
// EXTERNAL MODULE: ./src/pages/Competitions/Detail/components/InitGitLink/index.less?modules
var InitGitLinkmodules = __webpack_require__("IpFe");
var InitGitLinkmodules_default = /*#__PURE__*/__webpack_require__.n(InitGitLinkmodules);
// EXTERNAL MODULE: ./src/components/Header/index.tsx + 8 modules
var Header = __webpack_require__("ruvs");
// CONCATENATED MODULE: ./src/pages/Competitions/Detail/components/InitGitLink/index.tsx
var InitGitLink_InitGitlink = function InitGitlink(_ref) {
var _user$userInfo8;
var visible = _ref.visible,
user = _ref.user,
_ref$onClose = _ref.onClose,
onClose = _ref$onClose === void 0 ? function () {} : _ref$onClose,
dispatch = _ref.dispatch;
var _Form$useForm = es_form["a" /* default */].useForm(),
_Form$useForm2 = Object(slicedToArray["a" /* default */])(_Form$useForm, 1),
form = _Form$useForm2[0];
var _useState = Object(react["useState"])(false),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
emailforName = _useState2[0],
setEmailforName = _useState2[1];
var _useState3 = Object(react["useState"])(false),
_useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
loading = _useState4[0],
setLoading = _useState4[1];
Object(react["useEffect"])(function () {
var _user$userInfo, _user$userInfo2, _user$userInfo3;
if (!(user === null || user === void 0 ? void 0 : (_user$userInfo = user.userInfo) === null || _user$userInfo === void 0 ? void 0 : _user$userInfo.email) || (user === null || user === void 0 ? void 0 : (_user$userInfo2 = user.userInfo) === null || _user$userInfo2 === void 0 ? void 0 : _user$userInfo2.email) && (user === null || user === void 0 ? void 0 : (_user$userInfo3 = user.userInfo) === null || _user$userInfo3 === void 0 ? void 0 : _user$userInfo3.email.indexOf("gitlink.org.cn")) > -1) {
form.setFieldsValue({
email: ""
});
} else {
var _user$userInfo4, _user$userInfo5;
form.setFieldsValue({
email: user === null || user === void 0 ? void 0 : (_user$userInfo4 = user.userInfo) === null || _user$userInfo4 === void 0 ? void 0 : _user$userInfo4.email,
username: user === null || user === void 0 ? void 0 : (_user$userInfo5 = user.userInfo) === null || _user$userInfo5 === void 0 ? void 0 : _user$userInfo5.login
});
}
}, [user === null || user === void 0 ? void 0 : user.userInfo]);
var handleFinish = /*#__PURE__*/function () {
var _ref2 = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee(values) {
var _user$userInfo6, res, _user$userInfo7, _res, payload, _res2;
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
setLoading(true);
if (!emailforName) {
_context.next = 9;
break;
}
_context.next = 4;
return dispatch({
type: "user/ForgeLogin",
payload: {
login: (values === null || values === void 0 ? void 0 : values.email) || (user === null || user === void 0 ? void 0 : (_user$userInfo6 = user.userInfo) === null || _user$userInfo6 === void 0 ? void 0 : _user$userInfo6.email),
password: values === null || values === void 0 ? void 0 : values.password
}
});
case 4:
res = _context.sent;
if (res.status === 0) {
onClose();
}
setLoading(false);
_context.next = 13;
break;
case 9:
_context.next = 11;
return dispatch({
type: "user/ForgeSaveUserInfo",
payload: Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, values), {}, {
email: (values === null || values === void 0 ? void 0 : values.email) || (user === null || user === void 0 ? void 0 : (_user$userInfo7 = user.userInfo) === null || _user$userInfo7 === void 0 ? void 0 : _user$userInfo7.email),
platform: "educoder"
})
});
case 11:
_res = _context.sent;
if (_res) {
setLoading(false);
onClose();
payload = Object(Header["b" /* getCourseParam */])();
_res2 = dispatch({
type: 'user/getUserInfo',
payload: Object(objectSpread2["a" /* default */])({}, payload)
});
if (_res2) {
dispatch({
type: 'globalSetting/query',
payload: {}
});
}
}
case 13:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function handleFinish(_x) {
return _ref2.apply(this, arguments);
};
}(); //判断用户名username是否注册
var usernameConfirm = /*#__PURE__*/function () {
var _ref3 = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee2() {
var value, res;
return regenerator_default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
value = form.getFieldValue("username");
if (!(value && !emailforName)) {
_context2.next = 6;
break;
}
_context2.next = 4;
return dispatch({
type: "user/ForgeCheckName",
payload: {
value: value,
type: 1
}
});
case 4:
res = _context2.sent;
if ((res === null || res === void 0 ? void 0 : res.status) < 0) {
form.setFields([{
name: 'username',
errors: [res === null || res === void 0 ? void 0 : res.message]
}]);
}
case 6:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
return function usernameConfirm() {
return _ref3.apply(this, arguments);
};
}(); //判断邮箱email是否注册
function useremailConfirm() {
return _useremailConfirm.apply(this, arguments);
}
function _useremailConfirm() {
_useremailConfirm = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee3() {
var value, result, _user$userInfo9;
return regenerator_default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
value = form.getFieldValue('email');
if (value) {
_context3.next = 3;
break;
}
return _context3.abrupt("return", Promise.resolve());
case 3:
_context3.next = 5;
return dispatch({
type: "user/ForgeCheckEmail",
payload: {
email: value
}
});
case 5:
result = _context3.sent;
if (!(result === null || result === void 0 ? void 0 : result.login)) {
_context3.next = 12;
break;
}
setEmailforName(value === (user === null || user === void 0 ? void 0 : (_user$userInfo9 = user.userInfo) === null || _user$userInfo9 === void 0 ? void 0 : _user$userInfo9.email) ? false : true);
form.setFieldsValue({
username: result === null || result === void 0 ? void 0 : result.login
});
return _context3.abrupt("return", Promise.resolve());
case 12:
setEmailforName(false);
form.setFieldsValue({
username: ""
});
return _context3.abrupt("return", Promise.resolve());
case 15:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
return _useremailConfirm.apply(this, arguments);
}
return /*#__PURE__*/react_default.a.createElement(es_modal["a" /* default */], {
centered: true,
keyboard: false,
closable: true,
destroyOnClose: true,
visible: visible,
title: "\u5B8C\u5584\u7528\u6237\u4FE1\u606F",
width: "600px",
onCancel: onClose,
footer: null
}, /*#__PURE__*/react_default.a.createElement(spin["a" /* default */], {
spinning: loading
}, /*#__PURE__*/react_default.a.createElement("p", {
className: InitGitLinkmodules_default.a.tips
}, "\u8BF7\u5B8C\u5584\u60A8\u5728GitLink\u5E73\u53F0\u4E0A\u7684\u8D26\u53F7\u4FE1\u606F\u4EE5\u4FBF\u540E\u7EED\u53C2\u8D5B\uFF1A\u5982\u679C\u60A8\u5DF2\u6709GitLink\u8D26\u53F7\uFF0C\u8BF7\u8F93\u5165\u5DF2\u6709\u8D26\u53F7\uFF1B\u5982\u679C\u6682\u65E0GitLink\u8D26\u53F7\uFF0C\u5E73\u53F0\u5C06\u6839\u636E\u60A8\u8F93\u5165\u7684\u4FE1\u606F\u81EA\u52A8\u4E3A\u60A8\u521B\u5EFA\u4E00\u4E2A\u8D26\u53F7\uFF0C\u8BF7\u8BB0\u4F4F\u60A8\u8F93\u5165\u7684\u7528\u6237\u540D\u548C\u5BC6\u7801\u7B49\u4FE1\u606F\u3002"), /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */], {
className: InitGitLinkmodules_default.a.formWrap,
form: form,
layout: "horizontal",
onFinish: handleFinish
}, /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
label: "\u59D3\u540D"
}, /*#__PURE__*/react_default.a.createElement("span", {
style: {
fontSize: "16px"
}
}, user === null || user === void 0 ? void 0 : (_user$userInfo8 = user.userInfo) === null || _user$userInfo8 === void 0 ? void 0 : _user$userInfo8.real_name)), /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
label: "\u90AE\u7BB1",
name: "email",
rules: [{
required: true,
message: '请输入邮箱'
}],
validateFirst: true,
validateTrigger: 'onChange'
}, /*#__PURE__*/react_default.a.createElement(es_input["a" /* default */], {
placeholder: "\u8BF7\u8F93\u5165\u90AE\u7BB1",
size: "large",
onBlur: useremailConfirm
})), /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
label: "\u7528\u6237\u540D",
name: "username",
rules: [{
required: true,
message: "请输入用户名"
}, {
pattern: /^[a-zA-Z]/,
message: "用户名必须以字母开头"
}, {
pattern: /[a-zA-Z0-9]$/,
message: "用户名只能使用英文字母和数字"
}, {
min: 4,
max: 15,
message: "用户名长度为4到15个字符"
}],
validateFirst: true,
validateTrigger: 'onChange'
}, /*#__PURE__*/react_default.a.createElement(es_input["a" /* default */], {
placeholder: "\u8BF7\u8F93\u51654-15\u4F4D\u7528\u6237\u540D\uFF0C\u4EE5\u5B57\u6BCD\u5F00\u5934\uFF0C\u53EA\u80FD\u4F7F\u7528\u5B57\u6BCD\u548C\u6570\u5B57",
disabled: emailforName,
size: "large",
onBlur: usernameConfirm
})), /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
label: "\u5BC6\u7801",
name: "password",
rules: [{
required: true,
message: '请输入密码'
}]
}, /*#__PURE__*/react_default.a.createElement(es_input["a" /* default */].Password, {
placeholder: "\u8BF7\u8F93\u5165\u5BC6\u7801",
size: "large"
})), /*#__PURE__*/react_default.a.createElement(es_form["a" /* default */].Item, {
label: " ",
colon: false
}, /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
size: "large",
type: "default",
onClick: onClose,
style: {
marginRight: "30px",
width: "80px"
}
}, "\u53D6\u6D88"), /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
size: "large",
type: "primary",
htmlType: "submit",
style: {
marginRight: "30px",
width: "80px"
}
}, "\u4FDD\u5B58")))));
};
/* harmony default export */ var InitGitLink = (Object(umiExports["a" /* connect */])(function (_ref4) {
var loading = _ref4.loading,
globalSetting = _ref4.globalSetting,
user = _ref4.user;
return {
globalSetting: globalSetting,
loading: loading.effects,
user: user
};
})(InitGitLink_InitGitlink));
// EXTERNAL MODULE: ./src/pages/Competitions/components/PhoneModal.tsx + 1 modules
var PhoneModal = __webpack_require__("QtKJ");
// EXTERNAL MODULE: ./src/pages/Competitions/components/ClaModal.tsx
var ClaModal = __webpack_require__("ZSFt");
// CONCATENATED MODULE: ./src/pages/Competitions/Detail/index.tsx
//查看内容
//编辑内容
//排行榜
//获奖证书
var Detail_competitionDetails = function competitionDetails(_ref) {
var _HeaderDetail$competi5, _HeaderDetail$competi6, _user$userInfo4, _HeaderDetail$permiss, _HeaderDetail$permiss2, _HeaderDetail$permiss3, _HeaderDetail$permiss4, _HeaderDetail$permiss5;
var globalSetting = _ref.globalSetting,
loading = _ref.loading,
dispatch = _ref.dispatch,
user = _ref.user,
props = Object(objectWithoutProperties["a" /* default */])(_ref, ["globalSetting", "loading", "dispatch", "user"]);
var _useState = Object(react["useState"])({
avatar_url: ""
}),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
HeaderDetail = _useState2[0],
setHeaderDetail = _useState2[1];
var _useState3 = Object(react["useState"])([]),
_useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
StaffDetail = _useState4[0],
setStaffDetail = _useState4[1];
var _useParams = Object(react_router["l" /* useParams */])(),
identifier = _useParams.identifier;
var _useState5 = Object(react["useState"])([]),
_useState6 = Object(slicedToArray["a" /* default */])(_useState5, 2),
ItemData = _useState6[0],
setItemData = _useState6[1]; //打开编辑还是打开查看
var _useState7 = Object(react["useState"])(true),
_useState8 = Object(slicedToArray["a" /* default */])(_useState7, 2),
ISsee = _useState8[0],
setIssee = _useState8[1];
var _useState9 = Object(react["useState"])([]),
_useState10 = Object(slicedToArray["a" /* default */])(_useState9, 2),
MenuItem = _useState10[0],
setMenuItem = _useState10[1];
var _useState11 = Object(react["useState"])([]),
_useState12 = Object(slicedToArray["a" /* default */])(_useState11, 2),
ModelType = _useState12[0],
setModelType = _useState12[1]; //点击了排行榜
var _useState13 = Object(react["useState"])(false),
_useState14 = Object(slicedToArray["a" /* default */])(_useState13, 2),
isRanKing = _useState14[0],
setIsRanKing = _useState14[1]; //获取排行榜
var _useState15 = Object(react["useState"])(false),
_useState16 = Object(slicedToArray["a" /* default */])(_useState15, 2),
ChartRules = _useState16[0],
setChartRules = _useState16[1]; //点击了获奖证书
var _useState17 = Object(react["useState"])(false),
_useState18 = Object(slicedToArray["a" /* default */])(_useState17, 2),
isAward = _useState18[0],
setIsAward = _useState18[1]; //获奖证书信息
var _useState19 = Object(react["useState"])([]),
_useState20 = Object(slicedToArray["a" /* default */])(_useState19, 2),
Prize = _useState20[0],
setPrize = _useState20[1]; //获取个人信息 Accounts
var _useState21 = Object(react["useState"])([]),
_useState22 = Object(slicedToArray["a" /* default */])(_useState21, 2),
Accounts = _useState22[0],
SetAccounts = _useState22[1]; //设置选中的条目
var _useState23 = Object(react["useState"])([]),
_useState24 = Object(slicedToArray["a" /* default */])(_useState23, 2),
Selectkey = _useState24[0],
setSeleckjey = _useState24[1]; //md_tab
var _useState25 = Object(react["useState"])(false),
_useState26 = Object(slicedToArray["a" /* default */])(_useState25, 2),
MdTab = _useState26[0],
setMdTab = _useState26[1]; //getTabResults
var _useState27 = Object(react["useState"])([]),
_useState28 = Object(slicedToArray["a" /* default */])(_useState27, 2),
TabResults = _useState28[0],
setTabResults = _useState28[1]; //弹窗
var _useState29 = Object(react["useState"])(),
_useState30 = Object(slicedToArray["a" /* default */])(_useState29, 2),
isshowType = _useState30[0],
setisshowType = _useState30[1];
var _useState31 = Object(react["useState"])(true),
_useState32 = Object(slicedToArray["a" /* default */])(_useState31, 2),
itLoading = _useState32[0],
setItLoading = _useState32[1];
var _useState33 = Object(react["useState"])(false),
_useState34 = Object(slicedToArray["a" /* default */])(_useState33, 2),
showmake = _useState34[0],
setshowmake = _useState34[1];
var _useState35 = Object(react["useState"])(false),
_useState36 = Object(slicedToArray["a" /* default */])(_useState35, 2),
entrance = _useState36[0],
setentrance = _useState36[1];
var _useState37 = Object(react["useState"])(false),
_useState38 = Object(slicedToArray["a" /* default */])(_useState37, 2),
subGitlinkShow = _useState38[0],
setSubGitlinkShow = _useState38[1];
var _useState39 = Object(react["useState"])(false),
_useState40 = Object(slicedToArray["a" /* default */])(_useState39, 2),
isshowmodal = _useState40[0],
setisshowmodal = _useState40[1];
var _useState41 = Object(react["useState"])(false),
_useState42 = Object(slicedToArray["a" /* default */])(_useState41, 2),
isAddmodel = _useState42[0],
setIsAddmodel = _useState42[1]; //新建战队
var _useState43 = Object(react["useState"])(false),
_useState44 = Object(slicedToArray["a" /* default */])(_useState43, 2),
isJoin = _useState44[0],
setJoin = _useState44[1]; //加入战队
var _useState45 = Object(react["useState"])(true),
_useState46 = Object(slicedToArray["a" /* default */])(_useState45, 2),
isClick = _useState46[0],
setIsClick = _useState46[1]; //增加参数 防止点击过快 多次调用
var _useState47 = Object(react["useState"])(false),
_useState48 = Object(slicedToArray["a" /* default */])(_useState47, 2),
showphone = _useState48[0],
setshowphone = _useState48[1];
var _useState49 = Object(react["useState"])(false),
_useState50 = Object(slicedToArray["a" /* default */])(_useState49, 2),
isopen = _useState50[0],
setisopen = _useState50[1];
var _useState51 = Object(react["useState"])(''),
_useState52 = Object(slicedToArray["a" /* default */])(_useState51, 2),
datas = _useState52[0],
setdatas = _useState52[1];
var _useState53 = Object(react["useState"])(false),
_useState54 = Object(slicedToArray["a" /* default */])(_useState53, 2),
visible = _useState54[0],
setVisible = _useState54[1];
var loction = Object(react_router["k" /* useLocation */])();
var see = Object(react["useRef"])(null);
Object(react["useEffect"])(function () {
var _user$userInfo;
if (user === null || user === void 0 ? void 0 : (_user$userInfo = user.userInfo) === null || _user$userInfo === void 0 ? void 0 : _user$userInfo.is_new) {
setSubGitlinkShow(true);
}
}, [user === null || user === void 0 ? void 0 : user.userInfo]);
Object(react["useEffect"])(function () {
if (identifier) {
setTimeout(function () {
init();
}, 200);
}
}, [identifier]);
function init() {
return _init.apply(this, arguments);
}
function _init() {
_init = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee2() {
var res;
return regenerator_default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.t0 = setStaffDetail;
_context2.next = 3;
return dispatch({
type: 'competitions/getStaff',
payload: {
identifier: identifier
}
});
case 3:
_context2.t1 = _context2.sent;
(0, _context2.t0)(_context2.t1);
_context2.next = 7;
return dispatch({
type: 'competitions/getHeader',
payload: {
identifier: identifier
}
});
case 7:
res = _context2.sent;
setHeaderDetail(res);
Object(util["p" /* setDocumentTitle */])((res === null || res === void 0 ? void 0 : res.name) || '竞赛');
case 10:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
return _init.apply(this, arguments);
}
Object(react["useEffect"])(function () {
var _loction$query;
// console.log('--------',parseInt(loction?.query?.type)===1);
setisshowType(parseInt(loction === null || loction === void 0 ? void 0 : (_loction$query = loction.query) === null || _loction$query === void 0 ? void 0 : _loction$query.type) === 1);
}, [loction]);
Object(react["useEffect"])(function () {
var _HeaderDetail$competi;
if ((HeaderDetail === null || HeaderDetail === void 0 ? void 0 : (_HeaderDetail$competi = HeaderDetail.competition_modules) === null || _HeaderDetail$competi === void 0 ? void 0 : _HeaderDetail$competi.length) > 0) {
var _loction$query2, _HeaderDetail$competi3;
if ((loction === null || loction === void 0 ? void 0 : (_loction$query2 = loction.query) === null || _loction$query2 === void 0 ? void 0 : _loction$query2.active) === '赛题发布') {
var _HeaderDetail$competi2;
var item = HeaderDetail === null || HeaderDetail === void 0 ? void 0 : (_HeaderDetail$competi2 = HeaderDetail.competition_modules) === null || _HeaderDetail$competi2 === void 0 ? void 0 : _HeaderDetail$competi2.find(function (e) {
return e.name === '赛题发布';
});
if (item) {
getrightdatas(item);
return;
}
}
getrightdatas(HeaderDetail === null || HeaderDetail === void 0 ? void 0 : (_HeaderDetail$competi3 = HeaderDetail.competition_modules) === null || _HeaderDetail$competi3 === void 0 ? void 0 : _HeaderDetail$competi3[0]);
}
}, [HeaderDetail]);
function getrightdatas(_x) {
return _getrightdatas.apply(this, arguments);
}
function _getrightdatas() {
_getrightdatas = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee3(item) {
var data;
return regenerator_default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
setSeleckjey(item.id);
Selectkey = item.id;
setMenuItem(item);
if (!(item.module_type === 'entrance')) {
_context3.next = 9;
break;
}
_context3.next = 6;
return dispatch({
type: 'competitions/getItem',
payload: {
url: item.module_url,
module_type: 'entrance'
}
});
case 6:
data = _context3.sent;
_context3.next = 12;
break;
case 9:
_context3.next = 11;
return dispatch({
type: 'competitions/getItem',
payload: {
url: item.module_url
}
});
case 11:
data = _context3.sent;
case 12:
setIsRanKing(false);
setIsAward(false);
setMdTab(false);
setItemData(data);
setshowmake(false);
setentrance(false);
setModelType(item.module_type);
if (item.module_type === "chart") {
setIsRanKing(true);
setIssee(false);
getChartRules();
} else if (item.module_type === "certificate") {
setIsAward(true);
setIsRanKing(false);
setIssee(false);
getPrize();
} else if (item.module_type === "md_tab") {
setMdTab(true);
setIssee(false);
localStorage.setItem('issee', '2');
setIsRanKing(false);
setIsAward(false); // getChartRules();
getTabResults();
} else if (item.module_type === "md_shixun") {
setshowmake(true);
setIssee(false);
getTabResults();
} else if (item.module_type === 'entrance') {
setentrance(true);
setIssee(false);
getTabResults();
} else {
setIssee(true);
localStorage.setItem('issee', '1');
}
case 20:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
return _getrightdatas.apply(this, arguments);
}
function gotocourse(_x2, _x3, _x4) {
return _gotocourse.apply(this, arguments);
} // useEffect(()=>{
// if(user?.userInfo?.login){
// getId();
// }
// },[user?.userInfo])
// async function getId() {
// let data =await dispatch({
// type: 'competitions/GetKylinId',
// payload: {
// owner:user?.userInfo?.login
// }
// })
// // data.data ||
// let a = data.data;
// console.log(a);
// let filter = a.filter((i:any)=>i === identifier.toString());
// console.log(filter && filter.length>0?true:false);
// }
function _gotocourse() {
_gotocourse = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee4(e, item, url) {
var _user$userInfo5, _user$userInfo7;
var data, a, filter, flag, _user$userInfo6, result;
return regenerator_default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
e.stopPropagation();
if (Object(verifyLogin["b" /* handleVerify */])(dispatch)) {
_context4.next = 3;
break;
}
return _context4.abrupt("return");
case 3:
if (!(HeaderDetail.teacher_need_phone || HeaderDetail.member_need_phone)) {
_context4.next = 6;
break;
}
setshowphone(true);
return _context4.abrupt("return");
case 6:
_context4.next = 8;
return dispatch({
type: 'competitions/GetKylinId',
payload: {
owner: user === null || user === void 0 ? void 0 : (_user$userInfo5 = user.userInfo) === null || _user$userInfo5 === void 0 ? void 0 : _user$userInfo5.login
}
});
case 8:
data = _context4.sent;
a = data.data;
filter = a.filter(function (i) {
return i.toString() === (item === null || item === void 0 ? void 0 : item.id.toString());
});
flag = filter && filter.length > 0 ? true : false;
if (!flag) {
_context4.next = 16;
break;
}
if (user === null || user === void 0 ? void 0 : (_user$userInfo6 = user.userInfo) === null || _user$userInfo6 === void 0 ? void 0 : _user$userInfo6.sign_cla) {
_context4.next = 16;
break;
}
setVisible(true);
return _context4.abrupt("return");
case 16:
if (!((HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.is_authentication) && !(user === null || user === void 0 ? void 0 : (_user$userInfo7 = user.userInfo) === null || _user$userInfo7 === void 0 ? void 0 : _user$userInfo7.authentication))) {
_context4.next = 19;
break;
}
dispatch({
type: 'shixunsDetail/setActionTabs',
payload: {
key: 'Banner-Auth'
}
});
return _context4.abrupt("return");
case 19:
if (!(HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.enroll_url)) {
_context4.next = 22;
break;
}
Object(util["n" /* openNewWindow */])(HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.enroll_url);
return _context4.abrupt("return");
case 22:
if (!(url === "ismodel")) {
_context4.next = 36;
break;
}
if (!(item.member_of_course === true)) {
_context4.next = 27;
break;
}
Object(util["n" /* openNewWindow */])("/classrooms/".concat(item.course_id));
_context4.next = 34;
break;
case 27:
if (item.invite_code) {
_context4.next = 30;
break;
}
es_message["b" /* default */].info('本竞赛只面向部分学校/单位开放,你暂时没有参赛资格');
return _context4.abrupt("return");
case 30:
_context4.next = 32;
return dispatch({
type: 'competitions/addApplytojoincourse',
payload: {
invite_code: item.invite_code,
student: 1
}
});
case 32:
result = _context4.sent;
if (result.status === 0) {
Object(util["n" /* openNewWindow */])("/classrooms/".concat(item.course_id));
}
case 34:
_context4.next = 40;
break;
case 36:
if (!(StaffDetail.enrolled === true)) {
_context4.next = 39;
break;
}
Object(util["n" /* openNewWindow */])(url);
return _context4.abrupt("return");
case 39:
setisshowmodal(true); // if (url === "personal") {
// if (item.enroll_ended === true) {
// //已截止
// message.info(`报名已截止`);
// return;
// }
// if (StaffDetail.enrolled === true) {
// message.info(`你已经报名,不能重复报名!`);
// return;
// }
// const competitionTeamsresult = await dispatch({
// type: 'competitions/competitionTeams',
// payload: {
// identifier: item.identifier
// }
// })
// if (competitionTeamsresult) {
// message.info('报名成功,预祝您夺得桂冠!')
// }
// } else {
// openNewWindow(url)
// }
case 40:
case "end":
return _context4.stop();
}
}
}, _callee4);
}));
return _gotocourse.apply(this, arguments);
}
function getChartRules() {
return _getChartRules.apply(this, arguments);
}
function _getChartRules() {
_getChartRules = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee5() {
return regenerator_default.a.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
_context5.t0 = setChartRules;
_context5.next = 3;
return dispatch({
type: 'competitions/ChartRules',
payload: {
identifier: identifier
}
});
case 3:
_context5.t1 = _context5.sent;
_context5.next = 6;
return (0, _context5.t0)(_context5.t1);
case 6:
case "end":
return _context5.stop();
}
}
}, _callee5);
}));
return _getChartRules.apply(this, arguments);
}
function getCharts(_x5) {
return _getCharts.apply(this, arguments);
}
function _getCharts() {
_getCharts = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee6(id) {
var data;
return regenerator_default.a.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
_context6.next = 2;
return dispatch({
type: 'competitions/Charts',
payload: {
identifier: identifier,
stage_id: id
}
});
case 2:
data = _context6.sent;
setItemData(data);
case 4:
case "end":
return _context6.stop();
}
}
}, _callee6);
}));
return _getCharts.apply(this, arguments);
}
function getshixunCharts(_x6) {
return _getshixunCharts.apply(this, arguments);
}
function _getshixunCharts() {
_getshixunCharts = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee7(params) {
var data;
return regenerator_default.a.wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
setItLoading(true);
_context7.next = 3;
return dispatch({
type: 'competitions/Results',
payload: Object(objectSpread2["a" /* default */])({
identifier: identifier,
stage_id: params === null || params === void 0 ? void 0 : params.id
}, params)
});
case 3:
data = _context7.sent;
setItemData(data);
setItLoading(false);
case 6:
case "end":
return _context7.stop();
}
}
}, _callee7);
}));
return _getshixunCharts.apply(this, arguments);
}
function getEntrance(_x7) {
return _getEntrance.apply(this, arguments);
}
function _getEntrance() {
_getEntrance = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee8(params) {
var data;
return regenerator_default.a.wrap(function _callee8$(_context8) {
while (1) {
switch (_context8.prev = _context8.next) {
case 0:
setItLoading(true);
_context8.next = 3;
return dispatch({
type: 'competitions/Results',
payload: Object(objectSpread2["a" /* default */])({
identifier: identifier,
stage_id: params === null || params === void 0 ? void 0 : params.id,
module_type: 'entrance'
}, params)
});
case 3:
data = _context8.sent;
setItemData(data);
setItLoading(false);
case 6:
case "end":
return _context8.stop();
}
}
}, _callee8);
}));
return _getEntrance.apply(this, arguments);
}
function getResults(_x8) {
return _getResults.apply(this, arguments);
}
function _getResults() {
_getResults = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee9(id) {
var data;
return regenerator_default.a.wrap(function _callee9$(_context9) {
while (1) {
switch (_context9.prev = _context9.next) {
case 0:
_context9.next = 2;
return dispatch({
type: 'competitions/Results',
payload: {
identifier: identifier,
stage_id: id
}
});
case 2:
data = _context9.sent;
if (!(localStorage.getItem('issee') === '1')) {
_context9.next = 5;
break;
}
return _context9.abrupt("return");
case 5:
setItemData(data);
case 6:
case "end":
return _context9.stop();
}
}
}, _callee9);
}));
return _getResults.apply(this, arguments);
}
function getTabResults() {
return _getTabResults.apply(this, arguments);
}
function _getTabResults() {
_getTabResults = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee10() {
return regenerator_default.a.wrap(function _callee10$(_context10) {
while (1) {
switch (_context10.prev = _context10.next) {
case 0:
_context10.t0 = setTabResults;
_context10.next = 3;
return dispatch({
type: 'competitions/TabResults',
payload: {
identifier: identifier,
competition_module_id: Selectkey
}
});
case 3:
_context10.t1 = _context10.sent;
(0, _context10.t0)(_context10.t1);
case 5:
case "end":
return _context10.stop();
}
}
}, _callee10);
}));
return _getTabResults.apply(this, arguments);
}
function getPrize() {
return _getPrize.apply(this, arguments);
} //个人信息 Accounts
function _getPrize() {
_getPrize = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee11() {
var _user$userInfo8;
var data;
return regenerator_default.a.wrap(function _callee11$(_context11) {
while (1) {
switch (_context11.prev = _context11.next) {
case 0:
_context11.next = 2;
return dispatch({
type: 'competitions/Prize',
payload: {
identifier: identifier,
user_id: user === null || user === void 0 ? void 0 : (_user$userInfo8 = user.userInfo) === null || _user$userInfo8 === void 0 ? void 0 : _user$userInfo8.user_id //user_id:39416
}
});
case 2:
data = _context11.sent;
setPrize(data);
case 4:
case "end":
return _context11.stop();
}
}
}, _callee11);
}));
return _getPrize.apply(this, arguments);
}
function getAccounts() {
return _getAccounts.apply(this, arguments);
}
function _getAccounts() {
_getAccounts = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee12() {
var _user$userInfo9;
var data;
return regenerator_default.a.wrap(function _callee12$(_context12) {
while (1) {
switch (_context12.prev = _context12.next) {
case 0:
_context12.next = 2;
return dispatch({
type: 'competitions/Accounts',
payload: {
id: user === null || user === void 0 ? void 0 : (_user$userInfo9 = user.userInfo) === null || _user$userInfo9 === void 0 ? void 0 : _user$userInfo9.user_id //user_id:39416
}
});
case 2:
data = _context12.sent;
SetAccounts(data);
case 4:
case "end":
return _context12.stop();
}
}
}, _callee12);
}));
return _getAccounts.apply(this, arguments);
}
function addTeams(_x9) {
return _addTeams.apply(this, arguments);
}
function _addTeams() {
_addTeams = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee13(name) {
var data;
return regenerator_default.a.wrap(function _callee13$(_context13) {
while (1) {
switch (_context13.prev = _context13.next) {
case 0:
if (isClick) {
_context13.next = 2;
break;
}
return _context13.abrupt("return");
case 2:
setIsClick(false);
if (!isadd()) {
_context13.next = 5;
break;
}
return _context13.abrupt("return");
case 5:
_context13.next = 7;
return dispatch({
type: 'competitions/AddTeam',
payload: {
identifier: identifier,
name: name
}
});
case 7:
data = _context13.sent;
if (data && data.status === 0) {
setdatas(data);
setisopen(true);
init();
setIsAddmodel(false);
} else {
setIsClick(true);
}
case 9:
case "end":
return _context13.stop();
}
}
}, _callee13);
}));
return _addTeams.apply(this, arguments);
}
function isadd() {
var _user$userInfo2, _user$userInfo3;
//判断 如果不符合条件 不能加入竞赛
if (user === null || user === void 0 ? void 0 : (_user$userInfo2 = user.userInfo) === null || _user$userInfo2 === void 0 ? void 0 : _user$userInfo2.is_teacher) {
var _StaffDetail$teacher_;
if (StaffDetail === null || StaffDetail === void 0 ? void 0 : (_StaffDetail$teacher_ = StaffDetail.teacher_staff) === null || _StaffDetail$teacher_ === void 0 ? void 0 : _StaffDetail$teacher_.mutiple_limited) {
if (StaffDetail === null || StaffDetail === void 0 ? void 0 : StaffDetail.enrolled) {
es_message["b" /* default */].info('你已经报名,不能重复报名');
setIsClick(true);
return true;
}
}
} else {
var _StaffDetail$member_s;
if (StaffDetail === null || StaffDetail === void 0 ? void 0 : (_StaffDetail$member_s = StaffDetail.member_staff) === null || _StaffDetail$member_s === void 0 ? void 0 : _StaffDetail$member_s.mutiple_limited) {
if (StaffDetail === null || StaffDetail === void 0 ? void 0 : StaffDetail.enrolled) {
es_message["b" /* default */].info('你已经报名,不能重复报名');
setIsClick(true);
return true;
}
}
} //判断竞赛是否关闭
if (StaffDetail === null || StaffDetail === void 0 ? void 0 : StaffDetail.enroll_ended) {
es_message["b" /* default */].info('报名已截止,无需报名');
setIsClick(true);
return true;
} //禁止老师or学生报名
if (user === null || user === void 0 ? void 0 : (_user$userInfo3 = user.userInfo) === null || _user$userInfo3 === void 0 ? void 0 : _user$userInfo3.is_teacher) {
if (!StaffDetail.teacher_staff) {
es_message["b" /* default */].info('已禁止老师报名');
setIsClick(true);
return true;
}
} else {
if (!(StaffDetail === null || StaffDetail === void 0 ? void 0 : StaffDetail.member_staff)) {
es_message["b" /* default */].info('已禁止学生报名');
setIsClick(true);
return true;
}
}
} //加入战队
function JoinTeams(_x10) {
return _JoinTeams.apply(this, arguments);
} // console.log('-------',useLocation().query.type);
function _JoinTeams() {
_JoinTeams = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee14(name) {
var data;
return regenerator_default.a.wrap(function _callee14$(_context14) {
while (1) {
switch (_context14.prev = _context14.next) {
case 0:
if (isClick) {
_context14.next = 2;
break;
}
return _context14.abrupt("return");
case 2:
if (!isadd()) {
_context14.next = 4;
break;
}
return _context14.abrupt("return");
case 4:
setIsClick(false);
_context14.next = 7;
return dispatch({
type: 'competitions/JoinTeam',
payload: {
identifier: identifier,
invite_code: name
}
});
case 7:
data = _context14.sent;
if (data && data.status === 0) {
setisopen(true);
setdatas(data);
setJoin(false);
setIsClick(true);
init();
} else {
setIsClick(true);
}
case 9:
case "end":
return _context14.stop();
}
}
}, _callee14);
}));
return _JoinTeams.apply(this, arguments);
}
return /*#__PURE__*/react_default.a.createElement("div", {
className: "edu-container minH500"
}, /*#__PURE__*/react_default.a.createElement(InitGitLink, {
visible: subGitlinkShow,
onClose: function onClose() {
return setSubGitlinkShow(false);
}
}), /*#__PURE__*/react_default.a.createElement(breadcrumb["a" /* default */], {
className: "mt10",
separator: ">"
}, /*#__PURE__*/react_default.a.createElement(breadcrumb["a" /* default */].Item, null, /*#__PURE__*/react_default.a.createElement(react_router_dom["a" /* Link */], {
to: "/competitions/index"
}, "\u5728\u7EBF\u7ADE\u8D5B")), /*#__PURE__*/react_default.a.createElement(breadcrumb["a" /* default */].Item, null, HeaderDetail.name, HeaderDetail.sub_title ? '-' + HeaderDetail.sub_title : null)), /*#__PURE__*/react_default.a.createElement("div", {
className: "mt10",
style: {
display: 'flex',
background: '#fff',
position: 'relative',
padding: '20px 12px'
}
}, /*#__PURE__*/react_default.a.createElement(spin["a" /* default */], {
spinning: loading.effects['competitions/getHeader']
}, /*#__PURE__*/react_default.a.createElement("div", {
style: {
height: '355px',
width: "800px"
}
}, (HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.avatar_url) && (HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.avatar_url) !== null && /*#__PURE__*/react_default.a.createElement("img", {
style: {
height: '355px',
width: '800px'
},
src: env["a" /* default */].IMG_SERVER + '/' + (HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.avatar_url)
}), !(HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.avatar_url) && (HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.avatar_url) == null && /*#__PURE__*/react_default.a.createElement("img", {
style: {
height: '355px',
width: '800px'
},
src: env["a" /* default */].IMG_SERVER + "/images/educoder/competitions/mainbanner.jpg"
}))), /*#__PURE__*/react_default.a.createElement("div", {
style: {
marginLeft: '20px',
width: '400px'
}
}, /*#__PURE__*/react_default.a.createElement("p", {
className: "".concat(Detailmodules_default.a.titlesize)
}, HeaderDetail.name, HeaderDetail.sub_title ? '-' + HeaderDetail.sub_title : null), /*#__PURE__*/react_default.a.createElement("p", {
style: {
display: 'flex',
justifyContent: 'space-between',
marginRight: 18
}
}, /*#__PURE__*/react_default.a.createElement("span", {
style: {
display: 'flex',
flexDirection: 'column',
alignItems: 'center'
}
}, /*#__PURE__*/react_default.a.createElement("span", null, "\u5956\u91D1"), !!(HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.bonus) ? /*#__PURE__*/react_default.a.createElement("span", {
style: {
fontSize: '24px'
}
}, "\xA5", parseInt(HeaderDetail && HeaderDetail.bonus).toLocaleString()) : /*#__PURE__*/react_default.a.createElement("span", {
style: {
fontSize: '24px'
}
}, "\u6682\u65E0")), /*#__PURE__*/react_default.a.createElement("span", {
style: {
display: 'flex',
flexDirection: 'column',
alignItems: 'center'
}
}, /*#__PURE__*/react_default.a.createElement("span", null, "\u6D4F\u89C8"), /*#__PURE__*/react_default.a.createElement("span", {
style: {
fontSize: '24px'
}
}, parseInt(HeaderDetail && HeaderDetail.visits_count).toLocaleString())), /*#__PURE__*/react_default.a.createElement("span", {
style: {
display: 'flex',
flexDirection: 'column',
alignItems: 'center'
}
}, /*#__PURE__*/react_default.a.createElement("span", null, "\u62A5\u540D"), /*#__PURE__*/react_default.a.createElement("span", {
style: {
fontSize: '24px'
}
}, parseInt(HeaderDetail && HeaderDetail.member_count).toLocaleString()))), /*#__PURE__*/react_default.a.createElement("p", {
className: Detailmodules_default.a.timesize,
style: {
marginTop: 30
}
}, /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#9b9b9b',
marginTop: '30px'
}
}, "\u7ADE\u8D5B\u65F6\u95F4\uFF1A"), HeaderDetail.start_time, "~", HeaderDetail.end_time), /*#__PURE__*/react_default.a.createElement("p", {
className: Detailmodules_default.a.timesize
}, /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#9b9b9b'
}
}, "\u62A5\u540D\u622A\u6B62\uFF1A"), HeaderDetail.enroll_end_time), HeaderDetail.competition_status === 'ended' ? /*#__PURE__*/react_default.a.createElement("p", {
className: Detailmodules_default.a.timesize
}, /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#9b9b9b'
}
}, "\u7ADE\u8D5B\u72B6\u6001\uFF1A"), "\u5DF2\u7ED3\u675F") : null, HeaderDetail.competition_status === 'nearly_published' ? /*#__PURE__*/react_default.a.createElement("p", {
className: Detailmodules_default.a.timesize
}, /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#9b9b9b'
}
}, "\u7ADE\u8D5B\u72B6\u6001\uFF1A"), "\u672A\u53D1\u5E03") : null, HeaderDetail.competition_status === 'progressing' ? /*#__PURE__*/react_default.a.createElement("p", {
className: Detailmodules_default.a.timesize
}, /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#9b9b9b'
}
}, "\u7ADE\u8D5B\u72B6\u6001\uFF1A"), "\u8FDB\u884C\u4E2D") : null, /*#__PURE__*/react_default.a.createElement("div", {
style: {
display: 'flex',
justifyContent: 'center'
}
}, (HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.mode) <= 2 && StaffDetail.enrolled && /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
onClick: function onClick(e) {
if ((HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.mode) === 1) {
var _HeaderDetail$competi4;
getrightdatas((_HeaderDetail$competi4 = HeaderDetail.competition_modules) === null || _HeaderDetail$competi4 === void 0 ? void 0 : _HeaderDetail$competi4.find(function (item) {
return item.module_type === 'entrance';
}));
} else {
gotocourse(e, HeaderDetail, 'ismodel');
}
},
style: {
background: '#07C160',
color: '#fff',
border: '1px solid #07C160',
marginRight: 20,
display: (HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.mode) === 2 ? '' : (HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.mode) === 1 && ((_HeaderDetail$competi5 = HeaderDetail.competition_modules) === null || _HeaderDetail$competi5 === void 0 ? void 0 : (_HeaderDetail$competi6 = _HeaderDetail$competi5.filter(function (item) {
return item.module_type === 'entrance';
})) === null || _HeaderDetail$competi6 === void 0 ? void 0 : _HeaderDetail$competi6.length) > 0 ? '' : 'none'
},
className: Detailmodules_default.a.buttonsize
}, (HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.mode) === 1 && '赛题入口', (HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.mode) === 2 && '进入课堂'), HeaderDetail.competition_status === "ended" ? /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
type: "primary",
className: Detailmodules_default.a.buttonsize,
disabled: true
}, "\u5DF2\u7ED3\u675F") : null, HeaderDetail.competition_status === 'nearly_published' ? /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
type: "primary",
className: Detailmodules_default.a.buttonsize,
disabled: true
}, "\u672A\u53D1\u5E03") : null, HeaderDetail.competition_status !== 'nearly_published' && HeaderDetail.enroll_end && HeaderDetail.competition_status !== 'ended' ? /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
type: "primary",
className: Detailmodules_default.a.buttonsize,
disabled: true
}, "\u62A5\u540D\u622A\u6B62") : null, HeaderDetail.competition_status === 'progressing' && HeaderDetail.enroll_end != true ? /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
type: "primary",
disabled: StaffDetail.enrolled && !HeaderDetail.need_attachment,
className: Detailmodules_default.a.buttonsize,
onClick: function onClick(e) {
if (StaffDetail.enrolled && HeaderDetail.need_attachment) {
var _see$current;
(_see$current = see.current) === null || _see$current === void 0 ? void 0 : _see$current.handleVisible();
return;
}
gotocourse(e, HeaderDetail, HeaderDetail.mode === 2 ? 'ismodel' : HeaderDetail.personal ? 'personal' : "/competitions/index/".concat(HeaderDetail.identifier, "/enroll"));
}
}, StaffDetail.enrolled ? HeaderDetail.need_attachment ? '上传作品' : '已报名' : (HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.enroll_url) ? '前往大赛官网报名' : '立即报名') : null), user.userInfo.real_name != "游客" && !(HeaderDetail === null || HeaderDetail === void 0 ? void 0 : HeaderDetail.enroll_url) && /*#__PURE__*/react_default.a.createElement("span", {
onClick: function onClick(e) {
return gotocourse(e, HeaderDetail, HeaderDetail.mode === 2 ? 'ismodel' : HeaderDetail.personal ? 'personal' : "/competitions/index/".concat(HeaderDetail.identifier, "/enroll"));
},
className: Detailmodules_default.a.myteam
}, Object(authority["d" /* isSuperAdmin */])() ? '参赛战队>>' : '我的战队>>'))), /*#__PURE__*/react_default.a.createElement("div", {
className: Detailmodules_default.a.bootmdetail
}, /*#__PURE__*/react_default.a.createElement("div", {
className: Detailmodules_default.a.flex1
}, /*#__PURE__*/react_default.a.createElement(menu["a" /* default */], {
selectedKeys: ["".concat(Selectkey)]
}, HeaderDetail && HeaderDetail.competition_modules && HeaderDetail.competition_modules.map(function (item, index) {
if (item.module_type != "enroll") {
return /*#__PURE__*/react_default.a.createElement(menu["a" /* default */].Item, {
className: Detailmodules_default.a.menuItem,
onClick: function onClick() {
if (item === null || item === void 0 ? void 0 : item.is_authentication) {
if (!Object(verifyLogin["b" /* handleVerify */])(dispatch)) {
return;
}
es_message["b" /* default */].info('加入战队才能查看');
return;
} // if(item?.item?.has_url){
// window.visible(item?.module_url)
// return
// }
getrightdatas(item);
},
key: item.id
}, item.name);
}
}))), /*#__PURE__*/react_default.a.createElement("div", {
className: Detailmodules_default.a.flex6,
style: {
padding: (showmake || entrance) && 0
}
}, isAward ? /*#__PURE__*/react_default.a.createElement(AwardPdf, {
dispatch: dispatch,
userid: user === null || user === void 0 ? void 0 : (_user$userInfo4 = user.userInfo) === null || _user$userInfo4 === void 0 ? void 0 : _user$userInfo4.user_id,
Prize: Prize,
Accounts: Accounts,
getAccounts: getAccounts
}) : null, isRanKing ? /*#__PURE__*/react_default.a.createElement(Detail_Ranking, {
HeaderDetail: HeaderDetail,
userinfo: user.userInfo,
Editable: HeaderDetail === null || HeaderDetail === void 0 ? void 0 : (_HeaderDetail$permiss = HeaderDetail.permission) === null || _HeaderDetail$permiss === void 0 ? void 0 : _HeaderDetail$permiss.editable,
getCharts: getCharts,
getChartRules: getChartRules,
Selectkey: Selectkey,
ChartRules: ChartRules,
ItemData: ItemData
}) : null, ISsee ? /*#__PURE__*/react_default.a.createElement(Detail_SeeItem, {
ref: see,
StaffDetail: StaffDetail,
HeaderDetail: HeaderDetail,
userinfo: user.userInfo,
Editable: HeaderDetail === null || HeaderDetail === void 0 ? void 0 : (_HeaderDetail$permiss2 = HeaderDetail.permission) === null || _HeaderDetail$permiss2 === void 0 ? void 0 : _HeaderDetail$permiss2.editable,
ItemData: ItemData,
setIssee: setIssee,
ModelType: ModelType,
dispatch: dispatch
}) : null, !ISsee && !showmake && !entrance && !isRanKing && !isAward && !MdTab ? /*#__PURE__*/react_default.a.createElement(Update, {
userinfo: user.userInfo,
ModelType: ModelType,
getrightdatas: getrightdatas,
dispatch: dispatch,
MenuItem: MenuItem,
setIssee: setIssee,
identifier: identifier,
ItemData: ItemData
}) : null, MdTab && /*#__PURE__*/react_default.a.createElement(SubmitResult, {
dispatch: dispatch,
StaffDetail: StaffDetail,
userinfo: user.userInfo,
HeaderDetail: HeaderDetail,
Editable: HeaderDetail === null || HeaderDetail === void 0 ? void 0 : (_HeaderDetail$permiss3 = HeaderDetail.permission) === null || _HeaderDetail$permiss3 === void 0 ? void 0 : _HeaderDetail$permiss3.editable,
getCharts: getResults,
getChartRules: getTabResults,
Selectkey: Selectkey,
ChartRules: TabResults,
ItemData: ItemData
}), showmake && /*#__PURE__*/react_default.a.createElement(MakeItem, {
loading: itLoading,
dispatch: dispatch,
StaffDetail: StaffDetail,
userinfo: user.userInfo,
HeaderDetail: HeaderDetail,
Editable: HeaderDetail === null || HeaderDetail === void 0 ? void 0 : (_HeaderDetail$permiss4 = HeaderDetail.permission) === null || _HeaderDetail$permiss4 === void 0 ? void 0 : _HeaderDetail$permiss4.editable,
getCharts: getshixunCharts,
getChartRules: getTabResults,
Selectkey: Selectkey,
ChartRules: TabResults,
ItemData: ItemData
}), entrance && /*#__PURE__*/react_default.a.createElement(Entrance, {
loading: itLoading,
dispatch: dispatch,
StaffDetail: StaffDetail,
userinfo: user.userInfo,
HeaderDetail: HeaderDetail,
Editable: HeaderDetail === null || HeaderDetail === void 0 ? void 0 : (_HeaderDetail$permiss5 = HeaderDetail.permission) === null || _HeaderDetail$permiss5 === void 0 ? void 0 : _HeaderDetail$permiss5.editable,
getCharts: getEntrance,
getChartRules: getTabResults,
Selectkey: Selectkey,
ChartRules: TabResults,
ItemData: ItemData
}))), /*#__PURE__*/react_default.a.createElement(AuthenticationModel["a" /* default */], null), /*#__PURE__*/react_default.a.createElement(AddSubmitModel, {
getResults: getResults
}), /*#__PURE__*/react_default.a.createElement(es_modal["a" /* default */], {
visible: isshowType // visible
,
footer: null,
width: 720,
title: "\u63D0\u793A",
centered: true,
onCancel: function onCancel() {
return setisshowType(false);
}
}, /*#__PURE__*/react_default.a.createElement("div", {
className: Detailmodules_default.a.modal
}, /*#__PURE__*/react_default.a.createElement("div", null, "\u534E\u4E3A\u6A21\u578B\u738B\u8005\u6311\u6218\u8D5B\u9EC4\u91D1\u8D5B\u6B63\u5F0F\u5F00\u542F\u5566"), /*#__PURE__*/react_default.a.createElement("div", null, "\u672C\u8D5B\u6BB5\u603B\u5956\u91D1\u9AD8\u8FBE", /*#__PURE__*/react_default.a.createElement("span", {
style: {
color: '#FF8C29'
}
}, "300,000"), "\u5143"), /*#__PURE__*/react_default.a.createElement("div", null, "1\u3001\u7B26\u5408\u8D5B\u9898\u8981\u6C42\u7684\u961F\u4F0D\uFF08\u517125\u652F\uFF09\u53EF\u83B7\u5F97\u5956\u91D1\uFF1A12000RMB/\u961F \uFF1B"), /*#__PURE__*/react_default.a.createElement("div", null, "2\u3001\u53C2\u4E0E\u83B7\u5F97\u201C\u8363\u8000\u6BBF\u5802\u201D\u699C\u4E3B\u7684\u961F\u4F0D\uFF0C\u53EF\u83B7\u5F97\u7531\u4E2D\u56FD\u8F6F\u4EF6\u5F00\u6E90\u521B\u65B0\u5927\u8D5B\u7EC4\u59D4\u4F1A\u9881\u53D1\u7684\u9EC4\u91D1\u5B9D\u7BB1\uFF1B"), /*#__PURE__*/react_default.a.createElement("div", null, "3\u3001\u5404\u8D5B\u9898\u7CBE\u5EA6\u6700\u9AD8\u7684\u961F\u4F0D\uFF0C\u53EF\u83B7\u5F97\u7531\u4E2D\u56FD\u8F6F\u4EF6\u5F00\u6E90\u521B\u65B0\u5927\u8D5B\u7EC4\u59D4\u4F1A\u9881\u53D1\u7684\u9EC4\u91D1\u5B9D\u7BB1+\u8363\u8A89\u8BC1\u4E66\uFF1B"), /*#__PURE__*/react_default.a.createElement("div", null, "\u5FC3\u52A8\u5427\uFF0C\u90A3\u5C31\u5FEB\u70B9\u51FB\u4E0B\u65B9\u6309\u94AE\u62A5\u540D\u53C2\u8D5B"), /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
type: "primary",
onClick: function onClick() {
return Object(util["n" /* openNewWindow */])('https://competition.huaweicloud.com/information/1000041485/introduction');
}
}, "\u524D\u5F80\u62A5\u540D\u53C2\u8D5B"))), /*#__PURE__*/react_default.a.createElement(es_modal["a" /* default */], {
title: "\u9009\u62E9\u53C2\u8D5B\u65B9\u5F0F",
visible: isshowmodal,
onCancel: function onCancel() {
setisshowmodal(false);
},
footer: false
}, /*#__PURE__*/react_default.a.createElement("div", {
style: {
display: 'flex',
justifyContent: 'space-around',
height: 100,
alignItems: 'center'
}
}, /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
type: "primary",
style: {
height: 40
},
onClick: function onClick() {
setJoin(true);
setisshowmodal(false);
}
}, "\u52A0\u5165\u6218\u961F\u53C2\u8D5B"), /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
style: {
height: 40
},
onClick: function onClick() {
setIsAddmodel(true);
setisshowmodal(false);
}
}, "\u53BB\u521B\u5EFA\u6218\u961F\u53C2\u8D5B"))), isJoin ? /*#__PURE__*/react_default.a.createElement(JoinModel["a" /* default */], {
isjoin: isJoin,
setJoin: setJoin,
JoinTeams: JoinTeams
}) : null, isAddmodel ? /*#__PURE__*/react_default.a.createElement(Addteams["a" /* default */], {
isAddmodle: isAddmodel,
setIsAdd: setIsAddmodel,
createTeam: addTeams
}) : null, /*#__PURE__*/react_default.a.createElement(PhoneModal["a" /* default */], {
datas: datas,
isopen: isopen,
setisopen: setisopen,
isShowPhone: showphone,
setIsShowPhone: setshowphone,
user: user,
dispatch: dispatch,
onOK: /*#__PURE__*/Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee() {
var res;
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return dispatch({
type: 'competitions/getHeader',
payload: {
identifier: identifier
}
});
case 2:
res = _context.sent;
setHeaderDetail(res);
case 4:
case "end":
return _context.stop();
}
}
}, _callee);
}))
}), /*#__PURE__*/react_default.a.createElement(ClaModal["a" /* default */], {
visible: visible,
onCancel: function onCancel() {
setVisible(false);
},
onOk: function onOk() {
setVisible(false);
setisshowmodal(true);
dispatch({
type: 'user/getUserInfo',
payload: {}
});
}
}));
};
/* harmony default export */ var Detail = __webpack_exports__["default"] = (Object(umiExports["a" /* connect */])(function (_ref3) {
var loading = _ref3.loading,
globalSetting = _ref3.globalSetting,
user = _ref3.user;
return {
globalSetting: globalSetting,
loading: loading,
user: user
};
})(Detail_competitionDetails));
/***/ }),
/***/ "GRuw":
/*!******************************************!*\
!*** ./node_modules/crypto-js/sha224.js ***!
\******************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory, undef) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"), __webpack_require__(/*! ./sha256 */ "lPiR"));
}
else {}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var SHA256 = C_algo.SHA256;
/**
* SHA-224 hash algorithm.
*/
var SHA224 = C_algo.SHA224 = SHA256.extend({
_doReset: function () {
this._hash = new WordArray.init([
0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4
]);
},
_doFinalize: function () {
var hash = SHA256._doFinalize.call(this);
hash.sigBytes -= 4;
return hash;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA224('message');
* var hash = CryptoJS.SHA224(wordArray);
*/
C.SHA224 = SHA256._createHelper(SHA224);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA224(message, key);
*/
C.HmacSHA224 = SHA256._createHmacHelper(SHA224);
}());
return CryptoJS.SHA224;
}));
/***/ }),
/***/ "HBhm":
/*!*************************************************************************!*\
!*** ./node_modules/@ant-design/icons-svg/lib/asn/PaperClipOutlined.js ***!
\*************************************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// This icon file is generated automatically.
Object.defineProperty(exports, "__esModule", { value: true });
var PaperClipOutlined = { "icon": { "tag": "svg", "attrs": { "viewBox": "64 64 896 896", "focusable": "false" }, "children": [{ "tag": "path", "attrs": { "d": "M779.3 196.6c-94.2-94.2-247.6-94.2-341.7 0l-261 260.8c-1.7 1.7-2.6 4-2.6 6.4s.9 4.7 2.6 6.4l36.9 36.9a9 9 0 0012.7 0l261-260.8c32.4-32.4 75.5-50.2 121.3-50.2s88.9 17.8 121.2 50.2c32.4 32.4 50.2 75.5 50.2 121.2 0 45.8-17.8 88.8-50.2 121.2l-266 265.9-43.1 43.1c-40.3 40.3-105.8 40.3-146.1 0-19.5-19.5-30.2-45.4-30.2-73s10.7-53.5 30.2-73l263.9-263.8c6.7-6.6 15.5-10.3 24.9-10.3h.1c9.4 0 18.1 3.7 24.7 10.3 6.7 6.7 10.3 15.5 10.3 24.9 0 9.3-3.7 18.1-10.3 24.7L372.4 653c-1.7 1.7-2.6 4-2.6 6.4s.9 4.7 2.6 6.4l36.9 36.9a9 9 0 0012.7 0l215.6-215.6c19.9-19.9 30.8-46.3 30.8-74.4s-11-54.6-30.8-74.4c-41.1-41.1-107.9-41-149 0L463 364 224.8 602.1A172.22 172.22 0 00174 724.8c0 46.3 18.1 89.8 50.8 122.5 33.9 33.8 78.3 50.7 122.7 50.7 44.4 0 88.8-16.9 122.6-50.7l309.2-309C824.8 492.7 850 432 850 367.5c.1-64.6-25.1-125.3-70.7-170.9z" } }] }, "name": "paper-clip", "theme": "outlined" };
exports.default = PaperClipOutlined;
/***/ }),
/***/ "HmJG":
/*!****************************************************************!*\
!*** ./src/components/markdown-editor/upload-image/index.less ***!
\****************************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/***/ "HpTS":
/*!********************************************************!*\
!*** ./src/assets/images/classrooms/small_program.png ***!
\********************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/small_program.f74069ec.png";
/***/ }),
/***/ "Ib8C":
/*!****************************************!*\
!*** ./node_modules/crypto-js/core.js ***!
\****************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {;(function (root, factory) {
if (true) {
// CommonJS
module.exports = exports = factory();
}
else {}
}(this, function () {
/*globals window, global, require*/
/**
* CryptoJS core components.
*/
var CryptoJS = CryptoJS || (function (Math, undefined) {
var crypto;
// Native crypto from window (Browser)
if (typeof window !== 'undefined' && window.crypto) {
crypto = window.crypto;
}
// Native crypto in web worker (Browser)
if (typeof self !== 'undefined' && self.crypto) {
crypto = self.crypto;
}
// Native crypto from worker
if (typeof globalThis !== 'undefined' && globalThis.crypto) {
crypto = globalThis.crypto;
}
// Native (experimental IE 11) crypto from window (Browser)
if (!crypto && typeof window !== 'undefined' && window.msCrypto) {
crypto = window.msCrypto;
}
// Native crypto from global (NodeJS)
if (!crypto && typeof global !== 'undefined' && global.crypto) {
crypto = global.crypto;
}
// Native crypto import via require (NodeJS)
if (!crypto && "function" === 'function') {
try {
crypto = __webpack_require__(/*! crypto */ 4);
} catch (err) {}
}
/*
* Cryptographically secure pseudorandom number generator
*
* As Math.random() is cryptographically not safe to use
*/
var cryptoSecureRandomInt = function () {
if (crypto) {
// Use getRandomValues method (Browser)
if (typeof crypto.getRandomValues === 'function') {
try {
return crypto.getRandomValues(new Uint32Array(1))[0];
} catch (err) {}
}
// Use randomBytes method (NodeJS)
if (typeof crypto.randomBytes === 'function') {
try {
return crypto.randomBytes(4).readInt32LE();
} catch (err) {}
}
}
throw new Error('Native crypto module could not be used to get secure random number.');
};
/*
* Local polyfill of Object.create
*/
var create = Object.create || (function () {
function F() {}
return function (obj) {
var subtype;
F.prototype = obj;
subtype = new F();
F.prototype = null;
return subtype;
};
}());
/**
* CryptoJS namespace.
*/
var C = {};
/**
* Library namespace.
*/
var C_lib = C.lib = {};
/**
* Base object for prototypal inheritance.
*/
var Base = C_lib.Base = (function () {
return {
/**
* Creates a new object that inherits from this object.
*
* @param {Object} overrides Properties to copy into the new object.
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* field: 'value',
*
* method: function () {
* }
* });
*/
extend: function (overrides) {
// Spawn
var subtype = create(this);
// Augment
if (overrides) {
subtype.mixIn(overrides);
}
// Create default initializer
if (!subtype.hasOwnProperty('init') || this.init === subtype.init) {
subtype.init = function () {
subtype.$super.init.apply(this, arguments);
};
}
// Initializer's prototype is the subtype object
subtype.init.prototype = subtype;
// Reference supertype
subtype.$super = this;
return subtype;
},
/**
* Extends this object and runs the init method.
* Arguments to create() will be passed to init().
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var instance = MyType.create();
*/
create: function () {
var instance = this.extend();
instance.init.apply(instance, arguments);
return instance;
},
/**
* Initializes a newly created object.
* Override this method to add some logic when your objects are created.
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* init: function () {
* // ...
* }
* });
*/
init: function () {
},
/**
* Copies properties into this object.
*
* @param {Object} properties The properties to mix in.
*
* @example
*
* MyType.mixIn({
* field: 'value'
* });
*/
mixIn: function (properties) {
for (var propertyName in properties) {
if (properties.hasOwnProperty(propertyName)) {
this[propertyName] = properties[propertyName];
}
}
// IE won't copy toString using the loop above
if (properties.hasOwnProperty('toString')) {
this.toString = properties.toString;
}
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = instance.clone();
*/
clone: function () {
return this.init.prototype.extend(this);
}
};
}());
/**
* An array of 32-bit words.
*
* @property {Array} words The array of 32-bit words.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var WordArray = C_lib.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of 32-bit words.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.create();
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 4;
}
},
/**
* Converts this word array to a string.
*
* @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
*
* @return {string} The stringified word array.
*
* @example
*
* var string = wordArray + '';
* var string = wordArray.toString();
* var string = wordArray.toString(CryptoJS.enc.Utf8);
*/
toString: function (encoder) {
return (encoder || Hex).stringify(this);
},
/**
* Concatenates a word array to this word array.
*
* @param {WordArray} wordArray The word array to append.
*
* @return {WordArray} This word array.
*
* @example
*
* wordArray1.concat(wordArray2);
*/
concat: function (wordArray) {
// Shortcuts
var thisWords = this.words;
var thatWords = wordArray.words;
var thisSigBytes = this.sigBytes;
var thatSigBytes = wordArray.sigBytes;
// Clamp excess bits
this.clamp();
// Concat
if (thisSigBytes % 4) {
// Copy one byte at a time
for (var i = 0; i < thatSigBytes; i++) {
var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
}
} else {
// Copy one word at a time
for (var j = 0; j < thatSigBytes; j += 4) {
thisWords[(thisSigBytes + j) >>> 2] = thatWords[j >>> 2];
}
}
this.sigBytes += thatSigBytes;
// Chainable
return this;
},
/**
* Removes insignificant bits.
*
* @example
*
* wordArray.clamp();
*/
clamp: function () {
// Shortcuts
var words = this.words;
var sigBytes = this.sigBytes;
// Clamp
words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
words.length = Math.ceil(sigBytes / 4);
},
/**
* Creates a copy of this word array.
*
* @return {WordArray} The clone.
*
* @example
*
* var clone = wordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone.words = this.words.slice(0);
return clone;
},
/**
* Creates a word array filled with random bytes.
*
* @param {number} nBytes The number of random bytes to generate.
*
* @return {WordArray} The random word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.random(16);
*/
random: function (nBytes) {
var words = [];
for (var i = 0; i < nBytes; i += 4) {
words.push(cryptoSecureRandomInt());
}
return new WordArray.init(words, nBytes);
}
});
/**
* Encoder namespace.
*/
var C_enc = C.enc = {};
/**
* Hex encoding strategy.
*/
var Hex = C_enc.Hex = {
/**
* Converts a word array to a hex string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The hex string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.enc.Hex.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var hexChars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
hexChars.push((bite >>> 4).toString(16));
hexChars.push((bite & 0x0f).toString(16));
}
return hexChars.join('');
},
/**
* Converts a hex string to a word array.
*
* @param {string} hexStr The hex string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Hex.parse(hexString);
*/
parse: function (hexStr) {
// Shortcut
var hexStrLength = hexStr.length;
// Convert
var words = [];
for (var i = 0; i < hexStrLength; i += 2) {
words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
}
return new WordArray.init(words, hexStrLength / 2);
}
};
/**
* Latin1 encoding strategy.
*/
var Latin1 = C_enc.Latin1 = {
/**
* Converts a word array to a Latin1 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Latin1 string.
*
* @static
*
* @example
*
* var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var latin1Chars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
latin1Chars.push(String.fromCharCode(bite));
}
return latin1Chars.join('');
},
/**
* Converts a Latin1 string to a word array.
*
* @param {string} latin1Str The Latin1 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
*/
parse: function (latin1Str) {
// Shortcut
var latin1StrLength = latin1Str.length;
// Convert
var words = [];
for (var i = 0; i < latin1StrLength; i++) {
words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
}
return new WordArray.init(words, latin1StrLength);
}
};
/**
* UTF-8 encoding strategy.
*/
var Utf8 = C_enc.Utf8 = {
/**
* Converts a word array to a UTF-8 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-8 string.
*
* @static
*
* @example
*
* var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
*/
stringify: function (wordArray) {
try {
return decodeURIComponent(escape(Latin1.stringify(wordArray)));
} catch (e) {
throw new Error('Malformed UTF-8 data');
}
},
/**
* Converts a UTF-8 string to a word array.
*
* @param {string} utf8Str The UTF-8 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
*/
parse: function (utf8Str) {
return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
}
};
/**
* Abstract buffered block algorithm template.
*
* The property blockSize must be implemented in a concrete subtype.
*
* @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
*/
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
/**
* Resets this block algorithm's data buffer to its initial state.
*
* @example
*
* bufferedBlockAlgorithm.reset();
*/
reset: function () {
// Initial values
this._data = new WordArray.init();
this._nDataBytes = 0;
},
/**
* Adds new data to this block algorithm's buffer.
*
* @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
*
* @example
*
* bufferedBlockAlgorithm._append('data');
* bufferedBlockAlgorithm._append(wordArray);
*/
_append: function (data) {
// Convert string to WordArray, else assume WordArray already
if (typeof data == 'string') {
data = Utf8.parse(data);
}
// Append
this._data.concat(data);
this._nDataBytes += data.sigBytes;
},
/**
* Processes available data blocks.
*
* This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
*
* @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
*
* @return {WordArray} The processed data.
*
* @example
*
* var processedData = bufferedBlockAlgorithm._process();
* var processedData = bufferedBlockAlgorithm._process(!!'flush');
*/
_process: function (doFlush) {
var processedWords;
// Shortcuts
var data = this._data;
var dataWords = data.words;
var dataSigBytes = data.sigBytes;
var blockSize = this.blockSize;
var blockSizeBytes = blockSize * 4;
// Count blocks ready
var nBlocksReady = dataSigBytes / blockSizeBytes;
if (doFlush) {
// Round up to include partial blocks
nBlocksReady = Math.ceil(nBlocksReady);
} else {
// Round down to include only full blocks,
// less the number of blocks that must remain in the buffer
nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
}
// Count words ready
var nWordsReady = nBlocksReady * blockSize;
// Count bytes ready
var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
// Process blocks
if (nWordsReady) {
for (var offset = 0; offset < nWordsReady; offset += blockSize) {
// Perform concrete-algorithm logic
this._doProcessBlock(dataWords, offset);
}
// Remove processed words
processedWords = dataWords.splice(0, nWordsReady);
data.sigBytes -= nBytesReady;
}
// Return processed words
return new WordArray.init(processedWords, nBytesReady);
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = bufferedBlockAlgorithm.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone._data = this._data.clone();
return clone;
},
_minBufferSize: 0
});
/**
* Abstract hasher template.
*
* @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
*/
var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*/
cfg: Base.extend(),
/**
* Initializes a newly created hasher.
*
* @param {Object} cfg (Optional) The configuration options to use for this hash computation.
*
* @example
*
* var hasher = CryptoJS.algo.SHA256.create();
*/
init: function (cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Set initial values
this.reset();
},
/**
* Resets this hasher to its initial state.
*
* @example
*
* hasher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-hasher logic
this._doReset();
},
/**
* Updates this hasher with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {Hasher} This hasher.
*
* @example
*
* hasher.update('message');
* hasher.update(wordArray);
*/
update: function (messageUpdate) {
// Append
this._append(messageUpdate);
// Update the hash
this._process();
// Chainable
return this;
},
/**
* Finalizes the hash computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The hash.
*
* @example
*
* var hash = hasher.finalize();
* var hash = hasher.finalize('message');
* var hash = hasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Final message update
if (messageUpdate) {
this._append(messageUpdate);
}
// Perform concrete-hasher logic
var hash = this._doFinalize();
return hash;
},
blockSize: 512/32,
/**
* Creates a shortcut function to a hasher's object interface.
*
* @param {Hasher} hasher The hasher to create a helper for.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
*/
_createHelper: function (hasher) {
return function (message, cfg) {
return new hasher.init(cfg).finalize(message);
};
},
/**
* Creates a shortcut function to the HMAC's object interface.
*
* @param {Hasher} hasher The hasher to use in this HMAC helper.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
*/
_createHmacHelper: function (hasher) {
return function (message, key) {
return new C_algo.HMAC.init(hasher, key).finalize(message);
};
}
});
/**
* Algorithm namespace.
*/
var C_algo = C.algo = {};
return C;
}(Math));
return CryptoJS;
}));
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "yLpj")))
/***/ }),
/***/ "IpFe":
/*!*********************************************************************************!*\
!*** ./src/pages/Competitions/Detail/components/InitGitLink/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 = {"formWrap":"formWrap___2wjQc","tips":"tips___1ubm0"};
/***/ }),
/***/ "JGo8":
/*!******************************************************!*\
!*** ./node_modules/antd/es/upload/style/index.less ***!
\******************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/***/ "JWDV":
/*!****************************************************!*\
!*** ./src/assets/images/icons/charpter-white.svg ***!
\****************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/charpter-white.5fa14f93.svg";
/***/ }),
/***/ "JeFH":
/*!********************************************!*\
!*** ./src/assets/images/icons/blibli.png ***!
\********************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports) {
module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGgAAAAwCAYAAAD9wT87AAAe2UlEQVR4XtVcB5QUVbr+blV1T+ieGWaYBAwgOSgooJLjENeA6a2KCVfZNbum3VXXsG9VdFfc1TXtGlfXLCKgEiRnUAHJWRzAyTl3V9V957vV1dPTM+M4Hn2Pd8/xIHRV9f3vn77/+/9qgVaWlHIggHMB+AA8K4TIbe2ek/FzKWUmgLGw7THQtLlCiBUn4z6j9ySa26SUMg3A+ZDyaljBMTC87mXrAUwSQtT+fxBOSqmbpjnaMIyrYJnToRvtQ/sOAJgihFh1ssvRSEFSysEAroJlXQZdp8VhXUEAS07UYGavBPSIQz10vacQ4vjJLJiUMgPAhZByJoQYyr0erZFYmFOFZK+GK7szGOB3Qoi/nsxycG9KQVLKKyDltbDMbBge5NYD87+twvxjNdhbZiIoJZZMysRpPqsShreXECL/ZBRMSjkAwM2wzIugG2k2gOW59fjgaDU2FNbjRI2Fm/r48eigdtz+TUKIF05GOSL3JKSUDwN4SALYXBRQwqzIrUNBvQ1DAIYm4BHAJxMz0TPOLoJu9BFClJxsglVVVWXGx8d/IYTIOl4rsSCnGvNzarCvIghLAl5NoN6WuKVPAu4dkMjtXyuEeP1kk6NJDpJSHgTQ8+Ht5Xj5UBWoqBhNQAsFP/6dwi2alIlTYq1caEY/IUT5zyGYlLIvgD4AugLIgm0zF3qgaccDgcCbMTExu1v6Xinl6YDc/lWxiWvWF6E04BiYxxUEQK0lcUe/BNx9qlLQFUKIt38mOVIAnA6gG4AugM104Qe0ajo1gA+FEHTwVhc96CoAbzy9txJP7KpAPKWKWFRQrCawZEoHZHnN4yEFVbX65DZeIKW8DVI+DiHimrtVSnlCCDFUCHGihc+TYJl7jwf1DlOW5KHWltCiLqSCfndqIm7vlwDLsi41DOP9Nm6z1cullL0BLATAP1tavxZCvNTqw5iDpJSnwrZ2rC60tKvXFTayOCc/AXGGwNIpHdDRCOZA9/QXQtASfrIlpdQg5TYpxMDXDlVhf7mJ/DoLZQEbNabEnf0TMbVTLL+PCHJZy15kL5EQk6ctK8De8mATWaige09LxC19lYIuMQxj7k8mROhBUsrbAfydOW/pd3XIr7VQXG+jImjjtHYePHlmMmDb7wpdv/yHfDcV5Idt7c0NalmTl+Sh2pTh8OYqiF5FBXXwWEeh6acKIWp+yMPbco2U9icS4pyJSwuwsywQDrM1lsQDA5JwW78EPu4iIcS8lhUkHwfw+1s3l2LesRrE6o2jARV032mJuLlv689qy94bRRwpL2YIe3F/Fe7bVqYiEqMs82CvBAOrpmQA0vpUaAZry1ZXCMXZS22ISVM/L8CBSlPFbnfRg/53FCQfAXD/7VtKMTen4XB5qDf38eO+AUm0+usMw3j1exR0GYB3nttXicd2VSDu/0ZB/WCZuzaU2NqMNYUKZHFRQR3jdKyclgGvZa0XhjGqVe2EYbZlzYGm3fmbjSX47EQtYiIEaxTiPNa3IQ/6SUOc46nyUgDvRh8uFXRlNx+eGKKg8d1CiDktCRYIBM7wGPrW5flBce36IgVuIldkiANwsRDiox9ySG25RkqZEIpInRiRGKKFAGwJtPNqWD4tE8nC3AXNOEMIYbX2bLcOugbA63N2V+CpvZWNLK8RSPCYx6ErFPdzgIRBsK2tn+ebuG5Dw+HWWRLnZsXhxWEERnhMCHH/93hQMqzggaP1RuovPs9TsDpSRZEgAcAvhRAftHZAP+ZzadurLCHGTl5agMNVTkRyz3HxlA7o7LVyoOk/KJe7ChoKyE0Lj9fhpk0ljT0oBLs/m9QBp8SYuSEF/eQwW0oZDyuYc7BWb3/usjyY0qmiA7bEqLQYvD0mlWf1ohDixu9RkICUGwJCDJu4OB/HaixERrn/RZj9NIDbZq4vxvLcOnWeVBBR5fzsTPT3WaXQPb2FEEWtGYBSUHV1dYd4r+fA7hrNf8HyfBCgu5bHB//UhaqUkoVIOoBhAPrRBmzbLtSAWyul1mnSkjzk19nqcIO2xMBkLxZOSCP6eU/oOvNMRI6UQgjBbaolpXwZwHUz1hRhXWF9ozBHBf2UhaqUMgYA+T3Wb8Nh2+2haWUASDBf/PDX5XjpYFU4ItHo3hmThuFJMgiPt4sQIu/7ZOFnrgcZsO3tFdBOzV6Up2BhZKFKzX+cnYFTfXZFdV2gt9/v/1FUjySdBDkLltUVUqbD8BjRFsRYfeGqQmwvCSiYTKG6+XR8PjkDBuQ2CLEItt0NQrSDgAe2TIG0bWh6IYTYzLINwB/u31qG149UNwrXVND1Pf340xlJ/NofTfXU19f39Xq9s2Gb/WHLTjA8ityLXm8crsa928rCe6i3JF4a3h5TM3UJ3fMEbDsTQhB3xwOaH9KKhRAVEPpRAK8KIdaEQ7S07XkQ4oJzlxcqmBtZgfPQPhiXjiGJdn2IizvWmmtGfy6lZFW9RwKxJC4Lak10idPw6M5yFNbb+GXXeFzcNV7ddsvmEnx8rFbBZKKf9FgNi7LTkRLTUHrSy/k3opWgDSRqzt8BnABkp1cPVeOB7eVNFBQBOO4RQjzZVjlCXsrcdUlREDhaaSIzVmDZd3X49EQtuvkN/On0JFU7rs6rw9Xri8NnSQN5cnA7XO6QtY0WQ0CpBcTrjoUBKCAb0aAgKWfT8m7cVIKFx53DcRfDzH9Gp2F0CiQML0HC/rYKpmgcK7hnY4kUV68rUjH53yPb456vSrG33MRV3X145uxk9di/7KrA0/scsELj8BsCn2WnI8unozJo48ZNpThYaeLBgYnYWFiPuTm1qgh8a0wqvJBFsILJK4ulPnNdUSNDI+C4oHMcnh2qAMd/CyEeaqscIQV9CuAXF64sxLqCekUd8bQe31WBjDgNyyZloFO8joMVJs5fUYiAdMAKEd0fByTiJqcOwz8PVOH1w1U4MyUGl54Shxs3l6qQPOesZIzLYItHnBGpoGvpVpGH426ervmv4e0xrRNDrhgshNjWVsEU/LTMfTlBvePUJXmqsv7nsBS8eaQaq/LrMSkzFm+Odto17x2twV1fliojoSKJguaPT0PfJI8SctLnBYoE/duZyYoxeOVQNXonGlg5NQMeKbfBtjKP1GkdiOSCIbDB51KOiR1i8dpI9T1/F0Lc0VY5Qgr6C4B7fr2xRBXE/9UlHqPSY3DP1jL4DIF549JwajuPYkKmLisI51N6ENn0+weoEKsMcfaucozJiFVsyTXrihXyZBg8t5MHEPrASAWNAbD6g6M1uCN0OO7m+WAexi9PUSFoLGPjjxLMNldYQh9PtmBPWQCzB7XDzrIg3jlag8EpHiwYn6YKu/UF9bhibTGMUMyiF707JhVnp3ph2sD0lYX4orgejw9uh5wqCy8erELfRAMrpmRAk3I5YPtroA9lPs0LgQ3ul4hwWGoM3h+bSsDxutB1GmWbl5TySgBv/m1PpTrg4WkxuKG3Hzdsckj+N0elYkxGjArPF6wsxI5SJ2XwHGd08+GvTk2Hlw86bMPZqTGKgmI4DNAZRrTHtEwD0IwBkQrqBjO4f0s5PJeuLmwCTx8+PQmzevn53POFECQD27yklH8D8NvrNhRj/rFaxSxz46y9uvsNLMpOQ5JXw+FKE+etKAzXMTzYV4a3x6SOTnS+bE0RluXW4bFB7VBYZ+Mf+yrRN8nAyikZENL6BEJUAtrl01cUYnvocHgfQzUtm+ESkB8LoV3YZiEcpDgYtvXVkrwgfrWhGF19BmYPSsJvNpWi0rTxzFnJ4XxKL1sUKv7pwdM6xeFfw1WIxYff1uCWLaUYlOzBg6cn4ep1xUqJLzUo6LRIBfnJBp8IGllTluaiNlQB80G86bd9E3DPaYqmv0YI8caPFGwmgNfo2k/srsDlp8Qr6/n91jKkxmjq4Dr79CahgbnjqQYPBhmPD3Nq8OczklAdlHhyTwX6JXlCCpLzIcQOAA+wplsQkU9p0V18uvI0XVqrhWaM+5FyJMMyD3xTr6VOXZoHQwhVSN/5ZamqvR6MyDN/+roc/wpB7UYeDCgjo1JoNGwiXrWuSHGhLSlIwLLWB3R9+ITF+ar76OIEKmhmD5/bibxTCEFPaPOSUp4FaW9ZeCKAK9cWIjszFtf38mPWphIFBOaOS1PJngfJ5LorhCb5/Q8NTMKveysPxj1fluLFA1UqxFF5j+wsR/8kD9ZOy2SIWwCHwnl99s4KPLu/gRlhqGwf49AticLeAaExn7ZKt0QLKqXkWa0L6vqIMZ/l43BVEO+NTsXsXRXYURpU3OEDpzt55pWDVXjwawdN0oO5zwUT0lTk2FJUjwtWFqFPoqFY7l+uLkKVaePVkak4p0NUiOPDpGW9BU2bcdGqQnxV3AC1eQjnd47D8w76mS2EuK/N2nFCQxos8+CROi3pmT3lGJcRi3GZMThQEYTf0NAtwQjDYoaOz79zqnAq6Na+CfiD48F4dl8l3v6mBvcPSFR55aUDVciM1/HyiPZU0GIIQVZ7Fa8hSnRJUwIO/j97W508P5xuaU5WaVkvQdOuZzTgc6/p4VP1I/dDUjQjTle3LT5Ri1kbHXaGhpcVr6tQ7vdoCuUxb9Eo7+yfgPu3laOo3sJ9A5MwJt3DQqIBxSkFSevPgPbHyDqE/67olvQYvD1a0S0vCyFm/UgFMe0vAHBOa/f/cVsZXjvsFJqKMO3uwxODneRKS9SEaJQnSeqSlARAmuVvsM0ja4tsjZ7q1nSN6Ra7HLpBuoX1RpuXlJKMxluhcqzF+1lwX7LaKSu4Rw6tUEHpcboqIUwpm5C6vFYA3wEYFD3Vo6B2dGhwkqsXn2Wn8VsWCE2b3maJQjdIy3oWmnbzoUoTu0sD4J8Mp2VBG+MzY1U9xPX8/ipVxFJBTK6/6BSHf4aSKwWl0tgrMm2pckCiV7iCPsueECwz51Cd3v6cz3PDvB6fy+v/MyYNo5Jhw/D2FUKw5d/mFQgEzvZ4PBtKA7bOsMYocLTKVF6UYGi4f2CiYq+P11j4xfICVAUdVpvjBJ9MSEP3BIdEoWyUg+iNy+fRVLiHo6Ah0QrKZu76z5Fqlbjd0MB7WXitmJoBr5QbhaaNaLNEroKkZKv3+ivWOkhMF05Di0ZwVmqMgtr8+8c5DsJhLUQPJpR9zyFMwVKAwIAWqLwJAt0SdLwxJg0+2NugaUMh7a8qpDYgmrpiuH5uaAqmdyYiFMOEQw+1eUkpR3IqjWiUYcqlxnig3Ne8cakYmhajCutpywuVEfIafv7h2FSckeLF8WoLszYWozhgKzaEi2TJY4OSMaFDDEzTHButIDabdq8sssQ16xoof35hokdg2bQOSBXBQ8Lw9mqzRA0Kuo1h6IHtZSAdE2kEGaR0JqarMECGYMba4jBhyuRKwpR10ltHqnHXV2WID6EY7o/UysppHZCpBQ/C8PRh11IKfdoUNiErzHBNRc8jFUNwYprmVI/Hs+THyCKl7MjWxs4qzXfhinwVwtzD5HfMGZKMy7rFK2WRcXDhPg3qjVGpGJsRg9waC5OXFaAiKMPhmt7E8uFXPX1sUJ4TraBUwsd9NVry+cvyQHjDC9xqfmF2Jnr7ZAU0/WYyF5ZlBXVdZ+uBtHkhgJLWUJGUcjyAFe+G2ILIBO4RAgsmpKJ3ogeHKkyct7IAAduxSCZXwvAEj8CSUOL1hhTkTh4tntwBXY3AMeGN6SKlfB7AjVeuLcaagrpwnHc6tAm4zxm9eoZgIiQiaT1WmoW5ublFHTt2/N62vpTSoJdWSW1g9uI8VY+5XsTvuK1vAn4fAjXXbyjGkhDgoQeTaiLlRDZl2rJCfFcbgZhNiQcGJuGGPgqxXhKtIC9sc0exbfSZuCgX5cGG+QTGblbgrFuaLCtILZZBEzmAthuatgXAJgC7opt7UsosWOb+rytF/EUr8xs11BTnNyoVozNiUFRnYeryQpTUO77PeM7kSnS0pSigilXG9EgD+nRSB/SMDeZB92ax+0p67O4vy/Du0eowt8jDu7RrPJ46y+H9Gi9m7WA9OH+uaQcgxVZo2kYAXzU3TSSl/A/Ht/5rdRE2FzW0NqiECzvH4x9Dne+4f1sZXncBjynxyKAkXNvTr8IzywnSVW5rnB70+9DkkRoNa7LFEB2TvSQfR6ut8HwCFXR1D78q9MgxsQ3AhMeDIyLJ8nnQJUFHsoMunWWrIRNO4XDQYzWngVQNIe2vK0P5gUx2ZL311JBkXNotXiXPc1YUKhDBz0kiMrn2SDAUPD1vRUGYZ6MH8WvnT8xEvzirCIansxr9Bd5+anclntxbEQ6HlKN/Oy+u6BavWHQeJnOyz9CQGqujY7yBLgkecIgozJ1bZiU0fSOEmA/gUyHEtxRPSnkngDkPbCvHq4cb+j7MmUNDlBIP+B97SQk5I200kDv7JeAuZzYPl68pwvqIvlXU5zObKsiy3oCmXXXxKvJdgUYQkBqnYoii3EUrpiAMN0keTYUi4nomyKEZcch05+5tcz804zXCdABPsKl2yaoibClusDxu7u7+ibijv8P2snDbVFQfhslMroNSvMirtVTiLQ84YcWN//MmZGCAzy6F4ekCgHPmq9/5pgZ3R9RCym4kFI0ULQc/Y5jlQTIf9kr04Mz2XgzPiMOApJDlUVm6MS8YDD7r8XiINFa/d7RGuOQun+H2sBiSmRvfP1qjWAYCnqiiHzdvLlG0l9s9iKr5rm+qIOlM1xCZfBLVdmgmJoT/ycX5lnSUyAezah+c4sW5WfGY2iUOPgVx7G+gaXyFZURkrcMHcXNXdPPhLyEy8abNJVgQ2jyN4/WR7RUUJ2SdtrxAQVh6l2svH43PwOl+uxyGh72nNNjmvpWFtrhmXWGTWqM1WYhc6W18NsEIPZdM+PSufvTya4AVtKF7lsK2sr8utz00aNdQ3AERNySvyqvDNaG+ED32vKw4vODMWOCh0ESvm4sV493bj/sHKibixuYUdAOAF6Lbtc0JFIlcmvvchcG8jo2sy06Jx8zeCfCFYke0dTOsTciMxb9HOW0HjiO/dMgJHRTs6RAJGc0Su8Yxd3w6BiXKSuieHirxm8HDe2q0xOlRbfwmYT0CgbUkJ5VFKEwyl3u8oU8CBrRzapnSehtTlxegIMScu6Dq4/FpiiPcWRoE2RlmUxrayLQYvBMqGUj0so8UqaAbeoWpojuaU9D5DOccvPtzqFBsbtOM26xhyoO2StbMEU0eFnEjvYqxmXCZMHdkeoxqa7PKdhc3f1o7L+YTTgsWq5V4dKez+Wg+jiTjyvw6lQe5qDR2fc9MlNUwPD0BFMO29hVYeveJi3OV10VNYYW/l8+vNKkAp6qPGqdrJD4Pn8aSYAjF7nOgkgn+stVF2BgBFKhQth0IeFjvqGLVlGCEcUqGdAX93/3GKRkiFeS25W3bvrc5BZ0NyM3zcupw65aSJtOZ7mEwRr8wNEX1c5Z8V4ttJQGF+qIH1qOVSyUxIb86IgUDkr3IXpoftjx3uI+MBS2VdPxvv2iI3bf2ScAfHHiMO74oxQffNgw48t73xqbj7CS7FoaX7zB9J01zY0DXh41flN8IykbuiV5Lqp9Tn5wJZIf0WLXDn5IiakmpjA40mut6+vDIoHaNvJ33Rno8cyVzZm6t81wW/Qx/CR5NFevkHd0ZPj7zVz39iqlnBGxOQd3ZF9pQCmPGmoIw/IsUyn0Dgl/S1e+4OamOJSfqlJD7Kkz1by1ZIjcxOdTZvDTC8sLt7YnpCmxExu7oZtdjO8rx3IHGEzPvjk3DsCRZF1LQCWnbH0GIC5ubs3DlIay9JwKYENZTSQuP1SqPYK0SPQDp3suQReiwYnK6Ipdd5oOfc78kc2/qk6A8k/0twmlGHRofzy4zTse24gAuWeNEESqD913bw1E6gEeaU1AKK+QDofk0WmZzoYskH2sWkqiRix7yRVFAdQpzqhvPpbnXEUGNSY/BW6NTG1meS2Z+NC4NA5I9qhN58aoiFbvJVU3uGItXRjj5iQz2wzsahkIYUt4Zm47h7WR4sEVKSV7uZhUO8xxmPHrR0i/uEo+nQ/MQkZ/nVJsKIr//bU2TQXxe5+6XHs9zohLckTUe9KyefjzseEIYTtMrvRoUpUWU+E2liXNXFKIuNGTJ+8iMk00g2m1OQSxWdxbZRm8Wq6QhmnNzh85oh8u6NZ5QIXTlLNjf91Y2mex0hWdTikPst/ZLULxaZIs9Eq19W+Vsntczdg9J8aqeEXNeJFfH51JBb49Jx4hkOwAjhm8B5kgp2RZ59M4vStUhRw/T8z4a1NntY/DBuNQmhsgcee/WMhURmosGBA0MjQuz05SXTF3mhDFeq1o0WXF4PoTWIuE0IwV5xbNSvYpc5dyCO+qmFNTdh8cc5v6pZvO6NM11AV0fOWFRPk5E0BCR1sUH3d43Ab8L0Rn8jNwS0R/Hj2itzT2c3tPDb+DDcWmqixqJcHh9ZPeU4YZwmuiI1trDr+PT7HR10Gvz63HVuoa5BSrorTHpGJksAzC8bCN868zhNWXnI+Wg5XcO0Uh+TmiGPOONQ9X4y+4K1cJuLsRxP/Tqv4eQJf9OApjhkddHd08f3F6OV0KIVPWwhrXHlE6xSt5zlheGR4R5rld392G2o6B/NK8g254LIS4i8thd1vQ9G94ZNcKkRlypnCNVZpO3CsKhzZJIi9Xx0vAUDGmvKlirPGjrfJ8nt9ZhFLhB9x0efgeti/PNZKzTYjUsmZiu6ivuiwMZbkihBb/ltBGCIQUdlVKy7/QJhzMeCnU1o0McrZmTOJ9mp6GLz1Dv8/x5RznmH69VRWtz0YP38JDZRAzxbWpMj/ex00tERtRK7yL7QWNlRGEbh0Uw5XpySDtc0d2nDI811JchUoDyX9XNh8edWvCF5hUk5XOcvKRFrA1ZRLRgbmh4dWQKnttXpV6fpBVHDjy691Agbur0ZA/+OiQZpyWzWwjONbAiunJGhOU5yMiP/z4jSVX6v95UonIRn8HD+mBMKrr4DQe6rnD6LG67Qs3uJUsTHhXiqKCz+eotK3WGmOZCHDfCZ88dm6qg9h+3l6mhlehXVyKNjAq9q38iZjkt+BO2bc/RNDw1L6c+jHzpmWkxDjtPg/oop0bVOxSYaeOWvn4FILhmbSjG4ojuccRw5cstKehBAH+6dUsp5kW8qxOpJB4eebgOcbqi0psLaS6lQgqI3NftpybB7zAmfHn3N7ZtX6tp2ov0vGdCg4pU5PSsOLzqzK6pxR81CNJrTaB9aFiY0JXexbEqV0Fvjk7D2BSYMLx80fmIlLIXrODedSVSvzLiXZ1oY6MVD2znwd4KE7Wm3fQtw1CByetGcMhlQJIaEwPkIUCws3oIZvDYvlo9gQM3zE0uA7F0UrpiIbiIbflfre30fZw5WuAPX5XhzW8cQleh1VPinTfxgH+3pKDf8E2C1tgEKoDJO9JruDGGG1oQc8yUjnG4rlcC+iTqpHlKoWlU/nMceJdSjgawhvnk42M1yIo3kBqroXeiF0NTlZftA+R+SMpix4PDj0KvghBZpo0uVNCByqCK+QpcjErD+BRuKIY56JDk/LcZPLCnRk+avjyv0UsB0Uri/Sw4Iw+EMjBSsBgelOLBzB5+nNfZfYXWfh/Q7uJvRvAHMyDlF3UQgx7dXoZYQ1NcXlqsgeyOsTTKenBWAjYhbxxs6YemG3B+EGQY5xo4ekbPZF7j/OEcR0FzW1IQmeCPommI5iyPnkQlURgqhxU26Y3JHeNwXhcfsuL4/p9pQTdIzfP9ngPuc6SU3AU7mo0bgCYrXg/Hi2dETrHyXVa+HS2l5Ft21+6usMBuhMtidE/UECdlDYSggk6oV1psa893Qb3rlCW54ZepouXg37l3d0aAfzL/cNSYZcT0LvEYnuqyvnIrIChHo/dbZYjDbPxslSFLAfGUEIIcZ3gppTpvd6zLqweOVZuI0TUVDRgSOzjVy5yWFKSmTNn6vv2LxlMx7jdEMtiZcbR6h/kdmh7nkIlctlUCiLnQNL7Xs7W5g6mrq+sTExNDg6gM9eE5xFEM4HhLL4pJKYdwvg5msCsgg4AwFceueyptKZ/XNO3pkIdqkPaXVdAGjfwkt1FTzeXveCAN7QYNp/gMDEzxYFhaLAaneaH8xTY5hrvasu1/5ebmzuvcuXOTn8KRUpLZ5sQpWVD+EgvfAKEcBWQ1mjUK554XYFvnw7YEhAhCSr6pYULTv2R6aklBAwC5Y3uJief2VyqtEoHGG5rT/4nVVN+EPaCsBB0pkT0gyyyDpq+HEB8DWNTSa/PNbbgt/yal5NkxyzI90VRVdI3+HSFpmyuk0MeTeGXnkspgrE/0aGgfyxxqoJPPQGe/BxxcDYtiBiQ042to2mfsZwkheGA/ywr9NhJlIBekZBFqOrZ5kgCFhYUJqampbAWzp9LCsgDLrgB/t0foByDkdkB1UrdFv5j0s0j1Ax8qpfxdqP/U8h1mIABN5EEYhyHELgBUBv87IAS98/9utUhA19TUZMXFxc0AcCZbIqG5A+YFvhvEMEQXVm4s6Jon6VKzA053dTI46OH8hMARhbwa5OCbboU/9e8//BRH8j9mLdQoDqqNCwAAAABJRU5ErkJggg=="
/***/ }),
/***/ "Jq4h":
/*!*******************************************!*\
!*** ./src/assets/images/user/qrcode.png ***!
\*******************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/qrcode.54870d9b.png";
/***/ }),
/***/ "K3mO":
/*!******************************************!*\
!*** ./node_modules/crypto-js/evpkdf.js ***!
\******************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory, undef) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"), __webpack_require__(/*! ./sha1 */ "3y9D"), __webpack_require__(/*! ./hmac */ "WYAk"));
}
else {}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var MD5 = C_algo.MD5;
/**
* This key derivation function is meant to conform with EVP_BytesToKey.
* www.openssl.org/docs/crypto/EVP_BytesToKey.html
*/
var EvpKDF = C_algo.EvpKDF = Base.extend({
/**
* Configuration options.
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hash algorithm to use. Default: MD5
* @property {number} iterations The number of iterations to perform. Default: 1
*/
cfg: Base.extend({
keySize: 128/32,
hasher: MD5,
iterations: 1
}),
/**
* Initializes a newly created key derivation function.
*
* @param {Object} cfg (Optional) The configuration options to use for the derivation.
*
* @example
*
* var kdf = CryptoJS.algo.EvpKDF.create();
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 });
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 });
*/
init: function (cfg) {
this.cfg = this.cfg.extend(cfg);
},
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
*
* @return {WordArray} The derived key.
*
* @example
*
* var key = kdf.compute(password, salt);
*/
compute: function (password, salt) {
var block;
// Shortcut
var cfg = this.cfg;
// Init hasher
var hasher = cfg.hasher.create();
// Initial values
var derivedKey = WordArray.create();
// Shortcuts
var derivedKeyWords = derivedKey.words;
var keySize = cfg.keySize;
var iterations = cfg.iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
if (block) {
hasher.update(block);
}
block = hasher.update(password).finalize(salt);
hasher.reset();
// Iterations
for (var i = 1; i < iterations; i++) {
block = hasher.finalize(block);
hasher.reset();
}
derivedKey.concat(block);
}
derivedKey.sigBytes = keySize * 4;
return derivedKey;
}
});
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
* @param {Object} cfg (Optional) The configuration options to use for this computation.
*
* @return {WordArray} The derived key.
*
* @static
*
* @example
*
* var key = CryptoJS.EvpKDF(password, salt);
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 });
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 });
*/
C.EvpKDF = function (password, salt, cfg) {
return EvpKDF.create(cfg).compute(password, salt);
};
}());
return CryptoJS.EvpKDF;
}));
/***/ }),
/***/ "KPFz":
/*!*****************************************************!*\
!*** ./node_modules/antd/es/radio/style/index.less ***!
\*****************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/***/ "KQeH":
/*!************************************************************************!*\
!*** ./node_modules/@ant-design/icons-svg/lib/asn/DownloadOutlined.js ***!
\************************************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// This icon file is generated automatically.
Object.defineProperty(exports, "__esModule", { value: true });
var DownloadOutlined = { "icon": { "tag": "svg", "attrs": { "viewBox": "64 64 896 896", "focusable": "false" }, "children": [{ "tag": "path", "attrs": { "d": "M505.7 661a8 8 0 0012.6 0l112-141.7c4.1-5.2.4-12.9-6.3-12.9h-74.1V168c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8v338.3H400c-6.7 0-10.4 7.7-6.3 12.9l112 141.8zM878 626h-60c-4.4 0-8 3.6-8 8v154H214V634c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8v198c0 17.7 14.3 32 32 32h684c17.7 0 32-14.3 32-32V634c0-4.4-3.6-8-8-8z" } }] }, "name": "download", "theme": "outlined" };
exports.default = DownloadOutlined;
/***/ }),
/***/ "KXlV":
/*!*******************************************!*\
!*** ./src/assets/images/account/job.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/job.65c6034f.png";
/***/ }),
/***/ "KeDT":
/*!**********************************************************!*\
!*** ./src/pages/Competitions/Detail/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___3otMp","flex_space_between":"flex_space_between___2nig-","flex_box_vertical_center":"flex_box_vertical_center___3opWF","flex_box_center_end":"flex_box_center_end___1u2JP","flex_box_column":"flex_box_column___1RMsI","wrp":"wrp___-Shy4","bg":"bg___3aDMI","commonimg":"commonimg___15xnD","titlesize":"titlesize___2x92E","timesize":"timesize___3GFem","flex1":"flex1___1D3Li","buttonsize":"buttonsize___3oghG","myteam":"myteam___v6SIK","bootmdetail":"bootmdetail___3hk9v","flex6":"flex6___2iMiQ","menuItem":"menuItem___20c2q","spanprev":"spanprev___1dQoJ","spannext":"spannext___3fFnS","divwidth":"divwidth___1Dk29","receiveclick":"receiveclick___3mYYR","receivealready":"receivealready___20cCL","bkfff":"bkfff___WkCDR","ant-input":"ant-input___Zl9Xd","onediv":"onediv___2hHLH","onetop":"onetop___73xTC","towdiv":"towdiv___nqi1b","towtop":"towtop___pPhtO","threediv":"threediv___2G0u0","threetop":"threetop___2DsrB","imgradius":"imgradius___2WlXC","prize":"prize___1al1u","spanrightradius":"spanrightradius___3VHYc","bottomItem":"bottomItem___1NfPd","myTeam":"myTeam___2A-RJ","downloadpdf":"downloadpdf___1BQ_n","teamItem":"teamItem___220Fc","dash":"dash___3pxuh","modal":"modal___27esx"};
/***/ }),
/***/ "KmBX":
/*!******************************************************************!*\
!*** ./node_modules/@ant-design/icons/lib/icons/FilterFilled.js ***!
\******************************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireWildcard = __webpack_require__(/*! @babel/runtime/helpers/interopRequireWildcard */ "284h");
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "TqRt");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/objectSpread2 */ "3tO9"));
var React = _interopRequireWildcard(__webpack_require__(/*! react */ "q1tI"));
var _FilterFilled = _interopRequireDefault(__webpack_require__(/*! @ant-design/icons-svg/lib/asn/FilterFilled */ "CP8R"));
var _AntdIcon = _interopRequireDefault(__webpack_require__(/*! ../components/AntdIcon */ "KQxl"));
// GENERATE BY ./scripts/generate.ts
// DON NOT EDIT IT MANUALLY
var FilterFilled = function FilterFilled(props, ref) {
return /*#__PURE__*/React.createElement(_AntdIcon.default, (0, _objectSpread2.default)((0, _objectSpread2.default)({}, props), {}, {
ref: ref,
icon: _FilterFilled.default
}));
};
FilterFilled.displayName = 'FilterFilled';
var _default = /*#__PURE__*/React.forwardRef(FilterFilled);
exports.default = _default;
/***/ }),
/***/ "KmYQ":
/*!***************************************************!*\
!*** ./node_modules/crypto-js/pad-zeropadding.js ***!
\***************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory, undef) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"), __webpack_require__(/*! ./cipher-core */ "OLod"));
}
else {}
}(this, function (CryptoJS) {
/**
* Zero padding strategy.
*/
CryptoJS.pad.ZeroPadding = {
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Pad
data.clamp();
data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes);
},
unpad: function (data) {
// Shortcut
var dataWords = data.words;
// Unpad
var i = data.sigBytes - 1;
for (var i = data.sigBytes - 1; i >= 0; i--) {
if (((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) {
data.sigBytes = i + 1;
break;
}
}
}
};
return CryptoJS.pad.ZeroPadding;
}));
/***/ }),
/***/ "Kvyg":
/*!********************************************************!*\
!*** ./node_modules/antd/es/progress/style/index.less ***!
\********************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/***/ "MlIO":
/*!********************************************!*\
!*** ./node_modules/crypto-js/x64-core.js ***!
\********************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"));
}
else {}
}(this, function (CryptoJS) {
(function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var X32WordArray = C_lib.WordArray;
/**
* x64 namespace.
*/
var C_x64 = C.x64 = {};
/**
* A 64-bit word.
*/
var X64Word = C_x64.Word = Base.extend({
/**
* Initializes a newly created 64-bit word.
*
* @param {number} high The high 32 bits.
* @param {number} low The low 32 bits.
*
* @example
*
* var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607);
*/
init: function (high, low) {
this.high = high;
this.low = low;
}
/**
* Bitwise NOTs this word.
*
* @return {X64Word} A new x64-Word object after negating.
*
* @example
*
* var negated = x64Word.not();
*/
// not: function () {
// var high = ~this.high;
// var low = ~this.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ANDs this word with the passed word.
*
* @param {X64Word} word The x64-Word to AND with this word.
*
* @return {X64Word} A new x64-Word object after ANDing.
*
* @example
*
* var anded = x64Word.and(anotherX64Word);
*/
// and: function (word) {
// var high = this.high & word.high;
// var low = this.low & word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to OR with this word.
*
* @return {X64Word} A new x64-Word object after ORing.
*
* @example
*
* var ored = x64Word.or(anotherX64Word);
*/
// or: function (word) {
// var high = this.high | word.high;
// var low = this.low | word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise XORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to XOR with this word.
*
* @return {X64Word} A new x64-Word object after XORing.
*
* @example
*
* var xored = x64Word.xor(anotherX64Word);
*/
// xor: function (word) {
// var high = this.high ^ word.high;
// var low = this.low ^ word.low;
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the left.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftL(25);
*/
// shiftL: function (n) {
// if (n < 32) {
// var high = (this.high << n) | (this.low >>> (32 - n));
// var low = this.low << n;
// } else {
// var high = this.low << (n - 32);
// var low = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the right.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftR(7);
*/
// shiftR: function (n) {
// if (n < 32) {
// var low = (this.low >>> n) | (this.high << (32 - n));
// var high = this.high >>> n;
// } else {
// var low = this.high >>> (n - 32);
// var high = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Rotates this word n bits to the left.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotL(25);
*/
// rotL: function (n) {
// return this.shiftL(n).or(this.shiftR(64 - n));
// },
/**
* Rotates this word n bits to the right.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotR(7);
*/
// rotR: function (n) {
// return this.shiftR(n).or(this.shiftL(64 - n));
// },
/**
* Adds this word with the passed word.
*
* @param {X64Word} word The x64-Word to add with this word.
*
* @return {X64Word} A new x64-Word object after adding.
*
* @example
*
* var added = x64Word.add(anotherX64Word);
*/
// add: function (word) {
// var low = (this.low + word.low) | 0;
// var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0;
// var high = (this.high + word.high + carry) | 0;
// return X64Word.create(high, low);
// }
});
/**
* An array of 64-bit words.
*
* @property {Array} words The array of CryptoJS.x64.Word objects.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var X64WordArray = C_x64.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of CryptoJS.x64.Word objects.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.x64.WordArray.create();
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ]);
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ], 10);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 8;
}
},
/**
* Converts this 64-bit word array to a 32-bit word array.
*
* @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array.
*
* @example
*
* var x32WordArray = x64WordArray.toX32();
*/
toX32: function () {
// Shortcuts
var x64Words = this.words;
var x64WordsLength = x64Words.length;
// Convert
var x32Words = [];
for (var i = 0; i < x64WordsLength; i++) {
var x64Word = x64Words[i];
x32Words.push(x64Word.high);
x32Words.push(x64Word.low);
}
return X32WordArray.create(x32Words, this.sigBytes);
},
/**
* Creates a copy of this word array.
*
* @return {X64WordArray} The clone.
*
* @example
*
* var clone = x64WordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
// Clone "words" array
var words = clone.words = this.words.slice(0);
// Clone each X64Word object
var wordsLength = words.length;
for (var i = 0; i < wordsLength; i++) {
words[i] = words[i].clone();
}
return clone;
}
});
}());
return CryptoJS;
}));
/***/ }),
/***/ "N/JB":
/*!***********************************************************!*\
!*** ./node_modules/@ant-design/react-slick/lib/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 _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "TqRt");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _slider = _interopRequireDefault(__webpack_require__(/*! ./slider */ "ToDW"));
var _default = _slider["default"];
exports["default"] = _default;
/***/ }),
/***/ "NFKh":
/*!*****************************************!*\
!*** ./node_modules/crypto-js/index.js ***!
\*****************************************/
/*! no static exports found */
/*! exports used: default */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory, undef) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"), __webpack_require__(/*! ./x64-core */ "MlIO"), __webpack_require__(/*! ./lib-typedarrays */ "F+F2"), __webpack_require__(/*! ./enc-utf16 */ "qM6L"), __webpack_require__(/*! ./enc-base64 */ "ETIr"), __webpack_require__(/*! ./enc-base64url */ "wbyO"), __webpack_require__(/*! ./md5 */ "cv67"), __webpack_require__(/*! ./sha1 */ "3y9D"), __webpack_require__(/*! ./sha256 */ "lPiR"), __webpack_require__(/*! ./sha224 */ "GRuw"), __webpack_require__(/*! ./sha512 */ "1uat"), __webpack_require__(/*! ./sha384 */ "uGsb"), __webpack_require__(/*! ./sha3 */ "5hvy"), __webpack_require__(/*! ./ripemd160 */ "ELcG"), __webpack_require__(/*! ./hmac */ "WYAk"), __webpack_require__(/*! ./pbkdf2 */ "e7zE"), __webpack_require__(/*! ./evpkdf */ "K3mO"), __webpack_require__(/*! ./cipher-core */ "OLod"), __webpack_require__(/*! ./mode-cfb */ "ALsQ"), __webpack_require__(/*! ./mode-ctr */ "9OqN"), __webpack_require__(/*! ./mode-ctr-gladman */ "qu8F"), __webpack_require__(/*! ./mode-ofb */ "S6kV"), __webpack_require__(/*! ./mode-ecb */ "gb/T"), __webpack_require__(/*! ./pad-ansix923 */ "qBft"), __webpack_require__(/*! ./pad-iso10126 */ "oRuE"), __webpack_require__(/*! ./pad-iso97971 */ "jO9C"), __webpack_require__(/*! ./pad-zeropadding */ "KmYQ"), __webpack_require__(/*! ./pad-nopadding */ "uGxW"), __webpack_require__(/*! ./format-hex */ "bQjk"), __webpack_require__(/*! ./aes */ "wZgz"), __webpack_require__(/*! ./tripledes */ "pA7S"), __webpack_require__(/*! ./rc4 */ "w7YG"), __webpack_require__(/*! ./rabbit */ "E4JC"), __webpack_require__(/*! ./rabbit-legacy */ "PVpz"));
}
else {}
}(this, function (CryptoJS) {
return CryptoJS;
}));
/***/ }),
/***/ "NLgs":
/*!***********************************!*\
!*** ./src/utils/verifyLogin.tsx ***!
\***********************************/
/*! exports provided: handleVerify, handleVerifyLogin, handleProfleCompletedModal, handleProfessionalCertificationModal, handleCanShixunAddModal, AuthorizeModel, ShixunStatusModel */
/*! exports used: handleCanShixunAddModal, handleVerify, handleVerifyLogin */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return handleVerify; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return handleVerifyLogin; });
/* unused harmony export handleProfleCompletedModal */
/* unused harmony export handleProfessionalCertificationModal */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return handleCanShixunAddModal; });
/* unused harmony export AuthorizeModel */
/* unused harmony export ShixunStatusModel */
/* harmony import */ var _Users_xxq_node_forgeplus_react_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/regenerator */ "WmNS");
/* harmony import */ var _Users_xxq_node_forgeplus_react_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Users_xxq_node_forgeplus_react_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var antd_es_message_style__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! antd/es/message/style */ "miYZ");
/* harmony import */ var antd_es_message__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! antd/es/message */ "tsqr");
/* harmony import */ var _Users_xxq_node_forgeplus_react_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 antd_es_modal_style__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! antd/es/modal/style */ "2qtc");
/* harmony import */ var antd_es_modal__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! antd/es/modal */ "kLXV");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! react */ "q1tI");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var umi__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! umi */ "9kvl");
/* harmony import */ var _authority__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./authority */ "xKgJ");
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./util */ "1vsH");
/* harmony import */ var _ant_design_icons__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @ant-design/icons */ "RCxd");
/* harmony import */ var _assets_images_403Qrcode_png__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @/assets/images/403Qrcode.png */ "mOS8");
/* harmony import */ var _assets_images_403Qrcode_png__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_assets_images_403Qrcode_png__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _assets_images_Authorize_png__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @/assets/images/Authorize.png */ "1ZF9");
/* harmony import */ var _assets_images_Authorize_png__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_assets_images_Authorize_png__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var _assets_images_studnetqun_png__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! @/assets/images/studnetqun.png */ "WdTA");
/* harmony import */ var _assets_images_studnetqun_png__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_assets_images_studnetqun_png__WEBPACK_IMPORTED_MODULE_13__);
/* harmony import */ var _env__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./env */ "m3rI");
var handleVerify = function handleVerify(dispatch) {
if (handleVerifyLogin(dispatch) && handleProfleCompletedModal()) {
return true;
}
return false;
};
var handleVerifyLogin = function handleVerifyLogin(dispatch) {
if (!Object(_authority__WEBPACK_IMPORTED_MODULE_8__[/* isLogin */ "b"])()) {
dispatch({
type: 'user/showPopLogin',
payload: {
showPopLogin: true,
showClosable: true
}
});
return false;
}
return true;
};
var handleProfleCompletedModal = function handleProfleCompletedModal() {
var _user$userInfo;
var _getDvaApp$_store$get = Object(umi__WEBPACK_IMPORTED_MODULE_7__[/* getDvaApp */ "b"])()._store.getState(),
user = _getDvaApp$_store$get.user;
if (!((_user$userInfo = user.userInfo) === null || _user$userInfo === void 0 ? void 0 : _user$userInfo.profile_completed)) {
antd_es_modal__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].confirm({
title: '提示',
visible: true,
width: 530,
centered: true,
content: /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("div", {
className: "tc font16"
}, "\u60A8\u9700\u8981\u53BB\u5B8C\u5584\u60A8\u7684\u4E2A\u4EBA\u8D44\u6599\uFF0C\u624D\u80FD\u4F7F\u7528\u6B64\u529F\u80FD"),
okText: "\u7ACB\u5373\u5B8C\u5584",
cancelText: "稍后完善",
onOk: function onOk() {
window.location.href = "".concat(_env__WEBPACK_IMPORTED_MODULE_14__[/* default */ "a"].FORGE_SERVER, "/settings/profile");
}
});
return false;
}
return true;
};
var handleProfessionalCertificationModal = function handleProfessionalCertificationModal() {
var _user$userInfo2;
var _getDvaApp$_store$get2 = Object(umi__WEBPACK_IMPORTED_MODULE_7__[/* getDvaApp */ "b"])()._store.getState(),
user = _getDvaApp$_store$get2.user;
if (!((_user$userInfo2 = user.userInfo) === null || _user$userInfo2 === void 0 ? void 0 : _user$userInfo2.professional_certification)) {
antd_es_modal__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].confirm({
title: '提示',
centered: true,
content: /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("div", {
className: "tc"
}, "\u60A8\u9700\u8981\u53BB\u5B8C\u6210\u60A8\u7684\u804C\u4E1A\u8BA4\u8BC1\uFF0C\u624D\u80FD\u4F7F\u7528\u6B64\u529F\u80FD"),
okText: "\u7ACB\u5373\u5B8C\u5584",
cancelText: "稍后完善",
onOk: function onOk() {
Object(_util__WEBPACK_IMPORTED_MODULE_9__[/* openNewWindow */ "n"])('/account/certification');
}
});
return false;
}
return true;
};
var handleCanShixunAddModal = function handleCanShixunAddModal() {
if (Object(_authority__WEBPACK_IMPORTED_MODULE_8__[/* canShixunAdd */ "a"])()) {
return true;
}
antd_es_modal__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].warning({
centered: true,
width: 530,
title: '提示',
content: /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("div", {
className: "tc",
style: {
marginLeft: -38
}
}, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("p", null, "\u60A8\u53EF\u4EE5\u626B\u7801\u52A0\u7FA4@\u7FA4\u7BA1\u7406\u5458\uFF0C\u7533\u8BF7\u64CD\u4F5C\u6743\u9650\u54E6\uFF01"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("img", {
src: Object(_authority__WEBPACK_IMPORTED_MODULE_8__[/* isStudents */ "c"])() ? _assets_images_studnetqun_png__WEBPACK_IMPORTED_MODULE_13___default.a : "".concat(_env__WEBPACK_IMPORTED_MODULE_14__[/* default */ "a"].IMG_SERVER, "/images/educoder/qqqun20191230.png"),
width: 200
})),
okText: "\u6211\u77E5\u9053\u4E86",
maskClosable: true
});
return false;
};
var AuthorizeModel = function AuthorizeModel(type, text) {
if (type) {
return true;
}
antd_es_modal__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].confirm({
centered: true,
zIndex: 10000,
width: 530,
title: '提示',
content: /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("div", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("p", null, text || '该实践资源需授权后才可使用。 您可以在QQ服务群向管理员申请获得继续操作的权限。'), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("div", {
style: {
marginLeft: '110px'
}
}, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("img", {
src: _assets_images_Authorize_png__WEBPACK_IMPORTED_MODULE_12___default.a,
width: 200
}), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("div", {
style: {
marginLeft: '35px'
}
}, "\u7FA4\u53F7\uFF1A", '714336072'))),
okText: "\u7ACB\u5373\u8054\u7CFB",
cancelText: '取消',
onOk: function onOk() {
Object(_util__WEBPACK_IMPORTED_MODULE_9__[/* openNewWindow */ "n"])("https://qm.qq.com/cgi-bin/qm/qr?k=tIyDPXUtE0yEk-MOJxhH55lTUJS-nYAM&jump_from=webapi");
}
});
return false;
};
var ShixunStatusModel = function ShixunStatusModel(dispatch) {
var text = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var _getDvaApp$_store$get3 = Object(umi__WEBPACK_IMPORTED_MODULE_7__[/* getDvaApp */ "b"])()._store.getState(),
detail = _getDvaApp$_store$get3.shixunsDetail.detail;
if ((detail === null || detail === void 0 ? void 0 : detail.public) === 2 || (detail === null || detail === void 0 ? void 0 : detail.public) === 1 || (detail === null || detail === void 0 ? void 0 : detail.shixun_status) === 3) {
antd_es_modal__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].info({
centered: true,
icon: /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement(_ant_design_icons__WEBPACK_IMPORTED_MODULE_10__[/* default */ "a"], {
style: {
color: '#faad14'
}
}),
width: 460,
title: '提示',
content: /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("div", {
className: "tc",
style: {
marginLeft: -38
}
}, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("div", {
style: {
display: 'flex',
flexDirection: 'column',
alignItems: 'flex-start',
paddingLeft: 38,
margin: '12px 0'
}
}, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("span", null, "\u8BE5\u5B9E\u8DF5\u9879\u76EE\u7684\u72B6\u6001\u4E3A", (detail === null || detail === void 0 ? void 0 : detail.public) === 2 ? '已公开' : (detail === null || detail === void 0 ? void 0 : detail.public) === 1 ? '待审核' : '已关闭', "\uFF0C", text, "\u3002"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("p", null, "\u5982\u6709\u9700\u8981\uFF0C\u8BF7\u8054\u7CFB\u5E73\u53F0\u7BA1\u7406\u5458\u8FDB\u884C\u6280\u672F\u652F\u6301\u3002")), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("img", {
style: {
border: '4px solid #1890FF',
borderRadius: '4px'
},
src: _assets_images_403Qrcode_png__WEBPACK_IMPORTED_MODULE_11___default.a,
alt: "\u4E8C\u7EF4\u7801",
width: 160
})),
okText: '我知道了'
});
return true;
}
if ((detail === null || detail === void 0 ? void 0 : detail.shixun_status) === 2) {
antd_es_modal__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].confirm({
centered: true,
icon: /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement(_ant_design_icons__WEBPACK_IMPORTED_MODULE_10__[/* default */ "a"], null),
title: '提示',
content: /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("div", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("span", null, "\u8BE5\u5B9E\u8DF5\u9879\u76EE\u5DF2\u53D1\u5E03\uFF0C", text, "\u3002"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("br", null), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("span", null, "\u5982\u6709\u9700\u8981\uFF0C\u60A8\u53EF\u4EE5\u64A4\u9500\u53D1\u5E03\u540E\uFF0C\u518D\u8FDB\u884C\u64CD\u4F5C\u3002")),
okText: "\u64A4\u9500\u53D1\u5E03",
cancelText: '取消',
onOk: function onOk() {
antd_es_modal__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].confirm({
width: 440,
centered: true,
icon: /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement(_ant_design_icons__WEBPACK_IMPORTED_MODULE_10__[/* default */ "a"], {
style: {
color: '#faad14'
}
}),
title: '提示',
content: '撤销发布后,学员将无法进行练习。是否确认撤销发布?',
okText: "\u786E\u5B9A\u64A4\u9500\u53D1\u5E03",
cancelText: '取消',
onOk: function () {
var _onOk = Object(_Users_xxq_node_forgeplus_react_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_asyncToGenerator__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"])( /*#__PURE__*/_Users_xxq_node_forgeplus_react_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {
var res;
return _Users_xxq_node_forgeplus_react_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return dispatch({
type: 'shixunsDetail/cancelRelease',
payload: {
id: detail === null || detail === void 0 ? void 0 : detail.identifier
}
});
case 2:
res = _context.sent;
if (res.status !== 401) {
antd_es_message__WEBPACK_IMPORTED_MODULE_2__[/* default */ "b"].success('撤销发布成功。实训回到未发布的状态。');
dispatch({
type: 'shixunsDetail/getShixunsDetail',
payload: {
id: detail === null || detail === void 0 ? void 0 : detail.identifier
}
});
dispatch({
type: 'practiceSetting/getCommonData',
payload: {
id: detail === null || detail === void 0 ? void 0 : detail.identifier
}
});
}
case 4:
case "end":
return _context.stop();
}
}
}, _callee);
}));
function onOk() {
return _onOk.apply(this, arguments);
}
return onOk;
}()
});
}
});
return true;
}
return false;
};
/***/ }),
/***/ "Nmxd":
/*!*******************************************!*\
!*** ./src/assets/images/icons/done2.png ***!
\*******************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports) {
module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAF4ElEQVRoQ91aW2wUVRj+/rPbSivURIgKjZcHjUYTgZ0lthgv3V0LSqB9IAQeNNEIaKKwZbcFnuQJoZ1piyYawJjIiwZDwiVBaHd28QItaWeLD4KJPgimiA+YCAZj6Z7fzPZiu7e57WriJE0f5v++//tm/j3nn3MOoQyXcmJ/LdfeCBOjEUA9EdUzUA9g0ST9VQJGmXkU5n/CAN2q043Vm295TU9uCRS9MwCiFWBqAmD++R1yjQNIgTgF5tNGuCPtEJ8Nd2xgWarzPil9UbBsA1G1m6R5GOYxkOgRItM71NRxzQmnIwMBvStKoCiAB50kcRB7mcG96XB7r12MLQNPJXrvzdD4QQZW2yX2EkfACR/7N56PRH+14rE0sDSpLRaM4wA/YEVW3vt0RRLWjIRi35biLWkgmOhaz0SflleYMzZi3jAcaf+sGKqoAUVX3wbwnrN0FYveYoTj7xdiL2ggqKsvMnCyYnJcEBPw0nA4/kUuNM9AINX9MMnMIEDzXeSpIISvs/A1pJu2/TgzSZ4BRVf7ALxQQSVeqPuNcLy5qIHJcb7HS4ZKYxncNnOemH4DyqmehaiW58D8UKVFeOIn+gljYrmxsu2XWa2Eomt7AN7uidwd+CKBPy8EZdA7hSlprxGO7Zg2EPxSW8q35WDZehv7Ri4KEuuGQtu+y4UoSe0DML9ZkIp5jKpEw/BzsZFsCSkpNQYJ1X7eskQWF6+rbwD4sGQWgbjRFNcmDCS0oyBuKYsseyRFxS/TteWSZT+IaktSMR0zIrFWajzcXTM2X95w0c/bk5ofVVT8k6e77vT7qY+A5TbIx6uvizoKJNUVxDhlA1COkKLis5Wgq2bZmOVj62LCSlIS2m4Q77SF8BZkJd667nPzM71LSqLrExC94k2bJbqk+Im65xQIzr7wmA9RUFcTDIQtJWQDaB3A5lT+ur34bFRJ8WbdV1VRAowGB5wTagCdFF29BOAxSzAjbkTiWrZWU+oCSJgTScwCV1K8m7rPyfe9acAcgeaVFsIHjXD7ptyYxw/vqq5ZMHcHGOZvaE7OfTvindf97CQ3bRkgorXDodiRUiYDuhYlZAeDe6zKxuTJ1j34awDC8u0XD7hht4RuwkctxvOxlFWyYFJ7jUDnC7UHU1iz7qurxBlmDlrxlb5Pl5z8iC8LIVuHmjoueEtqjvddBwDa6JWHCQlnwyjjAu7wtxjPRK+4Ta7Y6XPskpvDqJLUdoMdTWTJOX9kWs+2bL9pN89U3GTdn3WKKxpvTmRuWglmPpKOtK91IiQ73vvJFL/YCa5UbLaVaDzXXTP2p4tmjvGREYnbruOgrn7MwKvlEg9gvLpG1E2000ntKNh5O82EznQobvkVF9S732LIgus6rg0RHTNCsdYJA7oWB7jLJdlOIxzfUwwbTHY+zSy+ccldAkbtRjimThroCYAzA46bqUl6JmxOh+IH8mbq1K65NXLuIIAnymqAMQbyNRrhtvT0qkQgqe4lRof7RHKdEe6Y9XEe0NVDBLzsnrMwcmbp/rOs8lXPQtzODHhY+/9LEq0aCcV0M22wX21jge5yiwdwGVW+RuPZnGUVM9FkP+NlYesaIFcJ8s+TLM9UQDwY1JYOx6Y3QPLXRpNqPzEiHpJfBOAD8KgHjoJQs3VIh+Kzlj3zDCzp63zEJ8QgCHeXW4AnPsZvGSkbLjR3/DCT5/+3vD7lTkl0bQHRPk9PrVxg5q1GpL3gZkvpLaZU93qW8r/dYhJiw3DTNudbTFMPb1lf5xIpxHEQ7i/XA7XFw/hZSLlmqLn094flLqWZzNzcZikO/JvbrCTkJjub3rYMZJ8YgwJJbSuBK7zRTb3pUGwfCGznTdk3MMm2tG/vIvL7tpJE1G3vlCeMMcYCvTye2TfSvP2qHeFTMY4NTI9Sek8AJFewlCGi7IEPc/JycmWYOUVCJMHitNmYOQF7NjAzmTK8v5Z/N4/biEYI1BN46riNeeTGvEazx21Ao5DmcRs5QHfV6UbQ+3GbvwHH7EQQahyMxwAAAABJRU5ErkJggg=="
/***/ }),
/***/ "NnUe":
/*!********************************************************************!*\
!*** ./src/pages/Competitions/Detail/component/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 = {"modal":"modal___sZeHv","colorBlue":"colorBlue___3FmfG","formWrap":"formWrap___3YEqH","flexRow":"flexRow___37Sa0","flexColumn":"flexColumn___1ykGy","example":"example___7mYRk","exampleImg":"exampleImg___UGH9Y","colorOrange":"colorOrange___1IJLa","uploader":"uploader___3f2Sm","uploadImg":"uploadImg___3WCoA","imageTip":"imageTip___FhklW","uploadTipIcon":"uploadTipIcon___2YZJx","uploadTip":"uploadTip___1eikX","color05101a":"color05101a___1Nuwt","viewLargerImg":"viewLargerImg___Ek8jW","footerWrap":"footerWrap___F9F0q","note":"note___1U6xc","schoolHintWrap":"schoolHintWrap___31S22","colorCDCDCD":"colorCDCDCD___1KqvR","color4CACFF":"color4CACFF___3urca"};
/***/ }),
/***/ "Nu4q":
/*!**********************************************************************!*\
!*** ./node_modules/@ant-design/icons-svg/lib/asn/PictureTwoTone.js ***!
\**********************************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// This icon file is generated automatically.
Object.defineProperty(exports, "__esModule", { value: true });
var PictureTwoTone = { "icon": function render(primaryColor, secondaryColor) { return { "tag": "svg", "attrs": { "viewBox": "64 64 896 896", "focusable": "false" }, "children": [{ "tag": "path", "attrs": { "d": "M928 160H96c-17.7 0-32 14.3-32 32v640c0 17.7 14.3 32 32 32h832c17.7 0 32-14.3 32-32V192c0-17.7-14.3-32-32-32zm-40 632H136v-39.9l138.5-164.3 150.1 178L658.1 489 888 761.6V792zm0-129.8L664.2 396.8c-3.2-3.8-9-3.8-12.2 0L424.6 666.4l-144-170.7c-3.2-3.8-9-3.8-12.2 0L136 652.7V232h752v430.2z", "fill": primaryColor } }, { "tag": "path", "attrs": { "d": "M424.6 765.8l-150.1-178L136 752.1V792h752v-30.4L658.1 489z", "fill": secondaryColor } }, { "tag": "path", "attrs": { "d": "M136 652.7l132.4-157c3.2-3.8 9-3.8 12.2 0l144 170.7L652 396.8c3.2-3.8 9-3.8 12.2 0L888 662.2V232H136v420.7zM304 280a88 88 0 110 176 88 88 0 010-176z", "fill": secondaryColor } }, { "tag": "path", "attrs": { "d": "M276 368a28 28 0 1056 0 28 28 0 10-56 0z", "fill": secondaryColor } }, { "tag": "path", "attrs": { "d": "M304 456a88 88 0 100-176 88 88 0 000 176zm0-116c15.5 0 28 12.5 28 28s-12.5 28-28 28-28-12.5-28-28 12.5-28 28-28z", "fill": primaryColor } }] }; }, "name": "picture", "theme": "twotone" };
exports.default = PictureTwoTone;
/***/ }),
/***/ "O/iA":
/*!*************************************************************!*\
!*** ./node_modules/antd/es/auto-complete/style/index.less ***!
\*************************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/***/ "OLod":
/*!***********************************************!*\
!*** ./node_modules/crypto-js/cipher-core.js ***!
\***********************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory, undef) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"), __webpack_require__(/*! ./evpkdf */ "K3mO"));
}
else {}
}(this, function (CryptoJS) {
/**
* Cipher core components.
*/
CryptoJS.lib.Cipher || (function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var Base64 = C_enc.Base64;
var C_algo = C.algo;
var EvpKDF = C_algo.EvpKDF;
/**
* Abstract base cipher template.
*
* @property {number} keySize This cipher's key size. Default: 4 (128 bits)
* @property {number} ivSize This cipher's IV size. Default: 4 (128 bits)
* @property {number} _ENC_XFORM_MODE A constant representing encryption mode.
* @property {number} _DEC_XFORM_MODE A constant representing decryption mode.
*/
var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*
* @property {WordArray} iv The IV to use for this operation.
*/
cfg: Base.extend(),
/**
* Creates this cipher in encryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
*/
createEncryptor: function (key, cfg) {
return this.create(this._ENC_XFORM_MODE, key, cfg);
},
/**
* Creates this cipher in decryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });
*/
createDecryptor: function (key, cfg) {
return this.create(this._DEC_XFORM_MODE, key, cfg);
},
/**
* Initializes a newly created cipher.
*
* @param {number} xformMode Either the encryption or decryption transormation mode constant.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @example
*
* var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray });
*/
init: function (xformMode, key, cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Store transform mode and key
this._xformMode = xformMode;
this._key = key;
// Set initial values
this.reset();
},
/**
* Resets this cipher to its initial state.
*
* @example
*
* cipher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-cipher logic
this._doReset();
},
/**
* Adds data to be encrypted or decrypted.
*
* @param {WordArray|string} dataUpdate The data to encrypt or decrypt.
*
* @return {WordArray} The data after processing.
*
* @example
*
* var encrypted = cipher.process('data');
* var encrypted = cipher.process(wordArray);
*/
process: function (dataUpdate) {
// Append
this._append(dataUpdate);
// Process available blocks
return this._process();
},
/**
* Finalizes the encryption or decryption process.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} dataUpdate The final data to encrypt or decrypt.
*
* @return {WordArray} The data after final processing.
*
* @example
*
* var encrypted = cipher.finalize();
* var encrypted = cipher.finalize('data');
* var encrypted = cipher.finalize(wordArray);
*/
finalize: function (dataUpdate) {
// Final data update
if (dataUpdate) {
this._append(dataUpdate);
}
// Perform concrete-cipher logic
var finalProcessedData = this._doFinalize();
return finalProcessedData;
},
keySize: 128/32,
ivSize: 128/32,
_ENC_XFORM_MODE: 1,
_DEC_XFORM_MODE: 2,
/**
* Creates shortcut functions to a cipher's object interface.
*
* @param {Cipher} cipher The cipher to create a helper for.
*
* @return {Object} An object with encrypt and decrypt shortcut functions.
*
* @static
*
* @example
*
* var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
*/
_createHelper: (function () {
function selectCipherStrategy(key) {
if (typeof key == 'string') {
return PasswordBasedCipher;
} else {
return SerializableCipher;
}
}
return function (cipher) {
return {
encrypt: function (message, key, cfg) {
return selectCipherStrategy(key).encrypt(cipher, message, key, cfg);
},
decrypt: function (ciphertext, key, cfg) {
return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg);
}
};
};
}())
});
/**
* Abstract base stream cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits)
*/
var StreamCipher = C_lib.StreamCipher = Cipher.extend({
_doFinalize: function () {
// Process partial blocks
var finalProcessedBlocks = this._process(!!'flush');
return finalProcessedBlocks;
},
blockSize: 1
});
/**
* Mode namespace.
*/
var C_mode = C.mode = {};
/**
* Abstract base block cipher mode template.
*/
var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({
/**
* Creates this mode for encryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
*/
createEncryptor: function (cipher, iv) {
return this.Encryptor.create(cipher, iv);
},
/**
* Creates this mode for decryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
*/
createDecryptor: function (cipher, iv) {
return this.Decryptor.create(cipher, iv);
},
/**
* Initializes a newly created mode.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @example
*
* var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);
*/
init: function (cipher, iv) {
this._cipher = cipher;
this._iv = iv;
}
});
/**
* Cipher Block Chaining mode.
*/
var CBC = C_mode.CBC = (function () {
/**
* Abstract base CBC mode.
*/
var CBC = BlockCipherMode.extend();
/**
* CBC encryptor.
*/
CBC.Encryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// XOR and encrypt
xorBlock.call(this, words, offset, blockSize);
cipher.encryptBlock(words, offset);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
/**
* CBC decryptor.
*/
CBC.Decryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// Remember this block to use with next block
var thisBlock = words.slice(offset, offset + blockSize);
// Decrypt and XOR
cipher.decryptBlock(words, offset);
xorBlock.call(this, words, offset, blockSize);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function xorBlock(words, offset, blockSize) {
var block;
// Shortcut
var iv = this._iv;
// Choose mixing block
if (iv) {
block = iv;
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
block = this._prevBlock;
}
// XOR blocks
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= block[i];
}
}
return CBC;
}());
/**
* Padding namespace.
*/
var C_pad = C.pad = {};
/**
* PKCS #5/7 padding strategy.
*/
var Pkcs7 = C_pad.Pkcs7 = {
/**
* Pads data using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to pad.
* @param {number} blockSize The multiple that the data should be padded to.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.pad(wordArray, 4);
*/
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
// Create padding word
var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes;
// Create padding
var paddingWords = [];
for (var i = 0; i < nPaddingBytes; i += 4) {
paddingWords.push(paddingWord);
}
var padding = WordArray.create(paddingWords, nPaddingBytes);
// Add padding
data.concat(padding);
},
/**
* Unpads data that had been padded using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to unpad.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.unpad(wordArray);
*/
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
/**
* Abstract base block cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits)
*/
var BlockCipher = C_lib.BlockCipher = Cipher.extend({
/**
* Configuration options.
*
* @property {Mode} mode The block mode to use. Default: CBC
* @property {Padding} padding The padding strategy to use. Default: Pkcs7
*/
cfg: Cipher.cfg.extend({
mode: CBC,
padding: Pkcs7
}),
reset: function () {
var modeCreator;
// Reset cipher
Cipher.reset.call(this);
// Shortcuts
var cfg = this.cfg;
var iv = cfg.iv;
var mode = cfg.mode;
// Reset block mode
if (this._xformMode == this._ENC_XFORM_MODE) {
modeCreator = mode.createEncryptor;
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
modeCreator = mode.createDecryptor;
// Keep at least one block in the buffer for unpadding
this._minBufferSize = 1;
}
if (this._mode && this._mode.__creator == modeCreator) {
this._mode.init(this, iv && iv.words);
} else {
this._mode = modeCreator.call(mode, this, iv && iv.words);
this._mode.__creator = modeCreator;
}
},
_doProcessBlock: function (words, offset) {
this._mode.processBlock(words, offset);
},
_doFinalize: function () {
var finalProcessedBlocks;
// Shortcut
var padding = this.cfg.padding;
// Finalize
if (this._xformMode == this._ENC_XFORM_MODE) {
// Pad data
padding.pad(this._data, this.blockSize);
// Process final blocks
finalProcessedBlocks = this._process(!!'flush');
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
// Process final blocks
finalProcessedBlocks = this._process(!!'flush');
// Unpad data
padding.unpad(finalProcessedBlocks);
}
return finalProcessedBlocks;
},
blockSize: 128/32
});
/**
* A collection of cipher parameters.
*
* @property {WordArray} ciphertext The raw ciphertext.
* @property {WordArray} key The key to this ciphertext.
* @property {WordArray} iv The IV used in the ciphering operation.
* @property {WordArray} salt The salt used with a key derivation function.
* @property {Cipher} algorithm The cipher algorithm.
* @property {Mode} mode The block mode used in the ciphering operation.
* @property {Padding} padding The padding scheme used in the ciphering operation.
* @property {number} blockSize The block size of the cipher.
* @property {Format} formatter The default formatting strategy to convert this cipher params object to a string.
*/
var CipherParams = C_lib.CipherParams = Base.extend({
/**
* Initializes a newly created cipher params object.
*
* @param {Object} cipherParams An object with any of the possible cipher parameters.
*
* @example
*
* var cipherParams = CryptoJS.lib.CipherParams.create({
* ciphertext: ciphertextWordArray,
* key: keyWordArray,
* iv: ivWordArray,
* salt: saltWordArray,
* algorithm: CryptoJS.algo.AES,
* mode: CryptoJS.mode.CBC,
* padding: CryptoJS.pad.PKCS7,
* blockSize: 4,
* formatter: CryptoJS.format.OpenSSL
* });
*/
init: function (cipherParams) {
this.mixIn(cipherParams);
},
/**
* Converts this cipher params object to a string.
*
* @param {Format} formatter (Optional) The formatting strategy to use.
*
* @return {string} The stringified cipher params.
*
* @throws Error If neither the formatter nor the default formatter is set.
*
* @example
*
* var string = cipherParams + '';
* var string = cipherParams.toString();
* var string = cipherParams.toString(CryptoJS.format.OpenSSL);
*/
toString: function (formatter) {
return (formatter || this.formatter).stringify(this);
}
});
/**
* Format namespace.
*/
var C_format = C.format = {};
/**
* OpenSSL formatting strategy.
*/
var OpenSSLFormatter = C_format.OpenSSL = {
/**
* Converts a cipher params object to an OpenSSL-compatible string.
*
* @param {CipherParams} cipherParams The cipher params object.
*
* @return {string} The OpenSSL-compatible string.
*
* @static
*
* @example
*
* var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams);
*/
stringify: function (cipherParams) {
var wordArray;
// Shortcuts
var ciphertext = cipherParams.ciphertext;
var salt = cipherParams.salt;
// Format
if (salt) {
wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext);
} else {
wordArray = ciphertext;
}
return wordArray.toString(Base64);
},
/**
* Converts an OpenSSL-compatible string to a cipher params object.
*
* @param {string} openSSLStr The OpenSSL-compatible string.
*
* @return {CipherParams} The cipher params object.
*
* @static
*
* @example
*
* var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString);
*/
parse: function (openSSLStr) {
var salt;
// Parse base64
var ciphertext = Base64.parse(openSSLStr);
// Shortcut
var ciphertextWords = ciphertext.words;
// Test for salt
if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) {
// Extract salt
salt = WordArray.create(ciphertextWords.slice(2, 4));
// Remove salt from ciphertext
ciphertextWords.splice(0, 4);
ciphertext.sigBytes -= 16;
}
return CipherParams.create({ ciphertext: ciphertext, salt: salt });
}
};
/**
* A cipher wrapper that returns ciphertext as a serializable cipher params object.
*/
var SerializableCipher = C_lib.SerializableCipher = Base.extend({
/**
* Configuration options.
*
* @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL
*/
cfg: Base.extend({
format: OpenSSLFormatter
}),
/**
* Encrypts a message.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key);
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv });
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Encrypt
var encryptor = cipher.createEncryptor(key, cfg);
var ciphertext = encryptor.finalize(message);
// Shortcut
var cipherCfg = encryptor.cfg;
// Create and return serializable cipher params
return CipherParams.create({
ciphertext: ciphertext,
key: key,
iv: cipherCfg.iv,
algorithm: cipher,
mode: cipherCfg.mode,
padding: cipherCfg.padding,
blockSize: cipher.blockSize,
formatter: cfg.format
});
},
/**
* Decrypts serialized ciphertext.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Decrypt
var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext);
return plaintext;
},
/**
* Converts serialized ciphertext to CipherParams,
* else assumed CipherParams already and returns ciphertext unchanged.
*
* @param {CipherParams|string} ciphertext The ciphertext.
* @param {Formatter} format The formatting strategy to use to parse serialized ciphertext.
*
* @return {CipherParams} The unserialized ciphertext.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format);
*/
_parse: function (ciphertext, format) {
if (typeof ciphertext == 'string') {
return format.parse(ciphertext, this);
} else {
return ciphertext;
}
}
});
/**
* Key derivation function namespace.
*/
var C_kdf = C.kdf = {};
/**
* OpenSSL key derivation function.
*/
var OpenSSLKdf = C_kdf.OpenSSL = {
/**
* Derives a key and IV from a password.
*
* @param {string} password The password to derive from.
* @param {number} keySize The size in words of the key to generate.
* @param {number} ivSize The size in words of the IV to generate.
* @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly.
*
* @return {CipherParams} A cipher params object with the key, IV, and salt.
*
* @static
*
* @example
*
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32);
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
*/
execute: function (password, keySize, ivSize, salt) {
// Generate random salt
if (!salt) {
salt = WordArray.random(64/8);
}
// Derive key and IV
var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt);
// Separate key and IV
var iv = WordArray.create(key.words.slice(keySize), ivSize * 4);
key.sigBytes = keySize * 4;
// Return params
return CipherParams.create({ key: key, iv: iv, salt: salt });
}
};
/**
* A serializable cipher wrapper that derives the key from a password,
* and returns ciphertext as a serializable cipher params object.
*/
var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({
/**
* Configuration options.
*
* @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL
*/
cfg: SerializableCipher.cfg.extend({
kdf: OpenSSLKdf
}),
/**
* Encrypts a message using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password');
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize);
// Add IV to config
cfg.iv = derivedParams.iv;
// Encrypt
var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg);
// Mix in derived params
ciphertext.mixIn(derivedParams);
return ciphertext;
},
/**
* Decrypts serialized ciphertext using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt);
// Add IV to config
cfg.iv = derivedParams.iv;
// Decrypt
var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg);
return plaintext;
}
});
}());
}));
/***/ }),
/***/ "Ohmc":
/*!*******************************************!*\
!*** ./src/assets/images/certificate.jpg ***!
\*******************************************/
/*! 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/certificate.fc32dc1b.jpg";
/***/ }),
/***/ "Oy/b":
/*!******************************************!*\
!*** ./node_modules/katex/dist/katex.js ***!
\******************************************/
/*! no static exports found */
/*! exports used: renderToString */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
(function webpackUniversalModuleDefinition(root, factory) {
if(true)
module.exports = factory();
else {}
})((typeof self !== 'undefined' ? self : 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 = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 1);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
// EXTERNAL MODULE: ./src/katex.less
var katex = __webpack_require__(0);
// CONCATENATED MODULE: ./src/SourceLocation.js
/**
* Lexing or parsing positional information for error reporting.
* This object is immutable.
*/
var SourceLocation =
/*#__PURE__*/
function () {
// The + prefix indicates that these fields aren't writeable
// Lexer holding the input string.
// Start offset, zero-based inclusive.
// End offset, zero-based exclusive.
function SourceLocation(lexer, start, end) {
this.lexer = void 0;
this.start = void 0;
this.end = void 0;
this.lexer = lexer;
this.start = start;
this.end = end;
}
/**
* Merges two `SourceLocation`s from location providers, given they are
* provided in order of appearance.
* - Returns the first one's location if only the first is provided.
* - Returns a merged range of the first and the last if both are provided
* and their lexers match.
* - Otherwise, returns null.
*/
SourceLocation.range = function range(first, second) {
if (!second) {
return first && first.loc;
} else if (!first || !first.loc || !second.loc || first.loc.lexer !== second.loc.lexer) {
return null;
} else {
return new SourceLocation(first.loc.lexer, first.loc.start, second.loc.end);
}
};
return SourceLocation;
}();
// CONCATENATED MODULE: ./src/Token.js
/**
* Interface required to break circular dependency between Token, Lexer, and
* ParseError.
*/
/**
* The resulting token returned from `lex`.
*
* It consists of the token text plus some position information.
* The position information is essentially a range in an input string,
* but instead of referencing the bare input string, we refer to the lexer.
* That way it is possible to attach extra metadata to the input string,
* like for example a file name or similar.
*
* The position information is optional, so it is OK to construct synthetic
* tokens if appropriate. Not providing available position information may
* lead to degraded error reporting, though.
*/
var Token_Token =
/*#__PURE__*/
function () {
function Token(text, // the text of this token
loc) {
this.text = void 0;
this.loc = void 0;
this.text = text;
this.loc = loc;
}
/**
* Given a pair of tokens (this and endToken), compute a `Token` encompassing
* the whole input range enclosed by these two.
*/
var _proto = Token.prototype;
_proto.range = function range(endToken, // last token of the range, inclusive
text) // the text of the newly constructed token
{
return new Token(text, SourceLocation.range(this, endToken));
};
return Token;
}();
// CONCATENATED MODULE: ./src/ParseError.js
/**
* This is the ParseError class, which is the main error thrown by KaTeX
* functions when something has gone wrong. This is used to distinguish internal
* errors from errors in the expression that the user provided.
*
* If possible, a caller should provide a Token or ParseNode with information
* about where in the source string the problem occurred.
*/
var ParseError = // Error position based on passed-in Token or ParseNode.
function ParseError(message, // The error message
token) // An object providing position information
{
this.position = void 0;
var error = "KaTeX parse error: " + message;
var start;
var loc = token && token.loc;
if (loc && loc.start <= loc.end) {
// If we have the input and a position, make the error a bit fancier
// Get the input
var input = loc.lexer.input; // Prepend some information
start = loc.start;
var end = loc.end;
if (start === input.length) {
error += " at end of input: ";
} else {
error += " at position " + (start + 1) + ": ";
} // Underline token in question using combining underscores
var underlined = input.slice(start, end).replace(/[^]/g, "$&\u0332"); // Extract some context from the input and add it to the error
var left;
if (start > 15) {
left = "…" + input.slice(start - 15, start);
} else {
left = input.slice(0, start);
}
var right;
if (end + 15 < input.length) {
right = input.slice(end, end + 15) + "…";
} else {
right = input.slice(end);
}
error += left + underlined + right;
} // Some hackery to make ParseError a prototype of Error
// See http://stackoverflow.com/a/8460753
var self = new Error(error);
self.name = "ParseError"; // $FlowFixMe
self.__proto__ = ParseError.prototype; // $FlowFixMe
self.position = start;
return self;
}; // $FlowFixMe More hackery
ParseError.prototype.__proto__ = Error.prototype;
/* harmony default export */ var src_ParseError = (ParseError);
// CONCATENATED MODULE: ./src/utils.js
/**
* This file contains a list of utility functions which are useful in other
* files.
*/
/**
* Return whether an element is contained in a list
*/
var contains = function contains(list, elem) {
return list.indexOf(elem) !== -1;
};
/**
* Provide a default value if a setting is undefined
* NOTE: Couldn't use `T` as the output type due to facebook/flow#5022.
*/
var deflt = function deflt(setting, defaultIfUndefined) {
return setting === undefined ? defaultIfUndefined : setting;
}; // hyphenate and escape adapted from Facebook's React under Apache 2 license
var uppercase = /([A-Z])/g;
var hyphenate = function hyphenate(str) {
return str.replace(uppercase, "-$1").toLowerCase();
};
var ESCAPE_LOOKUP = {
"&": "&amp;",
">": "&gt;",
"<": "&lt;",
"\"": "&quot;",
"'": "&#x27;"
};
var ESCAPE_REGEX = /[&><"']/g;
/**
* Escapes text to prevent scripting attacks.
*/
function utils_escape(text) {
return String(text).replace(ESCAPE_REGEX, function (match) {
return ESCAPE_LOOKUP[match];
});
}
/**
* Sometimes we want to pull out the innermost element of a group. In most
* cases, this will just be the group itself, but when ordgroups and colors have
* a single element, we want to pull that out.
*/
var getBaseElem = function getBaseElem(group) {
if (group.type === "ordgroup") {
if (group.body.length === 1) {
return getBaseElem(group.body[0]);
} else {
return group;
}
} else if (group.type === "color") {
if (group.body.length === 1) {
return getBaseElem(group.body[0]);
} else {
return group;
}
} else if (group.type === "font") {
return getBaseElem(group.body);
} else {
return group;
}
};
/**
* TeXbook algorithms often reference "character boxes", which are simply groups
* with a single character in them. To decide if something is a character box,
* we find its innermost group, and see if it is a single character.
*/
var utils_isCharacterBox = function isCharacterBox(group) {
var baseElem = getBaseElem(group); // These are all they types of groups which hold single characters
return baseElem.type === "mathord" || baseElem.type === "textord" || baseElem.type === "atom";
};
var assert = function assert(value) {
if (!value) {
throw new Error('Expected non-null, but got ' + String(value));
}
return value;
};
/**
* Return the protocol of a URL, or "_relative" if the URL does not specify a
* protocol (and thus is relative).
*/
var protocolFromUrl = function protocolFromUrl(url) {
var protocol = /^\s*([^\\/#]*?)(?::|&#0*58|&#x0*3a)/i.exec(url);
return protocol != null ? protocol[1] : "_relative";
};
/* harmony default export */ var utils = ({
contains: contains,
deflt: deflt,
escape: utils_escape,
hyphenate: hyphenate,
getBaseElem: getBaseElem,
isCharacterBox: utils_isCharacterBox,
protocolFromUrl: protocolFromUrl
});
// CONCATENATED MODULE: ./src/Settings.js
/* eslint no-console:0 */
/**
* This is a module for storing settings passed into KaTeX. It correctly handles
* default settings.
*/
/**
* The main Settings object
*
* The current options stored are:
* - displayMode: Whether the expression should be typeset as inline math
* (false, the default), meaning that the math starts in
* \textstyle and is placed in an inline-block); or as display
* math (true), meaning that the math starts in \displaystyle
* and is placed in a block with vertical margin.
*/
var Settings_Settings =
/*#__PURE__*/
function () {
function Settings(options) {
this.displayMode = void 0;
this.output = void 0;
this.leqno = void 0;
this.fleqn = void 0;
this.throwOnError = void 0;
this.errorColor = void 0;
this.macros = void 0;
this.minRuleThickness = void 0;
this.colorIsTextColor = void 0;
this.strict = void 0;
this.trust = void 0;
this.maxSize = void 0;
this.maxExpand = void 0;
// allow null options
options = options || {};
this.displayMode = utils.deflt(options.displayMode, false);
this.output = utils.deflt(options.output, "htmlAndMathml");
this.leqno = utils.deflt(options.leqno, false);
this.fleqn = utils.deflt(options.fleqn, false);
this.throwOnError = utils.deflt(options.throwOnError, true);
this.errorColor = utils.deflt(options.errorColor, "#cc0000");
this.macros = options.macros || {};
this.minRuleThickness = Math.max(0, utils.deflt(options.minRuleThickness, 0));
this.colorIsTextColor = utils.deflt(options.colorIsTextColor, false);
this.strict = utils.deflt(options.strict, "warn");
this.trust = utils.deflt(options.trust, false);
this.maxSize = Math.max(0, utils.deflt(options.maxSize, Infinity));
this.maxExpand = Math.max(0, utils.deflt(options.maxExpand, 1000));
}
/**
* Report nonstrict (non-LaTeX-compatible) input.
* Can safely not be called if `this.strict` is false in JavaScript.
*/
var _proto = Settings.prototype;
_proto.reportNonstrict = function reportNonstrict(errorCode, errorMsg, token) {
var strict = this.strict;
if (typeof strict === "function") {
// Allow return value of strict function to be boolean or string
// (or null/undefined, meaning no further processing).
strict = strict(errorCode, errorMsg, token);
}
if (!strict || strict === "ignore") {
return;
} else if (strict === true || strict === "error") {
throw new src_ParseError("LaTeX-incompatible input and strict mode is set to 'error': " + (errorMsg + " [" + errorCode + "]"), token);
} else if (strict === "warn") {
typeof console !== "undefined" && console.warn("LaTeX-incompatible input and strict mode is set to 'warn': " + (errorMsg + " [" + errorCode + "]"));
} else {
// won't happen in type-safe code
typeof console !== "undefined" && console.warn("LaTeX-incompatible input and strict mode is set to " + ("unrecognized '" + strict + "': " + errorMsg + " [" + errorCode + "]"));
}
}
/**
* Check whether to apply strict (LaTeX-adhering) behavior for unusual
* input (like `\\`). Unlike `nonstrict`, will not throw an error;
* instead, "error" translates to a return value of `true`, while "ignore"
* translates to a return value of `false`. May still print a warning:
* "warn" prints a warning and returns `false`.
* This is for the second category of `errorCode`s listed in the README.
*/
;
_proto.useStrictBehavior = function useStrictBehavior(errorCode, errorMsg, token) {
var strict = this.strict;
if (typeof strict === "function") {
// Allow return value of strict function to be boolean or string
// (or null/undefined, meaning no further processing).
// But catch any exceptions thrown by function, treating them
// like "error".
try {
strict = strict(errorCode, errorMsg, token);
} catch (error) {
strict = "error";
}
}
if (!strict || strict === "ignore") {
return false;
} else if (strict === true || strict === "error") {
return true;
} else if (strict === "warn") {
typeof console !== "undefined" && console.warn("LaTeX-incompatible input and strict mode is set to 'warn': " + (errorMsg + " [" + errorCode + "]"));
return false;
} else {
// won't happen in type-safe code
typeof console !== "undefined" && console.warn("LaTeX-incompatible input and strict mode is set to " + ("unrecognized '" + strict + "': " + errorMsg + " [" + errorCode + "]"));
return false;
}
}
/**
* Check whether to test potentially dangerous input, and return
* `true` (trusted) or `false` (untrusted). The sole argument `context`
* should be an object with `command` field specifying the relevant LaTeX
* command (as a string starting with `\`), and any other arguments, etc.
* If `context` has a `url` field, a `protocol` field will automatically
* get added by this function (changing the specified object).
*/
;
_proto.isTrusted = function isTrusted(context) {
if (context.url && !context.protocol) {
context.protocol = utils.protocolFromUrl(context.url);
}
var trust = typeof this.trust === "function" ? this.trust(context) : this.trust;
return Boolean(trust);
};
return Settings;
}();
// CONCATENATED MODULE: ./src/Style.js
/**
* This file contains information and classes for the various kinds of styles
* used in TeX. It provides a generic `Style` class, which holds information
* about a specific style. It then provides instances of all the different kinds
* of styles possible, and provides functions to move between them and get
* information about them.
*/
/**
* The main style class. Contains a unique id for the style, a size (which is
* the same for cramped and uncramped version of a style), and a cramped flag.
*/
var Style =
/*#__PURE__*/
function () {
function Style(id, size, cramped) {
this.id = void 0;
this.size = void 0;
this.cramped = void 0;
this.id = id;
this.size = size;
this.cramped = cramped;
}
/**
* Get the style of a superscript given a base in the current style.
*/
var _proto = Style.prototype;
_proto.sup = function sup() {
return Style_styles[_sup[this.id]];
}
/**
* Get the style of a subscript given a base in the current style.
*/
;
_proto.sub = function sub() {
return Style_styles[_sub[this.id]];
}
/**
* Get the style of a fraction numerator given the fraction in the current
* style.
*/
;
_proto.fracNum = function fracNum() {
return Style_styles[_fracNum[this.id]];
}
/**
* Get the style of a fraction denominator given the fraction in the current
* style.
*/
;
_proto.fracDen = function fracDen() {
return Style_styles[_fracDen[this.id]];
}
/**
* Get the cramped version of a style (in particular, cramping a cramped style
* doesn't change the style).
*/
;
_proto.cramp = function cramp() {
return Style_styles[_cramp[this.id]];
}
/**
* Get a text or display version of this style.
*/
;
_proto.text = function text() {
return Style_styles[_text[this.id]];
}
/**
* Return true if this style is tightly spaced (scriptstyle/scriptscriptstyle)
*/
;
_proto.isTight = function isTight() {
return this.size >= 2;
};
return Style;
}(); // Export an interface for type checking, but don't expose the implementation.
// This way, no more styles can be generated.
// IDs of the different styles
var D = 0;
var Dc = 1;
var T = 2;
var Tc = 3;
var S = 4;
var Sc = 5;
var SS = 6;
var SSc = 7; // Instances of the different styles
var Style_styles = [new Style(D, 0, false), new Style(Dc, 0, true), new Style(T, 1, false), new Style(Tc, 1, true), new Style(S, 2, false), new Style(Sc, 2, true), new Style(SS, 3, false), new Style(SSc, 3, true)]; // Lookup tables for switching from one style to another
var _sup = [S, Sc, S, Sc, SS, SSc, SS, SSc];
var _sub = [Sc, Sc, Sc, Sc, SSc, SSc, SSc, SSc];
var _fracNum = [T, Tc, S, Sc, SS, SSc, SS, SSc];
var _fracDen = [Tc, Tc, Sc, Sc, SSc, SSc, SSc, SSc];
var _cramp = [Dc, Dc, Tc, Tc, Sc, Sc, SSc, SSc];
var _text = [D, Dc, T, Tc, T, Tc, T, Tc]; // We only export some of the styles.
/* harmony default export */ var src_Style = ({
DISPLAY: Style_styles[D],
TEXT: Style_styles[T],
SCRIPT: Style_styles[S],
SCRIPTSCRIPT: Style_styles[SS]
});
// CONCATENATED MODULE: ./src/unicodeScripts.js
/*
* This file defines the Unicode scripts and script families that we
* support. To add new scripts or families, just add a new entry to the
* scriptData array below. Adding scripts to the scriptData array allows
* characters from that script to appear in \text{} environments.
*/
/**
* Each script or script family has a name and an array of blocks.
* Each block is an array of two numbers which specify the start and
* end points (inclusive) of a block of Unicode codepoints.
*/
/**
* Unicode block data for the families of scripts we support in \text{}.
* Scripts only need to appear here if they do not have font metrics.
*/
var scriptData = [{
// Latin characters beyond the Latin-1 characters we have metrics for.
// Needed for Czech, Hungarian and Turkish text, for example.
name: 'latin',
blocks: [[0x0100, 0x024f], // Latin Extended-A and Latin Extended-B
[0x0300, 0x036f]]
}, {
// The Cyrillic script used by Russian and related languages.
// A Cyrillic subset used to be supported as explicitly defined
// symbols in symbols.js
name: 'cyrillic',
blocks: [[0x0400, 0x04ff]]
}, {
// The Brahmic scripts of South and Southeast Asia
// Devanagari (0900097F)
// Bengali (098009FF)
// Gurmukhi (0A000A7F)
// Gujarati (0A800AFF)
// Oriya (0B000B7F)
// Tamil (0B800BFF)
// Telugu (0C000C7F)
// Kannada (0C800CFF)
// Malayalam (0D000D7F)
// Sinhala (0D800DFF)
// Thai (0E000E7F)
// Lao (0E800EFF)
// Tibetan (0F000FFF)
// Myanmar (1000109F)
name: 'brahmic',
blocks: [[0x0900, 0x109F]]
}, {
name: 'georgian',
blocks: [[0x10A0, 0x10ff]]
}, {
// Chinese and Japanese.
// The "k" in cjk is for Korean, but we've separated Korean out
name: "cjk",
blocks: [[0x3000, 0x30FF], // CJK symbols and punctuation, Hiragana, Katakana
[0x4E00, 0x9FAF], // CJK ideograms
[0xFF00, 0xFF60]]
}, {
// Korean
name: 'hangul',
blocks: [[0xAC00, 0xD7AF]]
}];
/**
* Given a codepoint, return the name of the script or script family
* it is from, or null if it is not part of a known block
*/
function scriptFromCodepoint(codepoint) {
for (var i = 0; i < scriptData.length; i++) {
var script = scriptData[i];
for (var _i = 0; _i < script.blocks.length; _i++) {
var block = script.blocks[_i];
if (codepoint >= block[0] && codepoint <= block[1]) {
return script.name;
}
}
}
return null;
}
/**
* A flattened version of all the supported blocks in a single array.
* This is an optimization to make supportedCodepoint() fast.
*/
var allBlocks = [];
scriptData.forEach(function (s) {
return s.blocks.forEach(function (b) {
return allBlocks.push.apply(allBlocks, b);
});
});
/**
* Given a codepoint, return true if it falls within one of the
* scripts or script families defined above and false otherwise.
*
* Micro benchmarks shows that this is faster than
* /[\u3000-\u30FF\u4E00-\u9FAF\uFF00-\uFF60\uAC00-\uD7AF\u0900-\u109F]/.test()
* in Firefox, Chrome and Node.
*/
function supportedCodepoint(codepoint) {
for (var i = 0; i < allBlocks.length; i += 2) {
if (codepoint >= allBlocks[i] && codepoint <= allBlocks[i + 1]) {
return true;
}
}
return false;
}
// CONCATENATED MODULE: ./src/svgGeometry.js
/**
* This file provides support to domTree.js and delimiter.js.
* It's a storehouse of path geometry for SVG images.
*/
// In all paths below, the viewBox-to-em scale is 1000:1.
var hLinePad = 80; // padding above a sqrt viniculum. Prevents image cropping.
// The viniculum of a \sqrt can be made thicker by a KaTeX rendering option.
// Think of variable extraViniculum as two detours in the SVG path.
// The detour begins at the lower left of the area labeled extraViniculum below.
// The detour proceeds one extraViniculum distance up and slightly to the right,
// displacing the radiused corner between surd and viniculum. The radius is
// traversed as usual, then the detour resumes. It goes right, to the end of
// the very long viniculumn, then down one extraViniculum distance,
// after which it resumes regular path geometry for the radical.
/* viniculum
/
/▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒←extraViniculum
/ █████████████████████←0.04em (40 unit) std viniculum thickness
/ /
/ /
/ /\
/ / surd
*/
var sqrtMain = function sqrtMain(extraViniculum, hLinePad) {
// sqrtMain path geometry is from glyph U221A in the font KaTeX Main
return "M95," + (622 + extraViniculum + hLinePad) + "\nc-2.7,0,-7.17,-2.7,-13.5,-8c-5.8,-5.3,-9.5,-10,-9.5,-14\nc0,-2,0.3,-3.3,1,-4c1.3,-2.7,23.83,-20.7,67.5,-54\nc44.2,-33.3,65.8,-50.3,66.5,-51c1.3,-1.3,3,-2,5,-2c4.7,0,8.7,3.3,12,10\ns173,378,173,378c0.7,0,35.3,-71,104,-213c68.7,-142,137.5,-285,206.5,-429\nc69,-144,104.5,-217.7,106.5,-221\nl" + extraViniculum / 2.075 + " -" + extraViniculum + "\nc5.3,-9.3,12,-14,20,-14\nH400000v" + (40 + extraViniculum) + "H845.2724\ns-225.272,467,-225.272,467s-235,486,-235,486c-2.7,4.7,-9,7,-19,7\nc-6,0,-10,-1,-12,-3s-194,-422,-194,-422s-65,47,-65,47z\nM" + (834 + extraViniculum) + " " + hLinePad + "h400000v" + (40 + extraViniculum) + "h-400000z";
};
var sqrtSize1 = function sqrtSize1(extraViniculum, hLinePad) {
// size1 is from glyph U221A in the font KaTeX_Size1-Regular
return "M263," + (601 + extraViniculum + hLinePad) + "c0.7,0,18,39.7,52,119\nc34,79.3,68.167,158.7,102.5,238c34.3,79.3,51.8,119.3,52.5,120\nc340,-704.7,510.7,-1060.3,512,-1067\nl" + extraViniculum / 2.084 + " -" + extraViniculum + "\nc4.7,-7.3,11,-11,19,-11\nH40000v" + (40 + extraViniculum) + "H1012.3\ns-271.3,567,-271.3,567c-38.7,80.7,-84,175,-136,283c-52,108,-89.167,185.3,-111.5,232\nc-22.3,46.7,-33.8,70.3,-34.5,71c-4.7,4.7,-12.3,7,-23,7s-12,-1,-12,-1\ns-109,-253,-109,-253c-72.7,-168,-109.3,-252,-110,-252c-10.7,8,-22,16.7,-34,26\nc-22,17.3,-33.3,26,-34,26s-26,-26,-26,-26s76,-59,76,-59s76,-60,76,-60z\nM" + (1001 + extraViniculum) + " " + hLinePad + "h400000v" + (40 + extraViniculum) + "h-400000z";
};
var sqrtSize2 = function sqrtSize2(extraViniculum, hLinePad) {
// size2 is from glyph U221A in the font KaTeX_Size2-Regular
return "M983 " + (10 + extraViniculum + hLinePad) + "\nl" + extraViniculum / 3.13 + " -" + extraViniculum + "\nc4,-6.7,10,-10,18,-10 H400000v" + (40 + extraViniculum) + "\nH1013.1s-83.4,268,-264.1,840c-180.7,572,-277,876.3,-289,913c-4.7,4.7,-12.7,7,-24,7\ns-12,0,-12,0c-1.3,-3.3,-3.7,-11.7,-7,-25c-35.3,-125.3,-106.7,-373.3,-214,-744\nc-10,12,-21,25,-33,39s-32,39,-32,39c-6,-5.3,-15,-14,-27,-26s25,-30,25,-30\nc26.7,-32.7,52,-63,76,-91s52,-60,52,-60s208,722,208,722\nc56,-175.3,126.3,-397.3,211,-666c84.7,-268.7,153.8,-488.2,207.5,-658.5\nc53.7,-170.3,84.5,-266.8,92.5,-289.5z\nM" + (1001 + extraViniculum) + " " + hLinePad + "h400000v" + (40 + extraViniculum) + "h-400000z";
};
var sqrtSize3 = function sqrtSize3(extraViniculum, hLinePad) {
// size3 is from glyph U221A in the font KaTeX_Size3-Regular
return "M424," + (2398 + extraViniculum + hLinePad) + "\nc-1.3,-0.7,-38.5,-172,-111.5,-514c-73,-342,-109.8,-513.3,-110.5,-514\nc0,-2,-10.7,14.3,-32,49c-4.7,7.3,-9.8,15.7,-15.5,25c-5.7,9.3,-9.8,16,-12.5,20\ns-5,7,-5,7c-4,-3.3,-8.3,-7.7,-13,-13s-13,-13,-13,-13s76,-122,76,-122s77,-121,77,-121\ns209,968,209,968c0,-2,84.7,-361.7,254,-1079c169.3,-717.3,254.7,-1077.7,256,-1081\nl" + extraViniculum / 4.223 + " -" + extraViniculum + "c4,-6.7,10,-10,18,-10 H400000\nv" + (40 + extraViniculum) + "H1014.6\ns-87.3,378.7,-272.6,1166c-185.3,787.3,-279.3,1182.3,-282,1185\nc-2,6,-10,9,-24,9\nc-8,0,-12,-0.7,-12,-2z M" + (1001 + extraViniculum) + " " + hLinePad + "\nh400000v" + (40 + extraViniculum) + "h-400000z";
};
var sqrtSize4 = function sqrtSize4(extraViniculum, hLinePad) {
// size4 is from glyph U221A in the font KaTeX_Size4-Regular
return "M473," + (2713 + extraViniculum + hLinePad) + "\nc339.3,-1799.3,509.3,-2700,510,-2702 l" + extraViniculum / 5.298 + " -" + extraViniculum + "\nc3.3,-7.3,9.3,-11,18,-11 H400000v" + (40 + extraViniculum) + "H1017.7\ns-90.5,478,-276.2,1466c-185.7,988,-279.5,1483,-281.5,1485c-2,6,-10,9,-24,9\nc-8,0,-12,-0.7,-12,-2c0,-1.3,-5.3,-32,-16,-92c-50.7,-293.3,-119.7,-693.3,-207,-1200\nc0,-1.3,-5.3,8.7,-16,30c-10.7,21.3,-21.3,42.7,-32,64s-16,33,-16,33s-26,-26,-26,-26\ns76,-153,76,-153s77,-151,77,-151c0.7,0.7,35.7,202,105,604c67.3,400.7,102,602.7,104,\n606zM" + (1001 + extraViniculum) + " " + hLinePad + "h400000v" + (40 + extraViniculum) + "H1017.7z";
};
var sqrtTall = function sqrtTall(extraViniculum, hLinePad, viewBoxHeight) {
// sqrtTall is from glyph U23B7 in the font KaTeX_Size4-Regular
// One path edge has a variable length. It runs vertically from the viniculumn
// to a point near (14 units) the bottom of the surd. The viniculum
// is normally 40 units thick. So the length of the line in question is:
var vertSegment = viewBoxHeight - 54 - hLinePad - extraViniculum;
return "M702 " + (extraViniculum + hLinePad) + "H400000" + (40 + extraViniculum) + "\nH742v" + vertSegment + "l-4 4-4 4c-.667.7 -2 1.5-4 2.5s-4.167 1.833-6.5 2.5-5.5 1-9.5 1\nh-12l-28-84c-16.667-52-96.667 -294.333-240-727l-212 -643 -85 170\nc-4-3.333-8.333-7.667-13 -13l-13-13l77-155 77-156c66 199.333 139 419.667\n219 661 l218 661zM702 " + hLinePad + "H400000v" + (40 + extraViniculum) + "H742z";
};
var sqrtPath = function sqrtPath(size, extraViniculum, viewBoxHeight) {
extraViniculum = 1000 * extraViniculum; // Convert from document ems to viewBox.
var path = "";
switch (size) {
case "sqrtMain":
path = sqrtMain(extraViniculum, hLinePad);
break;
case "sqrtSize1":
path = sqrtSize1(extraViniculum, hLinePad);
break;
case "sqrtSize2":
path = sqrtSize2(extraViniculum, hLinePad);
break;
case "sqrtSize3":
path = sqrtSize3(extraViniculum, hLinePad);
break;
case "sqrtSize4":
path = sqrtSize4(extraViniculum, hLinePad);
break;
case "sqrtTall":
path = sqrtTall(extraViniculum, hLinePad, viewBoxHeight);
}
return path;
};
var svgGeometry_path = {
// The doubleleftarrow geometry is from glyph U+21D0 in the font KaTeX Main
doubleleftarrow: "M262 157\nl10-10c34-36 62.7-77 86-123 3.3-8 5-13.3 5-16 0-5.3-6.7-8-20-8-7.3\n 0-12.2.5-14.5 1.5-2.3 1-4.8 4.5-7.5 10.5-49.3 97.3-121.7 169.3-217 216-28\n 14-57.3 25-88 33-6.7 2-11 3.8-13 5.5-2 1.7-3 4.2-3 7.5s1 5.8 3 7.5\nc2 1.7 6.3 3.5 13 5.5 68 17.3 128.2 47.8 180.5 91.5 52.3 43.7 93.8 96.2 124.5\n 157.5 9.3 8 15.3 12.3 18 13h6c12-.7 18-4 18-10 0-2-1.7-7-5-15-23.3-46-52-87\n-86-123l-10-10h399738v-40H218c328 0 0 0 0 0l-10-8c-26.7-20-65.7-43-117-69 2.7\n-2 6-3.7 10-5 36.7-16 72.3-37.3 107-64l10-8h399782v-40z\nm8 0v40h399730v-40zm0 194v40h399730v-40z",
// doublerightarrow is from glyph U+21D2 in font KaTeX Main
doublerightarrow: "M399738 392l\n-10 10c-34 36-62.7 77-86 123-3.3 8-5 13.3-5 16 0 5.3 6.7 8 20 8 7.3 0 12.2-.5\n 14.5-1.5 2.3-1 4.8-4.5 7.5-10.5 49.3-97.3 121.7-169.3 217-216 28-14 57.3-25 88\n-33 6.7-2 11-3.8 13-5.5 2-1.7 3-4.2 3-7.5s-1-5.8-3-7.5c-2-1.7-6.3-3.5-13-5.5-68\n-17.3-128.2-47.8-180.5-91.5-52.3-43.7-93.8-96.2-124.5-157.5-9.3-8-15.3-12.3-18\n-13h-6c-12 .7-18 4-18 10 0 2 1.7 7 5 15 23.3 46 52 87 86 123l10 10H0v40h399782\nc-328 0 0 0 0 0l10 8c26.7 20 65.7 43 117 69-2.7 2-6 3.7-10 5-36.7 16-72.3 37.3\n-107 64l-10 8H0v40zM0 157v40h399730v-40zm0 194v40h399730v-40z",
// leftarrow is from glyph U+2190 in font KaTeX Main
leftarrow: "M400000 241H110l3-3c68.7-52.7 113.7-120\n 135-202 4-14.7 6-23 6-25 0-7.3-7-11-21-11-8 0-13.2.8-15.5 2.5-2.3 1.7-4.2 5.8\n-5.5 12.5-1.3 4.7-2.7 10.3-4 17-12 48.7-34.8 92-68.5 130S65.3 228.3 18 247\nc-10 4-16 7.7-18 11 0 8.7 6 14.3 18 17 47.3 18.7 87.8 47 121.5 85S196 441.3 208\n 490c.7 2 1.3 5 2 9s1.2 6.7 1.5 8c.3 1.3 1 3.3 2 6s2.2 4.5 3.5 5.5c1.3 1 3.3\n 1.8 6 2.5s6 1 10 1c14 0 21-3.7 21-11 0-2-2-10.3-6-25-20-79.3-65-146.7-135-202\n l-3-3h399890zM100 241v40h399900v-40z",
// overbrace is from glyphs U+23A9/23A8/23A7 in font KaTeX_Size4-Regular
leftbrace: "M6 548l-6-6v-35l6-11c56-104 135.3-181.3 238-232 57.3-28.7 117\n-45 179-50h399577v120H403c-43.3 7-81 15-113 26-100.7 33-179.7 91-237 174-2.7\n 5-6 9-10 13-.7 1-7.3 1-20 1H6z",
leftbraceunder: "M0 6l6-6h17c12.688 0 19.313.3 20 1 4 4 7.313 8.3 10 13\n 35.313 51.3 80.813 93.8 136.5 127.5 55.688 33.7 117.188 55.8 184.5 66.5.688\n 0 2 .3 4 1 18.688 2.7 76 4.3 172 5h399450v120H429l-6-1c-124.688-8-235-61.7\n-331-161C60.687 138.7 32.312 99.3 7 54L0 41V6z",
// overgroup is from the MnSymbol package (public domain)
leftgroup: "M400000 80\nH435C64 80 168.3 229.4 21 260c-5.9 1.2-18 0-18 0-2 0-3-1-3-3v-38C76 61 257 0\n 435 0h399565z",
leftgroupunder: "M400000 262\nH435C64 262 168.3 112.6 21 82c-5.9-1.2-18 0-18 0-2 0-3 1-3 3v38c76 158 257 219\n 435 219h399565z",
// Harpoons are from glyph U+21BD in font KaTeX Main
leftharpoon: "M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3\n-3.3 10.2-9.5 20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5\n-18.3 3-21-1.3-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7\n-196 228-6.7 4.7-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40z",
leftharpoonplus: "M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3-3.3 10.2-9.5\n 20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5-18.3 3-21-1.3\n-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7-196 228-6.7 4.7\n-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40zM0 435v40h400000v-40z\nm0 0v40h400000v-40z",
leftharpoondown: "M7 241c-4 4-6.333 8.667-7 14 0 5.333.667 9 2 11s5.333\n 5.333 12 10c90.667 54 156 130 196 228 3.333 10.667 6.333 16.333 9 17 2 .667 5\n 1 9 1h5c10.667 0 16.667-2 18-6 2-2.667 1-9.667-3-21-32-87.333-82.667-157.667\n-152-211l-3-3h399907v-40zM93 281 H400000 v-40L7 241z",
leftharpoondownplus: "M7 435c-4 4-6.3 8.7-7 14 0 5.3.7 9 2 11s5.3 5.3 12\n 10c90.7 54 156 130 196 228 3.3 10.7 6.3 16.3 9 17 2 .7 5 1 9 1h5c10.7 0 16.7\n-2 18-6 2-2.7 1-9.7-3-21-32-87.3-82.7-157.7-152-211l-3-3h399907v-40H7zm93 0\nv40h399900v-40zM0 241v40h399900v-40zm0 0v40h399900v-40z",
// hook is from glyph U+21A9 in font KaTeX Main
lefthook: "M400000 281 H103s-33-11.2-61-33.5S0 197.3 0 164s14.2-61.2 42.5\n-83.5C70.8 58.2 104 47 142 47 c16.7 0 25 6.7 25 20 0 12-8.7 18.7-26 20-40 3.3\n-68.7 15.7-86 37-10 12-15 25.3-15 40 0 22.7 9.8 40.7 29.5 54 19.7 13.3 43.5 21\n 71.5 23h399859zM103 281v-40h399897v40z",
leftlinesegment: "M40 281 V428 H0 V94 H40 V241 H400000 v40z\nM40 281 V428 H0 V94 H40 V241 H400000 v40z",
leftmapsto: "M40 281 V448H0V74H40V241H400000v40z\nM40 281 V448H0V74H40V241H400000v40z",
// tofrom is from glyph U+21C4 in font KaTeX AMS Regular
leftToFrom: "M0 147h400000v40H0zm0 214c68 40 115.7 95.7 143 167h22c15.3 0 23\n-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69-70-101l-7-8h399905v-40H95l7-8\nc28.7-32 52-65.7 70-101 10.7-23.3 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 265.3\n 68 321 0 361zm0-174v-40h399900v40zm100 154v40h399900v-40z",
longequal: "M0 50 h400000 v40H0z m0 194h40000v40H0z\nM0 50 h400000 v40H0z m0 194h40000v40H0z",
midbrace: "M200428 334\nc-100.7-8.3-195.3-44-280-108-55.3-42-101.7-93-139-153l-9-14c-2.7 4-5.7 8.7-9 14\n-53.3 86.7-123.7 153-211 199-66.7 36-137.3 56.3-212 62H0V214h199568c178.3-11.7\n 311.7-78.3 403-201 6-8 9.7-12 11-12 .7-.7 6.7-1 18-1s17.3.3 18 1c1.3 0 5 4 11\n 12 44.7 59.3 101.3 106.3 170 141s145.3 54.3 229 60h199572v120z",
midbraceunder: "M199572 214\nc100.7 8.3 195.3 44 280 108 55.3 42 101.7 93 139 153l9 14c2.7-4 5.7-8.7 9-14\n 53.3-86.7 123.7-153 211-199 66.7-36 137.3-56.3 212-62h199568v120H200432c-178.3\n 11.7-311.7 78.3-403 201-6 8-9.7 12-11 12-.7.7-6.7 1-18 1s-17.3-.3-18-1c-1.3 0\n-5-4-11-12-44.7-59.3-101.3-106.3-170-141s-145.3-54.3-229-60H0V214z",
oiintSize1: "M512.6 71.6c272.6 0 320.3 106.8 320.3 178.2 0 70.8-47.7 177.6\n-320.3 177.6S193.1 320.6 193.1 249.8c0-71.4 46.9-178.2 319.5-178.2z\nm368.1 178.2c0-86.4-60.9-215.4-368.1-215.4-306.4 0-367.3 129-367.3 215.4 0 85.8\n60.9 214.8 367.3 214.8 307.2 0 368.1-129 368.1-214.8z",
oiintSize2: "M757.8 100.1c384.7 0 451.1 137.6 451.1 230 0 91.3-66.4 228.8\n-451.1 228.8-386.3 0-452.7-137.5-452.7-228.8 0-92.4 66.4-230 452.7-230z\nm502.4 230c0-111.2-82.4-277.2-502.4-277.2s-504 166-504 277.2\nc0 110 84 276 504 276s502.4-166 502.4-276z",
oiiintSize1: "M681.4 71.6c408.9 0 480.5 106.8 480.5 178.2 0 70.8-71.6 177.6\n-480.5 177.6S202.1 320.6 202.1 249.8c0-71.4 70.5-178.2 479.3-178.2z\nm525.8 178.2c0-86.4-86.8-215.4-525.7-215.4-437.9 0-524.7 129-524.7 215.4 0\n85.8 86.8 214.8 524.7 214.8 438.9 0 525.7-129 525.7-214.8z",
oiiintSize2: "M1021.2 53c603.6 0 707.8 165.8 707.8 277.2 0 110-104.2 275.8\n-707.8 275.8-606 0-710.2-165.8-710.2-275.8C311 218.8 415.2 53 1021.2 53z\nm770.4 277.1c0-131.2-126.4-327.6-770.5-327.6S248.4 198.9 248.4 330.1\nc0 130 128.8 326.4 772.7 326.4s770.5-196.4 770.5-326.4z",
rightarrow: "M0 241v40h399891c-47.3 35.3-84 78-110 128\n-16.7 32-27.7 63.7-33 95 0 1.3-.2 2.7-.5 4-.3 1.3-.5 2.3-.5 3 0 7.3 6.7 11 20\n 11 8 0 13.2-.8 15.5-2.5 2.3-1.7 4.2-5.5 5.5-11.5 2-13.3 5.7-27 11-41 14.7-44.7\n 39-84.5 73-119.5s73.7-60.2 119-75.5c6-2 9-5.7 9-11s-3-9-9-11c-45.3-15.3-85\n-40.5-119-75.5s-58.3-74.8-73-119.5c-4.7-14-8.3-27.3-11-40-1.3-6.7-3.2-10.8-5.5\n-12.5-2.3-1.7-7.5-2.5-15.5-2.5-14 0-21 3.7-21 11 0 2 2 10.3 6 25 20.7 83.3 67\n 151.7 139 205zm0 0v40h399900v-40z",
rightbrace: "M400000 542l\n-6 6h-17c-12.7 0-19.3-.3-20-1-4-4-7.3-8.3-10-13-35.3-51.3-80.8-93.8-136.5-127.5\ns-117.2-55.8-184.5-66.5c-.7 0-2-.3-4-1-18.7-2.7-76-4.3-172-5H0V214h399571l6 1\nc124.7 8 235 61.7 331 161 31.3 33.3 59.7 72.7 85 118l7 13v35z",
rightbraceunder: "M399994 0l6 6v35l-6 11c-56 104-135.3 181.3-238 232-57.3\n 28.7-117 45-179 50H-300V214h399897c43.3-7 81-15 113-26 100.7-33 179.7-91 237\n-174 2.7-5 6-9 10-13 .7-1 7.3-1 20-1h17z",
rightgroup: "M0 80h399565c371 0 266.7 149.4 414 180 5.9 1.2 18 0 18 0 2 0\n 3-1 3-3v-38c-76-158-257-219-435-219H0z",
rightgroupunder: "M0 262h399565c371 0 266.7-149.4 414-180 5.9-1.2 18 0 18\n 0 2 0 3 1 3 3v38c-76 158-257 219-435 219H0z",
rightharpoon: "M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3\n-3.7-15.3-11-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2\n-10.7 0-16.7 2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58\n 69.2 92 94.5zm0 0v40h399900v-40z",
rightharpoonplus: "M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3-3.7-15.3-11\n-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2-10.7 0-16.7\n 2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58 69.2 92 94.5z\nm0 0v40h399900v-40z m100 194v40h399900v-40zm0 0v40h399900v-40z",
rightharpoondown: "M399747 511c0 7.3 6.7 11 20 11 8 0 13-.8 15-2.5s4.7-6.8\n 8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3 8.5-5.8 9.5\n-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3-64.7 57-92 95\n-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 241v40h399900v-40z",
rightharpoondownplus: "M399747 705c0 7.3 6.7 11 20 11 8 0 13-.8\n 15-2.5s4.7-6.8 8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3\n 8.5-5.8 9.5-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3\n-64.7 57-92 95-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 435v40h399900v-40z\nm0-194v40h400000v-40zm0 0v40h400000v-40z",
righthook: "M399859 241c-764 0 0 0 0 0 40-3.3 68.7-15.7 86-37 10-12 15-25.3\n 15-40 0-22.7-9.8-40.7-29.5-54-19.7-13.3-43.5-21-71.5-23-17.3-1.3-26-8-26-20 0\n-13.3 8.7-20 26-20 38 0 71 11.2 99 33.5 0 0 7 5.6 21 16.7 14 11.2 21 33.5 21\n 66.8s-14 61.2-42 83.5c-28 22.3-61 33.5-99 33.5L0 241z M0 281v-40h399859v40z",
rightlinesegment: "M399960 241 V94 h40 V428 h-40 V281 H0 v-40z\nM399960 241 V94 h40 V428 h-40 V281 H0 v-40z",
rightToFrom: "M400000 167c-70.7-42-118-97.7-142-167h-23c-15.3 0-23 .3-23\n 1 0 1.3 5.3 13.7 16 37 18 35.3 41.3 69 70 101l7 8H0v40h399905l-7 8c-28.7 32\n-52 65.7-70 101-10.7 23.3-16 35.7-16 37 0 .7 7.7 1 23 1h23c24-69.3 71.3-125 142\n-167z M100 147v40h399900v-40zM0 341v40h399900v-40z",
// twoheadleftarrow is from glyph U+219E in font KaTeX AMS Regular
twoheadleftarrow: "M0 167c68 40\n 115.7 95.7 143 167h22c15.3 0 23-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69\n-70-101l-7-8h125l9 7c50.7 39.3 85 86 103 140h46c0-4.7-6.3-18.7-19-42-18-35.3\n-40-67.3-66-96l-9-9h399716v-40H284l9-9c26-28.7 48-60.7 66-96 12.7-23.333 19\n-37.333 19-42h-46c-18 54-52.3 100.7-103 140l-9 7H95l7-8c28.7-32 52-65.7 70-101\n 10.7-23.333 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 71.3 68 127 0 167z",
twoheadrightarrow: "M400000 167\nc-68-40-115.7-95.7-143-167h-22c-15.3 0-23 .3-23 1 0 1.3 5.3 13.7 16 37 18 35.3\n 41.3 69 70 101l7 8h-125l-9-7c-50.7-39.3-85-86-103-140h-46c0 4.7 6.3 18.7 19 42\n 18 35.3 40 67.3 66 96l9 9H0v40h399716l-9 9c-26 28.7-48 60.7-66 96-12.7 23.333\n-19 37.333-19 42h46c18-54 52.3-100.7 103-140l9-7h125l-7 8c-28.7 32-52 65.7-70\n 101-10.7 23.333-16 35.7-16 37 0 .7 7.7 1 23 1h22c27.3-71.3 75-127 143-167z",
// tilde1 is a modified version of a glyph from the MnSymbol package
tilde1: "M200 55.538c-77 0-168 73.953-177 73.953-3 0-7\n-2.175-9-5.437L2 97c-1-2-2-4-2-6 0-4 2-7 5-9l20-12C116 12 171 0 207 0c86 0\n 114 68 191 68 78 0 168-68 177-68 4 0 7 2 9 5l12 19c1 2.175 2 4.35 2 6.525 0\n 4.35-2 7.613-5 9.788l-19 13.05c-92 63.077-116.937 75.308-183 76.128\n-68.267.847-113-73.952-191-73.952z",
// ditto tilde2, tilde3, & tilde4
tilde2: "M344 55.266c-142 0-300.638 81.316-311.5 86.418\n-8.01 3.762-22.5 10.91-23.5 5.562L1 120c-1-2-1-3-1-4 0-5 3-9 8-10l18.4-9C160.9\n 31.9 283 0 358 0c148 0 188 122 331 122s314-97 326-97c4 0 8 2 10 7l7 21.114\nc1 2.14 1 3.21 1 4.28 0 5.347-3 9.626-7 10.696l-22.3 12.622C852.6 158.372 751\n 181.476 676 181.476c-149 0-189-126.21-332-126.21z",
tilde3: "M786 59C457 59 32 175.242 13 175.242c-6 0-10-3.457\n-11-10.37L.15 138c-1-7 3-12 10-13l19.2-6.4C378.4 40.7 634.3 0 804.3 0c337 0\n 411.8 157 746.8 157 328 0 754-112 773-112 5 0 10 3 11 9l1 14.075c1 8.066-.697\n 16.595-6.697 17.492l-21.052 7.31c-367.9 98.146-609.15 122.696-778.15 122.696\n -338 0-409-156.573-744-156.573z",
tilde4: "M786 58C457 58 32 177.487 13 177.487c-6 0-10-3.345\n-11-10.035L.15 143c-1-7 3-12 10-13l22-6.7C381.2 35 637.15 0 807.15 0c337 0 409\n 177 744 177 328 0 754-127 773-127 5 0 10 3 11 9l1 14.794c1 7.805-3 13.38-9\n 14.495l-20.7 5.574c-366.85 99.79-607.3 139.372-776.3 139.372-338 0-409\n -175.236-744-175.236z",
// vec is from glyph U+20D7 in font KaTeX Main
vec: "M377 20c0-5.333 1.833-10 5.5-14S391 0 397 0c4.667 0 8.667 1.667 12 5\n3.333 2.667 6.667 9 10 19 6.667 24.667 20.333 43.667 41 57 7.333 4.667 11\n10.667 11 18 0 6-1 10-3 12s-6.667 5-14 9c-28.667 14.667-53.667 35.667-75 63\n-1.333 1.333-3.167 3.5-5.5 6.5s-4 4.833-5 5.5c-1 .667-2.5 1.333-4.5 2s-4.333 1\n-7 1c-4.667 0-9.167-1.833-13.5-5.5S337 184 337 178c0-12.667 15.667-32.333 47-59\nH213l-171-1c-8.667-6-13-12.333-13-19 0-4.667 4.333-11.333 13-20h359\nc-16-25.333-24-45-24-59z",
// widehat1 is a modified version of a glyph from the MnSymbol package
widehat1: "M529 0h5l519 115c5 1 9 5 9 10 0 1-1 2-1 3l-4 22\nc-1 5-5 9-11 9h-2L532 67 19 159h-2c-5 0-9-4-11-9l-5-22c-1-6 2-12 8-13z",
// ditto widehat2, widehat3, & widehat4
widehat2: "M1181 0h2l1171 176c6 0 10 5 10 11l-2 23c-1 6-5 10\n-11 10h-1L1182 67 15 220h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z",
widehat3: "M1181 0h2l1171 236c6 0 10 5 10 11l-2 23c-1 6-5 10\n-11 10h-1L1182 67 15 280h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z",
widehat4: "M1181 0h2l1171 296c6 0 10 5 10 11l-2 23c-1 6-5 10\n-11 10h-1L1182 67 15 340h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z",
// widecheck paths are all inverted versions of widehat
widecheck1: "M529,159h5l519,-115c5,-1,9,-5,9,-10c0,-1,-1,-2,-1,-3l-4,-22c-1,\n-5,-5,-9,-11,-9h-2l-512,92l-513,-92h-2c-5,0,-9,4,-11,9l-5,22c-1,6,2,12,8,13z",
widecheck2: "M1181,220h2l1171,-176c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,\n-11,-10h-1l-1168,153l-1167,-153h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z",
widecheck3: "M1181,280h2l1171,-236c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,\n-11,-10h-1l-1168,213l-1167,-213h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z",
widecheck4: "M1181,340h2l1171,-296c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,\n-11,-10h-1l-1168,273l-1167,-273h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z",
// The next ten paths support reaction arrows from the mhchem package.
// Arrows for \ce{<-->} are offset from xAxis by 0.22ex, per mhchem in LaTeX
// baraboveleftarrow is mostly from from glyph U+2190 in font KaTeX Main
baraboveleftarrow: "M400000 620h-399890l3 -3c68.7 -52.7 113.7 -120 135 -202\nc4 -14.7 6 -23 6 -25c0 -7.3 -7 -11 -21 -11c-8 0 -13.2 0.8 -15.5 2.5\nc-2.3 1.7 -4.2 5.8 -5.5 12.5c-1.3 4.7 -2.7 10.3 -4 17c-12 48.7 -34.8 92 -68.5 130\ns-74.2 66.3 -121.5 85c-10 4 -16 7.7 -18 11c0 8.7 6 14.3 18 17c47.3 18.7 87.8 47\n121.5 85s56.5 81.3 68.5 130c0.7 2 1.3 5 2 9s1.2 6.7 1.5 8c0.3 1.3 1 3.3 2 6\ns2.2 4.5 3.5 5.5c1.3 1 3.3 1.8 6 2.5s6 1 10 1c14 0 21 -3.7 21 -11\nc0 -2 -2 -10.3 -6 -25c-20 -79.3 -65 -146.7 -135 -202l-3 -3h399890z\nM100 620v40h399900v-40z M0 241v40h399900v-40zM0 241v40h399900v-40z",
// rightarrowabovebar is mostly from glyph U+2192, KaTeX Main
rightarrowabovebar: "M0 241v40h399891c-47.3 35.3-84 78-110 128-16.7 32\n-27.7 63.7-33 95 0 1.3-.2 2.7-.5 4-.3 1.3-.5 2.3-.5 3 0 7.3 6.7 11 20 11 8 0\n13.2-.8 15.5-2.5 2.3-1.7 4.2-5.5 5.5-11.5 2-13.3 5.7-27 11-41 14.7-44.7 39\n-84.5 73-119.5s73.7-60.2 119-75.5c6-2 9-5.7 9-11s-3-9-9-11c-45.3-15.3-85-40.5\n-119-75.5s-58.3-74.8-73-119.5c-4.7-14-8.3-27.3-11-40-1.3-6.7-3.2-10.8-5.5\n-12.5-2.3-1.7-7.5-2.5-15.5-2.5-14 0-21 3.7-21 11 0 2 2 10.3 6 25 20.7 83.3 67\n151.7 139 205zm96 379h399894v40H0zm0 0h399904v40H0z",
// The short left harpoon has 0.5em (i.e. 500 units) kern on the left end.
// Ref from mhchem.sty: \rlap{\raisebox{-.22ex}{$\kern0.5em
baraboveshortleftharpoon: "M507,435c-4,4,-6.3,8.7,-7,14c0,5.3,0.7,9,2,11\nc1.3,2,5.3,5.3,12,10c90.7,54,156,130,196,228c3.3,10.7,6.3,16.3,9,17\nc2,0.7,5,1,9,1c0,0,5,0,5,0c10.7,0,16.7,-2,18,-6c2,-2.7,1,-9.7,-3,-21\nc-32,-87.3,-82.7,-157.7,-152,-211c0,0,-3,-3,-3,-3l399351,0l0,-40\nc-398570,0,-399437,0,-399437,0z M593 435 v40 H399500 v-40z\nM0 281 v-40 H399908 v40z M0 281 v-40 H399908 v40z",
rightharpoonaboveshortbar: "M0,241 l0,40c399126,0,399993,0,399993,0\nc4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199,\n-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6\nc-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z\nM0 241 v40 H399908 v-40z M0 475 v-40 H399500 v40z M0 475 v-40 H399500 v40z",
shortbaraboveleftharpoon: "M7,435c-4,4,-6.3,8.7,-7,14c0,5.3,0.7,9,2,11\nc1.3,2,5.3,5.3,12,10c90.7,54,156,130,196,228c3.3,10.7,6.3,16.3,9,17c2,0.7,5,1,9,\n1c0,0,5,0,5,0c10.7,0,16.7,-2,18,-6c2,-2.7,1,-9.7,-3,-21c-32,-87.3,-82.7,-157.7,\n-152,-211c0,0,-3,-3,-3,-3l399907,0l0,-40c-399126,0,-399993,0,-399993,0z\nM93 435 v40 H400000 v-40z M500 241 v40 H400000 v-40z M500 241 v40 H400000 v-40z",
shortrightharpoonabovebar: "M53,241l0,40c398570,0,399437,0,399437,0\nc4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199,\n-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6\nc-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z\nM500 241 v40 H399408 v-40z M500 435 v40 H400000 v-40z"
};
// CONCATENATED MODULE: ./src/tree.js
/**
* This node represents a document fragment, which contains elements, but when
* placed into the DOM doesn't have any representation itself. It only contains
* children and doesn't have any DOM node properties.
*/
var tree_DocumentFragment =
/*#__PURE__*/
function () {
// HtmlDomNode
// Never used; needed for satisfying interface.
function DocumentFragment(children) {
this.children = void 0;
this.classes = void 0;
this.height = void 0;
this.depth = void 0;
this.maxFontSize = void 0;
this.style = void 0;
this.children = children;
this.classes = [];
this.height = 0;
this.depth = 0;
this.maxFontSize = 0;
this.style = {};
}
var _proto = DocumentFragment.prototype;
_proto.hasClass = function hasClass(className) {
return utils.contains(this.classes, className);
}
/** Convert the fragment into a node. */
;
_proto.toNode = function toNode() {
var frag = document.createDocumentFragment();
for (var i = 0; i < this.children.length; i++) {
frag.appendChild(this.children[i].toNode());
}
return frag;
}
/** Convert the fragment into HTML markup. */
;
_proto.toMarkup = function toMarkup() {
var markup = ""; // Simply concatenate the markup for the children together.
for (var i = 0; i < this.children.length; i++) {
markup += this.children[i].toMarkup();
}
return markup;
}
/**
* Converts the math node into a string, similar to innerText. Applies to
* MathDomNode's only.
*/
;
_proto.toText = function toText() {
// To avoid this, we would subclass documentFragment separately for
// MathML, but polyfills for subclassing is expensive per PR 1469.
// $FlowFixMe: Only works for ChildType = MathDomNode.
var toText = function toText(child) {
return child.toText();
};
return this.children.map(toText).join("");
};
return DocumentFragment;
}();
// CONCATENATED MODULE: ./src/domTree.js
/**
* These objects store the data about the DOM nodes we create, as well as some
* extra data. They can then be transformed into real DOM nodes with the
* `toNode` function or HTML markup using `toMarkup`. They are useful for both
* storing extra properties on the nodes, as well as providing a way to easily
* work with the DOM.
*
* Similar functions for working with MathML nodes exist in mathMLTree.js.
*
* TODO: refactor `span` and `anchor` into common superclass when
* target environments support class inheritance
*/
/**
* Create an HTML className based on a list of classes. In addition to joining
* with spaces, we also remove empty classes.
*/
var createClass = function createClass(classes) {
return classes.filter(function (cls) {
return cls;
}).join(" ");
};
var initNode = function initNode(classes, options, style) {
this.classes = classes || [];
this.attributes = {};
this.height = 0;
this.depth = 0;
this.maxFontSize = 0;
this.style = style || {};
if (options) {
if (options.style.isTight()) {
this.classes.push("mtight");
}
var color = options.getColor();
if (color) {
this.style.color = color;
}
}
};
/**
* Convert into an HTML node
*/
var _toNode = function toNode(tagName) {
var node = document.createElement(tagName); // Apply the class
node.className = createClass(this.classes); // Apply inline styles
for (var style in this.style) {
if (this.style.hasOwnProperty(style)) {
// $FlowFixMe Flow doesn't seem to understand span.style's type.
node.style[style] = this.style[style];
}
} // Apply attributes
for (var attr in this.attributes) {
if (this.attributes.hasOwnProperty(attr)) {
node.setAttribute(attr, this.attributes[attr]);
}
} // Append the children, also as HTML nodes
for (var i = 0; i < this.children.length; i++) {
node.appendChild(this.children[i].toNode());
}
return node;
};
/**
* Convert into an HTML markup string
*/
var _toMarkup = function toMarkup(tagName) {
var markup = "<" + tagName; // Add the class
if (this.classes.length) {
markup += " class=\"" + utils.escape(createClass(this.classes)) + "\"";
}
var styles = ""; // Add the styles, after hyphenation
for (var style in this.style) {
if (this.style.hasOwnProperty(style)) {
styles += utils.hyphenate(style) + ":" + this.style[style] + ";";
}
}
if (styles) {
markup += " style=\"" + utils.escape(styles) + "\"";
} // Add the attributes
for (var attr in this.attributes) {
if (this.attributes.hasOwnProperty(attr)) {
markup += " " + attr + "=\"" + utils.escape(this.attributes[attr]) + "\"";
}
}
markup += ">"; // Add the markup of the children, also as markup
for (var i = 0; i < this.children.length; i++) {
markup += this.children[i].toMarkup();
}
markup += "</" + tagName + ">";
return markup;
}; // Making the type below exact with all optional fields doesn't work due to
// - https://github.com/facebook/flow/issues/4582
// - https://github.com/facebook/flow/issues/5688
// However, since *all* fields are optional, $Shape<> works as suggested in 5688
// above.
// This type does not include all CSS properties. Additional properties should
// be added as needed.
/**
* This node represents a span node, with a className, a list of children, and
* an inline style. It also contains information about its height, depth, and
* maxFontSize.
*
* Represents two types with different uses: SvgSpan to wrap an SVG and DomSpan
* otherwise. This typesafety is important when HTML builders access a span's
* children.
*/
var domTree_Span =
/*#__PURE__*/
function () {
function Span(classes, children, options, style) {
this.children = void 0;
this.attributes = void 0;
this.classes = void 0;
this.height = void 0;
this.depth = void 0;
this.width = void 0;
this.maxFontSize = void 0;
this.style = void 0;
initNode.call(this, classes, options, style);
this.children = children || [];
}
/**
* Sets an arbitrary attribute on the span. Warning: use this wisely. Not
* all browsers support attributes the same, and having too many custom
* attributes is probably bad.
*/
var _proto = Span.prototype;
_proto.setAttribute = function setAttribute(attribute, value) {
this.attributes[attribute] = value;
};
_proto.hasClass = function hasClass(className) {
return utils.contains(this.classes, className);
};
_proto.toNode = function toNode() {
return _toNode.call(this, "span");
};
_proto.toMarkup = function toMarkup() {
return _toMarkup.call(this, "span");
};
return Span;
}();
/**
* This node represents an anchor (<a>) element with a hyperlink. See `span`
* for further details.
*/
var domTree_Anchor =
/*#__PURE__*/
function () {
function Anchor(href, classes, children, options) {
this.children = void 0;
this.attributes = void 0;
this.classes = void 0;
this.height = void 0;
this.depth = void 0;
this.maxFontSize = void 0;
this.style = void 0;
initNode.call(this, classes, options);
this.children = children || [];
this.setAttribute('href', href);
}
var _proto2 = Anchor.prototype;
_proto2.setAttribute = function setAttribute(attribute, value) {
this.attributes[attribute] = value;
};
_proto2.hasClass = function hasClass(className) {
return utils.contains(this.classes, className);
};
_proto2.toNode = function toNode() {
return _toNode.call(this, "a");
};
_proto2.toMarkup = function toMarkup() {
return _toMarkup.call(this, "a");
};
return Anchor;
}();
/**
* This node represents an image embed (<img>) element.
*/
var domTree_Img =
/*#__PURE__*/
function () {
function Img(src, alt, style) {
this.src = void 0;
this.alt = void 0;
this.classes = void 0;
this.height = void 0;
this.depth = void 0;
this.maxFontSize = void 0;
this.style = void 0;
this.alt = alt;
this.src = src;
this.classes = ["mord"];
this.style = style;
}
var _proto3 = Img.prototype;
_proto3.hasClass = function hasClass(className) {
return utils.contains(this.classes, className);
};
_proto3.toNode = function toNode() {
var node = document.createElement("img");
node.src = this.src;
node.alt = this.alt;
node.className = "mord"; // Apply inline styles
for (var style in this.style) {
if (this.style.hasOwnProperty(style)) {
// $FlowFixMe
node.style[style] = this.style[style];
}
}
return node;
};
_proto3.toMarkup = function toMarkup() {
var markup = "<img src='" + this.src + " 'alt='" + this.alt + "' "; // Add the styles, after hyphenation
var styles = "";
for (var style in this.style) {
if (this.style.hasOwnProperty(style)) {
styles += utils.hyphenate(style) + ":" + this.style[style] + ";";
}
}
if (styles) {
markup += " style=\"" + utils.escape(styles) + "\"";
}
markup += "'/>";
return markup;
};
return Img;
}();
var iCombinations = {
'î': "\u0131\u0302",
'ï': "\u0131\u0308",
'í': "\u0131\u0301",
// 'ī': '\u0131\u0304', // enable when we add Extended Latin
'ì': "\u0131\u0300"
};
/**
* A symbol node contains information about a single symbol. It either renders
* to a single text node, or a span with a single text node in it, depending on
* whether it has CSS classes, styles, or needs italic correction.
*/
var domTree_SymbolNode =
/*#__PURE__*/
function () {
function SymbolNode(text, height, depth, italic, skew, width, classes, style) {
this.text = void 0;
this.height = void 0;
this.depth = void 0;
this.italic = void 0;
this.skew = void 0;
this.width = void 0;
this.maxFontSize = void 0;
this.classes = void 0;
this.style = void 0;
this.text = text;
this.height = height || 0;
this.depth = depth || 0;
this.italic = italic || 0;
this.skew = skew || 0;
this.width = width || 0;
this.classes = classes || [];
this.style = style || {};
this.maxFontSize = 0; // Mark text from non-Latin scripts with specific classes so that we
// can specify which fonts to use. This allows us to render these
// characters with a serif font in situations where the browser would
// either default to a sans serif or render a placeholder character.
// We use CSS class names like cjk_fallback, hangul_fallback and
// brahmic_fallback. See ./unicodeScripts.js for the set of possible
// script names
var script = scriptFromCodepoint(this.text.charCodeAt(0));
if (script) {
this.classes.push(script + "_fallback");
}
if (/[îïíì]/.test(this.text)) {
// add ī when we add Extended Latin
this.text = iCombinations[this.text];
}
}
var _proto4 = SymbolNode.prototype;
_proto4.hasClass = function hasClass(className) {
return utils.contains(this.classes, className);
}
/**
* Creates a text node or span from a symbol node. Note that a span is only
* created if it is needed.
*/
;
_proto4.toNode = function toNode() {
var node = document.createTextNode(this.text);
var span = null;
if (this.italic > 0) {
span = document.createElement("span");
span.style.marginRight = this.italic + "em";
}
if (this.classes.length > 0) {
span = span || document.createElement("span");
span.className = createClass(this.classes);
}
for (var style in this.style) {
if (this.style.hasOwnProperty(style)) {
span = span || document.createElement("span"); // $FlowFixMe Flow doesn't seem to understand span.style's type.
span.style[style] = this.style[style];
}
}
if (span) {
span.appendChild(node);
return span;
} else {
return node;
}
}
/**
* Creates markup for a symbol node.
*/
;
_proto4.toMarkup = function toMarkup() {
// TODO(alpert): More duplication than I'd like from
// span.prototype.toMarkup and symbolNode.prototype.toNode...
var needsSpan = false;
var markup = "<span";
if (this.classes.length) {
needsSpan = true;
markup += " class=\"";
markup += utils.escape(createClass(this.classes));
markup += "\"";
}
var styles = "";
if (this.italic > 0) {
styles += "margin-right:" + this.italic + "em;";
}
for (var style in this.style) {
if (this.style.hasOwnProperty(style)) {
styles += utils.hyphenate(style) + ":" + this.style[style] + ";";
}
}
if (styles) {
needsSpan = true;
markup += " style=\"" + utils.escape(styles) + "\"";
}
var escaped = utils.escape(this.text);
if (needsSpan) {
markup += ">";
markup += escaped;
markup += "</span>";
return markup;
} else {
return escaped;
}
};
return SymbolNode;
}();
/**
* SVG nodes are used to render stretchy wide elements.
*/
var SvgNode =
/*#__PURE__*/
function () {
function SvgNode(children, attributes) {
this.children = void 0;
this.attributes = void 0;
this.children = children || [];
this.attributes = attributes || {};
}
var _proto5 = SvgNode.prototype;
_proto5.toNode = function toNode() {
var svgNS = "http://www.w3.org/2000/svg";
var node = document.createElementNS(svgNS, "svg"); // Apply attributes
for (var attr in this.attributes) {
if (Object.prototype.hasOwnProperty.call(this.attributes, attr)) {
node.setAttribute(attr, this.attributes[attr]);
}
}
for (var i = 0; i < this.children.length; i++) {
node.appendChild(this.children[i].toNode());
}
return node;
};
_proto5.toMarkup = function toMarkup() {
var markup = "<svg"; // Apply attributes
for (var attr in this.attributes) {
if (Object.prototype.hasOwnProperty.call(this.attributes, attr)) {
markup += " " + attr + "='" + this.attributes[attr] + "'";
}
}
markup += ">";
for (var i = 0; i < this.children.length; i++) {
markup += this.children[i].toMarkup();
}
markup += "</svg>";
return markup;
};
return SvgNode;
}();
var domTree_PathNode =
/*#__PURE__*/
function () {
function PathNode(pathName, alternate) {
this.pathName = void 0;
this.alternate = void 0;
this.pathName = pathName;
this.alternate = alternate; // Used only for \sqrt
}
var _proto6 = PathNode.prototype;
_proto6.toNode = function toNode() {
var svgNS = "http://www.w3.org/2000/svg";
var node = document.createElementNS(svgNS, "path");
if (this.alternate) {
node.setAttribute("d", this.alternate);
} else {
node.setAttribute("d", svgGeometry_path[this.pathName]);
}
return node;
};
_proto6.toMarkup = function toMarkup() {
if (this.alternate) {
return "<path d='" + this.alternate + "'/>";
} else {
return "<path d='" + svgGeometry_path[this.pathName] + "'/>";
}
};
return PathNode;
}();
var LineNode =
/*#__PURE__*/
function () {
function LineNode(attributes) {
this.attributes = void 0;
this.attributes = attributes || {};
}
var _proto7 = LineNode.prototype;
_proto7.toNode = function toNode() {
var svgNS = "http://www.w3.org/2000/svg";
var node = document.createElementNS(svgNS, "line"); // Apply attributes
for (var attr in this.attributes) {
if (Object.prototype.hasOwnProperty.call(this.attributes, attr)) {
node.setAttribute(attr, this.attributes[attr]);
}
}
return node;
};
_proto7.toMarkup = function toMarkup() {
var markup = "<line";
for (var attr in this.attributes) {
if (Object.prototype.hasOwnProperty.call(this.attributes, attr)) {
markup += " " + attr + "='" + this.attributes[attr] + "'";
}
}
markup += "/>";
return markup;
};
return LineNode;
}();
function assertSymbolDomNode(group) {
if (group instanceof domTree_SymbolNode) {
return group;
} else {
throw new Error("Expected symbolNode but got " + String(group) + ".");
}
}
function assertSpan(group) {
if (group instanceof domTree_Span) {
return group;
} else {
throw new Error("Expected span<HtmlDomNode> but got " + String(group) + ".");
}
}
// CONCATENATED MODULE: ./submodules/katex-fonts/fontMetricsData.js
// This file is GENERATED by buildMetrics.sh. DO NOT MODIFY.
/* harmony default export */ var fontMetricsData = ({
"AMS-Regular": {
"65": [0, 0.68889, 0, 0, 0.72222],
"66": [0, 0.68889, 0, 0, 0.66667],
"67": [0, 0.68889, 0, 0, 0.72222],
"68": [0, 0.68889, 0, 0, 0.72222],
"69": [0, 0.68889, 0, 0, 0.66667],
"70": [0, 0.68889, 0, 0, 0.61111],
"71": [0, 0.68889, 0, 0, 0.77778],
"72": [0, 0.68889, 0, 0, 0.77778],
"73": [0, 0.68889, 0, 0, 0.38889],
"74": [0.16667, 0.68889, 0, 0, 0.5],
"75": [0, 0.68889, 0, 0, 0.77778],
"76": [0, 0.68889, 0, 0, 0.66667],
"77": [0, 0.68889, 0, 0, 0.94445],
"78": [0, 0.68889, 0, 0, 0.72222],
"79": [0.16667, 0.68889, 0, 0, 0.77778],
"80": [0, 0.68889, 0, 0, 0.61111],
"81": [0.16667, 0.68889, 0, 0, 0.77778],
"82": [0, 0.68889, 0, 0, 0.72222],
"83": [0, 0.68889, 0, 0, 0.55556],
"84": [0, 0.68889, 0, 0, 0.66667],
"85": [0, 0.68889, 0, 0, 0.72222],
"86": [0, 0.68889, 0, 0, 0.72222],
"87": [0, 0.68889, 0, 0, 1.0],
"88": [0, 0.68889, 0, 0, 0.72222],
"89": [0, 0.68889, 0, 0, 0.72222],
"90": [0, 0.68889, 0, 0, 0.66667],
"107": [0, 0.68889, 0, 0, 0.55556],
"165": [0, 0.675, 0.025, 0, 0.75],
"174": [0.15559, 0.69224, 0, 0, 0.94666],
"240": [0, 0.68889, 0, 0, 0.55556],
"295": [0, 0.68889, 0, 0, 0.54028],
"710": [0, 0.825, 0, 0, 2.33334],
"732": [0, 0.9, 0, 0, 2.33334],
"770": [0, 0.825, 0, 0, 2.33334],
"771": [0, 0.9, 0, 0, 2.33334],
"989": [0.08167, 0.58167, 0, 0, 0.77778],
"1008": [0, 0.43056, 0.04028, 0, 0.66667],
"8245": [0, 0.54986, 0, 0, 0.275],
"8463": [0, 0.68889, 0, 0, 0.54028],
"8487": [0, 0.68889, 0, 0, 0.72222],
"8498": [0, 0.68889, 0, 0, 0.55556],
"8502": [0, 0.68889, 0, 0, 0.66667],
"8503": [0, 0.68889, 0, 0, 0.44445],
"8504": [0, 0.68889, 0, 0, 0.66667],
"8513": [0, 0.68889, 0, 0, 0.63889],
"8592": [-0.03598, 0.46402, 0, 0, 0.5],
"8594": [-0.03598, 0.46402, 0, 0, 0.5],
"8602": [-0.13313, 0.36687, 0, 0, 1.0],
"8603": [-0.13313, 0.36687, 0, 0, 1.0],
"8606": [0.01354, 0.52239, 0, 0, 1.0],
"8608": [0.01354, 0.52239, 0, 0, 1.0],
"8610": [0.01354, 0.52239, 0, 0, 1.11111],
"8611": [0.01354, 0.52239, 0, 0, 1.11111],
"8619": [0, 0.54986, 0, 0, 1.0],
"8620": [0, 0.54986, 0, 0, 1.0],
"8621": [-0.13313, 0.37788, 0, 0, 1.38889],
"8622": [-0.13313, 0.36687, 0, 0, 1.0],
"8624": [0, 0.69224, 0, 0, 0.5],
"8625": [0, 0.69224, 0, 0, 0.5],
"8630": [0, 0.43056, 0, 0, 1.0],
"8631": [0, 0.43056, 0, 0, 1.0],
"8634": [0.08198, 0.58198, 0, 0, 0.77778],
"8635": [0.08198, 0.58198, 0, 0, 0.77778],
"8638": [0.19444, 0.69224, 0, 0, 0.41667],
"8639": [0.19444, 0.69224, 0, 0, 0.41667],
"8642": [0.19444, 0.69224, 0, 0, 0.41667],
"8643": [0.19444, 0.69224, 0, 0, 0.41667],
"8644": [0.1808, 0.675, 0, 0, 1.0],
"8646": [0.1808, 0.675, 0, 0, 1.0],
"8647": [0.1808, 0.675, 0, 0, 1.0],
"8648": [0.19444, 0.69224, 0, 0, 0.83334],
"8649": [0.1808, 0.675, 0, 0, 1.0],
"8650": [0.19444, 0.69224, 0, 0, 0.83334],
"8651": [0.01354, 0.52239, 0, 0, 1.0],
"8652": [0.01354, 0.52239, 0, 0, 1.0],
"8653": [-0.13313, 0.36687, 0, 0, 1.0],
"8654": [-0.13313, 0.36687, 0, 0, 1.0],
"8655": [-0.13313, 0.36687, 0, 0, 1.0],
"8666": [0.13667, 0.63667, 0, 0, 1.0],
"8667": [0.13667, 0.63667, 0, 0, 1.0],
"8669": [-0.13313, 0.37788, 0, 0, 1.0],
"8672": [-0.064, 0.437, 0, 0, 1.334],
"8674": [-0.064, 0.437, 0, 0, 1.334],
"8705": [0, 0.825, 0, 0, 0.5],
"8708": [0, 0.68889, 0, 0, 0.55556],
"8709": [0.08167, 0.58167, 0, 0, 0.77778],
"8717": [0, 0.43056, 0, 0, 0.42917],
"8722": [-0.03598, 0.46402, 0, 0, 0.5],
"8724": [0.08198, 0.69224, 0, 0, 0.77778],
"8726": [0.08167, 0.58167, 0, 0, 0.77778],
"8733": [0, 0.69224, 0, 0, 0.77778],
"8736": [0, 0.69224, 0, 0, 0.72222],
"8737": [0, 0.69224, 0, 0, 0.72222],
"8738": [0.03517, 0.52239, 0, 0, 0.72222],
"8739": [0.08167, 0.58167, 0, 0, 0.22222],
"8740": [0.25142, 0.74111, 0, 0, 0.27778],
"8741": [0.08167, 0.58167, 0, 0, 0.38889],
"8742": [0.25142, 0.74111, 0, 0, 0.5],
"8756": [0, 0.69224, 0, 0, 0.66667],
"8757": [0, 0.69224, 0, 0, 0.66667],
"8764": [-0.13313, 0.36687, 0, 0, 0.77778],
"8765": [-0.13313, 0.37788, 0, 0, 0.77778],
"8769": [-0.13313, 0.36687, 0, 0, 0.77778],
"8770": [-0.03625, 0.46375, 0, 0, 0.77778],
"8774": [0.30274, 0.79383, 0, 0, 0.77778],
"8776": [-0.01688, 0.48312, 0, 0, 0.77778],
"8778": [0.08167, 0.58167, 0, 0, 0.77778],
"8782": [0.06062, 0.54986, 0, 0, 0.77778],
"8783": [0.06062, 0.54986, 0, 0, 0.77778],
"8785": [0.08198, 0.58198, 0, 0, 0.77778],
"8786": [0.08198, 0.58198, 0, 0, 0.77778],
"8787": [0.08198, 0.58198, 0, 0, 0.77778],
"8790": [0, 0.69224, 0, 0, 0.77778],
"8791": [0.22958, 0.72958, 0, 0, 0.77778],
"8796": [0.08198, 0.91667, 0, 0, 0.77778],
"8806": [0.25583, 0.75583, 0, 0, 0.77778],
"8807": [0.25583, 0.75583, 0, 0, 0.77778],
"8808": [0.25142, 0.75726, 0, 0, 0.77778],
"8809": [0.25142, 0.75726, 0, 0, 0.77778],
"8812": [0.25583, 0.75583, 0, 0, 0.5],
"8814": [0.20576, 0.70576, 0, 0, 0.77778],
"8815": [0.20576, 0.70576, 0, 0, 0.77778],
"8816": [0.30274, 0.79383, 0, 0, 0.77778],
"8817": [0.30274, 0.79383, 0, 0, 0.77778],
"8818": [0.22958, 0.72958, 0, 0, 0.77778],
"8819": [0.22958, 0.72958, 0, 0, 0.77778],
"8822": [0.1808, 0.675, 0, 0, 0.77778],
"8823": [0.1808, 0.675, 0, 0, 0.77778],
"8828": [0.13667, 0.63667, 0, 0, 0.77778],
"8829": [0.13667, 0.63667, 0, 0, 0.77778],
"8830": [0.22958, 0.72958, 0, 0, 0.77778],
"8831": [0.22958, 0.72958, 0, 0, 0.77778],
"8832": [0.20576, 0.70576, 0, 0, 0.77778],
"8833": [0.20576, 0.70576, 0, 0, 0.77778],
"8840": [0.30274, 0.79383, 0, 0, 0.77778],
"8841": [0.30274, 0.79383, 0, 0, 0.77778],
"8842": [0.13597, 0.63597, 0, 0, 0.77778],
"8843": [0.13597, 0.63597, 0, 0, 0.77778],
"8847": [0.03517, 0.54986, 0, 0, 0.77778],
"8848": [0.03517, 0.54986, 0, 0, 0.77778],
"8858": [0.08198, 0.58198, 0, 0, 0.77778],
"8859": [0.08198, 0.58198, 0, 0, 0.77778],
"8861": [0.08198, 0.58198, 0, 0, 0.77778],
"8862": [0, 0.675, 0, 0, 0.77778],
"8863": [0, 0.675, 0, 0, 0.77778],
"8864": [0, 0.675, 0, 0, 0.77778],
"8865": [0, 0.675, 0, 0, 0.77778],
"8872": [0, 0.69224, 0, 0, 0.61111],
"8873": [0, 0.69224, 0, 0, 0.72222],
"8874": [0, 0.69224, 0, 0, 0.88889],
"8876": [0, 0.68889, 0, 0, 0.61111],
"8877": [0, 0.68889, 0, 0, 0.61111],
"8878": [0, 0.68889, 0, 0, 0.72222],
"8879": [0, 0.68889, 0, 0, 0.72222],
"8882": [0.03517, 0.54986, 0, 0, 0.77778],
"8883": [0.03517, 0.54986, 0, 0, 0.77778],
"8884": [0.13667, 0.63667, 0, 0, 0.77778],
"8885": [0.13667, 0.63667, 0, 0, 0.77778],
"8888": [0, 0.54986, 0, 0, 1.11111],
"8890": [0.19444, 0.43056, 0, 0, 0.55556],
"8891": [0.19444, 0.69224, 0, 0, 0.61111],
"8892": [0.19444, 0.69224, 0, 0, 0.61111],
"8901": [0, 0.54986, 0, 0, 0.27778],
"8903": [0.08167, 0.58167, 0, 0, 0.77778],
"8905": [0.08167, 0.58167, 0, 0, 0.77778],
"8906": [0.08167, 0.58167, 0, 0, 0.77778],
"8907": [0, 0.69224, 0, 0, 0.77778],
"8908": [0, 0.69224, 0, 0, 0.77778],
"8909": [-0.03598, 0.46402, 0, 0, 0.77778],
"8910": [0, 0.54986, 0, 0, 0.76042],
"8911": [0, 0.54986, 0, 0, 0.76042],
"8912": [0.03517, 0.54986, 0, 0, 0.77778],
"8913": [0.03517, 0.54986, 0, 0, 0.77778],
"8914": [0, 0.54986, 0, 0, 0.66667],
"8915": [0, 0.54986, 0, 0, 0.66667],
"8916": [0, 0.69224, 0, 0, 0.66667],
"8918": [0.0391, 0.5391, 0, 0, 0.77778],
"8919": [0.0391, 0.5391, 0, 0, 0.77778],
"8920": [0.03517, 0.54986, 0, 0, 1.33334],
"8921": [0.03517, 0.54986, 0, 0, 1.33334],
"8922": [0.38569, 0.88569, 0, 0, 0.77778],
"8923": [0.38569, 0.88569, 0, 0, 0.77778],
"8926": [0.13667, 0.63667, 0, 0, 0.77778],
"8927": [0.13667, 0.63667, 0, 0, 0.77778],
"8928": [0.30274, 0.79383, 0, 0, 0.77778],
"8929": [0.30274, 0.79383, 0, 0, 0.77778],
"8934": [0.23222, 0.74111, 0, 0, 0.77778],
"8935": [0.23222, 0.74111, 0, 0, 0.77778],
"8936": [0.23222, 0.74111, 0, 0, 0.77778],
"8937": [0.23222, 0.74111, 0, 0, 0.77778],
"8938": [0.20576, 0.70576, 0, 0, 0.77778],
"8939": [0.20576, 0.70576, 0, 0, 0.77778],
"8940": [0.30274, 0.79383, 0, 0, 0.77778],
"8941": [0.30274, 0.79383, 0, 0, 0.77778],
"8994": [0.19444, 0.69224, 0, 0, 0.77778],
"8995": [0.19444, 0.69224, 0, 0, 0.77778],
"9416": [0.15559, 0.69224, 0, 0, 0.90222],
"9484": [0, 0.69224, 0, 0, 0.5],
"9488": [0, 0.69224, 0, 0, 0.5],
"9492": [0, 0.37788, 0, 0, 0.5],
"9496": [0, 0.37788, 0, 0, 0.5],
"9585": [0.19444, 0.68889, 0, 0, 0.88889],
"9586": [0.19444, 0.74111, 0, 0, 0.88889],
"9632": [0, 0.675, 0, 0, 0.77778],
"9633": [0, 0.675, 0, 0, 0.77778],
"9650": [0, 0.54986, 0, 0, 0.72222],
"9651": [0, 0.54986, 0, 0, 0.72222],
"9654": [0.03517, 0.54986, 0, 0, 0.77778],
"9660": [0, 0.54986, 0, 0, 0.72222],
"9661": [0, 0.54986, 0, 0, 0.72222],
"9664": [0.03517, 0.54986, 0, 0, 0.77778],
"9674": [0.11111, 0.69224, 0, 0, 0.66667],
"9733": [0.19444, 0.69224, 0, 0, 0.94445],
"10003": [0, 0.69224, 0, 0, 0.83334],
"10016": [0, 0.69224, 0, 0, 0.83334],
"10731": [0.11111, 0.69224, 0, 0, 0.66667],
"10846": [0.19444, 0.75583, 0, 0, 0.61111],
"10877": [0.13667, 0.63667, 0, 0, 0.77778],
"10878": [0.13667, 0.63667, 0, 0, 0.77778],
"10885": [0.25583, 0.75583, 0, 0, 0.77778],
"10886": [0.25583, 0.75583, 0, 0, 0.77778],
"10887": [0.13597, 0.63597, 0, 0, 0.77778],
"10888": [0.13597, 0.63597, 0, 0, 0.77778],
"10889": [0.26167, 0.75726, 0, 0, 0.77778],
"10890": [0.26167, 0.75726, 0, 0, 0.77778],
"10891": [0.48256, 0.98256, 0, 0, 0.77778],
"10892": [0.48256, 0.98256, 0, 0, 0.77778],
"10901": [0.13667, 0.63667, 0, 0, 0.77778],
"10902": [0.13667, 0.63667, 0, 0, 0.77778],
"10933": [0.25142, 0.75726, 0, 0, 0.77778],
"10934": [0.25142, 0.75726, 0, 0, 0.77778],
"10935": [0.26167, 0.75726, 0, 0, 0.77778],
"10936": [0.26167, 0.75726, 0, 0, 0.77778],
"10937": [0.26167, 0.75726, 0, 0, 0.77778],
"10938": [0.26167, 0.75726, 0, 0, 0.77778],
"10949": [0.25583, 0.75583, 0, 0, 0.77778],
"10950": [0.25583, 0.75583, 0, 0, 0.77778],
"10955": [0.28481, 0.79383, 0, 0, 0.77778],
"10956": [0.28481, 0.79383, 0, 0, 0.77778],
"57350": [0.08167, 0.58167, 0, 0, 0.22222],
"57351": [0.08167, 0.58167, 0, 0, 0.38889],
"57352": [0.08167, 0.58167, 0, 0, 0.77778],
"57353": [0, 0.43056, 0.04028, 0, 0.66667],
"57356": [0.25142, 0.75726, 0, 0, 0.77778],
"57357": [0.25142, 0.75726, 0, 0, 0.77778],
"57358": [0.41951, 0.91951, 0, 0, 0.77778],
"57359": [0.30274, 0.79383, 0, 0, 0.77778],
"57360": [0.30274, 0.79383, 0, 0, 0.77778],
"57361": [0.41951, 0.91951, 0, 0, 0.77778],
"57366": [0.25142, 0.75726, 0, 0, 0.77778],
"57367": [0.25142, 0.75726, 0, 0, 0.77778],
"57368": [0.25142, 0.75726, 0, 0, 0.77778],
"57369": [0.25142, 0.75726, 0, 0, 0.77778],
"57370": [0.13597, 0.63597, 0, 0, 0.77778],
"57371": [0.13597, 0.63597, 0, 0, 0.77778]
},
"Caligraphic-Regular": {
"48": [0, 0.43056, 0, 0, 0.5],
"49": [0, 0.43056, 0, 0, 0.5],
"50": [0, 0.43056, 0, 0, 0.5],
"51": [0.19444, 0.43056, 0, 0, 0.5],
"52": [0.19444, 0.43056, 0, 0, 0.5],
"53": [0.19444, 0.43056, 0, 0, 0.5],
"54": [0, 0.64444, 0, 0, 0.5],
"55": [0.19444, 0.43056, 0, 0, 0.5],
"56": [0, 0.64444, 0, 0, 0.5],
"57": [0.19444, 0.43056, 0, 0, 0.5],
"65": [0, 0.68333, 0, 0.19445, 0.79847],
"66": [0, 0.68333, 0.03041, 0.13889, 0.65681],
"67": [0, 0.68333, 0.05834, 0.13889, 0.52653],
"68": [0, 0.68333, 0.02778, 0.08334, 0.77139],
"69": [0, 0.68333, 0.08944, 0.11111, 0.52778],
"70": [0, 0.68333, 0.09931, 0.11111, 0.71875],
"71": [0.09722, 0.68333, 0.0593, 0.11111, 0.59487],
"72": [0, 0.68333, 0.00965, 0.11111, 0.84452],
"73": [0, 0.68333, 0.07382, 0, 0.54452],
"74": [0.09722, 0.68333, 0.18472, 0.16667, 0.67778],
"75": [0, 0.68333, 0.01445, 0.05556, 0.76195],
"76": [0, 0.68333, 0, 0.13889, 0.68972],
"77": [0, 0.68333, 0, 0.13889, 1.2009],
"78": [0, 0.68333, 0.14736, 0.08334, 0.82049],
"79": [0, 0.68333, 0.02778, 0.11111, 0.79611],
"80": [0, 0.68333, 0.08222, 0.08334, 0.69556],
"81": [0.09722, 0.68333, 0, 0.11111, 0.81667],
"82": [0, 0.68333, 0, 0.08334, 0.8475],
"83": [0, 0.68333, 0.075, 0.13889, 0.60556],
"84": [0, 0.68333, 0.25417, 0, 0.54464],
"85": [0, 0.68333, 0.09931, 0.08334, 0.62583],
"86": [0, 0.68333, 0.08222, 0, 0.61278],
"87": [0, 0.68333, 0.08222, 0.08334, 0.98778],
"88": [0, 0.68333, 0.14643, 0.13889, 0.7133],
"89": [0.09722, 0.68333, 0.08222, 0.08334, 0.66834],
"90": [0, 0.68333, 0.07944, 0.13889, 0.72473]
},
"Fraktur-Regular": {
"33": [0, 0.69141, 0, 0, 0.29574],
"34": [0, 0.69141, 0, 0, 0.21471],
"38": [0, 0.69141, 0, 0, 0.73786],
"39": [0, 0.69141, 0, 0, 0.21201],
"40": [0.24982, 0.74947, 0, 0, 0.38865],
"41": [0.24982, 0.74947, 0, 0, 0.38865],
"42": [0, 0.62119, 0, 0, 0.27764],
"43": [0.08319, 0.58283, 0, 0, 0.75623],
"44": [0, 0.10803, 0, 0, 0.27764],
"45": [0.08319, 0.58283, 0, 0, 0.75623],
"46": [0, 0.10803, 0, 0, 0.27764],
"47": [0.24982, 0.74947, 0, 0, 0.50181],
"48": [0, 0.47534, 0, 0, 0.50181],
"49": [0, 0.47534, 0, 0, 0.50181],
"50": [0, 0.47534, 0, 0, 0.50181],
"51": [0.18906, 0.47534, 0, 0, 0.50181],
"52": [0.18906, 0.47534, 0, 0, 0.50181],
"53": [0.18906, 0.47534, 0, 0, 0.50181],
"54": [0, 0.69141, 0, 0, 0.50181],
"55": [0.18906, 0.47534, 0, 0, 0.50181],
"56": [0, 0.69141, 0, 0, 0.50181],
"57": [0.18906, 0.47534, 0, 0, 0.50181],
"58": [0, 0.47534, 0, 0, 0.21606],
"59": [0.12604, 0.47534, 0, 0, 0.21606],
"61": [-0.13099, 0.36866, 0, 0, 0.75623],
"63": [0, 0.69141, 0, 0, 0.36245],
"65": [0, 0.69141, 0, 0, 0.7176],
"66": [0, 0.69141, 0, 0, 0.88397],
"67": [0, 0.69141, 0, 0, 0.61254],
"68": [0, 0.69141, 0, 0, 0.83158],
"69": [0, 0.69141, 0, 0, 0.66278],
"70": [0.12604, 0.69141, 0, 0, 0.61119],
"71": [0, 0.69141, 0, 0, 0.78539],
"72": [0.06302, 0.69141, 0, 0, 0.7203],
"73": [0, 0.69141, 0, 0, 0.55448],
"74": [0.12604, 0.69141, 0, 0, 0.55231],
"75": [0, 0.69141, 0, 0, 0.66845],
"76": [0, 0.69141, 0, 0, 0.66602],
"77": [0, 0.69141, 0, 0, 1.04953],
"78": [0, 0.69141, 0, 0, 0.83212],
"79": [0, 0.69141, 0, 0, 0.82699],
"80": [0.18906, 0.69141, 0, 0, 0.82753],
"81": [0.03781, 0.69141, 0, 0, 0.82699],
"82": [0, 0.69141, 0, 0, 0.82807],
"83": [0, 0.69141, 0, 0, 0.82861],
"84": [0, 0.69141, 0, 0, 0.66899],
"85": [0, 0.69141, 0, 0, 0.64576],
"86": [0, 0.69141, 0, 0, 0.83131],
"87": [0, 0.69141, 0, 0, 1.04602],
"88": [0, 0.69141, 0, 0, 0.71922],
"89": [0.18906, 0.69141, 0, 0, 0.83293],
"90": [0.12604, 0.69141, 0, 0, 0.60201],
"91": [0.24982, 0.74947, 0, 0, 0.27764],
"93": [0.24982, 0.74947, 0, 0, 0.27764],
"94": [0, 0.69141, 0, 0, 0.49965],
"97": [0, 0.47534, 0, 0, 0.50046],
"98": [0, 0.69141, 0, 0, 0.51315],
"99": [0, 0.47534, 0, 0, 0.38946],
"100": [0, 0.62119, 0, 0, 0.49857],
"101": [0, 0.47534, 0, 0, 0.40053],
"102": [0.18906, 0.69141, 0, 0, 0.32626],
"103": [0.18906, 0.47534, 0, 0, 0.5037],
"104": [0.18906, 0.69141, 0, 0, 0.52126],
"105": [0, 0.69141, 0, 0, 0.27899],
"106": [0, 0.69141, 0, 0, 0.28088],
"107": [0, 0.69141, 0, 0, 0.38946],
"108": [0, 0.69141, 0, 0, 0.27953],
"109": [0, 0.47534, 0, 0, 0.76676],
"110": [0, 0.47534, 0, 0, 0.52666],
"111": [0, 0.47534, 0, 0, 0.48885],
"112": [0.18906, 0.52396, 0, 0, 0.50046],
"113": [0.18906, 0.47534, 0, 0, 0.48912],
"114": [0, 0.47534, 0, 0, 0.38919],
"115": [0, 0.47534, 0, 0, 0.44266],
"116": [0, 0.62119, 0, 0, 0.33301],
"117": [0, 0.47534, 0, 0, 0.5172],
"118": [0, 0.52396, 0, 0, 0.5118],
"119": [0, 0.52396, 0, 0, 0.77351],
"120": [0.18906, 0.47534, 0, 0, 0.38865],
"121": [0.18906, 0.47534, 0, 0, 0.49884],
"122": [0.18906, 0.47534, 0, 0, 0.39054],
"8216": [0, 0.69141, 0, 0, 0.21471],
"8217": [0, 0.69141, 0, 0, 0.21471],
"58112": [0, 0.62119, 0, 0, 0.49749],
"58113": [0, 0.62119, 0, 0, 0.4983],
"58114": [0.18906, 0.69141, 0, 0, 0.33328],
"58115": [0.18906, 0.69141, 0, 0, 0.32923],
"58116": [0.18906, 0.47534, 0, 0, 0.50343],
"58117": [0, 0.69141, 0, 0, 0.33301],
"58118": [0, 0.62119, 0, 0, 0.33409],
"58119": [0, 0.47534, 0, 0, 0.50073]
},
"Main-Bold": {
"33": [0, 0.69444, 0, 0, 0.35],
"34": [0, 0.69444, 0, 0, 0.60278],
"35": [0.19444, 0.69444, 0, 0, 0.95833],
"36": [0.05556, 0.75, 0, 0, 0.575],
"37": [0.05556, 0.75, 0, 0, 0.95833],
"38": [0, 0.69444, 0, 0, 0.89444],
"39": [0, 0.69444, 0, 0, 0.31944],
"40": [0.25, 0.75, 0, 0, 0.44722],
"41": [0.25, 0.75, 0, 0, 0.44722],
"42": [0, 0.75, 0, 0, 0.575],
"43": [0.13333, 0.63333, 0, 0, 0.89444],
"44": [0.19444, 0.15556, 0, 0, 0.31944],
"45": [0, 0.44444, 0, 0, 0.38333],
"46": [0, 0.15556, 0, 0, 0.31944],
"47": [0.25, 0.75, 0, 0, 0.575],
"48": [0, 0.64444, 0, 0, 0.575],
"49": [0, 0.64444, 0, 0, 0.575],
"50": [0, 0.64444, 0, 0, 0.575],
"51": [0, 0.64444, 0, 0, 0.575],
"52": [0, 0.64444, 0, 0, 0.575],
"53": [0, 0.64444, 0, 0, 0.575],
"54": [0, 0.64444, 0, 0, 0.575],
"55": [0, 0.64444, 0, 0, 0.575],
"56": [0, 0.64444, 0, 0, 0.575],
"57": [0, 0.64444, 0, 0, 0.575],
"58": [0, 0.44444, 0, 0, 0.31944],
"59": [0.19444, 0.44444, 0, 0, 0.31944],
"60": [0.08556, 0.58556, 0, 0, 0.89444],
"61": [-0.10889, 0.39111, 0, 0, 0.89444],
"62": [0.08556, 0.58556, 0, 0, 0.89444],
"63": [0, 0.69444, 0, 0, 0.54305],
"64": [0, 0.69444, 0, 0, 0.89444],
"65": [0, 0.68611, 0, 0, 0.86944],
"66": [0, 0.68611, 0, 0, 0.81805],
"67": [0, 0.68611, 0, 0, 0.83055],
"68": [0, 0.68611, 0, 0, 0.88194],
"69": [0, 0.68611, 0, 0, 0.75555],
"70": [0, 0.68611, 0, 0, 0.72361],
"71": [0, 0.68611, 0, 0, 0.90416],
"72": [0, 0.68611, 0, 0, 0.9],
"73": [0, 0.68611, 0, 0, 0.43611],
"74": [0, 0.68611, 0, 0, 0.59444],
"75": [0, 0.68611, 0, 0, 0.90138],
"76": [0, 0.68611, 0, 0, 0.69166],
"77": [0, 0.68611, 0, 0, 1.09166],
"78": [0, 0.68611, 0, 0, 0.9],
"79": [0, 0.68611, 0, 0, 0.86388],
"80": [0, 0.68611, 0, 0, 0.78611],
"81": [0.19444, 0.68611, 0, 0, 0.86388],
"82": [0, 0.68611, 0, 0, 0.8625],
"83": [0, 0.68611, 0, 0, 0.63889],
"84": [0, 0.68611, 0, 0, 0.8],
"85": [0, 0.68611, 0, 0, 0.88472],
"86": [0, 0.68611, 0.01597, 0, 0.86944],
"87": [0, 0.68611, 0.01597, 0, 1.18888],
"88": [0, 0.68611, 0, 0, 0.86944],
"89": [0, 0.68611, 0.02875, 0, 0.86944],
"90": [0, 0.68611, 0, 0, 0.70277],
"91": [0.25, 0.75, 0, 0, 0.31944],
"92": [0.25, 0.75, 0, 0, 0.575],
"93": [0.25, 0.75, 0, 0, 0.31944],
"94": [0, 0.69444, 0, 0, 0.575],
"95": [0.31, 0.13444, 0.03194, 0, 0.575],
"97": [0, 0.44444, 0, 0, 0.55902],
"98": [0, 0.69444, 0, 0, 0.63889],
"99": [0, 0.44444, 0, 0, 0.51111],
"100": [0, 0.69444, 0, 0, 0.63889],
"101": [0, 0.44444, 0, 0, 0.52708],
"102": [0, 0.69444, 0.10903, 0, 0.35139],
"103": [0.19444, 0.44444, 0.01597, 0, 0.575],
"104": [0, 0.69444, 0, 0, 0.63889],
"105": [0, 0.69444, 0, 0, 0.31944],
"106": [0.19444, 0.69444, 0, 0, 0.35139],
"107": [0, 0.69444, 0, 0, 0.60694],
"108": [0, 0.69444, 0, 0, 0.31944],
"109": [0, 0.44444, 0, 0, 0.95833],
"110": [0, 0.44444, 0, 0, 0.63889],
"111": [0, 0.44444, 0, 0, 0.575],
"112": [0.19444, 0.44444, 0, 0, 0.63889],
"113": [0.19444, 0.44444, 0, 0, 0.60694],
"114": [0, 0.44444, 0, 0, 0.47361],
"115": [0, 0.44444, 0, 0, 0.45361],
"116": [0, 0.63492, 0, 0, 0.44722],
"117": [0, 0.44444, 0, 0, 0.63889],
"118": [0, 0.44444, 0.01597, 0, 0.60694],
"119": [0, 0.44444, 0.01597, 0, 0.83055],
"120": [0, 0.44444, 0, 0, 0.60694],
"121": [0.19444, 0.44444, 0.01597, 0, 0.60694],
"122": [0, 0.44444, 0, 0, 0.51111],
"123": [0.25, 0.75, 0, 0, 0.575],
"124": [0.25, 0.75, 0, 0, 0.31944],
"125": [0.25, 0.75, 0, 0, 0.575],
"126": [0.35, 0.34444, 0, 0, 0.575],
"168": [0, 0.69444, 0, 0, 0.575],
"172": [0, 0.44444, 0, 0, 0.76666],
"176": [0, 0.69444, 0, 0, 0.86944],
"177": [0.13333, 0.63333, 0, 0, 0.89444],
"184": [0.17014, 0, 0, 0, 0.51111],
"198": [0, 0.68611, 0, 0, 1.04166],
"215": [0.13333, 0.63333, 0, 0, 0.89444],
"216": [0.04861, 0.73472, 0, 0, 0.89444],
"223": [0, 0.69444, 0, 0, 0.59722],
"230": [0, 0.44444, 0, 0, 0.83055],
"247": [0.13333, 0.63333, 0, 0, 0.89444],
"248": [0.09722, 0.54167, 0, 0, 0.575],
"305": [0, 0.44444, 0, 0, 0.31944],
"338": [0, 0.68611, 0, 0, 1.16944],
"339": [0, 0.44444, 0, 0, 0.89444],
"567": [0.19444, 0.44444, 0, 0, 0.35139],
"710": [0, 0.69444, 0, 0, 0.575],
"711": [0, 0.63194, 0, 0, 0.575],
"713": [0, 0.59611, 0, 0, 0.575],
"714": [0, 0.69444, 0, 0, 0.575],
"715": [0, 0.69444, 0, 0, 0.575],
"728": [0, 0.69444, 0, 0, 0.575],
"729": [0, 0.69444, 0, 0, 0.31944],
"730": [0, 0.69444, 0, 0, 0.86944],
"732": [0, 0.69444, 0, 0, 0.575],
"733": [0, 0.69444, 0, 0, 0.575],
"915": [0, 0.68611, 0, 0, 0.69166],
"916": [0, 0.68611, 0, 0, 0.95833],
"920": [0, 0.68611, 0, 0, 0.89444],
"923": [0, 0.68611, 0, 0, 0.80555],
"926": [0, 0.68611, 0, 0, 0.76666],
"928": [0, 0.68611, 0, 0, 0.9],
"931": [0, 0.68611, 0, 0, 0.83055],
"933": [0, 0.68611, 0, 0, 0.89444],
"934": [0, 0.68611, 0, 0, 0.83055],
"936": [0, 0.68611, 0, 0, 0.89444],
"937": [0, 0.68611, 0, 0, 0.83055],
"8211": [0, 0.44444, 0.03194, 0, 0.575],
"8212": [0, 0.44444, 0.03194, 0, 1.14999],
"8216": [0, 0.69444, 0, 0, 0.31944],
"8217": [0, 0.69444, 0, 0, 0.31944],
"8220": [0, 0.69444, 0, 0, 0.60278],
"8221": [0, 0.69444, 0, 0, 0.60278],
"8224": [0.19444, 0.69444, 0, 0, 0.51111],
"8225": [0.19444, 0.69444, 0, 0, 0.51111],
"8242": [0, 0.55556, 0, 0, 0.34444],
"8407": [0, 0.72444, 0.15486, 0, 0.575],
"8463": [0, 0.69444, 0, 0, 0.66759],
"8465": [0, 0.69444, 0, 0, 0.83055],
"8467": [0, 0.69444, 0, 0, 0.47361],
"8472": [0.19444, 0.44444, 0, 0, 0.74027],
"8476": [0, 0.69444, 0, 0, 0.83055],
"8501": [0, 0.69444, 0, 0, 0.70277],
"8592": [-0.10889, 0.39111, 0, 0, 1.14999],
"8593": [0.19444, 0.69444, 0, 0, 0.575],
"8594": [-0.10889, 0.39111, 0, 0, 1.14999],
"8595": [0.19444, 0.69444, 0, 0, 0.575],
"8596": [-0.10889, 0.39111, 0, 0, 1.14999],
"8597": [0.25, 0.75, 0, 0, 0.575],
"8598": [0.19444, 0.69444, 0, 0, 1.14999],
"8599": [0.19444, 0.69444, 0, 0, 1.14999],
"8600": [0.19444, 0.69444, 0, 0, 1.14999],
"8601": [0.19444, 0.69444, 0, 0, 1.14999],
"8636": [-0.10889, 0.39111, 0, 0, 1.14999],
"8637": [-0.10889, 0.39111, 0, 0, 1.14999],
"8640": [-0.10889, 0.39111, 0, 0, 1.14999],
"8641": [-0.10889, 0.39111, 0, 0, 1.14999],
"8656": [-0.10889, 0.39111, 0, 0, 1.14999],
"8657": [0.19444, 0.69444, 0, 0, 0.70277],
"8658": [-0.10889, 0.39111, 0, 0, 1.14999],
"8659": [0.19444, 0.69444, 0, 0, 0.70277],
"8660": [-0.10889, 0.39111, 0, 0, 1.14999],
"8661": [0.25, 0.75, 0, 0, 0.70277],
"8704": [0, 0.69444, 0, 0, 0.63889],
"8706": [0, 0.69444, 0.06389, 0, 0.62847],
"8707": [0, 0.69444, 0, 0, 0.63889],
"8709": [0.05556, 0.75, 0, 0, 0.575],
"8711": [0, 0.68611, 0, 0, 0.95833],
"8712": [0.08556, 0.58556, 0, 0, 0.76666],
"8715": [0.08556, 0.58556, 0, 0, 0.76666],
"8722": [0.13333, 0.63333, 0, 0, 0.89444],
"8723": [0.13333, 0.63333, 0, 0, 0.89444],
"8725": [0.25, 0.75, 0, 0, 0.575],
"8726": [0.25, 0.75, 0, 0, 0.575],
"8727": [-0.02778, 0.47222, 0, 0, 0.575],
"8728": [-0.02639, 0.47361, 0, 0, 0.575],
"8729": [-0.02639, 0.47361, 0, 0, 0.575],
"8730": [0.18, 0.82, 0, 0, 0.95833],
"8733": [0, 0.44444, 0, 0, 0.89444],
"8734": [0, 0.44444, 0, 0, 1.14999],
"8736": [0, 0.69224, 0, 0, 0.72222],
"8739": [0.25, 0.75, 0, 0, 0.31944],
"8741": [0.25, 0.75, 0, 0, 0.575],
"8743": [0, 0.55556, 0, 0, 0.76666],
"8744": [0, 0.55556, 0, 0, 0.76666],
"8745": [0, 0.55556, 0, 0, 0.76666],
"8746": [0, 0.55556, 0, 0, 0.76666],
"8747": [0.19444, 0.69444, 0.12778, 0, 0.56875],
"8764": [-0.10889, 0.39111, 0, 0, 0.89444],
"8768": [0.19444, 0.69444, 0, 0, 0.31944],
"8771": [0.00222, 0.50222, 0, 0, 0.89444],
"8776": [0.02444, 0.52444, 0, 0, 0.89444],
"8781": [0.00222, 0.50222, 0, 0, 0.89444],
"8801": [0.00222, 0.50222, 0, 0, 0.89444],
"8804": [0.19667, 0.69667, 0, 0, 0.89444],
"8805": [0.19667, 0.69667, 0, 0, 0.89444],
"8810": [0.08556, 0.58556, 0, 0, 1.14999],
"8811": [0.08556, 0.58556, 0, 0, 1.14999],
"8826": [0.08556, 0.58556, 0, 0, 0.89444],
"8827": [0.08556, 0.58556, 0, 0, 0.89444],
"8834": [0.08556, 0.58556, 0, 0, 0.89444],
"8835": [0.08556, 0.58556, 0, 0, 0.89444],
"8838": [0.19667, 0.69667, 0, 0, 0.89444],
"8839": [0.19667, 0.69667, 0, 0, 0.89444],
"8846": [0, 0.55556, 0, 0, 0.76666],
"8849": [0.19667, 0.69667, 0, 0, 0.89444],
"8850": [0.19667, 0.69667, 0, 0, 0.89444],
"8851": [0, 0.55556, 0, 0, 0.76666],
"8852": [0, 0.55556, 0, 0, 0.76666],
"8853": [0.13333, 0.63333, 0, 0, 0.89444],
"8854": [0.13333, 0.63333, 0, 0, 0.89444],
"8855": [0.13333, 0.63333, 0, 0, 0.89444],
"8856": [0.13333, 0.63333, 0, 0, 0.89444],
"8857": [0.13333, 0.63333, 0, 0, 0.89444],
"8866": [0, 0.69444, 0, 0, 0.70277],
"8867": [0, 0.69444, 0, 0, 0.70277],
"8868": [0, 0.69444, 0, 0, 0.89444],
"8869": [0, 0.69444, 0, 0, 0.89444],
"8900": [-0.02639, 0.47361, 0, 0, 0.575],
"8901": [-0.02639, 0.47361, 0, 0, 0.31944],
"8902": [-0.02778, 0.47222, 0, 0, 0.575],
"8968": [0.25, 0.75, 0, 0, 0.51111],
"8969": [0.25, 0.75, 0, 0, 0.51111],
"8970": [0.25, 0.75, 0, 0, 0.51111],
"8971": [0.25, 0.75, 0, 0, 0.51111],
"8994": [-0.13889, 0.36111, 0, 0, 1.14999],
"8995": [-0.13889, 0.36111, 0, 0, 1.14999],
"9651": [0.19444, 0.69444, 0, 0, 1.02222],
"9657": [-0.02778, 0.47222, 0, 0, 0.575],
"9661": [0.19444, 0.69444, 0, 0, 1.02222],
"9667": [-0.02778, 0.47222, 0, 0, 0.575],
"9711": [0.19444, 0.69444, 0, 0, 1.14999],
"9824": [0.12963, 0.69444, 0, 0, 0.89444],
"9825": [0.12963, 0.69444, 0, 0, 0.89444],
"9826": [0.12963, 0.69444, 0, 0, 0.89444],
"9827": [0.12963, 0.69444, 0, 0, 0.89444],
"9837": [0, 0.75, 0, 0, 0.44722],
"9838": [0.19444, 0.69444, 0, 0, 0.44722],
"9839": [0.19444, 0.69444, 0, 0, 0.44722],
"10216": [0.25, 0.75, 0, 0, 0.44722],
"10217": [0.25, 0.75, 0, 0, 0.44722],
"10815": [0, 0.68611, 0, 0, 0.9],
"10927": [0.19667, 0.69667, 0, 0, 0.89444],
"10928": [0.19667, 0.69667, 0, 0, 0.89444],
"57376": [0.19444, 0.69444, 0, 0, 0]
},
"Main-BoldItalic": {
"33": [0, 0.69444, 0.11417, 0, 0.38611],
"34": [0, 0.69444, 0.07939, 0, 0.62055],
"35": [0.19444, 0.69444, 0.06833, 0, 0.94444],
"37": [0.05556, 0.75, 0.12861, 0, 0.94444],
"38": [0, 0.69444, 0.08528, 0, 0.88555],
"39": [0, 0.69444, 0.12945, 0, 0.35555],
"40": [0.25, 0.75, 0.15806, 0, 0.47333],
"41": [0.25, 0.75, 0.03306, 0, 0.47333],
"42": [0, 0.75, 0.14333, 0, 0.59111],
"43": [0.10333, 0.60333, 0.03306, 0, 0.88555],
"44": [0.19444, 0.14722, 0, 0, 0.35555],
"45": [0, 0.44444, 0.02611, 0, 0.41444],
"46": [0, 0.14722, 0, 0, 0.35555],
"47": [0.25, 0.75, 0.15806, 0, 0.59111],
"48": [0, 0.64444, 0.13167, 0, 0.59111],
"49": [0, 0.64444, 0.13167, 0, 0.59111],
"50": [0, 0.64444, 0.13167, 0, 0.59111],
"51": [0, 0.64444, 0.13167, 0, 0.59111],
"52": [0.19444, 0.64444, 0.13167, 0, 0.59111],
"53": [0, 0.64444, 0.13167, 0, 0.59111],
"54": [0, 0.64444, 0.13167, 0, 0.59111],
"55": [0.19444, 0.64444, 0.13167, 0, 0.59111],
"56": [0, 0.64444, 0.13167, 0, 0.59111],
"57": [0, 0.64444, 0.13167, 0, 0.59111],
"58": [0, 0.44444, 0.06695, 0, 0.35555],
"59": [0.19444, 0.44444, 0.06695, 0, 0.35555],
"61": [-0.10889, 0.39111, 0.06833, 0, 0.88555],
"63": [0, 0.69444, 0.11472, 0, 0.59111],
"64": [0, 0.69444, 0.09208, 0, 0.88555],
"65": [0, 0.68611, 0, 0, 0.86555],
"66": [0, 0.68611, 0.0992, 0, 0.81666],
"67": [0, 0.68611, 0.14208, 0, 0.82666],
"68": [0, 0.68611, 0.09062, 0, 0.87555],
"69": [0, 0.68611, 0.11431, 0, 0.75666],
"70": [0, 0.68611, 0.12903, 0, 0.72722],
"71": [0, 0.68611, 0.07347, 0, 0.89527],
"72": [0, 0.68611, 0.17208, 0, 0.8961],
"73": [0, 0.68611, 0.15681, 0, 0.47166],
"74": [0, 0.68611, 0.145, 0, 0.61055],
"75": [0, 0.68611, 0.14208, 0, 0.89499],
"76": [0, 0.68611, 0, 0, 0.69777],
"77": [0, 0.68611, 0.17208, 0, 1.07277],
"78": [0, 0.68611, 0.17208, 0, 0.8961],
"79": [0, 0.68611, 0.09062, 0, 0.85499],
"80": [0, 0.68611, 0.0992, 0, 0.78721],
"81": [0.19444, 0.68611, 0.09062, 0, 0.85499],
"82": [0, 0.68611, 0.02559, 0, 0.85944],
"83": [0, 0.68611, 0.11264, 0, 0.64999],
"84": [0, 0.68611, 0.12903, 0, 0.7961],
"85": [0, 0.68611, 0.17208, 0, 0.88083],
"86": [0, 0.68611, 0.18625, 0, 0.86555],
"87": [0, 0.68611, 0.18625, 0, 1.15999],
"88": [0, 0.68611, 0.15681, 0, 0.86555],
"89": [0, 0.68611, 0.19803, 0, 0.86555],
"90": [0, 0.68611, 0.14208, 0, 0.70888],
"91": [0.25, 0.75, 0.1875, 0, 0.35611],
"93": [0.25, 0.75, 0.09972, 0, 0.35611],
"94": [0, 0.69444, 0.06709, 0, 0.59111],
"95": [0.31, 0.13444, 0.09811, 0, 0.59111],
"97": [0, 0.44444, 0.09426, 0, 0.59111],
"98": [0, 0.69444, 0.07861, 0, 0.53222],
"99": [0, 0.44444, 0.05222, 0, 0.53222],
"100": [0, 0.69444, 0.10861, 0, 0.59111],
"101": [0, 0.44444, 0.085, 0, 0.53222],
"102": [0.19444, 0.69444, 0.21778, 0, 0.4],
"103": [0.19444, 0.44444, 0.105, 0, 0.53222],
"104": [0, 0.69444, 0.09426, 0, 0.59111],
"105": [0, 0.69326, 0.11387, 0, 0.35555],
"106": [0.19444, 0.69326, 0.1672, 0, 0.35555],
"107": [0, 0.69444, 0.11111, 0, 0.53222],
"108": [0, 0.69444, 0.10861, 0, 0.29666],
"109": [0, 0.44444, 0.09426, 0, 0.94444],
"110": [0, 0.44444, 0.09426, 0, 0.64999],
"111": [0, 0.44444, 0.07861, 0, 0.59111],
"112": [0.19444, 0.44444, 0.07861, 0, 0.59111],
"113": [0.19444, 0.44444, 0.105, 0, 0.53222],
"114": [0, 0.44444, 0.11111, 0, 0.50167],
"115": [0, 0.44444, 0.08167, 0, 0.48694],
"116": [0, 0.63492, 0.09639, 0, 0.385],
"117": [0, 0.44444, 0.09426, 0, 0.62055],
"118": [0, 0.44444, 0.11111, 0, 0.53222],
"119": [0, 0.44444, 0.11111, 0, 0.76777],
"120": [0, 0.44444, 0.12583, 0, 0.56055],
"121": [0.19444, 0.44444, 0.105, 0, 0.56166],
"122": [0, 0.44444, 0.13889, 0, 0.49055],
"126": [0.35, 0.34444, 0.11472, 0, 0.59111],
"163": [0, 0.69444, 0, 0, 0.86853],
"168": [0, 0.69444, 0.11473, 0, 0.59111],
"176": [0, 0.69444, 0, 0, 0.94888],
"184": [0.17014, 0, 0, 0, 0.53222],
"198": [0, 0.68611, 0.11431, 0, 1.02277],
"216": [0.04861, 0.73472, 0.09062, 0, 0.88555],
"223": [0.19444, 0.69444, 0.09736, 0, 0.665],
"230": [0, 0.44444, 0.085, 0, 0.82666],
"248": [0.09722, 0.54167, 0.09458, 0, 0.59111],
"305": [0, 0.44444, 0.09426, 0, 0.35555],
"338": [0, 0.68611, 0.11431, 0, 1.14054],
"339": [0, 0.44444, 0.085, 0, 0.82666],
"567": [0.19444, 0.44444, 0.04611, 0, 0.385],
"710": [0, 0.69444, 0.06709, 0, 0.59111],
"711": [0, 0.63194, 0.08271, 0, 0.59111],
"713": [0, 0.59444, 0.10444, 0, 0.59111],
"714": [0, 0.69444, 0.08528, 0, 0.59111],
"715": [0, 0.69444, 0, 0, 0.59111],
"728": [0, 0.69444, 0.10333, 0, 0.59111],
"729": [0, 0.69444, 0.12945, 0, 0.35555],
"730": [0, 0.69444, 0, 0, 0.94888],
"732": [0, 0.69444, 0.11472, 0, 0.59111],
"733": [0, 0.69444, 0.11472, 0, 0.59111],
"915": [0, 0.68611, 0.12903, 0, 0.69777],
"916": [0, 0.68611, 0, 0, 0.94444],
"920": [0, 0.68611, 0.09062, 0, 0.88555],
"923": [0, 0.68611, 0, 0, 0.80666],
"926": [0, 0.68611, 0.15092, 0, 0.76777],
"928": [0, 0.68611, 0.17208, 0, 0.8961],
"931": [0, 0.68611, 0.11431, 0, 0.82666],
"933": [0, 0.68611, 0.10778, 0, 0.88555],
"934": [0, 0.68611, 0.05632, 0, 0.82666],
"936": [0, 0.68611, 0.10778, 0, 0.88555],
"937": [0, 0.68611, 0.0992, 0, 0.82666],
"8211": [0, 0.44444, 0.09811, 0, 0.59111],
"8212": [0, 0.44444, 0.09811, 0, 1.18221],
"8216": [0, 0.69444, 0.12945, 0, 0.35555],
"8217": [0, 0.69444, 0.12945, 0, 0.35555],
"8220": [0, 0.69444, 0.16772, 0, 0.62055],
"8221": [0, 0.69444, 0.07939, 0, 0.62055]
},
"Main-Italic": {
"33": [0, 0.69444, 0.12417, 0, 0.30667],
"34": [0, 0.69444, 0.06961, 0, 0.51444],
"35": [0.19444, 0.69444, 0.06616, 0, 0.81777],
"37": [0.05556, 0.75, 0.13639, 0, 0.81777],
"38": [0, 0.69444, 0.09694, 0, 0.76666],
"39": [0, 0.69444, 0.12417, 0, 0.30667],
"40": [0.25, 0.75, 0.16194, 0, 0.40889],
"41": [0.25, 0.75, 0.03694, 0, 0.40889],
"42": [0, 0.75, 0.14917, 0, 0.51111],
"43": [0.05667, 0.56167, 0.03694, 0, 0.76666],
"44": [0.19444, 0.10556, 0, 0, 0.30667],
"45": [0, 0.43056, 0.02826, 0, 0.35778],
"46": [0, 0.10556, 0, 0, 0.30667],
"47": [0.25, 0.75, 0.16194, 0, 0.51111],
"48": [0, 0.64444, 0.13556, 0, 0.51111],
"49": [0, 0.64444, 0.13556, 0, 0.51111],
"50": [0, 0.64444, 0.13556, 0, 0.51111],
"51": [0, 0.64444, 0.13556, 0, 0.51111],
"52": [0.19444, 0.64444, 0.13556, 0, 0.51111],
"53": [0, 0.64444, 0.13556, 0, 0.51111],
"54": [0, 0.64444, 0.13556, 0, 0.51111],
"55": [0.19444, 0.64444, 0.13556, 0, 0.51111],
"56": [0, 0.64444, 0.13556, 0, 0.51111],
"57": [0, 0.64444, 0.13556, 0, 0.51111],
"58": [0, 0.43056, 0.0582, 0, 0.30667],
"59": [0.19444, 0.43056, 0.0582, 0, 0.30667],
"61": [-0.13313, 0.36687, 0.06616, 0, 0.76666],
"63": [0, 0.69444, 0.1225, 0, 0.51111],
"64": [0, 0.69444, 0.09597, 0, 0.76666],
"65": [0, 0.68333, 0, 0, 0.74333],
"66": [0, 0.68333, 0.10257, 0, 0.70389],
"67": [0, 0.68333, 0.14528, 0, 0.71555],
"68": [0, 0.68333, 0.09403, 0, 0.755],
"69": [0, 0.68333, 0.12028, 0, 0.67833],
"70": [0, 0.68333, 0.13305, 0, 0.65277],
"71": [0, 0.68333, 0.08722, 0, 0.77361],
"72": [0, 0.68333, 0.16389, 0, 0.74333],
"73": [0, 0.68333, 0.15806, 0, 0.38555],
"74": [0, 0.68333, 0.14028, 0, 0.525],
"75": [0, 0.68333, 0.14528, 0, 0.76888],
"76": [0, 0.68333, 0, 0, 0.62722],
"77": [0, 0.68333, 0.16389, 0, 0.89666],
"78": [0, 0.68333, 0.16389, 0, 0.74333],
"79": [0, 0.68333, 0.09403, 0, 0.76666],
"80": [0, 0.68333, 0.10257, 0, 0.67833],
"81": [0.19444, 0.68333, 0.09403, 0, 0.76666],
"82": [0, 0.68333, 0.03868, 0, 0.72944],
"83": [0, 0.68333, 0.11972, 0, 0.56222],
"84": [0, 0.68333, 0.13305, 0, 0.71555],
"85": [0, 0.68333, 0.16389, 0, 0.74333],
"86": [0, 0.68333, 0.18361, 0, 0.74333],
"87": [0, 0.68333, 0.18361, 0, 0.99888],
"88": [0, 0.68333, 0.15806, 0, 0.74333],
"89": [0, 0.68333, 0.19383, 0, 0.74333],
"90": [0, 0.68333, 0.14528, 0, 0.61333],
"91": [0.25, 0.75, 0.1875, 0, 0.30667],
"93": [0.25, 0.75, 0.10528, 0, 0.30667],
"94": [0, 0.69444, 0.06646, 0, 0.51111],
"95": [0.31, 0.12056, 0.09208, 0, 0.51111],
"97": [0, 0.43056, 0.07671, 0, 0.51111],
"98": [0, 0.69444, 0.06312, 0, 0.46],
"99": [0, 0.43056, 0.05653, 0, 0.46],
"100": [0, 0.69444, 0.10333, 0, 0.51111],
"101": [0, 0.43056, 0.07514, 0, 0.46],
"102": [0.19444, 0.69444, 0.21194, 0, 0.30667],
"103": [0.19444, 0.43056, 0.08847, 0, 0.46],
"104": [0, 0.69444, 0.07671, 0, 0.51111],
"105": [0, 0.65536, 0.1019, 0, 0.30667],
"106": [0.19444, 0.65536, 0.14467, 0, 0.30667],
"107": [0, 0.69444, 0.10764, 0, 0.46],
"108": [0, 0.69444, 0.10333, 0, 0.25555],
"109": [0, 0.43056, 0.07671, 0, 0.81777],
"110": [0, 0.43056, 0.07671, 0, 0.56222],
"111": [0, 0.43056, 0.06312, 0, 0.51111],
"112": [0.19444, 0.43056, 0.06312, 0, 0.51111],
"113": [0.19444, 0.43056, 0.08847, 0, 0.46],
"114": [0, 0.43056, 0.10764, 0, 0.42166],
"115": [0, 0.43056, 0.08208, 0, 0.40889],
"116": [0, 0.61508, 0.09486, 0, 0.33222],
"117": [0, 0.43056, 0.07671, 0, 0.53666],
"118": [0, 0.43056, 0.10764, 0, 0.46],
"119": [0, 0.43056, 0.10764, 0, 0.66444],
"120": [0, 0.43056, 0.12042, 0, 0.46389],
"121": [0.19444, 0.43056, 0.08847, 0, 0.48555],
"122": [0, 0.43056, 0.12292, 0, 0.40889],
"126": [0.35, 0.31786, 0.11585, 0, 0.51111],
"163": [0, 0.69444, 0, 0, 0.76909],
"168": [0, 0.66786, 0.10474, 0, 0.51111],
"176": [0, 0.69444, 0, 0, 0.83129],
"184": [0.17014, 0, 0, 0, 0.46],
"198": [0, 0.68333, 0.12028, 0, 0.88277],
"216": [0.04861, 0.73194, 0.09403, 0, 0.76666],
"223": [0.19444, 0.69444, 0.10514, 0, 0.53666],
"230": [0, 0.43056, 0.07514, 0, 0.71555],
"248": [0.09722, 0.52778, 0.09194, 0, 0.51111],
"305": [0, 0.43056, 0, 0.02778, 0.32246],
"338": [0, 0.68333, 0.12028, 0, 0.98499],
"339": [0, 0.43056, 0.07514, 0, 0.71555],
"567": [0.19444, 0.43056, 0, 0.08334, 0.38403],
"710": [0, 0.69444, 0.06646, 0, 0.51111],
"711": [0, 0.62847, 0.08295, 0, 0.51111],
"713": [0, 0.56167, 0.10333, 0, 0.51111],
"714": [0, 0.69444, 0.09694, 0, 0.51111],
"715": [0, 0.69444, 0, 0, 0.51111],
"728": [0, 0.69444, 0.10806, 0, 0.51111],
"729": [0, 0.66786, 0.11752, 0, 0.30667],
"730": [0, 0.69444, 0, 0, 0.83129],
"732": [0, 0.66786, 0.11585, 0, 0.51111],
"733": [0, 0.69444, 0.1225, 0, 0.51111],
"915": [0, 0.68333, 0.13305, 0, 0.62722],
"916": [0, 0.68333, 0, 0, 0.81777],
"920": [0, 0.68333, 0.09403, 0, 0.76666],
"923": [0, 0.68333, 0, 0, 0.69222],
"926": [0, 0.68333, 0.15294, 0, 0.66444],
"928": [0, 0.68333, 0.16389, 0, 0.74333],
"931": [0, 0.68333, 0.12028, 0, 0.71555],
"933": [0, 0.68333, 0.11111, 0, 0.76666],
"934": [0, 0.68333, 0.05986, 0, 0.71555],
"936": [0, 0.68333, 0.11111, 0, 0.76666],
"937": [0, 0.68333, 0.10257, 0, 0.71555],
"8211": [0, 0.43056, 0.09208, 0, 0.51111],
"8212": [0, 0.43056, 0.09208, 0, 1.02222],
"8216": [0, 0.69444, 0.12417, 0, 0.30667],
"8217": [0, 0.69444, 0.12417, 0, 0.30667],
"8220": [0, 0.69444, 0.1685, 0, 0.51444],
"8221": [0, 0.69444, 0.06961, 0, 0.51444],
"8463": [0, 0.68889, 0, 0, 0.54028]
},
"Main-Regular": {
"32": [0, 0, 0, 0, 0.25],
"33": [0, 0.69444, 0, 0, 0.27778],
"34": [0, 0.69444, 0, 0, 0.5],
"35": [0.19444, 0.69444, 0, 0, 0.83334],
"36": [0.05556, 0.75, 0, 0, 0.5],
"37": [0.05556, 0.75, 0, 0, 0.83334],
"38": [0, 0.69444, 0, 0, 0.77778],
"39": [0, 0.69444, 0, 0, 0.27778],
"40": [0.25, 0.75, 0, 0, 0.38889],
"41": [0.25, 0.75, 0, 0, 0.38889],
"42": [0, 0.75, 0, 0, 0.5],
"43": [0.08333, 0.58333, 0, 0, 0.77778],
"44": [0.19444, 0.10556, 0, 0, 0.27778],
"45": [0, 0.43056, 0, 0, 0.33333],
"46": [0, 0.10556, 0, 0, 0.27778],
"47": [0.25, 0.75, 0, 0, 0.5],
"48": [0, 0.64444, 0, 0, 0.5],
"49": [0, 0.64444, 0, 0, 0.5],
"50": [0, 0.64444, 0, 0, 0.5],
"51": [0, 0.64444, 0, 0, 0.5],
"52": [0, 0.64444, 0, 0, 0.5],
"53": [0, 0.64444, 0, 0, 0.5],
"54": [0, 0.64444, 0, 0, 0.5],
"55": [0, 0.64444, 0, 0, 0.5],
"56": [0, 0.64444, 0, 0, 0.5],
"57": [0, 0.64444, 0, 0, 0.5],
"58": [0, 0.43056, 0, 0, 0.27778],
"59": [0.19444, 0.43056, 0, 0, 0.27778],
"60": [0.0391, 0.5391, 0, 0, 0.77778],
"61": [-0.13313, 0.36687, 0, 0, 0.77778],
"62": [0.0391, 0.5391, 0, 0, 0.77778],
"63": [0, 0.69444, 0, 0, 0.47222],
"64": [0, 0.69444, 0, 0, 0.77778],
"65": [0, 0.68333, 0, 0, 0.75],
"66": [0, 0.68333, 0, 0, 0.70834],
"67": [0, 0.68333, 0, 0, 0.72222],
"68": [0, 0.68333, 0, 0, 0.76389],
"69": [0, 0.68333, 0, 0, 0.68056],
"70": [0, 0.68333, 0, 0, 0.65278],
"71": [0, 0.68333, 0, 0, 0.78472],
"72": [0, 0.68333, 0, 0, 0.75],
"73": [0, 0.68333, 0, 0, 0.36111],
"74": [0, 0.68333, 0, 0, 0.51389],
"75": [0, 0.68333, 0, 0, 0.77778],
"76": [0, 0.68333, 0, 0, 0.625],
"77": [0, 0.68333, 0, 0, 0.91667],
"78": [0, 0.68333, 0, 0, 0.75],
"79": [0, 0.68333, 0, 0, 0.77778],
"80": [0, 0.68333, 0, 0, 0.68056],
"81": [0.19444, 0.68333, 0, 0, 0.77778],
"82": [0, 0.68333, 0, 0, 0.73611],
"83": [0, 0.68333, 0, 0, 0.55556],
"84": [0, 0.68333, 0, 0, 0.72222],
"85": [0, 0.68333, 0, 0, 0.75],
"86": [0, 0.68333, 0.01389, 0, 0.75],
"87": [0, 0.68333, 0.01389, 0, 1.02778],
"88": [0, 0.68333, 0, 0, 0.75],
"89": [0, 0.68333, 0.025, 0, 0.75],
"90": [0, 0.68333, 0, 0, 0.61111],
"91": [0.25, 0.75, 0, 0, 0.27778],
"92": [0.25, 0.75, 0, 0, 0.5],
"93": [0.25, 0.75, 0, 0, 0.27778],
"94": [0, 0.69444, 0, 0, 0.5],
"95": [0.31, 0.12056, 0.02778, 0, 0.5],
"97": [0, 0.43056, 0, 0, 0.5],
"98": [0, 0.69444, 0, 0, 0.55556],
"99": [0, 0.43056, 0, 0, 0.44445],
"100": [0, 0.69444, 0, 0, 0.55556],
"101": [0, 0.43056, 0, 0, 0.44445],
"102": [0, 0.69444, 0.07778, 0, 0.30556],
"103": [0.19444, 0.43056, 0.01389, 0, 0.5],
"104": [0, 0.69444, 0, 0, 0.55556],
"105": [0, 0.66786, 0, 0, 0.27778],
"106": [0.19444, 0.66786, 0, 0, 0.30556],
"107": [0, 0.69444, 0, 0, 0.52778],
"108": [0, 0.69444, 0, 0, 0.27778],
"109": [0, 0.43056, 0, 0, 0.83334],
"110": [0, 0.43056, 0, 0, 0.55556],
"111": [0, 0.43056, 0, 0, 0.5],
"112": [0.19444, 0.43056, 0, 0, 0.55556],
"113": [0.19444, 0.43056, 0, 0, 0.52778],
"114": [0, 0.43056, 0, 0, 0.39167],
"115": [0, 0.43056, 0, 0, 0.39445],
"116": [0, 0.61508, 0, 0, 0.38889],
"117": [0, 0.43056, 0, 0, 0.55556],
"118": [0, 0.43056, 0.01389, 0, 0.52778],
"119": [0, 0.43056, 0.01389, 0, 0.72222],
"120": [0, 0.43056, 0, 0, 0.52778],
"121": [0.19444, 0.43056, 0.01389, 0, 0.52778],
"122": [0, 0.43056, 0, 0, 0.44445],
"123": [0.25, 0.75, 0, 0, 0.5],
"124": [0.25, 0.75, 0, 0, 0.27778],
"125": [0.25, 0.75, 0, 0, 0.5],
"126": [0.35, 0.31786, 0, 0, 0.5],
"160": [0, 0, 0, 0, 0.25],
"167": [0.19444, 0.69444, 0, 0, 0.44445],
"168": [0, 0.66786, 0, 0, 0.5],
"172": [0, 0.43056, 0, 0, 0.66667],
"176": [0, 0.69444, 0, 0, 0.75],
"177": [0.08333, 0.58333, 0, 0, 0.77778],
"182": [0.19444, 0.69444, 0, 0, 0.61111],
"184": [0.17014, 0, 0, 0, 0.44445],
"198": [0, 0.68333, 0, 0, 0.90278],
"215": [0.08333, 0.58333, 0, 0, 0.77778],
"216": [0.04861, 0.73194, 0, 0, 0.77778],
"223": [0, 0.69444, 0, 0, 0.5],
"230": [0, 0.43056, 0, 0, 0.72222],
"247": [0.08333, 0.58333, 0, 0, 0.77778],
"248": [0.09722, 0.52778, 0, 0, 0.5],
"305": [0, 0.43056, 0, 0, 0.27778],
"338": [0, 0.68333, 0, 0, 1.01389],
"339": [0, 0.43056, 0, 0, 0.77778],
"567": [0.19444, 0.43056, 0, 0, 0.30556],
"710": [0, 0.69444, 0, 0, 0.5],
"711": [0, 0.62847, 0, 0, 0.5],
"713": [0, 0.56778, 0, 0, 0.5],
"714": [0, 0.69444, 0, 0, 0.5],
"715": [0, 0.69444, 0, 0, 0.5],
"728": [0, 0.69444, 0, 0, 0.5],
"729": [0, 0.66786, 0, 0, 0.27778],
"730": [0, 0.69444, 0, 0, 0.75],
"732": [0, 0.66786, 0, 0, 0.5],
"733": [0, 0.69444, 0, 0, 0.5],
"915": [0, 0.68333, 0, 0, 0.625],
"916": [0, 0.68333, 0, 0, 0.83334],
"920": [0, 0.68333, 0, 0, 0.77778],
"923": [0, 0.68333, 0, 0, 0.69445],
"926": [0, 0.68333, 0, 0, 0.66667],
"928": [0, 0.68333, 0, 0, 0.75],
"931": [0, 0.68333, 0, 0, 0.72222],
"933": [0, 0.68333, 0, 0, 0.77778],
"934": [0, 0.68333, 0, 0, 0.72222],
"936": [0, 0.68333, 0, 0, 0.77778],
"937": [0, 0.68333, 0, 0, 0.72222],
"8211": [0, 0.43056, 0.02778, 0, 0.5],
"8212": [0, 0.43056, 0.02778, 0, 1.0],
"8216": [0, 0.69444, 0, 0, 0.27778],
"8217": [0, 0.69444, 0, 0, 0.27778],
"8220": [0, 0.69444, 0, 0, 0.5],
"8221": [0, 0.69444, 0, 0, 0.5],
"8224": [0.19444, 0.69444, 0, 0, 0.44445],
"8225": [0.19444, 0.69444, 0, 0, 0.44445],
"8230": [0, 0.12, 0, 0, 1.172],
"8242": [0, 0.55556, 0, 0, 0.275],
"8407": [0, 0.71444, 0.15382, 0, 0.5],
"8463": [0, 0.68889, 0, 0, 0.54028],
"8465": [0, 0.69444, 0, 0, 0.72222],
"8467": [0, 0.69444, 0, 0.11111, 0.41667],
"8472": [0.19444, 0.43056, 0, 0.11111, 0.63646],
"8476": [0, 0.69444, 0, 0, 0.72222],
"8501": [0, 0.69444, 0, 0, 0.61111],
"8592": [-0.13313, 0.36687, 0, 0, 1.0],
"8593": [0.19444, 0.69444, 0, 0, 0.5],
"8594": [-0.13313, 0.36687, 0, 0, 1.0],
"8595": [0.19444, 0.69444, 0, 0, 0.5],
"8596": [-0.13313, 0.36687, 0, 0, 1.0],
"8597": [0.25, 0.75, 0, 0, 0.5],
"8598": [0.19444, 0.69444, 0, 0, 1.0],
"8599": [0.19444, 0.69444, 0, 0, 1.0],
"8600": [0.19444, 0.69444, 0, 0, 1.0],
"8601": [0.19444, 0.69444, 0, 0, 1.0],
"8614": [0.011, 0.511, 0, 0, 1.0],
"8617": [0.011, 0.511, 0, 0, 1.126],
"8618": [0.011, 0.511, 0, 0, 1.126],
"8636": [-0.13313, 0.36687, 0, 0, 1.0],
"8637": [-0.13313, 0.36687, 0, 0, 1.0],
"8640": [-0.13313, 0.36687, 0, 0, 1.0],
"8641": [-0.13313, 0.36687, 0, 0, 1.0],
"8652": [0.011, 0.671, 0, 0, 1.0],
"8656": [-0.13313, 0.36687, 0, 0, 1.0],
"8657": [0.19444, 0.69444, 0, 0, 0.61111],
"8658": [-0.13313, 0.36687, 0, 0, 1.0],
"8659": [0.19444, 0.69444, 0, 0, 0.61111],
"8660": [-0.13313, 0.36687, 0, 0, 1.0],
"8661": [0.25, 0.75, 0, 0, 0.61111],
"8704": [0, 0.69444, 0, 0, 0.55556],
"8706": [0, 0.69444, 0.05556, 0.08334, 0.5309],
"8707": [0, 0.69444, 0, 0, 0.55556],
"8709": [0.05556, 0.75, 0, 0, 0.5],
"8711": [0, 0.68333, 0, 0, 0.83334],
"8712": [0.0391, 0.5391, 0, 0, 0.66667],
"8715": [0.0391, 0.5391, 0, 0, 0.66667],
"8722": [0.08333, 0.58333, 0, 0, 0.77778],
"8723": [0.08333, 0.58333, 0, 0, 0.77778],
"8725": [0.25, 0.75, 0, 0, 0.5],
"8726": [0.25, 0.75, 0, 0, 0.5],
"8727": [-0.03472, 0.46528, 0, 0, 0.5],
"8728": [-0.05555, 0.44445, 0, 0, 0.5],
"8729": [-0.05555, 0.44445, 0, 0, 0.5],
"8730": [0.2, 0.8, 0, 0, 0.83334],
"8733": [0, 0.43056, 0, 0, 0.77778],
"8734": [0, 0.43056, 0, 0, 1.0],
"8736": [0, 0.69224, 0, 0, 0.72222],
"8739": [0.25, 0.75, 0, 0, 0.27778],
"8741": [0.25, 0.75, 0, 0, 0.5],
"8743": [0, 0.55556, 0, 0, 0.66667],
"8744": [0, 0.55556, 0, 0, 0.66667],
"8745": [0, 0.55556, 0, 0, 0.66667],
"8746": [0, 0.55556, 0, 0, 0.66667],
"8747": [0.19444, 0.69444, 0.11111, 0, 0.41667],
"8764": [-0.13313, 0.36687, 0, 0, 0.77778],
"8768": [0.19444, 0.69444, 0, 0, 0.27778],
"8771": [-0.03625, 0.46375, 0, 0, 0.77778],
"8773": [-0.022, 0.589, 0, 0, 1.0],
"8776": [-0.01688, 0.48312, 0, 0, 0.77778],
"8781": [-0.03625, 0.46375, 0, 0, 0.77778],
"8784": [-0.133, 0.67, 0, 0, 0.778],
"8801": [-0.03625, 0.46375, 0, 0, 0.77778],
"8804": [0.13597, 0.63597, 0, 0, 0.77778],
"8805": [0.13597, 0.63597, 0, 0, 0.77778],
"8810": [0.0391, 0.5391, 0, 0, 1.0],
"8811": [0.0391, 0.5391, 0, 0, 1.0],
"8826": [0.0391, 0.5391, 0, 0, 0.77778],
"8827": [0.0391, 0.5391, 0, 0, 0.77778],
"8834": [0.0391, 0.5391, 0, 0, 0.77778],
"8835": [0.0391, 0.5391, 0, 0, 0.77778],
"8838": [0.13597, 0.63597, 0, 0, 0.77778],
"8839": [0.13597, 0.63597, 0, 0, 0.77778],
"8846": [0, 0.55556, 0, 0, 0.66667],
"8849": [0.13597, 0.63597, 0, 0, 0.77778],
"8850": [0.13597, 0.63597, 0, 0, 0.77778],
"8851": [0, 0.55556, 0, 0, 0.66667],
"8852": [0, 0.55556, 0, 0, 0.66667],
"8853": [0.08333, 0.58333, 0, 0, 0.77778],
"8854": [0.08333, 0.58333, 0, 0, 0.77778],
"8855": [0.08333, 0.58333, 0, 0, 0.77778],
"8856": [0.08333, 0.58333, 0, 0, 0.77778],
"8857": [0.08333, 0.58333, 0, 0, 0.77778],
"8866": [0, 0.69444, 0, 0, 0.61111],
"8867": [0, 0.69444, 0, 0, 0.61111],
"8868": [0, 0.69444, 0, 0, 0.77778],
"8869": [0, 0.69444, 0, 0, 0.77778],
"8872": [0.249, 0.75, 0, 0, 0.867],
"8900": [-0.05555, 0.44445, 0, 0, 0.5],
"8901": [-0.05555, 0.44445, 0, 0, 0.27778],
"8902": [-0.03472, 0.46528, 0, 0, 0.5],
"8904": [0.005, 0.505, 0, 0, 0.9],
"8942": [0.03, 0.9, 0, 0, 0.278],
"8943": [-0.19, 0.31, 0, 0, 1.172],
"8945": [-0.1, 0.82, 0, 0, 1.282],
"8968": [0.25, 0.75, 0, 0, 0.44445],
"8969": [0.25, 0.75, 0, 0, 0.44445],
"8970": [0.25, 0.75, 0, 0, 0.44445],
"8971": [0.25, 0.75, 0, 0, 0.44445],
"8994": [-0.14236, 0.35764, 0, 0, 1.0],
"8995": [-0.14236, 0.35764, 0, 0, 1.0],
"9136": [0.244, 0.744, 0, 0, 0.412],
"9137": [0.244, 0.744, 0, 0, 0.412],
"9651": [0.19444, 0.69444, 0, 0, 0.88889],
"9657": [-0.03472, 0.46528, 0, 0, 0.5],
"9661": [0.19444, 0.69444, 0, 0, 0.88889],
"9667": [-0.03472, 0.46528, 0, 0, 0.5],
"9711": [0.19444, 0.69444, 0, 0, 1.0],
"9824": [0.12963, 0.69444, 0, 0, 0.77778],
"9825": [0.12963, 0.69444, 0, 0, 0.77778],
"9826": [0.12963, 0.69444, 0, 0, 0.77778],
"9827": [0.12963, 0.69444, 0, 0, 0.77778],
"9837": [0, 0.75, 0, 0, 0.38889],
"9838": [0.19444, 0.69444, 0, 0, 0.38889],
"9839": [0.19444, 0.69444, 0, 0, 0.38889],
"10216": [0.25, 0.75, 0, 0, 0.38889],
"10217": [0.25, 0.75, 0, 0, 0.38889],
"10222": [0.244, 0.744, 0, 0, 0.412],
"10223": [0.244, 0.744, 0, 0, 0.412],
"10229": [0.011, 0.511, 0, 0, 1.609],
"10230": [0.011, 0.511, 0, 0, 1.638],
"10231": [0.011, 0.511, 0, 0, 1.859],
"10232": [0.024, 0.525, 0, 0, 1.609],
"10233": [0.024, 0.525, 0, 0, 1.638],
"10234": [0.024, 0.525, 0, 0, 1.858],
"10236": [0.011, 0.511, 0, 0, 1.638],
"10815": [0, 0.68333, 0, 0, 0.75],
"10927": [0.13597, 0.63597, 0, 0, 0.77778],
"10928": [0.13597, 0.63597, 0, 0, 0.77778],
"57376": [0.19444, 0.69444, 0, 0, 0]
},
"Math-BoldItalic": {
"65": [0, 0.68611, 0, 0, 0.86944],
"66": [0, 0.68611, 0.04835, 0, 0.8664],
"67": [0, 0.68611, 0.06979, 0, 0.81694],
"68": [0, 0.68611, 0.03194, 0, 0.93812],
"69": [0, 0.68611, 0.05451, 0, 0.81007],
"70": [0, 0.68611, 0.15972, 0, 0.68889],
"71": [0, 0.68611, 0, 0, 0.88673],
"72": [0, 0.68611, 0.08229, 0, 0.98229],
"73": [0, 0.68611, 0.07778, 0, 0.51111],
"74": [0, 0.68611, 0.10069, 0, 0.63125],
"75": [0, 0.68611, 0.06979, 0, 0.97118],
"76": [0, 0.68611, 0, 0, 0.75555],
"77": [0, 0.68611, 0.11424, 0, 1.14201],
"78": [0, 0.68611, 0.11424, 0, 0.95034],
"79": [0, 0.68611, 0.03194, 0, 0.83666],
"80": [0, 0.68611, 0.15972, 0, 0.72309],
"81": [0.19444, 0.68611, 0, 0, 0.86861],
"82": [0, 0.68611, 0.00421, 0, 0.87235],
"83": [0, 0.68611, 0.05382, 0, 0.69271],
"84": [0, 0.68611, 0.15972, 0, 0.63663],
"85": [0, 0.68611, 0.11424, 0, 0.80027],
"86": [0, 0.68611, 0.25555, 0, 0.67778],
"87": [0, 0.68611, 0.15972, 0, 1.09305],
"88": [0, 0.68611, 0.07778, 0, 0.94722],
"89": [0, 0.68611, 0.25555, 0, 0.67458],
"90": [0, 0.68611, 0.06979, 0, 0.77257],
"97": [0, 0.44444, 0, 0, 0.63287],
"98": [0, 0.69444, 0, 0, 0.52083],
"99": [0, 0.44444, 0, 0, 0.51342],
"100": [0, 0.69444, 0, 0, 0.60972],
"101": [0, 0.44444, 0, 0, 0.55361],
"102": [0.19444, 0.69444, 0.11042, 0, 0.56806],
"103": [0.19444, 0.44444, 0.03704, 0, 0.5449],
"104": [0, 0.69444, 0, 0, 0.66759],
"105": [0, 0.69326, 0, 0, 0.4048],
"106": [0.19444, 0.69326, 0.0622, 0, 0.47083],
"107": [0, 0.69444, 0.01852, 0, 0.6037],
"108": [0, 0.69444, 0.0088, 0, 0.34815],
"109": [0, 0.44444, 0, 0, 1.0324],
"110": [0, 0.44444, 0, 0, 0.71296],
"111": [0, 0.44444, 0, 0, 0.58472],
"112": [0.19444, 0.44444, 0, 0, 0.60092],
"113": [0.19444, 0.44444, 0.03704, 0, 0.54213],
"114": [0, 0.44444, 0.03194, 0, 0.5287],
"115": [0, 0.44444, 0, 0, 0.53125],
"116": [0, 0.63492, 0, 0, 0.41528],
"117": [0, 0.44444, 0, 0, 0.68102],
"118": [0, 0.44444, 0.03704, 0, 0.56666],
"119": [0, 0.44444, 0.02778, 0, 0.83148],
"120": [0, 0.44444, 0, 0, 0.65903],
"121": [0.19444, 0.44444, 0.03704, 0, 0.59028],
"122": [0, 0.44444, 0.04213, 0, 0.55509],
"915": [0, 0.68611, 0.15972, 0, 0.65694],
"916": [0, 0.68611, 0, 0, 0.95833],
"920": [0, 0.68611, 0.03194, 0, 0.86722],
"923": [0, 0.68611, 0, 0, 0.80555],
"926": [0, 0.68611, 0.07458, 0, 0.84125],
"928": [0, 0.68611, 0.08229, 0, 0.98229],
"931": [0, 0.68611, 0.05451, 0, 0.88507],
"933": [0, 0.68611, 0.15972, 0, 0.67083],
"934": [0, 0.68611, 0, 0, 0.76666],
"936": [0, 0.68611, 0.11653, 0, 0.71402],
"937": [0, 0.68611, 0.04835, 0, 0.8789],
"945": [0, 0.44444, 0, 0, 0.76064],
"946": [0.19444, 0.69444, 0.03403, 0, 0.65972],
"947": [0.19444, 0.44444, 0.06389, 0, 0.59003],
"948": [0, 0.69444, 0.03819, 0, 0.52222],
"949": [0, 0.44444, 0, 0, 0.52882],
"950": [0.19444, 0.69444, 0.06215, 0, 0.50833],
"951": [0.19444, 0.44444, 0.03704, 0, 0.6],
"952": [0, 0.69444, 0.03194, 0, 0.5618],
"953": [0, 0.44444, 0, 0, 0.41204],
"954": [0, 0.44444, 0, 0, 0.66759],
"955": [0, 0.69444, 0, 0, 0.67083],
"956": [0.19444, 0.44444, 0, 0, 0.70787],
"957": [0, 0.44444, 0.06898, 0, 0.57685],
"958": [0.19444, 0.69444, 0.03021, 0, 0.50833],
"959": [0, 0.44444, 0, 0, 0.58472],
"960": [0, 0.44444, 0.03704, 0, 0.68241],
"961": [0.19444, 0.44444, 0, 0, 0.6118],
"962": [0.09722, 0.44444, 0.07917, 0, 0.42361],
"963": [0, 0.44444, 0.03704, 0, 0.68588],
"964": [0, 0.44444, 0.13472, 0, 0.52083],
"965": [0, 0.44444, 0.03704, 0, 0.63055],
"966": [0.19444, 0.44444, 0, 0, 0.74722],
"967": [0.19444, 0.44444, 0, 0, 0.71805],
"968": [0.19444, 0.69444, 0.03704, 0, 0.75833],
"969": [0, 0.44444, 0.03704, 0, 0.71782],
"977": [0, 0.69444, 0, 0, 0.69155],
"981": [0.19444, 0.69444, 0, 0, 0.7125],
"982": [0, 0.44444, 0.03194, 0, 0.975],
"1009": [0.19444, 0.44444, 0, 0, 0.6118],
"1013": [0, 0.44444, 0, 0, 0.48333]
},
"Math-Italic": {
"65": [0, 0.68333, 0, 0.13889, 0.75],
"66": [0, 0.68333, 0.05017, 0.08334, 0.75851],
"67": [0, 0.68333, 0.07153, 0.08334, 0.71472],
"68": [0, 0.68333, 0.02778, 0.05556, 0.82792],
"69": [0, 0.68333, 0.05764, 0.08334, 0.7382],
"70": [0, 0.68333, 0.13889, 0.08334, 0.64306],
"71": [0, 0.68333, 0, 0.08334, 0.78625],
"72": [0, 0.68333, 0.08125, 0.05556, 0.83125],
"73": [0, 0.68333, 0.07847, 0.11111, 0.43958],
"74": [0, 0.68333, 0.09618, 0.16667, 0.55451],
"75": [0, 0.68333, 0.07153, 0.05556, 0.84931],
"76": [0, 0.68333, 0, 0.02778, 0.68056],
"77": [0, 0.68333, 0.10903, 0.08334, 0.97014],
"78": [0, 0.68333, 0.10903, 0.08334, 0.80347],
"79": [0, 0.68333, 0.02778, 0.08334, 0.76278],
"80": [0, 0.68333, 0.13889, 0.08334, 0.64201],
"81": [0.19444, 0.68333, 0, 0.08334, 0.79056],
"82": [0, 0.68333, 0.00773, 0.08334, 0.75929],
"83": [0, 0.68333, 0.05764, 0.08334, 0.6132],
"84": [0, 0.68333, 0.13889, 0.08334, 0.58438],
"85": [0, 0.68333, 0.10903, 0.02778, 0.68278],
"86": [0, 0.68333, 0.22222, 0, 0.58333],
"87": [0, 0.68333, 0.13889, 0, 0.94445],
"88": [0, 0.68333, 0.07847, 0.08334, 0.82847],
"89": [0, 0.68333, 0.22222, 0, 0.58056],
"90": [0, 0.68333, 0.07153, 0.08334, 0.68264],
"97": [0, 0.43056, 0, 0, 0.52859],
"98": [0, 0.69444, 0, 0, 0.42917],
"99": [0, 0.43056, 0, 0.05556, 0.43276],
"100": [0, 0.69444, 0, 0.16667, 0.52049],
"101": [0, 0.43056, 0, 0.05556, 0.46563],
"102": [0.19444, 0.69444, 0.10764, 0.16667, 0.48959],
"103": [0.19444, 0.43056, 0.03588, 0.02778, 0.47697],
"104": [0, 0.69444, 0, 0, 0.57616],
"105": [0, 0.65952, 0, 0, 0.34451],
"106": [0.19444, 0.65952, 0.05724, 0, 0.41181],
"107": [0, 0.69444, 0.03148, 0, 0.5206],
"108": [0, 0.69444, 0.01968, 0.08334, 0.29838],
"109": [0, 0.43056, 0, 0, 0.87801],
"110": [0, 0.43056, 0, 0, 0.60023],
"111": [0, 0.43056, 0, 0.05556, 0.48472],
"112": [0.19444, 0.43056, 0, 0.08334, 0.50313],
"113": [0.19444, 0.43056, 0.03588, 0.08334, 0.44641],
"114": [0, 0.43056, 0.02778, 0.05556, 0.45116],
"115": [0, 0.43056, 0, 0.05556, 0.46875],
"116": [0, 0.61508, 0, 0.08334, 0.36111],
"117": [0, 0.43056, 0, 0.02778, 0.57246],
"118": [0, 0.43056, 0.03588, 0.02778, 0.48472],
"119": [0, 0.43056, 0.02691, 0.08334, 0.71592],
"120": [0, 0.43056, 0, 0.02778, 0.57153],
"121": [0.19444, 0.43056, 0.03588, 0.05556, 0.49028],
"122": [0, 0.43056, 0.04398, 0.05556, 0.46505],
"915": [0, 0.68333, 0.13889, 0.08334, 0.61528],
"916": [0, 0.68333, 0, 0.16667, 0.83334],
"920": [0, 0.68333, 0.02778, 0.08334, 0.76278],
"923": [0, 0.68333, 0, 0.16667, 0.69445],
"926": [0, 0.68333, 0.07569, 0.08334, 0.74236],
"928": [0, 0.68333, 0.08125, 0.05556, 0.83125],
"931": [0, 0.68333, 0.05764, 0.08334, 0.77986],
"933": [0, 0.68333, 0.13889, 0.05556, 0.58333],
"934": [0, 0.68333, 0, 0.08334, 0.66667],
"936": [0, 0.68333, 0.11, 0.05556, 0.61222],
"937": [0, 0.68333, 0.05017, 0.08334, 0.7724],
"945": [0, 0.43056, 0.0037, 0.02778, 0.6397],
"946": [0.19444, 0.69444, 0.05278, 0.08334, 0.56563],
"947": [0.19444, 0.43056, 0.05556, 0, 0.51773],
"948": [0, 0.69444, 0.03785, 0.05556, 0.44444],
"949": [0, 0.43056, 0, 0.08334, 0.46632],
"950": [0.19444, 0.69444, 0.07378, 0.08334, 0.4375],
"951": [0.19444, 0.43056, 0.03588, 0.05556, 0.49653],
"952": [0, 0.69444, 0.02778, 0.08334, 0.46944],
"953": [0, 0.43056, 0, 0.05556, 0.35394],
"954": [0, 0.43056, 0, 0, 0.57616],
"955": [0, 0.69444, 0, 0, 0.58334],
"956": [0.19444, 0.43056, 0, 0.02778, 0.60255],
"957": [0, 0.43056, 0.06366, 0.02778, 0.49398],
"958": [0.19444, 0.69444, 0.04601, 0.11111, 0.4375],
"959": [0, 0.43056, 0, 0.05556, 0.48472],
"960": [0, 0.43056, 0.03588, 0, 0.57003],
"961": [0.19444, 0.43056, 0, 0.08334, 0.51702],
"962": [0.09722, 0.43056, 0.07986, 0.08334, 0.36285],
"963": [0, 0.43056, 0.03588, 0, 0.57141],
"964": [0, 0.43056, 0.1132, 0.02778, 0.43715],
"965": [0, 0.43056, 0.03588, 0.02778, 0.54028],
"966": [0.19444, 0.43056, 0, 0.08334, 0.65417],
"967": [0.19444, 0.43056, 0, 0.05556, 0.62569],
"968": [0.19444, 0.69444, 0.03588, 0.11111, 0.65139],
"969": [0, 0.43056, 0.03588, 0, 0.62245],
"977": [0, 0.69444, 0, 0.08334, 0.59144],
"981": [0.19444, 0.69444, 0, 0.08334, 0.59583],
"982": [0, 0.43056, 0.02778, 0, 0.82813],
"1009": [0.19444, 0.43056, 0, 0.08334, 0.51702],
"1013": [0, 0.43056, 0, 0.05556, 0.4059]
},
"Math-Regular": {
"65": [0, 0.68333, 0, 0.13889, 0.75],
"66": [0, 0.68333, 0.05017, 0.08334, 0.75851],
"67": [0, 0.68333, 0.07153, 0.08334, 0.71472],
"68": [0, 0.68333, 0.02778, 0.05556, 0.82792],
"69": [0, 0.68333, 0.05764, 0.08334, 0.7382],
"70": [0, 0.68333, 0.13889, 0.08334, 0.64306],
"71": [0, 0.68333, 0, 0.08334, 0.78625],
"72": [0, 0.68333, 0.08125, 0.05556, 0.83125],
"73": [0, 0.68333, 0.07847, 0.11111, 0.43958],
"74": [0, 0.68333, 0.09618, 0.16667, 0.55451],
"75": [0, 0.68333, 0.07153, 0.05556, 0.84931],
"76": [0, 0.68333, 0, 0.02778, 0.68056],
"77": [0, 0.68333, 0.10903, 0.08334, 0.97014],
"78": [0, 0.68333, 0.10903, 0.08334, 0.80347],
"79": [0, 0.68333, 0.02778, 0.08334, 0.76278],
"80": [0, 0.68333, 0.13889, 0.08334, 0.64201],
"81": [0.19444, 0.68333, 0, 0.08334, 0.79056],
"82": [0, 0.68333, 0.00773, 0.08334, 0.75929],
"83": [0, 0.68333, 0.05764, 0.08334, 0.6132],
"84": [0, 0.68333, 0.13889, 0.08334, 0.58438],
"85": [0, 0.68333, 0.10903, 0.02778, 0.68278],
"86": [0, 0.68333, 0.22222, 0, 0.58333],
"87": [0, 0.68333, 0.13889, 0, 0.94445],
"88": [0, 0.68333, 0.07847, 0.08334, 0.82847],
"89": [0, 0.68333, 0.22222, 0, 0.58056],
"90": [0, 0.68333, 0.07153, 0.08334, 0.68264],
"97": [0, 0.43056, 0, 0, 0.52859],
"98": [0, 0.69444, 0, 0, 0.42917],
"99": [0, 0.43056, 0, 0.05556, 0.43276],
"100": [0, 0.69444, 0, 0.16667, 0.52049],
"101": [0, 0.43056, 0, 0.05556, 0.46563],
"102": [0.19444, 0.69444, 0.10764, 0.16667, 0.48959],
"103": [0.19444, 0.43056, 0.03588, 0.02778, 0.47697],
"104": [0, 0.69444, 0, 0, 0.57616],
"105": [0, 0.65952, 0, 0, 0.34451],
"106": [0.19444, 0.65952, 0.05724, 0, 0.41181],
"107": [0, 0.69444, 0.03148, 0, 0.5206],
"108": [0, 0.69444, 0.01968, 0.08334, 0.29838],
"109": [0, 0.43056, 0, 0, 0.87801],
"110": [0, 0.43056, 0, 0, 0.60023],
"111": [0, 0.43056, 0, 0.05556, 0.48472],
"112": [0.19444, 0.43056, 0, 0.08334, 0.50313],
"113": [0.19444, 0.43056, 0.03588, 0.08334, 0.44641],
"114": [0, 0.43056, 0.02778, 0.05556, 0.45116],
"115": [0, 0.43056, 0, 0.05556, 0.46875],
"116": [0, 0.61508, 0, 0.08334, 0.36111],
"117": [0, 0.43056, 0, 0.02778, 0.57246],
"118": [0, 0.43056, 0.03588, 0.02778, 0.48472],
"119": [0, 0.43056, 0.02691, 0.08334, 0.71592],
"120": [0, 0.43056, 0, 0.02778, 0.57153],
"121": [0.19444, 0.43056, 0.03588, 0.05556, 0.49028],
"122": [0, 0.43056, 0.04398, 0.05556, 0.46505],
"915": [0, 0.68333, 0.13889, 0.08334, 0.61528],
"916": [0, 0.68333, 0, 0.16667, 0.83334],
"920": [0, 0.68333, 0.02778, 0.08334, 0.76278],
"923": [0, 0.68333, 0, 0.16667, 0.69445],
"926": [0, 0.68333, 0.07569, 0.08334, 0.74236],
"928": [0, 0.68333, 0.08125, 0.05556, 0.83125],
"931": [0, 0.68333, 0.05764, 0.08334, 0.77986],
"933": [0, 0.68333, 0.13889, 0.05556, 0.58333],
"934": [0, 0.68333, 0, 0.08334, 0.66667],
"936": [0, 0.68333, 0.11, 0.05556, 0.61222],
"937": [0, 0.68333, 0.05017, 0.08334, 0.7724],
"945": [0, 0.43056, 0.0037, 0.02778, 0.6397],
"946": [0.19444, 0.69444, 0.05278, 0.08334, 0.56563],
"947": [0.19444, 0.43056, 0.05556, 0, 0.51773],
"948": [0, 0.69444, 0.03785, 0.05556, 0.44444],
"949": [0, 0.43056, 0, 0.08334, 0.46632],
"950": [0.19444, 0.69444, 0.07378, 0.08334, 0.4375],
"951": [0.19444, 0.43056, 0.03588, 0.05556, 0.49653],
"952": [0, 0.69444, 0.02778, 0.08334, 0.46944],
"953": [0, 0.43056, 0, 0.05556, 0.35394],
"954": [0, 0.43056, 0, 0, 0.57616],
"955": [0, 0.69444, 0, 0, 0.58334],
"956": [0.19444, 0.43056, 0, 0.02778, 0.60255],
"957": [0, 0.43056, 0.06366, 0.02778, 0.49398],
"958": [0.19444, 0.69444, 0.04601, 0.11111, 0.4375],
"959": [0, 0.43056, 0, 0.05556, 0.48472],
"960": [0, 0.43056, 0.03588, 0, 0.57003],
"961": [0.19444, 0.43056, 0, 0.08334, 0.51702],
"962": [0.09722, 0.43056, 0.07986, 0.08334, 0.36285],
"963": [0, 0.43056, 0.03588, 0, 0.57141],
"964": [0, 0.43056, 0.1132, 0.02778, 0.43715],
"965": [0, 0.43056, 0.03588, 0.02778, 0.54028],
"966": [0.19444, 0.43056, 0, 0.08334, 0.65417],
"967": [0.19444, 0.43056, 0, 0.05556, 0.62569],
"968": [0.19444, 0.69444, 0.03588, 0.11111, 0.65139],
"969": [0, 0.43056, 0.03588, 0, 0.62245],
"977": [0, 0.69444, 0, 0.08334, 0.59144],
"981": [0.19444, 0.69444, 0, 0.08334, 0.59583],
"982": [0, 0.43056, 0.02778, 0, 0.82813],
"1009": [0.19444, 0.43056, 0, 0.08334, 0.51702],
"1013": [0, 0.43056, 0, 0.05556, 0.4059]
},
"SansSerif-Bold": {
"33": [0, 0.69444, 0, 0, 0.36667],
"34": [0, 0.69444, 0, 0, 0.55834],
"35": [0.19444, 0.69444, 0, 0, 0.91667],
"36": [0.05556, 0.75, 0, 0, 0.55],
"37": [0.05556, 0.75, 0, 0, 1.02912],
"38": [0, 0.69444, 0, 0, 0.83056],
"39": [0, 0.69444, 0, 0, 0.30556],
"40": [0.25, 0.75, 0, 0, 0.42778],
"41": [0.25, 0.75, 0, 0, 0.42778],
"42": [0, 0.75, 0, 0, 0.55],
"43": [0.11667, 0.61667, 0, 0, 0.85556],
"44": [0.10556, 0.13056, 0, 0, 0.30556],
"45": [0, 0.45833, 0, 0, 0.36667],
"46": [0, 0.13056, 0, 0, 0.30556],
"47": [0.25, 0.75, 0, 0, 0.55],
"48": [0, 0.69444, 0, 0, 0.55],
"49": [0, 0.69444, 0, 0, 0.55],
"50": [0, 0.69444, 0, 0, 0.55],
"51": [0, 0.69444, 0, 0, 0.55],
"52": [0, 0.69444, 0, 0, 0.55],
"53": [0, 0.69444, 0, 0, 0.55],
"54": [0, 0.69444, 0, 0, 0.55],
"55": [0, 0.69444, 0, 0, 0.55],
"56": [0, 0.69444, 0, 0, 0.55],
"57": [0, 0.69444, 0, 0, 0.55],
"58": [0, 0.45833, 0, 0, 0.30556],
"59": [0.10556, 0.45833, 0, 0, 0.30556],
"61": [-0.09375, 0.40625, 0, 0, 0.85556],
"63": [0, 0.69444, 0, 0, 0.51945],
"64": [0, 0.69444, 0, 0, 0.73334],
"65": [0, 0.69444, 0, 0, 0.73334],
"66": [0, 0.69444, 0, 0, 0.73334],
"67": [0, 0.69444, 0, 0, 0.70278],
"68": [0, 0.69444, 0, 0, 0.79445],
"69": [0, 0.69444, 0, 0, 0.64167],
"70": [0, 0.69444, 0, 0, 0.61111],
"71": [0, 0.69444, 0, 0, 0.73334],
"72": [0, 0.69444, 0, 0, 0.79445],
"73": [0, 0.69444, 0, 0, 0.33056],
"74": [0, 0.69444, 0, 0, 0.51945],
"75": [0, 0.69444, 0, 0, 0.76389],
"76": [0, 0.69444, 0, 0, 0.58056],
"77": [0, 0.69444, 0, 0, 0.97778],
"78": [0, 0.69444, 0, 0, 0.79445],
"79": [0, 0.69444, 0, 0, 0.79445],
"80": [0, 0.69444, 0, 0, 0.70278],
"81": [0.10556, 0.69444, 0, 0, 0.79445],
"82": [0, 0.69444, 0, 0, 0.70278],
"83": [0, 0.69444, 0, 0, 0.61111],
"84": [0, 0.69444, 0, 0, 0.73334],
"85": [0, 0.69444, 0, 0, 0.76389],
"86": [0, 0.69444, 0.01528, 0, 0.73334],
"87": [0, 0.69444, 0.01528, 0, 1.03889],
"88": [0, 0.69444, 0, 0, 0.73334],
"89": [0, 0.69444, 0.0275, 0, 0.73334],
"90": [0, 0.69444, 0, 0, 0.67223],
"91": [0.25, 0.75, 0, 0, 0.34306],
"93": [0.25, 0.75, 0, 0, 0.34306],
"94": [0, 0.69444, 0, 0, 0.55],
"95": [0.35, 0.10833, 0.03056, 0, 0.55],
"97": [0, 0.45833, 0, 0, 0.525],
"98": [0, 0.69444, 0, 0, 0.56111],
"99": [0, 0.45833, 0, 0, 0.48889],
"100": [0, 0.69444, 0, 0, 0.56111],
"101": [0, 0.45833, 0, 0, 0.51111],
"102": [0, 0.69444, 0.07639, 0, 0.33611],
"103": [0.19444, 0.45833, 0.01528, 0, 0.55],
"104": [0, 0.69444, 0, 0, 0.56111],
"105": [0, 0.69444, 0, 0, 0.25556],
"106": [0.19444, 0.69444, 0, 0, 0.28611],
"107": [0, 0.69444, 0, 0, 0.53056],
"108": [0, 0.69444, 0, 0, 0.25556],
"109": [0, 0.45833, 0, 0, 0.86667],
"110": [0, 0.45833, 0, 0, 0.56111],
"111": [0, 0.45833, 0, 0, 0.55],
"112": [0.19444, 0.45833, 0, 0, 0.56111],
"113": [0.19444, 0.45833, 0, 0, 0.56111],
"114": [0, 0.45833, 0.01528, 0, 0.37222],
"115": [0, 0.45833, 0, 0, 0.42167],
"116": [0, 0.58929, 0, 0, 0.40417],
"117": [0, 0.45833, 0, 0, 0.56111],
"118": [0, 0.45833, 0.01528, 0, 0.5],
"119": [0, 0.45833, 0.01528, 0, 0.74445],
"120": [0, 0.45833, 0, 0, 0.5],
"121": [0.19444, 0.45833, 0.01528, 0, 0.5],
"122": [0, 0.45833, 0, 0, 0.47639],
"126": [0.35, 0.34444, 0, 0, 0.55],
"168": [0, 0.69444, 0, 0, 0.55],
"176": [0, 0.69444, 0, 0, 0.73334],
"180": [0, 0.69444, 0, 0, 0.55],
"184": [0.17014, 0, 0, 0, 0.48889],
"305": [0, 0.45833, 0, 0, 0.25556],
"567": [0.19444, 0.45833, 0, 0, 0.28611],
"710": [0, 0.69444, 0, 0, 0.55],
"711": [0, 0.63542, 0, 0, 0.55],
"713": [0, 0.63778, 0, 0, 0.55],
"728": [0, 0.69444, 0, 0, 0.55],
"729": [0, 0.69444, 0, 0, 0.30556],
"730": [0, 0.69444, 0, 0, 0.73334],
"732": [0, 0.69444, 0, 0, 0.55],
"733": [0, 0.69444, 0, 0, 0.55],
"915": [0, 0.69444, 0, 0, 0.58056],
"916": [0, 0.69444, 0, 0, 0.91667],
"920": [0, 0.69444, 0, 0, 0.85556],
"923": [0, 0.69444, 0, 0, 0.67223],
"926": [0, 0.69444, 0, 0, 0.73334],
"928": [0, 0.69444, 0, 0, 0.79445],
"931": [0, 0.69444, 0, 0, 0.79445],
"933": [0, 0.69444, 0, 0, 0.85556],
"934": [0, 0.69444, 0, 0, 0.79445],
"936": [0, 0.69444, 0, 0, 0.85556],
"937": [0, 0.69444, 0, 0, 0.79445],
"8211": [0, 0.45833, 0.03056, 0, 0.55],
"8212": [0, 0.45833, 0.03056, 0, 1.10001],
"8216": [0, 0.69444, 0, 0, 0.30556],
"8217": [0, 0.69444, 0, 0, 0.30556],
"8220": [0, 0.69444, 0, 0, 0.55834],
"8221": [0, 0.69444, 0, 0, 0.55834]
},
"SansSerif-Italic": {
"33": [0, 0.69444, 0.05733, 0, 0.31945],
"34": [0, 0.69444, 0.00316, 0, 0.5],
"35": [0.19444, 0.69444, 0.05087, 0, 0.83334],
"36": [0.05556, 0.75, 0.11156, 0, 0.5],
"37": [0.05556, 0.75, 0.03126, 0, 0.83334],
"38": [0, 0.69444, 0.03058, 0, 0.75834],
"39": [0, 0.69444, 0.07816, 0, 0.27778],
"40": [0.25, 0.75, 0.13164, 0, 0.38889],
"41": [0.25, 0.75, 0.02536, 0, 0.38889],
"42": [0, 0.75, 0.11775, 0, 0.5],
"43": [0.08333, 0.58333, 0.02536, 0, 0.77778],
"44": [0.125, 0.08333, 0, 0, 0.27778],
"45": [0, 0.44444, 0.01946, 0, 0.33333],
"46": [0, 0.08333, 0, 0, 0.27778],
"47": [0.25, 0.75, 0.13164, 0, 0.5],
"48": [0, 0.65556, 0.11156, 0, 0.5],
"49": [0, 0.65556, 0.11156, 0, 0.5],
"50": [0, 0.65556, 0.11156, 0, 0.5],
"51": [0, 0.65556, 0.11156, 0, 0.5],
"52": [0, 0.65556, 0.11156, 0, 0.5],
"53": [0, 0.65556, 0.11156, 0, 0.5],
"54": [0, 0.65556, 0.11156, 0, 0.5],
"55": [0, 0.65556, 0.11156, 0, 0.5],
"56": [0, 0.65556, 0.11156, 0, 0.5],
"57": [0, 0.65556, 0.11156, 0, 0.5],
"58": [0, 0.44444, 0.02502, 0, 0.27778],
"59": [0.125, 0.44444, 0.02502, 0, 0.27778],
"61": [-0.13, 0.37, 0.05087, 0, 0.77778],
"63": [0, 0.69444, 0.11809, 0, 0.47222],
"64": [0, 0.69444, 0.07555, 0, 0.66667],
"65": [0, 0.69444, 0, 0, 0.66667],
"66": [0, 0.69444, 0.08293, 0, 0.66667],
"67": [0, 0.69444, 0.11983, 0, 0.63889],
"68": [0, 0.69444, 0.07555, 0, 0.72223],
"69": [0, 0.69444, 0.11983, 0, 0.59722],
"70": [0, 0.69444, 0.13372, 0, 0.56945],
"71": [0, 0.69444, 0.11983, 0, 0.66667],
"72": [0, 0.69444, 0.08094, 0, 0.70834],
"73": [0, 0.69444, 0.13372, 0, 0.27778],
"74": [0, 0.69444, 0.08094, 0, 0.47222],
"75": [0, 0.69444, 0.11983, 0, 0.69445],
"76": [0, 0.69444, 0, 0, 0.54167],
"77": [0, 0.69444, 0.08094, 0, 0.875],
"78": [0, 0.69444, 0.08094, 0, 0.70834],
"79": [0, 0.69444, 0.07555, 0, 0.73611],
"80": [0, 0.69444, 0.08293, 0, 0.63889],
"81": [0.125, 0.69444, 0.07555, 0, 0.73611],
"82": [0, 0.69444, 0.08293, 0, 0.64584],
"83": [0, 0.69444, 0.09205, 0, 0.55556],
"84": [0, 0.69444, 0.13372, 0, 0.68056],
"85": [0, 0.69444, 0.08094, 0, 0.6875],
"86": [0, 0.69444, 0.1615, 0, 0.66667],
"87": [0, 0.69444, 0.1615, 0, 0.94445],
"88": [0, 0.69444, 0.13372, 0, 0.66667],
"89": [0, 0.69444, 0.17261, 0, 0.66667],
"90": [0, 0.69444, 0.11983, 0, 0.61111],
"91": [0.25, 0.75, 0.15942, 0, 0.28889],
"93": [0.25, 0.75, 0.08719, 0, 0.28889],
"94": [0, 0.69444, 0.0799, 0, 0.5],
"95": [0.35, 0.09444, 0.08616, 0, 0.5],
"97": [0, 0.44444, 0.00981, 0, 0.48056],
"98": [0, 0.69444, 0.03057, 0, 0.51667],
"99": [0, 0.44444, 0.08336, 0, 0.44445],
"100": [0, 0.69444, 0.09483, 0, 0.51667],
"101": [0, 0.44444, 0.06778, 0, 0.44445],
"102": [0, 0.69444, 0.21705, 0, 0.30556],
"103": [0.19444, 0.44444, 0.10836, 0, 0.5],
"104": [0, 0.69444, 0.01778, 0, 0.51667],
"105": [0, 0.67937, 0.09718, 0, 0.23889],
"106": [0.19444, 0.67937, 0.09162, 0, 0.26667],
"107": [0, 0.69444, 0.08336, 0, 0.48889],
"108": [0, 0.69444, 0.09483, 0, 0.23889],
"109": [0, 0.44444, 0.01778, 0, 0.79445],
"110": [0, 0.44444, 0.01778, 0, 0.51667],
"111": [0, 0.44444, 0.06613, 0, 0.5],
"112": [0.19444, 0.44444, 0.0389, 0, 0.51667],
"113": [0.19444, 0.44444, 0.04169, 0, 0.51667],
"114": [0, 0.44444, 0.10836, 0, 0.34167],
"115": [0, 0.44444, 0.0778, 0, 0.38333],
"116": [0, 0.57143, 0.07225, 0, 0.36111],
"117": [0, 0.44444, 0.04169, 0, 0.51667],
"118": [0, 0.44444, 0.10836, 0, 0.46111],
"119": [0, 0.44444, 0.10836, 0, 0.68334],
"120": [0, 0.44444, 0.09169, 0, 0.46111],
"121": [0.19444, 0.44444, 0.10836, 0, 0.46111],
"122": [0, 0.44444, 0.08752, 0, 0.43472],
"126": [0.35, 0.32659, 0.08826, 0, 0.5],
"168": [0, 0.67937, 0.06385, 0, 0.5],
"176": [0, 0.69444, 0, 0, 0.73752],
"184": [0.17014, 0, 0, 0, 0.44445],
"305": [0, 0.44444, 0.04169, 0, 0.23889],
"567": [0.19444, 0.44444, 0.04169, 0, 0.26667],
"710": [0, 0.69444, 0.0799, 0, 0.5],
"711": [0, 0.63194, 0.08432, 0, 0.5],
"713": [0, 0.60889, 0.08776, 0, 0.5],
"714": [0, 0.69444, 0.09205, 0, 0.5],
"715": [0, 0.69444, 0, 0, 0.5],
"728": [0, 0.69444, 0.09483, 0, 0.5],
"729": [0, 0.67937, 0.07774, 0, 0.27778],
"730": [0, 0.69444, 0, 0, 0.73752],
"732": [0, 0.67659, 0.08826, 0, 0.5],
"733": [0, 0.69444, 0.09205, 0, 0.5],
"915": [0, 0.69444, 0.13372, 0, 0.54167],
"916": [0, 0.69444, 0, 0, 0.83334],
"920": [0, 0.69444, 0.07555, 0, 0.77778],
"923": [0, 0.69444, 0, 0, 0.61111],
"926": [0, 0.69444, 0.12816, 0, 0.66667],
"928": [0, 0.69444, 0.08094, 0, 0.70834],
"931": [0, 0.69444, 0.11983, 0, 0.72222],
"933": [0, 0.69444, 0.09031, 0, 0.77778],
"934": [0, 0.69444, 0.04603, 0, 0.72222],
"936": [0, 0.69444, 0.09031, 0, 0.77778],
"937": [0, 0.69444, 0.08293, 0, 0.72222],
"8211": [0, 0.44444, 0.08616, 0, 0.5],
"8212": [0, 0.44444, 0.08616, 0, 1.0],
"8216": [0, 0.69444, 0.07816, 0, 0.27778],
"8217": [0, 0.69444, 0.07816, 0, 0.27778],
"8220": [0, 0.69444, 0.14205, 0, 0.5],
"8221": [0, 0.69444, 0.00316, 0, 0.5]
},
"SansSerif-Regular": {
"33": [0, 0.69444, 0, 0, 0.31945],
"34": [0, 0.69444, 0, 0, 0.5],
"35": [0.19444, 0.69444, 0, 0, 0.83334],
"36": [0.05556, 0.75, 0, 0, 0.5],
"37": [0.05556, 0.75, 0, 0, 0.83334],
"38": [0, 0.69444, 0, 0, 0.75834],
"39": [0, 0.69444, 0, 0, 0.27778],
"40": [0.25, 0.75, 0, 0, 0.38889],
"41": [0.25, 0.75, 0, 0, 0.38889],
"42": [0, 0.75, 0, 0, 0.5],
"43": [0.08333, 0.58333, 0, 0, 0.77778],
"44": [0.125, 0.08333, 0, 0, 0.27778],
"45": [0, 0.44444, 0, 0, 0.33333],
"46": [0, 0.08333, 0, 0, 0.27778],
"47": [0.25, 0.75, 0, 0, 0.5],
"48": [0, 0.65556, 0, 0, 0.5],
"49": [0, 0.65556, 0, 0, 0.5],
"50": [0, 0.65556, 0, 0, 0.5],
"51": [0, 0.65556, 0, 0, 0.5],
"52": [0, 0.65556, 0, 0, 0.5],
"53": [0, 0.65556, 0, 0, 0.5],
"54": [0, 0.65556, 0, 0, 0.5],
"55": [0, 0.65556, 0, 0, 0.5],
"56": [0, 0.65556, 0, 0, 0.5],
"57": [0, 0.65556, 0, 0, 0.5],
"58": [0, 0.44444, 0, 0, 0.27778],
"59": [0.125, 0.44444, 0, 0, 0.27778],
"61": [-0.13, 0.37, 0, 0, 0.77778],
"63": [0, 0.69444, 0, 0, 0.47222],
"64": [0, 0.69444, 0, 0, 0.66667],
"65": [0, 0.69444, 0, 0, 0.66667],
"66": [0, 0.69444, 0, 0, 0.66667],
"67": [0, 0.69444, 0, 0, 0.63889],
"68": [0, 0.69444, 0, 0, 0.72223],
"69": [0, 0.69444, 0, 0, 0.59722],
"70": [0, 0.69444, 0, 0, 0.56945],
"71": [0, 0.69444, 0, 0, 0.66667],
"72": [0, 0.69444, 0, 0, 0.70834],
"73": [0, 0.69444, 0, 0, 0.27778],
"74": [0, 0.69444, 0, 0, 0.47222],
"75": [0, 0.69444, 0, 0, 0.69445],
"76": [0, 0.69444, 0, 0, 0.54167],
"77": [0, 0.69444, 0, 0, 0.875],
"78": [0, 0.69444, 0, 0, 0.70834],
"79": [0, 0.69444, 0, 0, 0.73611],
"80": [0, 0.69444, 0, 0, 0.63889],
"81": [0.125, 0.69444, 0, 0, 0.73611],
"82": [0, 0.69444, 0, 0, 0.64584],
"83": [0, 0.69444, 0, 0, 0.55556],
"84": [0, 0.69444, 0, 0, 0.68056],
"85": [0, 0.69444, 0, 0, 0.6875],
"86": [0, 0.69444, 0.01389, 0, 0.66667],
"87": [0, 0.69444, 0.01389, 0, 0.94445],
"88": [0, 0.69444, 0, 0, 0.66667],
"89": [0, 0.69444, 0.025, 0, 0.66667],
"90": [0, 0.69444, 0, 0, 0.61111],
"91": [0.25, 0.75, 0, 0, 0.28889],
"93": [0.25, 0.75, 0, 0, 0.28889],
"94": [0, 0.69444, 0, 0, 0.5],
"95": [0.35, 0.09444, 0.02778, 0, 0.5],
"97": [0, 0.44444, 0, 0, 0.48056],
"98": [0, 0.69444, 0, 0, 0.51667],
"99": [0, 0.44444, 0, 0, 0.44445],
"100": [0, 0.69444, 0, 0, 0.51667],
"101": [0, 0.44444, 0, 0, 0.44445],
"102": [0, 0.69444, 0.06944, 0, 0.30556],
"103": [0.19444, 0.44444, 0.01389, 0, 0.5],
"104": [0, 0.69444, 0, 0, 0.51667],
"105": [0, 0.67937, 0, 0, 0.23889],
"106": [0.19444, 0.67937, 0, 0, 0.26667],
"107": [0, 0.69444, 0, 0, 0.48889],
"108": [0, 0.69444, 0, 0, 0.23889],
"109": [0, 0.44444, 0, 0, 0.79445],
"110": [0, 0.44444, 0, 0, 0.51667],
"111": [0, 0.44444, 0, 0, 0.5],
"112": [0.19444, 0.44444, 0, 0, 0.51667],
"113": [0.19444, 0.44444, 0, 0, 0.51667],
"114": [0, 0.44444, 0.01389, 0, 0.34167],
"115": [0, 0.44444, 0, 0, 0.38333],
"116": [0, 0.57143, 0, 0, 0.36111],
"117": [0, 0.44444, 0, 0, 0.51667],
"118": [0, 0.44444, 0.01389, 0, 0.46111],
"119": [0, 0.44444, 0.01389, 0, 0.68334],
"120": [0, 0.44444, 0, 0, 0.46111],
"121": [0.19444, 0.44444, 0.01389, 0, 0.46111],
"122": [0, 0.44444, 0, 0, 0.43472],
"126": [0.35, 0.32659, 0, 0, 0.5],
"168": [0, 0.67937, 0, 0, 0.5],
"176": [0, 0.69444, 0, 0, 0.66667],
"184": [0.17014, 0, 0, 0, 0.44445],
"305": [0, 0.44444, 0, 0, 0.23889],
"567": [0.19444, 0.44444, 0, 0, 0.26667],
"710": [0, 0.69444, 0, 0, 0.5],
"711": [0, 0.63194, 0, 0, 0.5],
"713": [0, 0.60889, 0, 0, 0.5],
"714": [0, 0.69444, 0, 0, 0.5],
"715": [0, 0.69444, 0, 0, 0.5],
"728": [0, 0.69444, 0, 0, 0.5],
"729": [0, 0.67937, 0, 0, 0.27778],
"730": [0, 0.69444, 0, 0, 0.66667],
"732": [0, 0.67659, 0, 0, 0.5],
"733": [0, 0.69444, 0, 0, 0.5],
"915": [0, 0.69444, 0, 0, 0.54167],
"916": [0, 0.69444, 0, 0, 0.83334],
"920": [0, 0.69444, 0, 0, 0.77778],
"923": [0, 0.69444, 0, 0, 0.61111],
"926": [0, 0.69444, 0, 0, 0.66667],
"928": [0, 0.69444, 0, 0, 0.70834],
"931": [0, 0.69444, 0, 0, 0.72222],
"933": [0, 0.69444, 0, 0, 0.77778],
"934": [0, 0.69444, 0, 0, 0.72222],
"936": [0, 0.69444, 0, 0, 0.77778],
"937": [0, 0.69444, 0, 0, 0.72222],
"8211": [0, 0.44444, 0.02778, 0, 0.5],
"8212": [0, 0.44444, 0.02778, 0, 1.0],
"8216": [0, 0.69444, 0, 0, 0.27778],
"8217": [0, 0.69444, 0, 0, 0.27778],
"8220": [0, 0.69444, 0, 0, 0.5],
"8221": [0, 0.69444, 0, 0, 0.5]
},
"Script-Regular": {
"65": [0, 0.7, 0.22925, 0, 0.80253],
"66": [0, 0.7, 0.04087, 0, 0.90757],
"67": [0, 0.7, 0.1689, 0, 0.66619],
"68": [0, 0.7, 0.09371, 0, 0.77443],
"69": [0, 0.7, 0.18583, 0, 0.56162],
"70": [0, 0.7, 0.13634, 0, 0.89544],
"71": [0, 0.7, 0.17322, 0, 0.60961],
"72": [0, 0.7, 0.29694, 0, 0.96919],
"73": [0, 0.7, 0.19189, 0, 0.80907],
"74": [0.27778, 0.7, 0.19189, 0, 1.05159],
"75": [0, 0.7, 0.31259, 0, 0.91364],
"76": [0, 0.7, 0.19189, 0, 0.87373],
"77": [0, 0.7, 0.15981, 0, 1.08031],
"78": [0, 0.7, 0.3525, 0, 0.9015],
"79": [0, 0.7, 0.08078, 0, 0.73787],
"80": [0, 0.7, 0.08078, 0, 1.01262],
"81": [0, 0.7, 0.03305, 0, 0.88282],
"82": [0, 0.7, 0.06259, 0, 0.85],
"83": [0, 0.7, 0.19189, 0, 0.86767],
"84": [0, 0.7, 0.29087, 0, 0.74697],
"85": [0, 0.7, 0.25815, 0, 0.79996],
"86": [0, 0.7, 0.27523, 0, 0.62204],
"87": [0, 0.7, 0.27523, 0, 0.80532],
"88": [0, 0.7, 0.26006, 0, 0.94445],
"89": [0, 0.7, 0.2939, 0, 0.70961],
"90": [0, 0.7, 0.24037, 0, 0.8212]
},
"Size1-Regular": {
"40": [0.35001, 0.85, 0, 0, 0.45834],
"41": [0.35001, 0.85, 0, 0, 0.45834],
"47": [0.35001, 0.85, 0, 0, 0.57778],
"91": [0.35001, 0.85, 0, 0, 0.41667],
"92": [0.35001, 0.85, 0, 0, 0.57778],
"93": [0.35001, 0.85, 0, 0, 0.41667],
"123": [0.35001, 0.85, 0, 0, 0.58334],
"125": [0.35001, 0.85, 0, 0, 0.58334],
"710": [0, 0.72222, 0, 0, 0.55556],
"732": [0, 0.72222, 0, 0, 0.55556],
"770": [0, 0.72222, 0, 0, 0.55556],
"771": [0, 0.72222, 0, 0, 0.55556],
"8214": [-0.00099, 0.601, 0, 0, 0.77778],
"8593": [1e-05, 0.6, 0, 0, 0.66667],
"8595": [1e-05, 0.6, 0, 0, 0.66667],
"8657": [1e-05, 0.6, 0, 0, 0.77778],
"8659": [1e-05, 0.6, 0, 0, 0.77778],
"8719": [0.25001, 0.75, 0, 0, 0.94445],
"8720": [0.25001, 0.75, 0, 0, 0.94445],
"8721": [0.25001, 0.75, 0, 0, 1.05556],
"8730": [0.35001, 0.85, 0, 0, 1.0],
"8739": [-0.00599, 0.606, 0, 0, 0.33333],
"8741": [-0.00599, 0.606, 0, 0, 0.55556],
"8747": [0.30612, 0.805, 0.19445, 0, 0.47222],
"8748": [0.306, 0.805, 0.19445, 0, 0.47222],
"8749": [0.306, 0.805, 0.19445, 0, 0.47222],
"8750": [0.30612, 0.805, 0.19445, 0, 0.47222],
"8896": [0.25001, 0.75, 0, 0, 0.83334],
"8897": [0.25001, 0.75, 0, 0, 0.83334],
"8898": [0.25001, 0.75, 0, 0, 0.83334],
"8899": [0.25001, 0.75, 0, 0, 0.83334],
"8968": [0.35001, 0.85, 0, 0, 0.47222],
"8969": [0.35001, 0.85, 0, 0, 0.47222],
"8970": [0.35001, 0.85, 0, 0, 0.47222],
"8971": [0.35001, 0.85, 0, 0, 0.47222],
"9168": [-0.00099, 0.601, 0, 0, 0.66667],
"10216": [0.35001, 0.85, 0, 0, 0.47222],
"10217": [0.35001, 0.85, 0, 0, 0.47222],
"10752": [0.25001, 0.75, 0, 0, 1.11111],
"10753": [0.25001, 0.75, 0, 0, 1.11111],
"10754": [0.25001, 0.75, 0, 0, 1.11111],
"10756": [0.25001, 0.75, 0, 0, 0.83334],
"10758": [0.25001, 0.75, 0, 0, 0.83334]
},
"Size2-Regular": {
"40": [0.65002, 1.15, 0, 0, 0.59722],
"41": [0.65002, 1.15, 0, 0, 0.59722],
"47": [0.65002, 1.15, 0, 0, 0.81111],
"91": [0.65002, 1.15, 0, 0, 0.47222],
"92": [0.65002, 1.15, 0, 0, 0.81111],
"93": [0.65002, 1.15, 0, 0, 0.47222],
"123": [0.65002, 1.15, 0, 0, 0.66667],
"125": [0.65002, 1.15, 0, 0, 0.66667],
"710": [0, 0.75, 0, 0, 1.0],
"732": [0, 0.75, 0, 0, 1.0],
"770": [0, 0.75, 0, 0, 1.0],
"771": [0, 0.75, 0, 0, 1.0],
"8719": [0.55001, 1.05, 0, 0, 1.27778],
"8720": [0.55001, 1.05, 0, 0, 1.27778],
"8721": [0.55001, 1.05, 0, 0, 1.44445],
"8730": [0.65002, 1.15, 0, 0, 1.0],
"8747": [0.86225, 1.36, 0.44445, 0, 0.55556],
"8748": [0.862, 1.36, 0.44445, 0, 0.55556],
"8749": [0.862, 1.36, 0.44445, 0, 0.55556],
"8750": [0.86225, 1.36, 0.44445, 0, 0.55556],
"8896": [0.55001, 1.05, 0, 0, 1.11111],
"8897": [0.55001, 1.05, 0, 0, 1.11111],
"8898": [0.55001, 1.05, 0, 0, 1.11111],
"8899": [0.55001, 1.05, 0, 0, 1.11111],
"8968": [0.65002, 1.15, 0, 0, 0.52778],
"8969": [0.65002, 1.15, 0, 0, 0.52778],
"8970": [0.65002, 1.15, 0, 0, 0.52778],
"8971": [0.65002, 1.15, 0, 0, 0.52778],
"10216": [0.65002, 1.15, 0, 0, 0.61111],
"10217": [0.65002, 1.15, 0, 0, 0.61111],
"10752": [0.55001, 1.05, 0, 0, 1.51112],
"10753": [0.55001, 1.05, 0, 0, 1.51112],
"10754": [0.55001, 1.05, 0, 0, 1.51112],
"10756": [0.55001, 1.05, 0, 0, 1.11111],
"10758": [0.55001, 1.05, 0, 0, 1.11111]
},
"Size3-Regular": {
"40": [0.95003, 1.45, 0, 0, 0.73611],
"41": [0.95003, 1.45, 0, 0, 0.73611],
"47": [0.95003, 1.45, 0, 0, 1.04445],
"91": [0.95003, 1.45, 0, 0, 0.52778],
"92": [0.95003, 1.45, 0, 0, 1.04445],
"93": [0.95003, 1.45, 0, 0, 0.52778],
"123": [0.95003, 1.45, 0, 0, 0.75],
"125": [0.95003, 1.45, 0, 0, 0.75],
"710": [0, 0.75, 0, 0, 1.44445],
"732": [0, 0.75, 0, 0, 1.44445],
"770": [0, 0.75, 0, 0, 1.44445],
"771": [0, 0.75, 0, 0, 1.44445],
"8730": [0.95003, 1.45, 0, 0, 1.0],
"8968": [0.95003, 1.45, 0, 0, 0.58334],
"8969": [0.95003, 1.45, 0, 0, 0.58334],
"8970": [0.95003, 1.45, 0, 0, 0.58334],
"8971": [0.95003, 1.45, 0, 0, 0.58334],
"10216": [0.95003, 1.45, 0, 0, 0.75],
"10217": [0.95003, 1.45, 0, 0, 0.75]
},
"Size4-Regular": {
"40": [1.25003, 1.75, 0, 0, 0.79167],
"41": [1.25003, 1.75, 0, 0, 0.79167],
"47": [1.25003, 1.75, 0, 0, 1.27778],
"91": [1.25003, 1.75, 0, 0, 0.58334],
"92": [1.25003, 1.75, 0, 0, 1.27778],
"93": [1.25003, 1.75, 0, 0, 0.58334],
"123": [1.25003, 1.75, 0, 0, 0.80556],
"125": [1.25003, 1.75, 0, 0, 0.80556],
"710": [0, 0.825, 0, 0, 1.8889],
"732": [0, 0.825, 0, 0, 1.8889],
"770": [0, 0.825, 0, 0, 1.8889],
"771": [0, 0.825, 0, 0, 1.8889],
"8730": [1.25003, 1.75, 0, 0, 1.0],
"8968": [1.25003, 1.75, 0, 0, 0.63889],
"8969": [1.25003, 1.75, 0, 0, 0.63889],
"8970": [1.25003, 1.75, 0, 0, 0.63889],
"8971": [1.25003, 1.75, 0, 0, 0.63889],
"9115": [0.64502, 1.155, 0, 0, 0.875],
"9116": [1e-05, 0.6, 0, 0, 0.875],
"9117": [0.64502, 1.155, 0, 0, 0.875],
"9118": [0.64502, 1.155, 0, 0, 0.875],
"9119": [1e-05, 0.6, 0, 0, 0.875],
"9120": [0.64502, 1.155, 0, 0, 0.875],
"9121": [0.64502, 1.155, 0, 0, 0.66667],
"9122": [-0.00099, 0.601, 0, 0, 0.66667],
"9123": [0.64502, 1.155, 0, 0, 0.66667],
"9124": [0.64502, 1.155, 0, 0, 0.66667],
"9125": [-0.00099, 0.601, 0, 0, 0.66667],
"9126": [0.64502, 1.155, 0, 0, 0.66667],
"9127": [1e-05, 0.9, 0, 0, 0.88889],
"9128": [0.65002, 1.15, 0, 0, 0.88889],
"9129": [0.90001, 0, 0, 0, 0.88889],
"9130": [0, 0.3, 0, 0, 0.88889],
"9131": [1e-05, 0.9, 0, 0, 0.88889],
"9132": [0.65002, 1.15, 0, 0, 0.88889],
"9133": [0.90001, 0, 0, 0, 0.88889],
"9143": [0.88502, 0.915, 0, 0, 1.05556],
"10216": [1.25003, 1.75, 0, 0, 0.80556],
"10217": [1.25003, 1.75, 0, 0, 0.80556],
"57344": [-0.00499, 0.605, 0, 0, 1.05556],
"57345": [-0.00499, 0.605, 0, 0, 1.05556],
"57680": [0, 0.12, 0, 0, 0.45],
"57681": [0, 0.12, 0, 0, 0.45],
"57682": [0, 0.12, 0, 0, 0.45],
"57683": [0, 0.12, 0, 0, 0.45]
},
"Typewriter-Regular": {
"32": [0, 0, 0, 0, 0.525],
"33": [0, 0.61111, 0, 0, 0.525],
"34": [0, 0.61111, 0, 0, 0.525],
"35": [0, 0.61111, 0, 0, 0.525],
"36": [0.08333, 0.69444, 0, 0, 0.525],
"37": [0.08333, 0.69444, 0, 0, 0.525],
"38": [0, 0.61111, 0, 0, 0.525],
"39": [0, 0.61111, 0, 0, 0.525],
"40": [0.08333, 0.69444, 0, 0, 0.525],
"41": [0.08333, 0.69444, 0, 0, 0.525],
"42": [0, 0.52083, 0, 0, 0.525],
"43": [-0.08056, 0.53055, 0, 0, 0.525],
"44": [0.13889, 0.125, 0, 0, 0.525],
"45": [-0.08056, 0.53055, 0, 0, 0.525],
"46": [0, 0.125, 0, 0, 0.525],
"47": [0.08333, 0.69444, 0, 0, 0.525],
"48": [0, 0.61111, 0, 0, 0.525],
"49": [0, 0.61111, 0, 0, 0.525],
"50": [0, 0.61111, 0, 0, 0.525],
"51": [0, 0.61111, 0, 0, 0.525],
"52": [0, 0.61111, 0, 0, 0.525],
"53": [0, 0.61111, 0, 0, 0.525],
"54": [0, 0.61111, 0, 0, 0.525],
"55": [0, 0.61111, 0, 0, 0.525],
"56": [0, 0.61111, 0, 0, 0.525],
"57": [0, 0.61111, 0, 0, 0.525],
"58": [0, 0.43056, 0, 0, 0.525],
"59": [0.13889, 0.43056, 0, 0, 0.525],
"60": [-0.05556, 0.55556, 0, 0, 0.525],
"61": [-0.19549, 0.41562, 0, 0, 0.525],
"62": [-0.05556, 0.55556, 0, 0, 0.525],
"63": [0, 0.61111, 0, 0, 0.525],
"64": [0, 0.61111, 0, 0, 0.525],
"65": [0, 0.61111, 0, 0, 0.525],
"66": [0, 0.61111, 0, 0, 0.525],
"67": [0, 0.61111, 0, 0, 0.525],
"68": [0, 0.61111, 0, 0, 0.525],
"69": [0, 0.61111, 0, 0, 0.525],
"70": [0, 0.61111, 0, 0, 0.525],
"71": [0, 0.61111, 0, 0, 0.525],
"72": [0, 0.61111, 0, 0, 0.525],
"73": [0, 0.61111, 0, 0, 0.525],
"74": [0, 0.61111, 0, 0, 0.525],
"75": [0, 0.61111, 0, 0, 0.525],
"76": [0, 0.61111, 0, 0, 0.525],
"77": [0, 0.61111, 0, 0, 0.525],
"78": [0, 0.61111, 0, 0, 0.525],
"79": [0, 0.61111, 0, 0, 0.525],
"80": [0, 0.61111, 0, 0, 0.525],
"81": [0.13889, 0.61111, 0, 0, 0.525],
"82": [0, 0.61111, 0, 0, 0.525],
"83": [0, 0.61111, 0, 0, 0.525],
"84": [0, 0.61111, 0, 0, 0.525],
"85": [0, 0.61111, 0, 0, 0.525],
"86": [0, 0.61111, 0, 0, 0.525],
"87": [0, 0.61111, 0, 0, 0.525],
"88": [0, 0.61111, 0, 0, 0.525],
"89": [0, 0.61111, 0, 0, 0.525],
"90": [0, 0.61111, 0, 0, 0.525],
"91": [0.08333, 0.69444, 0, 0, 0.525],
"92": [0.08333, 0.69444, 0, 0, 0.525],
"93": [0.08333, 0.69444, 0, 0, 0.525],
"94": [0, 0.61111, 0, 0, 0.525],
"95": [0.09514, 0, 0, 0, 0.525],
"96": [0, 0.61111, 0, 0, 0.525],
"97": [0, 0.43056, 0, 0, 0.525],
"98": [0, 0.61111, 0, 0, 0.525],
"99": [0, 0.43056, 0, 0, 0.525],
"100": [0, 0.61111, 0, 0, 0.525],
"101": [0, 0.43056, 0, 0, 0.525],
"102": [0, 0.61111, 0, 0, 0.525],
"103": [0.22222, 0.43056, 0, 0, 0.525],
"104": [0, 0.61111, 0, 0, 0.525],
"105": [0, 0.61111, 0, 0, 0.525],
"106": [0.22222, 0.61111, 0, 0, 0.525],
"107": [0, 0.61111, 0, 0, 0.525],
"108": [0, 0.61111, 0, 0, 0.525],
"109": [0, 0.43056, 0, 0, 0.525],
"110": [0, 0.43056, 0, 0, 0.525],
"111": [0, 0.43056, 0, 0, 0.525],
"112": [0.22222, 0.43056, 0, 0, 0.525],
"113": [0.22222, 0.43056, 0, 0, 0.525],
"114": [0, 0.43056, 0, 0, 0.525],
"115": [0, 0.43056, 0, 0, 0.525],
"116": [0, 0.55358, 0, 0, 0.525],
"117": [0, 0.43056, 0, 0, 0.525],
"118": [0, 0.43056, 0, 0, 0.525],
"119": [0, 0.43056, 0, 0, 0.525],
"120": [0, 0.43056, 0, 0, 0.525],
"121": [0.22222, 0.43056, 0, 0, 0.525],
"122": [0, 0.43056, 0, 0, 0.525],
"123": [0.08333, 0.69444, 0, 0, 0.525],
"124": [0.08333, 0.69444, 0, 0, 0.525],
"125": [0.08333, 0.69444, 0, 0, 0.525],
"126": [0, 0.61111, 0, 0, 0.525],
"127": [0, 0.61111, 0, 0, 0.525],
"160": [0, 0, 0, 0, 0.525],
"176": [0, 0.61111, 0, 0, 0.525],
"184": [0.19445, 0, 0, 0, 0.525],
"305": [0, 0.43056, 0, 0, 0.525],
"567": [0.22222, 0.43056, 0, 0, 0.525],
"711": [0, 0.56597, 0, 0, 0.525],
"713": [0, 0.56555, 0, 0, 0.525],
"714": [0, 0.61111, 0, 0, 0.525],
"715": [0, 0.61111, 0, 0, 0.525],
"728": [0, 0.61111, 0, 0, 0.525],
"730": [0, 0.61111, 0, 0, 0.525],
"770": [0, 0.61111, 0, 0, 0.525],
"771": [0, 0.61111, 0, 0, 0.525],
"776": [0, 0.61111, 0, 0, 0.525],
"915": [0, 0.61111, 0, 0, 0.525],
"916": [0, 0.61111, 0, 0, 0.525],
"920": [0, 0.61111, 0, 0, 0.525],
"923": [0, 0.61111, 0, 0, 0.525],
"926": [0, 0.61111, 0, 0, 0.525],
"928": [0, 0.61111, 0, 0, 0.525],
"931": [0, 0.61111, 0, 0, 0.525],
"933": [0, 0.61111, 0, 0, 0.525],
"934": [0, 0.61111, 0, 0, 0.525],
"936": [0, 0.61111, 0, 0, 0.525],
"937": [0, 0.61111, 0, 0, 0.525],
"8216": [0, 0.61111, 0, 0, 0.525],
"8217": [0, 0.61111, 0, 0, 0.525],
"8242": [0, 0.61111, 0, 0, 0.525],
"9251": [0.11111, 0.21944, 0, 0, 0.525]
}
});
// CONCATENATED MODULE: ./src/fontMetrics.js
/**
* This file contains metrics regarding fonts and individual symbols. The sigma
* and xi variables, as well as the metricMap map contain data extracted from
* TeX, TeX font metrics, and the TTF files. These data are then exposed via the
* `metrics` variable and the getCharacterMetrics function.
*/
// In TeX, there are actually three sets of dimensions, one for each of
// textstyle (size index 5 and higher: >=9pt), scriptstyle (size index 3 and 4:
// 7-8pt), and scriptscriptstyle (size index 1 and 2: 5-6pt). These are
// provided in the the arrays below, in that order.
//
// The font metrics are stored in fonts cmsy10, cmsy7, and cmsy5 respsectively.
// This was determined by running the following script:
//
// latex -interaction=nonstopmode \
// '\documentclass{article}\usepackage{amsmath}\begin{document}' \
// '$a$ \expandafter\show\the\textfont2' \
// '\expandafter\show\the\scriptfont2' \
// '\expandafter\show\the\scriptscriptfont2' \
// '\stop'
//
// The metrics themselves were retreived using the following commands:
//
// tftopl cmsy10
// tftopl cmsy7
// tftopl cmsy5
//
// The output of each of these commands is quite lengthy. The only part we
// care about is the FONTDIMEN section. Each value is measured in EMs.
var sigmasAndXis = {
slant: [0.250, 0.250, 0.250],
// sigma1
space: [0.000, 0.000, 0.000],
// sigma2
stretch: [0.000, 0.000, 0.000],
// sigma3
shrink: [0.000, 0.000, 0.000],
// sigma4
xHeight: [0.431, 0.431, 0.431],
// sigma5
quad: [1.000, 1.171, 1.472],
// sigma6
extraSpace: [0.000, 0.000, 0.000],
// sigma7
num1: [0.677, 0.732, 0.925],
// sigma8
num2: [0.394, 0.384, 0.387],
// sigma9
num3: [0.444, 0.471, 0.504],
// sigma10
denom1: [0.686, 0.752, 1.025],
// sigma11
denom2: [0.345, 0.344, 0.532],
// sigma12
sup1: [0.413, 0.503, 0.504],
// sigma13
sup2: [0.363, 0.431, 0.404],
// sigma14
sup3: [0.289, 0.286, 0.294],
// sigma15
sub1: [0.150, 0.143, 0.200],
// sigma16
sub2: [0.247, 0.286, 0.400],
// sigma17
supDrop: [0.386, 0.353, 0.494],
// sigma18
subDrop: [0.050, 0.071, 0.100],
// sigma19
delim1: [2.390, 1.700, 1.980],
// sigma20
delim2: [1.010, 1.157, 1.420],
// sigma21
axisHeight: [0.250, 0.250, 0.250],
// sigma22
// These font metrics are extracted from TeX by using tftopl on cmex10.tfm;
// they correspond to the font parameters of the extension fonts (family 3).
// See the TeXbook, page 441. In AMSTeX, the extension fonts scale; to
// match cmex7, we'd use cmex7.tfm values for script and scriptscript
// values.
defaultRuleThickness: [0.04, 0.049, 0.049],
// xi8; cmex7: 0.049
bigOpSpacing1: [0.111, 0.111, 0.111],
// xi9
bigOpSpacing2: [0.166, 0.166, 0.166],
// xi10
bigOpSpacing3: [0.2, 0.2, 0.2],
// xi11
bigOpSpacing4: [0.6, 0.611, 0.611],
// xi12; cmex7: 0.611
bigOpSpacing5: [0.1, 0.143, 0.143],
// xi13; cmex7: 0.143
// The \sqrt rule width is taken from the height of the surd character.
// Since we use the same font at all sizes, this thickness doesn't scale.
sqrtRuleThickness: [0.04, 0.04, 0.04],
// This value determines how large a pt is, for metrics which are defined
// in terms of pts.
// This value is also used in katex.less; if you change it make sure the
// values match.
ptPerEm: [10.0, 10.0, 10.0],
// The space between adjacent `|` columns in an array definition. From
// `\showthe\doublerulesep` in LaTeX. Equals 2.0 / ptPerEm.
doubleRuleSep: [0.2, 0.2, 0.2],
// The width of separator lines in {array} environments. From
// `\showthe\arrayrulewidth` in LaTeX. Equals 0.4 / ptPerEm.
arrayRuleWidth: [0.04, 0.04, 0.04],
// Two values from LaTeX source2e:
fboxsep: [0.3, 0.3, 0.3],
// 3 pt / ptPerEm
fboxrule: [0.04, 0.04, 0.04] // 0.4 pt / ptPerEm
}; // This map contains a mapping from font name and character code to character
// metrics, including height, depth, italic correction, and skew (kern from the
// character to the corresponding \skewchar)
// This map is generated via `make metrics`. It should not be changed manually.
// These are very rough approximations. We default to Times New Roman which
// should have Latin-1 and Cyrillic characters, but may not depending on the
// operating system. The metrics do not account for extra height from the
// accents. In the case of Cyrillic characters which have both ascenders and
// descenders we prefer approximations with ascenders, primarily to prevent
// the fraction bar or root line from intersecting the glyph.
// TODO(kevinb) allow union of multiple glyph metrics for better accuracy.
var extraCharacterMap = {
// Latin-1
'Å': 'A',
'Ç': 'C',
'Ð': 'D',
'Þ': 'o',
'å': 'a',
'ç': 'c',
'ð': 'd',
'þ': 'o',
// Cyrillic
'А': 'A',
'Б': 'B',
'В': 'B',
'Г': 'F',
'Д': 'A',
'Е': 'E',
'Ж': 'K',
'З': '3',
'И': 'N',
'Й': 'N',
'К': 'K',
'Л': 'N',
'М': 'M',
'Н': 'H',
'О': 'O',
'П': 'N',
'Р': 'P',
'С': 'C',
'Т': 'T',
'У': 'y',
'Ф': 'O',
'Х': 'X',
'Ц': 'U',
'Ч': 'h',
'Ш': 'W',
'Щ': 'W',
'Ъ': 'B',
'Ы': 'X',
'Ь': 'B',
'Э': '3',
'Ю': 'X',
'Я': 'R',
'а': 'a',
'б': 'b',
'в': 'a',
'г': 'r',
'д': 'y',
'е': 'e',
'ж': 'm',
'з': 'e',
'и': 'n',
'й': 'n',
'к': 'n',
'л': 'n',
'м': 'm',
'н': 'n',
'о': 'o',
'п': 'n',
'р': 'p',
'с': 'c',
'т': 'o',
'у': 'y',
'ф': 'b',
'х': 'x',
'ц': 'n',
'ч': 'n',
'ш': 'w',
'щ': 'w',
'ъ': 'a',
'ы': 'm',
'ь': 'a',
'э': 'e',
'ю': 'm',
'я': 'r'
};
/**
* This function adds new font metrics to default metricMap
* It can also override existing metrics
*/
function setFontMetrics(fontName, metrics) {
fontMetricsData[fontName] = metrics;
}
/**
* This function is a convenience function for looking up information in the
* metricMap table. It takes a character as a string, and a font.
*
* Note: the `width` property may be undefined if fontMetricsData.js wasn't
* built using `Make extended_metrics`.
*/
function getCharacterMetrics(character, font, mode) {
if (!fontMetricsData[font]) {
throw new Error("Font metrics not found for font: " + font + ".");
}
var ch = character.charCodeAt(0);
var metrics = fontMetricsData[font][ch];
if (!metrics && character[0] in extraCharacterMap) {
ch = extraCharacterMap[character[0]].charCodeAt(0);
metrics = fontMetricsData[font][ch];
}
if (!metrics && mode === 'text') {
// We don't typically have font metrics for Asian scripts.
// But since we support them in text mode, we need to return
// some sort of metrics.
// So if the character is in a script we support but we
// don't have metrics for it, just use the metrics for
// the Latin capital letter M. This is close enough because
// we (currently) only care about the height of the glpyh
// not its width.
if (supportedCodepoint(ch)) {
metrics = fontMetricsData[font][77]; // 77 is the charcode for 'M'
}
}
if (metrics) {
return {
depth: metrics[0],
height: metrics[1],
italic: metrics[2],
skew: metrics[3],
width: metrics[4]
};
}
}
var fontMetricsBySizeIndex = {};
/**
* Get the font metrics for a given size.
*/
function getGlobalMetrics(size) {
var sizeIndex;
if (size >= 5) {
sizeIndex = 0;
} else if (size >= 3) {
sizeIndex = 1;
} else {
sizeIndex = 2;
}
if (!fontMetricsBySizeIndex[sizeIndex]) {
var metrics = fontMetricsBySizeIndex[sizeIndex] = {
cssEmPerMu: sigmasAndXis.quad[sizeIndex] / 18
};
for (var key in sigmasAndXis) {
if (sigmasAndXis.hasOwnProperty(key)) {
metrics[key] = sigmasAndXis[key][sizeIndex];
}
}
}
return fontMetricsBySizeIndex[sizeIndex];
}
// CONCATENATED MODULE: ./src/symbols.js
/**
* This file holds a list of all no-argument functions and single-character
* symbols (like 'a' or ';').
*
* For each of the symbols, there are three properties they can have:
* - font (required): the font to be used for this symbol. Either "main" (the
normal font), or "ams" (the ams fonts).
* - group (required): the ParseNode group type the symbol should have (i.e.
"textord", "mathord", etc).
See https://github.com/KaTeX/KaTeX/wiki/Examining-TeX#group-types
* - replace: the character that this symbol or function should be
* replaced with (i.e. "\phi" has a replace value of "\u03d5", the phi
* character in the main font).
*
* The outermost map in the table indicates what mode the symbols should be
* accepted in (e.g. "math" or "text").
*/
// Some of these have a "-token" suffix since these are also used as `ParseNode`
// types for raw text tokens, and we want to avoid conflicts with higher-level
// `ParseNode` types. These `ParseNode`s are constructed within `Parser` by
// looking up the `symbols` map.
var ATOMS = {
"bin": 1,
"close": 1,
"inner": 1,
"open": 1,
"punct": 1,
"rel": 1
};
var NON_ATOMS = {
"accent-token": 1,
"mathord": 1,
"op-token": 1,
"spacing": 1,
"textord": 1
};
var symbols = {
"math": {},
"text": {}
};
/* harmony default export */ var src_symbols = (symbols);
/** `acceptUnicodeChar = true` is only applicable if `replace` is set. */
function defineSymbol(mode, font, group, replace, name, acceptUnicodeChar) {
symbols[mode][name] = {
font: font,
group: group,
replace: replace
};
if (acceptUnicodeChar && replace) {
symbols[mode][replace] = symbols[mode][name];
}
} // Some abbreviations for commonly used strings.
// This helps minify the code, and also spotting typos using jshint.
// modes:
var symbols_math = "math";
var symbols_text = "text"; // fonts:
var main = "main";
var ams = "ams"; // groups:
var symbols_accent = "accent-token";
var bin = "bin";
var symbols_close = "close";
var symbols_inner = "inner";
var mathord = "mathord";
var op = "op-token";
var symbols_open = "open";
var punct = "punct";
var rel = "rel";
var symbols_spacing = "spacing";
var symbols_textord = "textord"; // Now comes the symbol table
// Relation Symbols
defineSymbol(symbols_math, main, rel, "\u2261", "\\equiv", true);
defineSymbol(symbols_math, main, rel, "\u227A", "\\prec", true);
defineSymbol(symbols_math, main, rel, "\u227B", "\\succ", true);
defineSymbol(symbols_math, main, rel, "\u223C", "\\sim", true);
defineSymbol(symbols_math, main, rel, "\u22A5", "\\perp");
defineSymbol(symbols_math, main, rel, "\u2AAF", "\\preceq", true);
defineSymbol(symbols_math, main, rel, "\u2AB0", "\\succeq", true);
defineSymbol(symbols_math, main, rel, "\u2243", "\\simeq", true);
defineSymbol(symbols_math, main, rel, "\u2223", "\\mid", true);
defineSymbol(symbols_math, main, rel, "\u226A", "\\ll", true);
defineSymbol(symbols_math, main, rel, "\u226B", "\\gg", true);
defineSymbol(symbols_math, main, rel, "\u224D", "\\asymp", true);
defineSymbol(symbols_math, main, rel, "\u2225", "\\parallel");
defineSymbol(symbols_math, main, rel, "\u22C8", "\\bowtie", true);
defineSymbol(symbols_math, main, rel, "\u2323", "\\smile", true);
defineSymbol(symbols_math, main, rel, "\u2291", "\\sqsubseteq", true);
defineSymbol(symbols_math, main, rel, "\u2292", "\\sqsupseteq", true);
defineSymbol(symbols_math, main, rel, "\u2250", "\\doteq", true);
defineSymbol(symbols_math, main, rel, "\u2322", "\\frown", true);
defineSymbol(symbols_math, main, rel, "\u220B", "\\ni", true);
defineSymbol(symbols_math, main, rel, "\u221D", "\\propto", true);
defineSymbol(symbols_math, main, rel, "\u22A2", "\\vdash", true);
defineSymbol(symbols_math, main, rel, "\u22A3", "\\dashv", true);
defineSymbol(symbols_math, main, rel, "\u220B", "\\owns"); // Punctuation
defineSymbol(symbols_math, main, punct, ".", "\\ldotp");
defineSymbol(symbols_math, main, punct, "\u22C5", "\\cdotp"); // Misc Symbols
defineSymbol(symbols_math, main, symbols_textord, "#", "\\#");
defineSymbol(symbols_text, main, symbols_textord, "#", "\\#");
defineSymbol(symbols_math, main, symbols_textord, "&", "\\&");
defineSymbol(symbols_text, main, symbols_textord, "&", "\\&");
defineSymbol(symbols_math, main, symbols_textord, "\u2135", "\\aleph", true);
defineSymbol(symbols_math, main, symbols_textord, "\u2200", "\\forall", true);
defineSymbol(symbols_math, main, symbols_textord, "\u210F", "\\hbar", true);
defineSymbol(symbols_math, main, symbols_textord, "\u2203", "\\exists", true);
defineSymbol(symbols_math, main, symbols_textord, "\u2207", "\\nabla", true);
defineSymbol(symbols_math, main, symbols_textord, "\u266D", "\\flat", true);
defineSymbol(symbols_math, main, symbols_textord, "\u2113", "\\ell", true);
defineSymbol(symbols_math, main, symbols_textord, "\u266E", "\\natural", true);
defineSymbol(symbols_math, main, symbols_textord, "\u2663", "\\clubsuit", true);
defineSymbol(symbols_math, main, symbols_textord, "\u2118", "\\wp", true);
defineSymbol(symbols_math, main, symbols_textord, "\u266F", "\\sharp", true);
defineSymbol(symbols_math, main, symbols_textord, "\u2662", "\\diamondsuit", true);
defineSymbol(symbols_math, main, symbols_textord, "\u211C", "\\Re", true);
defineSymbol(symbols_math, main, symbols_textord, "\u2661", "\\heartsuit", true);
defineSymbol(symbols_math, main, symbols_textord, "\u2111", "\\Im", true);
defineSymbol(symbols_math, main, symbols_textord, "\u2660", "\\spadesuit", true);
defineSymbol(symbols_text, main, symbols_textord, "\xA7", "\\S", true);
defineSymbol(symbols_text, main, symbols_textord, "\xB6", "\\P", true); // Math and Text
defineSymbol(symbols_math, main, symbols_textord, "\u2020", "\\dag");
defineSymbol(symbols_text, main, symbols_textord, "\u2020", "\\dag");
defineSymbol(symbols_text, main, symbols_textord, "\u2020", "\\textdagger");
defineSymbol(symbols_math, main, symbols_textord, "\u2021", "\\ddag");
defineSymbol(symbols_text, main, symbols_textord, "\u2021", "\\ddag");
defineSymbol(symbols_text, main, symbols_textord, "\u2021", "\\textdaggerdbl"); // Large Delimiters
defineSymbol(symbols_math, main, symbols_close, "\u23B1", "\\rmoustache", true);
defineSymbol(symbols_math, main, symbols_open, "\u23B0", "\\lmoustache", true);
defineSymbol(symbols_math, main, symbols_close, "\u27EF", "\\rgroup", true);
defineSymbol(symbols_math, main, symbols_open, "\u27EE", "\\lgroup", true); // Binary Operators
defineSymbol(symbols_math, main, bin, "\u2213", "\\mp", true);
defineSymbol(symbols_math, main, bin, "\u2296", "\\ominus", true);
defineSymbol(symbols_math, main, bin, "\u228E", "\\uplus", true);
defineSymbol(symbols_math, main, bin, "\u2293", "\\sqcap", true);
defineSymbol(symbols_math, main, bin, "\u2217", "\\ast");
defineSymbol(symbols_math, main, bin, "\u2294", "\\sqcup", true);
defineSymbol(symbols_math, main, bin, "\u25EF", "\\bigcirc");
defineSymbol(symbols_math, main, bin, "\u2219", "\\bullet");
defineSymbol(symbols_math, main, bin, "\u2021", "\\ddagger");
defineSymbol(symbols_math, main, bin, "\u2240", "\\wr", true);
defineSymbol(symbols_math, main, bin, "\u2A3F", "\\amalg");
defineSymbol(symbols_math, main, bin, "&", "\\And"); // from amsmath
// Arrow Symbols
defineSymbol(symbols_math, main, rel, "\u27F5", "\\longleftarrow", true);
defineSymbol(symbols_math, main, rel, "\u21D0", "\\Leftarrow", true);
defineSymbol(symbols_math, main, rel, "\u27F8", "\\Longleftarrow", true);
defineSymbol(symbols_math, main, rel, "\u27F6", "\\longrightarrow", true);
defineSymbol(symbols_math, main, rel, "\u21D2", "\\Rightarrow", true);
defineSymbol(symbols_math, main, rel, "\u27F9", "\\Longrightarrow", true);
defineSymbol(symbols_math, main, rel, "\u2194", "\\leftrightarrow", true);
defineSymbol(symbols_math, main, rel, "\u27F7", "\\longleftrightarrow", true);
defineSymbol(symbols_math, main, rel, "\u21D4", "\\Leftrightarrow", true);
defineSymbol(symbols_math, main, rel, "\u27FA", "\\Longleftrightarrow", true);
defineSymbol(symbols_math, main, rel, "\u21A6", "\\mapsto", true);
defineSymbol(symbols_math, main, rel, "\u27FC", "\\longmapsto", true);
defineSymbol(symbols_math, main, rel, "\u2197", "\\nearrow", true);
defineSymbol(symbols_math, main, rel, "\u21A9", "\\hookleftarrow", true);
defineSymbol(symbols_math, main, rel, "\u21AA", "\\hookrightarrow", true);
defineSymbol(symbols_math, main, rel, "\u2198", "\\searrow", true);
defineSymbol(symbols_math, main, rel, "\u21BC", "\\leftharpoonup", true);
defineSymbol(symbols_math, main, rel, "\u21C0", "\\rightharpoonup", true);
defineSymbol(symbols_math, main, rel, "\u2199", "\\swarrow", true);
defineSymbol(symbols_math, main, rel, "\u21BD", "\\leftharpoondown", true);
defineSymbol(symbols_math, main, rel, "\u21C1", "\\rightharpoondown", true);
defineSymbol(symbols_math, main, rel, "\u2196", "\\nwarrow", true);
defineSymbol(symbols_math, main, rel, "\u21CC", "\\rightleftharpoons", true); // AMS Negated Binary Relations
defineSymbol(symbols_math, ams, rel, "\u226E", "\\nless", true); // Symbol names preceeded by "@" each have a corresponding macro.
defineSymbol(symbols_math, ams, rel, "\uE010", "\\@nleqslant");
defineSymbol(symbols_math, ams, rel, "\uE011", "\\@nleqq");
defineSymbol(symbols_math, ams, rel, "\u2A87", "\\lneq", true);
defineSymbol(symbols_math, ams, rel, "\u2268", "\\lneqq", true);
defineSymbol(symbols_math, ams, rel, "\uE00C", "\\@lvertneqq");
defineSymbol(symbols_math, ams, rel, "\u22E6", "\\lnsim", true);
defineSymbol(symbols_math, ams, rel, "\u2A89", "\\lnapprox", true);
defineSymbol(symbols_math, ams, rel, "\u2280", "\\nprec", true); // unicode-math maps \u22e0 to \npreccurlyeq. We'll use the AMS synonym.
defineSymbol(symbols_math, ams, rel, "\u22E0", "\\npreceq", true);
defineSymbol(symbols_math, ams, rel, "\u22E8", "\\precnsim", true);
defineSymbol(symbols_math, ams, rel, "\u2AB9", "\\precnapprox", true);
defineSymbol(symbols_math, ams, rel, "\u2241", "\\nsim", true);
defineSymbol(symbols_math, ams, rel, "\uE006", "\\@nshortmid");
defineSymbol(symbols_math, ams, rel, "\u2224", "\\nmid", true);
defineSymbol(symbols_math, ams, rel, "\u22AC", "\\nvdash", true);
defineSymbol(symbols_math, ams, rel, "\u22AD", "\\nvDash", true);
defineSymbol(symbols_math, ams, rel, "\u22EA", "\\ntriangleleft");
defineSymbol(symbols_math, ams, rel, "\u22EC", "\\ntrianglelefteq", true);
defineSymbol(symbols_math, ams, rel, "\u228A", "\\subsetneq", true);
defineSymbol(symbols_math, ams, rel, "\uE01A", "\\@varsubsetneq");
defineSymbol(symbols_math, ams, rel, "\u2ACB", "\\subsetneqq", true);
defineSymbol(symbols_math, ams, rel, "\uE017", "\\@varsubsetneqq");
defineSymbol(symbols_math, ams, rel, "\u226F", "\\ngtr", true);
defineSymbol(symbols_math, ams, rel, "\uE00F", "\\@ngeqslant");
defineSymbol(symbols_math, ams, rel, "\uE00E", "\\@ngeqq");
defineSymbol(symbols_math, ams, rel, "\u2A88", "\\gneq", true);
defineSymbol(symbols_math, ams, rel, "\u2269", "\\gneqq", true);
defineSymbol(symbols_math, ams, rel, "\uE00D", "\\@gvertneqq");
defineSymbol(symbols_math, ams, rel, "\u22E7", "\\gnsim", true);
defineSymbol(symbols_math, ams, rel, "\u2A8A", "\\gnapprox", true);
defineSymbol(symbols_math, ams, rel, "\u2281", "\\nsucc", true); // unicode-math maps \u22e1 to \nsucccurlyeq. We'll use the AMS synonym.
defineSymbol(symbols_math, ams, rel, "\u22E1", "\\nsucceq", true);
defineSymbol(symbols_math, ams, rel, "\u22E9", "\\succnsim", true);
defineSymbol(symbols_math, ams, rel, "\u2ABA", "\\succnapprox", true); // unicode-math maps \u2246 to \simneqq. We'll use the AMS synonym.
defineSymbol(symbols_math, ams, rel, "\u2246", "\\ncong", true);
defineSymbol(symbols_math, ams, rel, "\uE007", "\\@nshortparallel");
defineSymbol(symbols_math, ams, rel, "\u2226", "\\nparallel", true);
defineSymbol(symbols_math, ams, rel, "\u22AF", "\\nVDash", true);
defineSymbol(symbols_math, ams, rel, "\u22EB", "\\ntriangleright");
defineSymbol(symbols_math, ams, rel, "\u22ED", "\\ntrianglerighteq", true);
defineSymbol(symbols_math, ams, rel, "\uE018", "\\@nsupseteqq");
defineSymbol(symbols_math, ams, rel, "\u228B", "\\supsetneq", true);
defineSymbol(symbols_math, ams, rel, "\uE01B", "\\@varsupsetneq");
defineSymbol(symbols_math, ams, rel, "\u2ACC", "\\supsetneqq", true);
defineSymbol(symbols_math, ams, rel, "\uE019", "\\@varsupsetneqq");
defineSymbol(symbols_math, ams, rel, "\u22AE", "\\nVdash", true);
defineSymbol(symbols_math, ams, rel, "\u2AB5", "\\precneqq", true);
defineSymbol(symbols_math, ams, rel, "\u2AB6", "\\succneqq", true);
defineSymbol(symbols_math, ams, rel, "\uE016", "\\@nsubseteqq");
defineSymbol(symbols_math, ams, bin, "\u22B4", "\\unlhd");
defineSymbol(symbols_math, ams, bin, "\u22B5", "\\unrhd"); // AMS Negated Arrows
defineSymbol(symbols_math, ams, rel, "\u219A", "\\nleftarrow", true);
defineSymbol(symbols_math, ams, rel, "\u219B", "\\nrightarrow", true);
defineSymbol(symbols_math, ams, rel, "\u21CD", "\\nLeftarrow", true);
defineSymbol(symbols_math, ams, rel, "\u21CF", "\\nRightarrow", true);
defineSymbol(symbols_math, ams, rel, "\u21AE", "\\nleftrightarrow", true);
defineSymbol(symbols_math, ams, rel, "\u21CE", "\\nLeftrightarrow", true); // AMS Misc
defineSymbol(symbols_math, ams, rel, "\u25B3", "\\vartriangle");
defineSymbol(symbols_math, ams, symbols_textord, "\u210F", "\\hslash");
defineSymbol(symbols_math, ams, symbols_textord, "\u25BD", "\\triangledown");
defineSymbol(symbols_math, ams, symbols_textord, "\u25CA", "\\lozenge");
defineSymbol(symbols_math, ams, symbols_textord, "\u24C8", "\\circledS");
defineSymbol(symbols_math, ams, symbols_textord, "\xAE", "\\circledR");
defineSymbol(symbols_text, ams, symbols_textord, "\xAE", "\\circledR");
defineSymbol(symbols_math, ams, symbols_textord, "\u2221", "\\measuredangle", true);
defineSymbol(symbols_math, ams, symbols_textord, "\u2204", "\\nexists");
defineSymbol(symbols_math, ams, symbols_textord, "\u2127", "\\mho");
defineSymbol(symbols_math, ams, symbols_textord, "\u2132", "\\Finv", true);
defineSymbol(symbols_math, ams, symbols_textord, "\u2141", "\\Game", true);
defineSymbol(symbols_math, ams, symbols_textord, "\u2035", "\\backprime");
defineSymbol(symbols_math, ams, symbols_textord, "\u25B2", "\\blacktriangle");
defineSymbol(symbols_math, ams, symbols_textord, "\u25BC", "\\blacktriangledown");
defineSymbol(symbols_math, ams, symbols_textord, "\u25A0", "\\blacksquare");
defineSymbol(symbols_math, ams, symbols_textord, "\u29EB", "\\blacklozenge");
defineSymbol(symbols_math, ams, symbols_textord, "\u2605", "\\bigstar");
defineSymbol(symbols_math, ams, symbols_textord, "\u2222", "\\sphericalangle", true);
defineSymbol(symbols_math, ams, symbols_textord, "\u2201", "\\complement", true); // unicode-math maps U+F0 (ð) to \matheth. We map to AMS function \eth
defineSymbol(symbols_math, ams, symbols_textord, "\xF0", "\\eth", true);
defineSymbol(symbols_math, ams, symbols_textord, "\u2571", "\\diagup");
defineSymbol(symbols_math, ams, symbols_textord, "\u2572", "\\diagdown");
defineSymbol(symbols_math, ams, symbols_textord, "\u25A1", "\\square");
defineSymbol(symbols_math, ams, symbols_textord, "\u25A1", "\\Box");
defineSymbol(symbols_math, ams, symbols_textord, "\u25CA", "\\Diamond"); // unicode-math maps U+A5 to \mathyen. We map to AMS function \yen
defineSymbol(symbols_math, ams, symbols_textord, "\xA5", "\\yen", true);
defineSymbol(symbols_text, ams, symbols_textord, "\xA5", "\\yen", true);
defineSymbol(symbols_math, ams, symbols_textord, "\u2713", "\\checkmark", true);
defineSymbol(symbols_text, ams, symbols_textord, "\u2713", "\\checkmark"); // AMS Hebrew
defineSymbol(symbols_math, ams, symbols_textord, "\u2136", "\\beth", true);
defineSymbol(symbols_math, ams, symbols_textord, "\u2138", "\\daleth", true);
defineSymbol(symbols_math, ams, symbols_textord, "\u2137", "\\gimel", true); // AMS Greek
defineSymbol(symbols_math, ams, symbols_textord, "\u03DD", "\\digamma", true);
defineSymbol(symbols_math, ams, symbols_textord, "\u03F0", "\\varkappa"); // AMS Delimiters
defineSymbol(symbols_math, ams, symbols_open, "\u250C", "\\ulcorner", true);
defineSymbol(symbols_math, ams, symbols_close, "\u2510", "\\urcorner", true);
defineSymbol(symbols_math, ams, symbols_open, "\u2514", "\\llcorner", true);
defineSymbol(symbols_math, ams, symbols_close, "\u2518", "\\lrcorner", true); // AMS Binary Relations
defineSymbol(symbols_math, ams, rel, "\u2266", "\\leqq", true);
defineSymbol(symbols_math, ams, rel, "\u2A7D", "\\leqslant", true);
defineSymbol(symbols_math, ams, rel, "\u2A95", "\\eqslantless", true);
defineSymbol(symbols_math, ams, rel, "\u2272", "\\lesssim", true);
defineSymbol(symbols_math, ams, rel, "\u2A85", "\\lessapprox", true);
defineSymbol(symbols_math, ams, rel, "\u224A", "\\approxeq", true);
defineSymbol(symbols_math, ams, bin, "\u22D6", "\\lessdot");
defineSymbol(symbols_math, ams, rel, "\u22D8", "\\lll", true);
defineSymbol(symbols_math, ams, rel, "\u2276", "\\lessgtr", true);
defineSymbol(symbols_math, ams, rel, "\u22DA", "\\lesseqgtr", true);
defineSymbol(symbols_math, ams, rel, "\u2A8B", "\\lesseqqgtr", true);
defineSymbol(symbols_math, ams, rel, "\u2251", "\\doteqdot");
defineSymbol(symbols_math, ams, rel, "\u2253", "\\risingdotseq", true);
defineSymbol(symbols_math, ams, rel, "\u2252", "\\fallingdotseq", true);
defineSymbol(symbols_math, ams, rel, "\u223D", "\\backsim", true);
defineSymbol(symbols_math, ams, rel, "\u22CD", "\\backsimeq", true);
defineSymbol(symbols_math, ams, rel, "\u2AC5", "\\subseteqq", true);
defineSymbol(symbols_math, ams, rel, "\u22D0", "\\Subset", true);
defineSymbol(symbols_math, ams, rel, "\u228F", "\\sqsubset", true);
defineSymbol(symbols_math, ams, rel, "\u227C", "\\preccurlyeq", true);
defineSymbol(symbols_math, ams, rel, "\u22DE", "\\curlyeqprec", true);
defineSymbol(symbols_math, ams, rel, "\u227E", "\\precsim", true);
defineSymbol(symbols_math, ams, rel, "\u2AB7", "\\precapprox", true);
defineSymbol(symbols_math, ams, rel, "\u22B2", "\\vartriangleleft");
defineSymbol(symbols_math, ams, rel, "\u22B4", "\\trianglelefteq");
defineSymbol(symbols_math, ams, rel, "\u22A8", "\\vDash", true);
defineSymbol(symbols_math, ams, rel, "\u22AA", "\\Vvdash", true);
defineSymbol(symbols_math, ams, rel, "\u2323", "\\smallsmile");
defineSymbol(symbols_math, ams, rel, "\u2322", "\\smallfrown");
defineSymbol(symbols_math, ams, rel, "\u224F", "\\bumpeq", true);
defineSymbol(symbols_math, ams, rel, "\u224E", "\\Bumpeq", true);
defineSymbol(symbols_math, ams, rel, "\u2267", "\\geqq", true);
defineSymbol(symbols_math, ams, rel, "\u2A7E", "\\geqslant", true);
defineSymbol(symbols_math, ams, rel, "\u2A96", "\\eqslantgtr", true);
defineSymbol(symbols_math, ams, rel, "\u2273", "\\gtrsim", true);
defineSymbol(symbols_math, ams, rel, "\u2A86", "\\gtrapprox", true);
defineSymbol(symbols_math, ams, bin, "\u22D7", "\\gtrdot");
defineSymbol(symbols_math, ams, rel, "\u22D9", "\\ggg", true);
defineSymbol(symbols_math, ams, rel, "\u2277", "\\gtrless", true);
defineSymbol(symbols_math, ams, rel, "\u22DB", "\\gtreqless", true);
defineSymbol(symbols_math, ams, rel, "\u2A8C", "\\gtreqqless", true);
defineSymbol(symbols_math, ams, rel, "\u2256", "\\eqcirc", true);
defineSymbol(symbols_math, ams, rel, "\u2257", "\\circeq", true);
defineSymbol(symbols_math, ams, rel, "\u225C", "\\triangleq", true);
defineSymbol(symbols_math, ams, rel, "\u223C", "\\thicksim");
defineSymbol(symbols_math, ams, rel, "\u2248", "\\thickapprox");
defineSymbol(symbols_math, ams, rel, "\u2AC6", "\\supseteqq", true);
defineSymbol(symbols_math, ams, rel, "\u22D1", "\\Supset", true);
defineSymbol(symbols_math, ams, rel, "\u2290", "\\sqsupset", true);
defineSymbol(symbols_math, ams, rel, "\u227D", "\\succcurlyeq", true);
defineSymbol(symbols_math, ams, rel, "\u22DF", "\\curlyeqsucc", true);
defineSymbol(symbols_math, ams, rel, "\u227F", "\\succsim", true);
defineSymbol(symbols_math, ams, rel, "\u2AB8", "\\succapprox", true);
defineSymbol(symbols_math, ams, rel, "\u22B3", "\\vartriangleright");
defineSymbol(symbols_math, ams, rel, "\u22B5", "\\trianglerighteq");
defineSymbol(symbols_math, ams, rel, "\u22A9", "\\Vdash", true);
defineSymbol(symbols_math, ams, rel, "\u2223", "\\shortmid");
defineSymbol(symbols_math, ams, rel, "\u2225", "\\shortparallel");
defineSymbol(symbols_math, ams, rel, "\u226C", "\\between", true);
defineSymbol(symbols_math, ams, rel, "\u22D4", "\\pitchfork", true);
defineSymbol(symbols_math, ams, rel, "\u221D", "\\varpropto");
defineSymbol(symbols_math, ams, rel, "\u25C0", "\\blacktriangleleft"); // unicode-math says that \therefore is a mathord atom.
// We kept the amssymb atom type, which is rel.
defineSymbol(symbols_math, ams, rel, "\u2234", "\\therefore", true);
defineSymbol(symbols_math, ams, rel, "\u220D", "\\backepsilon");
defineSymbol(symbols_math, ams, rel, "\u25B6", "\\blacktriangleright"); // unicode-math says that \because is a mathord atom.
// We kept the amssymb atom type, which is rel.
defineSymbol(symbols_math, ams, rel, "\u2235", "\\because", true);
defineSymbol(symbols_math, ams, rel, "\u22D8", "\\llless");
defineSymbol(symbols_math, ams, rel, "\u22D9", "\\gggtr");
defineSymbol(symbols_math, ams, bin, "\u22B2", "\\lhd");
defineSymbol(symbols_math, ams, bin, "\u22B3", "\\rhd");
defineSymbol(symbols_math, ams, rel, "\u2242", "\\eqsim", true);
defineSymbol(symbols_math, main, rel, "\u22C8", "\\Join");
defineSymbol(symbols_math, ams, rel, "\u2251", "\\Doteq", true); // AMS Binary Operators
defineSymbol(symbols_math, ams, bin, "\u2214", "\\dotplus", true);
defineSymbol(symbols_math, ams, bin, "\u2216", "\\smallsetminus");
defineSymbol(symbols_math, ams, bin, "\u22D2", "\\Cap", true);
defineSymbol(symbols_math, ams, bin, "\u22D3", "\\Cup", true);
defineSymbol(symbols_math, ams, bin, "\u2A5E", "\\doublebarwedge", true);
defineSymbol(symbols_math, ams, bin, "\u229F", "\\boxminus", true);
defineSymbol(symbols_math, ams, bin, "\u229E", "\\boxplus", true);
defineSymbol(symbols_math, ams, bin, "\u22C7", "\\divideontimes", true);
defineSymbol(symbols_math, ams, bin, "\u22C9", "\\ltimes", true);
defineSymbol(symbols_math, ams, bin, "\u22CA", "\\rtimes", true);
defineSymbol(symbols_math, ams, bin, "\u22CB", "\\leftthreetimes", true);
defineSymbol(symbols_math, ams, bin, "\u22CC", "\\rightthreetimes", true);
defineSymbol(symbols_math, ams, bin, "\u22CF", "\\curlywedge", true);
defineSymbol(symbols_math, ams, bin, "\u22CE", "\\curlyvee", true);
defineSymbol(symbols_math, ams, bin, "\u229D", "\\circleddash", true);
defineSymbol(symbols_math, ams, bin, "\u229B", "\\circledast", true);
defineSymbol(symbols_math, ams, bin, "\u22C5", "\\centerdot");
defineSymbol(symbols_math, ams, bin, "\u22BA", "\\intercal", true);
defineSymbol(symbols_math, ams, bin, "\u22D2", "\\doublecap");
defineSymbol(symbols_math, ams, bin, "\u22D3", "\\doublecup");
defineSymbol(symbols_math, ams, bin, "\u22A0", "\\boxtimes", true); // AMS Arrows
// Note: unicode-math maps \u21e2 to their own function \rightdasharrow.
// We'll map it to AMS function \dashrightarrow. It produces the same atom.
defineSymbol(symbols_math, ams, rel, "\u21E2", "\\dashrightarrow", true); // unicode-math maps \u21e0 to \leftdasharrow. We'll use the AMS synonym.
defineSymbol(symbols_math, ams, rel, "\u21E0", "\\dashleftarrow", true);
defineSymbol(symbols_math, ams, rel, "\u21C7", "\\leftleftarrows", true);
defineSymbol(symbols_math, ams, rel, "\u21C6", "\\leftrightarrows", true);
defineSymbol(symbols_math, ams, rel, "\u21DA", "\\Lleftarrow", true);
defineSymbol(symbols_math, ams, rel, "\u219E", "\\twoheadleftarrow", true);
defineSymbol(symbols_math, ams, rel, "\u21A2", "\\leftarrowtail", true);
defineSymbol(symbols_math, ams, rel, "\u21AB", "\\looparrowleft", true);
defineSymbol(symbols_math, ams, rel, "\u21CB", "\\leftrightharpoons", true);
defineSymbol(symbols_math, ams, rel, "\u21B6", "\\curvearrowleft", true); // unicode-math maps \u21ba to \acwopencirclearrow. We'll use the AMS synonym.
defineSymbol(symbols_math, ams, rel, "\u21BA", "\\circlearrowleft", true);
defineSymbol(symbols_math, ams, rel, "\u21B0", "\\Lsh", true);
defineSymbol(symbols_math, ams, rel, "\u21C8", "\\upuparrows", true);
defineSymbol(symbols_math, ams, rel, "\u21BF", "\\upharpoonleft", true);
defineSymbol(symbols_math, ams, rel, "\u21C3", "\\downharpoonleft", true);
defineSymbol(symbols_math, ams, rel, "\u22B8", "\\multimap", true);
defineSymbol(symbols_math, ams, rel, "\u21AD", "\\leftrightsquigarrow", true);
defineSymbol(symbols_math, ams, rel, "\u21C9", "\\rightrightarrows", true);
defineSymbol(symbols_math, ams, rel, "\u21C4", "\\rightleftarrows", true);
defineSymbol(symbols_math, ams, rel, "\u21A0", "\\twoheadrightarrow", true);
defineSymbol(symbols_math, ams, rel, "\u21A3", "\\rightarrowtail", true);
defineSymbol(symbols_math, ams, rel, "\u21AC", "\\looparrowright", true);
defineSymbol(symbols_math, ams, rel, "\u21B7", "\\curvearrowright", true); // unicode-math maps \u21bb to \cwopencirclearrow. We'll use the AMS synonym.
defineSymbol(symbols_math, ams, rel, "\u21BB", "\\circlearrowright", true);
defineSymbol(symbols_math, ams, rel, "\u21B1", "\\Rsh", true);
defineSymbol(symbols_math, ams, rel, "\u21CA", "\\downdownarrows", true);
defineSymbol(symbols_math, ams, rel, "\u21BE", "\\upharpoonright", true);
defineSymbol(symbols_math, ams, rel, "\u21C2", "\\downharpoonright", true);
defineSymbol(symbols_math, ams, rel, "\u21DD", "\\rightsquigarrow", true);
defineSymbol(symbols_math, ams, rel, "\u21DD", "\\leadsto");
defineSymbol(symbols_math, ams, rel, "\u21DB", "\\Rrightarrow", true);
defineSymbol(symbols_math, ams, rel, "\u21BE", "\\restriction");
defineSymbol(symbols_math, main, symbols_textord, "\u2018", "`");
defineSymbol(symbols_math, main, symbols_textord, "$", "\\$");
defineSymbol(symbols_text, main, symbols_textord, "$", "\\$");
defineSymbol(symbols_text, main, symbols_textord, "$", "\\textdollar");
defineSymbol(symbols_math, main, symbols_textord, "%", "\\%");
defineSymbol(symbols_text, main, symbols_textord, "%", "\\%");
defineSymbol(symbols_math, main, symbols_textord, "_", "\\_");
defineSymbol(symbols_text, main, symbols_textord, "_", "\\_");
defineSymbol(symbols_text, main, symbols_textord, "_", "\\textunderscore");
defineSymbol(symbols_math, main, symbols_textord, "\u2220", "\\angle", true);
defineSymbol(symbols_math, main, symbols_textord, "\u221E", "\\infty", true);
defineSymbol(symbols_math, main, symbols_textord, "\u2032", "\\prime");
defineSymbol(symbols_math, main, symbols_textord, "\u25B3", "\\triangle");
defineSymbol(symbols_math, main, symbols_textord, "\u0393", "\\Gamma", true);
defineSymbol(symbols_math, main, symbols_textord, "\u0394", "\\Delta", true);
defineSymbol(symbols_math, main, symbols_textord, "\u0398", "\\Theta", true);
defineSymbol(symbols_math, main, symbols_textord, "\u039B", "\\Lambda", true);
defineSymbol(symbols_math, main, symbols_textord, "\u039E", "\\Xi", true);
defineSymbol(symbols_math, main, symbols_textord, "\u03A0", "\\Pi", true);
defineSymbol(symbols_math, main, symbols_textord, "\u03A3", "\\Sigma", true);
defineSymbol(symbols_math, main, symbols_textord, "\u03A5", "\\Upsilon", true);
defineSymbol(symbols_math, main, symbols_textord, "\u03A6", "\\Phi", true);
defineSymbol(symbols_math, main, symbols_textord, "\u03A8", "\\Psi", true);
defineSymbol(symbols_math, main, symbols_textord, "\u03A9", "\\Omega", true);
defineSymbol(symbols_math, main, symbols_textord, "A", "\u0391");
defineSymbol(symbols_math, main, symbols_textord, "B", "\u0392");
defineSymbol(symbols_math, main, symbols_textord, "E", "\u0395");
defineSymbol(symbols_math, main, symbols_textord, "Z", "\u0396");
defineSymbol(symbols_math, main, symbols_textord, "H", "\u0397");
defineSymbol(symbols_math, main, symbols_textord, "I", "\u0399");
defineSymbol(symbols_math, main, symbols_textord, "K", "\u039A");
defineSymbol(symbols_math, main, symbols_textord, "M", "\u039C");
defineSymbol(symbols_math, main, symbols_textord, "N", "\u039D");
defineSymbol(symbols_math, main, symbols_textord, "O", "\u039F");
defineSymbol(symbols_math, main, symbols_textord, "P", "\u03A1");
defineSymbol(symbols_math, main, symbols_textord, "T", "\u03A4");
defineSymbol(symbols_math, main, symbols_textord, "X", "\u03A7");
defineSymbol(symbols_math, main, symbols_textord, "\xAC", "\\neg", true);
defineSymbol(symbols_math, main, symbols_textord, "\xAC", "\\lnot");
defineSymbol(symbols_math, main, symbols_textord, "\u22A4", "\\top");
defineSymbol(symbols_math, main, symbols_textord, "\u22A5", "\\bot");
defineSymbol(symbols_math, main, symbols_textord, "\u2205", "\\emptyset");
defineSymbol(symbols_math, ams, symbols_textord, "\u2205", "\\varnothing");
defineSymbol(symbols_math, main, mathord, "\u03B1", "\\alpha", true);
defineSymbol(symbols_math, main, mathord, "\u03B2", "\\beta", true);
defineSymbol(symbols_math, main, mathord, "\u03B3", "\\gamma", true);
defineSymbol(symbols_math, main, mathord, "\u03B4", "\\delta", true);
defineSymbol(symbols_math, main, mathord, "\u03F5", "\\epsilon", true);
defineSymbol(symbols_math, main, mathord, "\u03B6", "\\zeta", true);
defineSymbol(symbols_math, main, mathord, "\u03B7", "\\eta", true);
defineSymbol(symbols_math, main, mathord, "\u03B8", "\\theta", true);
defineSymbol(symbols_math, main, mathord, "\u03B9", "\\iota", true);
defineSymbol(symbols_math, main, mathord, "\u03BA", "\\kappa", true);
defineSymbol(symbols_math, main, mathord, "\u03BB", "\\lambda", true);
defineSymbol(symbols_math, main, mathord, "\u03BC", "\\mu", true);
defineSymbol(symbols_math, main, mathord, "\u03BD", "\\nu", true);
defineSymbol(symbols_math, main, mathord, "\u03BE", "\\xi", true);
defineSymbol(symbols_math, main, mathord, "\u03BF", "\\omicron", true);
defineSymbol(symbols_math, main, mathord, "\u03C0", "\\pi", true);
defineSymbol(symbols_math, main, mathord, "\u03C1", "\\rho", true);
defineSymbol(symbols_math, main, mathord, "\u03C3", "\\sigma", true);
defineSymbol(symbols_math, main, mathord, "\u03C4", "\\tau", true);
defineSymbol(symbols_math, main, mathord, "\u03C5", "\\upsilon", true);
defineSymbol(symbols_math, main, mathord, "\u03D5", "\\phi", true);
defineSymbol(symbols_math, main, mathord, "\u03C7", "\\chi", true);
defineSymbol(symbols_math, main, mathord, "\u03C8", "\\psi", true);
defineSymbol(symbols_math, main, mathord, "\u03C9", "\\omega", true);
defineSymbol(symbols_math, main, mathord, "\u03B5", "\\varepsilon", true);
defineSymbol(symbols_math, main, mathord, "\u03D1", "\\vartheta", true);
defineSymbol(symbols_math, main, mathord, "\u03D6", "\\varpi", true);
defineSymbol(symbols_math, main, mathord, "\u03F1", "\\varrho", true);
defineSymbol(symbols_math, main, mathord, "\u03C2", "\\varsigma", true);
defineSymbol(symbols_math, main, mathord, "\u03C6", "\\varphi", true);
defineSymbol(symbols_math, main, bin, "\u2217", "*");
defineSymbol(symbols_math, main, bin, "+", "+");
defineSymbol(symbols_math, main, bin, "\u2212", "-");
defineSymbol(symbols_math, main, bin, "\u22C5", "\\cdot", true);
defineSymbol(symbols_math, main, bin, "\u2218", "\\circ");
defineSymbol(symbols_math, main, bin, "\xF7", "\\div", true);
defineSymbol(symbols_math, main, bin, "\xB1", "\\pm", true);
defineSymbol(symbols_math, main, bin, "\xD7", "\\times", true);
defineSymbol(symbols_math, main, bin, "\u2229", "\\cap", true);
defineSymbol(symbols_math, main, bin, "\u222A", "\\cup", true);
defineSymbol(symbols_math, main, bin, "\u2216", "\\setminus");
defineSymbol(symbols_math, main, bin, "\u2227", "\\land");
defineSymbol(symbols_math, main, bin, "\u2228", "\\lor");
defineSymbol(symbols_math, main, bin, "\u2227", "\\wedge", true);
defineSymbol(symbols_math, main, bin, "\u2228", "\\vee", true);
defineSymbol(symbols_math, main, symbols_textord, "\u221A", "\\surd");
defineSymbol(symbols_math, main, symbols_open, "(", "(");
defineSymbol(symbols_math, main, symbols_open, "[", "[");
defineSymbol(symbols_math, main, symbols_open, "\u27E8", "\\langle", true);
defineSymbol(symbols_math, main, symbols_open, "\u2223", "\\lvert");
defineSymbol(symbols_math, main, symbols_open, "\u2225", "\\lVert");
defineSymbol(symbols_math, main, symbols_close, ")", ")");
defineSymbol(symbols_math, main, symbols_close, "]", "]");
defineSymbol(symbols_math, main, symbols_close, "?", "?");
defineSymbol(symbols_math, main, symbols_close, "!", "!");
defineSymbol(symbols_math, main, symbols_close, "\u27E9", "\\rangle", true);
defineSymbol(symbols_math, main, symbols_close, "\u2223", "\\rvert");
defineSymbol(symbols_math, main, symbols_close, "\u2225", "\\rVert");
defineSymbol(symbols_math, main, rel, "=", "=");
defineSymbol(symbols_math, main, rel, "<", "<");
defineSymbol(symbols_math, main, rel, ">", ">");
defineSymbol(symbols_math, main, rel, ":", ":");
defineSymbol(symbols_math, main, rel, "\u2248", "\\approx", true);
defineSymbol(symbols_math, main, rel, "\u2245", "\\cong", true);
defineSymbol(symbols_math, main, rel, "\u2265", "\\ge");
defineSymbol(symbols_math, main, rel, "\u2265", "\\geq", true);
defineSymbol(symbols_math, main, rel, "\u2190", "\\gets");
defineSymbol(symbols_math, main, rel, ">", "\\gt");
defineSymbol(symbols_math, main, rel, "\u2208", "\\in", true);
defineSymbol(symbols_math, main, rel, "\uE020", "\\@not");
defineSymbol(symbols_math, main, rel, "\u2282", "\\subset", true);
defineSymbol(symbols_math, main, rel, "\u2283", "\\supset", true);
defineSymbol(symbols_math, main, rel, "\u2286", "\\subseteq", true);
defineSymbol(symbols_math, main, rel, "\u2287", "\\supseteq", true);
defineSymbol(symbols_math, ams, rel, "\u2288", "\\nsubseteq", true);
defineSymbol(symbols_math, ams, rel, "\u2289", "\\nsupseteq", true);
defineSymbol(symbols_math, main, rel, "\u22A8", "\\models");
defineSymbol(symbols_math, main, rel, "\u2190", "\\leftarrow", true);
defineSymbol(symbols_math, main, rel, "\u2264", "\\le");
defineSymbol(symbols_math, main, rel, "\u2264", "\\leq", true);
defineSymbol(symbols_math, main, rel, "<", "\\lt");
defineSymbol(symbols_math, main, rel, "\u2192", "\\rightarrow", true);
defineSymbol(symbols_math, main, rel, "\u2192", "\\to");
defineSymbol(symbols_math, ams, rel, "\u2271", "\\ngeq", true);
defineSymbol(symbols_math, ams, rel, "\u2270", "\\nleq", true);
defineSymbol(symbols_math, main, symbols_spacing, "\xA0", "\\ ");
defineSymbol(symbols_math, main, symbols_spacing, "\xA0", "~");
defineSymbol(symbols_math, main, symbols_spacing, "\xA0", "\\space"); // Ref: LaTeX Source 2e: \DeclareRobustCommand{\nobreakspace}{%
defineSymbol(symbols_math, main, symbols_spacing, "\xA0", "\\nobreakspace");
defineSymbol(symbols_text, main, symbols_spacing, "\xA0", "\\ ");
defineSymbol(symbols_text, main, symbols_spacing, "\xA0", "~");
defineSymbol(symbols_text, main, symbols_spacing, "\xA0", "\\space");
defineSymbol(symbols_text, main, symbols_spacing, "\xA0", "\\nobreakspace");
defineSymbol(symbols_math, main, symbols_spacing, null, "\\nobreak");
defineSymbol(symbols_math, main, symbols_spacing, null, "\\allowbreak");
defineSymbol(symbols_math, main, punct, ",", ",");
defineSymbol(symbols_math, main, punct, ";", ";");
defineSymbol(symbols_math, ams, bin, "\u22BC", "\\barwedge", true);
defineSymbol(symbols_math, ams, bin, "\u22BB", "\\veebar", true);
defineSymbol(symbols_math, main, bin, "\u2299", "\\odot", true);
defineSymbol(symbols_math, main, bin, "\u2295", "\\oplus", true);
defineSymbol(symbols_math, main, bin, "\u2297", "\\otimes", true);
defineSymbol(symbols_math, main, symbols_textord, "\u2202", "\\partial", true);
defineSymbol(symbols_math, main, bin, "\u2298", "\\oslash", true);
defineSymbol(symbols_math, ams, bin, "\u229A", "\\circledcirc", true);
defineSymbol(symbols_math, ams, bin, "\u22A1", "\\boxdot", true);
defineSymbol(symbols_math, main, bin, "\u25B3", "\\bigtriangleup");
defineSymbol(symbols_math, main, bin, "\u25BD", "\\bigtriangledown");
defineSymbol(symbols_math, main, bin, "\u2020", "\\dagger");
defineSymbol(symbols_math, main, bin, "\u22C4", "\\diamond");
defineSymbol(symbols_math, main, bin, "\u22C6", "\\star");
defineSymbol(symbols_math, main, bin, "\u25C3", "\\triangleleft");
defineSymbol(symbols_math, main, bin, "\u25B9", "\\triangleright");
defineSymbol(symbols_math, main, symbols_open, "{", "\\{");
defineSymbol(symbols_text, main, symbols_textord, "{", "\\{");
defineSymbol(symbols_text, main, symbols_textord, "{", "\\textbraceleft");
defineSymbol(symbols_math, main, symbols_close, "}", "\\}");
defineSymbol(symbols_text, main, symbols_textord, "}", "\\}");
defineSymbol(symbols_text, main, symbols_textord, "}", "\\textbraceright");
defineSymbol(symbols_math, main, symbols_open, "{", "\\lbrace");
defineSymbol(symbols_math, main, symbols_close, "}", "\\rbrace");
defineSymbol(symbols_math, main, symbols_open, "[", "\\lbrack");
defineSymbol(symbols_text, main, symbols_textord, "[", "\\lbrack");
defineSymbol(symbols_math, main, symbols_close, "]", "\\rbrack");
defineSymbol(symbols_text, main, symbols_textord, "]", "\\rbrack");
defineSymbol(symbols_math, main, symbols_open, "(", "\\lparen");
defineSymbol(symbols_math, main, symbols_close, ")", "\\rparen");
defineSymbol(symbols_text, main, symbols_textord, "<", "\\textless"); // in T1 fontenc
defineSymbol(symbols_text, main, symbols_textord, ">", "\\textgreater"); // in T1 fontenc
defineSymbol(symbols_math, main, symbols_open, "\u230A", "\\lfloor", true);
defineSymbol(symbols_math, main, symbols_close, "\u230B", "\\rfloor", true);
defineSymbol(symbols_math, main, symbols_open, "\u2308", "\\lceil", true);
defineSymbol(symbols_math, main, symbols_close, "\u2309", "\\rceil", true);
defineSymbol(symbols_math, main, symbols_textord, "\\", "\\backslash");
defineSymbol(symbols_math, main, symbols_textord, "\u2223", "|");
defineSymbol(symbols_math, main, symbols_textord, "\u2223", "\\vert");
defineSymbol(symbols_text, main, symbols_textord, "|", "\\textbar"); // in T1 fontenc
defineSymbol(symbols_math, main, symbols_textord, "\u2225", "\\|");
defineSymbol(symbols_math, main, symbols_textord, "\u2225", "\\Vert");
defineSymbol(symbols_text, main, symbols_textord, "\u2225", "\\textbardbl");
defineSymbol(symbols_text, main, symbols_textord, "~", "\\textasciitilde");
defineSymbol(symbols_text, main, symbols_textord, "\\", "\\textbackslash");
defineSymbol(symbols_text, main, symbols_textord, "^", "\\textasciicircum");
defineSymbol(symbols_math, main, rel, "\u2191", "\\uparrow", true);
defineSymbol(symbols_math, main, rel, "\u21D1", "\\Uparrow", true);
defineSymbol(symbols_math, main, rel, "\u2193", "\\downarrow", true);
defineSymbol(symbols_math, main, rel, "\u21D3", "\\Downarrow", true);
defineSymbol(symbols_math, main, rel, "\u2195", "\\updownarrow", true);
defineSymbol(symbols_math, main, rel, "\u21D5", "\\Updownarrow", true);
defineSymbol(symbols_math, main, op, "\u2210", "\\coprod");
defineSymbol(symbols_math, main, op, "\u22C1", "\\bigvee");
defineSymbol(symbols_math, main, op, "\u22C0", "\\bigwedge");
defineSymbol(symbols_math, main, op, "\u2A04", "\\biguplus");
defineSymbol(symbols_math, main, op, "\u22C2", "\\bigcap");
defineSymbol(symbols_math, main, op, "\u22C3", "\\bigcup");
defineSymbol(symbols_math, main, op, "\u222B", "\\int");
defineSymbol(symbols_math, main, op, "\u222B", "\\intop");
defineSymbol(symbols_math, main, op, "\u222C", "\\iint");
defineSymbol(symbols_math, main, op, "\u222D", "\\iiint");
defineSymbol(symbols_math, main, op, "\u220F", "\\prod");
defineSymbol(symbols_math, main, op, "\u2211", "\\sum");
defineSymbol(symbols_math, main, op, "\u2A02", "\\bigotimes");
defineSymbol(symbols_math, main, op, "\u2A01", "\\bigoplus");
defineSymbol(symbols_math, main, op, "\u2A00", "\\bigodot");
defineSymbol(symbols_math, main, op, "\u222E", "\\oint");
defineSymbol(symbols_math, main, op, "\u222F", "\\oiint");
defineSymbol(symbols_math, main, op, "\u2230", "\\oiiint");
defineSymbol(symbols_math, main, op, "\u2A06", "\\bigsqcup");
defineSymbol(symbols_math, main, op, "\u222B", "\\smallint");
defineSymbol(symbols_text, main, symbols_inner, "\u2026", "\\textellipsis");
defineSymbol(symbols_math, main, symbols_inner, "\u2026", "\\mathellipsis");
defineSymbol(symbols_text, main, symbols_inner, "\u2026", "\\ldots", true);
defineSymbol(symbols_math, main, symbols_inner, "\u2026", "\\ldots", true);
defineSymbol(symbols_math, main, symbols_inner, "\u22EF", "\\@cdots", true);
defineSymbol(symbols_math, main, symbols_inner, "\u22F1", "\\ddots", true);
defineSymbol(symbols_math, main, symbols_textord, "\u22EE", "\\varvdots"); // \vdots is a macro
defineSymbol(symbols_math, main, symbols_accent, "\u02CA", "\\acute");
defineSymbol(symbols_math, main, symbols_accent, "\u02CB", "\\grave");
defineSymbol(symbols_math, main, symbols_accent, "\xA8", "\\ddot");
defineSymbol(symbols_math, main, symbols_accent, "~", "\\tilde");
defineSymbol(symbols_math, main, symbols_accent, "\u02C9", "\\bar");
defineSymbol(symbols_math, main, symbols_accent, "\u02D8", "\\breve");
defineSymbol(symbols_math, main, symbols_accent, "\u02C7", "\\check");
defineSymbol(symbols_math, main, symbols_accent, "^", "\\hat");
defineSymbol(symbols_math, main, symbols_accent, "\u20D7", "\\vec");
defineSymbol(symbols_math, main, symbols_accent, "\u02D9", "\\dot");
defineSymbol(symbols_math, main, symbols_accent, "\u02DA", "\\mathring");
defineSymbol(symbols_math, main, mathord, "\u0131", "\\imath", true);
defineSymbol(symbols_math, main, mathord, "\u0237", "\\jmath", true);
defineSymbol(symbols_text, main, symbols_textord, "\u0131", "\\i", true);
defineSymbol(symbols_text, main, symbols_textord, "\u0237", "\\j", true);
defineSymbol(symbols_text, main, symbols_textord, "\xDF", "\\ss", true);
defineSymbol(symbols_text, main, symbols_textord, "\xE6", "\\ae", true);
defineSymbol(symbols_text, main, symbols_textord, "\xE6", "\\ae", true);
defineSymbol(symbols_text, main, symbols_textord, "\u0153", "\\oe", true);
defineSymbol(symbols_text, main, symbols_textord, "\xF8", "\\o", true);
defineSymbol(symbols_text, main, symbols_textord, "\xC6", "\\AE", true);
defineSymbol(symbols_text, main, symbols_textord, "\u0152", "\\OE", true);
defineSymbol(symbols_text, main, symbols_textord, "\xD8", "\\O", true);
defineSymbol(symbols_text, main, symbols_accent, "\u02CA", "\\'"); // acute
defineSymbol(symbols_text, main, symbols_accent, "\u02CB", "\\`"); // grave
defineSymbol(symbols_text, main, symbols_accent, "\u02C6", "\\^"); // circumflex
defineSymbol(symbols_text, main, symbols_accent, "\u02DC", "\\~"); // tilde
defineSymbol(symbols_text, main, symbols_accent, "\u02C9", "\\="); // macron
defineSymbol(symbols_text, main, symbols_accent, "\u02D8", "\\u"); // breve
defineSymbol(symbols_text, main, symbols_accent, "\u02D9", "\\."); // dot above
defineSymbol(symbols_text, main, symbols_accent, "\u02DA", "\\r"); // ring above
defineSymbol(symbols_text, main, symbols_accent, "\u02C7", "\\v"); // caron
defineSymbol(symbols_text, main, symbols_accent, "\xA8", '\\"'); // diaresis
defineSymbol(symbols_text, main, symbols_accent, "\u02DD", "\\H"); // double acute
defineSymbol(symbols_text, main, symbols_accent, "\u25EF", "\\textcircled"); // \bigcirc glyph
// These ligatures are detected and created in Parser.js's `formLigatures`.
var ligatures = {
"--": true,
"---": true,
"``": true,
"''": true
};
defineSymbol(symbols_text, main, symbols_textord, "\u2013", "--");
defineSymbol(symbols_text, main, symbols_textord, "\u2013", "\\textendash");
defineSymbol(symbols_text, main, symbols_textord, "\u2014", "---");
defineSymbol(symbols_text, main, symbols_textord, "\u2014", "\\textemdash");
defineSymbol(symbols_text, main, symbols_textord, "\u2018", "`");
defineSymbol(symbols_text, main, symbols_textord, "\u2018", "\\textquoteleft");
defineSymbol(symbols_text, main, symbols_textord, "\u2019", "'");
defineSymbol(symbols_text, main, symbols_textord, "\u2019", "\\textquoteright");
defineSymbol(symbols_text, main, symbols_textord, "\u201C", "``");
defineSymbol(symbols_text, main, symbols_textord, "\u201C", "\\textquotedblleft");
defineSymbol(symbols_text, main, symbols_textord, "\u201D", "''");
defineSymbol(symbols_text, main, symbols_textord, "\u201D", "\\textquotedblright"); // \degree from gensymb package
defineSymbol(symbols_math, main, symbols_textord, "\xB0", "\\degree", true);
defineSymbol(symbols_text, main, symbols_textord, "\xB0", "\\degree"); // \textdegree from inputenc package
defineSymbol(symbols_text, main, symbols_textord, "\xB0", "\\textdegree", true); // TODO: In LaTeX, \pounds can generate a different character in text and math
// mode, but among our fonts, only Main-Italic defines this character "163".
defineSymbol(symbols_math, main, mathord, "\xA3", "\\pounds");
defineSymbol(symbols_math, main, mathord, "\xA3", "\\mathsterling", true);
defineSymbol(symbols_text, main, mathord, "\xA3", "\\pounds");
defineSymbol(symbols_text, main, mathord, "\xA3", "\\textsterling", true);
defineSymbol(symbols_math, ams, symbols_textord, "\u2720", "\\maltese");
defineSymbol(symbols_text, ams, symbols_textord, "\u2720", "\\maltese");
defineSymbol(symbols_text, main, symbols_spacing, "\xA0", "\\ ");
defineSymbol(symbols_text, main, symbols_spacing, "\xA0", " ");
defineSymbol(symbols_text, main, symbols_spacing, "\xA0", "~"); // There are lots of symbols which are the same, so we add them in afterwards.
// All of these are textords in math mode
var mathTextSymbols = "0123456789/@.\"";
for (var symbols_i = 0; symbols_i < mathTextSymbols.length; symbols_i++) {
var symbols_ch = mathTextSymbols.charAt(symbols_i);
defineSymbol(symbols_math, main, symbols_textord, symbols_ch, symbols_ch);
} // All of these are textords in text mode
var textSymbols = "0123456789!@*()-=+[]<>|\";:?/.,";
for (var src_symbols_i = 0; src_symbols_i < textSymbols.length; src_symbols_i++) {
var _ch = textSymbols.charAt(src_symbols_i);
defineSymbol(symbols_text, main, symbols_textord, _ch, _ch);
} // All of these are textords in text mode, and mathords in math mode
var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for (var symbols_i2 = 0; symbols_i2 < letters.length; symbols_i2++) {
var _ch2 = letters.charAt(symbols_i2);
defineSymbol(symbols_math, main, mathord, _ch2, _ch2);
defineSymbol(symbols_text, main, symbols_textord, _ch2, _ch2);
} // Blackboard bold and script letters in Unicode range
defineSymbol(symbols_math, ams, symbols_textord, "C", "\u2102"); // blackboard bold
defineSymbol(symbols_text, ams, symbols_textord, "C", "\u2102");
defineSymbol(symbols_math, ams, symbols_textord, "H", "\u210D");
defineSymbol(symbols_text, ams, symbols_textord, "H", "\u210D");
defineSymbol(symbols_math, ams, symbols_textord, "N", "\u2115");
defineSymbol(symbols_text, ams, symbols_textord, "N", "\u2115");
defineSymbol(symbols_math, ams, symbols_textord, "P", "\u2119");
defineSymbol(symbols_text, ams, symbols_textord, "P", "\u2119");
defineSymbol(symbols_math, ams, symbols_textord, "Q", "\u211A");
defineSymbol(symbols_text, ams, symbols_textord, "Q", "\u211A");
defineSymbol(symbols_math, ams, symbols_textord, "R", "\u211D");
defineSymbol(symbols_text, ams, symbols_textord, "R", "\u211D");
defineSymbol(symbols_math, ams, symbols_textord, "Z", "\u2124");
defineSymbol(symbols_text, ams, symbols_textord, "Z", "\u2124");
defineSymbol(symbols_math, main, mathord, "h", "\u210E"); // italic h, Planck constant
defineSymbol(symbols_text, main, mathord, "h", "\u210E"); // The next loop loads wide (surrogate pair) characters.
// We support some letters in the Unicode range U+1D400 to U+1D7FF,
// Mathematical Alphanumeric Symbols.
// Some editors do not deal well with wide characters. So don't write the
// string into this file. Instead, create the string from the surrogate pair.
var symbols_wideChar = "";
for (var symbols_i3 = 0; symbols_i3 < letters.length; symbols_i3++) {
var _ch3 = letters.charAt(symbols_i3); // The hex numbers in the next line are a surrogate pair.
// 0xD835 is the high surrogate for all letters in the range we support.
// 0xDC00 is the low surrogate for bold A.
symbols_wideChar = String.fromCharCode(0xD835, 0xDC00 + symbols_i3); // A-Z a-z bold
defineSymbol(symbols_math, main, mathord, _ch3, symbols_wideChar);
defineSymbol(symbols_text, main, symbols_textord, _ch3, symbols_wideChar);
symbols_wideChar = String.fromCharCode(0xD835, 0xDC34 + symbols_i3); // A-Z a-z italic
defineSymbol(symbols_math, main, mathord, _ch3, symbols_wideChar);
defineSymbol(symbols_text, main, symbols_textord, _ch3, symbols_wideChar);
symbols_wideChar = String.fromCharCode(0xD835, 0xDC68 + symbols_i3); // A-Z a-z bold italic
defineSymbol(symbols_math, main, mathord, _ch3, symbols_wideChar);
defineSymbol(symbols_text, main, symbols_textord, _ch3, symbols_wideChar);
symbols_wideChar = String.fromCharCode(0xD835, 0xDD04 + symbols_i3); // A-Z a-z Fractur
defineSymbol(symbols_math, main, mathord, _ch3, symbols_wideChar);
defineSymbol(symbols_text, main, symbols_textord, _ch3, symbols_wideChar);
symbols_wideChar = String.fromCharCode(0xD835, 0xDDA0 + symbols_i3); // A-Z a-z sans-serif
defineSymbol(symbols_math, main, mathord, _ch3, symbols_wideChar);
defineSymbol(symbols_text, main, symbols_textord, _ch3, symbols_wideChar);
symbols_wideChar = String.fromCharCode(0xD835, 0xDDD4 + symbols_i3); // A-Z a-z sans bold
defineSymbol(symbols_math, main, mathord, _ch3, symbols_wideChar);
defineSymbol(symbols_text, main, symbols_textord, _ch3, symbols_wideChar);
symbols_wideChar = String.fromCharCode(0xD835, 0xDE08 + symbols_i3); // A-Z a-z sans italic
defineSymbol(symbols_math, main, mathord, _ch3, symbols_wideChar);
defineSymbol(symbols_text, main, symbols_textord, _ch3, symbols_wideChar);
symbols_wideChar = String.fromCharCode(0xD835, 0xDE70 + symbols_i3); // A-Z a-z monospace
defineSymbol(symbols_math, main, mathord, _ch3, symbols_wideChar);
defineSymbol(symbols_text, main, symbols_textord, _ch3, symbols_wideChar);
if (symbols_i3 < 26) {
// KaTeX fonts have only capital letters for blackboard bold and script.
// See exception for k below.
symbols_wideChar = String.fromCharCode(0xD835, 0xDD38 + symbols_i3); // A-Z double struck
defineSymbol(symbols_math, main, mathord, _ch3, symbols_wideChar);
defineSymbol(symbols_text, main, symbols_textord, _ch3, symbols_wideChar);
symbols_wideChar = String.fromCharCode(0xD835, 0xDC9C + symbols_i3); // A-Z script
defineSymbol(symbols_math, main, mathord, _ch3, symbols_wideChar);
defineSymbol(symbols_text, main, symbols_textord, _ch3, symbols_wideChar);
} // TODO: Add bold script when it is supported by a KaTeX font.
} // "k" is the only double struck lower case letter in the KaTeX fonts.
symbols_wideChar = String.fromCharCode(0xD835, 0xDD5C); // k double struck
defineSymbol(symbols_math, main, mathord, "k", symbols_wideChar);
defineSymbol(symbols_text, main, symbols_textord, "k", symbols_wideChar); // Next, some wide character numerals
for (var symbols_i4 = 0; symbols_i4 < 10; symbols_i4++) {
var _ch4 = symbols_i4.toString();
symbols_wideChar = String.fromCharCode(0xD835, 0xDFCE + symbols_i4); // 0-9 bold
defineSymbol(symbols_math, main, mathord, _ch4, symbols_wideChar);
defineSymbol(symbols_text, main, symbols_textord, _ch4, symbols_wideChar);
symbols_wideChar = String.fromCharCode(0xD835, 0xDFE2 + symbols_i4); // 0-9 sans serif
defineSymbol(symbols_math, main, mathord, _ch4, symbols_wideChar);
defineSymbol(symbols_text, main, symbols_textord, _ch4, symbols_wideChar);
symbols_wideChar = String.fromCharCode(0xD835, 0xDFEC + symbols_i4); // 0-9 bold sans
defineSymbol(symbols_math, main, mathord, _ch4, symbols_wideChar);
defineSymbol(symbols_text, main, symbols_textord, _ch4, symbols_wideChar);
symbols_wideChar = String.fromCharCode(0xD835, 0xDFF6 + symbols_i4); // 0-9 monospace
defineSymbol(symbols_math, main, mathord, _ch4, symbols_wideChar);
defineSymbol(symbols_text, main, symbols_textord, _ch4, symbols_wideChar);
} // We add these Latin-1 letters as symbols for backwards-compatibility,
// but they are not actually in the font, nor are they supported by the
// Unicode accent mechanism, so they fall back to Times font and look ugly.
// TODO(edemaine): Fix this.
var extraLatin = "ÇÐÞçþ";
for (var _i5 = 0; _i5 < extraLatin.length; _i5++) {
var _ch5 = extraLatin.charAt(_i5);
defineSymbol(symbols_math, main, mathord, _ch5, _ch5);
defineSymbol(symbols_text, main, symbols_textord, _ch5, _ch5);
}
defineSymbol(symbols_text, main, symbols_textord, "ð", "ð"); // Unicode versions of existing characters
defineSymbol(symbols_text, main, symbols_textord, "\u2013", "");
defineSymbol(symbols_text, main, symbols_textord, "\u2014", "—");
defineSymbol(symbols_text, main, symbols_textord, "\u2018", "");
defineSymbol(symbols_text, main, symbols_textord, "\u2019", "");
defineSymbol(symbols_text, main, symbols_textord, "\u201C", "“");
defineSymbol(symbols_text, main, symbols_textord, "\u201D", "”");
// CONCATENATED MODULE: ./src/wide-character.js
/**
* This file provides support for Unicode range U+1D400 to U+1D7FF,
* Mathematical Alphanumeric Symbols.
*
* Function wideCharacterFont takes a wide character as input and returns
* the font information necessary to render it properly.
*/
/**
* Data below is from https://www.unicode.org/charts/PDF/U1D400.pdf
* That document sorts characters into groups by font type, say bold or italic.
*
* In the arrays below, each subarray consists three elements:
* * The CSS class of that group when in math mode.
* * The CSS class of that group when in text mode.
* * The font name, so that KaTeX can get font metrics.
*/
var wideLatinLetterData = [["mathbf", "textbf", "Main-Bold"], // A-Z bold upright
["mathbf", "textbf", "Main-Bold"], // a-z bold upright
["mathdefault", "textit", "Math-Italic"], // A-Z italic
["mathdefault", "textit", "Math-Italic"], // a-z italic
["boldsymbol", "boldsymbol", "Main-BoldItalic"], // A-Z bold italic
["boldsymbol", "boldsymbol", "Main-BoldItalic"], // a-z bold italic
// Map fancy A-Z letters to script, not calligraphic.
// This aligns with unicode-math and math fonts (except Cambria Math).
["mathscr", "textscr", "Script-Regular"], // A-Z script
["", "", ""], // a-z script. No font
["", "", ""], // A-Z bold script. No font
["", "", ""], // a-z bold script. No font
["mathfrak", "textfrak", "Fraktur-Regular"], // A-Z Fraktur
["mathfrak", "textfrak", "Fraktur-Regular"], // a-z Fraktur
["mathbb", "textbb", "AMS-Regular"], // A-Z double-struck
["mathbb", "textbb", "AMS-Regular"], // k double-struck
["", "", ""], // A-Z bold Fraktur No font metrics
["", "", ""], // a-z bold Fraktur. No font.
["mathsf", "textsf", "SansSerif-Regular"], // A-Z sans-serif
["mathsf", "textsf", "SansSerif-Regular"], // a-z sans-serif
["mathboldsf", "textboldsf", "SansSerif-Bold"], // A-Z bold sans-serif
["mathboldsf", "textboldsf", "SansSerif-Bold"], // a-z bold sans-serif
["mathitsf", "textitsf", "SansSerif-Italic"], // A-Z italic sans-serif
["mathitsf", "textitsf", "SansSerif-Italic"], // a-z italic sans-serif
["", "", ""], // A-Z bold italic sans. No font
["", "", ""], // a-z bold italic sans. No font
["mathtt", "texttt", "Typewriter-Regular"], // A-Z monospace
["mathtt", "texttt", "Typewriter-Regular"]];
var wideNumeralData = [["mathbf", "textbf", "Main-Bold"], // 0-9 bold
["", "", ""], // 0-9 double-struck. No KaTeX font.
["mathsf", "textsf", "SansSerif-Regular"], // 0-9 sans-serif
["mathboldsf", "textboldsf", "SansSerif-Bold"], // 0-9 bold sans-serif
["mathtt", "texttt", "Typewriter-Regular"]];
var wide_character_wideCharacterFont = function wideCharacterFont(wideChar, mode) {
// IE doesn't support codePointAt(). So work with the surrogate pair.
var H = wideChar.charCodeAt(0); // high surrogate
var L = wideChar.charCodeAt(1); // low surrogate
var codePoint = (H - 0xD800) * 0x400 + (L - 0xDC00) + 0x10000;
var j = mode === "math" ? 0 : 1; // column index for CSS class.
if (0x1D400 <= codePoint && codePoint < 0x1D6A4) {
// wideLatinLetterData contains exactly 26 chars on each row.
// So we can calculate the relevant row. No traverse necessary.
var i = Math.floor((codePoint - 0x1D400) / 26);
return [wideLatinLetterData[i][2], wideLatinLetterData[i][j]];
} else if (0x1D7CE <= codePoint && codePoint <= 0x1D7FF) {
// Numerals, ten per row.
var _i = Math.floor((codePoint - 0x1D7CE) / 10);
return [wideNumeralData[_i][2], wideNumeralData[_i][j]];
} else if (codePoint === 0x1D6A5 || codePoint === 0x1D6A6) {
// dotless i or j
return [wideLatinLetterData[0][2], wideLatinLetterData[0][j]];
} else if (0x1D6A6 < codePoint && codePoint < 0x1D7CE) {
// Greek letters. Not supported, yet.
return ["", ""];
} else {
// We don't support any wide characters outside 1D4001D7FF.
throw new src_ParseError("Unsupported character: " + wideChar);
}
};
// CONCATENATED MODULE: ./src/Options.js
/**
* This file contains information about the options that the Parser carries
* around with it while parsing. Data is held in an `Options` object, and when
* recursing, a new `Options` object can be created with the `.with*` and
* `.reset` functions.
*/
var sizeStyleMap = [// Each element contains [textsize, scriptsize, scriptscriptsize].
// The size mappings are taken from TeX with \normalsize=10pt.
[1, 1, 1], // size1: [5, 5, 5] \tiny
[2, 1, 1], // size2: [6, 5, 5]
[3, 1, 1], // size3: [7, 5, 5] \scriptsize
[4, 2, 1], // size4: [8, 6, 5] \footnotesize
[5, 2, 1], // size5: [9, 6, 5] \small
[6, 3, 1], // size6: [10, 7, 5] \normalsize
[7, 4, 2], // size7: [12, 8, 6] \large
[8, 6, 3], // size8: [14.4, 10, 7] \Large
[9, 7, 6], // size9: [17.28, 12, 10] \LARGE
[10, 8, 7], // size10: [20.74, 14.4, 12] \huge
[11, 10, 9]];
var sizeMultipliers = [// fontMetrics.js:getGlobalMetrics also uses size indexes, so if
// you change size indexes, change that function.
0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.2, 1.44, 1.728, 2.074, 2.488];
var sizeAtStyle = function sizeAtStyle(size, style) {
return style.size < 2 ? size : sizeStyleMap[size - 1][style.size - 1];
}; // In these types, "" (empty string) means "no change".
/**
* This is the main options class. It contains the current style, size, color,
* and font.
*
* Options objects should not be modified. To create a new Options with
* different properties, call a `.having*` method.
*/
var Options_Options =
/*#__PURE__*/
function () {
// A font family applies to a group of fonts (i.e. SansSerif), while a font
// represents a specific font (i.e. SansSerif Bold).
// See: https://tex.stackexchange.com/questions/22350/difference-between-textrm-and-mathrm
/**
* The base size index.
*/
function Options(data) {
this.style = void 0;
this.color = void 0;
this.size = void 0;
this.textSize = void 0;
this.phantom = void 0;
this.font = void 0;
this.fontFamily = void 0;
this.fontWeight = void 0;
this.fontShape = void 0;
this.sizeMultiplier = void 0;
this.maxSize = void 0;
this.minRuleThickness = void 0;
this._fontMetrics = void 0;
this.style = data.style;
this.color = data.color;
this.size = data.size || Options.BASESIZE;
this.textSize = data.textSize || this.size;
this.phantom = !!data.phantom;
this.font = data.font || "";
this.fontFamily = data.fontFamily || "";
this.fontWeight = data.fontWeight || '';
this.fontShape = data.fontShape || '';
this.sizeMultiplier = sizeMultipliers[this.size - 1];
this.maxSize = data.maxSize;
this.minRuleThickness = data.minRuleThickness;
this._fontMetrics = undefined;
}
/**
* Returns a new options object with the same properties as "this". Properties
* from "extension" will be copied to the new options object.
*/
var _proto = Options.prototype;
_proto.extend = function extend(extension) {
var data = {
style: this.style,
size: this.size,
textSize: this.textSize,
color: this.color,
phantom: this.phantom,
font: this.font,
fontFamily: this.fontFamily,
fontWeight: this.fontWeight,
fontShape: this.fontShape,
maxSize: this.maxSize,
minRuleThickness: this.minRuleThickness
};
for (var key in extension) {
if (extension.hasOwnProperty(key)) {
data[key] = extension[key];
}
}
return new Options(data);
}
/**
* Return an options object with the given style. If `this.style === style`,
* returns `this`.
*/
;
_proto.havingStyle = function havingStyle(style) {
if (this.style === style) {
return this;
} else {
return this.extend({
style: style,
size: sizeAtStyle(this.textSize, style)
});
}
}
/**
* Return an options object with a cramped version of the current style. If
* the current style is cramped, returns `this`.
*/
;
_proto.havingCrampedStyle = function havingCrampedStyle() {
return this.havingStyle(this.style.cramp());
}
/**
* Return an options object with the given size and in at least `\textstyle`.
* Returns `this` if appropriate.
*/
;
_proto.havingSize = function havingSize(size) {
if (this.size === size && this.textSize === size) {
return this;
} else {
return this.extend({
style: this.style.text(),
size: size,
textSize: size,
sizeMultiplier: sizeMultipliers[size - 1]
});
}
}
/**
* Like `this.havingSize(BASESIZE).havingStyle(style)`. If `style` is omitted,
* changes to at least `\textstyle`.
*/
;
_proto.havingBaseStyle = function havingBaseStyle(style) {
style = style || this.style.text();
var wantSize = sizeAtStyle(Options.BASESIZE, style);
if (this.size === wantSize && this.textSize === Options.BASESIZE && this.style === style) {
return this;
} else {
return this.extend({
style: style,
size: wantSize
});
}
}
/**
* Remove the effect of sizing changes such as \Huge.
* Keep the effect of the current style, such as \scriptstyle.
*/
;
_proto.havingBaseSizing = function havingBaseSizing() {
var size;
switch (this.style.id) {
case 4:
case 5:
size = 3; // normalsize in scriptstyle
break;
case 6:
case 7:
size = 1; // normalsize in scriptscriptstyle
break;
default:
size = 6;
// normalsize in textstyle or displaystyle
}
return this.extend({
style: this.style.text(),
size: size
});
}
/**
* Create a new options object with the given color.
*/
;
_proto.withColor = function withColor(color) {
return this.extend({
color: color
});
}
/**
* Create a new options object with "phantom" set to true.
*/
;
_proto.withPhantom = function withPhantom() {
return this.extend({
phantom: true
});
}
/**
* Creates a new options object with the given math font or old text font.
* @type {[type]}
*/
;
_proto.withFont = function withFont(font) {
return this.extend({
font: font
});
}
/**
* Create a new options objects with the given fontFamily.
*/
;
_proto.withTextFontFamily = function withTextFontFamily(fontFamily) {
return this.extend({
fontFamily: fontFamily,
font: ""
});
}
/**
* Creates a new options object with the given font weight
*/
;
_proto.withTextFontWeight = function withTextFontWeight(fontWeight) {
return this.extend({
fontWeight: fontWeight,
font: ""
});
}
/**
* Creates a new options object with the given font weight
*/
;
_proto.withTextFontShape = function withTextFontShape(fontShape) {
return this.extend({
fontShape: fontShape,
font: ""
});
}
/**
* Return the CSS sizing classes required to switch from enclosing options
* `oldOptions` to `this`. Returns an array of classes.
*/
;
_proto.sizingClasses = function sizingClasses(oldOptions) {
if (oldOptions.size !== this.size) {
return ["sizing", "reset-size" + oldOptions.size, "size" + this.size];
} else {
return [];
}
}
/**
* Return the CSS sizing classes required to switch to the base size. Like
* `this.havingSize(BASESIZE).sizingClasses(this)`.
*/
;
_proto.baseSizingClasses = function baseSizingClasses() {
if (this.size !== Options.BASESIZE) {
return ["sizing", "reset-size" + this.size, "size" + Options.BASESIZE];
} else {
return [];
}
}
/**
* Return the font metrics for this size.
*/
;
_proto.fontMetrics = function fontMetrics() {
if (!this._fontMetrics) {
this._fontMetrics = getGlobalMetrics(this.size);
}
return this._fontMetrics;
}
/**
* Gets the CSS color of the current options object
*/
;
_proto.getColor = function getColor() {
if (this.phantom) {
return "transparent";
} else {
return this.color;
}
};
return Options;
}();
Options_Options.BASESIZE = 6;
/* harmony default export */ var src_Options = (Options_Options);
// CONCATENATED MODULE: ./src/units.js
/**
* This file does conversion between units. In particular, it provides
* calculateSize to convert other units into ems.
*/
// This table gives the number of TeX pts in one of each *absolute* TeX unit.
// Thus, multiplying a length by this number converts the length from units
// into pts. Dividing the result by ptPerEm gives the number of ems
// *assuming* a font size of ptPerEm (normal size, normal style).
var ptPerUnit = {
// https://en.wikibooks.org/wiki/LaTeX/Lengths and
// https://tex.stackexchange.com/a/8263
"pt": 1,
// TeX point
"mm": 7227 / 2540,
// millimeter
"cm": 7227 / 254,
// centimeter
"in": 72.27,
// inch
"bp": 803 / 800,
// big (PostScript) points
"pc": 12,
// pica
"dd": 1238 / 1157,
// didot
"cc": 14856 / 1157,
// cicero (12 didot)
"nd": 685 / 642,
// new didot
"nc": 1370 / 107,
// new cicero (12 new didot)
"sp": 1 / 65536,
// scaled point (TeX's internal smallest unit)
// https://tex.stackexchange.com/a/41371
"px": 803 / 800 // \pdfpxdimen defaults to 1 bp in pdfTeX and LuaTeX
}; // Dictionary of relative units, for fast validity testing.
var relativeUnit = {
"ex": true,
"em": true,
"mu": true
};
/**
* Determine whether the specified unit (either a string defining the unit
* or a "size" parse node containing a unit field) is valid.
*/
var validUnit = function validUnit(unit) {
if (typeof unit !== "string") {
unit = unit.unit;
}
return unit in ptPerUnit || unit in relativeUnit || unit === "ex";
};
/*
* Convert a "size" parse node (with numeric "number" and string "unit" fields,
* as parsed by functions.js argType "size") into a CSS em value for the
* current style/scale. `options` gives the current options.
*/
var units_calculateSize = function calculateSize(sizeValue, options) {
var scale;
if (sizeValue.unit in ptPerUnit) {
// Absolute units
scale = ptPerUnit[sizeValue.unit] // Convert unit to pt
/ options.fontMetrics().ptPerEm // Convert pt to CSS em
/ options.sizeMultiplier; // Unscale to make absolute units
} else if (sizeValue.unit === "mu") {
// `mu` units scale with scriptstyle/scriptscriptstyle.
scale = options.fontMetrics().cssEmPerMu;
} else {
// Other relative units always refer to the *textstyle* font
// in the current size.
var unitOptions;
if (options.style.isTight()) {
// isTight() means current style is script/scriptscript.
unitOptions = options.havingStyle(options.style.text());
} else {
unitOptions = options;
} // TODO: In TeX these units are relative to the quad of the current
// *text* font, e.g. cmr10. KaTeX instead uses values from the
// comparably-sized *Computer Modern symbol* font. At 10pt, these
// match. At 7pt and 5pt, they differ: cmr7=1.138894, cmsy7=1.170641;
// cmr5=1.361133, cmsy5=1.472241. Consider $\scriptsize a\kern1emb$.
// TeX \showlists shows a kern of 1.13889 * fontsize;
// KaTeX shows a kern of 1.171 * fontsize.
if (sizeValue.unit === "ex") {
scale = unitOptions.fontMetrics().xHeight;
} else if (sizeValue.unit === "em") {
scale = unitOptions.fontMetrics().quad;
} else {
throw new src_ParseError("Invalid unit: '" + sizeValue.unit + "'");
}
if (unitOptions !== options) {
scale *= unitOptions.sizeMultiplier / options.sizeMultiplier;
}
}
return Math.min(sizeValue.number * scale, options.maxSize);
};
// CONCATENATED MODULE: ./src/buildCommon.js
/* eslint no-console:0 */
/**
* This module contains general functions that can be used for building
* different kinds of domTree nodes in a consistent manner.
*/
// The following have to be loaded from Main-Italic font, using class mathit
var mathitLetters = ["\\imath", "ı", // dotless i
"\\jmath", "ȷ", // dotless j
"\\pounds", "\\mathsterling", "\\textsterling", "£"];
/**
* Looks up the given symbol in fontMetrics, after applying any symbol
* replacements defined in symbol.js
*/
var buildCommon_lookupSymbol = function lookupSymbol(value, // TODO(#963): Use a union type for this.
fontName, mode) {
// Replace the value with its replaced value from symbol.js
if (src_symbols[mode][value] && src_symbols[mode][value].replace) {
value = src_symbols[mode][value].replace;
}
return {
value: value,
metrics: getCharacterMetrics(value, fontName, mode)
};
};
/**
* Makes a symbolNode after translation via the list of symbols in symbols.js.
* Correctly pulls out metrics for the character, and optionally takes a list of
* classes to be attached to the node.
*
* TODO: make argument order closer to makeSpan
* TODO: add a separate argument for math class (e.g. `mop`, `mbin`), which
* should if present come first in `classes`.
* TODO(#953): Make `options` mandatory and always pass it in.
*/
var buildCommon_makeSymbol = function makeSymbol(value, fontName, mode, options, classes) {
var lookup = buildCommon_lookupSymbol(value, fontName, mode);
var metrics = lookup.metrics;
value = lookup.value;
var symbolNode;
if (metrics) {
var italic = metrics.italic;
if (mode === "text" || options && options.font === "mathit") {
italic = 0;
}
symbolNode = new domTree_SymbolNode(value, metrics.height, metrics.depth, italic, metrics.skew, metrics.width, classes);
} else {
// TODO(emily): Figure out a good way to only print this in development
typeof console !== "undefined" && console.warn("No character metrics " + ("for '" + value + "' in style '" + fontName + "' and mode '" + mode + "'"));
symbolNode = new domTree_SymbolNode(value, 0, 0, 0, 0, 0, classes);
}
if (options) {
symbolNode.maxFontSize = options.sizeMultiplier;
if (options.style.isTight()) {
symbolNode.classes.push("mtight");
}
var color = options.getColor();
if (color) {
symbolNode.style.color = color;
}
}
return symbolNode;
};
/**
* Makes a symbol in Main-Regular or AMS-Regular.
* Used for rel, bin, open, close, inner, and punct.
*/
var buildCommon_mathsym = function mathsym(value, mode, options, classes) {
if (classes === void 0) {
classes = [];
}
// Decide what font to render the symbol in by its entry in the symbols
// table.
// Have a special case for when the value = \ because the \ is used as a
// textord in unsupported command errors but cannot be parsed as a regular
// text ordinal and is therefore not present as a symbol in the symbols
// table for text, as well as a special case for boldsymbol because it
// can be used for bold + and -
if (options.font === "boldsymbol" && buildCommon_lookupSymbol(value, "Main-Bold", mode).metrics) {
return buildCommon_makeSymbol(value, "Main-Bold", mode, options, classes.concat(["mathbf"]));
} else if (value === "\\" || src_symbols[mode][value].font === "main") {
return buildCommon_makeSymbol(value, "Main-Regular", mode, options, classes);
} else {
return buildCommon_makeSymbol(value, "AMS-Regular", mode, options, classes.concat(["amsrm"]));
}
};
/**
* Determines which of the two font names (Main-Italic and Math-Italic) and
* corresponding style tags (maindefault or mathit) to use for default math font,
* depending on the symbol.
*/
var buildCommon_mathdefault = function mathdefault(value, mode, options, classes) {
if (/[0-9]/.test(value.charAt(0)) || // glyphs for \imath and \jmath do not exist in Math-Italic so we
// need to use Main-Italic instead
utils.contains(mathitLetters, value)) {
return {
fontName: "Main-Italic",
fontClass: "mathit"
};
} else {
return {
fontName: "Math-Italic",
fontClass: "mathdefault"
};
}
};
/**
* Determines which of the font names (Main-Italic, Math-Italic, and Caligraphic)
* and corresponding style tags (mathit, mathdefault, or mathcal) to use for font
* "mathnormal", depending on the symbol. Use this function instead of fontMap for
* font "mathnormal".
*/
var buildCommon_mathnormal = function mathnormal(value, mode, options, classes) {
if (utils.contains(mathitLetters, value)) {
return {
fontName: "Main-Italic",
fontClass: "mathit"
};
} else if (/[0-9]/.test(value.charAt(0))) {
return {
fontName: "Caligraphic-Regular",
fontClass: "mathcal"
};
} else {
return {
fontName: "Math-Italic",
fontClass: "mathdefault"
};
}
};
/**
* Determines which of the two font names (Main-Bold and Math-BoldItalic) and
* corresponding style tags (mathbf or boldsymbol) to use for font "boldsymbol",
* depending on the symbol. Use this function instead of fontMap for font
* "boldsymbol".
*/
var boldsymbol = function boldsymbol(value, mode, options, classes) {
if (buildCommon_lookupSymbol(value, "Math-BoldItalic", mode).metrics) {
return {
fontName: "Math-BoldItalic",
fontClass: "boldsymbol"
};
} else {
// Some glyphs do not exist in Math-BoldItalic so we need to use
// Main-Bold instead.
return {
fontName: "Main-Bold",
fontClass: "mathbf"
};
}
};
/**
* Makes either a mathord or textord in the correct font and color.
*/
var buildCommon_makeOrd = function makeOrd(group, options, type) {
var mode = group.mode;
var text = group.text;
var classes = ["mord"]; // Math mode or Old font (i.e. \rm)
var isFont = mode === "math" || mode === "text" && options.font;
var fontOrFamily = isFont ? options.font : options.fontFamily;
if (text.charCodeAt(0) === 0xD835) {
// surrogate pairs get special treatment
var _wideCharacterFont = wide_character_wideCharacterFont(text, mode),
wideFontName = _wideCharacterFont[0],
wideFontClass = _wideCharacterFont[1];
return buildCommon_makeSymbol(text, wideFontName, mode, options, classes.concat(wideFontClass));
} else if (fontOrFamily) {
var fontName;
var fontClasses;
if (fontOrFamily === "boldsymbol" || fontOrFamily === "mathnormal") {
var fontData = fontOrFamily === "boldsymbol" ? boldsymbol(text, mode, options, classes) : buildCommon_mathnormal(text, mode, options, classes);
fontName = fontData.fontName;
fontClasses = [fontData.fontClass];
} else if (utils.contains(mathitLetters, text)) {
fontName = "Main-Italic";
fontClasses = ["mathit"];
} else if (isFont) {
fontName = fontMap[fontOrFamily].fontName;
fontClasses = [fontOrFamily];
} else {
fontName = retrieveTextFontName(fontOrFamily, options.fontWeight, options.fontShape);
fontClasses = [fontOrFamily, options.fontWeight, options.fontShape];
}
if (buildCommon_lookupSymbol(text, fontName, mode).metrics) {
return buildCommon_makeSymbol(text, fontName, mode, options, classes.concat(fontClasses));
} else if (ligatures.hasOwnProperty(text) && fontName.substr(0, 10) === "Typewriter") {
// Deconstruct ligatures in monospace fonts (\texttt, \tt).
var parts = [];
for (var i = 0; i < text.length; i++) {
parts.push(buildCommon_makeSymbol(text[i], fontName, mode, options, classes.concat(fontClasses)));
}
return buildCommon_makeFragment(parts);
}
} // Makes a symbol in the default font for mathords and textords.
if (type === "mathord") {
var fontLookup = buildCommon_mathdefault(text, mode, options, classes);
return buildCommon_makeSymbol(text, fontLookup.fontName, mode, options, classes.concat([fontLookup.fontClass]));
} else if (type === "textord") {
var font = src_symbols[mode][text] && src_symbols[mode][text].font;
if (font === "ams") {
var _fontName = retrieveTextFontName("amsrm", options.fontWeight, options.fontShape);
return buildCommon_makeSymbol(text, _fontName, mode, options, classes.concat("amsrm", options.fontWeight, options.fontShape));
} else if (font === "main" || !font) {
var _fontName2 = retrieveTextFontName("textrm", options.fontWeight, options.fontShape);
return buildCommon_makeSymbol(text, _fontName2, mode, options, classes.concat(options.fontWeight, options.fontShape));
} else {
// fonts added by plugins
var _fontName3 = retrieveTextFontName(font, options.fontWeight, options.fontShape); // We add font name as a css class
return buildCommon_makeSymbol(text, _fontName3, mode, options, classes.concat(_fontName3, options.fontWeight, options.fontShape));
}
} else {
throw new Error("unexpected type: " + type + " in makeOrd");
}
};
/**
* Returns true if subsequent symbolNodes have the same classes, skew, maxFont,
* and styles.
*/
var buildCommon_canCombine = function canCombine(prev, next) {
if (createClass(prev.classes) !== createClass(next.classes) || prev.skew !== next.skew || prev.maxFontSize !== next.maxFontSize) {
return false;
}
for (var style in prev.style) {
if (prev.style.hasOwnProperty(style) && prev.style[style] !== next.style[style]) {
return false;
}
}
for (var _style in next.style) {
if (next.style.hasOwnProperty(_style) && prev.style[_style] !== next.style[_style]) {
return false;
}
}
return true;
};
/**
* Combine consequetive domTree.symbolNodes into a single symbolNode.
* Note: this function mutates the argument.
*/
var buildCommon_tryCombineChars = function tryCombineChars(chars) {
for (var i = 0; i < chars.length - 1; i++) {
var prev = chars[i];
var next = chars[i + 1];
if (prev instanceof domTree_SymbolNode && next instanceof domTree_SymbolNode && buildCommon_canCombine(prev, next)) {
prev.text += next.text;
prev.height = Math.max(prev.height, next.height);
prev.depth = Math.max(prev.depth, next.depth); // Use the last character's italic correction since we use
// it to add padding to the right of the span created from
// the combined characters.
prev.italic = next.italic;
chars.splice(i + 1, 1);
i--;
}
}
return chars;
};
/**
* Calculate the height, depth, and maxFontSize of an element based on its
* children.
*/
var sizeElementFromChildren = function sizeElementFromChildren(elem) {
var height = 0;
var depth = 0;
var maxFontSize = 0;
for (var i = 0; i < elem.children.length; i++) {
var child = elem.children[i];
if (child.height > height) {
height = child.height;
}
if (child.depth > depth) {
depth = child.depth;
}
if (child.maxFontSize > maxFontSize) {
maxFontSize = child.maxFontSize;
}
}
elem.height = height;
elem.depth = depth;
elem.maxFontSize = maxFontSize;
};
/**
* Makes a span with the given list of classes, list of children, and options.
*
* TODO(#953): Ensure that `options` is always provided (currently some call
* sites don't pass it) and make the type below mandatory.
* TODO: add a separate argument for math class (e.g. `mop`, `mbin`), which
* should if present come first in `classes`.
*/
var buildCommon_makeSpan = function makeSpan(classes, children, options, style) {
var span = new domTree_Span(classes, children, options, style);
sizeElementFromChildren(span);
return span;
}; // SVG one is simpler -- doesn't require height, depth, max-font setting.
// This is also a separate method for typesafety.
var buildCommon_makeSvgSpan = function makeSvgSpan(classes, children, options, style) {
return new domTree_Span(classes, children, options, style);
};
var makeLineSpan = function makeLineSpan(className, options, thickness) {
var line = buildCommon_makeSpan([className], [], options);
line.height = Math.max(thickness || options.fontMetrics().defaultRuleThickness, options.minRuleThickness);
line.style.borderBottomWidth = line.height + "em";
line.maxFontSize = 1.0;
return line;
};
/**
* Makes an anchor with the given href, list of classes, list of children,
* and options.
*/
var buildCommon_makeAnchor = function makeAnchor(href, classes, children, options) {
var anchor = new domTree_Anchor(href, classes, children, options);
sizeElementFromChildren(anchor);
return anchor;
};
/**
* Makes a document fragment with the given list of children.
*/
var buildCommon_makeFragment = function makeFragment(children) {
var fragment = new tree_DocumentFragment(children);
sizeElementFromChildren(fragment);
return fragment;
};
/**
* Wraps group in a span if it's a document fragment, allowing to apply classes
* and styles
*/
var buildCommon_wrapFragment = function wrapFragment(group, options) {
if (group instanceof tree_DocumentFragment) {
return buildCommon_makeSpan([], [group], options);
}
return group;
}; // These are exact object types to catch typos in the names of the optional fields.
// Computes the updated `children` list and the overall depth.
//
// This helper function for makeVList makes it easier to enforce type safety by
// allowing early exits (returns) in the logic.
var getVListChildrenAndDepth = function getVListChildrenAndDepth(params) {
if (params.positionType === "individualShift") {
var oldChildren = params.children;
var children = [oldChildren[0]]; // Add in kerns to the list of params.children to get each element to be
// shifted to the correct specified shift
var _depth = -oldChildren[0].shift - oldChildren[0].elem.depth;
var currPos = _depth;
for (var i = 1; i < oldChildren.length; i++) {
var diff = -oldChildren[i].shift - currPos - oldChildren[i].elem.depth;
var size = diff - (oldChildren[i - 1].elem.height + oldChildren[i - 1].elem.depth);
currPos = currPos + diff;
children.push({
type: "kern",
size: size
});
children.push(oldChildren[i]);
}
return {
children: children,
depth: _depth
};
}
var depth;
if (params.positionType === "top") {
// We always start at the bottom, so calculate the bottom by adding up
// all the sizes
var bottom = params.positionData;
for (var _i = 0; _i < params.children.length; _i++) {
var child = params.children[_i];
bottom -= child.type === "kern" ? child.size : child.elem.height + child.elem.depth;
}
depth = bottom;
} else if (params.positionType === "bottom") {
depth = -params.positionData;
} else {
var firstChild = params.children[0];
if (firstChild.type !== "elem") {
throw new Error('First child must have type "elem".');
}
if (params.positionType === "shift") {
depth = -firstChild.elem.depth - params.positionData;
} else if (params.positionType === "firstBaseline") {
depth = -firstChild.elem.depth;
} else {
throw new Error("Invalid positionType " + params.positionType + ".");
}
}
return {
children: params.children,
depth: depth
};
};
/**
* Makes a vertical list by stacking elements and kerns on top of each other.
* Allows for many different ways of specifying the positioning method.
*
* See VListParam documentation above.
*/
var buildCommon_makeVList = function makeVList(params, options) {
var _getVListChildrenAndD = getVListChildrenAndDepth(params),
children = _getVListChildrenAndD.children,
depth = _getVListChildrenAndD.depth; // Create a strut that is taller than any list item. The strut is added to
// each item, where it will determine the item's baseline. Since it has
// `overflow:hidden`, the strut's top edge will sit on the item's line box's
// top edge and the strut's bottom edge will sit on the item's baseline,
// with no additional line-height spacing. This allows the item baseline to
// be positioned precisely without worrying about font ascent and
// line-height.
var pstrutSize = 0;
for (var i = 0; i < children.length; i++) {
var child = children[i];
if (child.type === "elem") {
var elem = child.elem;
pstrutSize = Math.max(pstrutSize, elem.maxFontSize, elem.height);
}
}
pstrutSize += 2;
var pstrut = buildCommon_makeSpan(["pstrut"], []);
pstrut.style.height = pstrutSize + "em"; // Create a new list of actual children at the correct offsets
var realChildren = [];
var minPos = depth;
var maxPos = depth;
var currPos = depth;
for (var _i2 = 0; _i2 < children.length; _i2++) {
var _child = children[_i2];
if (_child.type === "kern") {
currPos += _child.size;
} else {
var _elem = _child.elem;
var classes = _child.wrapperClasses || [];
var style = _child.wrapperStyle || {};
var childWrap = buildCommon_makeSpan(classes, [pstrut, _elem], undefined, style);
childWrap.style.top = -pstrutSize - currPos - _elem.depth + "em";
if (_child.marginLeft) {
childWrap.style.marginLeft = _child.marginLeft;
}
if (_child.marginRight) {
childWrap.style.marginRight = _child.marginRight;
}
realChildren.push(childWrap);
currPos += _elem.height + _elem.depth;
}
minPos = Math.min(minPos, currPos);
maxPos = Math.max(maxPos, currPos);
} // The vlist contents go in a table-cell with `vertical-align:bottom`.
// This cell's bottom edge will determine the containing table's baseline
// without overly expanding the containing line-box.
var vlist = buildCommon_makeSpan(["vlist"], realChildren);
vlist.style.height = maxPos + "em"; // A second row is used if necessary to represent the vlist's depth.
var rows;
if (minPos < 0) {
// We will define depth in an empty span with display: table-cell.
// It should render with the height that we define. But Chrome, in
// contenteditable mode only, treats that span as if it contains some
// text content. And that min-height over-rides our desired height.
// So we put another empty span inside the depth strut span.
var emptySpan = buildCommon_makeSpan([], []);
var depthStrut = buildCommon_makeSpan(["vlist"], [emptySpan]);
depthStrut.style.height = -minPos + "em"; // Safari wants the first row to have inline content; otherwise it
// puts the bottom of the *second* row on the baseline.
var topStrut = buildCommon_makeSpan(["vlist-s"], [new domTree_SymbolNode("\u200B")]);
rows = [buildCommon_makeSpan(["vlist-r"], [vlist, topStrut]), buildCommon_makeSpan(["vlist-r"], [depthStrut])];
} else {
rows = [buildCommon_makeSpan(["vlist-r"], [vlist])];
}
var vtable = buildCommon_makeSpan(["vlist-t"], rows);
if (rows.length === 2) {
vtable.classes.push("vlist-t2");
}
vtable.height = maxPos;
vtable.depth = -minPos;
return vtable;
}; // Glue is a concept from TeX which is a flexible space between elements in
// either a vertical or horizontal list. In KaTeX, at least for now, it's
// static space between elements in a horizontal layout.
var buildCommon_makeGlue = function makeGlue(measurement, options) {
// Make an empty span for the space
var rule = buildCommon_makeSpan(["mspace"], [], options);
var size = units_calculateSize(measurement, options);
rule.style.marginRight = size + "em";
return rule;
}; // Takes font options, and returns the appropriate fontLookup name
var retrieveTextFontName = function retrieveTextFontName(fontFamily, fontWeight, fontShape) {
var baseFontName = "";
switch (fontFamily) {
case "amsrm":
baseFontName = "AMS";
break;
case "textrm":
baseFontName = "Main";
break;
case "textsf":
baseFontName = "SansSerif";
break;
case "texttt":
baseFontName = "Typewriter";
break;
default:
baseFontName = fontFamily;
// use fonts added by a plugin
}
var fontStylesName;
if (fontWeight === "textbf" && fontShape === "textit") {
fontStylesName = "BoldItalic";
} else if (fontWeight === "textbf") {
fontStylesName = "Bold";
} else if (fontWeight === "textit") {
fontStylesName = "Italic";
} else {
fontStylesName = "Regular";
}
return baseFontName + "-" + fontStylesName;
};
/**
* Maps TeX font commands to objects containing:
* - variant: string used for "mathvariant" attribute in buildMathML.js
* - fontName: the "style" parameter to fontMetrics.getCharacterMetrics
*/
// A map between tex font commands an MathML mathvariant attribute values
var fontMap = {
// styles
"mathbf": {
variant: "bold",
fontName: "Main-Bold"
},
"mathrm": {
variant: "normal",
fontName: "Main-Regular"
},
"textit": {
variant: "italic",
fontName: "Main-Italic"
},
"mathit": {
variant: "italic",
fontName: "Main-Italic"
},
// Default math font, "mathnormal" and "boldsymbol" are missing because they
// require the use of several fonts: Main-Italic and Math-Italic for default
// math font, Main-Italic, Math-Italic, Caligraphic for "mathnormal", and
// Math-BoldItalic and Main-Bold for "boldsymbol". This is handled by a
// special case in makeOrd which ends up calling mathdefault, mathnormal,
// and boldsymbol.
// families
"mathbb": {
variant: "double-struck",
fontName: "AMS-Regular"
},
"mathcal": {
variant: "script",
fontName: "Caligraphic-Regular"
},
"mathfrak": {
variant: "fraktur",
fontName: "Fraktur-Regular"
},
"mathscr": {
variant: "script",
fontName: "Script-Regular"
},
"mathsf": {
variant: "sans-serif",
fontName: "SansSerif-Regular"
},
"mathtt": {
variant: "monospace",
fontName: "Typewriter-Regular"
}
};
var svgData = {
// path, width, height
vec: ["vec", 0.471, 0.714],
// values from the font glyph
oiintSize1: ["oiintSize1", 0.957, 0.499],
// oval to overlay the integrand
oiintSize2: ["oiintSize2", 1.472, 0.659],
oiiintSize1: ["oiiintSize1", 1.304, 0.499],
oiiintSize2: ["oiiintSize2", 1.98, 0.659]
};
var buildCommon_staticSvg = function staticSvg(value, options) {
// Create a span with inline SVG for the element.
var _svgData$value = svgData[value],
pathName = _svgData$value[0],
width = _svgData$value[1],
height = _svgData$value[2];
var path = new domTree_PathNode(pathName);
var svgNode = new SvgNode([path], {
"width": width + "em",
"height": height + "em",
// Override CSS rule `.katex svg { width: 100% }`
"style": "width:" + width + "em",
"viewBox": "0 0 " + 1000 * width + " " + 1000 * height,
"preserveAspectRatio": "xMinYMin"
});
var span = buildCommon_makeSvgSpan(["overlay"], [svgNode], options);
span.height = height;
span.style.height = height + "em";
span.style.width = width + "em";
return span;
};
/* harmony default export */ var buildCommon = ({
fontMap: fontMap,
makeSymbol: buildCommon_makeSymbol,
mathsym: buildCommon_mathsym,
makeSpan: buildCommon_makeSpan,
makeSvgSpan: buildCommon_makeSvgSpan,
makeLineSpan: makeLineSpan,
makeAnchor: buildCommon_makeAnchor,
makeFragment: buildCommon_makeFragment,
wrapFragment: buildCommon_wrapFragment,
makeVList: buildCommon_makeVList,
makeOrd: buildCommon_makeOrd,
makeGlue: buildCommon_makeGlue,
staticSvg: buildCommon_staticSvg,
svgData: svgData,
tryCombineChars: buildCommon_tryCombineChars
});
// CONCATENATED MODULE: ./src/parseNode.js
/**
* Asserts that the node is of the given type and returns it with stricter
* typing. Throws if the node's type does not match.
*/
function assertNodeType(node, type) {
var typedNode = checkNodeType(node, type);
if (!typedNode) {
throw new Error("Expected node of type " + type + ", but got " + (node ? "node of type " + node.type : String(node)));
} // $FlowFixMe: Unsure why.
return typedNode;
}
/**
* Returns the node more strictly typed iff it is of the given type. Otherwise,
* returns null.
*/
function checkNodeType(node, type) {
if (node && node.type === type) {
// The definition of ParseNode<TYPE> doesn't communicate to flow that
// `type: TYPE` (as that's not explicitly mentioned anywhere), though that
// happens to be true for all our value types.
// $FlowFixMe
return node;
}
return null;
}
/**
* Asserts that the node is of the given type and returns it with stricter
* typing. Throws if the node's type does not match.
*/
function assertAtomFamily(node, family) {
var typedNode = checkAtomFamily(node, family);
if (!typedNode) {
throw new Error("Expected node of type \"atom\" and family \"" + family + "\", but got " + (node ? node.type === "atom" ? "atom of family " + node.family : "node of type " + node.type : String(node)));
}
return typedNode;
}
/**
* Returns the node more strictly typed iff it is of the given type. Otherwise,
* returns null.
*/
function checkAtomFamily(node, family) {
return node && node.type === "atom" && node.family === family ? node : null;
}
/**
* Returns the node more strictly typed iff it is of the given type. Otherwise,
* returns null.
*/
function assertSymbolNodeType(node) {
var typedNode = checkSymbolNodeType(node);
if (!typedNode) {
throw new Error("Expected node of symbol group type, but got " + (node ? "node of type " + node.type : String(node)));
}
return typedNode;
}
/**
* Returns the node more strictly typed iff it is of the given type. Otherwise,
* returns null.
*/
function checkSymbolNodeType(node) {
if (node && (node.type === "atom" || NON_ATOMS.hasOwnProperty(node.type))) {
// $FlowFixMe
return node;
}
return null;
}
// CONCATENATED MODULE: ./src/spacingData.js
/**
* Describes spaces between different classes of atoms.
*/
var thinspace = {
number: 3,
unit: "mu"
};
var mediumspace = {
number: 4,
unit: "mu"
};
var thickspace = {
number: 5,
unit: "mu"
}; // Making the type below exact with all optional fields doesn't work due to
// - https://github.com/facebook/flow/issues/4582
// - https://github.com/facebook/flow/issues/5688
// However, since *all* fields are optional, $Shape<> works as suggested in 5688
// above.
// Spacing relationships for display and text styles
var spacings = {
mord: {
mop: thinspace,
mbin: mediumspace,
mrel: thickspace,
minner: thinspace
},
mop: {
mord: thinspace,
mop: thinspace,
mrel: thickspace,
minner: thinspace
},
mbin: {
mord: mediumspace,
mop: mediumspace,
mopen: mediumspace,
minner: mediumspace
},
mrel: {
mord: thickspace,
mop: thickspace,
mopen: thickspace,
minner: thickspace
},
mopen: {},
mclose: {
mop: thinspace,
mbin: mediumspace,
mrel: thickspace,
minner: thinspace
},
mpunct: {
mord: thinspace,
mop: thinspace,
mrel: thickspace,
mopen: thinspace,
mclose: thinspace,
mpunct: thinspace,
minner: thinspace
},
minner: {
mord: thinspace,
mop: thinspace,
mbin: mediumspace,
mrel: thickspace,
mopen: thinspace,
mpunct: thinspace,
minner: thinspace
}
}; // Spacing relationships for script and scriptscript styles
var tightSpacings = {
mord: {
mop: thinspace
},
mop: {
mord: thinspace,
mop: thinspace
},
mbin: {},
mrel: {},
mopen: {},
mclose: {
mop: thinspace
},
mpunct: {},
minner: {
mop: thinspace
}
};
// CONCATENATED MODULE: ./src/defineFunction.js
/**
* All registered functions.
* `functions.js` just exports this same dictionary again and makes it public.
* `Parser.js` requires this dictionary.
*/
var _functions = {};
/**
* All HTML builders. Should be only used in the `define*` and the `build*ML`
* functions.
*/
var _htmlGroupBuilders = {};
/**
* All MathML builders. Should be only used in the `define*` and the `build*ML`
* functions.
*/
var _mathmlGroupBuilders = {};
function defineFunction(_ref) {
var type = _ref.type,
names = _ref.names,
props = _ref.props,
handler = _ref.handler,
htmlBuilder = _ref.htmlBuilder,
mathmlBuilder = _ref.mathmlBuilder;
// Set default values of functions
var data = {
type: type,
numArgs: props.numArgs,
argTypes: props.argTypes,
greediness: props.greediness === undefined ? 1 : props.greediness,
allowedInText: !!props.allowedInText,
allowedInMath: props.allowedInMath === undefined ? true : props.allowedInMath,
numOptionalArgs: props.numOptionalArgs || 0,
infix: !!props.infix,
handler: handler
};
for (var i = 0; i < names.length; ++i) {
_functions[names[i]] = data;
}
if (type) {
if (htmlBuilder) {
_htmlGroupBuilders[type] = htmlBuilder;
}
if (mathmlBuilder) {
_mathmlGroupBuilders[type] = mathmlBuilder;
}
}
}
/**
* Use this to register only the HTML and MathML builders for a function (e.g.
* if the function's ParseNode is generated in Parser.js rather than via a
* stand-alone handler provided to `defineFunction`).
*/
function defineFunctionBuilders(_ref2) {
var type = _ref2.type,
htmlBuilder = _ref2.htmlBuilder,
mathmlBuilder = _ref2.mathmlBuilder;
defineFunction({
type: type,
names: [],
props: {
numArgs: 0
},
handler: function handler() {
throw new Error('Should never be called.');
},
htmlBuilder: htmlBuilder,
mathmlBuilder: mathmlBuilder
});
} // Since the corresponding buildHTML/buildMathML function expects a
// list of elements, we normalize for different kinds of arguments
var defineFunction_ordargument = function ordargument(arg) {
var node = checkNodeType(arg, "ordgroup");
return node ? node.body : [arg];
};
// CONCATENATED MODULE: ./src/buildHTML.js
/**
* This file does the main work of building a domTree structure from a parse
* tree. The entry point is the `buildHTML` function, which takes a parse tree.
* Then, the buildExpression, buildGroup, and various groupBuilders functions
* are called, to produce a final HTML tree.
*/
var buildHTML_makeSpan = buildCommon.makeSpan; // Binary atoms (first class `mbin`) change into ordinary atoms (`mord`)
// depending on their surroundings. See TeXbook pg. 442-446, Rules 5 and 6,
// and the text before Rule 19.
var binLeftCanceller = ["leftmost", "mbin", "mopen", "mrel", "mop", "mpunct"];
var binRightCanceller = ["rightmost", "mrel", "mclose", "mpunct"];
var styleMap = {
"display": src_Style.DISPLAY,
"text": src_Style.TEXT,
"script": src_Style.SCRIPT,
"scriptscript": src_Style.SCRIPTSCRIPT
};
var DomEnum = {
mord: "mord",
mop: "mop",
mbin: "mbin",
mrel: "mrel",
mopen: "mopen",
mclose: "mclose",
mpunct: "mpunct",
minner: "minner"
};
/**
* Take a list of nodes, build them in order, and return a list of the built
* nodes. documentFragments are flattened into their contents, so the
* returned list contains no fragments. `isRealGroup` is true if `expression`
* is a real group (no atoms will be added on either side), as opposed to
* a partial group (e.g. one created by \color). `surrounding` is an array
* consisting type of nodes that will be added to the left and right.
*/
var buildHTML_buildExpression = function buildExpression(expression, options, isRealGroup, surrounding) {
if (surrounding === void 0) {
surrounding = [null, null];
}
// Parse expressions into `groups`.
var groups = [];
for (var i = 0; i < expression.length; i++) {
var output = buildHTML_buildGroup(expression[i], options);
if (output instanceof tree_DocumentFragment) {
var children = output.children;
groups.push.apply(groups, children);
} else {
groups.push(output);
}
} // If `expression` is a partial group, let the parent handle spacings
// to avoid processing groups multiple times.
if (!isRealGroup) {
return groups;
}
var glueOptions = options;
if (expression.length === 1) {
var node = checkNodeType(expression[0], "sizing") || checkNodeType(expression[0], "styling");
if (!node) {// No match.
} else if (node.type === "sizing") {
glueOptions = options.havingSize(node.size);
} else if (node.type === "styling") {
glueOptions = options.havingStyle(styleMap[node.style]);
}
} // Dummy spans for determining spacings between surrounding atoms.
// If `expression` has no atoms on the left or right, class "leftmost"
// or "rightmost", respectively, is used to indicate it.
var dummyPrev = buildHTML_makeSpan([surrounding[0] || "leftmost"], [], options);
var dummyNext = buildHTML_makeSpan([surrounding[1] || "rightmost"], [], options); // TODO: These code assumes that a node's math class is the first element
// of its `classes` array. A later cleanup should ensure this, for
// instance by changing the signature of `makeSpan`.
// Before determining what spaces to insert, perform bin cancellation.
// Binary operators change to ordinary symbols in some contexts.
traverseNonSpaceNodes(groups, function (node, prev) {
var prevType = prev.classes[0];
var type = node.classes[0];
if (prevType === "mbin" && utils.contains(binRightCanceller, type)) {
prev.classes[0] = "mord";
} else if (type === "mbin" && utils.contains(binLeftCanceller, prevType)) {
node.classes[0] = "mord";
}
}, {
node: dummyPrev
}, dummyNext);
traverseNonSpaceNodes(groups, function (node, prev) {
var prevType = getTypeOfDomTree(prev);
var type = getTypeOfDomTree(node); // 'mtight' indicates that the node is script or scriptscript style.
var space = prevType && type ? node.hasClass("mtight") ? tightSpacings[prevType][type] : spacings[prevType][type] : null;
if (space) {
// Insert glue (spacing) after the `prev`.
return buildCommon.makeGlue(space, glueOptions);
}
}, {
node: dummyPrev
}, dummyNext);
return groups;
}; // Depth-first traverse non-space `nodes`, calling `callback` with the current and
// previous node as arguments, optionally returning a node to insert after the
// previous node. `prev` is an object with the previous node and `insertAfter`
// function to insert after it. `next` is a node that will be added to the right.
// Used for bin cancellation and inserting spacings.
var traverseNonSpaceNodes = function traverseNonSpaceNodes(nodes, callback, prev, next) {
if (next) {
// temporarily append the right node, if exists
nodes.push(next);
}
var i = 0;
for (; i < nodes.length; i++) {
var node = nodes[i];
var partialGroup = buildHTML_checkPartialGroup(node);
if (partialGroup) {
// Recursive DFS
// $FlowFixMe: make nodes a $ReadOnlyArray by returning a new array
traverseNonSpaceNodes(partialGroup.children, callback, prev);
continue;
} // Ignore explicit spaces (e.g., \;, \,) when determining what implicit
// spacing should go between atoms of different classes
if (node.classes[0] === "mspace") {
continue;
}
var result = callback(node, prev.node);
if (result) {
if (prev.insertAfter) {
prev.insertAfter(result);
} else {
// insert at front
nodes.unshift(result);
i++;
}
}
prev.node = node;
prev.insertAfter = function (index) {
return function (n) {
nodes.splice(index + 1, 0, n);
i++;
};
}(i);
}
if (next) {
nodes.pop();
}
}; // Check if given node is a partial group, i.e., does not affect spacing around.
var buildHTML_checkPartialGroup = function checkPartialGroup(node) {
if (node instanceof tree_DocumentFragment || node instanceof domTree_Anchor) {
return node;
}
return null;
}; // Return the outermost node of a domTree.
var getOutermostNode = function getOutermostNode(node, side) {
var partialGroup = buildHTML_checkPartialGroup(node);
if (partialGroup) {
var children = partialGroup.children;
if (children.length) {
if (side === "right") {
return getOutermostNode(children[children.length - 1], "right");
} else if (side === "left") {
return getOutermostNode(children[0], "left");
}
}
}
return node;
}; // Return math atom class (mclass) of a domTree.
// If `side` is given, it will get the type of the outermost node at given side.
var getTypeOfDomTree = function getTypeOfDomTree(node, side) {
if (!node) {
return null;
}
if (side) {
node = getOutermostNode(node, side);
} // This makes a lot of assumptions as to where the type of atom
// appears. We should do a better job of enforcing this.
return DomEnum[node.classes[0]] || null;
};
var makeNullDelimiter = function makeNullDelimiter(options, classes) {
var moreClasses = ["nulldelimiter"].concat(options.baseSizingClasses());
return buildHTML_makeSpan(classes.concat(moreClasses));
};
/**
* buildGroup is the function that takes a group and calls the correct groupType
* function for it. It also handles the interaction of size and style changes
* between parents and children.
*/
var buildHTML_buildGroup = function buildGroup(group, options, baseOptions) {
if (!group) {
return buildHTML_makeSpan();
}
if (_htmlGroupBuilders[group.type]) {
// Call the groupBuilders function
var groupNode = _htmlGroupBuilders[group.type](group, options); // If the size changed between the parent and the current group, account
// for that size difference.
if (baseOptions && options.size !== baseOptions.size) {
groupNode = buildHTML_makeSpan(options.sizingClasses(baseOptions), [groupNode], options);
var multiplier = options.sizeMultiplier / baseOptions.sizeMultiplier;
groupNode.height *= multiplier;
groupNode.depth *= multiplier;
}
return groupNode;
} else {
throw new src_ParseError("Got group of unknown type: '" + group.type + "'");
}
};
/**
* Combine an array of HTML DOM nodes (e.g., the output of `buildExpression`)
* into an unbreakable HTML node of class .base, with proper struts to
* guarantee correct vertical extent. `buildHTML` calls this repeatedly to
* make up the entire expression as a sequence of unbreakable units.
*/
function buildHTMLUnbreakable(children, options) {
// Compute height and depth of this chunk.
var body = buildHTML_makeSpan(["base"], children, options); // Add strut, which ensures that the top of the HTML element falls at
// the height of the expression, and the bottom of the HTML element
// falls at the depth of the expression.
// We used to have separate top and bottom struts, where the bottom strut
// would like to use `vertical-align: top`, but in IE 9 this lowers the
// baseline of the box to the bottom of this strut (instead of staying in
// the normal place) so we use an absolute value for vertical-align instead.
var strut = buildHTML_makeSpan(["strut"]);
strut.style.height = body.height + body.depth + "em";
strut.style.verticalAlign = -body.depth + "em";
body.children.unshift(strut);
return body;
}
/**
* Take an entire parse tree, and build it into an appropriate set of HTML
* nodes.
*/
function buildHTML(tree, options) {
// Strip off outer tag wrapper for processing below.
var tag = null;
if (tree.length === 1 && tree[0].type === "tag") {
tag = tree[0].tag;
tree = tree[0].body;
} // Build the expression contained in the tree
var expression = buildHTML_buildExpression(tree, options, true);
var children = []; // Create one base node for each chunk between potential line breaks.
// The TeXBook [p.173] says "A formula will be broken only after a
// relation symbol like $=$ or $<$ or $\rightarrow$, or after a binary
// operation symbol like $+$ or $-$ or $\times$, where the relation or
// binary operation is on the ``outer level'' of the formula (i.e., not
// enclosed in {...} and not part of an \over construction)."
var parts = [];
for (var i = 0; i < expression.length; i++) {
parts.push(expression[i]);
if (expression[i].hasClass("mbin") || expression[i].hasClass("mrel") || expression[i].hasClass("allowbreak")) {
// Put any post-operator glue on same line as operator.
// Watch for \nobreak along the way, and stop at \newline.
var nobreak = false;
while (i < expression.length - 1 && expression[i + 1].hasClass("mspace") && !expression[i + 1].hasClass("newline")) {
i++;
parts.push(expression[i]);
if (expression[i].hasClass("nobreak")) {
nobreak = true;
}
} // Don't allow break if \nobreak among the post-operator glue.
if (!nobreak) {
children.push(buildHTMLUnbreakable(parts, options));
parts = [];
}
} else if (expression[i].hasClass("newline")) {
// Write the line except the newline
parts.pop();
if (parts.length > 0) {
children.push(buildHTMLUnbreakable(parts, options));
parts = [];
} // Put the newline at the top level
children.push(expression[i]);
}
}
if (parts.length > 0) {
children.push(buildHTMLUnbreakable(parts, options));
} // Now, if there was a tag, build it too and append it as a final child.
var tagChild;
if (tag) {
tagChild = buildHTMLUnbreakable(buildHTML_buildExpression(tag, options, true));
tagChild.classes = ["tag"];
children.push(tagChild);
}
var htmlNode = buildHTML_makeSpan(["katex-html"], children);
htmlNode.setAttribute("aria-hidden", "true"); // Adjust the strut of the tag to be the maximum height of all children
// (the height of the enclosing htmlNode) for proper vertical alignment.
if (tagChild) {
var strut = tagChild.children[0];
strut.style.height = htmlNode.height + htmlNode.depth + "em";
strut.style.verticalAlign = -htmlNode.depth + "em";
}
return htmlNode;
}
// CONCATENATED MODULE: ./src/mathMLTree.js
/**
* These objects store data about MathML nodes. This is the MathML equivalent
* of the types in domTree.js. Since MathML handles its own rendering, and
* since we're mainly using MathML to improve accessibility, we don't manage
* any of the styling state that the plain DOM nodes do.
*
* The `toNode` and `toMarkup` functions work simlarly to how they do in
* domTree.js, creating namespaced DOM nodes and HTML text markup respectively.
*/
function newDocumentFragment(children) {
return new tree_DocumentFragment(children);
}
/**
* This node represents a general purpose MathML node of any type. The
* constructor requires the type of node to create (for example, `"mo"` or
* `"mspace"`, corresponding to `<mo>` and `<mspace>` tags).
*/
var mathMLTree_MathNode =
/*#__PURE__*/
function () {
function MathNode(type, children) {
this.type = void 0;
this.attributes = void 0;
this.children = void 0;
this.type = type;
this.attributes = {};
this.children = children || [];
}
/**
* Sets an attribute on a MathML node. MathML depends on attributes to convey a
* semantic content, so this is used heavily.
*/
var _proto = MathNode.prototype;
_proto.setAttribute = function setAttribute(name, value) {
this.attributes[name] = value;
}
/**
* Gets an attribute on a MathML node.
*/
;
_proto.getAttribute = function getAttribute(name) {
return this.attributes[name];
}
/**
* Converts the math node into a MathML-namespaced DOM element.
*/
;
_proto.toNode = function toNode() {
var node = document.createElementNS("http://www.w3.org/1998/Math/MathML", this.type);
for (var attr in this.attributes) {
if (Object.prototype.hasOwnProperty.call(this.attributes, attr)) {
node.setAttribute(attr, this.attributes[attr]);
}
}
for (var i = 0; i < this.children.length; i++) {
node.appendChild(this.children[i].toNode());
}
return node;
}
/**
* Converts the math node into an HTML markup string.
*/
;
_proto.toMarkup = function toMarkup() {
var markup = "<" + this.type; // Add the attributes
for (var attr in this.attributes) {
if (Object.prototype.hasOwnProperty.call(this.attributes, attr)) {
markup += " " + attr + "=\"";
markup += utils.escape(this.attributes[attr]);
markup += "\"";
}
}
markup += ">";
for (var i = 0; i < this.children.length; i++) {
markup += this.children[i].toMarkup();
}
markup += "</" + this.type + ">";
return markup;
}
/**
* Converts the math node into a string, similar to innerText, but escaped.
*/
;
_proto.toText = function toText() {
return this.children.map(function (child) {
return child.toText();
}).join("");
};
return MathNode;
}();
/**
* This node represents a piece of text.
*/
var mathMLTree_TextNode =
/*#__PURE__*/
function () {
function TextNode(text) {
this.text = void 0;
this.text = text;
}
/**
* Converts the text node into a DOM text node.
*/
var _proto2 = TextNode.prototype;
_proto2.toNode = function toNode() {
return document.createTextNode(this.text);
}
/**
* Converts the text node into escaped HTML markup
* (representing the text itself).
*/
;
_proto2.toMarkup = function toMarkup() {
return utils.escape(this.toText());
}
/**
* Converts the text node into a string
* (representing the text iteself).
*/
;
_proto2.toText = function toText() {
return this.text;
};
return TextNode;
}();
/**
* This node represents a space, but may render as <mspace.../> or as text,
* depending on the width.
*/
var SpaceNode =
/*#__PURE__*/
function () {
/**
* Create a Space node with width given in CSS ems.
*/
function SpaceNode(width) {
this.width = void 0;
this.character = void 0;
this.width = width; // See https://www.w3.org/TR/2000/WD-MathML2-20000328/chapter6.html
// for a table of space-like characters. We use Unicode
// representations instead of &LongNames; as it's not clear how to
// make the latter via document.createTextNode.
if (width >= 0.05555 && width <= 0.05556) {
this.character = "\u200A"; // &VeryThinSpace;
} else if (width >= 0.1666 && width <= 0.1667) {
this.character = "\u2009"; // &ThinSpace;
} else if (width >= 0.2222 && width <= 0.2223) {
this.character = "\u2005"; // &MediumSpace;
} else if (width >= 0.2777 && width <= 0.2778) {
this.character = "\u2005\u200A"; // &ThickSpace;
} else if (width >= -0.05556 && width <= -0.05555) {
this.character = "\u200A\u2063"; // &NegativeVeryThinSpace;
} else if (width >= -0.1667 && width <= -0.1666) {
this.character = "\u2009\u2063"; // &NegativeThinSpace;
} else if (width >= -0.2223 && width <= -0.2222) {
this.character = "\u205F\u2063"; // &NegativeMediumSpace;
} else if (width >= -0.2778 && width <= -0.2777) {
this.character = "\u2005\u2063"; // &NegativeThickSpace;
} else {
this.character = null;
}
}
/**
* Converts the math node into a MathML-namespaced DOM element.
*/
var _proto3 = SpaceNode.prototype;
_proto3.toNode = function toNode() {
if (this.character) {
return document.createTextNode(this.character);
} else {
var node = document.createElementNS("http://www.w3.org/1998/Math/MathML", "mspace");
node.setAttribute("width", this.width + "em");
return node;
}
}
/**
* Converts the math node into an HTML markup string.
*/
;
_proto3.toMarkup = function toMarkup() {
if (this.character) {
return "<mtext>" + this.character + "</mtext>";
} else {
return "<mspace width=\"" + this.width + "em\"/>";
}
}
/**
* Converts the math node into a string, similar to innerText.
*/
;
_proto3.toText = function toText() {
if (this.character) {
return this.character;
} else {
return " ";
}
};
return SpaceNode;
}();
/* harmony default export */ var mathMLTree = ({
MathNode: mathMLTree_MathNode,
TextNode: mathMLTree_TextNode,
SpaceNode: SpaceNode,
newDocumentFragment: newDocumentFragment
});
// CONCATENATED MODULE: ./src/buildMathML.js
/**
* This file converts a parse tree into a cooresponding MathML tree. The main
* entry point is the `buildMathML` function, which takes a parse tree from the
* parser.
*/
/**
* Takes a symbol and converts it into a MathML text node after performing
* optional replacement from symbols.js.
*/
var buildMathML_makeText = function makeText(text, mode, options) {
if (src_symbols[mode][text] && src_symbols[mode][text].replace && text.charCodeAt(0) !== 0xD835 && !(ligatures.hasOwnProperty(text) && options && (options.fontFamily && options.fontFamily.substr(4, 2) === "tt" || options.font && options.font.substr(4, 2) === "tt"))) {
text = src_symbols[mode][text].replace;
}
return new mathMLTree.TextNode(text);
};
/**
* Wrap the given array of nodes in an <mrow> node if needed, i.e.,
* unless the array has length 1. Always returns a single node.
*/
var buildMathML_makeRow = function makeRow(body) {
if (body.length === 1) {
return body[0];
} else {
return new mathMLTree.MathNode("mrow", body);
}
};
/**
* Returns the math variant as a string or null if none is required.
*/
var buildMathML_getVariant = function getVariant(group, options) {
// Handle \text... font specifiers as best we can.
// MathML has a limited list of allowable mathvariant specifiers; see
// https://www.w3.org/TR/MathML3/chapter3.html#presm.commatt
if (options.fontFamily === "texttt") {
return "monospace";
} else if (options.fontFamily === "textsf") {
if (options.fontShape === "textit" && options.fontWeight === "textbf") {
return "sans-serif-bold-italic";
} else if (options.fontShape === "textit") {
return "sans-serif-italic";
} else if (options.fontWeight === "textbf") {
return "bold-sans-serif";
} else {
return "sans-serif";
}
} else if (options.fontShape === "textit" && options.fontWeight === "textbf") {
return "bold-italic";
} else if (options.fontShape === "textit") {
return "italic";
} else if (options.fontWeight === "textbf") {
return "bold";
}
var font = options.font;
if (!font || font === "mathnormal") {
return null;
}
var mode = group.mode;
if (font === "mathit") {
return "italic";
} else if (font === "boldsymbol") {
return "bold-italic";
} else if (font === "mathbf") {
return "bold";
} else if (font === "mathbb") {
return "double-struck";
} else if (font === "mathfrak") {
return "fraktur";
} else if (font === "mathscr" || font === "mathcal") {
// MathML makes no distinction between script and caligrahpic
return "script";
} else if (font === "mathsf") {
return "sans-serif";
} else if (font === "mathtt") {
return "monospace";
}
var text = group.text;
if (utils.contains(["\\imath", "\\jmath"], text)) {
return null;
}
if (src_symbols[mode][text] && src_symbols[mode][text].replace) {
text = src_symbols[mode][text].replace;
}
var fontName = buildCommon.fontMap[font].fontName;
if (getCharacterMetrics(text, fontName, mode)) {
return buildCommon.fontMap[font].variant;
}
return null;
};
/**
* Takes a list of nodes, builds them, and returns a list of the generated
* MathML nodes. Also combine consecutive <mtext> outputs into a single
* <mtext> tag.
*/
var buildMathML_buildExpression = function buildExpression(expression, options, isOrdgroup) {
if (expression.length === 1) {
var group = buildMathML_buildGroup(expression[0], options);
if (isOrdgroup && group instanceof mathMLTree_MathNode && group.type === "mo") {
// When TeX writers want to suppress spacing on an operator,
// they often put the operator by itself inside braces.
group.setAttribute("lspace", "0em");
group.setAttribute("rspace", "0em");
}
return [group];
}
var groups = [];
var lastGroup;
for (var i = 0; i < expression.length; i++) {
var _group = buildMathML_buildGroup(expression[i], options);
if (_group instanceof mathMLTree_MathNode && lastGroup instanceof mathMLTree_MathNode) {
// Concatenate adjacent <mtext>s
if (_group.type === 'mtext' && lastGroup.type === 'mtext' && _group.getAttribute('mathvariant') === lastGroup.getAttribute('mathvariant')) {
var _lastGroup$children;
(_lastGroup$children = lastGroup.children).push.apply(_lastGroup$children, _group.children);
continue; // Concatenate adjacent <mn>s
} else if (_group.type === 'mn' && lastGroup.type === 'mn') {
var _lastGroup$children2;
(_lastGroup$children2 = lastGroup.children).push.apply(_lastGroup$children2, _group.children);
continue; // Concatenate <mn>...</mn> followed by <mi>.</mi>
} else if (_group.type === 'mi' && _group.children.length === 1 && lastGroup.type === 'mn') {
var child = _group.children[0];
if (child instanceof mathMLTree_TextNode && child.text === '.') {
var _lastGroup$children3;
(_lastGroup$children3 = lastGroup.children).push.apply(_lastGroup$children3, _group.children);
continue;
}
} else if (lastGroup.type === 'mi' && lastGroup.children.length === 1) {
var lastChild = lastGroup.children[0];
if (lastChild instanceof mathMLTree_TextNode && lastChild.text === "\u0338" && (_group.type === 'mo' || _group.type === 'mi' || _group.type === 'mn')) {
var _child = _group.children[0];
if (_child instanceof mathMLTree_TextNode && _child.text.length > 0) {
// Overlay with combining character long solidus
_child.text = _child.text.slice(0, 1) + "\u0338" + _child.text.slice(1);
groups.pop();
}
}
}
}
groups.push(_group);
lastGroup = _group;
}
return groups;
};
/**
* Equivalent to buildExpression, but wraps the elements in an <mrow>
* if there's more than one. Returns a single node instead of an array.
*/
var buildExpressionRow = function buildExpressionRow(expression, options, isOrdgroup) {
return buildMathML_makeRow(buildMathML_buildExpression(expression, options, isOrdgroup));
};
/**
* Takes a group from the parser and calls the appropriate groupBuilders function
* on it to produce a MathML node.
*/
var buildMathML_buildGroup = function buildGroup(group, options) {
if (!group) {
return new mathMLTree.MathNode("mrow");
}
if (_mathmlGroupBuilders[group.type]) {
// Call the groupBuilders function
var result = _mathmlGroupBuilders[group.type](group, options);
return result;
} else {
throw new src_ParseError("Got group of unknown type: '" + group.type + "'");
}
};
/**
* Takes a full parse tree and settings and builds a MathML representation of
* it. In particular, we put the elements from building the parse tree into a
* <semantics> tag so we can also include that TeX source as an annotation.
*
* Note that we actually return a domTree element with a `<math>` inside it so
* we can do appropriate styling.
*/
function buildMathML(tree, texExpression, options, forMathmlOnly) {
var expression = buildMathML_buildExpression(tree, options); // Wrap up the expression in an mrow so it is presented in the semantics
// tag correctly, unless it's a single <mrow> or <mtable>.
var wrapper;
if (expression.length === 1 && expression[0] instanceof mathMLTree_MathNode && utils.contains(["mrow", "mtable"], expression[0].type)) {
wrapper = expression[0];
} else {
wrapper = new mathMLTree.MathNode("mrow", expression);
} // Build a TeX annotation of the source
var annotation = new mathMLTree.MathNode("annotation", [new mathMLTree.TextNode(texExpression)]);
annotation.setAttribute("encoding", "application/x-tex");
var semantics = new mathMLTree.MathNode("semantics", [wrapper, annotation]);
var math = new mathMLTree.MathNode("math", [semantics]);
math.setAttribute("xmlns", "http://www.w3.org/1998/Math/MathML"); // You can't style <math> nodes, so we wrap the node in a span.
// NOTE: The span class is not typed to have <math> nodes as children, and
// we don't want to make the children type more generic since the children
// of span are expected to have more fields in `buildHtml` contexts.
var wrapperClass = forMathmlOnly ? "katex" : "katex-mathml"; // $FlowFixMe
return buildCommon.makeSpan([wrapperClass], [math]);
}
// CONCATENATED MODULE: ./src/buildTree.js
var buildTree_optionsFromSettings = function optionsFromSettings(settings) {
return new src_Options({
style: settings.displayMode ? src_Style.DISPLAY : src_Style.TEXT,
maxSize: settings.maxSize,
minRuleThickness: settings.minRuleThickness
});
};
var buildTree_displayWrap = function displayWrap(node, settings) {
if (settings.displayMode) {
var classes = ["katex-display"];
if (settings.leqno) {
classes.push("leqno");
}
if (settings.fleqn) {
classes.push("fleqn");
}
node = buildCommon.makeSpan(classes, [node]);
}
return node;
};
var buildTree_buildTree = function buildTree(tree, expression, settings) {
var options = buildTree_optionsFromSettings(settings);
var katexNode;
if (settings.output === "mathml") {
return buildMathML(tree, expression, options, true);
} else if (settings.output === "html") {
var htmlNode = buildHTML(tree, options);
katexNode = buildCommon.makeSpan(["katex"], [htmlNode]);
} else {
var mathMLNode = buildMathML(tree, expression, options, false);
var _htmlNode = buildHTML(tree, options);
katexNode = buildCommon.makeSpan(["katex"], [mathMLNode, _htmlNode]);
}
return buildTree_displayWrap(katexNode, settings);
};
var buildTree_buildHTMLTree = function buildHTMLTree(tree, expression, settings) {
var options = buildTree_optionsFromSettings(settings);
var htmlNode = buildHTML(tree, options);
var katexNode = buildCommon.makeSpan(["katex"], [htmlNode]);
return buildTree_displayWrap(katexNode, settings);
};
/* harmony default export */ var src_buildTree = (buildTree_buildTree);
// CONCATENATED MODULE: ./src/stretchy.js
/**
* This file provides support to buildMathML.js and buildHTML.js
* for stretchy wide elements rendered from SVG files
* and other CSS trickery.
*/
var stretchyCodePoint = {
widehat: "^",
widecheck: "ˇ",
widetilde: "~",
utilde: "~",
overleftarrow: "\u2190",
underleftarrow: "\u2190",
xleftarrow: "\u2190",
overrightarrow: "\u2192",
underrightarrow: "\u2192",
xrightarrow: "\u2192",
underbrace: "\u23DF",
overbrace: "\u23DE",
overgroup: "\u23E0",
undergroup: "\u23E1",
overleftrightarrow: "\u2194",
underleftrightarrow: "\u2194",
xleftrightarrow: "\u2194",
Overrightarrow: "\u21D2",
xRightarrow: "\u21D2",
overleftharpoon: "\u21BC",
xleftharpoonup: "\u21BC",
overrightharpoon: "\u21C0",
xrightharpoonup: "\u21C0",
xLeftarrow: "\u21D0",
xLeftrightarrow: "\u21D4",
xhookleftarrow: "\u21A9",
xhookrightarrow: "\u21AA",
xmapsto: "\u21A6",
xrightharpoondown: "\u21C1",
xleftharpoondown: "\u21BD",
xrightleftharpoons: "\u21CC",
xleftrightharpoons: "\u21CB",
xtwoheadleftarrow: "\u219E",
xtwoheadrightarrow: "\u21A0",
xlongequal: "=",
xtofrom: "\u21C4",
xrightleftarrows: "\u21C4",
xrightequilibrium: "\u21CC",
// Not a perfect match.
xleftequilibrium: "\u21CB" // None better available.
};
var stretchy_mathMLnode = function mathMLnode(label) {
var node = new mathMLTree.MathNode("mo", [new mathMLTree.TextNode(stretchyCodePoint[label.substr(1)])]);
node.setAttribute("stretchy", "true");
return node;
}; // Many of the KaTeX SVG images have been adapted from glyphs in KaTeX fonts.
// Copyright (c) 2009-2010, Design Science, Inc. (<www.mathjax.org>)
// Copyright (c) 2014-2017 Khan Academy (<www.khanacademy.org>)
// Licensed under the SIL Open Font License, Version 1.1.
// See \nhttp://scripts.sil.org/OFL
// Very Long SVGs
// Many of the KaTeX stretchy wide elements use a long SVG image and an
// overflow: hidden tactic to achieve a stretchy image while avoiding
// distortion of arrowheads or brace corners.
// The SVG typically contains a very long (400 em) arrow.
// The SVG is in a container span that has overflow: hidden, so the span
// acts like a window that exposes only part of the SVG.
// The SVG always has a longer, thinner aspect ratio than the container span.
// After the SVG fills 100% of the height of the container span,
// there is a long arrow shaft left over. That left-over shaft is not shown.
// Instead, it is sliced off because the span's CSS has overflow: hidden.
// Thus, the reader sees an arrow that matches the subject matter width
// without distortion.
// Some functions, such as \cancel, need to vary their aspect ratio. These
// functions do not get the overflow SVG treatment.
// Second Brush Stroke
// Low resolution monitors struggle to display images in fine detail.
// So browsers apply anti-aliasing. A long straight arrow shaft therefore
// will sometimes appear as if it has a blurred edge.
// To mitigate this, these SVG files contain a second "brush-stroke" on the
// arrow shafts. That is, a second long thin rectangular SVG path has been
// written directly on top of each arrow shaft. This reinforcement causes
// some of the screen pixels to display as black instead of the anti-aliased
// gray pixel that a single path would generate. So we get arrow shafts
// whose edges appear to be sharper.
// In the katexImagesData object just below, the dimensions all
// correspond to path geometry inside the relevant SVG.
// For example, \overrightarrow uses the same arrowhead as glyph U+2192
// from the KaTeX Main font. The scaling factor is 1000.
// That is, inside the font, that arrowhead is 522 units tall, which
// corresponds to 0.522 em inside the document.
var katexImagesData = {
// path(s), minWidth, height, align
overrightarrow: [["rightarrow"], 0.888, 522, "xMaxYMin"],
overleftarrow: [["leftarrow"], 0.888, 522, "xMinYMin"],
underrightarrow: [["rightarrow"], 0.888, 522, "xMaxYMin"],
underleftarrow: [["leftarrow"], 0.888, 522, "xMinYMin"],
xrightarrow: [["rightarrow"], 1.469, 522, "xMaxYMin"],
xleftarrow: [["leftarrow"], 1.469, 522, "xMinYMin"],
Overrightarrow: [["doublerightarrow"], 0.888, 560, "xMaxYMin"],
xRightarrow: [["doublerightarrow"], 1.526, 560, "xMaxYMin"],
xLeftarrow: [["doubleleftarrow"], 1.526, 560, "xMinYMin"],
overleftharpoon: [["leftharpoon"], 0.888, 522, "xMinYMin"],
xleftharpoonup: [["leftharpoon"], 0.888, 522, "xMinYMin"],
xleftharpoondown: [["leftharpoondown"], 0.888, 522, "xMinYMin"],
overrightharpoon: [["rightharpoon"], 0.888, 522, "xMaxYMin"],
xrightharpoonup: [["rightharpoon"], 0.888, 522, "xMaxYMin"],
xrightharpoondown: [["rightharpoondown"], 0.888, 522, "xMaxYMin"],
xlongequal: [["longequal"], 0.888, 334, "xMinYMin"],
xtwoheadleftarrow: [["twoheadleftarrow"], 0.888, 334, "xMinYMin"],
xtwoheadrightarrow: [["twoheadrightarrow"], 0.888, 334, "xMaxYMin"],
overleftrightarrow: [["leftarrow", "rightarrow"], 0.888, 522],
overbrace: [["leftbrace", "midbrace", "rightbrace"], 1.6, 548],
underbrace: [["leftbraceunder", "midbraceunder", "rightbraceunder"], 1.6, 548],
underleftrightarrow: [["leftarrow", "rightarrow"], 0.888, 522],
xleftrightarrow: [["leftarrow", "rightarrow"], 1.75, 522],
xLeftrightarrow: [["doubleleftarrow", "doublerightarrow"], 1.75, 560],
xrightleftharpoons: [["leftharpoondownplus", "rightharpoonplus"], 1.75, 716],
xleftrightharpoons: [["leftharpoonplus", "rightharpoondownplus"], 1.75, 716],
xhookleftarrow: [["leftarrow", "righthook"], 1.08, 522],
xhookrightarrow: [["lefthook", "rightarrow"], 1.08, 522],
overlinesegment: [["leftlinesegment", "rightlinesegment"], 0.888, 522],
underlinesegment: [["leftlinesegment", "rightlinesegment"], 0.888, 522],
overgroup: [["leftgroup", "rightgroup"], 0.888, 342],
undergroup: [["leftgroupunder", "rightgroupunder"], 0.888, 342],
xmapsto: [["leftmapsto", "rightarrow"], 1.5, 522],
xtofrom: [["leftToFrom", "rightToFrom"], 1.75, 528],
// The next three arrows are from the mhchem package.
// In mhchem.sty, min-length is 2.0em. But these arrows might appear in the
// document as \xrightarrow or \xrightleftharpoons. Those have
// min-length = 1.75em, so we set min-length on these next three to match.
xrightleftarrows: [["baraboveleftarrow", "rightarrowabovebar"], 1.75, 901],
xrightequilibrium: [["baraboveshortleftharpoon", "rightharpoonaboveshortbar"], 1.75, 716],
xleftequilibrium: [["shortbaraboveleftharpoon", "shortrightharpoonabovebar"], 1.75, 716]
};
var groupLength = function groupLength(arg) {
if (arg.type === "ordgroup") {
return arg.body.length;
} else {
return 1;
}
};
var stretchy_svgSpan = function svgSpan(group, options) {
// Create a span with inline SVG for the element.
function buildSvgSpan_() {
var viewBoxWidth = 400000; // default
var label = group.label.substr(1);
if (utils.contains(["widehat", "widecheck", "widetilde", "utilde"], label)) {
// Each type in the `if` statement corresponds to one of the ParseNode
// types below. This narrowing is required to access `grp.base`.
var grp = group; // There are four SVG images available for each function.
// Choose a taller image when there are more characters.
var numChars = groupLength(grp.base);
var viewBoxHeight;
var pathName;
var _height;
if (numChars > 5) {
if (label === "widehat" || label === "widecheck") {
viewBoxHeight = 420;
viewBoxWidth = 2364;
_height = 0.42;
pathName = label + "4";
} else {
viewBoxHeight = 312;
viewBoxWidth = 2340;
_height = 0.34;
pathName = "tilde4";
}
} else {
var imgIndex = [1, 1, 2, 2, 3, 3][numChars];
if (label === "widehat" || label === "widecheck") {
viewBoxWidth = [0, 1062, 2364, 2364, 2364][imgIndex];
viewBoxHeight = [0, 239, 300, 360, 420][imgIndex];
_height = [0, 0.24, 0.3, 0.3, 0.36, 0.42][imgIndex];
pathName = label + imgIndex;
} else {
viewBoxWidth = [0, 600, 1033, 2339, 2340][imgIndex];
viewBoxHeight = [0, 260, 286, 306, 312][imgIndex];
_height = [0, 0.26, 0.286, 0.3, 0.306, 0.34][imgIndex];
pathName = "tilde" + imgIndex;
}
}
var path = new domTree_PathNode(pathName);
var svgNode = new SvgNode([path], {
"width": "100%",
"height": _height + "em",
"viewBox": "0 0 " + viewBoxWidth + " " + viewBoxHeight,
"preserveAspectRatio": "none"
});
return {
span: buildCommon.makeSvgSpan([], [svgNode], options),
minWidth: 0,
height: _height
};
} else {
var spans = [];
var data = katexImagesData[label];
var paths = data[0],
_minWidth = data[1],
_viewBoxHeight = data[2];
var _height2 = _viewBoxHeight / 1000;
var numSvgChildren = paths.length;
var widthClasses;
var aligns;
if (numSvgChildren === 1) {
// $FlowFixMe: All these cases must be of the 4-tuple type.
var align1 = data[3];
widthClasses = ["hide-tail"];
aligns = [align1];
} else if (numSvgChildren === 2) {
widthClasses = ["halfarrow-left", "halfarrow-right"];
aligns = ["xMinYMin", "xMaxYMin"];
} else if (numSvgChildren === 3) {
widthClasses = ["brace-left", "brace-center", "brace-right"];
aligns = ["xMinYMin", "xMidYMin", "xMaxYMin"];
} else {
throw new Error("Correct katexImagesData or update code here to support\n " + numSvgChildren + " children.");
}
for (var i = 0; i < numSvgChildren; i++) {
var _path = new domTree_PathNode(paths[i]);
var _svgNode = new SvgNode([_path], {
"width": "400em",
"height": _height2 + "em",
"viewBox": "0 0 " + viewBoxWidth + " " + _viewBoxHeight,
"preserveAspectRatio": aligns[i] + " slice"
});
var _span = buildCommon.makeSvgSpan([widthClasses[i]], [_svgNode], options);
if (numSvgChildren === 1) {
return {
span: _span,
minWidth: _minWidth,
height: _height2
};
} else {
_span.style.height = _height2 + "em";
spans.push(_span);
}
}
return {
span: buildCommon.makeSpan(["stretchy"], spans, options),
minWidth: _minWidth,
height: _height2
};
}
} // buildSvgSpan_()
var _buildSvgSpan_ = buildSvgSpan_(),
span = _buildSvgSpan_.span,
minWidth = _buildSvgSpan_.minWidth,
height = _buildSvgSpan_.height; // Note that we are returning span.depth = 0.
// Any adjustments relative to the baseline must be done in buildHTML.
span.height = height;
span.style.height = height + "em";
if (minWidth > 0) {
span.style.minWidth = minWidth + "em";
}
return span;
};
var stretchy_encloseSpan = function encloseSpan(inner, label, pad, options) {
// Return an image span for \cancel, \bcancel, \xcancel, or \fbox
var img;
var totalHeight = inner.height + inner.depth + 2 * pad;
if (/fbox|color/.test(label)) {
img = buildCommon.makeSpan(["stretchy", label], [], options);
if (label === "fbox") {
var color = options.color && options.getColor();
if (color) {
img.style.borderColor = color;
}
}
} else {
// \cancel, \bcancel, or \xcancel
// Since \cancel's SVG is inline and it omits the viewBox attribute,
// its stroke-width will not vary with span area.
var lines = [];
if (/^[bx]cancel$/.test(label)) {
lines.push(new LineNode({
"x1": "0",
"y1": "0",
"x2": "100%",
"y2": "100%",
"stroke-width": "0.046em"
}));
}
if (/^x?cancel$/.test(label)) {
lines.push(new LineNode({
"x1": "0",
"y1": "100%",
"x2": "100%",
"y2": "0",
"stroke-width": "0.046em"
}));
}
var svgNode = new SvgNode(lines, {
"width": "100%",
"height": totalHeight + "em"
});
img = buildCommon.makeSvgSpan([], [svgNode], options);
}
img.height = totalHeight;
img.style.height = totalHeight + "em";
return img;
};
/* harmony default export */ var stretchy = ({
encloseSpan: stretchy_encloseSpan,
mathMLnode: stretchy_mathMLnode,
svgSpan: stretchy_svgSpan
});
// CONCATENATED MODULE: ./src/functions/accent.js
// NOTE: Unlike most `htmlBuilder`s, this one handles not only "accent", but
var accent_htmlBuilder = function htmlBuilder(grp, options) {
// Accents are handled in the TeXbook pg. 443, rule 12.
var base;
var group;
var supSub = checkNodeType(grp, "supsub");
var supSubGroup;
if (supSub) {
// If our base is a character box, and we have superscripts and
// subscripts, the supsub will defer to us. In particular, we want
// to attach the superscripts and subscripts to the inner body (so
// that the position of the superscripts and subscripts won't be
// affected by the height of the accent). We accomplish this by
// sticking the base of the accent into the base of the supsub, and
// rendering that, while keeping track of where the accent is.
// The real accent group is the base of the supsub group
group = assertNodeType(supSub.base, "accent"); // The character box is the base of the accent group
base = group.base; // Stick the character box into the base of the supsub group
supSub.base = base; // Rerender the supsub group with its new base, and store that
// result.
supSubGroup = assertSpan(buildHTML_buildGroup(supSub, options)); // reset original base
supSub.base = group;
} else {
group = assertNodeType(grp, "accent");
base = group.base;
} // Build the base group
var body = buildHTML_buildGroup(base, options.havingCrampedStyle()); // Does the accent need to shift for the skew of a character?
var mustShift = group.isShifty && utils.isCharacterBox(base); // Calculate the skew of the accent. This is based on the line "If the
// nucleus is not a single character, let s = 0; otherwise set s to the
// kern amount for the nucleus followed by the \skewchar of its font."
// Note that our skew metrics are just the kern between each character
// and the skewchar.
var skew = 0;
if (mustShift) {
// If the base is a character box, then we want the skew of the
// innermost character. To do that, we find the innermost character:
var baseChar = utils.getBaseElem(base); // Then, we render its group to get the symbol inside it
var baseGroup = buildHTML_buildGroup(baseChar, options.havingCrampedStyle()); // Finally, we pull the skew off of the symbol.
skew = assertSymbolDomNode(baseGroup).skew; // Note that we now throw away baseGroup, because the layers we
// removed with getBaseElem might contain things like \color which
// we can't get rid of.
// TODO(emily): Find a better way to get the skew
} // calculate the amount of space between the body and the accent
var clearance = Math.min(body.height, options.fontMetrics().xHeight); // Build the accent
var accentBody;
if (!group.isStretchy) {
var accent;
var width;
if (group.label === "\\vec") {
// Before version 0.9, \vec used the combining font glyph U+20D7.
// But browsers, especially Safari, are not consistent in how they
// render combining characters when not preceded by a character.
// So now we use an SVG.
// If Safari reforms, we should consider reverting to the glyph.
accent = buildCommon.staticSvg("vec", options);
width = buildCommon.svgData.vec[1];
} else {
accent = buildCommon.makeOrd({
mode: group.mode,
text: group.label
}, options, "textord");
accent = assertSymbolDomNode(accent); // Remove the italic correction of the accent, because it only serves to
// shift the accent over to a place we don't want.
accent.italic = 0;
width = accent.width;
}
accentBody = buildCommon.makeSpan(["accent-body"], [accent]); // "Full" accents expand the width of the resulting symbol to be
// at least the width of the accent, and overlap directly onto the
// character without any vertical offset.
var accentFull = group.label === "\\textcircled";
if (accentFull) {
accentBody.classes.push('accent-full');
clearance = body.height;
} // Shift the accent over by the skew.
var left = skew; // CSS defines `.katex .accent .accent-body:not(.accent-full) { width: 0 }`
// so that the accent doesn't contribute to the bounding box.
// We need to shift the character by its width (effectively half
// its width) to compensate.
if (!accentFull) {
left -= width / 2;
}
accentBody.style.left = left + "em"; // \textcircled uses the \bigcirc glyph, so it needs some
// vertical adjustment to match LaTeX.
if (group.label === "\\textcircled") {
accentBody.style.top = ".2em";
}
accentBody = buildCommon.makeVList({
positionType: "firstBaseline",
children: [{
type: "elem",
elem: body
}, {
type: "kern",
size: -clearance
}, {
type: "elem",
elem: accentBody
}]
}, options);
} else {
accentBody = stretchy.svgSpan(group, options);
accentBody = buildCommon.makeVList({
positionType: "firstBaseline",
children: [{
type: "elem",
elem: body
}, {
type: "elem",
elem: accentBody,
wrapperClasses: ["svg-align"],
wrapperStyle: skew > 0 ? {
width: "calc(100% - " + 2 * skew + "em)",
marginLeft: 2 * skew + "em"
} : undefined
}]
}, options);
}
var accentWrap = buildCommon.makeSpan(["mord", "accent"], [accentBody], options);
if (supSubGroup) {
// Here, we replace the "base" child of the supsub with our newly
// generated accent.
supSubGroup.children[0] = accentWrap; // Since we don't rerun the height calculation after replacing the
// accent, we manually recalculate height.
supSubGroup.height = Math.max(accentWrap.height, supSubGroup.height); // Accents should always be ords, even when their innards are not.
supSubGroup.classes[0] = "mord";
return supSubGroup;
} else {
return accentWrap;
}
};
var accent_mathmlBuilder = function mathmlBuilder(group, options) {
var accentNode = group.isStretchy ? stretchy.mathMLnode(group.label) : new mathMLTree.MathNode("mo", [buildMathML_makeText(group.label, group.mode)]);
var node = new mathMLTree.MathNode("mover", [buildMathML_buildGroup(group.base, options), accentNode]);
node.setAttribute("accent", "true");
return node;
};
var NON_STRETCHY_ACCENT_REGEX = new RegExp(["\\acute", "\\grave", "\\ddot", "\\tilde", "\\bar", "\\breve", "\\check", "\\hat", "\\vec", "\\dot", "\\mathring"].map(function (accent) {
return "\\" + accent;
}).join("|")); // Accents
defineFunction({
type: "accent",
names: ["\\acute", "\\grave", "\\ddot", "\\tilde", "\\bar", "\\breve", "\\check", "\\hat", "\\vec", "\\dot", "\\mathring", "\\widecheck", "\\widehat", "\\widetilde", "\\overrightarrow", "\\overleftarrow", "\\Overrightarrow", "\\overleftrightarrow", "\\overgroup", "\\overlinesegment", "\\overleftharpoon", "\\overrightharpoon"],
props: {
numArgs: 1
},
handler: function handler(context, args) {
var base = args[0];
var isStretchy = !NON_STRETCHY_ACCENT_REGEX.test(context.funcName);
var isShifty = !isStretchy || context.funcName === "\\widehat" || context.funcName === "\\widetilde" || context.funcName === "\\widecheck";
return {
type: "accent",
mode: context.parser.mode,
label: context.funcName,
isStretchy: isStretchy,
isShifty: isShifty,
base: base
};
},
htmlBuilder: accent_htmlBuilder,
mathmlBuilder: accent_mathmlBuilder
}); // Text-mode accents
defineFunction({
type: "accent",
names: ["\\'", "\\`", "\\^", "\\~", "\\=", "\\u", "\\.", '\\"', "\\r", "\\H", "\\v", "\\textcircled"],
props: {
numArgs: 1,
allowedInText: true,
allowedInMath: false
},
handler: function handler(context, args) {
var base = args[0];
return {
type: "accent",
mode: context.parser.mode,
label: context.funcName,
isStretchy: false,
isShifty: true,
base: base
};
},
htmlBuilder: accent_htmlBuilder,
mathmlBuilder: accent_mathmlBuilder
});
// CONCATENATED MODULE: ./src/functions/accentunder.js
// Horizontal overlap functions
defineFunction({
type: "accentUnder",
names: ["\\underleftarrow", "\\underrightarrow", "\\underleftrightarrow", "\\undergroup", "\\underlinesegment", "\\utilde"],
props: {
numArgs: 1
},
handler: function handler(_ref, args) {
var parser = _ref.parser,
funcName = _ref.funcName;
var base = args[0];
return {
type: "accentUnder",
mode: parser.mode,
label: funcName,
base: base
};
},
htmlBuilder: function htmlBuilder(group, options) {
// Treat under accents much like underlines.
var innerGroup = buildHTML_buildGroup(group.base, options);
var accentBody = stretchy.svgSpan(group, options);
var kern = group.label === "\\utilde" ? 0.12 : 0; // Generate the vlist, with the appropriate kerns
var vlist = buildCommon.makeVList({
positionType: "bottom",
positionData: accentBody.height + kern,
children: [{
type: "elem",
elem: accentBody,
wrapperClasses: ["svg-align"]
}, {
type: "kern",
size: kern
}, {
type: "elem",
elem: innerGroup
}]
}, options);
return buildCommon.makeSpan(["mord", "accentunder"], [vlist], options);
},
mathmlBuilder: function mathmlBuilder(group, options) {
var accentNode = stretchy.mathMLnode(group.label);
var node = new mathMLTree.MathNode("munder", [buildMathML_buildGroup(group.base, options), accentNode]);
node.setAttribute("accentunder", "true");
return node;
}
});
// CONCATENATED MODULE: ./src/functions/arrow.js
// Helper function
var arrow_paddedNode = function paddedNode(group) {
var node = new mathMLTree.MathNode("mpadded", group ? [group] : []);
node.setAttribute("width", "+0.6em");
node.setAttribute("lspace", "0.3em");
return node;
}; // Stretchy arrows with an optional argument
defineFunction({
type: "xArrow",
names: ["\\xleftarrow", "\\xrightarrow", "\\xLeftarrow", "\\xRightarrow", "\\xleftrightarrow", "\\xLeftrightarrow", "\\xhookleftarrow", "\\xhookrightarrow", "\\xmapsto", "\\xrightharpoondown", "\\xrightharpoonup", "\\xleftharpoondown", "\\xleftharpoonup", "\\xrightleftharpoons", "\\xleftrightharpoons", "\\xlongequal", "\\xtwoheadrightarrow", "\\xtwoheadleftarrow", "\\xtofrom", // The next 3 functions are here to support the mhchem extension.
// Direct use of these functions is discouraged and may break someday.
"\\xrightleftarrows", "\\xrightequilibrium", "\\xleftequilibrium"],
props: {
numArgs: 1,
numOptionalArgs: 1
},
handler: function handler(_ref, args, optArgs) {
var parser = _ref.parser,
funcName = _ref.funcName;
return {
type: "xArrow",
mode: parser.mode,
label: funcName,
body: args[0],
below: optArgs[0]
};
},
// Flow is unable to correctly infer the type of `group`, even though it's
// unamibiguously determined from the passed-in `type` above.
htmlBuilder: function htmlBuilder(group, options) {
var style = options.style; // Build the argument groups in the appropriate style.
// Ref: amsmath.dtx: \hbox{$\scriptstyle\mkern#3mu{#6}\mkern#4mu$}%
// Some groups can return document fragments. Handle those by wrapping
// them in a span.
var newOptions = options.havingStyle(style.sup());
var upperGroup = buildCommon.wrapFragment(buildHTML_buildGroup(group.body, newOptions, options), options);
upperGroup.classes.push("x-arrow-pad");
var lowerGroup;
if (group.below) {
// Build the lower group
newOptions = options.havingStyle(style.sub());
lowerGroup = buildCommon.wrapFragment(buildHTML_buildGroup(group.below, newOptions, options), options);
lowerGroup.classes.push("x-arrow-pad");
}
var arrowBody = stretchy.svgSpan(group, options); // Re shift: Note that stretchy.svgSpan returned arrowBody.depth = 0.
// The point we want on the math axis is at 0.5 * arrowBody.height.
var arrowShift = -options.fontMetrics().axisHeight + 0.5 * arrowBody.height; // 2 mu kern. Ref: amsmath.dtx: #7\if0#2\else\mkern#2mu\fi
var upperShift = -options.fontMetrics().axisHeight - 0.5 * arrowBody.height - 0.111; // 0.111 em = 2 mu
if (upperGroup.depth > 0.25 || group.label === "\\xleftequilibrium") {
upperShift -= upperGroup.depth; // shift up if depth encroaches
} // Generate the vlist
var vlist;
if (lowerGroup) {
var lowerShift = -options.fontMetrics().axisHeight + lowerGroup.height + 0.5 * arrowBody.height + 0.111;
vlist = buildCommon.makeVList({
positionType: "individualShift",
children: [{
type: "elem",
elem: upperGroup,
shift: upperShift
}, {
type: "elem",
elem: arrowBody,
shift: arrowShift
}, {
type: "elem",
elem: lowerGroup,
shift: lowerShift
}]
}, options);
} else {
vlist = buildCommon.makeVList({
positionType: "individualShift",
children: [{
type: "elem",
elem: upperGroup,
shift: upperShift
}, {
type: "elem",
elem: arrowBody,
shift: arrowShift
}]
}, options);
} // $FlowFixMe: Replace this with passing "svg-align" into makeVList.
vlist.children[0].children[0].children[1].classes.push("svg-align");
return buildCommon.makeSpan(["mrel", "x-arrow"], [vlist], options);
},
mathmlBuilder: function mathmlBuilder(group, options) {
var arrowNode = stretchy.mathMLnode(group.label);
var node;
if (group.body) {
var upperNode = arrow_paddedNode(buildMathML_buildGroup(group.body, options));
if (group.below) {
var lowerNode = arrow_paddedNode(buildMathML_buildGroup(group.below, options));
node = new mathMLTree.MathNode("munderover", [arrowNode, lowerNode, upperNode]);
} else {
node = new mathMLTree.MathNode("mover", [arrowNode, upperNode]);
}
} else if (group.below) {
var _lowerNode = arrow_paddedNode(buildMathML_buildGroup(group.below, options));
node = new mathMLTree.MathNode("munder", [arrowNode, _lowerNode]);
} else {
// This should never happen.
// Parser.js throws an error if there is no argument.
node = arrow_paddedNode();
node = new mathMLTree.MathNode("mover", [arrowNode, node]);
}
return node;
}
});
// CONCATENATED MODULE: ./src/functions/char.js
// \@char is an internal function that takes a grouped decimal argument like
// {123} and converts into symbol with code 123. It is used by the *macro*
// \char defined in macros.js.
defineFunction({
type: "textord",
names: ["\\@char"],
props: {
numArgs: 1,
allowedInText: true
},
handler: function handler(_ref, args) {
var parser = _ref.parser;
var arg = assertNodeType(args[0], "ordgroup");
var group = arg.body;
var number = "";
for (var i = 0; i < group.length; i++) {
var node = assertNodeType(group[i], "textord");
number += node.text;
}
var code = parseInt(number);
if (isNaN(code)) {
throw new src_ParseError("\\@char has non-numeric argument " + number);
}
return {
type: "textord",
mode: parser.mode,
text: String.fromCharCode(code)
};
}
});
// CONCATENATED MODULE: ./src/functions/color.js
var color_htmlBuilder = function htmlBuilder(group, options) {
var elements = buildHTML_buildExpression(group.body, options.withColor(group.color), false); // \color isn't supposed to affect the type of the elements it contains.
// To accomplish this, we wrap the results in a fragment, so the inner
// elements will be able to directly interact with their neighbors. For
// example, `\color{red}{2 +} 3` has the same spacing as `2 + 3`
return buildCommon.makeFragment(elements);
};
var color_mathmlBuilder = function mathmlBuilder(group, options) {
var inner = buildMathML_buildExpression(group.body, options.withColor(group.color));
var node = new mathMLTree.MathNode("mstyle", inner);
node.setAttribute("mathcolor", group.color);
return node;
};
defineFunction({
type: "color",
names: ["\\textcolor"],
props: {
numArgs: 2,
allowedInText: true,
greediness: 3,
argTypes: ["color", "original"]
},
handler: function handler(_ref, args) {
var parser = _ref.parser;
var color = assertNodeType(args[0], "color-token").color;
var body = args[1];
return {
type: "color",
mode: parser.mode,
color: color,
body: defineFunction_ordargument(body)
};
},
htmlBuilder: color_htmlBuilder,
mathmlBuilder: color_mathmlBuilder
});
defineFunction({
type: "color",
names: ["\\color"],
props: {
numArgs: 1,
allowedInText: true,
greediness: 3,
argTypes: ["color"]
},
handler: function handler(_ref2, args) {
var parser = _ref2.parser,
breakOnTokenText = _ref2.breakOnTokenText;
var color = assertNodeType(args[0], "color-token").color; // Set macro \current@color in current namespace to store the current
// color, mimicking the behavior of color.sty.
// This is currently used just to correctly color a \right
// that follows a \color command.
parser.gullet.macros.set("\\current@color", color); // Parse out the implicit body that should be colored.
var body = parser.parseExpression(true, breakOnTokenText);
return {
type: "color",
mode: parser.mode,
color: color,
body: body
};
},
htmlBuilder: color_htmlBuilder,
mathmlBuilder: color_mathmlBuilder
});
// CONCATENATED MODULE: ./src/functions/cr.js
// Row breaks within tabular environments, and line breaks at top level
// \\ is a macro mapping to either \cr or \newline. Because they have the
// same signature, we implement them as one megafunction, with newRow
// indicating whether we're in the \cr case, and newLine indicating whether
// to break the line in the \newline case.
defineFunction({
type: "cr",
names: ["\\cr", "\\newline"],
props: {
numArgs: 0,
numOptionalArgs: 1,
argTypes: ["size"],
allowedInText: true
},
handler: function handler(_ref, args, optArgs) {
var parser = _ref.parser,
funcName = _ref.funcName;
var size = optArgs[0];
var newRow = funcName === "\\cr";
var newLine = false;
if (!newRow) {
if (parser.settings.displayMode && parser.settings.useStrictBehavior("newLineInDisplayMode", "In LaTeX, \\\\ or \\newline " + "does nothing in display mode")) {
newLine = false;
} else {
newLine = true;
}
}
return {
type: "cr",
mode: parser.mode,
newLine: newLine,
newRow: newRow,
size: size && assertNodeType(size, "size").value
};
},
// The following builders are called only at the top level,
// not within tabular/array environments.
htmlBuilder: function htmlBuilder(group, options) {
if (group.newRow) {
throw new src_ParseError("\\cr valid only within a tabular/array environment");
}
var span = buildCommon.makeSpan(["mspace"], [], options);
if (group.newLine) {
span.classes.push("newline");
if (group.size) {
span.style.marginTop = units_calculateSize(group.size, options) + "em";
}
}
return span;
},
mathmlBuilder: function mathmlBuilder(group, options) {
var node = new mathMLTree.MathNode("mspace");
if (group.newLine) {
node.setAttribute("linebreak", "newline");
if (group.size) {
node.setAttribute("height", units_calculateSize(group.size, options) + "em");
}
}
return node;
}
});
// CONCATENATED MODULE: ./src/delimiter.js
/**
* This file deals with creating delimiters of various sizes. The TeXbook
* discusses these routines on page 441-442, in the "Another subroutine sets box
* x to a specified variable delimiter" paragraph.
*
* There are three main routines here. `makeSmallDelim` makes a delimiter in the
* normal font, but in either text, script, or scriptscript style.
* `makeLargeDelim` makes a delimiter in textstyle, but in one of the Size1,
* Size2, Size3, or Size4 fonts. `makeStackedDelim` makes a delimiter out of
* smaller pieces that are stacked on top of one another.
*
* The functions take a parameter `center`, which determines if the delimiter
* should be centered around the axis.
*
* Then, there are three exposed functions. `sizedDelim` makes a delimiter in
* one of the given sizes. This is used for things like `\bigl`.
* `customSizedDelim` makes a delimiter with a given total height+depth. It is
* called in places like `\sqrt`. `leftRightDelim` makes an appropriate
* delimiter which surrounds an expression of a given height an depth. It is
* used in `\left` and `\right`.
*/
/**
* Get the metrics for a given symbol and font, after transformation (i.e.
* after following replacement from symbols.js)
*/
var delimiter_getMetrics = function getMetrics(symbol, font, mode) {
var replace = src_symbols.math[symbol] && src_symbols.math[symbol].replace;
var metrics = getCharacterMetrics(replace || symbol, font, mode);
if (!metrics) {
throw new Error("Unsupported symbol " + symbol + " and font size " + font + ".");
}
return metrics;
};
/**
* Puts a delimiter span in a given style, and adds appropriate height, depth,
* and maxFontSizes.
*/
var delimiter_styleWrap = function styleWrap(delim, toStyle, options, classes) {
var newOptions = options.havingBaseStyle(toStyle);
var span = buildCommon.makeSpan(classes.concat(newOptions.sizingClasses(options)), [delim], options);
var delimSizeMultiplier = newOptions.sizeMultiplier / options.sizeMultiplier;
span.height *= delimSizeMultiplier;
span.depth *= delimSizeMultiplier;
span.maxFontSize = newOptions.sizeMultiplier;
return span;
};
var centerSpan = function centerSpan(span, options, style) {
var newOptions = options.havingBaseStyle(style);
var shift = (1 - options.sizeMultiplier / newOptions.sizeMultiplier) * options.fontMetrics().axisHeight;
span.classes.push("delimcenter");
span.style.top = shift + "em";
span.height -= shift;
span.depth += shift;
};
/**
* Makes a small delimiter. This is a delimiter that comes in the Main-Regular
* font, but is restyled to either be in textstyle, scriptstyle, or
* scriptscriptstyle.
*/
var delimiter_makeSmallDelim = function makeSmallDelim(delim, style, center, options, mode, classes) {
var text = buildCommon.makeSymbol(delim, "Main-Regular", mode, options);
var span = delimiter_styleWrap(text, style, options, classes);
if (center) {
centerSpan(span, options, style);
}
return span;
};
/**
* Builds a symbol in the given font size (note size is an integer)
*/
var delimiter_mathrmSize = function mathrmSize(value, size, mode, options) {
return buildCommon.makeSymbol(value, "Size" + size + "-Regular", mode, options);
};
/**
* Makes a large delimiter. This is a delimiter that comes in the Size1, Size2,
* Size3, or Size4 fonts. It is always rendered in textstyle.
*/
var delimiter_makeLargeDelim = function makeLargeDelim(delim, size, center, options, mode, classes) {
var inner = delimiter_mathrmSize(delim, size, mode, options);
var span = delimiter_styleWrap(buildCommon.makeSpan(["delimsizing", "size" + size], [inner], options), src_Style.TEXT, options, classes);
if (center) {
centerSpan(span, options, src_Style.TEXT);
}
return span;
};
/**
* Make an inner span with the given offset and in the given font. This is used
* in `makeStackedDelim` to make the stacking pieces for the delimiter.
*/
var delimiter_makeInner = function makeInner(symbol, font, mode) {
var sizeClass; // Apply the correct CSS class to choose the right font.
if (font === "Size1-Regular") {
sizeClass = "delim-size1";
} else
/* if (font === "Size4-Regular") */
{
sizeClass = "delim-size4";
}
var inner = buildCommon.makeSpan(["delimsizinginner", sizeClass], [buildCommon.makeSpan([], [buildCommon.makeSymbol(symbol, font, mode)])]); // Since this will be passed into `makeVList` in the end, wrap the element
// in the appropriate tag that VList uses.
return {
type: "elem",
elem: inner
};
}; // Helper for makeStackedDelim
var lap = {
type: "kern",
size: -0.005
};
/**
* Make a stacked delimiter out of a given delimiter, with the total height at
* least `heightTotal`. This routine is mentioned on page 442 of the TeXbook.
*/
var delimiter_makeStackedDelim = function makeStackedDelim(delim, heightTotal, center, options, mode, classes) {
// There are four parts, the top, an optional middle, a repeated part, and a
// bottom.
var top;
var middle;
var repeat;
var bottom;
top = repeat = bottom = delim;
middle = null; // Also keep track of what font the delimiters are in
var font = "Size1-Regular"; // We set the parts and font based on the symbol. Note that we use
// '\u23d0' instead of '|' and '\u2016' instead of '\\|' for the
// repeats of the arrows
if (delim === "\\uparrow") {
repeat = bottom = "\u23D0";
} else if (delim === "\\Uparrow") {
repeat = bottom = "\u2016";
} else if (delim === "\\downarrow") {
top = repeat = "\u23D0";
} else if (delim === "\\Downarrow") {
top = repeat = "\u2016";
} else if (delim === "\\updownarrow") {
top = "\\uparrow";
repeat = "\u23D0";
bottom = "\\downarrow";
} else if (delim === "\\Updownarrow") {
top = "\\Uparrow";
repeat = "\u2016";
bottom = "\\Downarrow";
} else if (delim === "[" || delim === "\\lbrack") {
top = "\u23A1";
repeat = "\u23A2";
bottom = "\u23A3";
font = "Size4-Regular";
} else if (delim === "]" || delim === "\\rbrack") {
top = "\u23A4";
repeat = "\u23A5";
bottom = "\u23A6";
font = "Size4-Regular";
} else if (delim === "\\lfloor" || delim === "\u230A") {
repeat = top = "\u23A2";
bottom = "\u23A3";
font = "Size4-Regular";
} else if (delim === "\\lceil" || delim === "\u2308") {
top = "\u23A1";
repeat = bottom = "\u23A2";
font = "Size4-Regular";
} else if (delim === "\\rfloor" || delim === "\u230B") {
repeat = top = "\u23A5";
bottom = "\u23A6";
font = "Size4-Regular";
} else if (delim === "\\rceil" || delim === "\u2309") {
top = "\u23A4";
repeat = bottom = "\u23A5";
font = "Size4-Regular";
} else if (delim === "(" || delim === "\\lparen") {
top = "\u239B";
repeat = "\u239C";
bottom = "\u239D";
font = "Size4-Regular";
} else if (delim === ")" || delim === "\\rparen") {
top = "\u239E";
repeat = "\u239F";
bottom = "\u23A0";
font = "Size4-Regular";
} else if (delim === "\\{" || delim === "\\lbrace") {
top = "\u23A7";
middle = "\u23A8";
bottom = "\u23A9";
repeat = "\u23AA";
font = "Size4-Regular";
} else if (delim === "\\}" || delim === "\\rbrace") {
top = "\u23AB";
middle = "\u23AC";
bottom = "\u23AD";
repeat = "\u23AA";
font = "Size4-Regular";
} else if (delim === "\\lgroup" || delim === "\u27EE") {
top = "\u23A7";
bottom = "\u23A9";
repeat = "\u23AA";
font = "Size4-Regular";
} else if (delim === "\\rgroup" || delim === "\u27EF") {
top = "\u23AB";
bottom = "\u23AD";
repeat = "\u23AA";
font = "Size4-Regular";
} else if (delim === "\\lmoustache" || delim === "\u23B0") {
top = "\u23A7";
bottom = "\u23AD";
repeat = "\u23AA";
font = "Size4-Regular";
} else if (delim === "\\rmoustache" || delim === "\u23B1") {
top = "\u23AB";
bottom = "\u23A9";
repeat = "\u23AA";
font = "Size4-Regular";
} // Get the metrics of the four sections
var topMetrics = delimiter_getMetrics(top, font, mode);
var topHeightTotal = topMetrics.height + topMetrics.depth;
var repeatMetrics = delimiter_getMetrics(repeat, font, mode);
var repeatHeightTotal = repeatMetrics.height + repeatMetrics.depth;
var bottomMetrics = delimiter_getMetrics(bottom, font, mode);
var bottomHeightTotal = bottomMetrics.height + bottomMetrics.depth;
var middleHeightTotal = 0;
var middleFactor = 1;
if (middle !== null) {
var middleMetrics = delimiter_getMetrics(middle, font, mode);
middleHeightTotal = middleMetrics.height + middleMetrics.depth;
middleFactor = 2; // repeat symmetrically above and below middle
} // Calcuate the minimal height that the delimiter can have.
// It is at least the size of the top, bottom, and optional middle combined.
var minHeight = topHeightTotal + bottomHeightTotal + middleHeightTotal; // Compute the number of copies of the repeat symbol we will need
var repeatCount = Math.max(0, Math.ceil((heightTotal - minHeight) / (middleFactor * repeatHeightTotal))); // Compute the total height of the delimiter including all the symbols
var realHeightTotal = minHeight + repeatCount * middleFactor * repeatHeightTotal; // The center of the delimiter is placed at the center of the axis. Note
// that in this context, "center" means that the delimiter should be
// centered around the axis in the current style, while normally it is
// centered around the axis in textstyle.
var axisHeight = options.fontMetrics().axisHeight;
if (center) {
axisHeight *= options.sizeMultiplier;
} // Calculate the depth
var depth = realHeightTotal / 2 - axisHeight; // This function differs from the TeX procedure in one way.
// We shift each repeat element downwards by 0.005em, to prevent a gap
// due to browser floating point rounding error.
// Then, at the last element-to element joint, we add one extra repeat
// element to cover the gap created by the shifts.
// Find the shift needed to align the upper end of the extra element at a point
// 0.005em above the lower end of the top element.
var shiftOfExtraElement = (repeatCount + 1) * 0.005 - repeatHeightTotal; // Now, we start building the pieces that will go into the vlist
// Keep a list of the inner pieces
var inners = []; // Add the bottom symbol
inners.push(delimiter_makeInner(bottom, font, mode));
if (middle === null) {
// Add that many symbols
for (var i = 0; i < repeatCount; i++) {
inners.push(lap); // overlap
inners.push(delimiter_makeInner(repeat, font, mode));
}
} else {
// When there is a middle bit, we need the middle part and two repeated
// sections
for (var _i = 0; _i < repeatCount; _i++) {
inners.push(lap);
inners.push(delimiter_makeInner(repeat, font, mode));
} // Insert one extra repeat element.
inners.push({
type: "kern",
size: shiftOfExtraElement
});
inners.push(delimiter_makeInner(repeat, font, mode));
inners.push(lap); // Now insert the middle of the brace.
inners.push(delimiter_makeInner(middle, font, mode));
for (var _i2 = 0; _i2 < repeatCount; _i2++) {
inners.push(lap);
inners.push(delimiter_makeInner(repeat, font, mode));
}
} // To cover the gap create by the overlaps, insert one more repeat element,
// at a position that juts 0.005 above the bottom of the top element.
inners.push({
type: "kern",
size: shiftOfExtraElement
});
inners.push(delimiter_makeInner(repeat, font, mode));
inners.push(lap); // Add the top symbol
inners.push(delimiter_makeInner(top, font, mode)); // Finally, build the vlist
var newOptions = options.havingBaseStyle(src_Style.TEXT);
var inner = buildCommon.makeVList({
positionType: "bottom",
positionData: depth,
children: inners
}, newOptions);
return delimiter_styleWrap(buildCommon.makeSpan(["delimsizing", "mult"], [inner], newOptions), src_Style.TEXT, options, classes);
}; // All surds have 0.08em padding above the viniculum inside the SVG.
// That keeps browser span height rounding error from pinching the line.
var vbPad = 80; // padding above the surd, measured inside the viewBox.
var emPad = 0.08; // padding, in ems, measured in the document.
var delimiter_sqrtSvg = function sqrtSvg(sqrtName, height, viewBoxHeight, extraViniculum, options) {
var path = sqrtPath(sqrtName, extraViniculum, viewBoxHeight);
var pathNode = new domTree_PathNode(sqrtName, path);
var svg = new SvgNode([pathNode], {
// Note: 1000:1 ratio of viewBox to document em width.
"width": "400em",
"height": height + "em",
"viewBox": "0 0 400000 " + viewBoxHeight,
"preserveAspectRatio": "xMinYMin slice"
});
return buildCommon.makeSvgSpan(["hide-tail"], [svg], options);
};
/**
* Make a sqrt image of the given height,
*/
var makeSqrtImage = function makeSqrtImage(height, options) {
// Define a newOptions that removes the effect of size changes such as \Huge.
// We don't pick different a height surd for \Huge. For it, we scale up.
var newOptions = options.havingBaseSizing(); // Pick the desired surd glyph from a sequence of surds.
var delim = traverseSequence("\\surd", height * newOptions.sizeMultiplier, stackLargeDelimiterSequence, newOptions);
var sizeMultiplier = newOptions.sizeMultiplier; // default
// The standard sqrt SVGs each have a 0.04em thick viniculum.
// If Settings.minRuleThickness is larger than that, we add extraViniculum.
var extraViniculum = Math.max(0, options.minRuleThickness - options.fontMetrics().sqrtRuleThickness); // Create a span containing an SVG image of a sqrt symbol.
var span;
var spanHeight = 0;
var texHeight = 0;
var viewBoxHeight = 0;
var advanceWidth; // We create viewBoxes with 80 units of "padding" above each surd.
// Then browser rounding error on the parent span height will not
// encroach on the ink of the viniculum. But that padding is not
// included in the TeX-like `height` used for calculation of
// vertical alignment. So texHeight = span.height < span.style.height.
if (delim.type === "small") {
// Get an SVG that is derived from glyph U+221A in font KaTeX-Main.
// 1000 unit normal glyph height.
viewBoxHeight = 1000 + 1000 * extraViniculum + vbPad;
if (height < 1.0) {
sizeMultiplier = 1.0; // mimic a \textfont radical
} else if (height < 1.4) {
sizeMultiplier = 0.7; // mimic a \scriptfont radical
}
spanHeight = (1.0 + extraViniculum + emPad) / sizeMultiplier;
texHeight = (1.00 + extraViniculum) / sizeMultiplier;
span = delimiter_sqrtSvg("sqrtMain", spanHeight, viewBoxHeight, extraViniculum, options);
span.style.minWidth = "0.853em";
advanceWidth = 0.833 / sizeMultiplier; // from the font.
} else if (delim.type === "large") {
// These SVGs come from fonts: KaTeX_Size1, _Size2, etc.
viewBoxHeight = (1000 + vbPad) * sizeToMaxHeight[delim.size];
texHeight = (sizeToMaxHeight[delim.size] + extraViniculum) / sizeMultiplier;
spanHeight = (sizeToMaxHeight[delim.size] + extraViniculum + emPad) / sizeMultiplier;
span = delimiter_sqrtSvg("sqrtSize" + delim.size, spanHeight, viewBoxHeight, extraViniculum, options);
span.style.minWidth = "1.02em";
advanceWidth = 1.0 / sizeMultiplier; // 1.0 from the font.
} else {
// Tall sqrt. In TeX, this would be stacked using multiple glyphs.
// We'll use a single SVG to accomplish the same thing.
spanHeight = height + extraViniculum + emPad;
texHeight = height + extraViniculum;
viewBoxHeight = Math.floor(1000 * height + extraViniculum) + vbPad;
span = delimiter_sqrtSvg("sqrtTall", spanHeight, viewBoxHeight, extraViniculum, options);
span.style.minWidth = "0.742em";
advanceWidth = 1.056;
}
span.height = texHeight;
span.style.height = spanHeight + "em";
return {
span: span,
advanceWidth: advanceWidth,
// Calculate the actual line width.
// This actually should depend on the chosen font -- e.g. \boldmath
// should use the thicker surd symbols from e.g. KaTeX_Main-Bold, and
// have thicker rules.
ruleWidth: (options.fontMetrics().sqrtRuleThickness + extraViniculum) * sizeMultiplier
};
}; // There are three kinds of delimiters, delimiters that stack when they become
// too large
var stackLargeDelimiters = ["(", "\\lparen", ")", "\\rparen", "[", "\\lbrack", "]", "\\rbrack", "\\{", "\\lbrace", "\\}", "\\rbrace", "\\lfloor", "\\rfloor", "\u230A", "\u230B", "\\lceil", "\\rceil", "\u2308", "\u2309", "\\surd"]; // delimiters that always stack
var stackAlwaysDelimiters = ["\\uparrow", "\\downarrow", "\\updownarrow", "\\Uparrow", "\\Downarrow", "\\Updownarrow", "|", "\\|", "\\vert", "\\Vert", "\\lvert", "\\rvert", "\\lVert", "\\rVert", "\\lgroup", "\\rgroup", "\u27EE", "\u27EF", "\\lmoustache", "\\rmoustache", "\u23B0", "\u23B1"]; // and delimiters that never stack
var stackNeverDelimiters = ["<", ">", "\\langle", "\\rangle", "/", "\\backslash", "\\lt", "\\gt"]; // Metrics of the different sizes. Found by looking at TeX's output of
// $\bigl| // \Bigl| \biggl| \Biggl| \showlists$
// Used to create stacked delimiters of appropriate sizes in makeSizedDelim.
var sizeToMaxHeight = [0, 1.2, 1.8, 2.4, 3.0];
/**
* Used to create a delimiter of a specific size, where `size` is 1, 2, 3, or 4.
*/
var delimiter_makeSizedDelim = function makeSizedDelim(delim, size, options, mode, classes) {
// < and > turn into \langle and \rangle in delimiters
if (delim === "<" || delim === "\\lt" || delim === "\u27E8") {
delim = "\\langle";
} else if (delim === ">" || delim === "\\gt" || delim === "\u27E9") {
delim = "\\rangle";
} // Sized delimiters are never centered.
if (utils.contains(stackLargeDelimiters, delim) || utils.contains(stackNeverDelimiters, delim)) {
return delimiter_makeLargeDelim(delim, size, false, options, mode, classes);
} else if (utils.contains(stackAlwaysDelimiters, delim)) {
return delimiter_makeStackedDelim(delim, sizeToMaxHeight[size], false, options, mode, classes);
} else {
throw new src_ParseError("Illegal delimiter: '" + delim + "'");
}
};
/**
* There are three different sequences of delimiter sizes that the delimiters
* follow depending on the kind of delimiter. This is used when creating custom
* sized delimiters to decide whether to create a small, large, or stacked
* delimiter.
*
* In real TeX, these sequences aren't explicitly defined, but are instead
* defined inside the font metrics. Since there are only three sequences that
* are possible for the delimiters that TeX defines, it is easier to just encode
* them explicitly here.
*/
// Delimiters that never stack try small delimiters and large delimiters only
var stackNeverDelimiterSequence = [{
type: "small",
style: src_Style.SCRIPTSCRIPT
}, {
type: "small",
style: src_Style.SCRIPT
}, {
type: "small",
style: src_Style.TEXT
}, {
type: "large",
size: 1
}, {
type: "large",
size: 2
}, {
type: "large",
size: 3
}, {
type: "large",
size: 4
}]; // Delimiters that always stack try the small delimiters first, then stack
var stackAlwaysDelimiterSequence = [{
type: "small",
style: src_Style.SCRIPTSCRIPT
}, {
type: "small",
style: src_Style.SCRIPT
}, {
type: "small",
style: src_Style.TEXT
}, {
type: "stack"
}]; // Delimiters that stack when large try the small and then large delimiters, and
// stack afterwards
var stackLargeDelimiterSequence = [{
type: "small",
style: src_Style.SCRIPTSCRIPT
}, {
type: "small",
style: src_Style.SCRIPT
}, {
type: "small",
style: src_Style.TEXT
}, {
type: "large",
size: 1
}, {
type: "large",
size: 2
}, {
type: "large",
size: 3
}, {
type: "large",
size: 4
}, {
type: "stack"
}];
/**
* Get the font used in a delimiter based on what kind of delimiter it is.
* TODO(#963) Use more specific font family return type once that is introduced.
*/
var delimTypeToFont = function delimTypeToFont(type) {
if (type.type === "small") {
return "Main-Regular";
} else if (type.type === "large") {
return "Size" + type.size + "-Regular";
} else if (type.type === "stack") {
return "Size4-Regular";
} else {
throw new Error("Add support for delim type '" + type.type + "' here.");
}
};
/**
* Traverse a sequence of types of delimiters to decide what kind of delimiter
* should be used to create a delimiter of the given height+depth.
*/
var traverseSequence = function traverseSequence(delim, height, sequence, options) {
// Here, we choose the index we should start at in the sequences. In smaller
// sizes (which correspond to larger numbers in style.size) we start earlier
// in the sequence. Thus, scriptscript starts at index 3-3=0, script starts
// at index 3-2=1, text starts at 3-1=2, and display starts at min(2,3-0)=2
var start = Math.min(2, 3 - options.style.size);
for (var i = start; i < sequence.length; i++) {
if (sequence[i].type === "stack") {
// This is always the last delimiter, so we just break the loop now.
break;
}
var metrics = delimiter_getMetrics(delim, delimTypeToFont(sequence[i]), "math");
var heightDepth = metrics.height + metrics.depth; // Small delimiters are scaled down versions of the same font, so we
// account for the style change size.
if (sequence[i].type === "small") {
var newOptions = options.havingBaseStyle(sequence[i].style);
heightDepth *= newOptions.sizeMultiplier;
} // Check if the delimiter at this size works for the given height.
if (heightDepth > height) {
return sequence[i];
}
} // If we reached the end of the sequence, return the last sequence element.
return sequence[sequence.length - 1];
};
/**
* Make a delimiter of a given height+depth, with optional centering. Here, we
* traverse the sequences, and create a delimiter that the sequence tells us to.
*/
var delimiter_makeCustomSizedDelim = function makeCustomSizedDelim(delim, height, center, options, mode, classes) {
if (delim === "<" || delim === "\\lt" || delim === "\u27E8") {
delim = "\\langle";
} else if (delim === ">" || delim === "\\gt" || delim === "\u27E9") {
delim = "\\rangle";
} // Decide what sequence to use
var sequence;
if (utils.contains(stackNeverDelimiters, delim)) {
sequence = stackNeverDelimiterSequence;
} else if (utils.contains(stackLargeDelimiters, delim)) {
sequence = stackLargeDelimiterSequence;
} else {
sequence = stackAlwaysDelimiterSequence;
} // Look through the sequence
var delimType = traverseSequence(delim, height, sequence, options); // Get the delimiter from font glyphs.
// Depending on the sequence element we decided on, call the
// appropriate function.
if (delimType.type === "small") {
return delimiter_makeSmallDelim(delim, delimType.style, center, options, mode, classes);
} else if (delimType.type === "large") {
return delimiter_makeLargeDelim(delim, delimType.size, center, options, mode, classes);
} else
/* if (delimType.type === "stack") */
{
return delimiter_makeStackedDelim(delim, height, center, options, mode, classes);
}
};
/**
* Make a delimiter for use with `\left` and `\right`, given a height and depth
* of an expression that the delimiters surround.
*/
var makeLeftRightDelim = function makeLeftRightDelim(delim, height, depth, options, mode, classes) {
// We always center \left/\right delimiters, so the axis is always shifted
var axisHeight = options.fontMetrics().axisHeight * options.sizeMultiplier; // Taken from TeX source, tex.web, function make_left_right
var delimiterFactor = 901;
var delimiterExtend = 5.0 / options.fontMetrics().ptPerEm;
var maxDistFromAxis = Math.max(height - axisHeight, depth + axisHeight);
var totalHeight = Math.max( // In real TeX, calculations are done using integral values which are
// 65536 per pt, or 655360 per em. So, the division here truncates in
// TeX but doesn't here, producing different results. If we wanted to
// exactly match TeX's calculation, we could do
// Math.floor(655360 * maxDistFromAxis / 500) *
// delimiterFactor / 655360
// (To see the difference, compare
// x^{x^{\left(\rule{0.1em}{0.68em}\right)}}
// in TeX and KaTeX)
maxDistFromAxis / 500 * delimiterFactor, 2 * maxDistFromAxis - delimiterExtend); // Finally, we defer to `makeCustomSizedDelim` with our calculated total
// height
return delimiter_makeCustomSizedDelim(delim, totalHeight, true, options, mode, classes);
};
/* harmony default export */ var delimiter = ({
sqrtImage: makeSqrtImage,
sizedDelim: delimiter_makeSizedDelim,
customSizedDelim: delimiter_makeCustomSizedDelim,
leftRightDelim: makeLeftRightDelim
});
// CONCATENATED MODULE: ./src/functions/delimsizing.js
// Extra data needed for the delimiter handler down below
var delimiterSizes = {
"\\bigl": {
mclass: "mopen",
size: 1
},
"\\Bigl": {
mclass: "mopen",
size: 2
},
"\\biggl": {
mclass: "mopen",
size: 3
},
"\\Biggl": {
mclass: "mopen",
size: 4
},
"\\bigr": {
mclass: "mclose",
size: 1
},
"\\Bigr": {
mclass: "mclose",
size: 2
},
"\\biggr": {
mclass: "mclose",
size: 3
},
"\\Biggr": {
mclass: "mclose",
size: 4
},
"\\bigm": {
mclass: "mrel",
size: 1
},
"\\Bigm": {
mclass: "mrel",
size: 2
},
"\\biggm": {
mclass: "mrel",
size: 3
},
"\\Biggm": {
mclass: "mrel",
size: 4
},
"\\big": {
mclass: "mord",
size: 1
},
"\\Big": {
mclass: "mord",
size: 2
},
"\\bigg": {
mclass: "mord",
size: 3
},
"\\Bigg": {
mclass: "mord",
size: 4
}
};
var delimiters = ["(", "\\lparen", ")", "\\rparen", "[", "\\lbrack", "]", "\\rbrack", "\\{", "\\lbrace", "\\}", "\\rbrace", "\\lfloor", "\\rfloor", "\u230A", "\u230B", "\\lceil", "\\rceil", "\u2308", "\u2309", "<", ">", "\\langle", "\u27E8", "\\rangle", "\u27E9", "\\lt", "\\gt", "\\lvert", "\\rvert", "\\lVert", "\\rVert", "\\lgroup", "\\rgroup", "\u27EE", "\u27EF", "\\lmoustache", "\\rmoustache", "\u23B0", "\u23B1", "/", "\\backslash", "|", "\\vert", "\\|", "\\Vert", "\\uparrow", "\\Uparrow", "\\downarrow", "\\Downarrow", "\\updownarrow", "\\Updownarrow", "."];
// Delimiter functions
function checkDelimiter(delim, context) {
var symDelim = checkSymbolNodeType(delim);
if (symDelim && utils.contains(delimiters, symDelim.text)) {
return symDelim;
} else {
throw new src_ParseError("Invalid delimiter: '" + (symDelim ? symDelim.text : JSON.stringify(delim)) + "' after '" + context.funcName + "'", delim);
}
}
defineFunction({
type: "delimsizing",
names: ["\\bigl", "\\Bigl", "\\biggl", "\\Biggl", "\\bigr", "\\Bigr", "\\biggr", "\\Biggr", "\\bigm", "\\Bigm", "\\biggm", "\\Biggm", "\\big", "\\Big", "\\bigg", "\\Bigg"],
props: {
numArgs: 1
},
handler: function handler(context, args) {
var delim = checkDelimiter(args[0], context);
return {
type: "delimsizing",
mode: context.parser.mode,
size: delimiterSizes[context.funcName].size,
mclass: delimiterSizes[context.funcName].mclass,
delim: delim.text
};
},
htmlBuilder: function htmlBuilder(group, options) {
if (group.delim === ".") {
// Empty delimiters still count as elements, even though they don't
// show anything.
return buildCommon.makeSpan([group.mclass]);
} // Use delimiter.sizedDelim to generate the delimiter.
return delimiter.sizedDelim(group.delim, group.size, options, group.mode, [group.mclass]);
},
mathmlBuilder: function mathmlBuilder(group) {
var children = [];
if (group.delim !== ".") {
children.push(buildMathML_makeText(group.delim, group.mode));
}
var node = new mathMLTree.MathNode("mo", children);
if (group.mclass === "mopen" || group.mclass === "mclose") {
// Only some of the delimsizing functions act as fences, and they
// return "mopen" or "mclose" mclass.
node.setAttribute("fence", "true");
} else {
// Explicitly disable fencing if it's not a fence, to override the
// defaults.
node.setAttribute("fence", "false");
}
return node;
}
});
function assertParsed(group) {
if (!group.body) {
throw new Error("Bug: The leftright ParseNode wasn't fully parsed.");
}
}
defineFunction({
type: "leftright-right",
names: ["\\right"],
props: {
numArgs: 1
},
handler: function handler(context, args) {
// \left case below triggers parsing of \right in
// `const right = parser.parseFunction();`
// uses this return value.
var color = context.parser.gullet.macros.get("\\current@color");
if (color && typeof color !== "string") {
throw new src_ParseError("\\current@color set to non-string in \\right");
}
return {
type: "leftright-right",
mode: context.parser.mode,
delim: checkDelimiter(args[0], context).text,
color: color // undefined if not set via \color
};
}
});
defineFunction({
type: "leftright",
names: ["\\left"],
props: {
numArgs: 1
},
handler: function handler(context, args) {
var delim = checkDelimiter(args[0], context);
var parser = context.parser; // Parse out the implicit body
++parser.leftrightDepth; // parseExpression stops before '\\right'
var body = parser.parseExpression(false);
--parser.leftrightDepth; // Check the next token
parser.expect("\\right", false);
var right = assertNodeType(parser.parseFunction(), "leftright-right");
return {
type: "leftright",
mode: parser.mode,
body: body,
left: delim.text,
right: right.delim,
rightColor: right.color
};
},
htmlBuilder: function htmlBuilder(group, options) {
assertParsed(group); // Build the inner expression
var inner = buildHTML_buildExpression(group.body, options, true, ["mopen", "mclose"]);
var innerHeight = 0;
var innerDepth = 0;
var hadMiddle = false; // Calculate its height and depth
for (var i = 0; i < inner.length; i++) {
// Property `isMiddle` not defined on `span`. See comment in
// "middle"'s htmlBuilder.
// $FlowFixMe
if (inner[i].isMiddle) {
hadMiddle = true;
} else {
innerHeight = Math.max(inner[i].height, innerHeight);
innerDepth = Math.max(inner[i].depth, innerDepth);
}
} // The size of delimiters is the same, regardless of what style we are
// in. Thus, to correctly calculate the size of delimiter we need around
// a group, we scale down the inner size based on the size.
innerHeight *= options.sizeMultiplier;
innerDepth *= options.sizeMultiplier;
var leftDelim;
if (group.left === ".") {
// Empty delimiters in \left and \right make null delimiter spaces.
leftDelim = makeNullDelimiter(options, ["mopen"]);
} else {
// Otherwise, use leftRightDelim to generate the correct sized
// delimiter.
leftDelim = delimiter.leftRightDelim(group.left, innerHeight, innerDepth, options, group.mode, ["mopen"]);
} // Add it to the beginning of the expression
inner.unshift(leftDelim); // Handle middle delimiters
if (hadMiddle) {
for (var _i = 1; _i < inner.length; _i++) {
var middleDelim = inner[_i]; // Property `isMiddle` not defined on `span`. See comment in
// "middle"'s htmlBuilder.
// $FlowFixMe
var isMiddle = middleDelim.isMiddle;
if (isMiddle) {
// Apply the options that were active when \middle was called
inner[_i] = delimiter.leftRightDelim(isMiddle.delim, innerHeight, innerDepth, isMiddle.options, group.mode, []);
}
}
}
var rightDelim; // Same for the right delimiter, but using color specified by \color
if (group.right === ".") {
rightDelim = makeNullDelimiter(options, ["mclose"]);
} else {
var colorOptions = group.rightColor ? options.withColor(group.rightColor) : options;
rightDelim = delimiter.leftRightDelim(group.right, innerHeight, innerDepth, colorOptions, group.mode, ["mclose"]);
} // Add it to the end of the expression.
inner.push(rightDelim);
return buildCommon.makeSpan(["minner"], inner, options);
},
mathmlBuilder: function mathmlBuilder(group, options) {
assertParsed(group);
var inner = buildMathML_buildExpression(group.body, options);
if (group.left !== ".") {
var leftNode = new mathMLTree.MathNode("mo", [buildMathML_makeText(group.left, group.mode)]);
leftNode.setAttribute("fence", "true");
inner.unshift(leftNode);
}
if (group.right !== ".") {
var rightNode = new mathMLTree.MathNode("mo", [buildMathML_makeText(group.right, group.mode)]);
rightNode.setAttribute("fence", "true");
if (group.rightColor) {
rightNode.setAttribute("mathcolor", group.rightColor);
}
inner.push(rightNode);
}
return buildMathML_makeRow(inner);
}
});
defineFunction({
type: "middle",
names: ["\\middle"],
props: {
numArgs: 1
},
handler: function handler(context, args) {
var delim = checkDelimiter(args[0], context);
if (!context.parser.leftrightDepth) {
throw new src_ParseError("\\middle without preceding \\left", delim);
}
return {
type: "middle",
mode: context.parser.mode,
delim: delim.text
};
},
htmlBuilder: function htmlBuilder(group, options) {
var middleDelim;
if (group.delim === ".") {
middleDelim = makeNullDelimiter(options, []);
} else {
middleDelim = delimiter.sizedDelim(group.delim, 1, options, group.mode, []);
var isMiddle = {
delim: group.delim,
options: options
}; // Property `isMiddle` not defined on `span`. It is only used in
// this file above.
// TODO: Fix this violation of the `span` type and possibly rename
// things since `isMiddle` sounds like a boolean, but is a struct.
// $FlowFixMe
middleDelim.isMiddle = isMiddle;
}
return middleDelim;
},
mathmlBuilder: function mathmlBuilder(group, options) {
// A Firefox \middle will strech a character vertically only if it
// is in the fence part of the operator dictionary at:
// https://www.w3.org/TR/MathML3/appendixc.html.
// So we need to avoid U+2223 and use plain "|" instead.
var textNode = group.delim === "\\vert" || group.delim === "|" ? buildMathML_makeText("|", "text") : buildMathML_makeText(group.delim, group.mode);
var middleNode = new mathMLTree.MathNode("mo", [textNode]);
middleNode.setAttribute("fence", "true"); // MathML gives 5/18em spacing to each <mo> element.
// \middle should get delimiter spacing instead.
middleNode.setAttribute("lspace", "0.05em");
middleNode.setAttribute("rspace", "0.05em");
return middleNode;
}
});
// CONCATENATED MODULE: ./src/functions/enclose.js
var enclose_htmlBuilder = function htmlBuilder(group, options) {
// \cancel, \bcancel, \xcancel, \sout, \fbox, \colorbox, \fcolorbox
// Some groups can return document fragments. Handle those by wrapping
// them in a span.
var inner = buildCommon.wrapFragment(buildHTML_buildGroup(group.body, options), options);
var label = group.label.substr(1);
var scale = options.sizeMultiplier;
var img;
var imgShift = 0; // In the LaTeX cancel package, line geometry is slightly different
// depending on whether the subject is wider than it is tall, or vice versa.
// We don't know the width of a group, so as a proxy, we test if
// the subject is a single character. This captures most of the
// subjects that should get the "tall" treatment.
var isSingleChar = utils.isCharacterBox(group.body);
if (label === "sout") {
img = buildCommon.makeSpan(["stretchy", "sout"]);
img.height = options.fontMetrics().defaultRuleThickness / scale;
imgShift = -0.5 * options.fontMetrics().xHeight;
} else {
// Add horizontal padding
if (/cancel/.test(label)) {
if (!isSingleChar) {
inner.classes.push("cancel-pad");
}
} else {
inner.classes.push("boxpad");
} // Add vertical padding
var vertPad = 0;
var ruleThickness = 0; // ref: cancel package: \advance\totalheight2\p@ % "+2"
if (/box/.test(label)) {
ruleThickness = Math.max(options.fontMetrics().fboxrule, // default
options.minRuleThickness // User override.
);
vertPad = options.fontMetrics().fboxsep + (label === "colorbox" ? 0 : ruleThickness);
} else {
vertPad = isSingleChar ? 0.2 : 0;
}
img = stretchy.encloseSpan(inner, label, vertPad, options);
if (/fbox|boxed|fcolorbox/.test(label)) {
img.style.borderStyle = "solid";
img.style.borderWidth = ruleThickness + "em";
}
imgShift = inner.depth + vertPad;
if (group.backgroundColor) {
img.style.backgroundColor = group.backgroundColor;
if (group.borderColor) {
img.style.borderColor = group.borderColor;
}
}
}
var vlist;
if (group.backgroundColor) {
vlist = buildCommon.makeVList({
positionType: "individualShift",
children: [// Put the color background behind inner;
{
type: "elem",
elem: img,
shift: imgShift
}, {
type: "elem",
elem: inner,
shift: 0
}]
}, options);
} else {
vlist = buildCommon.makeVList({
positionType: "individualShift",
children: [// Write the \cancel stroke on top of inner.
{
type: "elem",
elem: inner,
shift: 0
}, {
type: "elem",
elem: img,
shift: imgShift,
wrapperClasses: /cancel/.test(label) ? ["svg-align"] : []
}]
}, options);
}
if (/cancel/.test(label)) {
// The cancel package documentation says that cancel lines add their height
// to the expression, but tests show that isn't how it actually works.
vlist.height = inner.height;
vlist.depth = inner.depth;
}
if (/cancel/.test(label) && !isSingleChar) {
// cancel does not create horiz space for its line extension.
return buildCommon.makeSpan(["mord", "cancel-lap"], [vlist], options);
} else {
return buildCommon.makeSpan(["mord"], [vlist], options);
}
};
var enclose_mathmlBuilder = function mathmlBuilder(group, options) {
var fboxsep = 0;
var node = new mathMLTree.MathNode(group.label.indexOf("colorbox") > -1 ? "mpadded" : "menclose", [buildMathML_buildGroup(group.body, options)]);
switch (group.label) {
case "\\cancel":
node.setAttribute("notation", "updiagonalstrike");
break;
case "\\bcancel":
node.setAttribute("notation", "downdiagonalstrike");
break;
case "\\sout":
node.setAttribute("notation", "horizontalstrike");
break;
case "\\fbox":
node.setAttribute("notation", "box");
break;
case "\\fcolorbox":
case "\\colorbox":
// <menclose> doesn't have a good notation option. So use <mpadded>
// instead. Set some attributes that come included with <menclose>.
fboxsep = options.fontMetrics().fboxsep * options.fontMetrics().ptPerEm;
node.setAttribute("width", "+" + 2 * fboxsep + "pt");
node.setAttribute("height", "+" + 2 * fboxsep + "pt");
node.setAttribute("lspace", fboxsep + "pt"); //
node.setAttribute("voffset", fboxsep + "pt");
if (group.label === "\\fcolorbox") {
var thk = Math.max(options.fontMetrics().fboxrule, // default
options.minRuleThickness // user override
);
node.setAttribute("style", "border: " + thk + "em solid " + String(group.borderColor));
}
break;
case "\\xcancel":
node.setAttribute("notation", "updiagonalstrike downdiagonalstrike");
break;
}
if (group.backgroundColor) {
node.setAttribute("mathbackground", group.backgroundColor);
}
return node;
};
defineFunction({
type: "enclose",
names: ["\\colorbox"],
props: {
numArgs: 2,
allowedInText: true,
greediness: 3,
argTypes: ["color", "text"]
},
handler: function handler(_ref, args, optArgs) {
var parser = _ref.parser,
funcName = _ref.funcName;
var color = assertNodeType(args[0], "color-token").color;
var body = args[1];
return {
type: "enclose",
mode: parser.mode,
label: funcName,
backgroundColor: color,
body: body
};
},
htmlBuilder: enclose_htmlBuilder,
mathmlBuilder: enclose_mathmlBuilder
});
defineFunction({
type: "enclose",
names: ["\\fcolorbox"],
props: {
numArgs: 3,
allowedInText: true,
greediness: 3,
argTypes: ["color", "color", "text"]
},
handler: function handler(_ref2, args, optArgs) {
var parser = _ref2.parser,
funcName = _ref2.funcName;
var borderColor = assertNodeType(args[0], "color-token").color;
var backgroundColor = assertNodeType(args[1], "color-token").color;
var body = args[2];
return {
type: "enclose",
mode: parser.mode,
label: funcName,
backgroundColor: backgroundColor,
borderColor: borderColor,
body: body
};
},
htmlBuilder: enclose_htmlBuilder,
mathmlBuilder: enclose_mathmlBuilder
});
defineFunction({
type: "enclose",
names: ["\\fbox"],
props: {
numArgs: 1,
argTypes: ["hbox"],
allowedInText: true
},
handler: function handler(_ref3, args) {
var parser = _ref3.parser;
return {
type: "enclose",
mode: parser.mode,
label: "\\fbox",
body: args[0]
};
}
});
defineFunction({
type: "enclose",
names: ["\\cancel", "\\bcancel", "\\xcancel", "\\sout"],
props: {
numArgs: 1
},
handler: function handler(_ref4, args, optArgs) {
var parser = _ref4.parser,
funcName = _ref4.funcName;
var body = args[0];
return {
type: "enclose",
mode: parser.mode,
label: funcName,
body: body
};
},
htmlBuilder: enclose_htmlBuilder,
mathmlBuilder: enclose_mathmlBuilder
});
// CONCATENATED MODULE: ./src/defineEnvironment.js
/**
* All registered environments.
* `environments.js` exports this same dictionary again and makes it public.
* `Parser.js` requires this dictionary via `environments.js`.
*/
var _environments = {};
function defineEnvironment(_ref) {
var type = _ref.type,
names = _ref.names,
props = _ref.props,
handler = _ref.handler,
htmlBuilder = _ref.htmlBuilder,
mathmlBuilder = _ref.mathmlBuilder;
// Set default values of environments.
var data = {
type: type,
numArgs: props.numArgs || 0,
greediness: 1,
allowedInText: false,
numOptionalArgs: 0,
handler: handler
};
for (var i = 0; i < names.length; ++i) {
// TODO: The value type of _environments should be a type union of all
// possible `EnvSpec<>` possibilities instead of `EnvSpec<*>`, which is
// an existential type.
// $FlowFixMe
_environments[names[i]] = data;
}
if (htmlBuilder) {
_htmlGroupBuilders[type] = htmlBuilder;
}
if (mathmlBuilder) {
_mathmlGroupBuilders[type] = mathmlBuilder;
}
}
// CONCATENATED MODULE: ./src/environments/array.js
function getHLines(parser) {
// Return an array. The array length = number of hlines.
// Each element in the array tells if the line is dashed.
var hlineInfo = [];
parser.consumeSpaces();
var nxt = parser.fetch().text;
while (nxt === "\\hline" || nxt === "\\hdashline") {
parser.consume();
hlineInfo.push(nxt === "\\hdashline");
parser.consumeSpaces();
nxt = parser.fetch().text;
}
return hlineInfo;
}
/**
* Parse the body of the environment, with rows delimited by \\ and
* columns delimited by &, and create a nested list in row-major order
* with one group per cell. If given an optional argument style
* ("text", "display", etc.), then each cell is cast into that style.
*/
function parseArray(parser, _ref, style) {
var hskipBeforeAndAfter = _ref.hskipBeforeAndAfter,
addJot = _ref.addJot,
cols = _ref.cols,
arraystretch = _ref.arraystretch,
colSeparationType = _ref.colSeparationType;
// Parse body of array with \\ temporarily mapped to \cr
parser.gullet.beginGroup();
parser.gullet.macros.set("\\\\", "\\cr"); // Get current arraystretch if it's not set by the environment
if (!arraystretch) {
var stretch = parser.gullet.expandMacroAsText("\\arraystretch");
if (stretch == null) {
// Default \arraystretch from lttab.dtx
arraystretch = 1;
} else {
arraystretch = parseFloat(stretch);
if (!arraystretch || arraystretch < 0) {
throw new src_ParseError("Invalid \\arraystretch: " + stretch);
}
}
} // Start group for first cell
parser.gullet.beginGroup();
var row = [];
var body = [row];
var rowGaps = [];
var hLinesBeforeRow = []; // Test for \hline at the top of the array.
hLinesBeforeRow.push(getHLines(parser));
while (true) {
// eslint-disable-line no-constant-condition
// Parse each cell in its own group (namespace)
var cell = parser.parseExpression(false, "\\cr");
parser.gullet.endGroup();
parser.gullet.beginGroup();
cell = {
type: "ordgroup",
mode: parser.mode,
body: cell
};
if (style) {
cell = {
type: "styling",
mode: parser.mode,
style: style,
body: [cell]
};
}
row.push(cell);
var next = parser.fetch().text;
if (next === "&") {
parser.consume();
} else if (next === "\\end") {
// Arrays terminate newlines with `\crcr` which consumes a `\cr` if
// the last line is empty.
// NOTE: Currently, `cell` is the last item added into `row`.
if (row.length === 1 && cell.type === "styling" && cell.body[0].body.length === 0) {
body.pop();
}
if (hLinesBeforeRow.length < body.length + 1) {
hLinesBeforeRow.push([]);
}
break;
} else if (next === "\\cr") {
var cr = assertNodeType(parser.parseFunction(), "cr");
rowGaps.push(cr.size); // check for \hline(s) following the row separator
hLinesBeforeRow.push(getHLines(parser));
row = [];
body.push(row);
} else {
throw new src_ParseError("Expected & or \\\\ or \\cr or \\end", parser.nextToken);
}
} // End cell group
parser.gullet.endGroup(); // End array group defining \\
parser.gullet.endGroup();
return {
type: "array",
mode: parser.mode,
addJot: addJot,
arraystretch: arraystretch,
body: body,
cols: cols,
rowGaps: rowGaps,
hskipBeforeAndAfter: hskipBeforeAndAfter,
hLinesBeforeRow: hLinesBeforeRow,
colSeparationType: colSeparationType
};
} // Decides on a style for cells in an array according to whether the given
// environment name starts with the letter 'd'.
function dCellStyle(envName) {
if (envName.substr(0, 1) === "d") {
return "display";
} else {
return "text";
}
}
var array_htmlBuilder = function htmlBuilder(group, options) {
var r;
var c;
var nr = group.body.length;
var hLinesBeforeRow = group.hLinesBeforeRow;
var nc = 0;
var body = new Array(nr);
var hlines = [];
var ruleThickness = Math.max( // From LaTeX \showthe\arrayrulewidth. Equals 0.04 em.
options.fontMetrics().arrayRuleWidth, options.minRuleThickness // User override.
); // Horizontal spacing
var pt = 1 / options.fontMetrics().ptPerEm;
var arraycolsep = 5 * pt; // default value, i.e. \arraycolsep in article.cls
if (group.colSeparationType && group.colSeparationType === "small") {
// We're in a {smallmatrix}. Default column space is \thickspace,
// i.e. 5/18em = 0.2778em, per amsmath.dtx for {smallmatrix}.
// But that needs adjustment because LaTeX applies \scriptstyle to the
// entire array, including the colspace, but this function applies
// \scriptstyle only inside each element.
var localMultiplier = options.havingStyle(src_Style.SCRIPT).sizeMultiplier;
arraycolsep = 0.2778 * (localMultiplier / options.sizeMultiplier);
} // Vertical spacing
var baselineskip = 12 * pt; // see size10.clo
// Default \jot from ltmath.dtx
// TODO(edemaine): allow overriding \jot via \setlength (#687)
var jot = 3 * pt;
var arrayskip = group.arraystretch * baselineskip;
var arstrutHeight = 0.7 * arrayskip; // \strutbox in ltfsstrc.dtx and
var arstrutDepth = 0.3 * arrayskip; // \@arstrutbox in lttab.dtx
var totalHeight = 0; // Set a position for \hline(s) at the top of the array, if any.
function setHLinePos(hlinesInGap) {
for (var i = 0; i < hlinesInGap.length; ++i) {
if (i > 0) {
totalHeight += 0.25;
}
hlines.push({
pos: totalHeight,
isDashed: hlinesInGap[i]
});
}
}
setHLinePos(hLinesBeforeRow[0]);
for (r = 0; r < group.body.length; ++r) {
var inrow = group.body[r];
var height = arstrutHeight; // \@array adds an \@arstrut
var depth = arstrutDepth; // to each tow (via the template)
if (nc < inrow.length) {
nc = inrow.length;
}
var outrow = new Array(inrow.length);
for (c = 0; c < inrow.length; ++c) {
var elt = buildHTML_buildGroup(inrow[c], options);
if (depth < elt.depth) {
depth = elt.depth;
}
if (height < elt.height) {
height = elt.height;
}
outrow[c] = elt;
}
var rowGap = group.rowGaps[r];
var gap = 0;
if (rowGap) {
gap = units_calculateSize(rowGap, options);
if (gap > 0) {
// \@argarraycr
gap += arstrutDepth;
if (depth < gap) {
depth = gap; // \@xargarraycr
}
gap = 0;
}
} // In AMS multiline environments such as aligned and gathered, rows
// correspond to lines that have additional \jot added to the
// \baselineskip via \openup.
if (group.addJot) {
depth += jot;
}
outrow.height = height;
outrow.depth = depth;
totalHeight += height;
outrow.pos = totalHeight;
totalHeight += depth + gap; // \@yargarraycr
body[r] = outrow; // Set a position for \hline(s), if any.
setHLinePos(hLinesBeforeRow[r + 1]);
}
var offset = totalHeight / 2 + options.fontMetrics().axisHeight;
var colDescriptions = group.cols || [];
var cols = [];
var colSep;
var colDescrNum;
for (c = 0, colDescrNum = 0; // Continue while either there are more columns or more column
// descriptions, so trailing separators don't get lost.
c < nc || colDescrNum < colDescriptions.length; ++c, ++colDescrNum) {
var colDescr = colDescriptions[colDescrNum] || {};
var firstSeparator = true;
while (colDescr.type === "separator") {
// If there is more than one separator in a row, add a space
// between them.
if (!firstSeparator) {
colSep = buildCommon.makeSpan(["arraycolsep"], []);
colSep.style.width = options.fontMetrics().doubleRuleSep + "em";
cols.push(colSep);
}
if (colDescr.separator === "|" || colDescr.separator === ":") {
var lineType = colDescr.separator === "|" ? "solid" : "dashed";
var separator = buildCommon.makeSpan(["vertical-separator"], [], options);
separator.style.height = totalHeight + "em";
separator.style.borderRightWidth = ruleThickness + "em";
separator.style.borderRightStyle = lineType;
separator.style.margin = "0 -" + ruleThickness / 2 + "em";
separator.style.verticalAlign = -(totalHeight - offset) + "em";
cols.push(separator);
} else {
throw new src_ParseError("Invalid separator type: " + colDescr.separator);
}
colDescrNum++;
colDescr = colDescriptions[colDescrNum] || {};
firstSeparator = false;
}
if (c >= nc) {
continue;
}
var sepwidth = void 0;
if (c > 0 || group.hskipBeforeAndAfter) {
sepwidth = utils.deflt(colDescr.pregap, arraycolsep);
if (sepwidth !== 0) {
colSep = buildCommon.makeSpan(["arraycolsep"], []);
colSep.style.width = sepwidth + "em";
cols.push(colSep);
}
}
var col = [];
for (r = 0; r < nr; ++r) {
var row = body[r];
var elem = row[c];
if (!elem) {
continue;
}
var shift = row.pos - offset;
elem.depth = row.depth;
elem.height = row.height;
col.push({
type: "elem",
elem: elem,
shift: shift
});
}
col = buildCommon.makeVList({
positionType: "individualShift",
children: col
}, options);
col = buildCommon.makeSpan(["col-align-" + (colDescr.align || "c")], [col]);
cols.push(col);
if (c < nc - 1 || group.hskipBeforeAndAfter) {
sepwidth = utils.deflt(colDescr.postgap, arraycolsep);
if (sepwidth !== 0) {
colSep = buildCommon.makeSpan(["arraycolsep"], []);
colSep.style.width = sepwidth + "em";
cols.push(colSep);
}
}
}
body = buildCommon.makeSpan(["mtable"], cols); // Add \hline(s), if any.
if (hlines.length > 0) {
var line = buildCommon.makeLineSpan("hline", options, ruleThickness);
var dashes = buildCommon.makeLineSpan("hdashline", options, ruleThickness);
var vListElems = [{
type: "elem",
elem: body,
shift: 0
}];
while (hlines.length > 0) {
var hline = hlines.pop();
var lineShift = hline.pos - offset;
if (hline.isDashed) {
vListElems.push({
type: "elem",
elem: dashes,
shift: lineShift
});
} else {
vListElems.push({
type: "elem",
elem: line,
shift: lineShift
});
}
}
body = buildCommon.makeVList({
positionType: "individualShift",
children: vListElems
}, options);
}
return buildCommon.makeSpan(["mord"], [body], options);
};
var alignMap = {
c: "center ",
l: "left ",
r: "right "
};
var array_mathmlBuilder = function mathmlBuilder(group, options) {
var table = new mathMLTree.MathNode("mtable", group.body.map(function (row) {
return new mathMLTree.MathNode("mtr", row.map(function (cell) {
return new mathMLTree.MathNode("mtd", [buildMathML_buildGroup(cell, options)]);
}));
})); // Set column alignment, row spacing, column spacing, and
// array lines by setting attributes on the table element.
// Set the row spacing. In MathML, we specify a gap distance.
// We do not use rowGap[] because MathML automatically increases
// cell height with the height/depth of the element content.
// LaTeX \arraystretch multiplies the row baseline-to-baseline distance.
// We simulate this by adding (arraystretch - 1)em to the gap. This
// does a reasonable job of adjusting arrays containing 1 em tall content.
// The 0.16 and 0.09 values are found emprically. They produce an array
// similar to LaTeX and in which content does not interfere with \hines.
var gap = group.arraystretch === 0.5 ? 0.1 // {smallmatrix}, {subarray}
: 0.16 + group.arraystretch - 1 + (group.addJot ? 0.09 : 0);
table.setAttribute("rowspacing", gap + "em"); // MathML table lines go only between cells.
// To place a line on an edge we'll use <menclose>, if necessary.
var menclose = "";
var align = "";
if (group.cols) {
// Find column alignment, column spacing, and vertical lines.
var cols = group.cols;
var columnLines = "";
var prevTypeWasAlign = false;
var iStart = 0;
var iEnd = cols.length;
if (cols[0].type === "separator") {
menclose += "top ";
iStart = 1;
}
if (cols[cols.length - 1].type === "separator") {
menclose += "bottom ";
iEnd -= 1;
}
for (var i = iStart; i < iEnd; i++) {
if (cols[i].type === "align") {
align += alignMap[cols[i].align];
if (prevTypeWasAlign) {
columnLines += "none ";
}
prevTypeWasAlign = true;
} else if (cols[i].type === "separator") {
// MathML accepts only single lines between cells.
// So we read only the first of consecutive separators.
if (prevTypeWasAlign) {
columnLines += cols[i].separator === "|" ? "solid " : "dashed ";
prevTypeWasAlign = false;
}
}
}
table.setAttribute("columnalign", align.trim());
if (/[sd]/.test(columnLines)) {
table.setAttribute("columnlines", columnLines.trim());
}
} // Set column spacing.
if (group.colSeparationType === "align") {
var _cols = group.cols || [];
var spacing = "";
for (var _i = 1; _i < _cols.length; _i++) {
spacing += _i % 2 ? "0em " : "1em ";
}
table.setAttribute("columnspacing", spacing.trim());
} else if (group.colSeparationType === "alignat") {
table.setAttribute("columnspacing", "0em");
} else if (group.colSeparationType === "small") {
table.setAttribute("columnspacing", "0.2778em");
} else {
table.setAttribute("columnspacing", "1em");
} // Address \hline and \hdashline
var rowLines = "";
var hlines = group.hLinesBeforeRow;
menclose += hlines[0].length > 0 ? "left " : "";
menclose += hlines[hlines.length - 1].length > 0 ? "right " : "";
for (var _i2 = 1; _i2 < hlines.length - 1; _i2++) {
rowLines += hlines[_i2].length === 0 ? "none " // MathML accepts only a single line between rows. Read one element.
: hlines[_i2][0] ? "dashed " : "solid ";
}
if (/[sd]/.test(rowLines)) {
table.setAttribute("rowlines", rowLines.trim());
}
if (menclose !== "") {
table = new mathMLTree.MathNode("menclose", [table]);
table.setAttribute("notation", menclose.trim());
}
if (group.arraystretch && group.arraystretch < 1) {
// A small array. Wrap in scriptstyle so row gap is not too large.
table = new mathMLTree.MathNode("mstyle", [table]);
table.setAttribute("scriptlevel", "1");
}
return table;
}; // Convenience function for aligned and alignedat environments.
var array_alignedHandler = function alignedHandler(context, args) {
var cols = [];
var res = parseArray(context.parser, {
cols: cols,
addJot: true
}, "display"); // Determining number of columns.
// 1. If the first argument is given, we use it as a number of columns,
// and makes sure that each row doesn't exceed that number.
// 2. Otherwise, just count number of columns = maximum number
// of cells in each row ("aligned" mode -- isAligned will be true).
//
// At the same time, prepend empty group {} at beginning of every second
// cell in each row (starting with second cell) so that operators become
// binary. This behavior is implemented in amsmath's \start@aligned.
var numMaths;
var numCols = 0;
var emptyGroup = {
type: "ordgroup",
mode: context.mode,
body: []
};
var ordgroup = checkNodeType(args[0], "ordgroup");
if (ordgroup) {
var arg0 = "";
for (var i = 0; i < ordgroup.body.length; i++) {
var textord = assertNodeType(ordgroup.body[i], "textord");
arg0 += textord.text;
}
numMaths = Number(arg0);
numCols = numMaths * 2;
}
var isAligned = !numCols;
res.body.forEach(function (row) {
for (var _i3 = 1; _i3 < row.length; _i3 += 2) {
// Modify ordgroup node within styling node
var styling = assertNodeType(row[_i3], "styling");
var _ordgroup = assertNodeType(styling.body[0], "ordgroup");
_ordgroup.body.unshift(emptyGroup);
}
if (!isAligned) {
// Case 1
var curMaths = row.length / 2;
if (numMaths < curMaths) {
throw new src_ParseError("Too many math in a row: " + ("expected " + numMaths + ", but got " + curMaths), row[0]);
}
} else if (numCols < row.length) {
// Case 2
numCols = row.length;
}
}); // Adjusting alignment.
// In aligned mode, we add one \qquad between columns;
// otherwise we add nothing.
for (var _i4 = 0; _i4 < numCols; ++_i4) {
var align = "r";
var pregap = 0;
if (_i4 % 2 === 1) {
align = "l";
} else if (_i4 > 0 && isAligned) {
// "aligned" mode.
pregap = 1; // add one \quad
}
cols[_i4] = {
type: "align",
align: align,
pregap: pregap,
postgap: 0
};
}
res.colSeparationType = isAligned ? "align" : "alignat";
return res;
}; // Arrays are part of LaTeX, defined in lttab.dtx so its documentation
// is part of the source2e.pdf file of LaTeX2e source documentation.
// {darray} is an {array} environment where cells are set in \displaystyle,
// as defined in nccmath.sty.
defineEnvironment({
type: "array",
names: ["array", "darray"],
props: {
numArgs: 1
},
handler: function handler(context, args) {
// Since no types are specified above, the two possibilities are
// - The argument is wrapped in {} or [], in which case Parser's
// parseGroup() returns an "ordgroup" wrapping some symbol node.
// - The argument is a bare symbol node.
var symNode = checkSymbolNodeType(args[0]);
var colalign = symNode ? [args[0]] : assertNodeType(args[0], "ordgroup").body;
var cols = colalign.map(function (nde) {
var node = assertSymbolNodeType(nde);
var ca = node.text;
if ("lcr".indexOf(ca) !== -1) {
return {
type: "align",
align: ca
};
} else if (ca === "|") {
return {
type: "separator",
separator: "|"
};
} else if (ca === ":") {
return {
type: "separator",
separator: ":"
};
}
throw new src_ParseError("Unknown column alignment: " + ca, nde);
});
var res = {
cols: cols,
hskipBeforeAndAfter: true // \@preamble in lttab.dtx
};
return parseArray(context.parser, res, dCellStyle(context.envName));
},
htmlBuilder: array_htmlBuilder,
mathmlBuilder: array_mathmlBuilder
}); // The matrix environments of amsmath builds on the array environment
// of LaTeX, which is discussed above.
defineEnvironment({
type: "array",
names: ["matrix", "pmatrix", "bmatrix", "Bmatrix", "vmatrix", "Vmatrix"],
props: {
numArgs: 0
},
handler: function handler(context) {
var delimiters = {
"matrix": null,
"pmatrix": ["(", ")"],
"bmatrix": ["[", "]"],
"Bmatrix": ["\\{", "\\}"],
"vmatrix": ["|", "|"],
"Vmatrix": ["\\Vert", "\\Vert"]
}[context.envName]; // \hskip -\arraycolsep in amsmath
var payload = {
hskipBeforeAndAfter: false
};
var res = parseArray(context.parser, payload, dCellStyle(context.envName));
return delimiters ? {
type: "leftright",
mode: context.mode,
body: [res],
left: delimiters[0],
right: delimiters[1],
rightColor: undefined // \right uninfluenced by \color in array
} : res;
},
htmlBuilder: array_htmlBuilder,
mathmlBuilder: array_mathmlBuilder
});
defineEnvironment({
type: "array",
names: ["smallmatrix"],
props: {
numArgs: 0
},
handler: function handler(context) {
var payload = {
arraystretch: 0.5
};
var res = parseArray(context.parser, payload, "script");
res.colSeparationType = "small";
return res;
},
htmlBuilder: array_htmlBuilder,
mathmlBuilder: array_mathmlBuilder
});
defineEnvironment({
type: "array",
names: ["subarray"],
props: {
numArgs: 1
},
handler: function handler(context, args) {
// Parsing of {subarray} is similar to {array}
var symNode = checkSymbolNodeType(args[0]);
var colalign = symNode ? [args[0]] : assertNodeType(args[0], "ordgroup").body;
var cols = colalign.map(function (nde) {
var node = assertSymbolNodeType(nde);
var ca = node.text; // {subarray} only recognizes "l" & "c"
if ("lc".indexOf(ca) !== -1) {
return {
type: "align",
align: ca
};
}
throw new src_ParseError("Unknown column alignment: " + ca, nde);
});
if (cols.length > 1) {
throw new src_ParseError("{subarray} can contain only one column");
}
var res = {
cols: cols,
hskipBeforeAndAfter: false,
arraystretch: 0.5
};
res = parseArray(context.parser, res, "script");
if (res.body[0].length > 1) {
throw new src_ParseError("{subarray} can contain only one column");
}
return res;
},
htmlBuilder: array_htmlBuilder,
mathmlBuilder: array_mathmlBuilder
}); // A cases environment (in amsmath.sty) is almost equivalent to
// \def\arraystretch{1.2}%
// \left\{\begin{array}{@{}l@{\quad}l@{}} … \end{array}\right.
// {dcases} is a {cases} environment where cells are set in \displaystyle,
// as defined in mathtools.sty.
defineEnvironment({
type: "array",
names: ["cases", "dcases"],
props: {
numArgs: 0
},
handler: function handler(context) {
var payload = {
arraystretch: 1.2,
cols: [{
type: "align",
align: "l",
pregap: 0,
// TODO(kevinb) get the current style.
// For now we use the metrics for TEXT style which is what we were
// doing before. Before attempting to get the current style we
// should look at TeX's behavior especially for \over and matrices.
postgap: 1.0
/* 1em quad */
}, {
type: "align",
align: "l",
pregap: 0,
postgap: 0
}]
};
var res = parseArray(context.parser, payload, dCellStyle(context.envName));
return {
type: "leftright",
mode: context.mode,
body: [res],
left: "\\{",
right: ".",
rightColor: undefined
};
},
htmlBuilder: array_htmlBuilder,
mathmlBuilder: array_mathmlBuilder
}); // An aligned environment is like the align* environment
// except it operates within math mode.
// Note that we assume \nomallineskiplimit to be zero,
// so that \strut@ is the same as \strut.
defineEnvironment({
type: "array",
names: ["aligned"],
props: {
numArgs: 0
},
handler: array_alignedHandler,
htmlBuilder: array_htmlBuilder,
mathmlBuilder: array_mathmlBuilder
}); // A gathered environment is like an array environment with one centered
// column, but where rows are considered lines so get \jot line spacing
// and contents are set in \displaystyle.
defineEnvironment({
type: "array",
names: ["gathered"],
props: {
numArgs: 0
},
handler: function handler(context) {
var res = {
cols: [{
type: "align",
align: "c"
}],
addJot: true
};
return parseArray(context.parser, res, "display");
},
htmlBuilder: array_htmlBuilder,
mathmlBuilder: array_mathmlBuilder
}); // alignat environment is like an align environment, but one must explicitly
// specify maximum number of columns in each row, and can adjust spacing between
// each columns.
defineEnvironment({
type: "array",
names: ["alignedat"],
// One for numbered and for unnumbered;
// but, KaTeX doesn't supports math numbering yet,
// they make no difference for now.
props: {
numArgs: 1
},
handler: array_alignedHandler,
htmlBuilder: array_htmlBuilder,
mathmlBuilder: array_mathmlBuilder
}); // Catch \hline outside array environment
defineFunction({
type: "text",
// Doesn't matter what this is.
names: ["\\hline", "\\hdashline"],
props: {
numArgs: 0,
allowedInText: true,
allowedInMath: true
},
handler: function handler(context, args) {
throw new src_ParseError(context.funcName + " valid only within array environment");
}
});
// CONCATENATED MODULE: ./src/environments.js
var environments = _environments;
/* harmony default export */ var src_environments = (environments); // All environment definitions should be imported below
// CONCATENATED MODULE: ./src/functions/environment.js
// Environment delimiters. HTML/MathML rendering is defined in the corresponding
// defineEnvironment definitions.
// $FlowFixMe, "environment" handler returns an environment ParseNode
defineFunction({
type: "environment",
names: ["\\begin", "\\end"],
props: {
numArgs: 1,
argTypes: ["text"]
},
handler: function handler(_ref, args) {
var parser = _ref.parser,
funcName = _ref.funcName;
var nameGroup = args[0];
if (nameGroup.type !== "ordgroup") {
throw new src_ParseError("Invalid environment name", nameGroup);
}
var envName = "";
for (var i = 0; i < nameGroup.body.length; ++i) {
envName += assertNodeType(nameGroup.body[i], "textord").text;
}
if (funcName === "\\begin") {
// begin...end is similar to left...right
if (!src_environments.hasOwnProperty(envName)) {
throw new src_ParseError("No such environment: " + envName, nameGroup);
} // Build the environment object. Arguments and other information will
// be made available to the begin and end methods using properties.
var env = src_environments[envName];
var _parser$parseArgument = parser.parseArguments("\\begin{" + envName + "}", env),
_args = _parser$parseArgument.args,
optArgs = _parser$parseArgument.optArgs;
var context = {
mode: parser.mode,
envName: envName,
parser: parser
};
var result = env.handler(context, _args, optArgs);
parser.expect("\\end", false);
var endNameToken = parser.nextToken;
var end = assertNodeType(parser.parseFunction(), "environment");
if (end.name !== envName) {
throw new src_ParseError("Mismatch: \\begin{" + envName + "} matched by \\end{" + end.name + "}", endNameToken);
}
return result;
}
return {
type: "environment",
mode: parser.mode,
name: envName,
nameGroup: nameGroup
};
}
});
// CONCATENATED MODULE: ./src/functions/mclass.js
var mclass_makeSpan = buildCommon.makeSpan;
function mclass_htmlBuilder(group, options) {
var elements = buildHTML_buildExpression(group.body, options, true);
return mclass_makeSpan([group.mclass], elements, options);
}
function mclass_mathmlBuilder(group, options) {
var node;
var inner = buildMathML_buildExpression(group.body, options);
if (group.mclass === "minner") {
return mathMLTree.newDocumentFragment(inner);
} else if (group.mclass === "mord") {
if (group.isCharacterBox) {
node = inner[0];
node.type = "mi";
} else {
node = new mathMLTree.MathNode("mi", inner);
}
} else {
if (group.isCharacterBox) {
node = inner[0];
node.type = "mo";
} else {
node = new mathMLTree.MathNode("mo", inner);
} // Set spacing based on what is the most likely adjacent atom type.
// See TeXbook p170.
if (group.mclass === "mbin") {
node.attributes.lspace = "0.22em"; // medium space
node.attributes.rspace = "0.22em";
} else if (group.mclass === "mpunct") {
node.attributes.lspace = "0em";
node.attributes.rspace = "0.17em"; // thinspace
} else if (group.mclass === "mopen" || group.mclass === "mclose") {
node.attributes.lspace = "0em";
node.attributes.rspace = "0em";
} // MathML <mo> default space is 5/18 em, so <mrel> needs no action.
// Ref: https://developer.mozilla.org/en-US/docs/Web/MathML/Element/mo
}
return node;
} // Math class commands except \mathop
defineFunction({
type: "mclass",
names: ["\\mathord", "\\mathbin", "\\mathrel", "\\mathopen", "\\mathclose", "\\mathpunct", "\\mathinner"],
props: {
numArgs: 1
},
handler: function handler(_ref, args) {
var parser = _ref.parser,
funcName = _ref.funcName;
var body = args[0];
return {
type: "mclass",
mode: parser.mode,
mclass: "m" + funcName.substr(5),
// TODO(kevinb): don't prefix with 'm'
body: defineFunction_ordargument(body),
isCharacterBox: utils.isCharacterBox(body)
};
},
htmlBuilder: mclass_htmlBuilder,
mathmlBuilder: mclass_mathmlBuilder
});
var binrelClass = function binrelClass(arg) {
// \binrel@ spacing varies with (bin|rel|ord) of the atom in the argument.
// (by rendering separately and with {}s before and after, and measuring
// the change in spacing). We'll do roughly the same by detecting the
// atom type directly.
var atom = arg.type === "ordgroup" && arg.body.length ? arg.body[0] : arg;
if (atom.type === "atom" && (atom.family === "bin" || atom.family === "rel")) {
return "m" + atom.family;
} else {
return "mord";
}
}; // \@binrel{x}{y} renders like y but as mbin/mrel/mord if x is mbin/mrel/mord.
// This is equivalent to \binrel@{x}\binrel@@{y} in AMSTeX.
defineFunction({
type: "mclass",
names: ["\\@binrel"],
props: {
numArgs: 2
},
handler: function handler(_ref2, args) {
var parser = _ref2.parser;
return {
type: "mclass",
mode: parser.mode,
mclass: binrelClass(args[0]),
body: [args[1]],
isCharacterBox: utils.isCharacterBox(args[1])
};
}
}); // Build a relation or stacked op by placing one symbol on top of another
defineFunction({
type: "mclass",
names: ["\\stackrel", "\\overset", "\\underset"],
props: {
numArgs: 2
},
handler: function handler(_ref3, args) {
var parser = _ref3.parser,
funcName = _ref3.funcName;
var baseArg = args[1];
var shiftedArg = args[0];
var mclass;
if (funcName !== "\\stackrel") {
// LaTeX applies \binrel spacing to \overset and \underset.
mclass = binrelClass(baseArg);
} else {
mclass = "mrel"; // for \stackrel
}
var baseOp = {
type: "op",
mode: baseArg.mode,
limits: true,
alwaysHandleSupSub: true,
parentIsSupSub: false,
symbol: false,
suppressBaseShift: funcName !== "\\stackrel",
body: defineFunction_ordargument(baseArg)
};
var supsub = {
type: "supsub",
mode: shiftedArg.mode,
base: baseOp,
sup: funcName === "\\underset" ? null : shiftedArg,
sub: funcName === "\\underset" ? shiftedArg : null
};
return {
type: "mclass",
mode: parser.mode,
mclass: mclass,
body: [supsub],
isCharacterBox: utils.isCharacterBox(supsub)
};
},
htmlBuilder: mclass_htmlBuilder,
mathmlBuilder: mclass_mathmlBuilder
});
// CONCATENATED MODULE: ./src/functions/font.js
// TODO(kevinb): implement \\sl and \\sc
var font_htmlBuilder = function htmlBuilder(group, options) {
var font = group.font;
var newOptions = options.withFont(font);
return buildHTML_buildGroup(group.body, newOptions);
};
var font_mathmlBuilder = function mathmlBuilder(group, options) {
var font = group.font;
var newOptions = options.withFont(font);
return buildMathML_buildGroup(group.body, newOptions);
};
var fontAliases = {
"\\Bbb": "\\mathbb",
"\\bold": "\\mathbf",
"\\frak": "\\mathfrak",
"\\bm": "\\boldsymbol"
};
defineFunction({
type: "font",
names: [// styles, except \boldsymbol defined below
"\\mathrm", "\\mathit", "\\mathbf", "\\mathnormal", // families
"\\mathbb", "\\mathcal", "\\mathfrak", "\\mathscr", "\\mathsf", "\\mathtt", // aliases, except \bm defined below
"\\Bbb", "\\bold", "\\frak"],
props: {
numArgs: 1,
greediness: 2
},
handler: function handler(_ref, args) {
var parser = _ref.parser,
funcName = _ref.funcName;
var body = args[0];
var func = funcName;
if (func in fontAliases) {
func = fontAliases[func];
}
return {
type: "font",
mode: parser.mode,
font: func.slice(1),
body: body
};
},
htmlBuilder: font_htmlBuilder,
mathmlBuilder: font_mathmlBuilder
});
defineFunction({
type: "mclass",
names: ["\\boldsymbol", "\\bm"],
props: {
numArgs: 1,
greediness: 2
},
handler: function handler(_ref2, args) {
var parser = _ref2.parser;
var body = args[0];
var isCharacterBox = utils.isCharacterBox(body); // amsbsy.sty's \boldsymbol uses \binrel spacing to inherit the
// argument's bin|rel|ord status
return {
type: "mclass",
mode: parser.mode,
mclass: binrelClass(body),
body: [{
type: "font",
mode: parser.mode,
font: "boldsymbol",
body: body
}],
isCharacterBox: isCharacterBox
};
}
}); // Old font changing functions
defineFunction({
type: "font",
names: ["\\rm", "\\sf", "\\tt", "\\bf", "\\it"],
props: {
numArgs: 0,
allowedInText: true
},
handler: function handler(_ref3, args) {
var parser = _ref3.parser,
funcName = _ref3.funcName,
breakOnTokenText = _ref3.breakOnTokenText;
var mode = parser.mode;
var body = parser.parseExpression(true, breakOnTokenText);
var style = "math" + funcName.slice(1);
return {
type: "font",
mode: mode,
font: style,
body: {
type: "ordgroup",
mode: parser.mode,
body: body
}
};
},
htmlBuilder: font_htmlBuilder,
mathmlBuilder: font_mathmlBuilder
});
// CONCATENATED MODULE: ./src/functions/genfrac.js
var genfrac_adjustStyle = function adjustStyle(size, originalStyle) {
// Figure out what style this fraction should be in based on the
// function used
var style = originalStyle;
if (size === "display") {
// Get display style as a default.
// If incoming style is sub/sup, use style.text() to get correct size.
style = style.id >= src_Style.SCRIPT.id ? style.text() : src_Style.DISPLAY;
} else if (size === "text" && style.size === src_Style.DISPLAY.size) {
// We're in a \tfrac but incoming style is displaystyle, so:
style = src_Style.TEXT;
} else if (size === "script") {
style = src_Style.SCRIPT;
} else if (size === "scriptscript") {
style = src_Style.SCRIPTSCRIPT;
}
return style;
};
var genfrac_htmlBuilder = function htmlBuilder(group, options) {
// Fractions are handled in the TeXbook on pages 444-445, rules 15(a-e).
var style = genfrac_adjustStyle(group.size, options.style);
var nstyle = style.fracNum();
var dstyle = style.fracDen();
var newOptions;
newOptions = options.havingStyle(nstyle);
var numerm = buildHTML_buildGroup(group.numer, newOptions, options);
if (group.continued) {
// \cfrac inserts a \strut into the numerator.
// Get \strut dimensions from TeXbook page 353.
var hStrut = 8.5 / options.fontMetrics().ptPerEm;
var dStrut = 3.5 / options.fontMetrics().ptPerEm;
numerm.height = numerm.height < hStrut ? hStrut : numerm.height;
numerm.depth = numerm.depth < dStrut ? dStrut : numerm.depth;
}
newOptions = options.havingStyle(dstyle);
var denomm = buildHTML_buildGroup(group.denom, newOptions, options);
var rule;
var ruleWidth;
var ruleSpacing;
if (group.hasBarLine) {
if (group.barSize) {
ruleWidth = units_calculateSize(group.barSize, options);
rule = buildCommon.makeLineSpan("frac-line", options, ruleWidth);
} else {
rule = buildCommon.makeLineSpan("frac-line", options);
}
ruleWidth = rule.height;
ruleSpacing = rule.height;
} else {
rule = null;
ruleWidth = 0;
ruleSpacing = options.fontMetrics().defaultRuleThickness;
} // Rule 15b
var numShift;
var clearance;
var denomShift;
if (style.size === src_Style.DISPLAY.size || group.size === "display") {
numShift = options.fontMetrics().num1;
if (ruleWidth > 0) {
clearance = 3 * ruleSpacing;
} else {
clearance = 7 * ruleSpacing;
}
denomShift = options.fontMetrics().denom1;
} else {
if (ruleWidth > 0) {
numShift = options.fontMetrics().num2;
clearance = ruleSpacing;
} else {
numShift = options.fontMetrics().num3;
clearance = 3 * ruleSpacing;
}
denomShift = options.fontMetrics().denom2;
}
var frac;
if (!rule) {
// Rule 15c
var candidateClearance = numShift - numerm.depth - (denomm.height - denomShift);
if (candidateClearance < clearance) {
numShift += 0.5 * (clearance - candidateClearance);
denomShift += 0.5 * (clearance - candidateClearance);
}
frac = buildCommon.makeVList({
positionType: "individualShift",
children: [{
type: "elem",
elem: denomm,
shift: denomShift
}, {
type: "elem",
elem: numerm,
shift: -numShift
}]
}, options);
} else {
// Rule 15d
var axisHeight = options.fontMetrics().axisHeight;
if (numShift - numerm.depth - (axisHeight + 0.5 * ruleWidth) < clearance) {
numShift += clearance - (numShift - numerm.depth - (axisHeight + 0.5 * ruleWidth));
}
if (axisHeight - 0.5 * ruleWidth - (denomm.height - denomShift) < clearance) {
denomShift += clearance - (axisHeight - 0.5 * ruleWidth - (denomm.height - denomShift));
}
var midShift = -(axisHeight - 0.5 * ruleWidth);
frac = buildCommon.makeVList({
positionType: "individualShift",
children: [{
type: "elem",
elem: denomm,
shift: denomShift
}, {
type: "elem",
elem: rule,
shift: midShift
}, {
type: "elem",
elem: numerm,
shift: -numShift
}]
}, options);
} // Since we manually change the style sometimes (with \dfrac or \tfrac),
// account for the possible size change here.
newOptions = options.havingStyle(style);
frac.height *= newOptions.sizeMultiplier / options.sizeMultiplier;
frac.depth *= newOptions.sizeMultiplier / options.sizeMultiplier; // Rule 15e
var delimSize;
if (style.size === src_Style.DISPLAY.size) {
delimSize = options.fontMetrics().delim1;
} else {
delimSize = options.fontMetrics().delim2;
}
var leftDelim;
var rightDelim;
if (group.leftDelim == null) {
leftDelim = makeNullDelimiter(options, ["mopen"]);
} else {
leftDelim = delimiter.customSizedDelim(group.leftDelim, delimSize, true, options.havingStyle(style), group.mode, ["mopen"]);
}
if (group.continued) {
rightDelim = buildCommon.makeSpan([]); // zero width for \cfrac
} else if (group.rightDelim == null) {
rightDelim = makeNullDelimiter(options, ["mclose"]);
} else {
rightDelim = delimiter.customSizedDelim(group.rightDelim, delimSize, true, options.havingStyle(style), group.mode, ["mclose"]);
}
return buildCommon.makeSpan(["mord"].concat(newOptions.sizingClasses(options)), [leftDelim, buildCommon.makeSpan(["mfrac"], [frac]), rightDelim], options);
};
var genfrac_mathmlBuilder = function mathmlBuilder(group, options) {
var node = new mathMLTree.MathNode("mfrac", [buildMathML_buildGroup(group.numer, options), buildMathML_buildGroup(group.denom, options)]);
if (!group.hasBarLine) {
node.setAttribute("linethickness", "0px");
} else if (group.barSize) {
var ruleWidth = units_calculateSize(group.barSize, options);
node.setAttribute("linethickness", ruleWidth + "em");
}
var style = genfrac_adjustStyle(group.size, options.style);
if (style.size !== options.style.size) {
node = new mathMLTree.MathNode("mstyle", [node]);
var isDisplay = style.size === src_Style.DISPLAY.size ? "true" : "false";
node.setAttribute("displaystyle", isDisplay);
node.setAttribute("scriptlevel", "0");
}
if (group.leftDelim != null || group.rightDelim != null) {
var withDelims = [];
if (group.leftDelim != null) {
var leftOp = new mathMLTree.MathNode("mo", [new mathMLTree.TextNode(group.leftDelim.replace("\\", ""))]);
leftOp.setAttribute("fence", "true");
withDelims.push(leftOp);
}
withDelims.push(node);
if (group.rightDelim != null) {
var rightOp = new mathMLTree.MathNode("mo", [new mathMLTree.TextNode(group.rightDelim.replace("\\", ""))]);
rightOp.setAttribute("fence", "true");
withDelims.push(rightOp);
}
return buildMathML_makeRow(withDelims);
}
return node;
};
defineFunction({
type: "genfrac",
names: ["\\cfrac", "\\dfrac", "\\frac", "\\tfrac", "\\dbinom", "\\binom", "\\tbinom", "\\\\atopfrac", // cant be entered directly
"\\\\bracefrac", "\\\\brackfrac"],
props: {
numArgs: 2,
greediness: 2
},
handler: function handler(_ref, args) {
var parser = _ref.parser,
funcName = _ref.funcName;
var numer = args[0];
var denom = args[1];
var hasBarLine;
var leftDelim = null;
var rightDelim = null;
var size = "auto";
switch (funcName) {
case "\\cfrac":
case "\\dfrac":
case "\\frac":
case "\\tfrac":
hasBarLine = true;
break;
case "\\\\atopfrac":
hasBarLine = false;
break;
case "\\dbinom":
case "\\binom":
case "\\tbinom":
hasBarLine = false;
leftDelim = "(";
rightDelim = ")";
break;
case "\\\\bracefrac":
hasBarLine = false;
leftDelim = "\\{";
rightDelim = "\\}";
break;
case "\\\\brackfrac":
hasBarLine = false;
leftDelim = "[";
rightDelim = "]";
break;
default:
throw new Error("Unrecognized genfrac command");
}
switch (funcName) {
case "\\cfrac":
case "\\dfrac":
case "\\dbinom":
size = "display";
break;
case "\\tfrac":
case "\\tbinom":
size = "text";
break;
}
return {
type: "genfrac",
mode: parser.mode,
continued: funcName === "\\cfrac",
numer: numer,
denom: denom,
hasBarLine: hasBarLine,
leftDelim: leftDelim,
rightDelim: rightDelim,
size: size,
barSize: null
};
},
htmlBuilder: genfrac_htmlBuilder,
mathmlBuilder: genfrac_mathmlBuilder
}); // Infix generalized fractions -- these are not rendered directly, but replaced
// immediately by one of the variants above.
defineFunction({
type: "infix",
names: ["\\over", "\\choose", "\\atop", "\\brace", "\\brack"],
props: {
numArgs: 0,
infix: true
},
handler: function handler(_ref2) {
var parser = _ref2.parser,
funcName = _ref2.funcName,
token = _ref2.token;
var replaceWith;
switch (funcName) {
case "\\over":
replaceWith = "\\frac";
break;
case "\\choose":
replaceWith = "\\binom";
break;
case "\\atop":
replaceWith = "\\\\atopfrac";
break;
case "\\brace":
replaceWith = "\\\\bracefrac";
break;
case "\\brack":
replaceWith = "\\\\brackfrac";
break;
default:
throw new Error("Unrecognized infix genfrac command");
}
return {
type: "infix",
mode: parser.mode,
replaceWith: replaceWith,
token: token
};
}
});
var stylArray = ["display", "text", "script", "scriptscript"];
var delimFromValue = function delimFromValue(delimString) {
var delim = null;
if (delimString.length > 0) {
delim = delimString;
delim = delim === "." ? null : delim;
}
return delim;
};
defineFunction({
type: "genfrac",
names: ["\\genfrac"],
props: {
numArgs: 6,
greediness: 6,
argTypes: ["math", "math", "size", "text", "math", "math"]
},
handler: function handler(_ref3, args) {
var parser = _ref3.parser;
var numer = args[4];
var denom = args[5]; // Look into the parse nodes to get the desired delimiters.
var leftNode = checkNodeType(args[0], "atom");
if (leftNode) {
leftNode = assertAtomFamily(args[0], "open");
}
var leftDelim = leftNode ? delimFromValue(leftNode.text) : null;
var rightNode = checkNodeType(args[1], "atom");
if (rightNode) {
rightNode = assertAtomFamily(args[1], "close");
}
var rightDelim = rightNode ? delimFromValue(rightNode.text) : null;
var barNode = assertNodeType(args[2], "size");
var hasBarLine;
var barSize = null;
if (barNode.isBlank) {
// \genfrac acts differently than \above.
// \genfrac treats an empty size group as a signal to use a
// standard bar size. \above would see size = 0 and omit the bar.
hasBarLine = true;
} else {
barSize = barNode.value;
hasBarLine = barSize.number > 0;
} // Find out if we want displaystyle, textstyle, etc.
var size = "auto";
var styl = checkNodeType(args[3], "ordgroup");
if (styl) {
if (styl.body.length > 0) {
var textOrd = assertNodeType(styl.body[0], "textord");
size = stylArray[Number(textOrd.text)];
}
} else {
styl = assertNodeType(args[3], "textord");
size = stylArray[Number(styl.text)];
}
return {
type: "genfrac",
mode: parser.mode,
numer: numer,
denom: denom,
continued: false,
hasBarLine: hasBarLine,
barSize: barSize,
leftDelim: leftDelim,
rightDelim: rightDelim,
size: size
};
},
htmlBuilder: genfrac_htmlBuilder,
mathmlBuilder: genfrac_mathmlBuilder
}); // \above is an infix fraction that also defines a fraction bar size.
defineFunction({
type: "infix",
names: ["\\above"],
props: {
numArgs: 1,
argTypes: ["size"],
infix: true
},
handler: function handler(_ref4, args) {
var parser = _ref4.parser,
funcName = _ref4.funcName,
token = _ref4.token;
return {
type: "infix",
mode: parser.mode,
replaceWith: "\\\\abovefrac",
size: assertNodeType(args[0], "size").value,
token: token
};
}
});
defineFunction({
type: "genfrac",
names: ["\\\\abovefrac"],
props: {
numArgs: 3,
argTypes: ["math", "size", "math"]
},
handler: function handler(_ref5, args) {
var parser = _ref5.parser,
funcName = _ref5.funcName;
var numer = args[0];
var barSize = assert(assertNodeType(args[1], "infix").size);
var denom = args[2];
var hasBarLine = barSize.number > 0;
return {
type: "genfrac",
mode: parser.mode,
numer: numer,
denom: denom,
continued: false,
hasBarLine: hasBarLine,
barSize: barSize,
leftDelim: null,
rightDelim: null,
size: "auto"
};
},
htmlBuilder: genfrac_htmlBuilder,
mathmlBuilder: genfrac_mathmlBuilder
});
// CONCATENATED MODULE: ./src/functions/horizBrace.js
// NOTE: Unlike most `htmlBuilder`s, this one handles not only "horizBrace", but
var horizBrace_htmlBuilder = function htmlBuilder(grp, options) {
var style = options.style; // Pull out the `ParseNode<"horizBrace">` if `grp` is a "supsub" node.
var supSubGroup;
var group;
var supSub = checkNodeType(grp, "supsub");
if (supSub) {
// Ref: LaTeX source2e: }}}}\limits}
// i.e. LaTeX treats the brace similar to an op and passes it
// with \limits, so we need to assign supsub style.
supSubGroup = supSub.sup ? buildHTML_buildGroup(supSub.sup, options.havingStyle(style.sup()), options) : buildHTML_buildGroup(supSub.sub, options.havingStyle(style.sub()), options);
group = assertNodeType(supSub.base, "horizBrace");
} else {
group = assertNodeType(grp, "horizBrace");
} // Build the base group
var body = buildHTML_buildGroup(group.base, options.havingBaseStyle(src_Style.DISPLAY)); // Create the stretchy element
var braceBody = stretchy.svgSpan(group, options); // Generate the vlist, with the appropriate kerns ┏━━━━━━━━┓
// This first vlist contains the content and the brace: equation
var vlist;
if (group.isOver) {
vlist = buildCommon.makeVList({
positionType: "firstBaseline",
children: [{
type: "elem",
elem: body
}, {
type: "kern",
size: 0.1
}, {
type: "elem",
elem: braceBody
}]
}, options); // $FlowFixMe: Replace this with passing "svg-align" into makeVList.
vlist.children[0].children[0].children[1].classes.push("svg-align");
} else {
vlist = buildCommon.makeVList({
positionType: "bottom",
positionData: body.depth + 0.1 + braceBody.height,
children: [{
type: "elem",
elem: braceBody
}, {
type: "kern",
size: 0.1
}, {
type: "elem",
elem: body
}]
}, options); // $FlowFixMe: Replace this with passing "svg-align" into makeVList.
vlist.children[0].children[0].children[0].classes.push("svg-align");
}
if (supSubGroup) {
// To write the supsub, wrap the first vlist in another vlist:
// They can't all go in the same vlist, because the note might be
// wider than the equation. We want the equation to control the
// brace width.
// note long note long note
// ┏━━━━━━━━┓ or ┏━━━┓ not ┏━━━━━━━━━┓
// equation eqn eqn
var vSpan = buildCommon.makeSpan(["mord", group.isOver ? "mover" : "munder"], [vlist], options);
if (group.isOver) {
vlist = buildCommon.makeVList({
positionType: "firstBaseline",
children: [{
type: "elem",
elem: vSpan
}, {
type: "kern",
size: 0.2
}, {
type: "elem",
elem: supSubGroup
}]
}, options);
} else {
vlist = buildCommon.makeVList({
positionType: "bottom",
positionData: vSpan.depth + 0.2 + supSubGroup.height + supSubGroup.depth,
children: [{
type: "elem",
elem: supSubGroup
}, {
type: "kern",
size: 0.2
}, {
type: "elem",
elem: vSpan
}]
}, options);
}
}
return buildCommon.makeSpan(["mord", group.isOver ? "mover" : "munder"], [vlist], options);
};
var horizBrace_mathmlBuilder = function mathmlBuilder(group, options) {
var accentNode = stretchy.mathMLnode(group.label);
return new mathMLTree.MathNode(group.isOver ? "mover" : "munder", [buildMathML_buildGroup(group.base, options), accentNode]);
}; // Horizontal stretchy braces
defineFunction({
type: "horizBrace",
names: ["\\overbrace", "\\underbrace"],
props: {
numArgs: 1
},
handler: function handler(_ref, args) {
var parser = _ref.parser,
funcName = _ref.funcName;
return {
type: "horizBrace",
mode: parser.mode,
label: funcName,
isOver: /^\\over/.test(funcName),
base: args[0]
};
},
htmlBuilder: horizBrace_htmlBuilder,
mathmlBuilder: horizBrace_mathmlBuilder
});
// CONCATENATED MODULE: ./src/functions/href.js
defineFunction({
type: "href",
names: ["\\href"],
props: {
numArgs: 2,
argTypes: ["url", "original"],
allowedInText: true
},
handler: function handler(_ref, args) {
var parser = _ref.parser;
var body = args[1];
var href = assertNodeType(args[0], "url").url;
if (!parser.settings.isTrusted({
command: "\\href",
url: href
})) {
return parser.formatUnsupportedCmd("\\href");
}
return {
type: "href",
mode: parser.mode,
href: href,
body: defineFunction_ordargument(body)
};
},
htmlBuilder: function htmlBuilder(group, options) {
var elements = buildHTML_buildExpression(group.body, options, false);
return buildCommon.makeAnchor(group.href, [], elements, options);
},
mathmlBuilder: function mathmlBuilder(group, options) {
var math = buildExpressionRow(group.body, options);
if (!(math instanceof mathMLTree_MathNode)) {
math = new mathMLTree_MathNode("mrow", [math]);
}
math.setAttribute("href", group.href);
return math;
}
});
defineFunction({
type: "href",
names: ["\\url"],
props: {
numArgs: 1,
argTypes: ["url"],
allowedInText: true
},
handler: function handler(_ref2, args) {
var parser = _ref2.parser;
var href = assertNodeType(args[0], "url").url;
if (!parser.settings.isTrusted({
command: "\\url",
url: href
})) {
return parser.formatUnsupportedCmd("\\url");
}
var chars = [];
for (var i = 0; i < href.length; i++) {
var c = href[i];
if (c === "~") {
c = "\\textasciitilde";
}
chars.push({
type: "textord",
mode: "text",
text: c
});
}
var body = {
type: "text",
mode: parser.mode,
font: "\\texttt",
body: chars
};
return {
type: "href",
mode: parser.mode,
href: href,
body: defineFunction_ordargument(body)
};
}
});
// CONCATENATED MODULE: ./src/functions/htmlmathml.js
defineFunction({
type: "htmlmathml",
names: ["\\html@mathml"],
props: {
numArgs: 2,
allowedInText: true
},
handler: function handler(_ref, args) {
var parser = _ref.parser;
return {
type: "htmlmathml",
mode: parser.mode,
html: defineFunction_ordargument(args[0]),
mathml: defineFunction_ordargument(args[1])
};
},
htmlBuilder: function htmlBuilder(group, options) {
var elements = buildHTML_buildExpression(group.html, options, false);
return buildCommon.makeFragment(elements);
},
mathmlBuilder: function mathmlBuilder(group, options) {
return buildExpressionRow(group.mathml, options);
}
});
// CONCATENATED MODULE: ./src/functions/includegraphics.js
var includegraphics_sizeData = function sizeData(str) {
if (/^[-+]? *(\d+(\.\d*)?|\.\d+)$/.test(str)) {
// str is a number with no unit specified.
// default unit is bp, per graphix package.
return {
number: +str,
unit: "bp"
};
} else {
var match = /([-+]?) *(\d+(?:\.\d*)?|\.\d+) *([a-z]{2})/.exec(str);
if (!match) {
throw new src_ParseError("Invalid size: '" + str + "' in \\includegraphics");
}
var data = {
number: +(match[1] + match[2]),
// sign + magnitude, cast to number
unit: match[3]
};
if (!validUnit(data)) {
throw new src_ParseError("Invalid unit: '" + data.unit + "' in \\includegraphics.");
}
return data;
}
};
defineFunction({
type: "includegraphics",
names: ["\\includegraphics"],
props: {
numArgs: 1,
numOptionalArgs: 1,
argTypes: ["raw", "url"],
allowedInText: false
},
handler: function handler(_ref, args, optArgs) {
var parser = _ref.parser;
var width = {
number: 0,
unit: "em"
};
var height = {
number: 0.9,
unit: "em"
}; // sorta character sized.
var totalheight = {
number: 0,
unit: "em"
};
var alt = "";
if (optArgs[0]) {
var attributeStr = assertNodeType(optArgs[0], "raw").string; // Parser.js does not parse key/value pairs. We get a string.
var attributes = attributeStr.split(",");
for (var i = 0; i < attributes.length; i++) {
var keyVal = attributes[i].split("=");
if (keyVal.length === 2) {
var str = keyVal[1].trim();
switch (keyVal[0].trim()) {
case "alt":
alt = str;
break;
case "width":
width = includegraphics_sizeData(str);
break;
case "height":
height = includegraphics_sizeData(str);
break;
case "totalheight":
totalheight = includegraphics_sizeData(str);
break;
default:
throw new src_ParseError("Invalid key: '" + keyVal[0] + "' in \\includegraphics.");
}
}
}
}
var src = assertNodeType(args[0], "url").url;
if (alt === "") {
// No alt given. Use the file name. Strip away the path.
alt = src;
alt = alt.replace(/^.*[\\/]/, '');
alt = alt.substring(0, alt.lastIndexOf('.'));
}
if (!parser.settings.isTrusted({
command: "\\includegraphics",
url: src
})) {
return parser.formatUnsupportedCmd("\\includegraphics");
}
return {
type: "includegraphics",
mode: parser.mode,
alt: alt,
width: width,
height: height,
totalheight: totalheight,
src: src
};
},
htmlBuilder: function htmlBuilder(group, options) {
var height = units_calculateSize(group.height, options);
var depth = 0;
if (group.totalheight.number > 0) {
depth = units_calculateSize(group.totalheight, options) - height;
depth = Number(depth.toFixed(2));
}
var width = 0;
if (group.width.number > 0) {
width = units_calculateSize(group.width, options);
}
var style = {
height: height + depth + "em"
};
if (width > 0) {
style.width = width + "em";
}
if (depth > 0) {
style.verticalAlign = -depth + "em";
}
var node = new domTree_Img(group.src, group.alt, style);
node.height = height;
node.depth = depth;
return node;
},
mathmlBuilder: function mathmlBuilder(group, options) {
var node = new mathMLTree.MathNode("mglyph", []);
node.setAttribute("alt", group.alt);
var height = units_calculateSize(group.height, options);
var depth = 0;
if (group.totalheight.number > 0) {
depth = units_calculateSize(group.totalheight, options) - height;
depth = depth.toFixed(2);
node.setAttribute("valign", "-" + depth + "em");
}
node.setAttribute("height", height + depth + "em");
if (group.width.number > 0) {
var width = units_calculateSize(group.width, options);
node.setAttribute("width", width + "em");
}
node.setAttribute("src", group.src);
return node;
}
});
// CONCATENATED MODULE: ./src/functions/kern.js
// Horizontal spacing commands
// TODO: \hskip and \mskip should support plus and minus in lengths
defineFunction({
type: "kern",
names: ["\\kern", "\\mkern", "\\hskip", "\\mskip"],
props: {
numArgs: 1,
argTypes: ["size"],
allowedInText: true
},
handler: function handler(_ref, args) {
var parser = _ref.parser,
funcName = _ref.funcName;
var size = assertNodeType(args[0], "size");
if (parser.settings.strict) {
var mathFunction = funcName[1] === 'm'; // \mkern, \mskip
var muUnit = size.value.unit === 'mu';
if (mathFunction) {
if (!muUnit) {
parser.settings.reportNonstrict("mathVsTextUnits", "LaTeX's " + funcName + " supports only mu units, " + ("not " + size.value.unit + " units"));
}
if (parser.mode !== "math") {
parser.settings.reportNonstrict("mathVsTextUnits", "LaTeX's " + funcName + " works only in math mode");
}
} else {
// !mathFunction
if (muUnit) {
parser.settings.reportNonstrict("mathVsTextUnits", "LaTeX's " + funcName + " doesn't support mu units");
}
}
}
return {
type: "kern",
mode: parser.mode,
dimension: size.value
};
},
htmlBuilder: function htmlBuilder(group, options) {
return buildCommon.makeGlue(group.dimension, options);
},
mathmlBuilder: function mathmlBuilder(group, options) {
var dimension = units_calculateSize(group.dimension, options);
return new mathMLTree.SpaceNode(dimension);
}
});
// CONCATENATED MODULE: ./src/functions/lap.js
// Horizontal overlap functions
defineFunction({
type: "lap",
names: ["\\mathllap", "\\mathrlap", "\\mathclap"],
props: {
numArgs: 1,
allowedInText: true
},
handler: function handler(_ref, args) {
var parser = _ref.parser,
funcName = _ref.funcName;
var body = args[0];
return {
type: "lap",
mode: parser.mode,
alignment: funcName.slice(5),
body: body
};
},
htmlBuilder: function htmlBuilder(group, options) {
// mathllap, mathrlap, mathclap
var inner;
if (group.alignment === "clap") {
// ref: https://www.math.lsu.edu/~aperlis/publications/mathclap/
inner = buildCommon.makeSpan([], [buildHTML_buildGroup(group.body, options)]); // wrap, since CSS will center a .clap > .inner > span
inner = buildCommon.makeSpan(["inner"], [inner], options);
} else {
inner = buildCommon.makeSpan(["inner"], [buildHTML_buildGroup(group.body, options)]);
}
var fix = buildCommon.makeSpan(["fix"], []);
var node = buildCommon.makeSpan([group.alignment], [inner, fix], options); // At this point, we have correctly set horizontal alignment of the
// two items involved in the lap.
// Next, use a strut to set the height of the HTML bounding box.
// Otherwise, a tall argument may be misplaced.
var strut = buildCommon.makeSpan(["strut"]);
strut.style.height = node.height + node.depth + "em";
strut.style.verticalAlign = -node.depth + "em";
node.children.unshift(strut); // Next, prevent vertical misplacement when next to something tall.
node = buildCommon.makeVList({
positionType: "firstBaseline",
children: [{
type: "elem",
elem: node
}]
}, options); // Get the horizontal spacing correct relative to adjacent items.
return buildCommon.makeSpan(["mord"], [node], options);
},
mathmlBuilder: function mathmlBuilder(group, options) {
// mathllap, mathrlap, mathclap
var node = new mathMLTree.MathNode("mpadded", [buildMathML_buildGroup(group.body, options)]);
if (group.alignment !== "rlap") {
var offset = group.alignment === "llap" ? "-1" : "-0.5";
node.setAttribute("lspace", offset + "width");
}
node.setAttribute("width", "0px");
return node;
}
});
// CONCATENATED MODULE: ./src/functions/math.js
// Switching from text mode back to math mode
defineFunction({
type: "styling",
names: ["\\(", "$"],
props: {
numArgs: 0,
allowedInText: true,
allowedInMath: false
},
handler: function handler(_ref, args) {
var funcName = _ref.funcName,
parser = _ref.parser;
var outerMode = parser.mode;
parser.switchMode("math");
var close = funcName === "\\(" ? "\\)" : "$";
var body = parser.parseExpression(false, close);
parser.expect(close);
parser.switchMode(outerMode);
return {
type: "styling",
mode: parser.mode,
style: "text",
body: body
};
}
}); // Check for extra closing math delimiters
defineFunction({
type: "text",
// Doesn't matter what this is.
names: ["\\)", "\\]"],
props: {
numArgs: 0,
allowedInText: true,
allowedInMath: false
},
handler: function handler(context, args) {
throw new src_ParseError("Mismatched " + context.funcName);
}
});
// CONCATENATED MODULE: ./src/functions/mathchoice.js
var mathchoice_chooseMathStyle = function chooseMathStyle(group, options) {
switch (options.style.size) {
case src_Style.DISPLAY.size:
return group.display;
case src_Style.TEXT.size:
return group.text;
case src_Style.SCRIPT.size:
return group.script;
case src_Style.SCRIPTSCRIPT.size:
return group.scriptscript;
default:
return group.text;
}
};
defineFunction({
type: "mathchoice",
names: ["\\mathchoice"],
props: {
numArgs: 4
},
handler: function handler(_ref, args) {
var parser = _ref.parser;
return {
type: "mathchoice",
mode: parser.mode,
display: defineFunction_ordargument(args[0]),
text: defineFunction_ordargument(args[1]),
script: defineFunction_ordargument(args[2]),
scriptscript: defineFunction_ordargument(args[3])
};
},
htmlBuilder: function htmlBuilder(group, options) {
var body = mathchoice_chooseMathStyle(group, options);
var elements = buildHTML_buildExpression(body, options, false);
return buildCommon.makeFragment(elements);
},
mathmlBuilder: function mathmlBuilder(group, options) {
var body = mathchoice_chooseMathStyle(group, options);
return buildExpressionRow(body, options);
}
});
// CONCATENATED MODULE: ./src/functions/utils/assembleSupSub.js
// For an operator with limits, assemble the base, sup, and sub into a span.
var assembleSupSub_assembleSupSub = function assembleSupSub(base, supGroup, subGroup, options, style, slant, baseShift) {
// IE 8 clips \int if it is in a display: inline-block. We wrap it
// in a new span so it is an inline, and works.
base = buildCommon.makeSpan([], [base]);
var sub;
var sup; // We manually have to handle the superscripts and subscripts. This,
// aside from the kern calculations, is copied from supsub.
if (supGroup) {
var elem = buildHTML_buildGroup(supGroup, options.havingStyle(style.sup()), options);
sup = {
elem: elem,
kern: Math.max(options.fontMetrics().bigOpSpacing1, options.fontMetrics().bigOpSpacing3 - elem.depth)
};
}
if (subGroup) {
var _elem = buildHTML_buildGroup(subGroup, options.havingStyle(style.sub()), options);
sub = {
elem: _elem,
kern: Math.max(options.fontMetrics().bigOpSpacing2, options.fontMetrics().bigOpSpacing4 - _elem.height)
};
} // Build the final group as a vlist of the possible subscript, base,
// and possible superscript.
var finalGroup;
if (sup && sub) {
var bottom = options.fontMetrics().bigOpSpacing5 + sub.elem.height + sub.elem.depth + sub.kern + base.depth + baseShift;
finalGroup = buildCommon.makeVList({
positionType: "bottom",
positionData: bottom,
children: [{
type: "kern",
size: options.fontMetrics().bigOpSpacing5
}, {
type: "elem",
elem: sub.elem,
marginLeft: -slant + "em"
}, {
type: "kern",
size: sub.kern
}, {
type: "elem",
elem: base
}, {
type: "kern",
size: sup.kern
}, {
type: "elem",
elem: sup.elem,
marginLeft: slant + "em"
}, {
type: "kern",
size: options.fontMetrics().bigOpSpacing5
}]
}, options);
} else if (sub) {
var top = base.height - baseShift; // Shift the limits by the slant of the symbol. Note
// that we are supposed to shift the limits by 1/2 of the slant,
// but since we are centering the limits adding a full slant of
// margin will shift by 1/2 that.
finalGroup = buildCommon.makeVList({
positionType: "top",
positionData: top,
children: [{
type: "kern",
size: options.fontMetrics().bigOpSpacing5
}, {
type: "elem",
elem: sub.elem,
marginLeft: -slant + "em"
}, {
type: "kern",
size: sub.kern
}, {
type: "elem",
elem: base
}]
}, options);
} else if (sup) {
var _bottom = base.depth + baseShift;
finalGroup = buildCommon.makeVList({
positionType: "bottom",
positionData: _bottom,
children: [{
type: "elem",
elem: base
}, {
type: "kern",
size: sup.kern
}, {
type: "elem",
elem: sup.elem,
marginLeft: slant + "em"
}, {
type: "kern",
size: options.fontMetrics().bigOpSpacing5
}]
}, options);
} else {
// This case probably shouldn't occur (this would mean the
// supsub was sending us a group with no superscript or
// subscript) but be safe.
return base;
}
return buildCommon.makeSpan(["mop", "op-limits"], [finalGroup], options);
};
// CONCATENATED MODULE: ./src/functions/op.js
// Limits, symbols
// Most operators have a large successor symbol, but these don't.
var noSuccessor = ["\\smallint"]; // NOTE: Unlike most `htmlBuilder`s, this one handles not only "op", but also
// "supsub" since some of them (like \int) can affect super/subscripting.
var op_htmlBuilder = function htmlBuilder(grp, options) {
// Operators are handled in the TeXbook pg. 443-444, rule 13(a).
var supGroup;
var subGroup;
var hasLimits = false;
var group;
var supSub = checkNodeType(grp, "supsub");
if (supSub) {
// If we have limits, supsub will pass us its group to handle. Pull
// out the superscript and subscript and set the group to the op in
// its base.
supGroup = supSub.sup;
subGroup = supSub.sub;
group = assertNodeType(supSub.base, "op");
hasLimits = true;
} else {
group = assertNodeType(grp, "op");
}
var style = options.style;
var large = false;
if (style.size === src_Style.DISPLAY.size && group.symbol && !utils.contains(noSuccessor, group.name)) {
// Most symbol operators get larger in displaystyle (rule 13)
large = true;
}
var base;
if (group.symbol) {
// If this is a symbol, create the symbol.
var fontName = large ? "Size2-Regular" : "Size1-Regular";
var stash = "";
if (group.name === "\\oiint" || group.name === "\\oiiint") {
// No font glyphs yet, so use a glyph w/o the oval.
// TODO: When font glyphs are available, delete this code.
stash = group.name.substr(1); // $FlowFixMe
group.name = stash === "oiint" ? "\\iint" : "\\iiint";
}
base = buildCommon.makeSymbol(group.name, fontName, "math", options, ["mop", "op-symbol", large ? "large-op" : "small-op"]);
if (stash.length > 0) {
// We're in \oiint or \oiiint. Overlay the oval.
// TODO: When font glyphs are available, delete this code.
var italic = base.italic;
var oval = buildCommon.staticSvg(stash + "Size" + (large ? "2" : "1"), options);
base = buildCommon.makeVList({
positionType: "individualShift",
children: [{
type: "elem",
elem: base,
shift: 0
}, {
type: "elem",
elem: oval,
shift: large ? 0.08 : 0
}]
}, options); // $FlowFixMe
group.name = "\\" + stash;
base.classes.unshift("mop"); // $FlowFixMe
base.italic = italic;
}
} else if (group.body) {
// If this is a list, compose that list.
var inner = buildHTML_buildExpression(group.body, options, true);
if (inner.length === 1 && inner[0] instanceof domTree_SymbolNode) {
base = inner[0];
base.classes[0] = "mop"; // replace old mclass
} else {
base = buildCommon.makeSpan(["mop"], buildCommon.tryCombineChars(inner), options);
}
} else {
// Otherwise, this is a text operator. Build the text from the
// operator's name.
// TODO(emily): Add a space in the middle of some of these
// operators, like \limsup
var output = [];
for (var i = 1; i < group.name.length; i++) {
output.push(buildCommon.mathsym(group.name[i], group.mode, options));
}
base = buildCommon.makeSpan(["mop"], output, options);
} // If content of op is a single symbol, shift it vertically.
var baseShift = 0;
var slant = 0;
if ((base instanceof domTree_SymbolNode || group.name === "\\oiint" || group.name === "\\oiiint") && !group.suppressBaseShift) {
// We suppress the shift of the base of \overset and \underset. Otherwise,
// shift the symbol so its center lies on the axis (rule 13). It
// appears that our fonts have the centers of the symbols already
// almost on the axis, so these numbers are very small. Note we
// don't actually apply this here, but instead it is used either in
// the vlist creation or separately when there are no limits.
baseShift = (base.height - base.depth) / 2 - options.fontMetrics().axisHeight; // The slant of the symbol is just its italic correction.
// $FlowFixMe
slant = base.italic;
}
if (hasLimits) {
return assembleSupSub_assembleSupSub(base, supGroup, subGroup, options, style, slant, baseShift);
} else {
if (baseShift) {
base.style.position = "relative";
base.style.top = baseShift + "em";
}
return base;
}
};
var op_mathmlBuilder = function mathmlBuilder(group, options) {
var node;
if (group.symbol) {
// This is a symbol. Just add the symbol.
node = new mathMLTree_MathNode("mo", [buildMathML_makeText(group.name, group.mode)]);
if (utils.contains(noSuccessor, group.name)) {
node.setAttribute("largeop", "false");
}
} else if (group.body) {
// This is an operator with children. Add them.
node = new mathMLTree_MathNode("mo", buildMathML_buildExpression(group.body, options));
} else {
// This is a text operator. Add all of the characters from the
// operator's name.
node = new mathMLTree_MathNode("mi", [new mathMLTree_TextNode(group.name.slice(1))]); // Append an <mo>&ApplyFunction;</mo>.
// ref: https://www.w3.org/TR/REC-MathML/chap3_2.html#sec3.2.4
var operator = new mathMLTree_MathNode("mo", [buildMathML_makeText("\u2061", "text")]);
if (group.parentIsSupSub) {
node = new mathMLTree_MathNode("mo", [node, operator]);
} else {
node = newDocumentFragment([node, operator]);
}
}
return node;
};
var singleCharBigOps = {
"\u220F": "\\prod",
"\u2210": "\\coprod",
"\u2211": "\\sum",
"\u22C0": "\\bigwedge",
"\u22C1": "\\bigvee",
"\u22C2": "\\bigcap",
"\u22C3": "\\bigcup",
"\u2A00": "\\bigodot",
"\u2A01": "\\bigoplus",
"\u2A02": "\\bigotimes",
"\u2A04": "\\biguplus",
"\u2A06": "\\bigsqcup"
};
defineFunction({
type: "op",
names: ["\\coprod", "\\bigvee", "\\bigwedge", "\\biguplus", "\\bigcap", "\\bigcup", "\\intop", "\\prod", "\\sum", "\\bigotimes", "\\bigoplus", "\\bigodot", "\\bigsqcup", "\\smallint", "\u220F", "\u2210", "\u2211", "\u22C0", "\u22C1", "\u22C2", "\u22C3", "\u2A00", "\u2A01", "\u2A02", "\u2A04", "\u2A06"],
props: {
numArgs: 0
},
handler: function handler(_ref, args) {
var parser = _ref.parser,
funcName = _ref.funcName;
var fName = funcName;
if (fName.length === 1) {
fName = singleCharBigOps[fName];
}
return {
type: "op",
mode: parser.mode,
limits: true,
parentIsSupSub: false,
symbol: true,
name: fName
};
},
htmlBuilder: op_htmlBuilder,
mathmlBuilder: op_mathmlBuilder
}); // Note: calling defineFunction with a type that's already been defined only
// works because the same htmlBuilder and mathmlBuilder are being used.
defineFunction({
type: "op",
names: ["\\mathop"],
props: {
numArgs: 1
},
handler: function handler(_ref2, args) {
var parser = _ref2.parser;
var body = args[0];
return {
type: "op",
mode: parser.mode,
limits: false,
parentIsSupSub: false,
symbol: false,
body: defineFunction_ordargument(body)
};
},
htmlBuilder: op_htmlBuilder,
mathmlBuilder: op_mathmlBuilder
}); // There are 2 flags for operators; whether they produce limits in
// displaystyle, and whether they are symbols and should grow in
// displaystyle. These four groups cover the four possible choices.
var singleCharIntegrals = {
"\u222B": "\\int",
"\u222C": "\\iint",
"\u222D": "\\iiint",
"\u222E": "\\oint",
"\u222F": "\\oiint",
"\u2230": "\\oiiint"
}; // No limits, not symbols
defineFunction({
type: "op",
names: ["\\arcsin", "\\arccos", "\\arctan", "\\arctg", "\\arcctg", "\\arg", "\\ch", "\\cos", "\\cosec", "\\cosh", "\\cot", "\\cotg", "\\coth", "\\csc", "\\ctg", "\\cth", "\\deg", "\\dim", "\\exp", "\\hom", "\\ker", "\\lg", "\\ln", "\\log", "\\sec", "\\sin", "\\sinh", "\\sh", "\\tan", "\\tanh", "\\tg", "\\th"],
props: {
numArgs: 0
},
handler: function handler(_ref3) {
var parser = _ref3.parser,
funcName = _ref3.funcName;
return {
type: "op",
mode: parser.mode,
limits: false,
parentIsSupSub: false,
symbol: false,
name: funcName
};
},
htmlBuilder: op_htmlBuilder,
mathmlBuilder: op_mathmlBuilder
}); // Limits, not symbols
defineFunction({
type: "op",
names: ["\\det", "\\gcd", "\\inf", "\\lim", "\\max", "\\min", "\\Pr", "\\sup"],
props: {
numArgs: 0
},
handler: function handler(_ref4) {
var parser = _ref4.parser,
funcName = _ref4.funcName;
return {
type: "op",
mode: parser.mode,
limits: true,
parentIsSupSub: false,
symbol: false,
name: funcName
};
},
htmlBuilder: op_htmlBuilder,
mathmlBuilder: op_mathmlBuilder
}); // No limits, symbols
defineFunction({
type: "op",
names: ["\\int", "\\iint", "\\iiint", "\\oint", "\\oiint", "\\oiiint", "\u222B", "\u222C", "\u222D", "\u222E", "\u222F", "\u2230"],
props: {
numArgs: 0
},
handler: function handler(_ref5) {
var parser = _ref5.parser,
funcName = _ref5.funcName;
var fName = funcName;
if (fName.length === 1) {
fName = singleCharIntegrals[fName];
}
return {
type: "op",
mode: parser.mode,
limits: false,
parentIsSupSub: false,
symbol: true,
name: fName
};
},
htmlBuilder: op_htmlBuilder,
mathmlBuilder: op_mathmlBuilder
});
// CONCATENATED MODULE: ./src/functions/operatorname.js
// NOTE: Unlike most `htmlBuilder`s, this one handles not only
// "operatorname", but also "supsub" since \operatorname* can
var operatorname_htmlBuilder = function htmlBuilder(grp, options) {
// Operators are handled in the TeXbook pg. 443-444, rule 13(a).
var supGroup;
var subGroup;
var hasLimits = false;
var group;
var supSub = checkNodeType(grp, "supsub");
if (supSub) {
// If we have limits, supsub will pass us its group to handle. Pull
// out the superscript and subscript and set the group to the op in
// its base.
supGroup = supSub.sup;
subGroup = supSub.sub;
group = assertNodeType(supSub.base, "operatorname");
hasLimits = true;
} else {
group = assertNodeType(grp, "operatorname");
}
var base;
if (group.body.length > 0) {
var body = group.body.map(function (child) {
// $FlowFixMe: Check if the node has a string `text` property.
var childText = child.text;
if (typeof childText === "string") {
return {
type: "textord",
mode: child.mode,
text: childText
};
} else {
return child;
}
}); // Consolidate function names into symbol characters.
var expression = buildHTML_buildExpression(body, options.withFont("mathrm"), true);
for (var i = 0; i < expression.length; i++) {
var child = expression[i];
if (child instanceof domTree_SymbolNode) {
// Per amsopn package,
// change minus to hyphen and \ast to asterisk
child.text = child.text.replace(/\u2212/, "-").replace(/\u2217/, "*");
}
}
base = buildCommon.makeSpan(["mop"], expression, options);
} else {
base = buildCommon.makeSpan(["mop"], [], options);
}
if (hasLimits) {
return assembleSupSub_assembleSupSub(base, supGroup, subGroup, options, options.style, 0, 0);
} else {
return base;
}
};
var operatorname_mathmlBuilder = function mathmlBuilder(group, options) {
// The steps taken here are similar to the html version.
var expression = buildMathML_buildExpression(group.body, options.withFont("mathrm")); // Is expression a string or has it something like a fraction?
var isAllString = true; // default
for (var i = 0; i < expression.length; i++) {
var node = expression[i];
if (node instanceof mathMLTree.SpaceNode) {// Do nothing
} else if (node instanceof mathMLTree.MathNode) {
switch (node.type) {
case "mi":
case "mn":
case "ms":
case "mspace":
case "mtext":
break;
// Do nothing yet.
case "mo":
{
var child = node.children[0];
if (node.children.length === 1 && child instanceof mathMLTree.TextNode) {
child.text = child.text.replace(/\u2212/, "-").replace(/\u2217/, "*");
} else {
isAllString = false;
}
break;
}
default:
isAllString = false;
}
} else {
isAllString = false;
}
}
if (isAllString) {
// Write a single TextNode instead of multiple nested tags.
var word = expression.map(function (node) {
return node.toText();
}).join("");
expression = [new mathMLTree.TextNode(word)];
}
var identifier = new mathMLTree.MathNode("mi", expression);
identifier.setAttribute("mathvariant", "normal"); // \u2061 is the same as &ApplyFunction;
// ref: https://www.w3schools.com/charsets/ref_html_entities_a.asp
var operator = new mathMLTree.MathNode("mo", [buildMathML_makeText("\u2061", "text")]);
if (group.parentIsSupSub) {
return new mathMLTree.MathNode("mo", [identifier, operator]);
} else {
return mathMLTree.newDocumentFragment([identifier, operator]);
}
}; // \operatorname
// amsopn.dtx: \mathop{#1\kern\z@\operator@font#3}\newmcodes@
defineFunction({
type: "operatorname",
names: ["\\operatorname", "\\operatorname*"],
props: {
numArgs: 1
},
handler: function handler(_ref, args) {
var parser = _ref.parser,
funcName = _ref.funcName;
var body = args[0];
return {
type: "operatorname",
mode: parser.mode,
body: defineFunction_ordargument(body),
alwaysHandleSupSub: funcName === "\\operatorname*",
limits: false,
parentIsSupSub: false
};
},
htmlBuilder: operatorname_htmlBuilder,
mathmlBuilder: operatorname_mathmlBuilder
});
// CONCATENATED MODULE: ./src/functions/ordgroup.js
defineFunctionBuilders({
type: "ordgroup",
htmlBuilder: function htmlBuilder(group, options) {
if (group.semisimple) {
return buildCommon.makeFragment(buildHTML_buildExpression(group.body, options, false));
}
return buildCommon.makeSpan(["mord"], buildHTML_buildExpression(group.body, options, true), options);
},
mathmlBuilder: function mathmlBuilder(group, options) {
return buildExpressionRow(group.body, options, true);
}
});
// CONCATENATED MODULE: ./src/functions/overline.js
defineFunction({
type: "overline",
names: ["\\overline"],
props: {
numArgs: 1
},
handler: function handler(_ref, args) {
var parser = _ref.parser;
var body = args[0];
return {
type: "overline",
mode: parser.mode,
body: body
};
},
htmlBuilder: function htmlBuilder(group, options) {
// Overlines are handled in the TeXbook pg 443, Rule 9.
// Build the inner group in the cramped style.
var innerGroup = buildHTML_buildGroup(group.body, options.havingCrampedStyle()); // Create the line above the body
var line = buildCommon.makeLineSpan("overline-line", options); // Generate the vlist, with the appropriate kerns
var defaultRuleThickness = options.fontMetrics().defaultRuleThickness;
var vlist = buildCommon.makeVList({
positionType: "firstBaseline",
children: [{
type: "elem",
elem: innerGroup
}, {
type: "kern",
size: 3 * defaultRuleThickness
}, {
type: "elem",
elem: line
}, {
type: "kern",
size: defaultRuleThickness
}]
}, options);
return buildCommon.makeSpan(["mord", "overline"], [vlist], options);
},
mathmlBuilder: function mathmlBuilder(group, options) {
var operator = new mathMLTree.MathNode("mo", [new mathMLTree.TextNode("\u203E")]);
operator.setAttribute("stretchy", "true");
var node = new mathMLTree.MathNode("mover", [buildMathML_buildGroup(group.body, options), operator]);
node.setAttribute("accent", "true");
return node;
}
});
// CONCATENATED MODULE: ./src/functions/phantom.js
defineFunction({
type: "phantom",
names: ["\\phantom"],
props: {
numArgs: 1,
allowedInText: true
},
handler: function handler(_ref, args) {
var parser = _ref.parser;
var body = args[0];
return {
type: "phantom",
mode: parser.mode,
body: defineFunction_ordargument(body)
};
},
htmlBuilder: function htmlBuilder(group, options) {
var elements = buildHTML_buildExpression(group.body, options.withPhantom(), false); // \phantom isn't supposed to affect the elements it contains.
// See "color" for more details.
return buildCommon.makeFragment(elements);
},
mathmlBuilder: function mathmlBuilder(group, options) {
var inner = buildMathML_buildExpression(group.body, options);
return new mathMLTree.MathNode("mphantom", inner);
}
});
defineFunction({
type: "hphantom",
names: ["\\hphantom"],
props: {
numArgs: 1,
allowedInText: true
},
handler: function handler(_ref2, args) {
var parser = _ref2.parser;
var body = args[0];
return {
type: "hphantom",
mode: parser.mode,
body: body
};
},
htmlBuilder: function htmlBuilder(group, options) {
var node = buildCommon.makeSpan([], [buildHTML_buildGroup(group.body, options.withPhantom())]);
node.height = 0;
node.depth = 0;
if (node.children) {
for (var i = 0; i < node.children.length; i++) {
node.children[i].height = 0;
node.children[i].depth = 0;
}
} // See smash for comment re: use of makeVList
node = buildCommon.makeVList({
positionType: "firstBaseline",
children: [{
type: "elem",
elem: node
}]
}, options); // For spacing, TeX treats \smash as a math group (same spacing as ord).
return buildCommon.makeSpan(["mord"], [node], options);
},
mathmlBuilder: function mathmlBuilder(group, options) {
var inner = buildMathML_buildExpression(defineFunction_ordargument(group.body), options);
var phantom = new mathMLTree.MathNode("mphantom", inner);
var node = new mathMLTree.MathNode("mpadded", [phantom]);
node.setAttribute("height", "0px");
node.setAttribute("depth", "0px");
return node;
}
});
defineFunction({
type: "vphantom",
names: ["\\vphantom"],
props: {
numArgs: 1,
allowedInText: true
},
handler: function handler(_ref3, args) {
var parser = _ref3.parser;
var body = args[0];
return {
type: "vphantom",
mode: parser.mode,
body: body
};
},
htmlBuilder: function htmlBuilder(group, options) {
var inner = buildCommon.makeSpan(["inner"], [buildHTML_buildGroup(group.body, options.withPhantom())]);
var fix = buildCommon.makeSpan(["fix"], []);
return buildCommon.makeSpan(["mord", "rlap"], [inner, fix], options);
},
mathmlBuilder: function mathmlBuilder(group, options) {
var inner = buildMathML_buildExpression(defineFunction_ordargument(group.body), options);
var phantom = new mathMLTree.MathNode("mphantom", inner);
var node = new mathMLTree.MathNode("mpadded", [phantom]);
node.setAttribute("width", "0px");
return node;
}
});
// CONCATENATED MODULE: ./src/functions/raisebox.js
// Box manipulation
defineFunction({
type: "raisebox",
names: ["\\raisebox"],
props: {
numArgs: 2,
argTypes: ["size", "hbox"],
allowedInText: true
},
handler: function handler(_ref, args) {
var parser = _ref.parser;
var amount = assertNodeType(args[0], "size").value;
var body = args[1];
return {
type: "raisebox",
mode: parser.mode,
dy: amount,
body: body
};
},
htmlBuilder: function htmlBuilder(group, options) {
var body = buildHTML_buildGroup(group.body, options);
var dy = units_calculateSize(group.dy, options);
return buildCommon.makeVList({
positionType: "shift",
positionData: -dy,
children: [{
type: "elem",
elem: body
}]
}, options);
},
mathmlBuilder: function mathmlBuilder(group, options) {
var node = new mathMLTree.MathNode("mpadded", [buildMathML_buildGroup(group.body, options)]);
var dy = group.dy.number + group.dy.unit;
node.setAttribute("voffset", dy);
return node;
}
});
// CONCATENATED MODULE: ./src/functions/rule.js
defineFunction({
type: "rule",
names: ["\\rule"],
props: {
numArgs: 2,
numOptionalArgs: 1,
argTypes: ["size", "size", "size"]
},
handler: function handler(_ref, args, optArgs) {
var parser = _ref.parser;
var shift = optArgs[0];
var width = assertNodeType(args[0], "size");
var height = assertNodeType(args[1], "size");
return {
type: "rule",
mode: parser.mode,
shift: shift && assertNodeType(shift, "size").value,
width: width.value,
height: height.value
};
},
htmlBuilder: function htmlBuilder(group, options) {
// Make an empty span for the rule
var rule = buildCommon.makeSpan(["mord", "rule"], [], options); // Calculate the shift, width, and height of the rule, and account for units
var width = units_calculateSize(group.width, options);
var height = units_calculateSize(group.height, options);
var shift = group.shift ? units_calculateSize(group.shift, options) : 0; // Style the rule to the right size
rule.style.borderRightWidth = width + "em";
rule.style.borderTopWidth = height + "em";
rule.style.bottom = shift + "em"; // Record the height and width
rule.width = width;
rule.height = height + shift;
rule.depth = -shift; // Font size is the number large enough that the browser will
// reserve at least `absHeight` space above the baseline.
// The 1.125 factor was empirically determined
rule.maxFontSize = height * 1.125 * options.sizeMultiplier;
return rule;
},
mathmlBuilder: function mathmlBuilder(group, options) {
var width = units_calculateSize(group.width, options);
var height = units_calculateSize(group.height, options);
var shift = group.shift ? units_calculateSize(group.shift, options) : 0;
var color = options.color && options.getColor() || "black";
var rule = new mathMLTree.MathNode("mspace");
rule.setAttribute("mathbackground", color);
rule.setAttribute("width", width + "em");
rule.setAttribute("height", height + "em");
var wrapper = new mathMLTree.MathNode("mpadded", [rule]);
if (shift >= 0) {
wrapper.setAttribute("height", "+" + shift + "em");
} else {
wrapper.setAttribute("height", shift + "em");
wrapper.setAttribute("depth", "+" + -shift + "em");
}
wrapper.setAttribute("voffset", shift + "em");
return wrapper;
}
});
// CONCATENATED MODULE: ./src/functions/sizing.js
function sizingGroup(value, options, baseOptions) {
var inner = buildHTML_buildExpression(value, options, false);
var multiplier = options.sizeMultiplier / baseOptions.sizeMultiplier; // Add size-resetting classes to the inner list and set maxFontSize
// manually. Handle nested size changes.
for (var i = 0; i < inner.length; i++) {
var pos = inner[i].classes.indexOf("sizing");
if (pos < 0) {
Array.prototype.push.apply(inner[i].classes, options.sizingClasses(baseOptions));
} else if (inner[i].classes[pos + 1] === "reset-size" + options.size) {
// This is a nested size change: e.g., inner[i] is the "b" in
// `\Huge a \small b`. Override the old size (the `reset-` class)
// but not the new size.
inner[i].classes[pos + 1] = "reset-size" + baseOptions.size;
}
inner[i].height *= multiplier;
inner[i].depth *= multiplier;
}
return buildCommon.makeFragment(inner);
}
var sizeFuncs = ["\\tiny", "\\sixptsize", "\\scriptsize", "\\footnotesize", "\\small", "\\normalsize", "\\large", "\\Large", "\\LARGE", "\\huge", "\\Huge"];
var sizing_htmlBuilder = function htmlBuilder(group, options) {
// Handle sizing operators like \Huge. Real TeX doesn't actually allow
// these functions inside of math expressions, so we do some special
// handling.
var newOptions = options.havingSize(group.size);
return sizingGroup(group.body, newOptions, options);
};
defineFunction({
type: "sizing",
names: sizeFuncs,
props: {
numArgs: 0,
allowedInText: true
},
handler: function handler(_ref, args) {
var breakOnTokenText = _ref.breakOnTokenText,
funcName = _ref.funcName,
parser = _ref.parser;
var body = parser.parseExpression(false, breakOnTokenText);
return {
type: "sizing",
mode: parser.mode,
// Figure out what size to use based on the list of functions above
size: sizeFuncs.indexOf(funcName) + 1,
body: body
};
},
htmlBuilder: sizing_htmlBuilder,
mathmlBuilder: function mathmlBuilder(group, options) {
var newOptions = options.havingSize(group.size);
var inner = buildMathML_buildExpression(group.body, newOptions);
var node = new mathMLTree.MathNode("mstyle", inner); // TODO(emily): This doesn't produce the correct size for nested size
// changes, because we don't keep state of what style we're currently
// in, so we can't reset the size to normal before changing it. Now
// that we're passing an options parameter we should be able to fix
// this.
node.setAttribute("mathsize", newOptions.sizeMultiplier + "em");
return node;
}
});
// CONCATENATED MODULE: ./src/functions/smash.js
// smash, with optional [tb], as in AMS
defineFunction({
type: "smash",
names: ["\\smash"],
props: {
numArgs: 1,
numOptionalArgs: 1,
allowedInText: true
},
handler: function handler(_ref, args, optArgs) {
var parser = _ref.parser;
var smashHeight = false;
var smashDepth = false;
var tbArg = optArgs[0] && assertNodeType(optArgs[0], "ordgroup");
if (tbArg) {
// Optional [tb] argument is engaged.
// ref: amsmath: \renewcommand{\smash}[1][tb]{%
// def\mb@t{\ht}\def\mb@b{\dp}\def\mb@tb{\ht\z@\z@\dp}%
var letter = "";
for (var i = 0; i < tbArg.body.length; ++i) {
var node = tbArg.body[i]; // $FlowFixMe: Not every node type has a `text` property.
letter = node.text;
if (letter === "t") {
smashHeight = true;
} else if (letter === "b") {
smashDepth = true;
} else {
smashHeight = false;
smashDepth = false;
break;
}
}
} else {
smashHeight = true;
smashDepth = true;
}
var body = args[0];
return {
type: "smash",
mode: parser.mode,
body: body,
smashHeight: smashHeight,
smashDepth: smashDepth
};
},
htmlBuilder: function htmlBuilder(group, options) {
var node = buildCommon.makeSpan([], [buildHTML_buildGroup(group.body, options)]);
if (!group.smashHeight && !group.smashDepth) {
return node;
}
if (group.smashHeight) {
node.height = 0; // In order to influence makeVList, we have to reset the children.
if (node.children) {
for (var i = 0; i < node.children.length; i++) {
node.children[i].height = 0;
}
}
}
if (group.smashDepth) {
node.depth = 0;
if (node.children) {
for (var _i = 0; _i < node.children.length; _i++) {
node.children[_i].depth = 0;
}
}
} // At this point, we've reset the TeX-like height and depth values.
// But the span still has an HTML line height.
// makeVList applies "display: table-cell", which prevents the browser
// from acting on that line height. So we'll call makeVList now.
var smashedNode = buildCommon.makeVList({
positionType: "firstBaseline",
children: [{
type: "elem",
elem: node
}]
}, options); // For spacing, TeX treats \hphantom as a math group (same spacing as ord).
return buildCommon.makeSpan(["mord"], [smashedNode], options);
},
mathmlBuilder: function mathmlBuilder(group, options) {
var node = new mathMLTree.MathNode("mpadded", [buildMathML_buildGroup(group.body, options)]);
if (group.smashHeight) {
node.setAttribute("height", "0px");
}
if (group.smashDepth) {
node.setAttribute("depth", "0px");
}
return node;
}
});
// CONCATENATED MODULE: ./src/functions/sqrt.js
defineFunction({
type: "sqrt",
names: ["\\sqrt"],
props: {
numArgs: 1,
numOptionalArgs: 1
},
handler: function handler(_ref, args, optArgs) {
var parser = _ref.parser;
var index = optArgs[0];
var body = args[0];
return {
type: "sqrt",
mode: parser.mode,
body: body,
index: index
};
},
htmlBuilder: function htmlBuilder(group, options) {
// Square roots are handled in the TeXbook pg. 443, Rule 11.
// First, we do the same steps as in overline to build the inner group
// and line
var inner = buildHTML_buildGroup(group.body, options.havingCrampedStyle());
if (inner.height === 0) {
// Render a small surd.
inner.height = options.fontMetrics().xHeight;
} // Some groups can return document fragments. Handle those by wrapping
// them in a span.
inner = buildCommon.wrapFragment(inner, options); // Calculate the minimum size for the \surd delimiter
var metrics = options.fontMetrics();
var theta = metrics.defaultRuleThickness;
var phi = theta;
if (options.style.id < src_Style.TEXT.id) {
phi = options.fontMetrics().xHeight;
} // Calculate the clearance between the body and line
var lineClearance = theta + phi / 4;
var minDelimiterHeight = inner.height + inner.depth + lineClearance + theta; // Create a sqrt SVG of the required minimum size
var _delimiter$sqrtImage = delimiter.sqrtImage(minDelimiterHeight, options),
img = _delimiter$sqrtImage.span,
ruleWidth = _delimiter$sqrtImage.ruleWidth,
advanceWidth = _delimiter$sqrtImage.advanceWidth;
var delimDepth = img.height - ruleWidth; // Adjust the clearance based on the delimiter size
if (delimDepth > inner.height + inner.depth + lineClearance) {
lineClearance = (lineClearance + delimDepth - inner.height - inner.depth) / 2;
} // Shift the sqrt image
var imgShift = img.height - inner.height - lineClearance - ruleWidth;
inner.style.paddingLeft = advanceWidth + "em"; // Overlay the image and the argument.
var body = buildCommon.makeVList({
positionType: "firstBaseline",
children: [{
type: "elem",
elem: inner,
wrapperClasses: ["svg-align"]
}, {
type: "kern",
size: -(inner.height + imgShift)
}, {
type: "elem",
elem: img
}, {
type: "kern",
size: ruleWidth
}]
}, options);
if (!group.index) {
return buildCommon.makeSpan(["mord", "sqrt"], [body], options);
} else {
// Handle the optional root index
// The index is always in scriptscript style
var newOptions = options.havingStyle(src_Style.SCRIPTSCRIPT);
var rootm = buildHTML_buildGroup(group.index, newOptions, options); // The amount the index is shifted by. This is taken from the TeX
// source, in the definition of `\r@@t`.
var toShift = 0.6 * (body.height - body.depth); // Build a VList with the superscript shifted up correctly
var rootVList = buildCommon.makeVList({
positionType: "shift",
positionData: -toShift,
children: [{
type: "elem",
elem: rootm
}]
}, options); // Add a class surrounding it so we can add on the appropriate
// kerning
var rootVListWrap = buildCommon.makeSpan(["root"], [rootVList]);
return buildCommon.makeSpan(["mord", "sqrt"], [rootVListWrap, body], options);
}
},
mathmlBuilder: function mathmlBuilder(group, options) {
var body = group.body,
index = group.index;
return index ? new mathMLTree.MathNode("mroot", [buildMathML_buildGroup(body, options), buildMathML_buildGroup(index, options)]) : new mathMLTree.MathNode("msqrt", [buildMathML_buildGroup(body, options)]);
}
});
// CONCATENATED MODULE: ./src/functions/styling.js
var styling_styleMap = {
"display": src_Style.DISPLAY,
"text": src_Style.TEXT,
"script": src_Style.SCRIPT,
"scriptscript": src_Style.SCRIPTSCRIPT
};
defineFunction({
type: "styling",
names: ["\\displaystyle", "\\textstyle", "\\scriptstyle", "\\scriptscriptstyle"],
props: {
numArgs: 0,
allowedInText: true
},
handler: function handler(_ref, args) {
var breakOnTokenText = _ref.breakOnTokenText,
funcName = _ref.funcName,
parser = _ref.parser;
// parse out the implicit body
var body = parser.parseExpression(true, breakOnTokenText); // TODO: Refactor to avoid duplicating styleMap in multiple places (e.g.
// here and in buildHTML and de-dupe the enumeration of all the styles).
// $FlowFixMe: The names above exactly match the styles.
var style = funcName.slice(1, funcName.length - 5);
return {
type: "styling",
mode: parser.mode,
// Figure out what style to use by pulling out the style from
// the function name
style: style,
body: body
};
},
htmlBuilder: function htmlBuilder(group, options) {
// Style changes are handled in the TeXbook on pg. 442, Rule 3.
var newStyle = styling_styleMap[group.style];
var newOptions = options.havingStyle(newStyle).withFont('');
return sizingGroup(group.body, newOptions, options);
},
mathmlBuilder: function mathmlBuilder(group, options) {
// Figure out what style we're changing to.
var newStyle = styling_styleMap[group.style];
var newOptions = options.havingStyle(newStyle);
var inner = buildMathML_buildExpression(group.body, newOptions);
var node = new mathMLTree.MathNode("mstyle", inner);
var styleAttributes = {
"display": ["0", "true"],
"text": ["0", "false"],
"script": ["1", "false"],
"scriptscript": ["2", "false"]
};
var attr = styleAttributes[group.style];
node.setAttribute("scriptlevel", attr[0]);
node.setAttribute("displaystyle", attr[1]);
return node;
}
});
// CONCATENATED MODULE: ./src/functions/supsub.js
/**
* Sometimes, groups perform special rules when they have superscripts or
* subscripts attached to them. This function lets the `supsub` group know that
* Sometimes, groups perform special rules when they have superscripts or
* its inner element should handle the superscripts and subscripts instead of
* handling them itself.
*/
var supsub_htmlBuilderDelegate = function htmlBuilderDelegate(group, options) {
var base = group.base;
if (!base) {
return null;
} else if (base.type === "op") {
// Operators handle supsubs differently when they have limits
// (e.g. `\displaystyle\sum_2^3`)
var delegate = base.limits && (options.style.size === src_Style.DISPLAY.size || base.alwaysHandleSupSub);
return delegate ? op_htmlBuilder : null;
} else if (base.type === "operatorname") {
var _delegate = base.alwaysHandleSupSub && (options.style.size === src_Style.DISPLAY.size || base.limits);
return _delegate ? operatorname_htmlBuilder : null;
} else if (base.type === "accent") {
return utils.isCharacterBox(base.base) ? accent_htmlBuilder : null;
} else if (base.type === "horizBrace") {
var isSup = !group.sub;
return isSup === base.isOver ? horizBrace_htmlBuilder : null;
} else {
return null;
}
}; // Super scripts and subscripts, whose precise placement can depend on other
// functions that precede them.
defineFunctionBuilders({
type: "supsub",
htmlBuilder: function htmlBuilder(group, options) {
// Superscript and subscripts are handled in the TeXbook on page
// 445-446, rules 18(a-f).
// Here is where we defer to the inner group if it should handle
// superscripts and subscripts itself.
var builderDelegate = supsub_htmlBuilderDelegate(group, options);
if (builderDelegate) {
return builderDelegate(group, options);
}
var valueBase = group.base,
valueSup = group.sup,
valueSub = group.sub;
var base = buildHTML_buildGroup(valueBase, options);
var supm;
var subm;
var metrics = options.fontMetrics(); // Rule 18a
var supShift = 0;
var subShift = 0;
var isCharacterBox = valueBase && utils.isCharacterBox(valueBase);
if (valueSup) {
var newOptions = options.havingStyle(options.style.sup());
supm = buildHTML_buildGroup(valueSup, newOptions, options);
if (!isCharacterBox) {
supShift = base.height - newOptions.fontMetrics().supDrop * newOptions.sizeMultiplier / options.sizeMultiplier;
}
}
if (valueSub) {
var _newOptions = options.havingStyle(options.style.sub());
subm = buildHTML_buildGroup(valueSub, _newOptions, options);
if (!isCharacterBox) {
subShift = base.depth + _newOptions.fontMetrics().subDrop * _newOptions.sizeMultiplier / options.sizeMultiplier;
}
} // Rule 18c
var minSupShift;
if (options.style === src_Style.DISPLAY) {
minSupShift = metrics.sup1;
} else if (options.style.cramped) {
minSupShift = metrics.sup3;
} else {
minSupShift = metrics.sup2;
} // scriptspace is a font-size-independent size, so scale it
// appropriately for use as the marginRight.
var multiplier = options.sizeMultiplier;
var marginRight = 0.5 / metrics.ptPerEm / multiplier + "em";
var marginLeft = null;
if (subm) {
// Subscripts shouldn't be shifted by the base's italic correction.
// Account for that by shifting the subscript back the appropriate
// amount. Note we only do this when the base is a single symbol.
var isOiint = group.base && group.base.type === "op" && group.base.name && (group.base.name === "\\oiint" || group.base.name === "\\oiiint");
if (base instanceof domTree_SymbolNode || isOiint) {
// $FlowFixMe
marginLeft = -base.italic + "em";
}
}
var supsub;
if (supm && subm) {
supShift = Math.max(supShift, minSupShift, supm.depth + 0.25 * metrics.xHeight);
subShift = Math.max(subShift, metrics.sub2);
var ruleWidth = metrics.defaultRuleThickness; // Rule 18e
var maxWidth = 4 * ruleWidth;
if (supShift - supm.depth - (subm.height - subShift) < maxWidth) {
subShift = maxWidth - (supShift - supm.depth) + subm.height;
var psi = 0.8 * metrics.xHeight - (supShift - supm.depth);
if (psi > 0) {
supShift += psi;
subShift -= psi;
}
}
var vlistElem = [{
type: "elem",
elem: subm,
shift: subShift,
marginRight: marginRight,
marginLeft: marginLeft
}, {
type: "elem",
elem: supm,
shift: -supShift,
marginRight: marginRight
}];
supsub = buildCommon.makeVList({
positionType: "individualShift",
children: vlistElem
}, options);
} else if (subm) {
// Rule 18b
subShift = Math.max(subShift, metrics.sub1, subm.height - 0.8 * metrics.xHeight);
var _vlistElem = [{
type: "elem",
elem: subm,
marginLeft: marginLeft,
marginRight: marginRight
}];
supsub = buildCommon.makeVList({
positionType: "shift",
positionData: subShift,
children: _vlistElem
}, options);
} else if (supm) {
// Rule 18c, d
supShift = Math.max(supShift, minSupShift, supm.depth + 0.25 * metrics.xHeight);
supsub = buildCommon.makeVList({
positionType: "shift",
positionData: -supShift,
children: [{
type: "elem",
elem: supm,
marginRight: marginRight
}]
}, options);
} else {
throw new Error("supsub must have either sup or sub.");
} // Wrap the supsub vlist in a span.msupsub to reset text-align.
var mclass = getTypeOfDomTree(base, "right") || "mord";
return buildCommon.makeSpan([mclass], [base, buildCommon.makeSpan(["msupsub"], [supsub])], options);
},
mathmlBuilder: function mathmlBuilder(group, options) {
// Is the inner group a relevant horizonal brace?
var isBrace = false;
var isOver;
var isSup;
var horizBrace = checkNodeType(group.base, "horizBrace");
if (horizBrace) {
isSup = !!group.sup;
if (isSup === horizBrace.isOver) {
isBrace = true;
isOver = horizBrace.isOver;
}
}
if (group.base && (group.base.type === "op" || group.base.type === "operatorname")) {
group.base.parentIsSupSub = true;
}
var children = [buildMathML_buildGroup(group.base, options)];
if (group.sub) {
children.push(buildMathML_buildGroup(group.sub, options));
}
if (group.sup) {
children.push(buildMathML_buildGroup(group.sup, options));
}
var nodeType;
if (isBrace) {
nodeType = isOver ? "mover" : "munder";
} else if (!group.sub) {
var base = group.base;
if (base && base.type === "op" && base.limits && (options.style === src_Style.DISPLAY || base.alwaysHandleSupSub)) {
nodeType = "mover";
} else if (base && base.type === "operatorname" && base.alwaysHandleSupSub && (base.limits || options.style === src_Style.DISPLAY)) {
nodeType = "mover";
} else {
nodeType = "msup";
}
} else if (!group.sup) {
var _base = group.base;
if (_base && _base.type === "op" && _base.limits && (options.style === src_Style.DISPLAY || _base.alwaysHandleSupSub)) {
nodeType = "munder";
} else if (_base && _base.type === "operatorname" && _base.alwaysHandleSupSub && (_base.limits || options.style === src_Style.DISPLAY)) {
nodeType = "munder";
} else {
nodeType = "msub";
}
} else {
var _base2 = group.base;
if (_base2 && _base2.type === "op" && _base2.limits && options.style === src_Style.DISPLAY) {
nodeType = "munderover";
} else if (_base2 && _base2.type === "operatorname" && _base2.alwaysHandleSupSub && (options.style === src_Style.DISPLAY || _base2.limits)) {
nodeType = "munderover";
} else {
nodeType = "msubsup";
}
}
var node = new mathMLTree.MathNode(nodeType, children);
return node;
}
});
// CONCATENATED MODULE: ./src/functions/symbolsOp.js
// Operator ParseNodes created in Parser.js from symbol Groups in src/symbols.js.
defineFunctionBuilders({
type: "atom",
htmlBuilder: function htmlBuilder(group, options) {
return buildCommon.mathsym(group.text, group.mode, options, ["m" + group.family]);
},
mathmlBuilder: function mathmlBuilder(group, options) {
var node = new mathMLTree.MathNode("mo", [buildMathML_makeText(group.text, group.mode)]);
if (group.family === "bin") {
var variant = buildMathML_getVariant(group, options);
if (variant === "bold-italic") {
node.setAttribute("mathvariant", variant);
}
} else if (group.family === "punct") {
node.setAttribute("separator", "true");
} else if (group.family === "open" || group.family === "close") {
// Delims built here should not stretch vertically.
// See delimsizing.js for stretchy delims.
node.setAttribute("stretchy", "false");
}
return node;
}
});
// CONCATENATED MODULE: ./src/functions/symbolsOrd.js
// "mathord" and "textord" ParseNodes created in Parser.js from symbol Groups in
var defaultVariant = {
"mi": "italic",
"mn": "normal",
"mtext": "normal"
};
defineFunctionBuilders({
type: "mathord",
htmlBuilder: function htmlBuilder(group, options) {
return buildCommon.makeOrd(group, options, "mathord");
},
mathmlBuilder: function mathmlBuilder(group, options) {
var node = new mathMLTree.MathNode("mi", [buildMathML_makeText(group.text, group.mode, options)]);
var variant = buildMathML_getVariant(group, options) || "italic";
if (variant !== defaultVariant[node.type]) {
node.setAttribute("mathvariant", variant);
}
return node;
}
});
defineFunctionBuilders({
type: "textord",
htmlBuilder: function htmlBuilder(group, options) {
return buildCommon.makeOrd(group, options, "textord");
},
mathmlBuilder: function mathmlBuilder(group, options) {
var text = buildMathML_makeText(group.text, group.mode, options);
var variant = buildMathML_getVariant(group, options) || "normal";
var node;
if (group.mode === 'text') {
node = new mathMLTree.MathNode("mtext", [text]);
} else if (/[0-9]/.test(group.text)) {
// TODO(kevinb) merge adjacent <mn> nodes
// do it as a post processing step
node = new mathMLTree.MathNode("mn", [text]);
} else if (group.text === "\\prime") {
node = new mathMLTree.MathNode("mo", [text]);
} else {
node = new mathMLTree.MathNode("mi", [text]);
}
if (variant !== defaultVariant[node.type]) {
node.setAttribute("mathvariant", variant);
}
return node;
}
});
// CONCATENATED MODULE: ./src/functions/symbolsSpacing.js
// A map of CSS-based spacing functions to their CSS class.
var cssSpace = {
"\\nobreak": "nobreak",
"\\allowbreak": "allowbreak"
}; // A lookup table to determine whether a spacing function/symbol should be
// treated like a regular space character. If a symbol or command is a key
// in this table, then it should be a regular space character. Furthermore,
// the associated value may have a `className` specifying an extra CSS class
// to add to the created `span`.
var regularSpace = {
" ": {},
"\\ ": {},
"~": {
className: "nobreak"
},
"\\space": {},
"\\nobreakspace": {
className: "nobreak"
}
}; // ParseNode<"spacing"> created in Parser.js from the "spacing" symbol Groups in
// src/symbols.js.
defineFunctionBuilders({
type: "spacing",
htmlBuilder: function htmlBuilder(group, options) {
if (regularSpace.hasOwnProperty(group.text)) {
var className = regularSpace[group.text].className || ""; // Spaces are generated by adding an actual space. Each of these
// things has an entry in the symbols table, so these will be turned
// into appropriate outputs.
if (group.mode === "text") {
var ord = buildCommon.makeOrd(group, options, "textord");
ord.classes.push(className);
return ord;
} else {
return buildCommon.makeSpan(["mspace", className], [buildCommon.mathsym(group.text, group.mode, options)], options);
}
} else if (cssSpace.hasOwnProperty(group.text)) {
// Spaces based on just a CSS class.
return buildCommon.makeSpan(["mspace", cssSpace[group.text]], [], options);
} else {
throw new src_ParseError("Unknown type of space \"" + group.text + "\"");
}
},
mathmlBuilder: function mathmlBuilder(group, options) {
var node;
if (regularSpace.hasOwnProperty(group.text)) {
node = new mathMLTree.MathNode("mtext", [new mathMLTree.TextNode("\xA0")]);
} else if (cssSpace.hasOwnProperty(group.text)) {
// CSS-based MathML spaces (\nobreak, \allowbreak) are ignored
return new mathMLTree.MathNode("mspace");
} else {
throw new src_ParseError("Unknown type of space \"" + group.text + "\"");
}
return node;
}
});
// CONCATENATED MODULE: ./src/functions/tag.js
var tag_pad = function pad() {
var padNode = new mathMLTree.MathNode("mtd", []);
padNode.setAttribute("width", "50%");
return padNode;
};
defineFunctionBuilders({
type: "tag",
mathmlBuilder: function mathmlBuilder(group, options) {
var table = new mathMLTree.MathNode("mtable", [new mathMLTree.MathNode("mtr", [tag_pad(), new mathMLTree.MathNode("mtd", [buildExpressionRow(group.body, options)]), tag_pad(), new mathMLTree.MathNode("mtd", [buildExpressionRow(group.tag, options)])])]);
table.setAttribute("width", "100%");
return table; // TODO: Left-aligned tags.
// Currently, the group and options passed here do not contain
// enough info to set tag alignment. `leqno` is in Settings but it is
// not passed to Options. On the HTML side, leqno is
// set by a CSS class applied in buildTree.js. That would have worked
// in MathML if browsers supported <mlabeledtr>. Since they don't, we
// need to rewrite the way this function is called.
}
});
// CONCATENATED MODULE: ./src/functions/text.js
// Non-mathy text, possibly in a font
var textFontFamilies = {
"\\text": undefined,
"\\textrm": "textrm",
"\\textsf": "textsf",
"\\texttt": "texttt",
"\\textnormal": "textrm"
};
var textFontWeights = {
"\\textbf": "textbf",
"\\textmd": "textmd"
};
var textFontShapes = {
"\\textit": "textit",
"\\textup": "textup"
};
var optionsWithFont = function optionsWithFont(group, options) {
var font = group.font; // Checks if the argument is a font family or a font style.
if (!font) {
return options;
} else if (textFontFamilies[font]) {
return options.withTextFontFamily(textFontFamilies[font]);
} else if (textFontWeights[font]) {
return options.withTextFontWeight(textFontWeights[font]);
} else {
return options.withTextFontShape(textFontShapes[font]);
}
};
defineFunction({
type: "text",
names: [// Font families
"\\text", "\\textrm", "\\textsf", "\\texttt", "\\textnormal", // Font weights
"\\textbf", "\\textmd", // Font Shapes
"\\textit", "\\textup"],
props: {
numArgs: 1,
argTypes: ["text"],
greediness: 2,
allowedInText: true
},
handler: function handler(_ref, args) {
var parser = _ref.parser,
funcName = _ref.funcName;
var body = args[0];
return {
type: "text",
mode: parser.mode,
body: defineFunction_ordargument(body),
font: funcName
};
},
htmlBuilder: function htmlBuilder(group, options) {
var newOptions = optionsWithFont(group, options);
var inner = buildHTML_buildExpression(group.body, newOptions, true);
return buildCommon.makeSpan(["mord", "text"], buildCommon.tryCombineChars(inner), newOptions);
},
mathmlBuilder: function mathmlBuilder(group, options) {
var newOptions = optionsWithFont(group, options);
return buildExpressionRow(group.body, newOptions);
}
});
// CONCATENATED MODULE: ./src/functions/underline.js
defineFunction({
type: "underline",
names: ["\\underline"],
props: {
numArgs: 1,
allowedInText: true
},
handler: function handler(_ref, args) {
var parser = _ref.parser;
return {
type: "underline",
mode: parser.mode,
body: args[0]
};
},
htmlBuilder: function htmlBuilder(group, options) {
// Underlines are handled in the TeXbook pg 443, Rule 10.
// Build the inner group.
var innerGroup = buildHTML_buildGroup(group.body, options); // Create the line to go below the body
var line = buildCommon.makeLineSpan("underline-line", options); // Generate the vlist, with the appropriate kerns
var defaultRuleThickness = options.fontMetrics().defaultRuleThickness;
var vlist = buildCommon.makeVList({
positionType: "top",
positionData: innerGroup.height,
children: [{
type: "kern",
size: defaultRuleThickness
}, {
type: "elem",
elem: line
}, {
type: "kern",
size: 3 * defaultRuleThickness
}, {
type: "elem",
elem: innerGroup
}]
}, options);
return buildCommon.makeSpan(["mord", "underline"], [vlist], options);
},
mathmlBuilder: function mathmlBuilder(group, options) {
var operator = new mathMLTree.MathNode("mo", [new mathMLTree.TextNode("\u203E")]);
operator.setAttribute("stretchy", "true");
var node = new mathMLTree.MathNode("munder", [buildMathML_buildGroup(group.body, options), operator]);
node.setAttribute("accentunder", "true");
return node;
}
});
// CONCATENATED MODULE: ./src/functions/verb.js
defineFunction({
type: "verb",
names: ["\\verb"],
props: {
numArgs: 0,
allowedInText: true
},
handler: function handler(context, args, optArgs) {
// \verb and \verb* are dealt with directly in Parser.js.
// If we end up here, it's because of a failure to match the two delimiters
// in the regex in Lexer.js. LaTeX raises the following error when \verb is
// terminated by end of line (or file).
throw new src_ParseError("\\verb ended by end of line instead of matching delimiter");
},
htmlBuilder: function htmlBuilder(group, options) {
var text = makeVerb(group);
var body = []; // \verb enters text mode and therefore is sized like \textstyle
var newOptions = options.havingStyle(options.style.text());
for (var i = 0; i < text.length; i++) {
var c = text[i];
if (c === '~') {
c = '\\textasciitilde';
}
body.push(buildCommon.makeSymbol(c, "Typewriter-Regular", group.mode, newOptions, ["mord", "texttt"]));
}
return buildCommon.makeSpan(["mord", "text"].concat(newOptions.sizingClasses(options)), buildCommon.tryCombineChars(body), newOptions);
},
mathmlBuilder: function mathmlBuilder(group, options) {
var text = new mathMLTree.TextNode(makeVerb(group));
var node = new mathMLTree.MathNode("mtext", [text]);
node.setAttribute("mathvariant", "monospace");
return node;
}
});
/**
* Converts verb group into body string.
*
* \verb* replaces each space with an open box \u2423
* \verb replaces each space with a no-break space \xA0
*/
var makeVerb = function makeVerb(group) {
return group.body.replace(/ /g, group.star ? "\u2423" : '\xA0');
};
// CONCATENATED MODULE: ./src/functions.js
/** Include this to ensure that all functions are defined. */
var functions = _functions;
/* harmony default export */ var src_functions = (functions); // TODO(kevinb): have functions return an object and call defineFunction with
// that object in this file instead of relying on side-effects.
// CONCATENATED MODULE: ./src/Lexer.js
/**
* The Lexer class handles tokenizing the input in various ways. Since our
* parser expects us to be able to backtrack, the lexer allows lexing from any
* given starting point.
*
* Its main exposed function is the `lex` function, which takes a position to
* lex from and a type of token to lex. It defers to the appropriate `_innerLex`
* function.
*
* The various `_innerLex` functions perform the actual lexing of different
* kinds.
*/
/* The following tokenRegex
* - matches typical whitespace (but not NBSP etc.) using its first group
* - does not match any control character \x00-\x1f except whitespace
* - does not match a bare backslash
* - matches any ASCII character except those just mentioned
* - does not match the BMP private use area \uE000-\uF8FF
* - does not match bare surrogate code units
* - matches any BMP character except for those just described
* - matches any valid Unicode surrogate pair
* - matches a backslash followed by one or more letters
* - matches a backslash followed by any BMP character, including newline
* Just because the Lexer matches something doesn't mean it's valid input:
* If there is no matching function or symbol definition, the Parser will
* still reject the input.
*/
var spaceRegexString = "[ \r\n\t]";
var controlWordRegexString = "\\\\[a-zA-Z@]+";
var controlSymbolRegexString = "\\\\[^\uD800-\uDFFF]";
var controlWordWhitespaceRegexString = "" + controlWordRegexString + spaceRegexString + "*";
var controlWordWhitespaceRegex = new RegExp("^(" + controlWordRegexString + ")" + spaceRegexString + "*$");
var combiningDiacriticalMarkString = "[\u0300-\u036F]";
var combiningDiacriticalMarksEndRegex = new RegExp(combiningDiacriticalMarkString + "+$");
var tokenRegexString = "(" + spaceRegexString + "+)|" + // whitespace
"([!-\\[\\]-\u2027\u202A-\uD7FF\uF900-\uFFFF]" + ( // single codepoint
combiningDiacriticalMarkString + "*") + // ...plus accents
"|[\uD800-\uDBFF][\uDC00-\uDFFF]" + ( // surrogate pair
combiningDiacriticalMarkString + "*") + // ...plus accents
"|\\\\verb\\*([^]).*?\\3" + // \verb*
"|\\\\verb([^*a-zA-Z]).*?\\4" + // \verb unstarred
"|\\\\operatorname\\*" + ( // \operatorname*
"|" + controlWordWhitespaceRegexString) + ( // \macroName + spaces
"|" + controlSymbolRegexString + ")"); // \\, \', etc.
/** Main Lexer class */
var Lexer_Lexer =
/*#__PURE__*/
function () {
// category codes, only supports comment characters (14) for now
function Lexer(input, settings) {
this.input = void 0;
this.settings = void 0;
this.tokenRegex = void 0;
this.catcodes = void 0;
// Separate accents from characters
this.input = input;
this.settings = settings;
this.tokenRegex = new RegExp(tokenRegexString, 'g');
this.catcodes = {
"%": 14 // comment character
};
}
var _proto = Lexer.prototype;
_proto.setCatcode = function setCatcode(char, code) {
this.catcodes[char] = code;
}
/**
* This function lexes a single token.
*/
;
_proto.lex = function lex() {
var input = this.input;
var pos = this.tokenRegex.lastIndex;
if (pos === input.length) {
return new Token_Token("EOF", new SourceLocation(this, pos, pos));
}
var match = this.tokenRegex.exec(input);
if (match === null || match.index !== pos) {
throw new src_ParseError("Unexpected character: '" + input[pos] + "'", new Token_Token(input[pos], new SourceLocation(this, pos, pos + 1)));
}
var text = match[2] || " ";
if (this.catcodes[text] === 14) {
// comment character
var nlIndex = input.indexOf('\n', this.tokenRegex.lastIndex);
if (nlIndex === -1) {
this.tokenRegex.lastIndex = input.length; // EOF
this.settings.reportNonstrict("commentAtEnd", "% comment has no terminating newline; LaTeX would " + "fail because of commenting the end of math mode (e.g. $)");
} else {
this.tokenRegex.lastIndex = nlIndex + 1;
}
return this.lex();
} // Trim any trailing whitespace from control word match
var controlMatch = text.match(controlWordWhitespaceRegex);
if (controlMatch) {
text = controlMatch[1];
}
return new Token_Token(text, new SourceLocation(this, pos, this.tokenRegex.lastIndex));
};
return Lexer;
}();
// CONCATENATED MODULE: ./src/Namespace.js
/**
* A `Namespace` refers to a space of nameable things like macros or lengths,
* which can be `set` either globally or local to a nested group, using an
* undo stack similar to how TeX implements this functionality.
* Performance-wise, `get` and local `set` take constant time, while global
* `set` takes time proportional to the depth of group nesting.
*/
var Namespace_Namespace =
/*#__PURE__*/
function () {
/**
* Both arguments are optional. The first argument is an object of
* built-in mappings which never change. The second argument is an object
* of initial (global-level) mappings, which will constantly change
* according to any global/top-level `set`s done.
*/
function Namespace(builtins, globalMacros) {
if (builtins === void 0) {
builtins = {};
}
if (globalMacros === void 0) {
globalMacros = {};
}
this.current = void 0;
this.builtins = void 0;
this.undefStack = void 0;
this.current = globalMacros;
this.builtins = builtins;
this.undefStack = [];
}
/**
* Start a new nested group, affecting future local `set`s.
*/
var _proto = Namespace.prototype;
_proto.beginGroup = function beginGroup() {
this.undefStack.push({});
}
/**
* End current nested group, restoring values before the group began.
*/
;
_proto.endGroup = function endGroup() {
if (this.undefStack.length === 0) {
throw new src_ParseError("Unbalanced namespace destruction: attempt " + "to pop global namespace; please report this as a bug");
}
var undefs = this.undefStack.pop();
for (var undef in undefs) {
if (undefs.hasOwnProperty(undef)) {
if (undefs[undef] === undefined) {
delete this.current[undef];
} else {
this.current[undef] = undefs[undef];
}
}
}
}
/**
* Detect whether `name` has a definition. Equivalent to
* `get(name) != null`.
*/
;
_proto.has = function has(name) {
return this.current.hasOwnProperty(name) || this.builtins.hasOwnProperty(name);
}
/**
* Get the current value of a name, or `undefined` if there is no value.
*
* Note: Do not use `if (namespace.get(...))` to detect whether a macro
* is defined, as the definition may be the empty string which evaluates
* to `false` in JavaScript. Use `if (namespace.get(...) != null)` or
* `if (namespace.has(...))`.
*/
;
_proto.get = function get(name) {
if (this.current.hasOwnProperty(name)) {
return this.current[name];
} else {
return this.builtins[name];
}
}
/**
* Set the current value of a name, and optionally set it globally too.
* Local set() sets the current value and (when appropriate) adds an undo
* operation to the undo stack. Global set() may change the undo
* operation at every level, so takes time linear in their number.
*/
;
_proto.set = function set(name, value, global) {
if (global === void 0) {
global = false;
}
if (global) {
// Global set is equivalent to setting in all groups. Simulate this
// by destroying any undos currently scheduled for this name,
// and adding an undo with the *new* value (in case it later gets
// locally reset within this environment).
for (var i = 0; i < this.undefStack.length; i++) {
delete this.undefStack[i][name];
}
if (this.undefStack.length > 0) {
this.undefStack[this.undefStack.length - 1][name] = value;
}
} else {
// Undo this set at end of this group (possibly to `undefined`),
// unless an undo is already in place, in which case that older
// value is the correct one.
var top = this.undefStack[this.undefStack.length - 1];
if (top && !top.hasOwnProperty(name)) {
top[name] = this.current[name];
}
}
this.current[name] = value;
};
return Namespace;
}();
// CONCATENATED MODULE: ./src/macros.js
/**
* Predefined macros for KaTeX.
* This can be used to define some commands in terms of others.
*/
var builtinMacros = {};
/* harmony default export */ var macros = (builtinMacros); // This function might one day accept an additional argument and do more things.
function defineMacro(name, body) {
builtinMacros[name] = body;
} //////////////////////////////////////////////////////////////////////
// macro tools
// LaTeX's \@firstoftwo{#1}{#2} expands to #1, skipping #2
// TeX source: \long\def\@firstoftwo#1#2{#1}
defineMacro("\\@firstoftwo", function (context) {
var args = context.consumeArgs(2);
return {
tokens: args[0],
numArgs: 0
};
}); // LaTeX's \@secondoftwo{#1}{#2} expands to #2, skipping #1
// TeX source: \long\def\@secondoftwo#1#2{#2}
defineMacro("\\@secondoftwo", function (context) {
var args = context.consumeArgs(2);
return {
tokens: args[1],
numArgs: 0
};
}); // LaTeX's \@ifnextchar{#1}{#2}{#3} looks ahead to the next (unexpanded)
// symbol. If it matches #1, then the macro expands to #2; otherwise, #3.
// Note, however, that it does not consume the next symbol in either case.
defineMacro("\\@ifnextchar", function (context) {
var args = context.consumeArgs(3); // symbol, if, else
var nextToken = context.future();
if (args[0].length === 1 && args[0][0].text === nextToken.text) {
return {
tokens: args[1],
numArgs: 0
};
} else {
return {
tokens: args[2],
numArgs: 0
};
}
}); // LaTeX's \@ifstar{#1}{#2} looks ahead to the next (unexpanded) symbol.
// If it is `*`, then it consumes the symbol, and the macro expands to #1;
// otherwise, the macro expands to #2 (without consuming the symbol).
// TeX source: \def\@ifstar#1{\@ifnextchar *{\@firstoftwo{#1}}}
defineMacro("\\@ifstar", "\\@ifnextchar *{\\@firstoftwo{#1}}"); // LaTeX's \TextOrMath{#1}{#2} expands to #1 in text mode, #2 in math mode
defineMacro("\\TextOrMath", function (context) {
var args = context.consumeArgs(2);
if (context.mode === 'text') {
return {
tokens: args[0],
numArgs: 0
};
} else {
return {
tokens: args[1],
numArgs: 0
};
}
}); // Lookup table for parsing numbers in base 8 through 16
var digitToNumber = {
"0": 0,
"1": 1,
"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
"7": 7,
"8": 8,
"9": 9,
"a": 10,
"A": 10,
"b": 11,
"B": 11,
"c": 12,
"C": 12,
"d": 13,
"D": 13,
"e": 14,
"E": 14,
"f": 15,
"F": 15
}; // TeX \char makes a literal character (catcode 12) using the following forms:
// (see The TeXBook, p. 43)
// \char123 -- decimal
// \char'123 -- octal
// \char"123 -- hex
// \char`x -- character that can be written (i.e. isn't active)
// \char`\x -- character that cannot be written (e.g. %)
// These all refer to characters from the font, so we turn them into special
// calls to a function \@char dealt with in the Parser.
defineMacro("\\char", function (context) {
var token = context.popToken();
var base;
var number = '';
if (token.text === "'") {
base = 8;
token = context.popToken();
} else if (token.text === '"') {
base = 16;
token = context.popToken();
} else if (token.text === "`") {
token = context.popToken();
if (token.text[0] === "\\") {
number = token.text.charCodeAt(1);
} else if (token.text === "EOF") {
throw new src_ParseError("\\char` missing argument");
} else {
number = token.text.charCodeAt(0);
}
} else {
base = 10;
}
if (base) {
// Parse a number in the given base, starting with first `token`.
number = digitToNumber[token.text];
if (number == null || number >= base) {
throw new src_ParseError("Invalid base-" + base + " digit " + token.text);
}
var digit;
while ((digit = digitToNumber[context.future().text]) != null && digit < base) {
number *= base;
number += digit;
context.popToken();
}
}
return "\\@char{" + number + "}";
}); // Basic support for macro definitions:
// \def\macro{expansion}
// \def\macro#1{expansion}
// \def\macro#1#2{expansion}
// \def\macro#1#2#3#4#5#6#7#8#9{expansion}
// Also the \gdef and \global\def equivalents
var macros_def = function def(context, global) {
var arg = context.consumeArgs(1)[0];
if (arg.length !== 1) {
throw new src_ParseError("\\gdef's first argument must be a macro name");
}
var name = arg[0].text; // Count argument specifiers, and check they are in the order #1 #2 ...
var numArgs = 0;
arg = context.consumeArgs(1)[0];
while (arg.length === 1 && arg[0].text === "#") {
arg = context.consumeArgs(1)[0];
if (arg.length !== 1) {
throw new src_ParseError("Invalid argument number length \"" + arg.length + "\"");
}
if (!/^[1-9]$/.test(arg[0].text)) {
throw new src_ParseError("Invalid argument number \"" + arg[0].text + "\"");
}
numArgs++;
if (parseInt(arg[0].text) !== numArgs) {
throw new src_ParseError("Argument number \"" + arg[0].text + "\" out of order");
}
arg = context.consumeArgs(1)[0];
} // Final arg is the expansion of the macro
context.macros.set(name, {
tokens: arg,
numArgs: numArgs
}, global);
return '';
};
defineMacro("\\gdef", function (context) {
return macros_def(context, true);
});
defineMacro("\\def", function (context) {
return macros_def(context, false);
});
defineMacro("\\global", function (context) {
var next = context.consumeArgs(1)[0];
if (next.length !== 1) {
throw new src_ParseError("Invalid command after \\global");
}
var command = next[0].text; // TODO: Should expand command
if (command === "\\def") {
// \global\def is equivalent to \gdef
return macros_def(context, true);
} else {
throw new src_ParseError("Invalid command '" + command + "' after \\global");
}
}); // \newcommand{\macro}[args]{definition}
// \renewcommand{\macro}[args]{definition}
// TODO: Optional arguments: \newcommand{\macro}[args][default]{definition}
var macros_newcommand = function newcommand(context, existsOK, nonexistsOK) {
var arg = context.consumeArgs(1)[0];
if (arg.length !== 1) {
throw new src_ParseError("\\newcommand's first argument must be a macro name");
}
var name = arg[0].text;
var exists = context.isDefined(name);
if (exists && !existsOK) {
throw new src_ParseError("\\newcommand{" + name + "} attempting to redefine " + (name + "; use \\renewcommand"));
}
if (!exists && !nonexistsOK) {
throw new src_ParseError("\\renewcommand{" + name + "} when command " + name + " " + "does not yet exist; use \\newcommand");
}
var numArgs = 0;
arg = context.consumeArgs(1)[0];
if (arg.length === 1 && arg[0].text === "[") {
var argText = '';
var token = context.expandNextToken();
while (token.text !== "]" && token.text !== "EOF") {
// TODO: Should properly expand arg, e.g., ignore {}s
argText += token.text;
token = context.expandNextToken();
}
if (!argText.match(/^\s*[0-9]+\s*$/)) {
throw new src_ParseError("Invalid number of arguments: " + argText);
}
numArgs = parseInt(argText);
arg = context.consumeArgs(1)[0];
} // Final arg is the expansion of the macro
context.macros.set(name, {
tokens: arg,
numArgs: numArgs
});
return '';
};
defineMacro("\\newcommand", function (context) {
return macros_newcommand(context, false, true);
});
defineMacro("\\renewcommand", function (context) {
return macros_newcommand(context, true, false);
});
defineMacro("\\providecommand", function (context) {
return macros_newcommand(context, true, true);
}); //////////////////////////////////////////////////////////////////////
// Grouping
// \let\bgroup={ \let\egroup=}
defineMacro("\\bgroup", "{");
defineMacro("\\egroup", "}"); // Symbols from latex.ltx:
// \def\lq{`}
// \def\rq{'}
// \def \aa {\r a}
// \def \AA {\r A}
defineMacro("\\lq", "`");
defineMacro("\\rq", "'");
defineMacro("\\aa", "\\r a");
defineMacro("\\AA", "\\r A"); // Copyright (C) and registered (R) symbols. Use raw symbol in MathML.
// \DeclareTextCommandDefault{\textcopyright}{\textcircled{c}}
// \DeclareTextCommandDefault{\textregistered}{\textcircled{%
// \check@mathfonts\fontsize\sf@size\z@\math@fontsfalse\selectfont R}}
// \DeclareRobustCommand{\copyright}{%
// \ifmmode{\nfss@text{\textcopyright}}\else\textcopyright\fi}
defineMacro("\\textcopyright", "\\html@mathml{\\textcircled{c}}{\\char`©}");
defineMacro("\\copyright", "\\TextOrMath{\\textcopyright}{\\text{\\textcopyright}}");
defineMacro("\\textregistered", "\\html@mathml{\\textcircled{\\scriptsize R}}{\\char`®}"); // Characters omitted from Unicode range 1D4001D7FF
defineMacro("\u212C", "\\mathscr{B}"); // script
defineMacro("\u2130", "\\mathscr{E}");
defineMacro("\u2131", "\\mathscr{F}");
defineMacro("\u210B", "\\mathscr{H}");
defineMacro("\u2110", "\\mathscr{I}");
defineMacro("\u2112", "\\mathscr{L}");
defineMacro("\u2133", "\\mathscr{M}");
defineMacro("\u211B", "\\mathscr{R}");
defineMacro("\u212D", "\\mathfrak{C}"); // Fraktur
defineMacro("\u210C", "\\mathfrak{H}");
defineMacro("\u2128", "\\mathfrak{Z}"); // Define \Bbbk with a macro that works in both HTML and MathML.
defineMacro("\\Bbbk", "\\Bbb{k}"); // Unicode middle dot
// The KaTeX fonts do not contain U+00B7. Instead, \cdotp displays
// the dot at U+22C5 and gives it punct spacing.
defineMacro("\xB7", "\\cdotp"); // \llap and \rlap render their contents in text mode
defineMacro("\\llap", "\\mathllap{\\textrm{#1}}");
defineMacro("\\rlap", "\\mathrlap{\\textrm{#1}}");
defineMacro("\\clap", "\\mathclap{\\textrm{#1}}"); // \not is defined by base/fontmath.ltx via
// \DeclareMathSymbol{\not}{\mathrel}{symbols}{"36}
// It's thus treated like a \mathrel, but defined by a symbol that has zero
// width but extends to the right. We use \rlap to get that spacing.
// For MathML we write U+0338 here. buildMathML.js will then do the overlay.
defineMacro("\\not", '\\html@mathml{\\mathrel{\\mathrlap\\@not}}{\\char"338}'); // Negated symbols from base/fontmath.ltx:
// \def\neq{\not=} \let\ne=\neq
// \DeclareRobustCommand
// \notin{\mathrel{\m@th\mathpalette\c@ncel\in}}
// \def\c@ncel#1#2{\m@th\ooalign{$\hfil#1\mkern1mu/\hfil$\crcr$#1#2$}}
defineMacro("\\neq", "\\html@mathml{\\mathrel{\\not=}}{\\mathrel{\\char`≠}}");
defineMacro("\\ne", "\\neq");
defineMacro("\u2260", "\\neq");
defineMacro("\\notin", "\\html@mathml{\\mathrel{{\\in}\\mathllap{/\\mskip1mu}}}" + "{\\mathrel{\\char`∉}}");
defineMacro("\u2209", "\\notin"); // Unicode stacked relations
defineMacro("\u2258", "\\html@mathml{" + "\\mathrel{=\\kern{-1em}\\raisebox{0.4em}{$\\scriptsize\\frown$}}" + "}{\\mathrel{\\char`\u2258}}");
defineMacro("\u2259", "\\html@mathml{\\stackrel{\\tiny\\wedge}{=}}{\\mathrel{\\char`\u2258}}");
defineMacro("\u225A", "\\html@mathml{\\stackrel{\\tiny\\vee}{=}}{\\mathrel{\\char`\u225A}}");
defineMacro("\u225B", "\\html@mathml{\\stackrel{\\scriptsize\\star}{=}}" + "{\\mathrel{\\char`\u225B}}");
defineMacro("\u225D", "\\html@mathml{\\stackrel{\\tiny\\mathrm{def}}{=}}" + "{\\mathrel{\\char`\u225D}}");
defineMacro("\u225E", "\\html@mathml{\\stackrel{\\tiny\\mathrm{m}}{=}}" + "{\\mathrel{\\char`\u225E}}");
defineMacro("\u225F", "\\html@mathml{\\stackrel{\\tiny?}{=}}{\\mathrel{\\char`\u225F}}"); // Misc Unicode
defineMacro("\u27C2", "\\perp");
defineMacro("\u203C", "\\mathclose{!\\mkern-0.8mu!}");
defineMacro("\u220C", "\\notni");
defineMacro("\u231C", "\\ulcorner");
defineMacro("\u231D", "\\urcorner");
defineMacro("\u231E", "\\llcorner");
defineMacro("\u231F", "\\lrcorner");
defineMacro("\xA9", "\\copyright");
defineMacro("\xAE", "\\textregistered");
defineMacro("\uFE0F", "\\textregistered"); //////////////////////////////////////////////////////////////////////
// LaTeX_2ε
// \vdots{\vbox{\baselineskip4\p@ \lineskiplimit\z@
// \kern6\p@\hbox{.}\hbox{.}\hbox{.}}}
// We'll call \varvdots, which gets a glyph from symbols.js.
// The zero-width rule gets us an equivalent to the vertical 6pt kern.
defineMacro("\\vdots", "\\mathord{\\varvdots\\rule{0pt}{15pt}}");
defineMacro("\u22EE", "\\vdots"); //////////////////////////////////////////////////////////////////////
// amsmath.sty
// http://mirrors.concertpass.com/tex-archive/macros/latex/required/amsmath/amsmath.pdf
// Italic Greek capital letters. AMS defines these with \DeclareMathSymbol,
// but they are equivalent to \mathit{\Letter}.
defineMacro("\\varGamma", "\\mathit{\\Gamma}");
defineMacro("\\varDelta", "\\mathit{\\Delta}");
defineMacro("\\varTheta", "\\mathit{\\Theta}");
defineMacro("\\varLambda", "\\mathit{\\Lambda}");
defineMacro("\\varXi", "\\mathit{\\Xi}");
defineMacro("\\varPi", "\\mathit{\\Pi}");
defineMacro("\\varSigma", "\\mathit{\\Sigma}");
defineMacro("\\varUpsilon", "\\mathit{\\Upsilon}");
defineMacro("\\varPhi", "\\mathit{\\Phi}");
defineMacro("\\varPsi", "\\mathit{\\Psi}");
defineMacro("\\varOmega", "\\mathit{\\Omega}"); //\newcommand{\substack}[1]{\subarray{c}#1\endsubarray}
defineMacro("\\substack", "\\begin{subarray}{c}#1\\end{subarray}"); // \renewcommand{\colon}{\nobreak\mskip2mu\mathpunct{}\nonscript
// \mkern-\thinmuskip{:}\mskip6muplus1mu\relax}
defineMacro("\\colon", "\\nobreak\\mskip2mu\\mathpunct{}" + "\\mathchoice{\\mkern-3mu}{\\mkern-3mu}{}{}{:}\\mskip6mu"); // \newcommand{\boxed}[1]{\fbox{\m@th$\displaystyle#1$}}
defineMacro("\\boxed", "\\fbox{$\\displaystyle{#1}$}"); // \def\iff{\DOTSB\;\Longleftrightarrow\;}
// \def\implies{\DOTSB\;\Longrightarrow\;}
// \def\impliedby{\DOTSB\;\Longleftarrow\;}
defineMacro("\\iff", "\\DOTSB\\;\\Longleftrightarrow\\;");
defineMacro("\\implies", "\\DOTSB\\;\\Longrightarrow\\;");
defineMacro("\\impliedby", "\\DOTSB\\;\\Longleftarrow\\;"); // AMSMath's automatic \dots, based on \mdots@@ macro.
var dotsByToken = {
',': '\\dotsc',
'\\not': '\\dotsb',
// \keybin@ checks for the following:
'+': '\\dotsb',
'=': '\\dotsb',
'<': '\\dotsb',
'>': '\\dotsb',
'-': '\\dotsb',
'*': '\\dotsb',
':': '\\dotsb',
// Symbols whose definition starts with \DOTSB:
'\\DOTSB': '\\dotsb',
'\\coprod': '\\dotsb',
'\\bigvee': '\\dotsb',
'\\bigwedge': '\\dotsb',
'\\biguplus': '\\dotsb',
'\\bigcap': '\\dotsb',
'\\bigcup': '\\dotsb',
'\\prod': '\\dotsb',
'\\sum': '\\dotsb',
'\\bigotimes': '\\dotsb',
'\\bigoplus': '\\dotsb',
'\\bigodot': '\\dotsb',
'\\bigsqcup': '\\dotsb',
'\\And': '\\dotsb',
'\\longrightarrow': '\\dotsb',
'\\Longrightarrow': '\\dotsb',
'\\longleftarrow': '\\dotsb',
'\\Longleftarrow': '\\dotsb',
'\\longleftrightarrow': '\\dotsb',
'\\Longleftrightarrow': '\\dotsb',
'\\mapsto': '\\dotsb',
'\\longmapsto': '\\dotsb',
'\\hookrightarrow': '\\dotsb',
'\\doteq': '\\dotsb',
// Symbols whose definition starts with \mathbin:
'\\mathbin': '\\dotsb',
// Symbols whose definition starts with \mathrel:
'\\mathrel': '\\dotsb',
'\\relbar': '\\dotsb',
'\\Relbar': '\\dotsb',
'\\xrightarrow': '\\dotsb',
'\\xleftarrow': '\\dotsb',
// Symbols whose definition starts with \DOTSI:
'\\DOTSI': '\\dotsi',
'\\int': '\\dotsi',
'\\oint': '\\dotsi',
'\\iint': '\\dotsi',
'\\iiint': '\\dotsi',
'\\iiiint': '\\dotsi',
'\\idotsint': '\\dotsi',
// Symbols whose definition starts with \DOTSX:
'\\DOTSX': '\\dotsx'
};
defineMacro("\\dots", function (context) {
// TODO: If used in text mode, should expand to \textellipsis.
// However, in KaTeX, \textellipsis and \ldots behave the same
// (in text mode), and it's unlikely we'd see any of the math commands
// that affect the behavior of \dots when in text mode. So fine for now
// (until we support \ifmmode ... \else ... \fi).
var thedots = '\\dotso';
var next = context.expandAfterFuture().text;
if (next in dotsByToken) {
thedots = dotsByToken[next];
} else if (next.substr(0, 4) === '\\not') {
thedots = '\\dotsb';
} else if (next in src_symbols.math) {
if (utils.contains(['bin', 'rel'], src_symbols.math[next].group)) {
thedots = '\\dotsb';
}
}
return thedots;
});
var spaceAfterDots = {
// \rightdelim@ checks for the following:
')': true,
']': true,
'\\rbrack': true,
'\\}': true,
'\\rbrace': true,
'\\rangle': true,
'\\rceil': true,
'\\rfloor': true,
'\\rgroup': true,
'\\rmoustache': true,
'\\right': true,
'\\bigr': true,
'\\biggr': true,
'\\Bigr': true,
'\\Biggr': true,
// \extra@ also tests for the following:
'$': true,
// \extrap@ checks for the following:
';': true,
'.': true,
',': true
};
defineMacro("\\dotso", function (context) {
var next = context.future().text;
if (next in spaceAfterDots) {
return "\\ldots\\,";
} else {
return "\\ldots";
}
});
defineMacro("\\dotsc", function (context) {
var next = context.future().text; // \dotsc uses \extra@ but not \extrap@, instead specially checking for
// ';' and '.', but doesn't check for ','.
if (next in spaceAfterDots && next !== ',') {
return "\\ldots\\,";
} else {
return "\\ldots";
}
});
defineMacro("\\cdots", function (context) {
var next = context.future().text;
if (next in spaceAfterDots) {
return "\\@cdots\\,";
} else {
return "\\@cdots";
}
});
defineMacro("\\dotsb", "\\cdots");
defineMacro("\\dotsm", "\\cdots");
defineMacro("\\dotsi", "\\!\\cdots"); // amsmath doesn't actually define \dotsx, but \dots followed by a macro
// starting with \DOTSX implies \dotso, and then \extra@ detects this case
// and forces the added `\,`.
defineMacro("\\dotsx", "\\ldots\\,"); // \let\DOTSI\relax
// \let\DOTSB\relax
// \let\DOTSX\relax
defineMacro("\\DOTSI", "\\relax");
defineMacro("\\DOTSB", "\\relax");
defineMacro("\\DOTSX", "\\relax"); // Spacing, based on amsmath.sty's override of LaTeX defaults
// \DeclareRobustCommand{\tmspace}[3]{%
// \ifmmode\mskip#1#2\else\kern#1#3\fi\relax}
defineMacro("\\tmspace", "\\TextOrMath{\\kern#1#3}{\\mskip#1#2}\\relax"); // \renewcommand{\,}{\tmspace+\thinmuskip{.1667em}}
// TODO: math mode should use \thinmuskip
defineMacro("\\,", "\\tmspace+{3mu}{.1667em}"); // \let\thinspace\,
defineMacro("\\thinspace", "\\,"); // \def\>{\mskip\medmuskip}
// \renewcommand{\:}{\tmspace+\medmuskip{.2222em}}
// TODO: \> and math mode of \: should use \medmuskip = 4mu plus 2mu minus 4mu
defineMacro("\\>", "\\mskip{4mu}");
defineMacro("\\:", "\\tmspace+{4mu}{.2222em}"); // \let\medspace\:
defineMacro("\\medspace", "\\:"); // \renewcommand{\;}{\tmspace+\thickmuskip{.2777em}}
// TODO: math mode should use \thickmuskip = 5mu plus 5mu
defineMacro("\\;", "\\tmspace+{5mu}{.2777em}"); // \let\thickspace\;
defineMacro("\\thickspace", "\\;"); // \renewcommand{\!}{\tmspace-\thinmuskip{.1667em}}
// TODO: math mode should use \thinmuskip
defineMacro("\\!", "\\tmspace-{3mu}{.1667em}"); // \let\negthinspace\!
defineMacro("\\negthinspace", "\\!"); // \newcommand{\negmedspace}{\tmspace-\medmuskip{.2222em}}
// TODO: math mode should use \medmuskip
defineMacro("\\negmedspace", "\\tmspace-{4mu}{.2222em}"); // \newcommand{\negthickspace}{\tmspace-\thickmuskip{.2777em}}
// TODO: math mode should use \thickmuskip
defineMacro("\\negthickspace", "\\tmspace-{5mu}{.277em}"); // \def\enspace{\kern.5em }
defineMacro("\\enspace", "\\kern.5em "); // \def\enskip{\hskip.5em\relax}
defineMacro("\\enskip", "\\hskip.5em\\relax"); // \def\quad{\hskip1em\relax}
defineMacro("\\quad", "\\hskip1em\\relax"); // \def\qquad{\hskip2em\relax}
defineMacro("\\qquad", "\\hskip2em\\relax"); // \tag@in@display form of \tag
defineMacro("\\tag", "\\@ifstar\\tag@literal\\tag@paren");
defineMacro("\\tag@paren", "\\tag@literal{({#1})}");
defineMacro("\\tag@literal", function (context) {
if (context.macros.get("\\df@tag")) {
throw new src_ParseError("Multiple \\tag");
}
return "\\gdef\\df@tag{\\text{#1}}";
}); // \renewcommand{\bmod}{\nonscript\mskip-\medmuskip\mkern5mu\mathbin
// {\operator@font mod}\penalty900
// \mkern5mu\nonscript\mskip-\medmuskip}
// \newcommand{\pod}[1]{\allowbreak
// \if@display\mkern18mu\else\mkern8mu\fi(#1)}
// \renewcommand{\pmod}[1]{\pod{{\operator@font mod}\mkern6mu#1}}
// \newcommand{\mod}[1]{\allowbreak\if@display\mkern18mu
// \else\mkern12mu\fi{\operator@font mod}\,\,#1}
// TODO: math mode should use \medmuskip = 4mu plus 2mu minus 4mu
defineMacro("\\bmod", "\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}" + "\\mathbin{\\rm mod}" + "\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}");
defineMacro("\\pod", "\\allowbreak" + "\\mathchoice{\\mkern18mu}{\\mkern8mu}{\\mkern8mu}{\\mkern8mu}(#1)");
defineMacro("\\pmod", "\\pod{{\\rm mod}\\mkern6mu#1}");
defineMacro("\\mod", "\\allowbreak" + "\\mathchoice{\\mkern18mu}{\\mkern12mu}{\\mkern12mu}{\\mkern12mu}" + "{\\rm mod}\\,\\,#1"); // \pmb -- A simulation of bold.
// The version in ambsy.sty works by typesetting three copies of the argument
// with small offsets. We use two copies. We omit the vertical offset because
// of rendering problems that makeVList encounters in Safari.
defineMacro("\\pmb", "\\html@mathml{" + "\\@binrel{#1}{\\mathrlap{#1}\\kern0.5px#1}}" + "{\\mathbf{#1}}"); //////////////////////////////////////////////////////////////////////
// LaTeX source2e
// \\ defaults to \newline, but changes to \cr within array environment
defineMacro("\\\\", "\\newline"); // \def\TeX{T\kern-.1667em\lower.5ex\hbox{E}\kern-.125emX\@}
// TODO: Doesn't normally work in math mode because \@ fails. KaTeX doesn't
// support \@ yet, so that's omitted, and we add \text so that the result
// doesn't look funny in math mode.
defineMacro("\\TeX", "\\textrm{\\html@mathml{" + "T\\kern-.1667em\\raisebox{-.5ex}{E}\\kern-.125emX" + "}{TeX}}"); // \DeclareRobustCommand{\LaTeX}{L\kern-.36em%
// {\sbox\z@ T%
// \vbox to\ht\z@{\hbox{\check@mathfonts
// \fontsize\sf@size\z@
// \math@fontsfalse\selectfont
// A}%
// \vss}%
// }%
// \kern-.15em%
// \TeX}
// This code aligns the top of the A with the T (from the perspective of TeX's
// boxes, though visually the A appears to extend above slightly).
// We compute the corresponding \raisebox when A is rendered in \normalsize
// \scriptstyle, which has a scale factor of 0.7 (see Options.js).
var latexRaiseA = fontMetricsData['Main-Regular']["T".charCodeAt(0)][1] - 0.7 * fontMetricsData['Main-Regular']["A".charCodeAt(0)][1] + "em";
defineMacro("\\LaTeX", "\\textrm{\\html@mathml{" + ("L\\kern-.36em\\raisebox{" + latexRaiseA + "}{\\scriptstyle A}") + "\\kern-.15em\\TeX}{LaTeX}}"); // New KaTeX logo based on tweaking LaTeX logo
defineMacro("\\KaTeX", "\\textrm{\\html@mathml{" + ("K\\kern-.17em\\raisebox{" + latexRaiseA + "}{\\scriptstyle A}") + "\\kern-.15em\\TeX}{KaTeX}}"); // \DeclareRobustCommand\hspace{\@ifstar\@hspacer\@hspace}
// \def\@hspace#1{\hskip #1\relax}
// \def\@hspacer#1{\vrule \@width\z@\nobreak
// \hskip #1\hskip \z@skip}
defineMacro("\\hspace", "\\@ifstar\\@hspacer\\@hspace");
defineMacro("\\@hspace", "\\hskip #1\\relax");
defineMacro("\\@hspacer", "\\rule{0pt}{0pt}\\hskip #1\\relax"); //////////////////////////////////////////////////////////////////////
// mathtools.sty
//\providecommand\ordinarycolon{:}
defineMacro("\\ordinarycolon", ":"); //\def\vcentcolon{\mathrel{\mathop\ordinarycolon}}
//TODO(edemaine): Not yet centered. Fix via \raisebox or #726
defineMacro("\\vcentcolon", "\\mathrel{\\mathop\\ordinarycolon}"); // \providecommand*\dblcolon{\vcentcolon\mathrel{\mkern-.9mu}\vcentcolon}
defineMacro("\\dblcolon", "\\html@mathml{" + "\\mathrel{\\vcentcolon\\mathrel{\\mkern-.9mu}\\vcentcolon}}" + "{\\mathop{\\char\"2237}}"); // \providecommand*\coloneqq{\vcentcolon\mathrel{\mkern-1.2mu}=}
defineMacro("\\coloneqq", "\\html@mathml{" + "\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}=}}" + "{\\mathop{\\char\"2254}}"); // ≔
// \providecommand*\Coloneqq{\dblcolon\mathrel{\mkern-1.2mu}=}
defineMacro("\\Coloneqq", "\\html@mathml{" + "\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}=}}" + "{\\mathop{\\char\"2237\\char\"3d}}"); // \providecommand*\coloneq{\vcentcolon\mathrel{\mkern-1.2mu}\mathrel{-}}
defineMacro("\\coloneq", "\\html@mathml{" + "\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}" + "{\\mathop{\\char\"3a\\char\"2212}}"); // \providecommand*\Coloneq{\dblcolon\mathrel{\mkern-1.2mu}\mathrel{-}}
defineMacro("\\Coloneq", "\\html@mathml{" + "\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}" + "{\\mathop{\\char\"2237\\char\"2212}}"); // \providecommand*\eqqcolon{=\mathrel{\mkern-1.2mu}\vcentcolon}
defineMacro("\\eqqcolon", "\\html@mathml{" + "\\mathrel{=\\mathrel{\\mkern-1.2mu}\\vcentcolon}}" + "{\\mathop{\\char\"2255}}"); // ≕
// \providecommand*\Eqqcolon{=\mathrel{\mkern-1.2mu}\dblcolon}
defineMacro("\\Eqqcolon", "\\html@mathml{" + "\\mathrel{=\\mathrel{\\mkern-1.2mu}\\dblcolon}}" + "{\\mathop{\\char\"3d\\char\"2237}}"); // \providecommand*\eqcolon{\mathrel{-}\mathrel{\mkern-1.2mu}\vcentcolon}
defineMacro("\\eqcolon", "\\html@mathml{" + "\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\vcentcolon}}" + "{\\mathop{\\char\"2239}}"); // \providecommand*\Eqcolon{\mathrel{-}\mathrel{\mkern-1.2mu}\dblcolon}
defineMacro("\\Eqcolon", "\\html@mathml{" + "\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\dblcolon}}" + "{\\mathop{\\char\"2212\\char\"2237}}"); // \providecommand*\colonapprox{\vcentcolon\mathrel{\mkern-1.2mu}\approx}
defineMacro("\\colonapprox", "\\html@mathml{" + "\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\approx}}" + "{\\mathop{\\char\"3a\\char\"2248}}"); // \providecommand*\Colonapprox{\dblcolon\mathrel{\mkern-1.2mu}\approx}
defineMacro("\\Colonapprox", "\\html@mathml{" + "\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\approx}}" + "{\\mathop{\\char\"2237\\char\"2248}}"); // \providecommand*\colonsim{\vcentcolon\mathrel{\mkern-1.2mu}\sim}
defineMacro("\\colonsim", "\\html@mathml{" + "\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\sim}}" + "{\\mathop{\\char\"3a\\char\"223c}}"); // \providecommand*\Colonsim{\dblcolon\mathrel{\mkern-1.2mu}\sim}
defineMacro("\\Colonsim", "\\html@mathml{" + "\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\sim}}" + "{\\mathop{\\char\"2237\\char\"223c}}"); // Some Unicode characters are implemented with macros to mathtools functions.
defineMacro("\u2237", "\\dblcolon"); // ::
defineMacro("\u2239", "\\eqcolon"); // -:
defineMacro("\u2254", "\\coloneqq"); // :=
defineMacro("\u2255", "\\eqqcolon"); // =:
defineMacro("\u2A74", "\\Coloneqq"); // ::=
//////////////////////////////////////////////////////////////////////
// colonequals.sty
// Alternate names for mathtools's macros:
defineMacro("\\ratio", "\\vcentcolon");
defineMacro("\\coloncolon", "\\dblcolon");
defineMacro("\\colonequals", "\\coloneqq");
defineMacro("\\coloncolonequals", "\\Coloneqq");
defineMacro("\\equalscolon", "\\eqqcolon");
defineMacro("\\equalscoloncolon", "\\Eqqcolon");
defineMacro("\\colonminus", "\\coloneq");
defineMacro("\\coloncolonminus", "\\Coloneq");
defineMacro("\\minuscolon", "\\eqcolon");
defineMacro("\\minuscoloncolon", "\\Eqcolon"); // \colonapprox name is same in mathtools and colonequals.
defineMacro("\\coloncolonapprox", "\\Colonapprox"); // \colonsim name is same in mathtools and colonequals.
defineMacro("\\coloncolonsim", "\\Colonsim"); // Additional macros, implemented by analogy with mathtools definitions:
defineMacro("\\simcolon", "\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\vcentcolon}");
defineMacro("\\simcoloncolon", "\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\dblcolon}");
defineMacro("\\approxcolon", "\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\vcentcolon}");
defineMacro("\\approxcoloncolon", "\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\dblcolon}"); // Present in newtxmath, pxfonts and txfonts
defineMacro("\\notni", "\\html@mathml{\\not\\ni}{\\mathrel{\\char`\u220C}}");
defineMacro("\\limsup", "\\DOTSB\\operatorname*{lim\\,sup}");
defineMacro("\\liminf", "\\DOTSB\\operatorname*{lim\\,inf}"); //////////////////////////////////////////////////////////////////////
// MathML alternates for KaTeX glyphs in the Unicode private area
defineMacro("\\gvertneqq", "\\html@mathml{\\@gvertneqq}{\u2269}");
defineMacro("\\lvertneqq", "\\html@mathml{\\@lvertneqq}{\u2268}");
defineMacro("\\ngeqq", "\\html@mathml{\\@ngeqq}{\u2271}");
defineMacro("\\ngeqslant", "\\html@mathml{\\@ngeqslant}{\u2271}");
defineMacro("\\nleqq", "\\html@mathml{\\@nleqq}{\u2270}");
defineMacro("\\nleqslant", "\\html@mathml{\\@nleqslant}{\u2270}");
defineMacro("\\nshortmid", "\\html@mathml{\\@nshortmid}{∤}");
defineMacro("\\nshortparallel", "\\html@mathml{\\@nshortparallel}{∦}");
defineMacro("\\nsubseteqq", "\\html@mathml{\\@nsubseteqq}{\u2288}");
defineMacro("\\nsupseteqq", "\\html@mathml{\\@nsupseteqq}{\u2289}");
defineMacro("\\varsubsetneq", "\\html@mathml{\\@varsubsetneq}{⊊}");
defineMacro("\\varsubsetneqq", "\\html@mathml{\\@varsubsetneqq}{⫋}");
defineMacro("\\varsupsetneq", "\\html@mathml{\\@varsupsetneq}{⊋}");
defineMacro("\\varsupsetneqq", "\\html@mathml{\\@varsupsetneqq}{⫌}"); //////////////////////////////////////////////////////////////////////
// stmaryrd and semantic
// The stmaryrd and semantic packages render the next four items by calling a
// glyph. Those glyphs do not exist in the KaTeX fonts. Hence the macros.
defineMacro("\\llbracket", "\\html@mathml{" + "\\mathopen{[\\mkern-3.2mu[}}" + "{\\mathopen{\\char`\u27E6}}");
defineMacro("\\rrbracket", "\\html@mathml{" + "\\mathclose{]\\mkern-3.2mu]}}" + "{\\mathclose{\\char`\u27E7}}");
defineMacro("\u27E6", "\\llbracket"); // blackboard bold [
defineMacro("\u27E7", "\\rrbracket"); // blackboard bold ]
defineMacro("\\lBrace", "\\html@mathml{" + "\\mathopen{\\{\\mkern-3.2mu[}}" + "{\\mathopen{\\char`\u2983}}");
defineMacro("\\rBrace", "\\html@mathml{" + "\\mathclose{]\\mkern-3.2mu\\}}}" + "{\\mathclose{\\char`\u2984}}");
defineMacro("\u2983", "\\lBrace"); // blackboard bold {
defineMacro("\u2984", "\\rBrace"); // blackboard bold }
// TODO: Create variable sized versions of the last two items. I believe that
// will require new font glyphs.
//////////////////////////////////////////////////////////////////////
// texvc.sty
// The texvc package contains macros available in mediawiki pages.
// We omit the functions deprecated at
// https://en.wikipedia.org/wiki/Help:Displaying_a_formula#Deprecated_syntax
// We also omit texvc's \O, which conflicts with \text{\O}
defineMacro("\\darr", "\\downarrow");
defineMacro("\\dArr", "\\Downarrow");
defineMacro("\\Darr", "\\Downarrow");
defineMacro("\\lang", "\\langle");
defineMacro("\\rang", "\\rangle");
defineMacro("\\uarr", "\\uparrow");
defineMacro("\\uArr", "\\Uparrow");
defineMacro("\\Uarr", "\\Uparrow");
defineMacro("\\N", "\\mathbb{N}");
defineMacro("\\R", "\\mathbb{R}");
defineMacro("\\Z", "\\mathbb{Z}");
defineMacro("\\alef", "\\aleph");
defineMacro("\\alefsym", "\\aleph");
defineMacro("\\Alpha", "\\mathrm{A}");
defineMacro("\\Beta", "\\mathrm{B}");
defineMacro("\\bull", "\\bullet");
defineMacro("\\Chi", "\\mathrm{X}");
defineMacro("\\clubs", "\\clubsuit");
defineMacro("\\cnums", "\\mathbb{C}");
defineMacro("\\Complex", "\\mathbb{C}");
defineMacro("\\Dagger", "\\ddagger");
defineMacro("\\diamonds", "\\diamondsuit");
defineMacro("\\empty", "\\emptyset");
defineMacro("\\Epsilon", "\\mathrm{E}");
defineMacro("\\Eta", "\\mathrm{H}");
defineMacro("\\exist", "\\exists");
defineMacro("\\harr", "\\leftrightarrow");
defineMacro("\\hArr", "\\Leftrightarrow");
defineMacro("\\Harr", "\\Leftrightarrow");
defineMacro("\\hearts", "\\heartsuit");
defineMacro("\\image", "\\Im");
defineMacro("\\infin", "\\infty");
defineMacro("\\Iota", "\\mathrm{I}");
defineMacro("\\isin", "\\in");
defineMacro("\\Kappa", "\\mathrm{K}");
defineMacro("\\larr", "\\leftarrow");
defineMacro("\\lArr", "\\Leftarrow");
defineMacro("\\Larr", "\\Leftarrow");
defineMacro("\\lrarr", "\\leftrightarrow");
defineMacro("\\lrArr", "\\Leftrightarrow");
defineMacro("\\Lrarr", "\\Leftrightarrow");
defineMacro("\\Mu", "\\mathrm{M}");
defineMacro("\\natnums", "\\mathbb{N}");
defineMacro("\\Nu", "\\mathrm{N}");
defineMacro("\\Omicron", "\\mathrm{O}");
defineMacro("\\plusmn", "\\pm");
defineMacro("\\rarr", "\\rightarrow");
defineMacro("\\rArr", "\\Rightarrow");
defineMacro("\\Rarr", "\\Rightarrow");
defineMacro("\\real", "\\Re");
defineMacro("\\reals", "\\mathbb{R}");
defineMacro("\\Reals", "\\mathbb{R}");
defineMacro("\\Rho", "\\mathrm{P}");
defineMacro("\\sdot", "\\cdot");
defineMacro("\\sect", "\\S");
defineMacro("\\spades", "\\spadesuit");
defineMacro("\\sub", "\\subset");
defineMacro("\\sube", "\\subseteq");
defineMacro("\\supe", "\\supseteq");
defineMacro("\\Tau", "\\mathrm{T}");
defineMacro("\\thetasym", "\\vartheta"); // TODO: defineMacro("\\varcoppa", "\\\mbox{\\coppa}");
defineMacro("\\weierp", "\\wp");
defineMacro("\\Zeta", "\\mathrm{Z}"); //////////////////////////////////////////////////////////////////////
// statmath.sty
// https://ctan.math.illinois.edu/macros/latex/contrib/statmath/statmath.pdf
defineMacro("\\argmin", "\\DOTSB\\operatorname*{arg\\,min}");
defineMacro("\\argmax", "\\DOTSB\\operatorname*{arg\\,max}");
defineMacro("\\plim", "\\DOTSB\\mathop{\\operatorname{plim}}\\limits"); // Custom Khan Academy colors, should be moved to an optional package
defineMacro("\\blue", "\\textcolor{##6495ed}{#1}");
defineMacro("\\orange", "\\textcolor{##ffa500}{#1}");
defineMacro("\\pink", "\\textcolor{##ff00af}{#1}");
defineMacro("\\red", "\\textcolor{##df0030}{#1}");
defineMacro("\\green", "\\textcolor{##28ae7b}{#1}");
defineMacro("\\gray", "\\textcolor{gray}{#1}");
defineMacro("\\purple", "\\textcolor{##9d38bd}{#1}");
defineMacro("\\blueA", "\\textcolor{##ccfaff}{#1}");
defineMacro("\\blueB", "\\textcolor{##80f6ff}{#1}");
defineMacro("\\blueC", "\\textcolor{##63d9ea}{#1}");
defineMacro("\\blueD", "\\textcolor{##11accd}{#1}");
defineMacro("\\blueE", "\\textcolor{##0c7f99}{#1}");
defineMacro("\\tealA", "\\textcolor{##94fff5}{#1}");
defineMacro("\\tealB", "\\textcolor{##26edd5}{#1}");
defineMacro("\\tealC", "\\textcolor{##01d1c1}{#1}");
defineMacro("\\tealD", "\\textcolor{##01a995}{#1}");
defineMacro("\\tealE", "\\textcolor{##208170}{#1}");
defineMacro("\\greenA", "\\textcolor{##b6ffb0}{#1}");
defineMacro("\\greenB", "\\textcolor{##8af281}{#1}");
defineMacro("\\greenC", "\\textcolor{##74cf70}{#1}");
defineMacro("\\greenD", "\\textcolor{##1fab54}{#1}");
defineMacro("\\greenE", "\\textcolor{##0d923f}{#1}");
defineMacro("\\goldA", "\\textcolor{##ffd0a9}{#1}");
defineMacro("\\goldB", "\\textcolor{##ffbb71}{#1}");
defineMacro("\\goldC", "\\textcolor{##ff9c39}{#1}");
defineMacro("\\goldD", "\\textcolor{##e07d10}{#1}");
defineMacro("\\goldE", "\\textcolor{##a75a05}{#1}");
defineMacro("\\redA", "\\textcolor{##fca9a9}{#1}");
defineMacro("\\redB", "\\textcolor{##ff8482}{#1}");
defineMacro("\\redC", "\\textcolor{##f9685d}{#1}");
defineMacro("\\redD", "\\textcolor{##e84d39}{#1}");
defineMacro("\\redE", "\\textcolor{##bc2612}{#1}");
defineMacro("\\maroonA", "\\textcolor{##ffbde0}{#1}");
defineMacro("\\maroonB", "\\textcolor{##ff92c6}{#1}");
defineMacro("\\maroonC", "\\textcolor{##ed5fa6}{#1}");
defineMacro("\\maroonD", "\\textcolor{##ca337c}{#1}");
defineMacro("\\maroonE", "\\textcolor{##9e034e}{#1}");
defineMacro("\\purpleA", "\\textcolor{##ddd7ff}{#1}");
defineMacro("\\purpleB", "\\textcolor{##c6b9fc}{#1}");
defineMacro("\\purpleC", "\\textcolor{##aa87ff}{#1}");
defineMacro("\\purpleD", "\\textcolor{##7854ab}{#1}");
defineMacro("\\purpleE", "\\textcolor{##543b78}{#1}");
defineMacro("\\mintA", "\\textcolor{##f5f9e8}{#1}");
defineMacro("\\mintB", "\\textcolor{##edf2df}{#1}");
defineMacro("\\mintC", "\\textcolor{##e0e5cc}{#1}");
defineMacro("\\grayA", "\\textcolor{##f6f7f7}{#1}");
defineMacro("\\grayB", "\\textcolor{##f0f1f2}{#1}");
defineMacro("\\grayC", "\\textcolor{##e3e5e6}{#1}");
defineMacro("\\grayD", "\\textcolor{##d6d8da}{#1}");
defineMacro("\\grayE", "\\textcolor{##babec2}{#1}");
defineMacro("\\grayF", "\\textcolor{##888d93}{#1}");
defineMacro("\\grayG", "\\textcolor{##626569}{#1}");
defineMacro("\\grayH", "\\textcolor{##3b3e40}{#1}");
defineMacro("\\grayI", "\\textcolor{##21242c}{#1}");
defineMacro("\\kaBlue", "\\textcolor{##314453}{#1}");
defineMacro("\\kaGreen", "\\textcolor{##71B307}{#1}");
// CONCATENATED MODULE: ./src/MacroExpander.js
/**
* This file contains the “gullet” where macros are expanded
* until only non-macro tokens remain.
*/
// List of commands that act like macros but aren't defined as a macro,
// function, or symbol. Used in `isDefined`.
var implicitCommands = {
"\\relax": true,
// MacroExpander.js
"^": true,
// Parser.js
"_": true,
// Parser.js
"\\limits": true,
// Parser.js
"\\nolimits": true // Parser.js
};
var MacroExpander_MacroExpander =
/*#__PURE__*/
function () {
function MacroExpander(input, settings, mode) {
this.settings = void 0;
this.expansionCount = void 0;
this.lexer = void 0;
this.macros = void 0;
this.stack = void 0;
this.mode = void 0;
this.settings = settings;
this.expansionCount = 0;
this.feed(input); // Make new global namespace
this.macros = new Namespace_Namespace(macros, settings.macros);
this.mode = mode;
this.stack = []; // contains tokens in REVERSE order
}
/**
* Feed a new input string to the same MacroExpander
* (with existing macros etc.).
*/
var _proto = MacroExpander.prototype;
_proto.feed = function feed(input) {
this.lexer = new Lexer_Lexer(input, this.settings);
}
/**
* Switches between "text" and "math" modes.
*/
;
_proto.switchMode = function switchMode(newMode) {
this.mode = newMode;
}
/**
* Start a new group nesting within all namespaces.
*/
;
_proto.beginGroup = function beginGroup() {
this.macros.beginGroup();
}
/**
* End current group nesting within all namespaces.
*/
;
_proto.endGroup = function endGroup() {
this.macros.endGroup();
}
/**
* Returns the topmost token on the stack, without expanding it.
* Similar in behavior to TeX's `\futurelet`.
*/
;
_proto.future = function future() {
if (this.stack.length === 0) {
this.pushToken(this.lexer.lex());
}
return this.stack[this.stack.length - 1];
}
/**
* Remove and return the next unexpanded token.
*/
;
_proto.popToken = function popToken() {
this.future(); // ensure non-empty stack
return this.stack.pop();
}
/**
* Add a given token to the token stack. In particular, this get be used
* to put back a token returned from one of the other methods.
*/
;
_proto.pushToken = function pushToken(token) {
this.stack.push(token);
}
/**
* Append an array of tokens to the token stack.
*/
;
_proto.pushTokens = function pushTokens(tokens) {
var _this$stack;
(_this$stack = this.stack).push.apply(_this$stack, tokens);
}
/**
* Consume all following space tokens, without expansion.
*/
;
_proto.consumeSpaces = function consumeSpaces() {
for (;;) {
var token = this.future();
if (token.text === " ") {
this.stack.pop();
} else {
break;
}
}
}
/**
* Consume the specified number of arguments from the token stream,
* and return the resulting array of arguments.
*/
;
_proto.consumeArgs = function consumeArgs(numArgs) {
var args = []; // obtain arguments, either single token or balanced {…} group
for (var i = 0; i < numArgs; ++i) {
this.consumeSpaces(); // ignore spaces before each argument
var startOfArg = this.popToken();
if (startOfArg.text === "{") {
var arg = [];
var depth = 1;
while (depth !== 0) {
var tok = this.popToken();
arg.push(tok);
if (tok.text === "{") {
++depth;
} else if (tok.text === "}") {
--depth;
} else if (tok.text === "EOF") {
throw new src_ParseError("End of input in macro argument", startOfArg);
}
}
arg.pop(); // remove last }
arg.reverse(); // like above, to fit in with stack order
args[i] = arg;
} else if (startOfArg.text === "EOF") {
throw new src_ParseError("End of input expecting macro argument");
} else {
args[i] = [startOfArg];
}
}
return args;
}
/**
* Expand the next token only once if possible.
*
* If the token is expanded, the resulting tokens will be pushed onto
* the stack in reverse order and will be returned as an array,
* also in reverse order.
*
* If not, the next token will be returned without removing it
* from the stack. This case can be detected by a `Token` return value
* instead of an `Array` return value.
*
* In either case, the next token will be on the top of the stack,
* or the stack will be empty.
*
* Used to implement `expandAfterFuture` and `expandNextToken`.
*
* At the moment, macro expansion doesn't handle delimited macros,
* i.e. things like those defined by \def\foo#1\end{…}.
* See the TeX book page 202ff. for details on how those should behave.
*/
;
_proto.expandOnce = function expandOnce() {
var topToken = this.popToken();
var name = topToken.text;
var expansion = this._getExpansion(name);
if (expansion == null) {
// mainly checking for undefined here
// Fully expanded
this.pushToken(topToken);
return topToken;
}
this.expansionCount++;
if (this.expansionCount > this.settings.maxExpand) {
throw new src_ParseError("Too many expansions: infinite loop or " + "need to increase maxExpand setting");
}
var tokens = expansion.tokens;
if (expansion.numArgs) {
var args = this.consumeArgs(expansion.numArgs); // paste arguments in place of the placeholders
tokens = tokens.slice(); // make a shallow copy
for (var i = tokens.length - 1; i >= 0; --i) {
var tok = tokens[i];
if (tok.text === "#") {
if (i === 0) {
throw new src_ParseError("Incomplete placeholder at end of macro body", tok);
}
tok = tokens[--i]; // next token on stack
if (tok.text === "#") {
// ## → #
tokens.splice(i + 1, 1); // drop first #
} else if (/^[1-9]$/.test(tok.text)) {
var _tokens;
// replace the placeholder with the indicated argument
(_tokens = tokens).splice.apply(_tokens, [i, 2].concat(args[+tok.text - 1]));
} else {
throw new src_ParseError("Not a valid argument number", tok);
}
}
}
} // Concatenate expansion onto top of stack.
this.pushTokens(tokens);
return tokens;
}
/**
* Expand the next token only once (if possible), and return the resulting
* top token on the stack (without removing anything from the stack).
* Similar in behavior to TeX's `\expandafter\futurelet`.
* Equivalent to expandOnce() followed by future().
*/
;
_proto.expandAfterFuture = function expandAfterFuture() {
this.expandOnce();
return this.future();
}
/**
* Recursively expand first token, then return first non-expandable token.
*/
;
_proto.expandNextToken = function expandNextToken() {
for (;;) {
var expanded = this.expandOnce(); // expandOnce returns Token if and only if it's fully expanded.
if (expanded instanceof Token_Token) {
// \relax stops the expansion, but shouldn't get returned (a
// null return value couldn't get implemented as a function).
if (expanded.text === "\\relax") {
this.stack.pop();
} else {
return this.stack.pop(); // === expanded
}
}
} // Flow unable to figure out that this pathway is impossible.
// https://github.com/facebook/flow/issues/4808
throw new Error(); // eslint-disable-line no-unreachable
}
/**
* Fully expand the given macro name and return the resulting list of
* tokens, or return `undefined` if no such macro is defined.
*/
;
_proto.expandMacro = function expandMacro(name) {
if (!this.macros.get(name)) {
return undefined;
}
var output = [];
var oldStackLength = this.stack.length;
this.pushToken(new Token_Token(name));
while (this.stack.length > oldStackLength) {
var expanded = this.expandOnce(); // expandOnce returns Token if and only if it's fully expanded.
if (expanded instanceof Token_Token) {
output.push(this.stack.pop());
}
}
return output;
}
/**
* Fully expand the given macro name and return the result as a string,
* or return `undefined` if no such macro is defined.
*/
;
_proto.expandMacroAsText = function expandMacroAsText(name) {
var tokens = this.expandMacro(name);
if (tokens) {
return tokens.map(function (token) {
return token.text;
}).join("");
} else {
return tokens;
}
}
/**
* Returns the expanded macro as a reversed array of tokens and a macro
* argument count. Or returns `null` if no such macro.
*/
;
_proto._getExpansion = function _getExpansion(name) {
var definition = this.macros.get(name);
if (definition == null) {
// mainly checking for undefined here
return definition;
}
var expansion = typeof definition === "function" ? definition(this) : definition;
if (typeof expansion === "string") {
var numArgs = 0;
if (expansion.indexOf("#") !== -1) {
var stripped = expansion.replace(/##/g, "");
while (stripped.indexOf("#" + (numArgs + 1)) !== -1) {
++numArgs;
}
}
var bodyLexer = new Lexer_Lexer(expansion, this.settings);
var tokens = [];
var tok = bodyLexer.lex();
while (tok.text !== "EOF") {
tokens.push(tok);
tok = bodyLexer.lex();
}
tokens.reverse(); // to fit in with stack using push and pop
var expanded = {
tokens: tokens,
numArgs: numArgs
};
return expanded;
}
return expansion;
}
/**
* Determine whether a command is currently "defined" (has some
* functionality), meaning that it's a macro (in the current group),
* a function, a symbol, or one of the special commands listed in
* `implicitCommands`.
*/
;
_proto.isDefined = function isDefined(name) {
return this.macros.has(name) || src_functions.hasOwnProperty(name) || src_symbols.math.hasOwnProperty(name) || src_symbols.text.hasOwnProperty(name) || implicitCommands.hasOwnProperty(name);
};
return MacroExpander;
}();
// CONCATENATED MODULE: ./src/unicodeAccents.js
// Mapping of Unicode accent characters to their LaTeX equivalent in text and
// math mode (when they exist).
/* harmony default export */ var unicodeAccents = ({
"\u0301": {
text: "\\'",
math: '\\acute'
},
"\u0300": {
text: '\\`',
math: '\\grave'
},
"\u0308": {
text: '\\"',
math: '\\ddot'
},
"\u0303": {
text: '\\~',
math: '\\tilde'
},
"\u0304": {
text: '\\=',
math: '\\bar'
},
"\u0306": {
text: "\\u",
math: '\\breve'
},
"\u030C": {
text: '\\v',
math: '\\check'
},
"\u0302": {
text: '\\^',
math: '\\hat'
},
"\u0307": {
text: '\\.',
math: '\\dot'
},
"\u030A": {
text: '\\r',
math: '\\mathring'
},
"\u030B": {
text: '\\H'
}
});
// CONCATENATED MODULE: ./src/unicodeSymbols.js
// This file is GENERATED by unicodeMake.js. DO NOT MODIFY.
/* harmony default export */ var unicodeSymbols = ({
"\xE1": "a\u0301",
// á = \'{a}
"\xE0": "a\u0300",
// à = \`{a}
"\xE4": "a\u0308",
// ä = \"{a}
"\u01DF": "a\u0308\u0304",
// ǟ = \"\={a}
"\xE3": "a\u0303",
// ã = \~{a}
"\u0101": "a\u0304",
// ā = \={a}
"\u0103": "a\u0306",
// ă = \u{a}
"\u1EAF": "a\u0306\u0301",
// ắ = \u\'{a}
"\u1EB1": "a\u0306\u0300",
// ằ = \u\`{a}
"\u1EB5": "a\u0306\u0303",
// ẵ = \u\~{a}
"\u01CE": "a\u030C",
// ǎ = \v{a}
"\xE2": "a\u0302",
// â = \^{a}
"\u1EA5": "a\u0302\u0301",
// ấ = \^\'{a}
"\u1EA7": "a\u0302\u0300",
// ầ = \^\`{a}
"\u1EAB": "a\u0302\u0303",
// ẫ = \^\~{a}
"\u0227": "a\u0307",
// ȧ = \.{a}
"\u01E1": "a\u0307\u0304",
// ǡ = \.\={a}
"\xE5": "a\u030A",
// å = \r{a}
"\u01FB": "a\u030A\u0301",
// ǻ = \r\'{a}
"\u1E03": "b\u0307",
// ḃ = \.{b}
"\u0107": "c\u0301",
// ć = \'{c}
"\u010D": "c\u030C",
// č = \v{c}
"\u0109": "c\u0302",
// ĉ = \^{c}
"\u010B": "c\u0307",
// ċ = \.{c}
"\u010F": "d\u030C",
// ď = \v{d}
"\u1E0B": "d\u0307",
// ḋ = \.{d}
"\xE9": "e\u0301",
// é = \'{e}
"\xE8": "e\u0300",
// è = \`{e}
"\xEB": "e\u0308",
// ë = \"{e}
"\u1EBD": "e\u0303",
// ẽ = \~{e}
"\u0113": "e\u0304",
// ē = \={e}
"\u1E17": "e\u0304\u0301",
// ḗ = \=\'{e}
"\u1E15": "e\u0304\u0300",
// ḕ = \=\`{e}
"\u0115": "e\u0306",
// ĕ = \u{e}
"\u011B": "e\u030C",
// ě = \v{e}
"\xEA": "e\u0302",
// ê = \^{e}
"\u1EBF": "e\u0302\u0301",
// ế = \^\'{e}
"\u1EC1": "e\u0302\u0300",
// ề = \^\`{e}
"\u1EC5": "e\u0302\u0303",
// ễ = \^\~{e}
"\u0117": "e\u0307",
// ė = \.{e}
"\u1E1F": "f\u0307",
// ḟ = \.{f}
"\u01F5": "g\u0301",
// ǵ = \'{g}
"\u1E21": "g\u0304",
// ḡ = \={g}
"\u011F": "g\u0306",
// ğ = \u{g}
"\u01E7": "g\u030C",
// ǧ = \v{g}
"\u011D": "g\u0302",
// ĝ = \^{g}
"\u0121": "g\u0307",
// ġ = \.{g}
"\u1E27": "h\u0308",
// ḧ = \"{h}
"\u021F": "h\u030C",
// ȟ = \v{h}
"\u0125": "h\u0302",
// ĥ = \^{h}
"\u1E23": "h\u0307",
// ḣ = \.{h}
"\xED": "i\u0301",
// í = \'{i}
"\xEC": "i\u0300",
// ì = \`{i}
"\xEF": "i\u0308",
// ï = \"{i}
"\u1E2F": "i\u0308\u0301",
// ḯ = \"\'{i}
"\u0129": "i\u0303",
// ĩ = \~{i}
"\u012B": "i\u0304",
// ī = \={i}
"\u012D": "i\u0306",
// ĭ = \u{i}
"\u01D0": "i\u030C",
// ǐ = \v{i}
"\xEE": "i\u0302",
// î = \^{i}
"\u01F0": "j\u030C",
// ǰ = \v{j}
"\u0135": "j\u0302",
// ĵ = \^{j}
"\u1E31": "k\u0301",
// ḱ = \'{k}
"\u01E9": "k\u030C",
// ǩ = \v{k}
"\u013A": "l\u0301",
// ĺ = \'{l}
"\u013E": "l\u030C",
// ľ = \v{l}
"\u1E3F": "m\u0301",
// ḿ = \'{m}
"\u1E41": "m\u0307",
// ṁ = \.{m}
"\u0144": "n\u0301",
// ń = \'{n}
"\u01F9": "n\u0300",
// ǹ = \`{n}
"\xF1": "n\u0303",
// ñ = \~{n}
"\u0148": "n\u030C",
// ň = \v{n}
"\u1E45": "n\u0307",
// ṅ = \.{n}
"\xF3": "o\u0301",
// ó = \'{o}
"\xF2": "o\u0300",
// ò = \`{o}
"\xF6": "o\u0308",
// ö = \"{o}
"\u022B": "o\u0308\u0304",
// ȫ = \"\={o}
"\xF5": "o\u0303",
// õ = \~{o}
"\u1E4D": "o\u0303\u0301",
// ṍ = \~\'{o}
"\u1E4F": "o\u0303\u0308",
// ṏ = \~\"{o}
"\u022D": "o\u0303\u0304",
// ȭ = \~\={o}
"\u014D": "o\u0304",
// ō = \={o}
"\u1E53": "o\u0304\u0301",
// ṓ = \=\'{o}
"\u1E51": "o\u0304\u0300",
// ṑ = \=\`{o}
"\u014F": "o\u0306",
// ŏ = \u{o}
"\u01D2": "o\u030C",
// ǒ = \v{o}
"\xF4": "o\u0302",
// ô = \^{o}
"\u1ED1": "o\u0302\u0301",
// ố = \^\'{o}
"\u1ED3": "o\u0302\u0300",
// ồ = \^\`{o}
"\u1ED7": "o\u0302\u0303",
// ỗ = \^\~{o}
"\u022F": "o\u0307",
// ȯ = \.{o}
"\u0231": "o\u0307\u0304",
// ȱ = \.\={o}
"\u0151": "o\u030B",
// ő = \H{o}
"\u1E55": "p\u0301",
// ṕ = \'{p}
"\u1E57": "p\u0307",
// ṗ = \.{p}
"\u0155": "r\u0301",
// ŕ = \'{r}
"\u0159": "r\u030C",
// ř = \v{r}
"\u1E59": "r\u0307",
// ṙ = \.{r}
"\u015B": "s\u0301",
// ś = \'{s}
"\u1E65": "s\u0301\u0307",
// ṥ = \'\.{s}
"\u0161": "s\u030C",
// š = \v{s}
"\u1E67": "s\u030C\u0307",
// ṧ = \v\.{s}
"\u015D": "s\u0302",
// ŝ = \^{s}
"\u1E61": "s\u0307",
// ṡ = \.{s}
"\u1E97": "t\u0308",
// ẗ = \"{t}
"\u0165": "t\u030C",
// ť = \v{t}
"\u1E6B": "t\u0307",
// ṫ = \.{t}
"\xFA": "u\u0301",
// ú = \'{u}
"\xF9": "u\u0300",
// ù = \`{u}
"\xFC": "u\u0308",
// ü = \"{u}
"\u01D8": "u\u0308\u0301",
// ǘ = \"\'{u}
"\u01DC": "u\u0308\u0300",
// ǜ = \"\`{u}
"\u01D6": "u\u0308\u0304",
// ǖ = \"\={u}
"\u01DA": "u\u0308\u030C",
// ǚ = \"\v{u}
"\u0169": "u\u0303",
// ũ = \~{u}
"\u1E79": "u\u0303\u0301",
// ṹ = \~\'{u}
"\u016B": "u\u0304",
// ū = \={u}
"\u1E7B": "u\u0304\u0308",
// ṻ = \=\"{u}
"\u016D": "u\u0306",
// ŭ = \u{u}
"\u01D4": "u\u030C",
// ǔ = \v{u}
"\xFB": "u\u0302",
// û = \^{u}
"\u016F": "u\u030A",
// ů = \r{u}
"\u0171": "u\u030B",
// ű = \H{u}
"\u1E7D": "v\u0303",
// ṽ = \~{v}
"\u1E83": "w\u0301",
// ẃ = \'{w}
"\u1E81": "w\u0300",
// ẁ = \`{w}
"\u1E85": "w\u0308",
// ẅ = \"{w}
"\u0175": "w\u0302",
// ŵ = \^{w}
"\u1E87": "w\u0307",
// ẇ = \.{w}
"\u1E98": "w\u030A",
// ẘ = \r{w}
"\u1E8D": "x\u0308",
// ẍ = \"{x}
"\u1E8B": "x\u0307",
// ẋ = \.{x}
"\xFD": "y\u0301",
// ý = \'{y}
"\u1EF3": "y\u0300",
// ỳ = \`{y}
"\xFF": "y\u0308",
// ÿ = \"{y}
"\u1EF9": "y\u0303",
// ỹ = \~{y}
"\u0233": "y\u0304",
// ȳ = \={y}
"\u0177": "y\u0302",
// ŷ = \^{y}
"\u1E8F": "y\u0307",
// ẏ = \.{y}
"\u1E99": "y\u030A",
// ẙ = \r{y}
"\u017A": "z\u0301",
// ź = \'{z}
"\u017E": "z\u030C",
// ž = \v{z}
"\u1E91": "z\u0302",
// ẑ = \^{z}
"\u017C": "z\u0307",
// ż = \.{z}
"\xC1": "A\u0301",
// Á = \'{A}
"\xC0": "A\u0300",
// À = \`{A}
"\xC4": "A\u0308",
// Ä = \"{A}
"\u01DE": "A\u0308\u0304",
// Ǟ = \"\={A}
"\xC3": "A\u0303",
// Ã = \~{A}
"\u0100": "A\u0304",
// Ā = \={A}
"\u0102": "A\u0306",
// Ă = \u{A}
"\u1EAE": "A\u0306\u0301",
// Ắ = \u\'{A}
"\u1EB0": "A\u0306\u0300",
// Ằ = \u\`{A}
"\u1EB4": "A\u0306\u0303",
// Ẵ = \u\~{A}
"\u01CD": "A\u030C",
// Ǎ = \v{A}
"\xC2": "A\u0302",
// Â = \^{A}
"\u1EA4": "A\u0302\u0301",
// Ấ = \^\'{A}
"\u1EA6": "A\u0302\u0300",
// Ầ = \^\`{A}
"\u1EAA": "A\u0302\u0303",
// Ẫ = \^\~{A}
"\u0226": "A\u0307",
// Ȧ = \.{A}
"\u01E0": "A\u0307\u0304",
// Ǡ = \.\={A}
"\xC5": "A\u030A",
// Å = \r{A}
"\u01FA": "A\u030A\u0301",
// Ǻ = \r\'{A}
"\u1E02": "B\u0307",
// Ḃ = \.{B}
"\u0106": "C\u0301",
// Ć = \'{C}
"\u010C": "C\u030C",
// Č = \v{C}
"\u0108": "C\u0302",
// Ĉ = \^{C}
"\u010A": "C\u0307",
// Ċ = \.{C}
"\u010E": "D\u030C",
// Ď = \v{D}
"\u1E0A": "D\u0307",
// Ḋ = \.{D}
"\xC9": "E\u0301",
// É = \'{E}
"\xC8": "E\u0300",
// È = \`{E}
"\xCB": "E\u0308",
// Ë = \"{E}
"\u1EBC": "E\u0303",
// Ẽ = \~{E}
"\u0112": "E\u0304",
// Ē = \={E}
"\u1E16": "E\u0304\u0301",
// Ḗ = \=\'{E}
"\u1E14": "E\u0304\u0300",
// Ḕ = \=\`{E}
"\u0114": "E\u0306",
// Ĕ = \u{E}
"\u011A": "E\u030C",
// Ě = \v{E}
"\xCA": "E\u0302",
// Ê = \^{E}
"\u1EBE": "E\u0302\u0301",
// Ế = \^\'{E}
"\u1EC0": "E\u0302\u0300",
// Ề = \^\`{E}
"\u1EC4": "E\u0302\u0303",
// Ễ = \^\~{E}
"\u0116": "E\u0307",
// Ė = \.{E}
"\u1E1E": "F\u0307",
// Ḟ = \.{F}
"\u01F4": "G\u0301",
// Ǵ = \'{G}
"\u1E20": "G\u0304",
// Ḡ = \={G}
"\u011E": "G\u0306",
// Ğ = \u{G}
"\u01E6": "G\u030C",
// Ǧ = \v{G}
"\u011C": "G\u0302",
// Ĝ = \^{G}
"\u0120": "G\u0307",
// Ġ = \.{G}
"\u1E26": "H\u0308",
// Ḧ = \"{H}
"\u021E": "H\u030C",
// Ȟ = \v{H}
"\u0124": "H\u0302",
// Ĥ = \^{H}
"\u1E22": "H\u0307",
// Ḣ = \.{H}
"\xCD": "I\u0301",
// Í = \'{I}
"\xCC": "I\u0300",
// Ì = \`{I}
"\xCF": "I\u0308",
// Ï = \"{I}
"\u1E2E": "I\u0308\u0301",
// Ḯ = \"\'{I}
"\u0128": "I\u0303",
// Ĩ = \~{I}
"\u012A": "I\u0304",
// Ī = \={I}
"\u012C": "I\u0306",
// Ĭ = \u{I}
"\u01CF": "I\u030C",
// Ǐ = \v{I}
"\xCE": "I\u0302",
// Î = \^{I}
"\u0130": "I\u0307",
// İ = \.{I}
"\u0134": "J\u0302",
// Ĵ = \^{J}
"\u1E30": "K\u0301",
// Ḱ = \'{K}
"\u01E8": "K\u030C",
// Ǩ = \v{K}
"\u0139": "L\u0301",
// Ĺ = \'{L}
"\u013D": "L\u030C",
// Ľ = \v{L}
"\u1E3E": "M\u0301",
// Ḿ = \'{M}
"\u1E40": "M\u0307",
// Ṁ = \.{M}
"\u0143": "N\u0301",
// Ń = \'{N}
"\u01F8": "N\u0300",
// Ǹ = \`{N}
"\xD1": "N\u0303",
// Ñ = \~{N}
"\u0147": "N\u030C",
// Ň = \v{N}
"\u1E44": "N\u0307",
// Ṅ = \.{N}
"\xD3": "O\u0301",
// Ó = \'{O}
"\xD2": "O\u0300",
// Ò = \`{O}
"\xD6": "O\u0308",
// Ö = \"{O}
"\u022A": "O\u0308\u0304",
// Ȫ = \"\={O}
"\xD5": "O\u0303",
// Õ = \~{O}
"\u1E4C": "O\u0303\u0301",
// Ṍ = \~\'{O}
"\u1E4E": "O\u0303\u0308",
// Ṏ = \~\"{O}
"\u022C": "O\u0303\u0304",
// Ȭ = \~\={O}
"\u014C": "O\u0304",
// Ō = \={O}
"\u1E52": "O\u0304\u0301",
// Ṓ = \=\'{O}
"\u1E50": "O\u0304\u0300",
// Ṑ = \=\`{O}
"\u014E": "O\u0306",
// Ŏ = \u{O}
"\u01D1": "O\u030C",
// Ǒ = \v{O}
"\xD4": "O\u0302",
// Ô = \^{O}
"\u1ED0": "O\u0302\u0301",
// Ố = \^\'{O}
"\u1ED2": "O\u0302\u0300",
// Ồ = \^\`{O}
"\u1ED6": "O\u0302\u0303",
// Ỗ = \^\~{O}
"\u022E": "O\u0307",
// Ȯ = \.{O}
"\u0230": "O\u0307\u0304",
// Ȱ = \.\={O}
"\u0150": "O\u030B",
// Ő = \H{O}
"\u1E54": "P\u0301",
// Ṕ = \'{P}
"\u1E56": "P\u0307",
// Ṗ = \.{P}
"\u0154": "R\u0301",
// Ŕ = \'{R}
"\u0158": "R\u030C",
// Ř = \v{R}
"\u1E58": "R\u0307",
// Ṙ = \.{R}
"\u015A": "S\u0301",
// Ś = \'{S}
"\u1E64": "S\u0301\u0307",
// Ṥ = \'\.{S}
"\u0160": "S\u030C",
// Š = \v{S}
"\u1E66": "S\u030C\u0307",
// Ṧ = \v\.{S}
"\u015C": "S\u0302",
// Ŝ = \^{S}
"\u1E60": "S\u0307",
// Ṡ = \.{S}
"\u0164": "T\u030C",
// Ť = \v{T}
"\u1E6A": "T\u0307",
// Ṫ = \.{T}
"\xDA": "U\u0301",
// Ú = \'{U}
"\xD9": "U\u0300",
// Ù = \`{U}
"\xDC": "U\u0308",
// Ü = \"{U}
"\u01D7": "U\u0308\u0301",
// Ǘ = \"\'{U}
"\u01DB": "U\u0308\u0300",
// Ǜ = \"\`{U}
"\u01D5": "U\u0308\u0304",
// Ǖ = \"\={U}
"\u01D9": "U\u0308\u030C",
// Ǚ = \"\v{U}
"\u0168": "U\u0303",
// Ũ = \~{U}
"\u1E78": "U\u0303\u0301",
// Ṹ = \~\'{U}
"\u016A": "U\u0304",
// Ū = \={U}
"\u1E7A": "U\u0304\u0308",
// Ṻ = \=\"{U}
"\u016C": "U\u0306",
// Ŭ = \u{U}
"\u01D3": "U\u030C",
// Ǔ = \v{U}
"\xDB": "U\u0302",
// Û = \^{U}
"\u016E": "U\u030A",
// Ů = \r{U}
"\u0170": "U\u030B",
// Ű = \H{U}
"\u1E7C": "V\u0303",
// Ṽ = \~{V}
"\u1E82": "W\u0301",
// Ẃ = \'{W}
"\u1E80": "W\u0300",
// Ẁ = \`{W}
"\u1E84": "W\u0308",
// Ẅ = \"{W}
"\u0174": "W\u0302",
// Ŵ = \^{W}
"\u1E86": "W\u0307",
// Ẇ = \.{W}
"\u1E8C": "X\u0308",
// Ẍ = \"{X}
"\u1E8A": "X\u0307",
// Ẋ = \.{X}
"\xDD": "Y\u0301",
// Ý = \'{Y}
"\u1EF2": "Y\u0300",
// Ỳ = \`{Y}
"\u0178": "Y\u0308",
// Ÿ = \"{Y}
"\u1EF8": "Y\u0303",
// Ỹ = \~{Y}
"\u0232": "Y\u0304",
// Ȳ = \={Y}
"\u0176": "Y\u0302",
// Ŷ = \^{Y}
"\u1E8E": "Y\u0307",
// Ẏ = \.{Y}
"\u0179": "Z\u0301",
// Ź = \'{Z}
"\u017D": "Z\u030C",
// Ž = \v{Z}
"\u1E90": "Z\u0302",
// Ẑ = \^{Z}
"\u017B": "Z\u0307",
// Ż = \.{Z}
"\u03AC": "\u03B1\u0301",
// ά = \'{α}
"\u1F70": "\u03B1\u0300",
// ὰ = \`{α}
"\u1FB1": "\u03B1\u0304",
// ᾱ = \={α}
"\u1FB0": "\u03B1\u0306",
// ᾰ = \u{α}
"\u03AD": "\u03B5\u0301",
// έ = \'{ε}
"\u1F72": "\u03B5\u0300",
// ὲ = \`{ε}
"\u03AE": "\u03B7\u0301",
// ή = \'{η}
"\u1F74": "\u03B7\u0300",
// ὴ = \`{η}
"\u03AF": "\u03B9\u0301",
// ί = \'{ι}
"\u1F76": "\u03B9\u0300",
// ὶ = \`{ι}
"\u03CA": "\u03B9\u0308",
// ϊ = \"{ι}
"\u0390": "\u03B9\u0308\u0301",
// ΐ = \"\'{ι}
"\u1FD2": "\u03B9\u0308\u0300",
// ῒ = \"\`{ι}
"\u1FD1": "\u03B9\u0304",
// ῑ = \={ι}
"\u1FD0": "\u03B9\u0306",
// ῐ = \u{ι}
"\u03CC": "\u03BF\u0301",
// ό = \'{ο}
"\u1F78": "\u03BF\u0300",
// ὸ = \`{ο}
"\u03CD": "\u03C5\u0301",
// ύ = \'{υ}
"\u1F7A": "\u03C5\u0300",
// ὺ = \`{υ}
"\u03CB": "\u03C5\u0308",
// ϋ = \"{υ}
"\u03B0": "\u03C5\u0308\u0301",
// ΰ = \"\'{υ}
"\u1FE2": "\u03C5\u0308\u0300",
// ῢ = \"\`{υ}
"\u1FE1": "\u03C5\u0304",
// ῡ = \={υ}
"\u1FE0": "\u03C5\u0306",
// ῠ = \u{υ}
"\u03CE": "\u03C9\u0301",
// ώ = \'{ω}
"\u1F7C": "\u03C9\u0300",
// ὼ = \`{ω}
"\u038E": "\u03A5\u0301",
// Ύ = \'{Υ}
"\u1FEA": "\u03A5\u0300",
// Ὺ = \`{Υ}
"\u03AB": "\u03A5\u0308",
// Ϋ = \"{Υ}
"\u1FE9": "\u03A5\u0304",
// Ῡ = \={Υ}
"\u1FE8": "\u03A5\u0306",
// Ῠ = \u{Υ}
"\u038F": "\u03A9\u0301",
// Ώ = \'{Ω}
"\u1FFA": "\u03A9\u0300" // Ὼ = \`{Ω}
});
// CONCATENATED MODULE: ./src/Parser.js
/* eslint no-constant-condition:0 */
/**
* This file contains the parser used to parse out a TeX expression from the
* input. Since TeX isn't context-free, standard parsers don't work particularly
* well.
*
* The strategy of this parser is as such:
*
* The main functions (the `.parse...` ones) take a position in the current
* parse string to parse tokens from. The lexer (found in Lexer.js, stored at
* this.gullet.lexer) also supports pulling out tokens at arbitrary places. When
* individual tokens are needed at a position, the lexer is called to pull out a
* token, which is then used.
*
* The parser has a property called "mode" indicating the mode that
* the parser is currently in. Currently it has to be one of "math" or
* "text", which denotes whether the current environment is a math-y
* one or a text-y one (e.g. inside \text). Currently, this serves to
* limit the functions which can be used in text mode.
*
* The main functions then return an object which contains the useful data that
* was parsed at its given point, and a new position at the end of the parsed
* data. The main functions can call each other and continue the parsing by
* using the returned position as a new starting point.
*
* There are also extra `.handle...` functions, which pull out some reused
* functionality into self-contained functions.
*
* The functions return ParseNodes.
*/
var Parser_Parser =
/*#__PURE__*/
function () {
function Parser(input, settings) {
this.mode = void 0;
this.gullet = void 0;
this.settings = void 0;
this.leftrightDepth = void 0;
this.nextToken = void 0;
// Start in math mode
this.mode = "math"; // Create a new macro expander (gullet) and (indirectly via that) also a
// new lexer (mouth) for this parser (stomach, in the language of TeX)
this.gullet = new MacroExpander_MacroExpander(input, settings, this.mode); // Store the settings for use in parsing
this.settings = settings; // Count leftright depth (for \middle errors)
this.leftrightDepth = 0;
}
/**
* Checks a result to make sure it has the right type, and throws an
* appropriate error otherwise.
*/
var _proto = Parser.prototype;
_proto.expect = function expect(text, consume) {
if (consume === void 0) {
consume = true;
}
if (this.fetch().text !== text) {
throw new src_ParseError("Expected '" + text + "', got '" + this.fetch().text + "'", this.fetch());
}
if (consume) {
this.consume();
}
}
/**
* Discards the current lookahead token, considering it consumed.
*/
;
_proto.consume = function consume() {
this.nextToken = null;
}
/**
* Return the current lookahead token, or if there isn't one (at the
* beginning, or if the previous lookahead token was consume()d),
* fetch the next token as the new lookahead token and return it.
*/
;
_proto.fetch = function fetch() {
if (this.nextToken == null) {
this.nextToken = this.gullet.expandNextToken();
}
return this.nextToken;
}
/**
* Switches between "text" and "math" modes.
*/
;
_proto.switchMode = function switchMode(newMode) {
this.mode = newMode;
this.gullet.switchMode(newMode);
}
/**
* Main parsing function, which parses an entire input.
*/
;
_proto.parse = function parse() {
// Create a group namespace for the math expression.
// (LaTeX creates a new group for every $...$, $$...$$, \[...\].)
this.gullet.beginGroup(); // Use old \color behavior (same as LaTeX's \textcolor) if requested.
// We do this within the group for the math expression, so it doesn't
// pollute settings.macros.
if (this.settings.colorIsTextColor) {
this.gullet.macros.set("\\color", "\\textcolor");
} // Try to parse the input
var parse = this.parseExpression(false); // If we succeeded, make sure there's an EOF at the end
this.expect("EOF"); // End the group namespace for the expression
this.gullet.endGroup();
return parse;
};
_proto.parseExpression = function parseExpression(breakOnInfix, breakOnTokenText) {
var body = []; // Keep adding atoms to the body until we can't parse any more atoms (either
// we reached the end, a }, or a \right)
while (true) {
// Ignore spaces in math mode
if (this.mode === "math") {
this.consumeSpaces();
}
var lex = this.fetch();
if (Parser.endOfExpression.indexOf(lex.text) !== -1) {
break;
}
if (breakOnTokenText && lex.text === breakOnTokenText) {
break;
}
if (breakOnInfix && src_functions[lex.text] && src_functions[lex.text].infix) {
break;
}
var atom = this.parseAtom(breakOnTokenText);
if (!atom) {
break;
}
body.push(atom);
}
if (this.mode === "text") {
this.formLigatures(body);
}
return this.handleInfixNodes(body);
}
/**
* Rewrites infix operators such as \over with corresponding commands such
* as \frac.
*
* There can only be one infix operator per group. If there's more than one
* then the expression is ambiguous. This can be resolved by adding {}.
*/
;
_proto.handleInfixNodes = function handleInfixNodes(body) {
var overIndex = -1;
var funcName;
for (var i = 0; i < body.length; i++) {
var node = checkNodeType(body[i], "infix");
if (node) {
if (overIndex !== -1) {
throw new src_ParseError("only one infix operator per group", node.token);
}
overIndex = i;
funcName = node.replaceWith;
}
}
if (overIndex !== -1 && funcName) {
var numerNode;
var denomNode;
var numerBody = body.slice(0, overIndex);
var denomBody = body.slice(overIndex + 1);
if (numerBody.length === 1 && numerBody[0].type === "ordgroup") {
numerNode = numerBody[0];
} else {
numerNode = {
type: "ordgroup",
mode: this.mode,
body: numerBody
};
}
if (denomBody.length === 1 && denomBody[0].type === "ordgroup") {
denomNode = denomBody[0];
} else {
denomNode = {
type: "ordgroup",
mode: this.mode,
body: denomBody
};
}
var _node;
if (funcName === "\\\\abovefrac") {
_node = this.callFunction(funcName, [numerNode, body[overIndex], denomNode], []);
} else {
_node = this.callFunction(funcName, [numerNode, denomNode], []);
}
return [_node];
} else {
return body;
}
} // The greediness of a superscript or subscript
;
/**
* Handle a subscript or superscript with nice errors.
*/
_proto.handleSupSubscript = function handleSupSubscript(name) {
var symbolToken = this.fetch();
var symbol = symbolToken.text;
this.consume();
var group = this.parseGroup(name, false, Parser.SUPSUB_GREEDINESS, undefined, undefined, true); // ignore spaces before sup/subscript argument
if (!group) {
throw new src_ParseError("Expected group after '" + symbol + "'", symbolToken);
}
return group;
}
/**
* Converts the textual input of an unsupported command into a text node
* contained within a color node whose color is determined by errorColor
*/
;
_proto.formatUnsupportedCmd = function formatUnsupportedCmd(text) {
var textordArray = [];
for (var i = 0; i < text.length; i++) {
textordArray.push({
type: "textord",
mode: "text",
text: text[i]
});
}
var textNode = {
type: "text",
mode: this.mode,
body: textordArray
};
var colorNode = {
type: "color",
mode: this.mode,
color: this.settings.errorColor,
body: [textNode]
};
return colorNode;
}
/**
* Parses a group with optional super/subscripts.
*/
;
_proto.parseAtom = function parseAtom(breakOnTokenText) {
// The body of an atom is an implicit group, so that things like
// \left(x\right)^2 work correctly.
var base = this.parseGroup("atom", false, null, breakOnTokenText); // In text mode, we don't have superscripts or subscripts
if (this.mode === "text") {
return base;
} // Note that base may be empty (i.e. null) at this point.
var superscript;
var subscript;
while (true) {
// Guaranteed in math mode, so eat any spaces first.
this.consumeSpaces(); // Lex the first token
var lex = this.fetch();
if (lex.text === "\\limits" || lex.text === "\\nolimits") {
// We got a limit control
var opNode = checkNodeType(base, "op");
if (opNode) {
var limits = lex.text === "\\limits";
opNode.limits = limits;
opNode.alwaysHandleSupSub = true;
} else {
opNode = checkNodeType(base, "operatorname");
if (opNode && opNode.alwaysHandleSupSub) {
var _limits = lex.text === "\\limits";
opNode.limits = _limits;
} else {
throw new src_ParseError("Limit controls must follow a math operator", lex);
}
}
this.consume();
} else if (lex.text === "^") {
// We got a superscript start
if (superscript) {
throw new src_ParseError("Double superscript", lex);
}
superscript = this.handleSupSubscript("superscript");
} else if (lex.text === "_") {
// We got a subscript start
if (subscript) {
throw new src_ParseError("Double subscript", lex);
}
subscript = this.handleSupSubscript("subscript");
} else if (lex.text === "'") {
// We got a prime
if (superscript) {
throw new src_ParseError("Double superscript", lex);
}
var prime = {
type: "textord",
mode: this.mode,
text: "\\prime"
}; // Many primes can be grouped together, so we handle this here
var primes = [prime];
this.consume(); // Keep lexing tokens until we get something that's not a prime
while (this.fetch().text === "'") {
// For each one, add another prime to the list
primes.push(prime);
this.consume();
} // If there's a superscript following the primes, combine that
// superscript in with the primes.
if (this.fetch().text === "^") {
primes.push(this.handleSupSubscript("superscript"));
} // Put everything into an ordgroup as the superscript
superscript = {
type: "ordgroup",
mode: this.mode,
body: primes
};
} else {
// If it wasn't ^, _, or ', stop parsing super/subscripts
break;
}
} // Base must be set if superscript or subscript are set per logic above,
// but need to check here for type check to pass.
if (superscript || subscript) {
// If we got either a superscript or subscript, create a supsub
return {
type: "supsub",
mode: this.mode,
base: base,
sup: superscript,
sub: subscript
};
} else {
// Otherwise return the original body
return base;
}
}
/**
* Parses an entire function, including its base and all of its arguments.
*/
;
_proto.parseFunction = function parseFunction(breakOnTokenText, name, // For error reporting.
greediness) {
var token = this.fetch();
var func = token.text;
var funcData = src_functions[func];
if (!funcData) {
return null;
}
this.consume(); // consume command token
if (greediness != null && funcData.greediness <= greediness) {
throw new src_ParseError("Got function '" + func + "' with no arguments" + (name ? " as " + name : ""), token);
} else if (this.mode === "text" && !funcData.allowedInText) {
throw new src_ParseError("Can't use function '" + func + "' in text mode", token);
} else if (this.mode === "math" && funcData.allowedInMath === false) {
throw new src_ParseError("Can't use function '" + func + "' in math mode", token);
}
var _this$parseArguments = this.parseArguments(func, funcData),
args = _this$parseArguments.args,
optArgs = _this$parseArguments.optArgs;
return this.callFunction(func, args, optArgs, token, breakOnTokenText);
}
/**
* Call a function handler with a suitable context and arguments.
*/
;
_proto.callFunction = function callFunction(name, args, optArgs, token, breakOnTokenText) {
var context = {
funcName: name,
parser: this,
token: token,
breakOnTokenText: breakOnTokenText
};
var func = src_functions[name];
if (func && func.handler) {
return func.handler(context, args, optArgs);
} else {
throw new src_ParseError("No function handler for " + name);
}
}
/**
* Parses the arguments of a function or environment
*/
;
_proto.parseArguments = function parseArguments(func, // Should look like "\name" or "\begin{name}".
funcData) {
var totalArgs = funcData.numArgs + funcData.numOptionalArgs;
if (totalArgs === 0) {
return {
args: [],
optArgs: []
};
}
var baseGreediness = funcData.greediness;
var args = [];
var optArgs = [];
for (var i = 0; i < totalArgs; i++) {
var argType = funcData.argTypes && funcData.argTypes[i];
var isOptional = i < funcData.numOptionalArgs; // Ignore spaces between arguments. As the TeXbook says:
// "After you have said \def\row#1#2{...}, you are allowed to
// put spaces between the arguments (e.g., \row x n), because
// TeX doesnt use single spaces as undelimited arguments."
var consumeSpaces = i > 0 && !isOptional || // Also consume leading spaces in math mode, as parseSymbol
// won't know what to do with them. This can only happen with
// macros, e.g. \frac\foo\foo where \foo expands to a space symbol.
// In LaTeX, the \foo's get treated as (blank) arguments.
// In KaTeX, for now, both spaces will get consumed.
// TODO(edemaine)
i === 0 && !isOptional && this.mode === "math";
var arg = this.parseGroupOfType("argument to '" + func + "'", argType, isOptional, baseGreediness, consumeSpaces);
if (!arg) {
if (isOptional) {
optArgs.push(null);
continue;
}
throw new src_ParseError("Expected group after '" + func + "'", this.fetch());
}
(isOptional ? optArgs : args).push(arg);
}
return {
args: args,
optArgs: optArgs
};
}
/**
* Parses a group when the mode is changing.
*/
;
_proto.parseGroupOfType = function parseGroupOfType(name, type, optional, greediness, consumeSpaces) {
switch (type) {
case "color":
if (consumeSpaces) {
this.consumeSpaces();
}
return this.parseColorGroup(optional);
case "size":
if (consumeSpaces) {
this.consumeSpaces();
}
return this.parseSizeGroup(optional);
case "url":
return this.parseUrlGroup(optional, consumeSpaces);
case "math":
case "text":
return this.parseGroup(name, optional, greediness, undefined, type, consumeSpaces);
case "hbox":
{
// hbox argument type wraps the argument in the equivalent of
// \hbox, which is like \text but switching to \textstyle size.
var group = this.parseGroup(name, optional, greediness, undefined, "text", consumeSpaces);
if (!group) {
return group;
}
var styledGroup = {
type: "styling",
mode: group.mode,
body: [group],
style: "text" // simulate \textstyle
};
return styledGroup;
}
case "raw":
{
if (consumeSpaces) {
this.consumeSpaces();
}
if (optional && this.fetch().text === "{") {
return null;
}
var token = this.parseStringGroup("raw", optional, true);
if (token) {
return {
type: "raw",
mode: "text",
string: token.text
};
} else {
throw new src_ParseError("Expected raw group", this.fetch());
}
}
case "original":
case null:
case undefined:
return this.parseGroup(name, optional, greediness, undefined, undefined, consumeSpaces);
default:
throw new src_ParseError("Unknown group type as " + name, this.fetch());
}
}
/**
* Discard any space tokens, fetching the next non-space token.
*/
;
_proto.consumeSpaces = function consumeSpaces() {
while (this.fetch().text === " ") {
this.consume();
}
}
/**
* Parses a group, essentially returning the string formed by the
* brace-enclosed tokens plus some position information.
*/
;
_proto.parseStringGroup = function parseStringGroup(modeName, // Used to describe the mode in error messages.
optional, raw) {
var groupBegin = optional ? "[" : "{";
var groupEnd = optional ? "]" : "}";
var beginToken = this.fetch();
if (beginToken.text !== groupBegin) {
if (optional) {
return null;
} else if (raw && beginToken.text !== "EOF" && /[^{}[\]]/.test(beginToken.text)) {
this.consume();
return beginToken;
}
}
var outerMode = this.mode;
this.mode = "text";
this.expect(groupBegin);
var str = "";
var firstToken = this.fetch();
var nested = 0; // allow nested braces in raw string group
var lastToken = firstToken;
var nextToken;
while ((nextToken = this.fetch()).text !== groupEnd || raw && nested > 0) {
switch (nextToken.text) {
case "EOF":
throw new src_ParseError("Unexpected end of input in " + modeName, firstToken.range(lastToken, str));
case groupBegin:
nested++;
break;
case groupEnd:
nested--;
break;
}
lastToken = nextToken;
str += lastToken.text;
this.consume();
}
this.expect(groupEnd);
this.mode = outerMode;
return firstToken.range(lastToken, str);
}
/**
* Parses a regex-delimited group: the largest sequence of tokens
* whose concatenated strings match `regex`. Returns the string
* formed by the tokens plus some position information.
*/
;
_proto.parseRegexGroup = function parseRegexGroup(regex, modeName) {
var outerMode = this.mode;
this.mode = "text";
var firstToken = this.fetch();
var lastToken = firstToken;
var str = "";
var nextToken;
while ((nextToken = this.fetch()).text !== "EOF" && regex.test(str + nextToken.text)) {
lastToken = nextToken;
str += lastToken.text;
this.consume();
}
if (str === "") {
throw new src_ParseError("Invalid " + modeName + ": '" + firstToken.text + "'", firstToken);
}
this.mode = outerMode;
return firstToken.range(lastToken, str);
}
/**
* Parses a color description.
*/
;
_proto.parseColorGroup = function parseColorGroup(optional) {
var res = this.parseStringGroup("color", optional);
if (!res) {
return null;
}
var match = /^(#[a-f0-9]{3}|#?[a-f0-9]{6}|[a-z]+)$/i.exec(res.text);
if (!match) {
throw new src_ParseError("Invalid color: '" + res.text + "'", res);
}
var color = match[0];
if (/^[0-9a-f]{6}$/i.test(color)) {
// We allow a 6-digit HTML color spec without a leading "#".
// This follows the xcolor package's HTML color model.
// Predefined color names are all missed by this RegEx pattern.
color = "#" + color;
}
return {
type: "color-token",
mode: this.mode,
color: color
};
}
/**
* Parses a size specification, consisting of magnitude and unit.
*/
;
_proto.parseSizeGroup = function parseSizeGroup(optional) {
var res;
var isBlank = false;
if (!optional && this.fetch().text !== "{") {
res = this.parseRegexGroup(/^[-+]? *(?:$|\d+|\d+\.\d*|\.\d*) *[a-z]{0,2} *$/, "size");
} else {
res = this.parseStringGroup("size", optional);
}
if (!res) {
return null;
}
if (!optional && res.text.length === 0) {
// Because we've tested for what is !optional, this block won't
// affect \kern, \hspace, etc. It will capture the mandatory arguments
// to \genfrac and \above.
res.text = "0pt"; // Enable \above{}
isBlank = true; // This is here specifically for \genfrac
}
var match = /([-+]?) *(\d+(?:\.\d*)?|\.\d+) *([a-z]{2})/.exec(res.text);
if (!match) {
throw new src_ParseError("Invalid size: '" + res.text + "'", res);
}
var data = {
number: +(match[1] + match[2]),
// sign + magnitude, cast to number
unit: match[3]
};
if (!validUnit(data)) {
throw new src_ParseError("Invalid unit: '" + data.unit + "'", res);
}
return {
type: "size",
mode: this.mode,
value: data,
isBlank: isBlank
};
}
/**
* Parses an URL, checking escaped letters and allowed protocols,
* and setting the catcode of % as an active character (as in \hyperref).
*/
;
_proto.parseUrlGroup = function parseUrlGroup(optional, consumeSpaces) {
this.gullet.lexer.setCatcode("%", 13); // active character
var res = this.parseStringGroup("url", optional, true); // get raw string
this.gullet.lexer.setCatcode("%", 14); // comment character
if (!res) {
return null;
} // hyperref package allows backslashes alone in href, but doesn't
// generate valid links in such cases; we interpret this as
// "undefined" behaviour, and keep them as-is. Some browser will
// replace backslashes with forward slashes.
var url = res.text.replace(/\\([#$%&~_^{}])/g, '$1');
return {
type: "url",
mode: this.mode,
url: url
};
}
/**
* If `optional` is false or absent, this parses an ordinary group,
* which is either a single nucleus (like "x") or an expression
* in braces (like "{x+y}") or an implicit group, a group that starts
* at the current position, and ends right before a higher explicit
* group ends, or at EOF.
* If `optional` is true, it parses either a bracket-delimited expression
* (like "[x+y]") or returns null to indicate the absence of a
* bracket-enclosed group.
* If `mode` is present, switches to that mode while parsing the group,
* and switches back after.
*/
;
_proto.parseGroup = function parseGroup(name, // For error reporting.
optional, greediness, breakOnTokenText, mode, consumeSpaces) {
// Switch to specified mode
var outerMode = this.mode;
if (mode) {
this.switchMode(mode);
} // Consume spaces if requested, crucially *after* we switch modes,
// so that the next non-space token is parsed in the correct mode.
if (consumeSpaces) {
this.consumeSpaces();
} // Get first token
var firstToken = this.fetch();
var text = firstToken.text;
var result; // Try to parse an open brace or \begingroup
if (optional ? text === "[" : text === "{" || text === "\\begingroup") {
this.consume();
var groupEnd = Parser.endOfGroup[text]; // Start a new group namespace
this.gullet.beginGroup(); // If we get a brace, parse an expression
var expression = this.parseExpression(false, groupEnd);
var lastToken = this.fetch(); // Check that we got a matching closing brace
this.expect(groupEnd); // End group namespace
this.gullet.endGroup();
result = {
type: "ordgroup",
mode: this.mode,
loc: SourceLocation.range(firstToken, lastToken),
body: expression,
// A group formed by \begingroup...\endgroup is a semi-simple group
// which doesn't affect spacing in math mode, i.e., is transparent.
// https://tex.stackexchange.com/questions/1930/when-should-one-
// use-begingroup-instead-of-bgroup
semisimple: text === "\\begingroup" || undefined
};
} else if (optional) {
// Return nothing for an optional group
result = null;
} else {
// If there exists a function with this name, parse the function.
// Otherwise, just return a nucleus
result = this.parseFunction(breakOnTokenText, name, greediness) || this.parseSymbol();
if (result == null && text[0] === "\\" && !implicitCommands.hasOwnProperty(text)) {
if (this.settings.throwOnError) {
throw new src_ParseError("Undefined control sequence: " + text, firstToken);
}
result = this.formatUnsupportedCmd(text);
this.consume();
}
} // Switch mode back
if (mode) {
this.switchMode(outerMode);
}
return result;
}
/**
* Form ligature-like combinations of characters for text mode.
* This includes inputs like "--", "---", "``" and "''".
* The result will simply replace multiple textord nodes with a single
* character in each value by a single textord node having multiple
* characters in its value. The representation is still ASCII source.
* The group will be modified in place.
*/
;
_proto.formLigatures = function formLigatures(group) {
var n = group.length - 1;
for (var i = 0; i < n; ++i) {
var a = group[i]; // $FlowFixMe: Not every node type has a `text` property.
var v = a.text;
if (v === "-" && group[i + 1].text === "-") {
if (i + 1 < n && group[i + 2].text === "-") {
group.splice(i, 3, {
type: "textord",
mode: "text",
loc: SourceLocation.range(a, group[i + 2]),
text: "---"
});
n -= 2;
} else {
group.splice(i, 2, {
type: "textord",
mode: "text",
loc: SourceLocation.range(a, group[i + 1]),
text: "--"
});
n -= 1;
}
}
if ((v === "'" || v === "`") && group[i + 1].text === v) {
group.splice(i, 2, {
type: "textord",
mode: "text",
loc: SourceLocation.range(a, group[i + 1]),
text: v + v
});
n -= 1;
}
}
}
/**
* Parse a single symbol out of the string. Here, we handle single character
* symbols and special functions like \verb.
*/
;
_proto.parseSymbol = function parseSymbol() {
var nucleus = this.fetch();
var text = nucleus.text;
if (/^\\verb[^a-zA-Z]/.test(text)) {
this.consume();
var arg = text.slice(5);
var star = arg.charAt(0) === "*";
if (star) {
arg = arg.slice(1);
} // Lexer's tokenRegex is constructed to always have matching
// first/last characters.
if (arg.length < 2 || arg.charAt(0) !== arg.slice(-1)) {
throw new src_ParseError("\\verb assertion failed --\n please report what input caused this bug");
}
arg = arg.slice(1, -1); // remove first and last char
return {
type: "verb",
mode: "text",
body: arg,
star: star
};
} // At this point, we should have a symbol, possibly with accents.
// First expand any accented base symbol according to unicodeSymbols.
if (unicodeSymbols.hasOwnProperty(text[0]) && !src_symbols[this.mode][text[0]]) {
// This behavior is not strict (XeTeX-compatible) in math mode.
if (this.settings.strict && this.mode === "math") {
this.settings.reportNonstrict("unicodeTextInMathMode", "Accented Unicode text character \"" + text[0] + "\" used in " + "math mode", nucleus);
}
text = unicodeSymbols[text[0]] + text.substr(1);
} // Strip off any combining characters
var match = combiningDiacriticalMarksEndRegex.exec(text);
if (match) {
text = text.substring(0, match.index);
if (text === 'i') {
text = "\u0131"; // dotless i, in math and text mode
} else if (text === 'j') {
text = "\u0237"; // dotless j, in math and text mode
}
} // Recognize base symbol
var symbol;
if (src_symbols[this.mode][text]) {
if (this.settings.strict && this.mode === 'math' && extraLatin.indexOf(text) >= 0) {
this.settings.reportNonstrict("unicodeTextInMathMode", "Latin-1/Unicode text character \"" + text[0] + "\" used in " + "math mode", nucleus);
}
var group = src_symbols[this.mode][text].group;
var loc = SourceLocation.range(nucleus);
var s;
if (ATOMS.hasOwnProperty(group)) {
// $FlowFixMe
var family = group;
s = {
type: "atom",
mode: this.mode,
family: family,
loc: loc,
text: text
};
} else {
// $FlowFixMe
s = {
type: group,
mode: this.mode,
loc: loc,
text: text
};
}
symbol = s;
} else if (text.charCodeAt(0) >= 0x80) {
// no symbol for e.g. ^
if (this.settings.strict) {
if (!supportedCodepoint(text.charCodeAt(0))) {
this.settings.reportNonstrict("unknownSymbol", "Unrecognized Unicode character \"" + text[0] + "\"" + (" (" + text.charCodeAt(0) + ")"), nucleus);
} else if (this.mode === "math") {
this.settings.reportNonstrict("unicodeTextInMathMode", "Unicode text character \"" + text[0] + "\" used in math mode", nucleus);
}
} // All nonmathematical Unicode characters are rendered as if they
// are in text mode (wrapped in \text) because that's what it
// takes to render them in LaTeX. Setting `mode: this.mode` is
// another natural choice (the user requested math mode), but
// this makes it more difficult for getCharacterMetrics() to
// distinguish Unicode characters without metrics and those for
// which we want to simulate the letter M.
symbol = {
type: "textord",
mode: "text",
loc: SourceLocation.range(nucleus),
text: text
};
} else {
return null; // EOF, ^, _, {, }, etc.
}
this.consume(); // Transform combining characters into accents
if (match) {
for (var i = 0; i < match[0].length; i++) {
var accent = match[0][i];
if (!unicodeAccents[accent]) {
throw new src_ParseError("Unknown accent ' " + accent + "'", nucleus);
}
var command = unicodeAccents[accent][this.mode];
if (!command) {
throw new src_ParseError("Accent " + accent + " unsupported in " + this.mode + " mode", nucleus);
}
symbol = {
type: "accent",
mode: this.mode,
loc: SourceLocation.range(nucleus),
label: command,
isStretchy: false,
isShifty: true,
base: symbol
};
}
}
return symbol;
};
return Parser;
}();
Parser_Parser.endOfExpression = ["}", "\\endgroup", "\\end", "\\right", "&"];
Parser_Parser.endOfGroup = {
"[": "]",
"{": "}",
"\\begingroup": "\\endgroup"
/**
* Parses an "expression", which is a list of atoms.
*
* `breakOnInfix`: Should the parsing stop when we hit infix nodes? This
* happens when functions have higher precendence han infix
* nodes in implicit parses.
*
* `breakOnTokenText`: The text of the token that the expression should end
* with, or `null` if something else should end the
* expression.
*/
};
Parser_Parser.SUPSUB_GREEDINESS = 1;
// CONCATENATED MODULE: ./src/parseTree.js
/**
* Provides a single function for parsing an expression using a Parser
* TODO(emily): Remove this
*/
/**
* Parses an expression using a Parser, then returns the parsed result.
*/
var parseTree_parseTree = function parseTree(toParse, settings) {
if (!(typeof toParse === 'string' || toParse instanceof String)) {
throw new TypeError('KaTeX can only parse string typed expression');
}
var parser = new Parser_Parser(toParse, settings); // Blank out any \df@tag to avoid spurious "Duplicate \tag" errors
delete parser.gullet.macros.current["\\df@tag"];
var tree = parser.parse(); // If the input used \tag, it will set the \df@tag macro to the tag.
// In this case, we separately parse the tag and wrap the tree.
if (parser.gullet.macros.get("\\df@tag")) {
if (!settings.displayMode) {
throw new src_ParseError("\\tag works only in display equations");
}
parser.gullet.feed("\\df@tag");
tree = [{
type: "tag",
mode: "text",
body: tree,
tag: parser.parse()
}];
}
return tree;
};
/* harmony default export */ var src_parseTree = (parseTree_parseTree);
// CONCATENATED MODULE: ./katex.js
/* eslint no-console:0 */
/**
* This is the main entry point for KaTeX. Here, we expose functions for
* rendering expressions either to DOM nodes or to markup strings.
*
* We also expose the ParseError class to check if errors thrown from KaTeX are
* errors in the expression, or errors in javascript handling.
*/
/**
* Parse and build an expression, and place that expression in the DOM node
* given.
*/
var katex_render = function render(expression, baseNode, options) {
baseNode.textContent = "";
var node = katex_renderToDomTree(expression, options).toNode();
baseNode.appendChild(node);
}; // KaTeX's styles don't work properly in quirks mode. Print out an error, and
// disable rendering.
if (typeof document !== "undefined") {
if (document.compatMode !== "CSS1Compat") {
typeof console !== "undefined" && console.warn("Warning: KaTeX doesn't work in quirks mode. Make sure your " + "website has a suitable doctype.");
katex_render = function render() {
throw new src_ParseError("KaTeX doesn't work in quirks mode.");
};
}
}
/**
* Parse and build an expression, and return the markup for that.
*/
var renderToString = function renderToString(expression, options) {
var markup = katex_renderToDomTree(expression, options).toMarkup();
return markup;
};
/**
* Parse an expression and return the parse tree.
*/
var katex_generateParseTree = function generateParseTree(expression, options) {
var settings = new Settings_Settings(options);
return src_parseTree(expression, settings);
};
/**
* If the given error is a KaTeX ParseError and options.throwOnError is false,
* renders the invalid LaTeX as a span with hover title giving the KaTeX
* error message. Otherwise, simply throws the error.
*/
var katex_renderError = function renderError(error, expression, options) {
if (options.throwOnError || !(error instanceof src_ParseError)) {
throw error;
}
var node = buildCommon.makeSpan(["katex-error"], [new domTree_SymbolNode(expression)]);
node.setAttribute("title", error.toString());
node.setAttribute("style", "color:" + options.errorColor);
return node;
};
/**
* Generates and returns the katex build tree. This is used for advanced
* use cases (like rendering to custom output).
*/
var katex_renderToDomTree = function renderToDomTree(expression, options) {
var settings = new Settings_Settings(options);
try {
var tree = src_parseTree(expression, settings);
return buildTree_buildTree(tree, expression, settings);
} catch (error) {
return katex_renderError(error, expression, settings);
}
};
/**
* Generates and returns the katex build tree, with just HTML (no MathML).
* This is used for advanced use cases (like rendering to custom output).
*/
var katex_renderToHTMLTree = function renderToHTMLTree(expression, options) {
var settings = new Settings_Settings(options);
try {
var tree = src_parseTree(expression, settings);
return buildTree_buildHTMLTree(tree, expression, settings);
} catch (error) {
return katex_renderError(error, expression, settings);
}
};
/* harmony default export */ var katex_0 = ({
/**
* Current KaTeX version
*/
version: "0.11.1",
/**
* Renders the given LaTeX into an HTML+MathML combination, and adds
* it as a child to the specified DOM node.
*/
render: katex_render,
/**
* Renders the given LaTeX into an HTML+MathML combination string,
* for sending to the client.
*/
renderToString: renderToString,
/**
* KaTeX error, usually during parsing.
*/
ParseError: src_ParseError,
/**
* Parses the given LaTeX into KaTeX's internal parse tree structure,
* without rendering to HTML or MathML.
*
* NOTE: This method is not currently recommended for public use.
* The internal tree representation is unstable and is very likely
* to change. Use at your own risk.
*/
__parse: katex_generateParseTree,
/**
* Renders the given LaTeX into an HTML+MathML internal DOM tree
* representation, without flattening that representation to a string.
*
* NOTE: This method is not currently recommended for public use.
* The internal tree representation is unstable and is very likely
* to change. Use at your own risk.
*/
__renderToDomTree: katex_renderToDomTree,
/**
* Renders the given LaTeX into an HTML internal DOM tree representation,
* without MathML and without flattening that representation to a string.
*
* NOTE: This method is not currently recommended for public use.
* The internal tree representation is unstable and is very likely
* to change. Use at your own risk.
*/
__renderToHTMLTree: katex_renderToHTMLTree,
/**
* extends internal font metrics object with a new object
* each key in the new object represents a font name
*/
__setFontMetrics: setFontMetrics,
/**
* adds a new symbol to builtin symbols table
*/
__defineSymbol: defineSymbol,
/**
* adds a new macro to builtin macro list
*/
__defineMacro: defineMacro,
/**
* Expose the dom tree node types, which can be useful for type checking nodes.
*
* NOTE: This method is not currently recommended for public use.
* The internal tree representation is unstable and is very likely
* to change. Use at your own risk.
*/
__domTree: {
Span: domTree_Span,
Anchor: domTree_Anchor,
SymbolNode: domTree_SymbolNode,
SvgNode: SvgNode,
PathNode: domTree_PathNode,
LineNode: LineNode
}
});
// CONCATENATED MODULE: ./katex.webpack.js
/**
* This is the webpack entry point for KaTeX. As ECMAScript, flow[1] and jest[2]
* doesn't support CSS modules natively, a separate entry point is used and
* it is not flowtyped.
*
* [1] https://gist.github.com/lambdahands/d19e0da96285b749f0ef
* [2] https://facebook.github.io/jest/docs/en/webpack.html
*/
/* harmony default export */ var katex_webpack = __webpack_exports__["default"] = (katex_0);
/***/ })
/******/ ])["default"];
});
/***/ }),
/***/ "PArb":
/*!***********************************************!*\
!*** ./node_modules/antd/es/divider/index.js ***!
\***********************************************/
/*! exports provided: default */
/*! exports used: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/extends */ "pVnL");
/* harmony import */ var _babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "lSNA");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react */ "q1tI");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! classnames */ "TSYQ");
/* harmony import */ var classnames__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(classnames__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _config_provider__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../config-provider */ "H84U");
var __rest = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
var Divider = function Divider(props) {
return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_config_provider__WEBPACK_IMPORTED_MODULE_4__[/* ConfigConsumer */ "a"], null, function (_ref) {
var _classNames;
var getPrefixCls = _ref.getPrefixCls,
direction = _ref.direction;
var customizePrefixCls = props.prefixCls,
_props$type = props.type,
type = _props$type === void 0 ? 'horizontal' : _props$type,
_props$orientation = props.orientation,
orientation = _props$orientation === void 0 ? 'center' : _props$orientation,
className = props.className,
children = props.children,
dashed = props.dashed,
plain = props.plain,
restProps = __rest(props, ["prefixCls", "type", "orientation", "className", "children", "dashed", "plain"]);
var prefixCls = getPrefixCls('divider', customizePrefixCls);
var orientationPrefix = orientation.length > 0 ? "-".concat(orientation) : orientation;
var hasChildren = !!children;
var classString = classnames__WEBPACK_IMPORTED_MODULE_3___default()(className, prefixCls, "".concat(prefixCls, "-").concat(type), (_classNames = {}, _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1___default()(_classNames, "".concat(prefixCls, "-with-text"), hasChildren), _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1___default()(_classNames, "".concat(prefixCls, "-with-text").concat(orientationPrefix), hasChildren), _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1___default()(_classNames, "".concat(prefixCls, "-dashed"), !!dashed), _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1___default()(_classNames, "".concat(prefixCls, "-plain"), !!plain), _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1___default()(_classNames, "".concat(prefixCls, "-rtl"), direction === 'rtl'), _classNames));
return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_2__["createElement"]("div", _babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0___default()({
className: classString
}, restProps, {
role: "separator"
}), children && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_2__["createElement"]("span", {
className: "".concat(prefixCls, "-inner-text")
}, children));
});
};
/* harmony default export */ __webpack_exports__["a"] = (Divider);
/***/ }),
/***/ "PVpz":
/*!*************************************************!*\
!*** ./node_modules/crypto-js/rabbit-legacy.js ***!
\*************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory, undef) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"), __webpack_require__(/*! ./enc-base64 */ "ETIr"), __webpack_require__(/*! ./md5 */ "cv67"), __webpack_require__(/*! ./evpkdf */ "K3mO"), __webpack_require__(/*! ./cipher-core */ "OLod"));
}
else {}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
// Reusable objects
var S = [];
var C_ = [];
var G = [];
/**
* Rabbit stream cipher algorithm.
*
* This is a legacy version that neglected to convert the key to little-endian.
* This error doesn't affect the cipher's security,
* but it does affect its compatibility with other implementations.
*/
var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var K = this._key.words;
var iv = this.cfg.iv;
// Generate initial state values
var X = this._X = [
K[0], (K[3] << 16) | (K[2] >>> 16),
K[1], (K[0] << 16) | (K[3] >>> 16),
K[2], (K[1] << 16) | (K[0] >>> 16),
K[3], (K[2] << 16) | (K[1] >>> 16)
];
// Generate initial counter values
var C = this._C = [
(K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
(K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
(K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
(K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
];
// Carry bit
this._b = 0;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
// Modify the counters
for (var i = 0; i < 8; i++) {
C[i] ^= X[(i + 4) & 7];
}
// IV setup
if (iv) {
// Shortcuts
var IV = iv.words;
var IV_0 = IV[0];
var IV_1 = IV[1];
// Generate four subvectors
var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
var i3 = (i2 << 16) | (i0 & 0x0000ffff);
// Modify counter values
C[0] ^= i0;
C[1] ^= i1;
C[2] ^= i2;
C[3] ^= i3;
C[4] ^= i0;
C[5] ^= i1;
C[6] ^= i2;
C[7] ^= i3;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
}
},
_doProcessBlock: function (M, offset) {
// Shortcut
var X = this._X;
// Iterate the system
nextState.call(this);
// Generate four keystream words
S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
for (var i = 0; i < 4; i++) {
// Swap endian
S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
(((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
// Encrypt
M[offset + i] ^= S[i];
}
},
blockSize: 128/32,
ivSize: 64/32
});
function nextState() {
// Shortcuts
var X = this._X;
var C = this._C;
// Save old counter values
for (var i = 0; i < 8; i++) {
C_[i] = C[i];
}
// Calculate new counter values
C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
// Calculate the g-values
for (var i = 0; i < 8; i++) {
var gx = X[i] + C[i];
// Construct high and low argument for squaring
var ga = gx & 0xffff;
var gb = gx >>> 16;
// Calculate high and low result of squaring
var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
// High XOR low
G[i] = gh ^ gl;
}
// Calculate new state values
X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg);
*/
C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy);
}());
return CryptoJS.RabbitLegacy;
}));
/***/ }),
/***/ "QB+1":
/*!**********************************************************!*\
!*** ./node_modules/@ant-design/icons/DeleteOutlined.js ***!
\**********************************************************/
/*! no static exports found */
/*! exports used: default */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _DeleteOutlined = _interopRequireDefault(__webpack_require__(/*! ./lib/icons/DeleteOutlined */ "Ywus"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _default = _DeleteOutlined;
exports.default = _default;
module.exports = _default;
/***/ }),
/***/ "QbM5":
/*!************************************************************!*\
!*** ./node_modules/antd/es/input-number/style/index.less ***!
\************************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/***/ "Qs3X":
/*!************************************************************!*\
!*** ./node_modules/@ant-design/icons/DownloadOutlined.js ***!
\************************************************************/
/*! no static exports found */
/*! exports used: default */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _DownloadOutlined = _interopRequireDefault(__webpack_require__(/*! ./lib/icons/DownloadOutlined */ "X+im"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _default = _DownloadOutlined;
exports.default = _default;
module.exports = _default;
/***/ }),
/***/ "QtKJ":
/*!**********************************************************************!*\
!*** ./src/pages/Competitions/components/PhoneModal.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/asyncToGenerator.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/regenerator/index.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./src/utils/env.ts */
/*! ModuleConcatenation bailout: Cannot concat with ./src/utils/fetch.ts */
/*! ModuleConcatenation bailout: Cannot concat with ./src/utils/util.tsx */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/button/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/button/style/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/input/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/input/style/index.js */
/*! 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/antd/es/modal/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/modal/style/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/react/index.js (<- Module is not an ECMAScript module) */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// EXTERNAL MODULE: ./node_modules/antd/es/modal/style/index.js
var style = __webpack_require__("2qtc");
// EXTERNAL MODULE: ./node_modules/antd/es/modal/index.js + 19 modules
var modal = __webpack_require__("kLXV");
// EXTERNAL MODULE: ./node_modules/antd/es/button/style/index.js
var button_style = __webpack_require__("+L6B");
// EXTERNAL MODULE: ./node_modules/antd/es/button/index.js
var es_button = __webpack_require__("2/Rp");
// EXTERNAL MODULE: ./node_modules/antd/es/input/style/index.js
var input_style = __webpack_require__("5NDa");
// EXTERNAL MODULE: ./node_modules/antd/es/input/index.js + 14 modules
var input = __webpack_require__("5rEg");
// 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);
// 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/asyncToGenerator.js
var asyncToGenerator = __webpack_require__("9og8");
// 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/react/index.js
var react = __webpack_require__("q1tI");
var react_default = /*#__PURE__*/__webpack_require__.n(react);
// EXTERNAL MODULE: ./src/utils/fetch.ts
var fetch = __webpack_require__("ErOA");
// CONCATENATED MODULE: ./src/utils/hooks/useInterval.tsx
function useInterval(callback, delay) {
var savedCallback = Object(react["useRef"])();
var savedId = Object(react["useRef"])(); // 保存新回调
Object(react["useEffect"])(function () {
savedCallback.current = callback;
}); // 建立 interval
Object(react["useEffect"])(function () {
function tick() {
savedCallback.current();
}
if (delay !== null) {
var id = setInterval(tick, delay);
savedId.current = id;
return function () {
return clearInterval(id);
};
}
}, [delay]);
}
// EXTERNAL MODULE: ./src/utils/util.tsx + 6 modules
var util = __webpack_require__("1vsH");
// EXTERNAL MODULE: ./src/utils/env.ts + 1 modules
var env = __webpack_require__("m3rI");
// CONCATENATED MODULE: ./src/pages/Competitions/components/PhoneModal.tsx
var phoneReg = /^1\d{10}$/;
function Addmodal(_ref) {
var isShowPhone = _ref.isShowPhone,
setIsShowPhone = _ref.setIsShowPhone,
user = _ref.user,
dispatch = _ref.dispatch,
onOK = _ref.onOK,
isopen = _ref.isopen,
setisopen = _ref.setisopen,
datas = _ref.datas;
var _useState = Object(react["useState"])(''),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
phone = _useState2[0],
setphone = _useState2[1];
var _useState3 = Object(react["useState"])(''),
_useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
PhoneValue = _useState4[0],
setPhoneValue = _useState4[1];
var _useState5 = Object(react["useState"])(60),
_useState6 = Object(slicedToArray["a" /* default */])(_useState5, 2),
countdown = _useState6[0],
setCountdown = _useState6[1];
var _useState7 = Object(react["useState"])(),
_useState8 = Object(slicedToArray["a" /* default */])(_useState7, 2),
countdownFlag = _useState8[0],
setCountdownFlag = _useState8[1];
var _useState9 = Object(react["useState"])(false),
_useState10 = Object(slicedToArray["a" /* default */])(_useState9, 2),
isShowPoint = _useState10[0],
setIsShowPoint = _useState10[1];
var _useState11 = Object(react["useState"])(false),
_useState12 = Object(slicedToArray["a" /* default */])(_useState11, 2),
isShowUntie = _useState12[0],
setIsShowUntie = _useState12[1];
var _useState13 = Object(react["useState"])(''),
_useState14 = Object(slicedToArray["a" /* default */])(_useState13, 2),
UntieValue = _useState14[0],
setUntieValue = _useState14[1];
var intervalId = Object(react["useRef"])();
Object(react["useEffect"])(function () {
return function () {
intervalId.current && clearInterval(intervalId.current);
};
}, []);
useInterval(function () {
if (!countdownFlag) {
return;
} else {
setCountdown(60);
}
if (countdown > 0) {
setCountdown(countdown - 1);
} else {
setCountdown(60);
setCountdownFlag(false);
intervalId.current && clearInterval(intervalId.current);
}
}, 1000);
var handleGetCode = /*#__PURE__*/function () {
var _ref2 = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee() {
var _user$eduUserInfo;
var data, smscode, res;
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return Object(fetch["a" /* default */])("/api/users/accounts/".concat((_user$eduUserInfo = user.eduUserInfo) === null || _user$eduUserInfo === void 0 ? void 0 : _user$eduUserInfo.login, "/valid_phone.json"), {
method: 'get',
params: {
phone: phone
}
});
case 2:
data = _context.sent;
if (!((data === null || data === void 0 ? void 0 : data.status) === -1)) {
_context.next = 5;
break;
}
return _context.abrupt("return");
case 5:
if (!(data === null || data === void 0 ? void 0 : data.is_exists)) {
_context.next = 8;
break;
}
setIsShowPoint(true);
return _context.abrupt("return");
case 8:
smscode = Object(util["r" /* setmiyah */])(phone);
_context.next = 11;
return dispatch({
type: 'account/getCode',
payload: {
login: phone,
type: 3,
smscode: smscode
}
});
case 11:
res = _context.sent;
if (res.status === 1) {
message["b" /* default */].info('验证码已发送,请注意查收');
setCountdownFlag(true);
}
case 13:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function handleGetCode() {
return _ref2.apply(this, arguments);
};
}();
return /*#__PURE__*/react_default.a.createElement("div", null, /*#__PURE__*/react_default.a.createElement(modal["a" /* default */], {
title: "\u5F3A\u5236\u89E3\u7ED1",
visible: isShowUntie,
onCancel: function onCancel() {
return setIsShowUntie(false);
},
onOk: /*#__PURE__*/Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee2() {
var _user$eduUserInfo2;
var data;
return regenerator_default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (UntieValue) {
_context2.next = 3;
break;
}
message["b" /* default */].info('验证码不能为空');
return _context2.abrupt("return");
case 3:
_context2.next = 5;
return Object(fetch["a" /* default */])("/api/users/accounts/".concat(user === null || user === void 0 ? void 0 : (_user$eduUserInfo2 = user.eduUserInfo) === null || _user$eduUserInfo2 === void 0 ? void 0 : _user$eduUserInfo2.login, "/phone_force_unbind.json"), {
method: 'POST',
body: {
code: UntieValue,
phone: phone
}
});
case 5:
data = _context2.sent;
if ((data === null || data === void 0 ? void 0 : data.status) === 0) {
message["b" /* default */].info('解绑成功');
setCountdownFlag(false);
setIsShowUntie(false);
onOK();
setIsShowPhone(false);
setUntieValue('');
}
case 7:
case "end":
return _context2.stop();
}
}
}, _callee2);
}))
}, /*#__PURE__*/react_default.a.createElement("div", {
style: {
padding: '8px 24px'
}
}, /*#__PURE__*/react_default.a.createElement("p", null, "\u82E5\u539F\u8D26\u53F7\u53EA\u6709\u7ED1\u5B9A\u4E86\u624B\u673A\u53F7\u4E00\u79CD\u767B\u5F55\u65B9\u5F0F\uFF0C\u5F3A\u5236\u89E3\u7ED1\u540E\u4F1A\u5BFC\u81F4\u539F\u8D26\u53F7\u65E0\u6CD5\u767B\u5F55\uFF0C\u8BF7\u786E\u5B9A\u662F\u5426\u5F3A\u5236\u89E3\u7ED1"), /*#__PURE__*/react_default.a.createElement("p", null, "\u4F60\u7684\u624B\u673A\u53F7\uFF1A", phone), /*#__PURE__*/react_default.a.createElement("p", null, "\u624B\u673A\u9A8C\u8BC1\u7801\uFF1A", /*#__PURE__*/react_default.a.createElement(input["a" /* default */], {
value: UntieValue,
size: "large",
onChange: function onChange(e) {
return setUntieValue(e.target.value);
},
style: {
width: '240px'
}
}), " ", /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
disabled: countdownFlag,
type: "primary",
size: "large",
onClick: /*#__PURE__*/Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee3() {
var smscode, res;
return regenerator_default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
smscode = Object(util["r" /* setmiyah */])(phone);
_context3.next = 3;
return dispatch({
type: 'account/getCode',
payload: {
login: phone,
type: 10,
smscode: smscode
}
});
case 3:
res = _context3.sent;
if (res.status === 1) {
message["b" /* default */].info('验证码已发送,请注意查收');
setCountdownFlag(true);
}
case 5:
case "end":
return _context3.stop();
}
}
}, _callee3);
}))
}, countdownFlag ? "\u91CD\u65B0\u53D1\u9001".concat(countdown, "s") : '获取验证码')))), /*#__PURE__*/react_default.a.createElement(modal["a" /* default */], {
title: "\u63D0\u793A",
visible: isShowPoint,
onCancel: function onCancel() {
setIsShowPoint(false);
},
okText: "\u8FDB\u884C\u5F3A\u5236\u89E3\u7ED1",
okButtonProps: {
type: "primary",
ghost: true,
style: {
width: "124px"
}
},
onOk: function onOk() {
setIsShowUntie(true);
setIsShowPoint(false);
} // footer={<div>
// <Button style={{textAlign:'end'}} type="primary" onClick={()=>setIsShowModal(false)}>确 定</Button>
// </div>}
}, /*#__PURE__*/react_default.a.createElement("div", {
style: {
padding: '7px 24px'
}
}, /*#__PURE__*/react_default.a.createElement("span", null, "\u8BE5\u624B\u673A\u53F7\u5DF2\u7ECF\u88AB\u7ED1\u5B9A\u8D26\u53F7\uFF0C\u5982\u679C\u9700\u8981\u5C06\u8BE5\u624B\u673A\u53F7\u7ED1\u5B9A\u5728\u5F53\u524D\u8D26\u53F7\u4E0A\uFF0C\u4F60\u53EF\u4EE5\u8FDB\u884C\u4E0B\u65B9\u4EFB\u610F\u4E00\u79CD\u89E3\u7ED1\u64CD\u4F5C\uFF1A"), /*#__PURE__*/react_default.a.createElement("br", null), /*#__PURE__*/react_default.a.createElement("p", {
style: {
marginTop: '1em',
display: 'flex'
}
}, /*#__PURE__*/react_default.a.createElement("span", {
style: {
flex: '1'
}
}, "1\u3001\u4F7F\u7528\u8BE5\u624B\u673A\u53F7\u767B\u5F55\u5E73\u53F0\u8FDB\u884C\u89E3\u7ED1\uFF0C\u518D\u5C06\u624B\u673A\u53F7\u7ED1\u5B9A\u5F53\u524D\u8D26\u53F7\u4E0A\u3002")), /*#__PURE__*/react_default.a.createElement("p", {
style: {
marginTop: '1em',
display: 'flex'
}
}, /*#__PURE__*/react_default.a.createElement("span", {
style: {
flex: '1'
}
}, "2\u3001\u5F3A\u5236\u89E3\u7ED1\uFF08\u5F3A\u5236\u89E3\u7ED1\u53EF\u80FD\u4F1A\u5BFC\u81F4\u89E3\u7ED1\u8D26\u53F7\u65E0\u6CD5\u767B\u5F55\uFF09")))), /*#__PURE__*/react_default.a.createElement(modal["a" /* default */], {
title: "\u7ED1\u5B9A\u624B\u673A\u53F7",
visible: isShowPhone,
onCancel: function onCancel() {
return setIsShowPhone(false);
},
onOk: /*#__PURE__*/Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee4() {
var _ref6, login, res;
return regenerator_default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
if (phoneReg.test(phone)) {
_context4.next = 3;
break;
}
message["b" /* default */].info("请输入有效的11位手机号码");
return _context4.abrupt("return");
case 3:
if (PhoneValue) {
_context4.next = 6;
break;
}
message["b" /* default */].info("请输入验证码");
return _context4.abrupt("return");
case 6:
_ref6 = user.eduUserInfo || {}, login = _ref6.login;
_context4.next = 9;
return dispatch({
type: 'account/bindPhone',
payload: {
login: login,
phone: phone,
code: PhoneValue
}
});
case 9:
res = _context4.sent;
if ((res === null || res === void 0 ? void 0 : res.status) === 0) {
setIsShowPhone(false);
onOK();
}
case 11:
case "end":
return _context4.stop();
}
}
}, _callee4);
}))
}, /*#__PURE__*/react_default.a.createElement("div", {
style: {
padding: '8px 24px'
}
}, /*#__PURE__*/react_default.a.createElement("p", null, "\u5E73\u53F0\u5DF2\u68C0\u6D4B\u5230\u60A8\u672A\u7ED1\u5B9A\u624B\u673A\u53F7\uFF0C\u4E3A\u4E86\u4E0D\u5F71\u54CD\u4F7F\u7528\u62A5\u540D\u529F\u80FD\uFF0C\u8BF7\u5148\u7ED1\u5B9A\u624B\u673A\u53F7\u7801"), /*#__PURE__*/react_default.a.createElement("p", null, "\u4F60\u7684\u624B\u673A\u53F7\uFF1A", /*#__PURE__*/react_default.a.createElement(input["a" /* default */], {
size: "large",
value: phone,
onChange: function onChange(e) {
return setphone(e.target.value);
},
style: {
width: '240px'
}
})), /*#__PURE__*/react_default.a.createElement("p", null, "\u624B\u673A\u9A8C\u8BC1\u7801\uFF1A", /*#__PURE__*/react_default.a.createElement(input["a" /* default */], {
size: "large",
value: PhoneValue,
onChange: function onChange(e) {
return setPhoneValue(e.target.value);
},
style: {
width: '240px'
}
}), " ", /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
disabled: countdownFlag,
type: "primary",
size: "large",
onClick: /*#__PURE__*/Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee5() {
return regenerator_default.a.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
if (phoneReg.test(phone)) {
_context5.next = 3;
break;
}
message["b" /* default */].info("请输入有效的11位手机号码");
return _context5.abrupt("return");
case 3:
handleGetCode();
case 4:
case "end":
return _context5.stop();
}
}
}, _callee5);
}))
}, countdownFlag ? "\u91CD\u65B0\u53D1\u9001".concat(countdown, "s") : '获取验证码')))), /*#__PURE__*/react_default.a.createElement(modal["a" /* default */], {
visible: isopen,
footer: false,
onCancel: function onCancel() {
return setisopen(false);
},
centered: true,
width: 460
}, /*#__PURE__*/react_default.a.createElement("div", null, /*#__PURE__*/react_default.a.createElement("div", {
style: {
marginTop: 50,
fontSize: 26,
color: '#3d3d3d',
textAlign: 'center',
marginBottom: 20
}
}, /*#__PURE__*/react_default.a.createElement("i", {
style: {
fontSize: 26,
color: '#52C41A'
},
className: "iconfont icon-tongguo"
}), " \u62A5\u540D\u6210\u529F"), /*#__PURE__*/react_default.a.createElement("div", {
style: {
alignItems: 'center',
textAlign: 'center'
}
}, /*#__PURE__*/react_default.a.createElement("img", {
style: {
width: 180,
border: '1px solid #eeeeef',
padding: 10,
marginBottom: 20
},
src: env["a" /* default */].IMG_SERVER + (datas === null || datas === void 0 ? void 0 : datas.QR_code)
}), /*#__PURE__*/react_default.a.createElement("p", {
style: {
color: '#AAAAAA'
}
}, "\u53C2\u8D5B\u8005\u53EF\u626B\u7801\u52A0\u5165\u5927\u8D5B\u5B98\u65B9\u4EA4\u6D41\u7FA4\uFF0C\u83B7\u53D6\u6700\u65B0\u7ADE\u8D5B\u901A\u77E5")))));
}
/* harmony default export */ var PhoneModal = __webpack_exports__["a"] = (Addmodal);
/***/ }),
/***/ "RCxd":
/*!******************************************************************************************!*\
!*** ./node_modules/@ant-design/icons/es/icons/ExclamationCircleOutlined.js + 1 modules ***!
\******************************************************************************************/
/*! exports provided: default */
/*! exports used: default */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/es/components/AntdIcon.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/esm/objectSpread2.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/react/index.js (<- Module is not an ECMAScript module) */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/objectSpread2.js
var objectSpread2 = __webpack_require__("VTBJ");
// EXTERNAL MODULE: ./node_modules/react/index.js
var react = __webpack_require__("q1tI");
// CONCATENATED MODULE: ./node_modules/@ant-design/icons-svg/es/asn/ExclamationCircleOutlined.js
// This icon file is generated automatically.
var ExclamationCircleOutlined_ExclamationCircleOutlined = { "icon": { "tag": "svg", "attrs": { "viewBox": "64 64 896 896", "focusable": "false" }, "children": [{ "tag": "path", "attrs": { "d": "M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm0 820c-205.4 0-372-166.6-372-372s166.6-372 372-372 372 166.6 372 372-166.6 372-372 372z" } }, { "tag": "path", "attrs": { "d": "M464 688a48 48 0 1096 0 48 48 0 10-96 0zm24-112h48c4.4 0 8-3.6 8-8V296c0-4.4-3.6-8-8-8h-48c-4.4 0-8 3.6-8 8v272c0 4.4 3.6 8 8 8z" } }] }, "name": "exclamation-circle", "theme": "outlined" };
/* harmony default export */ var asn_ExclamationCircleOutlined = (ExclamationCircleOutlined_ExclamationCircleOutlined);
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/es/components/AntdIcon.js + 5 modules
var AntdIcon = __webpack_require__("6VBw");
// CONCATENATED MODULE: ./node_modules/@ant-design/icons/es/icons/ExclamationCircleOutlined.js
// GENERATE BY ./scripts/generate.ts
// DON NOT EDIT IT MANUALLY
var icons_ExclamationCircleOutlined_ExclamationCircleOutlined = function ExclamationCircleOutlined(props, ref) {
return /*#__PURE__*/react["createElement"](AntdIcon["a" /* default */], Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, props), {}, {
ref: ref,
icon: asn_ExclamationCircleOutlined
}));
};
icons_ExclamationCircleOutlined_ExclamationCircleOutlined.displayName = 'ExclamationCircleOutlined';
/* harmony default export */ var icons_ExclamationCircleOutlined = __webpack_exports__["a"] = (/*#__PURE__*/react["forwardRef"](icons_ExclamationCircleOutlined_ExclamationCircleOutlined));
/***/ }),
/***/ "RMFE":
/*!**********************************!*\
!*** ./src/assets/images/hb.png ***!
\**********************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports) {
module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAWgAAAFyCAYAAADYqEAoAAAAAXNSR0IArs4c6QAADetJREFUeAHt1jFqXUEQRUHLaP9b/jZObmYU9MAJSlGDxNBUPw76+vz9+eWHAAECBHICv3MbWYgAAQIE/gkItA+BAAECUQGBjh7GWgQIEBBo3wABAgSiAgIdPYy1CBAgINC+AQIECEQFBDp6GGsRIEBAoH0DBAgQiAoIdPQw1iJAgIBA+wYIECAQFRDo6GGsRYAAAYH2DRAgQCAqINDRw1iLAAECAu0bIECAQFRAoKOHsRYBAgQE2jdAgACBqIBARw9jLQIECAi0b4AAAQJRAYGOHsZaBAgQEGjfAAECBKICAh09jLUIECAg0L4BAgQIRAUEOnoYaxEgQECgfQMECBCICgh09DDWIkCAgED7BggQIBAVEOjoYaxFgAABgfYNECBAICog0NHDWIsAAQIC7RsgQIBAVECgo4exFgECBATaN0CAAIGogEBHD2MtAgQICLRvgAABAlEBgY4exloECBAQaN8AAQIEogICHT2MtQgQICDQvgECBAhEBQQ6ehhrESBAQKB9AwQIEIgKCHT0MNYiQICAQPsGCBAgEBUQ6OhhrEWAAAGB9g0QIEAgKiDQ0cNYiwABAgLtGyBAgEBUQKCjh7EWAQIEBNo3QIAAgaiAQEcPYy0CBAh8/5Tg6+vrp3/q7wgQIEDgPwKfz+c/v92v/Ac9CxMBAgRSAgKdOodlCBAgMAGBnoWJAAECKQGBTp3DMgQIEJiAQM/CRIAAgZSAQKfOYRkCBAhMQKBnYSJAgEBKQKBT57AMAQIEJiDQszARIEAgJSDQqXNYhgABAhMQ6FmYCBAgkBIQ6NQ5LEOAAIEJCPQsTAQIEEgJCHTqHJYhQIDABAR6FiYCBAikBAQ6dQ7LECBAYAICPQsTAQIEUgICnTqHZQgQIDABgZ6FiQABAikBgU6dwzIECBCYgEDPwkSAAIGUgECnzmEZAgQITECgZ2EiQIBASkCgU+ewDAECBCYg0LMwESBAICUg0KlzWIYAAQITEOhZmAgQIJASEOjUOSxDgACBCQj0LEwECBBICQh06hyWIUCAwAQEehYmAgQIpAQEOnUOyxAgQGACAj0LEwECBFICAp06h2UIECAwAYGehYkAAQIpAYFOncMyBAgQmIBAz8JEgACBlIBAp85hGQIECExAoGdhIkCAQEpAoFPnsAwBAgQmINCzMBEgQCAlINCpc1iGAAECExDoWZgIECCQEhDo1DksQ4AAgQkI9CxMBAgQSAkIdOocliFAgMAEBHoWJgIECKQEBDp1DssQIEBgAgI9CxMBAgRSAgKdOodlCBAgMAGBnoWJAAECKQGBTp3DMgQIEJiAQM/CRIAAgZSAQKfOYRkCBAhMQKBnYSJAgEBKQKBT57AMAQIEJiDQszARIEAgJSDQqXNYhgABAhMQ6FmYCBAgkBIQ6NQ5LEOAAIEJCPQsTAQIEEgJCHTqHJYhQIDABAR6FiYCBAikBAQ6dQ7LECBAYAICPQsTAQIEUgICnTqHZQgQIDABgZ6FiQABAikBgU6dwzIECBCYgEDPwkSAAIGUgECnzmEZAgQITECgZ2EiQIBASkCgU+ewDAECBCYg0LMwESBAICUg0KlzWIYAAQITEOhZmAgQIJASEOjUOSxDgACBCQj0LEwECBBICQh06hyWIUCAwAQEehYmAgQIpAQEOnUOyxAgQGACAj0LEwECBFICAp06h2UIECAwAYGehYkAAQIpAYFOncMyBAgQmIBAz8JEgACBlIBAp85hGQIECExAoGdhIkCAQEpAoFPnsAwBAgQmINCzMBEgQCAlINCpc1iGAAECExDoWZgIECCQEhDo1DksQ4AAgQkI9CxMBAgQSAkIdOocliFAgMAEBHoWJgIECKQEBDp1DssQIEBgAgI9CxMBAgRSAgKdOodlCBAgMAGBnoWJAAECKQGBTp3DMgQIEJiAQM/CRIAAgZSAQKfOYRkCBAhMQKBnYSJAgEBKQKBT57AMAQIEJiDQszARIEAgJSDQqXNYhgABAhMQ6FmYCBAgkBIQ6NQ5LEOAAIEJCPQsTAQIEEgJCHTqHJYhQIDABAR6FiYCBAikBAQ6dQ7LECBAYAICPQsTAQIEUgICnTqHZQgQIDABgZ6FiQABAikBgU6dwzIECBCYgEDPwkSAAIGUgECnzmEZAgQITECgZ2EiQIBASkCgU+ewDAECBCYg0LMwESBAICUg0KlzWIYAAQITEOhZmAgQIJASEOjUOSxDgACBCQj0LEwECBBICQh06hyWIUCAwAQEehYmAgQIpAQEOnUOyxAgQGACAj0LEwECBFICAp06h2UIECAwAYGehYkAAQIpAYFOncMyBAgQmIBAz8JEgACBlIBAp85hGQIECExAoGdhIkCAQEpAoFPnsAwBAgQmINCzMBEgQCAlINCpc1iGAAECExDoWZgIECCQEhDo1DksQ4AAgQkI9CxMBAgQSAkIdOocliFAgMAEBHoWJgIECKQEBDp1DssQIEBgAgI9CxMBAgRSAgKdOodlCBAgMAGBnoWJAAECKQGBTp3DMgQIEJiAQM/CRIAAgZSAQKfOYRkCBAhMQKBnYSJAgEBKQKBT57AMAQIEJiDQszARIEAgJSDQqXNYhgABAhMQ6FmYCBAgkBIQ6NQ5LEOAAIEJCPQsTAQIEEgJCHTqHJYhQIDABAR6FiYCBAikBAQ6dQ7LECBAYAICPQsTAQIEUgICnTqHZQgQIDABgZ6FiQABAikBgU6dwzIECBCYgEDPwkSAAIGUgECnzmEZAgQITECgZ2EiQIBASkCgU+ewDAECBCYg0LMwESBAICUg0KlzWIYAAQITEOhZmAgQIJASEOjUOSxDgACBCQj0LEwECBBICQh06hyWIUCAwAQEehYmAgQIpAQEOnUOyxAgQGACAj0LEwECBFICAp06h2UIECAwAYGehYkAAQIpAYFOncMyBAgQmIBAz8JEgACBlIBAp85hGQIECExAoGdhIkCAQEpAoFPnsAwBAgQmINCzMBEgQCAlINCpc1iGAAECExDoWZgIECCQEhDo1DksQ4AAgQkI9CxMBAgQSAkIdOocliFAgMAEBHoWJgIECKQEBDp1DssQIEBgAgI9CxMBAgRSAgKdOodlCBAgMAGBnoWJAAECKQGBTp3DMgQIEJiAQM/CRIAAgZSAQKfOYRkCBAhMQKBnYSJAgEBKQKBT57AMAQIEJiDQszARIEAgJSDQqXNYhgABAhMQ6FmYCBAgkBIQ6NQ5LEOAAIEJCPQsTAQIEEgJCHTqHJYhQIDABAR6FiYCBAikBAQ6dQ7LECBAYAICPQsTAQIEUgICnTqHZQgQIDABgZ6FiQABAikBgU6dwzIECBCYgEDPwkSAAIGUgECnzmEZAgQITECgZ2EiQIBASkCgU+ewDAECBCYg0LMwESBAICUg0KlzWIYAAQITEOhZmAgQIJASEOjUOSxDgACBCQj0LEwECBBICQh06hyWIUCAwAQEehYmAgQIpAQEOnUOyxAgQGACAj0LEwECBFICAp06h2UIECAwAYGehYkAAQIpAYFOncMyBAgQmIBAz8JEgACBlIBAp85hGQIECExAoGdhIkCAQEpAoFPnsAwBAgQmINCzMBEgQCAlINCpc1iGAAECExDoWZgIECCQEhDo1DksQ4AAgQkI9CxMBAgQSAkIdOocliFAgMAEBHoWJgIECKQEBDp1DssQIEBgAgI9CxMBAgRSAgKdOodlCBAgMAGBnoWJAAECKQGBTp3DMgQIEJiAQM/CRIAAgZSAQKfOYRkCBAhMQKBnYSJAgEBKQKBT57AMAQIEJiDQszARIEAgJSDQqXNYhgABAhMQ6FmYCBAgkBIQ6NQ5LEOAAIEJCPQsTAQIEEgJCHTqHJYhQIDABAR6FiYCBAikBAQ6dQ7LECBAYAICPQsTAQIEUgICnTqHZQgQIDABgZ6FiQABAikBgU6dwzIECBCYgEDPwkSAAIGUgECnzmEZAgQITECgZ2EiQIBASkCgU+ewDAECBCYg0LMwESBAICUg0KlzWIYAAQITEOhZmAgQIJASEOjUOSxDgACBCQj0LEwECBBICXz/dJvP5/PTP/V3BAgQIHAg4D/oA0RPECBA4IWAQL9Q9SYBAgQOBAT6ANETBAgQeCEg0C9UvUmAAIEDAYE+QPQEAQIEXggI9AtVbxIgQOBAQKAPED1BgACBFwIC/ULVmwQIEDgQEOgDRE8QIEDghYBAv1D1JgECBA4EBPoA0RMECBB4ISDQL1S9SYAAgQMBgT5A9AQBAgReCAj0C1VvEiBA4EBAoA8QPUGAAIEXAgL9QtWbBAgQOBAQ6ANETxAgQOCFgEC/UPUmAQIEDgQE+gDREwQIEHghINAvVL1JgACBAwGBPkD0BAECBF4ICPQLVW8SIEDgQECgDxA9QYAAgRcCAv1C1ZsECBA4EBDoA0RPECBA4IWAQL9Q9SYBAgQOBAT6ANETBAgQeCEg0C9UvUmAAIEDAYE+QPQEAQIEXggI9AtVbxIgQOBAQKAPED1BgACBFwIC/ULVmwQIEDgQEOgDRE8QIEDghYBAv1D1JgECBA4EBPoA0RMECBB4ISDQL1S9SYAAgQMBgT5A9AQBAgReCAj0C1VvEiBA4EBAoA8QPUGAAIEXAgL9QtWbBAgQOBAQ6ANETxAgQOCFgEC/UPUmAQIEDgQE+gDREwQIEHghINAvVL1JgACBAwGBPkD0BAECBF4ICPQLVW8SIEDgQECgDxA9QYAAgRcCAv1C1ZsECBA4EBDoA0RPECBA4IXAH7PYDOHnuk1pAAAAAElFTkSuQmCC"
/***/ }),
/***/ "S6kV":
/*!********************************************!*\
!*** ./node_modules/crypto-js/mode-ofb.js ***!
\********************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory, undef) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"), __webpack_require__(/*! ./cipher-core */ "OLod"));
}
else {}
}(this, function (CryptoJS) {
/**
* Output Feedback block mode.
*/
CryptoJS.mode.OFB = (function () {
var OFB = CryptoJS.lib.BlockCipherMode.extend();
var Encryptor = OFB.Encryptor = OFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var keystream = this._keystream;
// Generate keystream
if (iv) {
keystream = this._keystream = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
OFB.Decryptor = Encryptor;
return OFB;
}());
return CryptoJS.mode.OFB;
}));
/***/ }),
/***/ "SA+Z":
/*!********************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/toArray.js ***!
\********************************************************/
/*! no static exports found */
/*! exports used: default */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
var arrayWithHoles = __webpack_require__(/*! ./arrayWithHoles.js */ "wTVA");
var iterableToArray = __webpack_require__(/*! ./iterableToArray.js */ "EbDI");
var unsupportedIterableToArray = __webpack_require__(/*! ./unsupportedIterableToArray.js */ "ZhPi");
var nonIterableRest = __webpack_require__(/*! ./nonIterableRest.js */ "wkBT");
function _toArray(arr) {
return arrayWithHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableRest();
}
module.exports = _toArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
/***/ }),
/***/ "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.
*
* <p>
* For a fairly comprehensive set of languages see the
* <a href="https://github.com/google/code-prettify#for-which-languages-does-it-work">README</a>
* 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.
* <p>
* Usage: <ol>
* <li> include this source file in an html page via
* {@code <script type="text/javascript" src="/path/to/prettify.js"></script>}
* <li> define style rules. See the example page for examples.
* <li> mark the {@code <pre>} and {@code <code>} tags in your source with
* {@code class=prettyprint.}
* You can also use the (html deprecated) {@code <xmp>} 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;
});
}
})();
/***/ }),
/***/ "SMhR":
/*!*****************************************!*\
!*** ./src/assets/images/teacherQQ.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,iVBORw0KGgoAAAANSUhEUgAAAcYAAAHGCAYAAADuYispAAAAAklEQVR4AewaftIAABHTSURBVO3BQY4cy5IEQdNA3//KNo2/8NU8XzCQyCpSReivSJKk/zmRJEnjRJIkjRNJkjROJEnSOJEkSeNEkiSNE0mSNE4kSdI4kSRJ40SSJI0TSZI0TiRJ0jiRJEnjRJIkjRNJkjROJEnSOJEkSeNEkiSNE0mSNE4kSdI4kSRJ40SSJI0TSZI0TiRJ0jiRJEnjRJIkjRNJkjROJEnSOJEkSeNEkiSNE0mSNH7yMiB/s7a5AWTTNhsgN9pmA2TTNp8MyI22uQHkv7TNDSCbttkAudE2bwJyo22eBGTTNhsgf7O2ecuJJEkaJ5IkaZxIkqRxIkmSxokkSRonkiRpnEiSpPGTD9c2nwzIk9pmA2TTNjeAPAnIpm1uANm0zQbIDSBPAXIDyKZtPhmQG22zAfLN2uaTAflUJ5IkaZxIkqRxIkmSxokkSRonkiRpnEiSpHEiSZLGT74ckCe1zZOAbNpm0zYbIDfaZgPkRts8qW1utM0GyKZtntI2GyBPArJpmw2QTds8CcimbW4A+WRAntQ23+pEkiSNE0mSNE4kSdI4kSRJ40SSJI0TSZI0TiRJ0viJXtU2T2qbDZA3Adm0zZOAbNpm0zYbIJu2+VZtswGyaZsbbbMBsmmbDZBN29xoG32mE0mSNE4kSdI4kSRJ40SSJI0TSZI0TiRJ0jiRJEnjJ3oVkCe1zZPaZgNk0zYbIJu2eRKQJwF5S9vcAPIkIJu2uQFk0zY32kbf6USSJI0TSZI0TiRJ0jiRJEnjRJIkjRNJkjROJEnS+MmXa5t/WdtsgGza5psB+WRt8xQgN4DcaJtv1jYbIDfa5pO1jf5/J5IkaZxIkqRxIkmSxokkSRonkiRpnEiSpHEiSZLGTz4ckH9Z22yAbNpmA2TTNhsgm7bZANm0zQbIpm02QDZtswFyA8h/aZsbbbMBsmmbDZBN22yAbNpmA2TTNhsgm7bZALkBZNM2N4Doz5xIkqRxIkmSxokkSRonkiRpnEiSpHEiSZLGiSRJGvRX9LGAvKltNkA2bXMDyJvaZgNk0zZPAfLN2mYD5EbbPAnIk9pG7ziRJEnjRJIkjRNJkjROJEnSOJEkSeNEkiSNE0mSNH7y4YBs2uYGkE3bbIBs2mYD5Ebb/Mva5klAbgB5S9tsgGza5gaQDZBN2zwJyJPaZgNkA2TTNhsgN9pmA2TTNt/qRJIkjRNJkjROJEnSOJEkSeNEkiSNE0mSNE4kSdKgv/IPA3KjbW4AeVLb3ADyzdrmBpAntc2nAnKjbTZANm1zA8gna5sNkH9Z27zlRJIkjRNJkjROJEnSOJEkSeNEkiSNE0mSNE4kSdL4yZcDcqNtbgDZtM2mbTZANm1zA8imbTZANm1zA8iTgGza5gaQpwDZtM2NttkAudE2b2qbDZAbbbMB8qa20f/vRJIkjRNJkjROJEnSOJEkSeNEkiSNE0mSNE4kSdL4ycuA3GibDZANkBttswHyJCA32uZJQDZt8yQgTwKyaZsNkD/VNk8CsmmbDZA3tc0GyI222QDZtM0NIJu2eRKQTdt8qxNJkjROJEnSOJEkSeNEkiSNE0mSNE4kSdI4kSRJ4yf/uLbZANkA2bTNDSBPAnKjbd7UNhsgN4Bs2uZG27wFyKZtbrTNBsimbW4AudE2N9pmA+RG29wAsmmbJwHZtM1bTiRJ0jiRJEnjRJIkjRNJkjROJEnSOJEkSeNEkiSNn3w5IJu2udE2N4DcaJsbQDZtswGyAfIvA7Jpmz8F5EbbPAnIpm1uANm0zZuAbNpm0zYbIBsgm7a5AeRJbfOpTiRJ0jiRJEnjRJIkjRNJkjROJEnSOJEkSeNEkiSNn3y4ttkAuQFk0zYbIDfa5gaQN7XNk4A8qW02QG4A+VNtswHyzdpmA+RJbfMkIJu2eVPbbIBs2uZvdSJJksaJJEkaJ5IkaZxIkqRxIkmSxokkSRonkiRp/ERX2kb/DcimbW4AuQFk0zYbIDfa5i1t8yYgm7a50TYbIN+sbW4A2bTNk4Bs2uYtJ5IkaZxIkqRxIkmSxokkSRonkiRpnEiSpHEiSZLGT/5yQDZtswHypLbZAHlT29xomw2QTdvcAHIDyKdqmze1zZuAvKltNkCeBOSTAflWJ5IkaZxIkqRxIkmSxokkSRonkiRpnEiSpHEiSZIG/ZUPBuRG22yAbNrmBpAbbbMBcqNtNkA2bbMBsmmbDZBN2zwJyFvaZgNk0zYbIDfaZgNk0zYbIG9qm08GZNM2GyCbttkA2bTNtzqRJEnjRJIkjRNJkjROJEnSOJEkSeNEkiSNE0mSNH7yMiBPAvIkIN8MyA0gm7bZALkB5Elt8yQgf6pt9N/aZgPkTUA2bbNpmycB+VedSJKkcSJJksaJJEkaJ5IkaZxIkqRxIkmSxokkSRr0V/5iQDZt882AbNrmBpBN22yAbNpmA+RG2zwJyKZt/hSQTds8CcimbW4A2bTNk4B8s7bZALnRNhsgm7bZANm0zVtOJEnSOJEkSeNEkiSNE0mSNE4kSdI4kSRJ40SSJI2ffDggm7bZtM0GyJvaZgPkBpBN2zypbTZAbrTNBsimbZ4E5ClAbrTNNwOyaZsbbXMDyI222QDZtM0GyAbIDSCbtvlUJ5IkaZxIkqRxIkmSxokkSRonkiRpnEiSpHEiSZIG/ZV/GJAbbbMB8qa22QDZtM0GyKZtbgDZtM0NIJu22QC50Tb/BciNttkAeVLbbIDcaJsNkE3bbIA8qW02QN7UNv+qE0mSNE4kSdI4kSRJ40SSJI0TSZI0TiRJ0jiRJEnjJy8DcqNt3gTkkwH5ZECeBOSTAXkKkE3bbIA8qW2e1DY32mYDZNM2GyD6TCeSJGmcSJKkcSJJksaJJEkaJ5IkaZxIkqRxIkmSxk++HJBN29xomycB2bTNm4Bs2mYD5JsBudE2TwGyaZsNkCcBudE2N4C8CciNtnkSkBtAbrTNpzqRJEnjRJIkjRNJkjROJEnSOJEkSeNEkiSNE0mSNH7ysrb5ZkA2bXMDyI22eRKQTds8CcimbTZANm2zAXIDyH9pmye1zQbIpm02QG4A+WRtswHyJCCbtnlT23yrE0mSNE4kSdI4kSRJ40SSJI0TSZI0TiRJ0vjJy4A8qW2e1DZvapsbQDZtswFyA8imbTZtc6Nt3tQ2TwGyaZtN22yA3GibDZBN22yAPAnIm9rmSUA2bbMBcqNt3nIiSZLGiSRJGieSJGmcSJKkcSJJksaJJEkaJ5IkadBf+WBANm2zAfLN2mYD5Ebb3AByo202QPSOttkA2bTNm4Bs2uYGEP25tvlUJ5IkaZxIkqRxIkmSxokkSRonkiRpnEiSpHEiSZIG/ZUXAbnRNjeA3GibG0ButM03A/LJ2mYDZNM2fwrIJ2ubG0A2bXMDyI22uQFk0zY3gNxomxtANm3zrU4kSdI4kSRJ40SSJI0TSZI0TiRJ0jiRJEnjRJIkDforLwKyaZsNkE3bPAnIpm02QJ7UNk8CcqNtNkButM0GyJPaZgPkT7XNBsiNttkA+Ze1zQ0gN9pmA+RNbbMBsmmbt5xIkqRxIkmSxokkSRonkiRpnEiSpHEiSZLGiSRJGvRX/mJANm3zzYDcaJsbQG60zQ0gm7a5AeRJbfMWIE9qmw2QG22zAXKjbTZANm2zAfKktrkB5E1t85YTSZI0TiRJ0jiRJEnjRJIkjRNJkjROJEnSOJEkSeMnLwOyaZsbbbMB8qa2udE2GyBvapsNkE3bbNrmTW2zAbIB8l/a5kltswHypLZ5U9s8CciNtnkSkE3b/KtOJEnSOJEkSeNEkiSNE0mSNE4kSdI4kSRJ40SSJI2fvKxtbgDZtM2NtvlmbbMB8iQgTwKyaZsNkG8F5Elt8yYgm7Z5EpBN2zwJyCcDcqNtPtWJJEkaJ5IkaZxIkqRxIkmSxokkSRonkiRpnEiSpPGTDwdk0zY32uYGkE3b3ACyaZtP1jZvArJpmw2QDZBN22yA/Bcgm7bZALkB5Ebb6L8B2bTNDSCbttkAudE2GyCbtnnLiSRJGieSJGmcSJKkcSJJksaJJEkaJ5IkaZxIkqRBf+UvBmTTNhsgm7a5AeSTtc2TgNxomw2QG22zAbJpmz8F5EbbbIC8qW2+GZBN2zwJyKZtNkButM0GyI22ecuJJEkaJ5IkaZxIkqRxIkmSxokkSRonkiRpnEiSpEF/5UVAbrTNk4DcaJsNkG/WNk8C8qS22QDZtM0GyKZtPhWQN7XNk4Bs2mYD5Elt8yQgN9rmb3UiSZLGiSRJGieSJGmcSJKkcSJJksaJJEkaJ5IkadBfeRGQN7XNk4Bs2uabAdm0zQbIm9rmUwHZtM0GyI222QB5U9tsgDypbZ4EZNM2bwKyaZtvdSJJksaJJEkaJ5IkaZxIkqRxIkmSxokkSRonkiRp/OTDtc0GyJOA3GibDZAbbXMDyKZtntQ23wzIjbb5L21zo21uALnRNhsgn6xtNkA2bfMmIG8CsmmbT3UiSZLGiSRJGieSJGmcSJKkcSJJksaJJEkaJ5IkadBf+WBANm2zAbJpmw2QTdv8y4DcaJsbQDZtswFyo202QDZt8xQgm7a5AeRG23wzIDfa5k1ANm1zA8iNtnnLiSRJGieSJGmcSJKkcSJJksaJJEkaJ5IkaZxIkqTxk79c2zwJyI222QDZtM2TgGzaZgNkA+RNbbMBcqNtNkD+VNvcALJpmzcB2bTNBsimbT4ZkE3bvAnIpm2+1YkkSRonkiRpnEiSpHEiSZLGiSRJGieSJGmcSJKkQX/lgwF5Uts8CciNtrkB5EltcwPIjbbZANm0zQbIp2qbJwHZtM0NIG9qmzcB2bTNBsiNttkAeVLbfKoTSZI0TiRJ0jiRJEnjRJIkjRNJkjROJEnSOJEkSYP+youAPKltngRk0zY3gGza5klAntQ2N4A8qW02QL5V22yAfLK22QC50TYbIJu22QD5Zm2zAXKjbd5yIkmSxokkSRonkiRpnEiSpHEiSZLGiSRJGieSJGnQX9FrgGzaZgNk0zYbIDfaZgNk0zYbIJu22QDZtM0NIJu2eQqQG21zA8imbTZANm3zJiBvapsnAbnRNn+rE0mSNE4kSdI4kSRJ40SSJI0TSZI0TiRJ0jiRJEnjJy8D8jdrm03b3GibDZA3tc2NtnkSkDcB+S9tc6NtntQ2N9rmBpAbbXOjbW4AuQFk0zZPAnKjbT7ViSRJGieSJGmcSJKkcSJJksaJJEkaJ5IkaZxIkqTxkw/XNp8MyJOAbNrmRts8CcimbT5Z22yA3GibpwDZtM0NIJ+sbTZAbgB5U9s8qW02QDZt861OJEnSOJEkSeNEkiSNE0mSNE4kSdI4kSRJ40SSJI2ffDkgT2qbJwF5UttsgLwJyJPa5gaQG0De0jY3gGza5gaQG22zAXKjbZ4EZAPkTUBuANm0zac6kSRJ40SSJI0TSZI0TiRJ0jiRJEnjRJIkjRNJkjR+ole1zZvaZgPkRtvcAPIkIJu22QDZtM3fCsiNttkAudE2TwKyaZtN22yAbNrmBpAbbbMBsgGyaZu3nEiSpHEiSZLGiSRJGieSJGmcSJKkcSJJksaJJEkaP9FHA3KjbTZAngRk0zafDMiTgPyptrkB5Eltc6Nt3gTkTW1zA8imbZ7UNt/qRJIkjRNJkjROJEnSOJEkSeNEkiSNE0mSNE4kSdL4yZdrm28G5JO1zQ0gN9pmA2QDZNM2GyCbtrnRNk8BcqNtNkA2QN7UNhsgTwKyaZsNkE3bvAnIjbb5VCeSJGmcSJKkcSJJksaJJEkaJ5IkaZxIkqRxIkmSBv2VFwH5m7XNk4Bs2uZJQJ7UNjeA3GibTwXkRttsgNxomw2QG22zAXKjbW4AeVLbbIDcaJsNkCe1zVtOJEnSOJEkSeNEkiSNE0mSNE4kSdI4kSRJ40SSJA36K5Ik6X9OJEnSOJEkSeNEkiSNE0mSNE4kSdI4kSRJ40SSJI0TSZI0TiRJ0jiRJEnjRJIkjRNJkjROJEnSOJEkSeNEkiSNE0mSNE4kSdI4kSRJ40SSJI0TSZI0TiRJ0jiRJEnjRJIkjRNJkjROJEnSOJEkSeNEkiSNE0mSNE4kSdI4kSRJ4/8ATrCgy9kbxW8AAAAASUVORK5CYII="
/***/ }),
/***/ "SRve":
/*!********************************************************************!*\
!*** ./node_modules/@ant-design/icons-svg/lib/asn/PlusOutlined.js ***!
\********************************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// This icon file is generated automatically.
Object.defineProperty(exports, "__esModule", { value: true });
var PlusOutlined = { "icon": { "tag": "svg", "attrs": { "viewBox": "64 64 896 896", "focusable": "false" }, "children": [{ "tag": "defs", "attrs": {}, "children": [{ "tag": "style", "attrs": {} }] }, { "tag": "path", "attrs": { "d": "M482 152h60q8 0 8 8v704q0 8-8 8h-60q-8 0-8-8V160q0-8 8-8z" } }, { "tag": "path", "attrs": { "d": "M176 474h672q8 0 8 8v60q0 8-8 8H176q-8 0-8-8v-60q0-8 8-8z" } }] }, "name": "plus", "theme": "outlined" };
exports.default = PlusOutlined;
/***/ }),
/***/ "Sjjz":
/*!*******************************************************************************************!*\
!*** ./src/pages/Competitions/Detail/components/AppplyDepartmentModal/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 = {"flexRow":"flexRow___1u_bL","flexColumn":"flexColumn___1kaUk","formWrap":"formWrap___31wys","example":"example___Cqoob","footerWrap":"footerWrap___2syNI"};
/***/ }),
/***/ "TGq3":
/*!***********************************************!*\
!*** ./src/assets/images/icons/lockclose.svg ***!
\***********************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/lockclose.365036e8.svg";
/***/ }),
/***/ "ToDW":
/*!************************************************************!*\
!*** ./node_modules/@ant-design/react-slick/lib/slider.js ***!
\************************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "TqRt");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _extends2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/extends */ "pVnL"));
var _objectSpread2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/objectSpread2 */ "3tO9"));
var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "lwsE"));
var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "W8MJ"));
var _assertThisInitialized2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "PJYZ"));
var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "7W2i"));
var _createSuper2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createSuper */ "LQ03"));
var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "lSNA"));
var _react = _interopRequireDefault(__webpack_require__(/*! react */ "q1tI"));
var _innerSlider = __webpack_require__(/*! ./inner-slider */ "hQUZ");
var _json2mq = _interopRequireDefault(__webpack_require__(/*! json2mq */ "pIsd"));
var _defaultProps = _interopRequireDefault(__webpack_require__(/*! ./default-props */ "cZFH"));
var _innerSliderUtils = __webpack_require__(/*! ./utils/innerSliderUtils */ "3K4p");
var Slider = /*#__PURE__*/function (_React$Component) {
(0, _inherits2["default"])(Slider, _React$Component);
var _super = (0, _createSuper2["default"])(Slider);
function Slider(props) {
var _this;
(0, _classCallCheck2["default"])(this, Slider);
_this = _super.call(this, props);
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "innerSliderRefHandler", function (ref) {
return _this.innerSlider = ref;
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "slickPrev", function () {
return _this.innerSlider.slickPrev();
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "slickNext", function () {
return _this.innerSlider.slickNext();
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "slickGoTo", function (slide) {
var dontAnimate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
return _this.innerSlider.slickGoTo(slide, dontAnimate);
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "slickPause", function () {
return _this.innerSlider.pause("paused");
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "slickPlay", function () {
return _this.innerSlider.autoPlay("play");
});
_this.state = {
breakpoint: null
};
_this._responsiveMediaHandlers = [];
return _this;
}
(0, _createClass2["default"])(Slider, [{
key: "media",
value: function media(query, handler) {
// javascript handler for css media query
var mql = window.matchMedia(query);
var listener = function listener(_ref) {
var matches = _ref.matches;
if (matches) {
handler();
}
};
mql.addListener(listener);
listener(mql);
this._responsiveMediaHandlers.push({
mql: mql,
query: query,
listener: listener
});
} // handles responsive breakpoints
}, {
key: "componentDidMount",
value: function componentDidMount() {
var _this2 = this;
// performance monitoring
//if (process.env.NODE_ENV !== 'production') {
//const { whyDidYouUpdate } = require('why-did-you-update')
//whyDidYouUpdate(React)
//}
if (this.props.responsive) {
var breakpoints = this.props.responsive.map(function (breakpt) {
return breakpt.breakpoint;
}); // sort them in increasing order of their numerical value
breakpoints.sort(function (x, y) {
return x - y;
});
breakpoints.forEach(function (breakpoint, index) {
// media query for each breakpoint
var bQuery;
if (index === 0) {
bQuery = (0, _json2mq["default"])({
minWidth: 0,
maxWidth: breakpoint
});
} else {
bQuery = (0, _json2mq["default"])({
minWidth: breakpoints[index - 1] + 1,
maxWidth: breakpoint
});
} // when not using server side rendering
(0, _innerSliderUtils.canUseDOM)() && _this2.media(bQuery, function () {
_this2.setState({
breakpoint: breakpoint
});
});
}); // Register media query for full screen. Need to support resize from small to large
// convert javascript object to media query string
var query = (0, _json2mq["default"])({
minWidth: breakpoints.slice(-1)[0]
});
(0, _innerSliderUtils.canUseDOM)() && this.media(query, function () {
_this2.setState({
breakpoint: null
});
});
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this._responsiveMediaHandlers.forEach(function (obj) {
obj.mql.removeListener(obj.listener);
});
}
}, {
key: "render",
value: function render() {
var _this3 = this;
var settings;
var newProps;
if (this.state.breakpoint) {
newProps = this.props.responsive.filter(function (resp) {
return resp.breakpoint === _this3.state.breakpoint;
});
settings = newProps[0].settings === "unslick" ? "unslick" : (0, _objectSpread2["default"])((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, _defaultProps["default"]), this.props), newProps[0].settings);
} else {
settings = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, _defaultProps["default"]), this.props);
} // force scrolling by one if centerMode is on
if (settings.centerMode) {
if (settings.slidesToScroll > 1 && "production" !== "production") {
console.warn("slidesToScroll should be equal to 1 in centerMode, you are using ".concat(settings.slidesToScroll));
}
settings.slidesToScroll = 1;
} // force showing one slide and scrolling by one if the fade mode is on
if (settings.fade) {
if (settings.slidesToShow > 1 && "production" !== "production") {
console.warn("slidesToShow should be equal to 1 when fade is true, you're using ".concat(settings.slidesToShow));
}
if (settings.slidesToScroll > 1 && "production" !== "production") {
console.warn("slidesToScroll should be equal to 1 when fade is true, you're using ".concat(settings.slidesToScroll));
}
settings.slidesToShow = 1;
settings.slidesToScroll = 1;
} // makes sure that children is an array, even when there is only 1 child
var children = _react["default"].Children.toArray(this.props.children); // Children may contain false or null, so we should filter them
// children may also contain string filled with spaces (in certain cases where we use jsx strings)
children = children.filter(function (child) {
if (typeof child === "string") {
return !!child.trim();
}
return !!child;
}); // rows and slidesPerRow logic is handled here
if (settings.variableWidth && (settings.rows > 1 || settings.slidesPerRow > 1)) {
console.warn("variableWidth is not supported in case of rows > 1 or slidesPerRow > 1");
settings.variableWidth = false;
}
var newChildren = [];
var currentWidth = null;
for (var i = 0; i < children.length; i += settings.rows * settings.slidesPerRow) {
var newSlide = [];
for (var j = i; j < i + settings.rows * settings.slidesPerRow; j += settings.slidesPerRow) {
var row = [];
for (var k = j; k < j + settings.slidesPerRow; k += 1) {
if (settings.variableWidth && children[k].props.style) {
currentWidth = children[k].props.style.width;
}
if (k >= children.length) break;
row.push( /*#__PURE__*/_react["default"].cloneElement(children[k], {
key: 100 * i + 10 * j + k,
tabIndex: -1,
style: {
width: "".concat(100 / settings.slidesPerRow, "%"),
display: "inline-block"
}
}));
}
newSlide.push( /*#__PURE__*/_react["default"].createElement("div", {
key: 10 * i + j
}, row));
}
if (settings.variableWidth) {
newChildren.push( /*#__PURE__*/_react["default"].createElement("div", {
key: i,
style: {
width: currentWidth
}
}, newSlide));
} else {
newChildren.push( /*#__PURE__*/_react["default"].createElement("div", {
key: i
}, newSlide));
}
}
if (settings === "unslick") {
var className = "regular slider " + (this.props.className || "");
return /*#__PURE__*/_react["default"].createElement("div", {
className: className
}, children);
} else if (newChildren.length <= settings.slidesToShow) {
settings.unslick = true;
}
return /*#__PURE__*/_react["default"].createElement(_innerSlider.InnerSlider, (0, _extends2["default"])({
style: this.props.style,
ref: this.innerSliderRefHandler
}, settings), newChildren);
}
}]);
return Slider;
}(_react["default"].Component);
exports["default"] = Slider;
/***/ }),
/***/ "UfjD":
/*!*******************************************************************!*\
!*** ./src/pages/Competitions/Entered/Enteredmodel/JoinModel.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 _Users_xxq_node_forgeplus_react_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/slicedToArray */ "tJVT");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! react */ "q1tI");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _ant_design_icons__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @ant-design/icons */ "4i/N");
//通过邀请码加入战队
function Jointeam(_ref) {
var isjoin = _ref.isjoin,
setJoin = _ref.setJoin,
JoinTeams = _ref.JoinTeams;
var _useState = Object(react__WEBPACK_IMPORTED_MODULE_7__["useState"])(""),
_useState2 = Object(_Users_xxq_node_forgeplus_react_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_6__[/* default */ "a"])(_useState, 2),
code = _useState2[0],
setCode = _useState2[1];
return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement(antd_es_modal__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"], {
centered: true,
title: /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("div", {
style: {
alignItems: 'center',
display: 'flex'
}
}, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("div", {
style: {
textAlign: 'left',
flex: '1'
}
}, "\u52A0\u5165\u6218\u961F"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement(_ant_design_icons__WEBPACK_IMPORTED_MODULE_8__[/* default */ "a"], {
onClick: function onClick() {
return setJoin(false);
},
style: {
cursor: 'porint'
}
})),
visible: isjoin,
closable: false,
destroyOnClose: true,
onOk: function onOk() {
if (!code) {
antd_es_message__WEBPACK_IMPORTED_MODULE_5__[/* default */ "b"].info('邀请码不能为空');
return;
}
JoinTeams(code);
},
onCancel: function onCancel() {
return setJoin(false);
}
}, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("div", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("p", {
style: {
marginTop: '15px',
marginLeft: '15px',
display: 'flex',
alignItems: 'center'
}
}, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("span", {
style: {
flex: 'none'
}
}, "\u9080\u8BF7\u7801\uFF1A"), " ", /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement(antd_es_input__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"], {
placeholder: "请输入邀请码",
value: code,
maxLength: 60,
addonAfter: String(code && code.length || 0) + "/60",
onChange: function onChange(e) {
return setCode(e.target.value);
}
}))));
}
/* harmony default export */ __webpack_exports__["a"] = (Jointeam);
/***/ }),
/***/ "UmKh":
/*!*****************************************************************************!*\
!*** ./node_modules/antd/node_modules/rc-animate/es/Animate.js + 4 modules ***!
\*****************************************************************************/
/*! exports provided: default */
/*! exports used: default */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/css-animation/es/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/react-dom/index.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/react/index.js (<- Module is not an ECMAScript module) */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// EXTERNAL MODULE: ./node_modules/react/index.js
var react = __webpack_require__("q1tI");
var react_default = /*#__PURE__*/__webpack_require__.n(react);
// CONCATENATED MODULE: ./node_modules/antd/node_modules/rc-animate/node_modules/rc-util/es/unsafeLifecyclesPolyfill.js
var unsafeLifecyclesPolyfill_unsafeLifecyclesPolyfill = function unsafeLifecyclesPolyfill(Component) {
var prototype = Component.prototype;
if (!prototype || !prototype.isReactComponent) {
throw new Error('Can only polyfill class components');
} // only handle componentWillReceiveProps
if (typeof prototype.componentWillReceiveProps !== 'function') {
return Component;
} // In React 16.9, React.Profiler was introduced together with UNSAFE_componentWillReceiveProps
// https://reactjs.org/blog/2019/08/08/react-v16.9.0.html#performance-measurements-with-reactprofiler
if (!react_default.a.Profiler) {
return Component;
} // Here polyfill get started
prototype.UNSAFE_componentWillReceiveProps = prototype.componentWillReceiveProps;
delete prototype.componentWillReceiveProps;
return Component;
};
/* harmony default export */ var es_unsafeLifecyclesPolyfill = (unsafeLifecyclesPolyfill_unsafeLifecyclesPolyfill);
// CONCATENATED MODULE: ./node_modules/antd/node_modules/rc-animate/es/ChildrenUtils.js
function toArrayChildren(children) {
var ret = [];
react_default.a.Children.forEach(children, function (child) {
ret.push(child);
});
return ret;
}
function findChildInChildrenByKey(children, key) {
var ret = null;
if (children) {
children.forEach(function (child) {
if (ret) {
return;
}
if (child && child.key === key) {
ret = child;
}
});
}
return ret;
}
function findShownChildInChildrenByKey(children, key, showProp) {
var ret = null;
if (children) {
children.forEach(function (child) {
if (child && child.key === key && child.props[showProp]) {
if (ret) {
throw new Error('two child with same key for <rc-animate> children');
}
ret = child;
}
});
}
return ret;
}
function findHiddenChildInChildrenByKey(children, key, showProp) {
var found = 0;
if (children) {
children.forEach(function (child) {
if (found) {
return;
}
found = child && child.key === key && !child.props[showProp];
});
}
return found;
}
function isSameChildren(c1, c2, showProp) {
var same = c1.length === c2.length;
if (same) {
c1.forEach(function (child, index) {
var child2 = c2[index];
if (child && child2) {
if (child && !child2 || !child && child2) {
same = false;
} else if (child.key !== child2.key) {
same = false;
} else if (showProp && child.props[showProp] !== child2.props[showProp]) {
same = false;
}
}
});
}
return same;
}
function mergeChildren(prev, next) {
var ret = [];
// For each key of `next`, the list of keys to insert before that key in
// the combined list
var nextChildrenPending = {};
var pendingChildren = [];
prev.forEach(function (child) {
if (child && findChildInChildrenByKey(next, child.key)) {
if (pendingChildren.length) {
nextChildrenPending[child.key] = pendingChildren;
pendingChildren = [];
}
} else {
pendingChildren.push(child);
}
});
next.forEach(function (child) {
if (child && Object.prototype.hasOwnProperty.call(nextChildrenPending, child.key)) {
ret = ret.concat(nextChildrenPending[child.key]);
}
ret.push(child);
});
ret = ret.concat(pendingChildren);
return ret;
}
// EXTERNAL MODULE: ./node_modules/react-dom/index.js
var react_dom = __webpack_require__("i8i4");
var react_dom_default = /*#__PURE__*/__webpack_require__.n(react_dom);
// EXTERNAL MODULE: ./node_modules/@ant-design/css-animation/es/index.js
var es = __webpack_require__("UwPn");
// CONCATENATED MODULE: ./node_modules/antd/node_modules/rc-animate/es/util/animate.js
var util = {
isAppearSupported: function isAppearSupported(props) {
return props.transitionName && props.transitionAppear || props.animation.appear;
},
isEnterSupported: function isEnterSupported(props) {
return props.transitionName && props.transitionEnter || props.animation.enter;
},
isLeaveSupported: function isLeaveSupported(props) {
return props.transitionName && props.transitionLeave || props.animation.leave;
},
allowAppearCallback: function allowAppearCallback(props) {
return props.transitionAppear || props.animation.appear;
},
allowEnterCallback: function allowEnterCallback(props) {
return props.transitionEnter || props.animation.enter;
},
allowLeaveCallback: function allowLeaveCallback(props) {
return props.transitionLeave || props.animation.leave;
}
};
/* harmony default export */ var animate = (util);
// CONCATENATED MODULE: ./node_modules/antd/node_modules/rc-animate/es/AnimateChild.js
var _createClass = function () { 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/* eslint react/prop-types: 0 */
var transitionMap = {
enter: 'transitionEnter',
appear: 'transitionAppear',
leave: 'transitionLeave'
};
var AnimateChild_AnimateChild = function (_React$Component) {
_inherits(AnimateChild, _React$Component);
function AnimateChild() {
_classCallCheck(this, AnimateChild);
return _possibleConstructorReturn(this, (AnimateChild.__proto__ || Object.getPrototypeOf(AnimateChild)).apply(this, arguments));
}
_createClass(AnimateChild, [{
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.stop();
}
}, {
key: 'componentWillEnter',
value: function componentWillEnter(done) {
if (animate.isEnterSupported(this.props)) {
this.transition('enter', done);
} else {
done();
}
}
}, {
key: 'componentWillAppear',
value: function componentWillAppear(done) {
if (animate.isAppearSupported(this.props)) {
this.transition('appear', done);
} else {
done();
}
}
}, {
key: 'componentWillLeave',
value: function componentWillLeave(done) {
if (animate.isLeaveSupported(this.props)) {
this.transition('leave', done);
} else {
// always sync, do not interupt with react component life cycle
// update hidden -> animate hidden ->
// didUpdate -> animate leave -> unmount (if animate is none)
done();
}
}
}, {
key: 'transition',
value: function transition(animationType, finishCallback) {
var _this2 = this;
var node = react_dom_default.a.findDOMNode(this);
var props = this.props;
var transitionName = props.transitionName;
var nameIsObj = typeof transitionName === 'object';
this.stop();
var end = function end() {
_this2.stopper = null;
finishCallback();
};
if ((es["b" /* isCssAnimationSupported */] || !props.animation[animationType]) && transitionName && props[transitionMap[animationType]]) {
var name = nameIsObj ? transitionName[animationType] : transitionName + '-' + animationType;
var activeName = name + '-active';
if (nameIsObj && transitionName[animationType + 'Active']) {
activeName = transitionName[animationType + 'Active'];
}
this.stopper = Object(es["a" /* default */])(node, {
name: name,
active: activeName
}, end);
} else {
this.stopper = props.animation[animationType](node, end);
}
}
}, {
key: 'stop',
value: function stop() {
var stopper = this.stopper;
if (stopper) {
this.stopper = null;
stopper.stop();
}
}
}, {
key: 'render',
value: function render() {
return this.props.children;
}
}]);
return AnimateChild;
}(react_default.a.Component);
/* harmony default export */ var es_AnimateChild = (AnimateChild_AnimateChild);
// CONCATENATED MODULE: ./node_modules/antd/node_modules/rc-animate/es/Animate.js
var _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; };
var Animate_createClass = function () { 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
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; }
function Animate_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function Animate_possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function Animate_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/* eslint react/prop-types: 0 */
var defaultKey = 'rc_animate_' + Date.now();
function getChildrenFromProps(props) {
var children = props.children;
if (react_default.a.isValidElement(children)) {
if (!children.key) {
return react_default.a.cloneElement(children, {
key: defaultKey
});
}
}
return children;
}
function noop() {}
var Animate_Animate = function (_React$Component) {
Animate_inherits(Animate, _React$Component);
function Animate(props) {
Animate_classCallCheck(this, Animate);
var _this = Animate_possibleConstructorReturn(this, (Animate.__proto__ || Object.getPrototypeOf(Animate)).call(this, props));
Animate_initialiseProps.call(_this);
_this.currentlyAnimatingKeys = {};
_this.keysToEnter = [];
_this.keysToLeave = [];
_this.state = {
children: toArrayChildren(getChildrenFromProps(props))
};
_this.childrenRefs = {};
return _this;
} // eslint-disable-line
Animate_createClass(Animate, [{
key: 'componentDidMount',
value: function componentDidMount() {
var _this2 = this;
var showProp = this.props.showProp;
var children = this.state.children;
if (showProp) {
children = children.filter(function (child) {
return !!child.props[showProp];
});
}
children.forEach(function (child) {
if (child) {
_this2.performAppear(child.key);
}
});
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
var _this3 = this;
this.nextProps = nextProps;
var nextChildren = toArrayChildren(getChildrenFromProps(nextProps));
var props = this.props;
// exclusive needs immediate response
if (props.exclusive) {
Object.keys(this.currentlyAnimatingKeys).forEach(function (key) {
_this3.stop(key);
});
}
var showProp = props.showProp;
var currentlyAnimatingKeys = this.currentlyAnimatingKeys;
// last props children if exclusive
var currentChildren = props.exclusive ? toArrayChildren(getChildrenFromProps(props)) : this.state.children;
// in case destroy in showProp mode
var newChildren = [];
if (showProp) {
currentChildren.forEach(function (currentChild) {
var nextChild = currentChild && findChildInChildrenByKey(nextChildren, currentChild.key);
var newChild = void 0;
if ((!nextChild || !nextChild.props[showProp]) && currentChild.props[showProp]) {
newChild = react_default.a.cloneElement(nextChild || currentChild, _defineProperty({}, showProp, true));
} else {
newChild = nextChild;
}
if (newChild) {
newChildren.push(newChild);
}
});
nextChildren.forEach(function (nextChild) {
if (!nextChild || !findChildInChildrenByKey(currentChildren, nextChild.key)) {
newChildren.push(nextChild);
}
});
} else {
newChildren = mergeChildren(currentChildren, nextChildren);
}
// need render to avoid update
this.setState({
children: newChildren
});
nextChildren.forEach(function (child) {
var key = child && child.key;
if (child && currentlyAnimatingKeys[key]) {
return;
}
var hasPrev = child && findChildInChildrenByKey(currentChildren, key);
if (showProp) {
var showInNext = child.props[showProp];
if (hasPrev) {
var showInNow = findShownChildInChildrenByKey(currentChildren, key, showProp);
if (!showInNow && showInNext) {
_this3.keysToEnter.push(key);
}
} else if (showInNext) {
_this3.keysToEnter.push(key);
}
} else if (!hasPrev) {
_this3.keysToEnter.push(key);
}
});
currentChildren.forEach(function (child) {
var key = child && child.key;
if (child && currentlyAnimatingKeys[key]) {
return;
}
var hasNext = child && findChildInChildrenByKey(nextChildren, key);
if (showProp) {
var showInNow = child.props[showProp];
if (hasNext) {
var showInNext = findShownChildInChildrenByKey(nextChildren, key, showProp);
if (!showInNext && showInNow) {
_this3.keysToLeave.push(key);
}
} else if (showInNow) {
_this3.keysToLeave.push(key);
}
} else if (!hasNext) {
_this3.keysToLeave.push(key);
}
});
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate() {
var keysToEnter = this.keysToEnter;
this.keysToEnter = [];
keysToEnter.forEach(this.performEnter);
var keysToLeave = this.keysToLeave;
this.keysToLeave = [];
keysToLeave.forEach(this.performLeave);
}
}, {
key: 'isValidChildByKey',
value: function isValidChildByKey(currentChildren, key) {
var showProp = this.props.showProp;
if (showProp) {
return findShownChildInChildrenByKey(currentChildren, key, showProp);
}
return findChildInChildrenByKey(currentChildren, key);
}
}, {
key: 'stop',
value: function stop(key) {
delete this.currentlyAnimatingKeys[key];
var component = this.childrenRefs[key];
if (component) {
component.stop();
}
}
}, {
key: 'render',
value: function render() {
var _this4 = this;
var props = this.props;
this.nextProps = props;
var stateChildren = this.state.children;
var children = null;
if (stateChildren) {
children = stateChildren.map(function (child) {
if (child === null || child === undefined) {
return child;
}
if (!child.key) {
throw new Error('must set key for <rc-animate> children');
}
return react_default.a.createElement(
es_AnimateChild,
{
key: child.key,
ref: function ref(node) {
_this4.childrenRefs[child.key] = node;
},
animation: props.animation,
transitionName: props.transitionName,
transitionEnter: props.transitionEnter,
transitionAppear: props.transitionAppear,
transitionLeave: props.transitionLeave
},
child
);
});
}
var Component = props.component;
if (Component) {
var passedProps = props;
if (typeof Component === 'string') {
passedProps = _extends({
className: props.className,
style: props.style
}, props.componentProps);
}
return react_default.a.createElement(
Component,
passedProps,
children
);
}
return children[0] || null;
}
}]);
return Animate;
}(react_default.a.Component);
Animate_Animate.isAnimate = true;
Animate_Animate.defaultProps = {
animation: {},
component: 'span',
componentProps: {},
transitionEnter: true,
transitionLeave: true,
transitionAppear: false,
onEnd: noop,
onEnter: noop,
onLeave: noop,
onAppear: noop
};
var Animate_initialiseProps = function _initialiseProps() {
var _this5 = this;
this.performEnter = function (key) {
// may already remove by exclusive
if (_this5.childrenRefs[key]) {
_this5.currentlyAnimatingKeys[key] = true;
_this5.childrenRefs[key].componentWillEnter(_this5.handleDoneAdding.bind(_this5, key, 'enter'));
}
};
this.performAppear = function (key) {
if (_this5.childrenRefs[key]) {
_this5.currentlyAnimatingKeys[key] = true;
_this5.childrenRefs[key].componentWillAppear(_this5.handleDoneAdding.bind(_this5, key, 'appear'));
}
};
this.handleDoneAdding = function (key, type) {
var props = _this5.props;
delete _this5.currentlyAnimatingKeys[key];
// if update on exclusive mode, skip check
if (props.exclusive && props !== _this5.nextProps) {
return;
}
var currentChildren = toArrayChildren(getChildrenFromProps(props));
if (!_this5.isValidChildByKey(currentChildren, key)) {
// exclusive will not need this
_this5.performLeave(key);
} else if (type === 'appear') {
if (animate.allowAppearCallback(props)) {
props.onAppear(key);
props.onEnd(key, true);
}
} else if (animate.allowEnterCallback(props)) {
props.onEnter(key);
props.onEnd(key, true);
}
};
this.performLeave = function (key) {
// may already remove by exclusive
if (_this5.childrenRefs[key]) {
_this5.currentlyAnimatingKeys[key] = true;
_this5.childrenRefs[key].componentWillLeave(_this5.handleDoneLeaving.bind(_this5, key));
}
};
this.handleDoneLeaving = function (key) {
var props = _this5.props;
delete _this5.currentlyAnimatingKeys[key];
// if update on exclusive mode, skip check
if (props.exclusive && props !== _this5.nextProps) {
return;
}
var currentChildren = toArrayChildren(getChildrenFromProps(props));
// in case state change is too fast
if (_this5.isValidChildByKey(currentChildren, key)) {
_this5.performEnter(key);
} else {
var end = function end() {
if (animate.allowLeaveCallback(props)) {
props.onLeave(key);
props.onEnd(key, false);
}
};
if (!isSameChildren(_this5.state.children, currentChildren, props.showProp)) {
_this5.setState({
children: currentChildren
}, end);
} else {
end();
}
}
};
};
/* harmony default export */ var es_Animate = __webpack_exports__["a"] = (es_unsafeLifecyclesPolyfill(Animate_Animate));
/***/ }),
/***/ "V7ic":
/*!*****************************************************************!*\
!*** ./node_modules/@ant-design/icons/lib/icons/FileTwoTone.js ***!
\*****************************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireWildcard = __webpack_require__(/*! @babel/runtime/helpers/interopRequireWildcard */ "284h");
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "TqRt");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/objectSpread2 */ "3tO9"));
var React = _interopRequireWildcard(__webpack_require__(/*! react */ "q1tI"));
var _FileTwoTone = _interopRequireDefault(__webpack_require__(/*! @ant-design/icons-svg/lib/asn/FileTwoTone */ "digP"));
var _AntdIcon = _interopRequireDefault(__webpack_require__(/*! ../components/AntdIcon */ "KQxl"));
// GENERATE BY ./scripts/generate.ts
// DON NOT EDIT IT MANUALLY
var FileTwoTone = function FileTwoTone(props, ref) {
return /*#__PURE__*/React.createElement(_AntdIcon.default, (0, _objectSpread2.default)((0, _objectSpread2.default)({}, props), {}, {
ref: ref,
icon: _FileTwoTone.default
}));
};
FileTwoTone.displayName = 'FileTwoTone';
var _default = /*#__PURE__*/React.forwardRef(FileTwoTone);
exports.default = _default;
/***/ }),
/***/ "Vl3Y":
/*!*********************************************************!*\
!*** ./node_modules/antd/es/form/index.js + 13 modules ***!
\*********************************************************/
/*! exports provided: default */
/*! exports used: default */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/CheckCircleFilled.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/CloseCircleFilled.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/ExclamationCircleFilled.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/LoadingOutlined.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/defineProperty.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/extends.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/slicedToArray.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/toConsumableArray.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/typeof.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/_util/devWarning.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/_util/hooks/useForceUpdate.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/_util/reactNode.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/_util/type.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/config-provider/SizeContext.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/config-provider/context.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/grid/col.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/grid/row.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/locale-provider/LocaleReceiver.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/locale/default.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/classnames/index.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/lodash/isEqual.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/omit.js/es/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-field-form/es/FieldContext.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-field-form/es/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-motion/es/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/hooks/useMemo.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/ref.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/react/index.js (<- Module is not an ECMAScript module) */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/extends.js
var helpers_extends = __webpack_require__("pVnL");
var extends_default = /*#__PURE__*/__webpack_require__.n(helpers_extends);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/slicedToArray.js
var slicedToArray = __webpack_require__("J4zp");
var slicedToArray_default = /*#__PURE__*/__webpack_require__.n(slicedToArray);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/defineProperty.js
var defineProperty = __webpack_require__("lSNA");
var defineProperty_default = /*#__PURE__*/__webpack_require__.n(defineProperty);
// EXTERNAL MODULE: ./node_modules/react/index.js
var react = __webpack_require__("q1tI");
// 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-field-form/es/index.js + 13 modules
var es = __webpack_require__("85Yc");
// EXTERNAL MODULE: ./node_modules/antd/es/config-provider/context.js + 1 modules
var config_provider_context = __webpack_require__("H84U");
// EXTERNAL MODULE: ./node_modules/omit.js/es/index.js
var omit_js_es = __webpack_require__("BGR+");
// CONCATENATED MODULE: ./node_modules/antd/es/form/context.js
var FormContext = /*#__PURE__*/react["createContext"]({
labelAlign: 'right',
vertical: false,
itemRef: function itemRef() {}
});
var FormItemContext = /*#__PURE__*/react["createContext"]({
updateItemErrors: function updateItemErrors() {}
});
var context_FormProvider = function FormProvider(props) {
var providerProps = Object(omit_js_es["a" /* default */])(props, ['prefixCls']);
return /*#__PURE__*/react["createElement"](es["b" /* FormProvider */], providerProps);
};
// CONCATENATED MODULE: ./node_modules/compute-scroll-into-view/dist/index.module.js
function t(t){return"object"==typeof t&&null!=t&&1===t.nodeType}function e(t,e){return(!e||"hidden"!==t)&&"visible"!==t&&"clip"!==t}function n(t,n){if(t.clientHeight<t.scrollHeight||t.clientWidth<t.scrollWidth){var r=getComputedStyle(t,null);return e(r.overflowY,n)||e(r.overflowX,n)||function(t){var e=function(t){if(!t.ownerDocument||!t.ownerDocument.defaultView)return null;try{return t.ownerDocument.defaultView.frameElement}catch(t){return null}}(t);return!!e&&(e.clientHeight<t.scrollHeight||e.clientWidth<t.scrollWidth)}(t)}return!1}function r(t,e,n,r,i,o,l,d){return o<t&&l>e||o>t&&l<e?0:o<=t&&d<=n||l>=e&&d>=n?o-t-r:l>e&&d<n||o<t&&d>n?l-e+i:0}/* harmony default export */ var index_module = (function(e,i){var o=window,l=i.scrollMode,d=i.block,u=i.inline,h=i.boundary,a=i.skipOverflowHiddenElements,c="function"==typeof h?h:function(t){return t!==h};if(!t(e))throw new TypeError("Invalid target");for(var f=document.scrollingElement||document.documentElement,s=[],p=e;t(p)&&c(p);){if((p=p.parentElement)===f){s.push(p);break}null!=p&&p===document.body&&n(p)&&!n(document.documentElement)||null!=p&&n(p,a)&&s.push(p)}for(var m=o.visualViewport?o.visualViewport.width:innerWidth,g=o.visualViewport?o.visualViewport.height:innerHeight,w=window.scrollX||pageXOffset,v=window.scrollY||pageYOffset,W=e.getBoundingClientRect(),b=W.height,H=W.width,y=W.top,E=W.right,M=W.bottom,V=W.left,x="start"===d||"nearest"===d?y:"end"===d?M:y+b/2,I="center"===u?V+H/2:"end"===u?E:V,C=[],T=0;T<s.length;T++){var k=s[T],B=k.getBoundingClientRect(),D=B.height,O=B.width,R=B.top,X=B.right,Y=B.bottom,L=B.left;if("if-needed"===l&&y>=0&&V>=0&&M<=g&&E<=m&&y>=R&&M<=Y&&V>=L&&E<=X)return C;var S=getComputedStyle(k),j=parseInt(S.borderLeftWidth,10),q=parseInt(S.borderTopWidth,10),z=parseInt(S.borderRightWidth,10),A=parseInt(S.borderBottomWidth,10),F=0,G=0,J="offsetWidth"in k?k.offsetWidth-k.clientWidth-j-z:0,K="offsetHeight"in k?k.offsetHeight-k.clientHeight-q-A:0;if(f===k)F="start"===d?x:"end"===d?x-g:"nearest"===d?r(v,v+g,g,q,A,v+x,v+x+b,b):x-g/2,G="start"===u?I:"center"===u?I-m/2:"end"===u?I-m:r(w,w+m,m,j,z,w+I,w+I+H,H),F=Math.max(0,F+v),G=Math.max(0,G+w);else{F="start"===d?x-R-q:"end"===d?x-Y+A+K:"nearest"===d?r(R,Y,D,q,A+K,x,x+b,b):x-(R+D/2)+K/2,G="start"===u?I-L-j:"center"===u?I-(L+O/2)+J/2:"end"===u?I-X+z+J:r(L,X,O,j,z+J,I,I+H,H);var N=k.scrollLeft,P=k.scrollTop;x+=P-(F=Math.max(0,Math.min(P+F,k.scrollHeight-D+K))),I+=N-(G=Math.max(0,Math.min(N+G,k.scrollWidth-O+J)))}C.push({el:k,top:F,left:G})}return C});
//# sourceMappingURL=index.module.js.map
// CONCATENATED MODULE: ./node_modules/scroll-into-view-if-needed/es/index.js
function isOptionsObject(options) {
return options === Object(options) && Object.keys(options).length !== 0;
}
function defaultBehavior(actions, behavior) {
if (behavior === void 0) {
behavior = 'auto';
}
var canSmoothScroll = ('scrollBehavior' in document.body.style);
actions.forEach(function (_ref) {
var el = _ref.el,
top = _ref.top,
left = _ref.left;
if (el.scroll && canSmoothScroll) {
el.scroll({
top: top,
left: left,
behavior: behavior
});
} else {
el.scrollTop = top;
el.scrollLeft = left;
}
});
}
function getOptions(options) {
if (options === false) {
return {
block: 'end',
inline: 'nearest'
};
}
if (isOptionsObject(options)) {
return options;
}
return {
block: 'start',
inline: 'nearest'
};
}
function scrollIntoView(target, options) {
var targetIsDetached = !target.ownerDocument.documentElement.contains(target);
if (isOptionsObject(options) && typeof options.behavior === 'function') {
return options.behavior(targetIsDetached ? [] : index_module(target, options));
}
if (targetIsDetached) {
return;
}
var computeOptions = getOptions(options);
return defaultBehavior(index_module(target, computeOptions), computeOptions.behavior);
}
/* harmony default export */ var scroll_into_view_if_needed_es = (scrollIntoView);
// CONCATENATED MODULE: ./node_modules/antd/es/form/util.js
function toArray(candidate) {
if (candidate === undefined || candidate === false) return [];
return Array.isArray(candidate) ? candidate : [candidate];
}
function getFieldId(namePath, formName) {
if (!namePath.length) return undefined;
var mergedId = namePath.join('_');
return formName ? "".concat(formName, "_").concat(mergedId) : mergedId;
}
// CONCATENATED MODULE: ./node_modules/antd/es/form/hooks/useForm.js
function toNamePathStr(name) {
var namePath = toArray(name);
return namePath.join('_');
}
function useForm(form) {
var _useRcForm = Object(es["e" /* useForm */])(),
_useRcForm2 = slicedToArray_default()(_useRcForm, 1),
rcForm = _useRcForm2[0];
var itemsRef = Object(react["useRef"])({});
var wrapForm = Object(react["useMemo"])(function () {
return form || extends_default()(extends_default()({}, rcForm), {
__INTERNAL__: {
itemRef: function itemRef(name) {
return function (node) {
var namePathStr = toNamePathStr(name);
if (node) {
itemsRef.current[namePathStr] = node;
} else {
delete itemsRef.current[namePathStr];
}
};
}
},
scrollToField: function scrollToField(name) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var namePath = toArray(name);
var fieldId = getFieldId(namePath, wrapForm.__INTERNAL__.name);
var node = fieldId ? document.getElementById(fieldId) : null;
if (node) {
scroll_into_view_if_needed_es(node, extends_default()({
scrollMode: 'if-needed',
block: 'nearest'
}, options));
}
},
getFieldInstance: function getFieldInstance(name) {
var namePathStr = toNamePathStr(name);
return itemsRef.current[namePathStr];
}
});
}, [form, rcForm]);
return [wrapForm];
}
// EXTERNAL MODULE: ./node_modules/antd/es/config-provider/SizeContext.js
var SizeContext = __webpack_require__("3Nzz");
// CONCATENATED MODULE: ./node_modules/antd/es/form/Form.js
var __rest = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
var Form_InternalForm = function InternalForm(props, ref) {
var _classNames;
var contextSize = react["useContext"](SizeContext["b" /* default */]);
var _React$useContext = react["useContext"](config_provider_context["b" /* ConfigContext */]),
getPrefixCls = _React$useContext.getPrefixCls,
direction = _React$useContext.direction;
var name = props.name;
var customizePrefixCls = props.prefixCls,
_props$className = props.className,
className = _props$className === void 0 ? '' : _props$className,
_props$size = props.size,
size = _props$size === void 0 ? contextSize : _props$size,
form = props.form,
colon = props.colon,
labelAlign = props.labelAlign,
labelCol = props.labelCol,
wrapperCol = props.wrapperCol,
hideRequiredMark = props.hideRequiredMark,
_props$layout = props.layout,
layout = _props$layout === void 0 ? 'horizontal' : _props$layout,
scrollToFirstError = props.scrollToFirstError,
requiredMark = props.requiredMark,
onFinishFailed = props.onFinishFailed,
restFormProps = __rest(props, ["prefixCls", "className", "size", "form", "colon", "labelAlign", "labelCol", "wrapperCol", "hideRequiredMark", "layout", "scrollToFirstError", "requiredMark", "onFinishFailed"]);
var mergedRequiredMark = Object(react["useMemo"])(function () {
if (requiredMark !== undefined) {
return requiredMark;
}
if (hideRequiredMark) {
return false;
}
return true;
}, [hideRequiredMark, requiredMark]);
var prefixCls = getPrefixCls('form', customizePrefixCls);
var formClassName = classnames_default()(prefixCls, (_classNames = {}, defineProperty_default()(_classNames, "".concat(prefixCls, "-").concat(layout), true), defineProperty_default()(_classNames, "".concat(prefixCls, "-hide-required-mark"), mergedRequiredMark === false), defineProperty_default()(_classNames, "".concat(prefixCls, "-rtl"), direction === 'rtl'), defineProperty_default()(_classNames, "".concat(prefixCls, "-").concat(size), size), _classNames), className);
var _useForm = useForm(form),
_useForm2 = slicedToArray_default()(_useForm, 1),
wrapForm = _useForm2[0];
var __INTERNAL__ = wrapForm.__INTERNAL__;
__INTERNAL__.name = name;
var formContextValue = Object(react["useMemo"])(function () {
return {
name: name,
labelAlign: labelAlign,
labelCol: labelCol,
wrapperCol: wrapperCol,
vertical: layout === 'vertical',
colon: colon,
requiredMark: mergedRequiredMark,
itemRef: __INTERNAL__.itemRef
};
}, [name, labelAlign, labelCol, wrapperCol, layout, colon, mergedRequiredMark]);
react["useImperativeHandle"](ref, function () {
return wrapForm;
});
var onInternalFinishFailed = function onInternalFinishFailed(errorInfo) {
if (onFinishFailed) {
onFinishFailed(errorInfo);
}
if (scrollToFirstError && errorInfo.errorFields.length) {
wrapForm.scrollToField(errorInfo.errorFields[0].name);
}
};
return /*#__PURE__*/react["createElement"](SizeContext["a" /* SizeContextProvider */], {
size: size
}, /*#__PURE__*/react["createElement"](FormContext.Provider, {
value: formContextValue
}, /*#__PURE__*/react["createElement"](es["d" /* default */], extends_default()({
id: name
}, restFormProps, {
onFinishFailed: onInternalFinishFailed,
form: wrapForm,
className: formClassName
}))));
};
var Form = /*#__PURE__*/react["forwardRef"](Form_InternalForm);
/* harmony default export */ var form_Form = (Form);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/typeof.js
var helpers_typeof = __webpack_require__("cDf5");
var typeof_default = /*#__PURE__*/__webpack_require__.n(helpers_typeof);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/toConsumableArray.js
var toConsumableArray = __webpack_require__("RIqP");
var toConsumableArray_default = /*#__PURE__*/__webpack_require__.n(toConsumableArray);
// EXTERNAL MODULE: ./node_modules/lodash/isEqual.js
var isEqual = __webpack_require__("Y+p1");
var isEqual_default = /*#__PURE__*/__webpack_require__.n(isEqual);
// EXTERNAL MODULE: ./node_modules/rc-field-form/es/FieldContext.js
var FieldContext = __webpack_require__("KW7l");
// EXTERNAL MODULE: ./node_modules/rc-util/es/ref.js
var es_ref = __webpack_require__("c+Xe");
// EXTERNAL MODULE: ./node_modules/antd/es/grid/row.js
var row = __webpack_require__("qrJ5");
// EXTERNAL MODULE: ./node_modules/antd/es/_util/type.js
var type = __webpack_require__("CWQg");
// EXTERNAL MODULE: ./node_modules/antd/es/_util/devWarning.js
var devWarning = __webpack_require__("uaoM");
// EXTERNAL MODULE: ./node_modules/antd/es/grid/col.js
var col = __webpack_require__("/kpp");
// EXTERNAL MODULE: ./node_modules/antd/es/locale-provider/LocaleReceiver.js + 1 modules
var LocaleReceiver = __webpack_require__("YMnH");
// EXTERNAL MODULE: ./node_modules/antd/es/locale/default.js + 4 modules
var locale_default = __webpack_require__("ZvpZ");
// CONCATENATED MODULE: ./node_modules/antd/es/form/FormItemLabel.js
var FormItemLabel_FormItemLabel = function FormItemLabel(_ref) {
var prefixCls = _ref.prefixCls,
label = _ref.label,
htmlFor = _ref.htmlFor,
labelCol = _ref.labelCol,
labelAlign = _ref.labelAlign,
colon = _ref.colon,
required = _ref.required,
requiredMark = _ref.requiredMark;
var _useLocaleReceiver = Object(LocaleReceiver["b" /* useLocaleReceiver */])('Form'),
_useLocaleReceiver2 = slicedToArray_default()(_useLocaleReceiver, 1),
formLocale = _useLocaleReceiver2[0];
if (!label) return null;
return /*#__PURE__*/react["createElement"](FormContext.Consumer, {
key: "label"
}, function (_ref2) {
var _classNames;
var vertical = _ref2.vertical,
contextLabelAlign = _ref2.labelAlign,
contextLabelCol = _ref2.labelCol,
contextColon = _ref2.colon;
var _a;
var mergedLabelCol = labelCol || contextLabelCol || {};
var mergedLabelAlign = labelAlign || contextLabelAlign;
var labelClsBasic = "".concat(prefixCls, "-item-label");
var labelColClassName = classnames_default()(labelClsBasic, mergedLabelAlign === 'left' && "".concat(labelClsBasic, "-left"), mergedLabelCol.className);
var labelChildren = label; // Keep label is original where there should have no colon
var computedColon = colon === true || contextColon !== false && colon !== false;
var haveColon = computedColon && !vertical; // Remove duplicated user input colon
if (haveColon && typeof label === 'string' && label.trim() !== '') {
labelChildren = label.replace(/[:|]\s*$/, '');
} // Add required mark if optional
if (requiredMark === 'optional' && !required) {
labelChildren = /*#__PURE__*/react["createElement"](react["Fragment"], null, labelChildren, /*#__PURE__*/react["createElement"]("span", {
className: "".concat(prefixCls, "-item-optional")
}, (formLocale === null || formLocale === void 0 ? void 0 : formLocale.optional) || ((_a = locale_default["a" /* default */].Form) === null || _a === void 0 ? void 0 : _a.optional)));
}
var labelClassName = classnames_default()((_classNames = {}, defineProperty_default()(_classNames, "".concat(prefixCls, "-item-required"), required), defineProperty_default()(_classNames, "".concat(prefixCls, "-item-required-mark-optional"), requiredMark === 'optional'), defineProperty_default()(_classNames, "".concat(prefixCls, "-item-no-colon"), !computedColon), _classNames));
return /*#__PURE__*/react["createElement"](col["a" /* default */], extends_default()({}, mergedLabelCol, {
className: labelColClassName
}), /*#__PURE__*/react["createElement"]("label", {
htmlFor: htmlFor,
className: labelClassName,
title: typeof label === 'string' ? label : ''
}, labelChildren));
});
};
/* harmony default export */ var form_FormItemLabel = (FormItemLabel_FormItemLabel);
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/LoadingOutlined.js
var LoadingOutlined = __webpack_require__("gZBC");
var LoadingOutlined_default = /*#__PURE__*/__webpack_require__.n(LoadingOutlined);
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/CloseCircleFilled.js
var CloseCircleFilled = __webpack_require__("kbBi");
var CloseCircleFilled_default = /*#__PURE__*/__webpack_require__.n(CloseCircleFilled);
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/CheckCircleFilled.js
var CheckCircleFilled = __webpack_require__("J84W");
var CheckCircleFilled_default = /*#__PURE__*/__webpack_require__.n(CheckCircleFilled);
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/ExclamationCircleFilled.js
var ExclamationCircleFilled = __webpack_require__("sKbD");
var ExclamationCircleFilled_default = /*#__PURE__*/__webpack_require__.n(ExclamationCircleFilled);
// EXTERNAL MODULE: ./node_modules/rc-util/es/hooks/useMemo.js
var useMemo = __webpack_require__("YrtM");
// EXTERNAL MODULE: ./node_modules/rc-motion/es/index.js + 5 modules
var rc_motion_es = __webpack_require__("8XRh");
// EXTERNAL MODULE: ./node_modules/antd/es/_util/hooks/useForceUpdate.js
var useForceUpdate = __webpack_require__("hkKa");
// CONCATENATED MODULE: ./node_modules/antd/es/form/hooks/useCacheErrors.js
/**
* Always debounce error to avoid [error -> null -> error] blink
*/
function useCacheErrors(errors, changeTrigger, directly) {
var cacheRef = react["useRef"]({
errors: errors,
visible: !!errors.length
});
var forceUpdate = Object(useForceUpdate["a" /* default */])();
var update = function update() {
var prevVisible = cacheRef.current.visible;
var newVisible = !!errors.length;
var prevErrors = cacheRef.current.errors;
cacheRef.current.errors = errors;
cacheRef.current.visible = newVisible;
if (prevVisible !== newVisible) {
changeTrigger(newVisible);
} else if (prevErrors.length !== errors.length || prevErrors.some(function (prevErr, index) {
return prevErr !== errors[index];
})) {
forceUpdate();
}
};
react["useEffect"](function () {
if (!directly) {
var timeout = setTimeout(update, 10);
return function () {
return clearTimeout(timeout);
};
}
}, [errors]);
if (directly) {
update();
}
return [cacheRef.current.visible, cacheRef.current.errors];
}
// CONCATENATED MODULE: ./node_modules/antd/es/form/FormItemInput.js
var iconMap = {
success: CheckCircleFilled_default.a,
warning: ExclamationCircleFilled_default.a,
error: CloseCircleFilled_default.a,
validating: LoadingOutlined_default.a
};
var FormItemInput_FormItemInput = function FormItemInput(_ref) {
var prefixCls = _ref.prefixCls,
wrapperCol = _ref.wrapperCol,
children = _ref.children,
help = _ref.help,
errors = _ref.errors,
onDomErrorVisibleChange = _ref.onDomErrorVisibleChange,
hasFeedback = _ref.hasFeedback,
validateStatus = _ref.validateStatus,
extra = _ref.extra;
var forceUpdate = Object(useForceUpdate["a" /* default */])();
var baseClassName = "".concat(prefixCls, "-item");
var formContext = react["useContext"](FormContext);
var mergedWrapperCol = wrapperCol || formContext.wrapperCol || {};
var className = classnames_default()("".concat(baseClassName, "-control"), mergedWrapperCol.className);
var _useCacheErrors = useCacheErrors(errors, function (changedVisible) {
if (changedVisible) {
/**
* We trigger in sync to avoid dom shaking but this get warning in react 16.13.
* So use Promise to keep in micro async to handle this.
* https://github.com/ant-design/ant-design/issues/21698#issuecomment-593743485
*/
Promise.resolve().then(function () {
onDomErrorVisibleChange(true);
});
}
forceUpdate();
}, !!help),
_useCacheErrors2 = slicedToArray_default()(_useCacheErrors, 2),
visible = _useCacheErrors2[0],
cacheErrors = _useCacheErrors2[1];
react["useEffect"](function () {
return function () {
onDomErrorVisibleChange(false);
};
}, []);
var memoErrors = Object(useMemo["a" /* default */])(function () {
return cacheErrors;
}, visible, function (_, nextVisible) {
return nextVisible;
}); // Should provides additional icon if `hasFeedback`
var IconNode = validateStatus && iconMap[validateStatus];
var icon = hasFeedback && IconNode ? /*#__PURE__*/react["createElement"]("span", {
className: "".concat(baseClassName, "-children-icon")
}, /*#__PURE__*/react["createElement"](IconNode, null)) : null; // Pass to sub FormItem should not with col info
var subFormContext = extends_default()({}, formContext);
delete subFormContext.labelCol;
delete subFormContext.wrapperCol;
return /*#__PURE__*/react["createElement"](FormContext.Provider, {
value: subFormContext
}, /*#__PURE__*/react["createElement"](col["a" /* default */], extends_default()({}, mergedWrapperCol, {
className: className
}), /*#__PURE__*/react["createElement"]("div", {
className: "".concat(baseClassName, "-control-input")
}, /*#__PURE__*/react["createElement"]("div", {
className: "".concat(baseClassName, "-control-input-content")
}, children), icon), /*#__PURE__*/react["createElement"](rc_motion_es["b" /* default */], {
motionDeadline: 500,
visible: visible,
motionName: "show-help",
onLeaveEnd: function onLeaveEnd() {
onDomErrorVisibleChange(false);
},
motionAppear: true,
removeOnLeave: true
}, function (_ref2) {
var motionClassName = _ref2.className;
return /*#__PURE__*/react["createElement"]("div", {
className: classnames_default()("".concat(baseClassName, "-explain"), motionClassName),
key: "help"
}, memoErrors.map(function (error, index) {
return (
/*#__PURE__*/
// eslint-disable-next-line react/no-array-index-key
react["createElement"]("div", {
key: index,
role: "alert"
}, error)
);
}));
}), extra && /*#__PURE__*/react["createElement"]("div", {
className: "".concat(baseClassName, "-extra")
}, extra)));
};
/* harmony default export */ var form_FormItemInput = (FormItemInput_FormItemInput);
// EXTERNAL MODULE: ./node_modules/antd/es/_util/reactNode.js
var reactNode = __webpack_require__("0n0R");
// EXTERNAL MODULE: ./node_modules/raf/index.js
var raf = __webpack_require__("xEkU");
var raf_default = /*#__PURE__*/__webpack_require__.n(raf);
// CONCATENATED MODULE: ./node_modules/antd/es/form/hooks/useFrameState.js
function useFrameState(defaultValue) {
var _React$useState = react["useState"](defaultValue),
_React$useState2 = slicedToArray_default()(_React$useState, 2),
value = _React$useState2[0],
setValue = _React$useState2[1];
var frameRef = Object(react["useRef"])(null);
var batchRef = Object(react["useRef"])([]);
var destroyRef = Object(react["useRef"])(false);
react["useEffect"](function () {
return function () {
destroyRef.current = true;
raf_default.a.cancel(frameRef.current);
};
}, []);
function setFrameValue(updater) {
if (destroyRef.current) {
return;
}
if (frameRef.current === null) {
batchRef.current = [];
frameRef.current = raf_default()(function () {
frameRef.current = null;
setValue(function (prevValue) {
var current = prevValue;
batchRef.current.forEach(function (func) {
current = func(current);
});
return current;
});
});
}
batchRef.current.push(updater);
}
return [value, setFrameValue];
}
// CONCATENATED MODULE: ./node_modules/antd/es/form/hooks/useItemRef.js
function useItemRef() {
var _React$useContext = react["useContext"](FormContext),
itemRef = _React$useContext.itemRef;
var cacheRef = react["useRef"]({});
function getRef(name, children) {
var childrenRef = children && typeof_default()(children) === 'object' && children.ref;
var nameStr = name.join('_');
if (cacheRef.current.name !== nameStr || cacheRef.current.originRef !== childrenRef) {
cacheRef.current.name = nameStr;
cacheRef.current.originRef = childrenRef;
cacheRef.current.ref = Object(es_ref["a" /* composeRef */])(itemRef(name), childrenRef);
}
return cacheRef.current.ref;
}
return getRef;
}
// CONCATENATED MODULE: ./node_modules/antd/es/form/FormItem.js
var FormItem_rest = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
var ValidateStatuses = Object(type["a" /* tuple */])('success', 'warning', 'error', 'validating', '');
var MemoInput = /*#__PURE__*/react["memo"](function (_ref) {
var children = _ref.children;
return children;
}, function (prev, next) {
return prev.value === next.value && prev.update === next.update;
});
function hasValidName(name) {
if (name === null) {
Object(devWarning["a" /* default */])(false, 'Form.Item', '`null` is passed as `name` property');
}
return !(name === undefined || name === null);
}
function FormItem(props) {
var name = props.name,
fieldKey = props.fieldKey,
noStyle = props.noStyle,
dependencies = props.dependencies,
customizePrefixCls = props.prefixCls,
style = props.style,
className = props.className,
shouldUpdate = props.shouldUpdate,
hasFeedback = props.hasFeedback,
help = props.help,
rules = props.rules,
validateStatus = props.validateStatus,
children = props.children,
required = props.required,
label = props.label,
_props$trigger = props.trigger,
trigger = _props$trigger === void 0 ? 'onChange' : _props$trigger,
validateTrigger = props.validateTrigger,
hidden = props.hidden,
restProps = FormItem_rest(props, ["name", "fieldKey", "noStyle", "dependencies", "prefixCls", "style", "className", "shouldUpdate", "hasFeedback", "help", "rules", "validateStatus", "children", "required", "label", "trigger", "validateTrigger", "hidden"]);
var destroyRef = react["useRef"](false);
var _React$useContext = react["useContext"](config_provider_context["b" /* ConfigContext */]),
getPrefixCls = _React$useContext.getPrefixCls;
var _React$useContext2 = react["useContext"](FormContext),
formName = _React$useContext2.name,
requiredMark = _React$useContext2.requiredMark;
var _React$useContext3 = react["useContext"](FormItemContext),
updateItemErrors = _React$useContext3.updateItemErrors;
var _React$useState = react["useState"](!!help),
_React$useState2 = slicedToArray_default()(_React$useState, 2),
domErrorVisible = _React$useState2[0],
innerSetDomErrorVisible = _React$useState2[1];
var prevValidateStatusRef = react["useRef"](validateStatus);
var _useFrameState = useFrameState({}),
_useFrameState2 = slicedToArray_default()(_useFrameState, 2),
inlineErrors = _useFrameState2[0],
setInlineErrors = _useFrameState2[1];
var _React$useContext4 = react["useContext"](FieldContext["b" /* default */]),
contextValidateTrigger = _React$useContext4.validateTrigger;
var mergedValidateTrigger = validateTrigger !== undefined ? validateTrigger : contextValidateTrigger;
function setDomErrorVisible(visible) {
if (!destroyRef.current) {
innerSetDomErrorVisible(visible);
}
}
var hasName = hasValidName(name); // Cache Field NamePath
var nameRef = react["useRef"]([]); // Should clean up if Field removed
react["useEffect"](function () {
return function () {
destroyRef.current = true;
updateItemErrors(nameRef.current.join('__SPLIT__'), []);
};
}, []);
var prefixCls = getPrefixCls('form', customizePrefixCls); // ======================== Errors ========================
// Collect noStyle Field error to the top FormItem
var updateChildItemErrors = noStyle ? updateItemErrors : function (subName, subErrors) {
setInlineErrors(function () {
var prevInlineErrors = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
if (!isEqual_default()(prevInlineErrors[subName], subErrors)) {
return extends_default()(extends_default()({}, prevInlineErrors), defineProperty_default()({}, subName, subErrors));
}
return prevInlineErrors;
});
}; // ===================== Children Ref =====================
var getItemRef = useItemRef();
function renderLayout(baseChildren, fieldId, meta, isRequired) {
var _itemClassName;
var _a;
if (noStyle && !hidden) {
return baseChildren;
} // ======================== Errors ========================
// >>> collect sub errors
var subErrorList = [];
Object.keys(inlineErrors).forEach(function (subName) {
subErrorList = [].concat(toConsumableArray_default()(subErrorList), toConsumableArray_default()(inlineErrors[subName] || []));
}); // >>> merged errors
var mergedErrors;
if (help !== undefined && help !== null) {
mergedErrors = toArray(help);
} else {
mergedErrors = meta ? meta.errors : [];
mergedErrors = [].concat(toConsumableArray_default()(mergedErrors), toConsumableArray_default()(subErrorList));
} // ======================== Status ========================
var mergedValidateStatus = '';
if (validateStatus !== undefined) {
mergedValidateStatus = validateStatus;
} else if (meta === null || meta === void 0 ? void 0 : meta.validating) {
mergedValidateStatus = 'validating';
} else if (((_a = meta === null || meta === void 0 ? void 0 : meta.errors) === null || _a === void 0 ? void 0 : _a.length) || subErrorList.length) {
mergedValidateStatus = 'error';
} else if (meta === null || meta === void 0 ? void 0 : meta.touched) {
mergedValidateStatus = 'success';
}
if (domErrorVisible && help) {
prevValidateStatusRef.current = mergedValidateStatus;
}
var itemClassName = (_itemClassName = {}, defineProperty_default()(_itemClassName, "".concat(prefixCls, "-item"), true), defineProperty_default()(_itemClassName, "".concat(prefixCls, "-item-with-help"), domErrorVisible || help), defineProperty_default()(_itemClassName, "".concat(className), !!className), defineProperty_default()(_itemClassName, "".concat(prefixCls, "-item-has-feedback"), mergedValidateStatus && hasFeedback), defineProperty_default()(_itemClassName, "".concat(prefixCls, "-item-has-success"), mergedValidateStatus === 'success'), defineProperty_default()(_itemClassName, "".concat(prefixCls, "-item-has-warning"), mergedValidateStatus === 'warning'), defineProperty_default()(_itemClassName, "".concat(prefixCls, "-item-has-error"), mergedValidateStatus === 'error'), defineProperty_default()(_itemClassName, "".concat(prefixCls, "-item-has-error-leave"), !help && domErrorVisible && prevValidateStatusRef.current === 'error'), defineProperty_default()(_itemClassName, "".concat(prefixCls, "-item-is-validating"), mergedValidateStatus === 'validating'), defineProperty_default()(_itemClassName, "".concat(prefixCls, "-item-hidden"), hidden), _itemClassName); // ======================= Children =======================
return /*#__PURE__*/react["createElement"](row["a" /* default */], extends_default()({
className: classnames_default()(itemClassName),
style: style,
key: "row"
}, Object(omit_js_es["a" /* default */])(restProps, ['colon', 'extra', 'getValueFromEvent', 'getValueProps', 'hasFeedback', 'help', 'htmlFor', 'id', 'initialValue', 'isListField', 'label', 'labelAlign', 'labelCol', 'normalize', 'preserve', 'required', 'validateFirst', 'validateStatus', 'valuePropName', 'wrapperCol'])), /*#__PURE__*/react["createElement"](form_FormItemLabel, extends_default()({
htmlFor: fieldId,
required: isRequired,
requiredMark: requiredMark
}, props, {
prefixCls: prefixCls
})), /*#__PURE__*/react["createElement"](form_FormItemInput, extends_default()({}, props, meta, {
errors: mergedErrors,
prefixCls: prefixCls,
onDomErrorVisibleChange: setDomErrorVisible,
validateStatus: mergedValidateStatus
}), /*#__PURE__*/react["createElement"](FormItemContext.Provider, {
value: {
updateItemErrors: updateChildItemErrors
}
}, baseChildren)));
}
var isRenderProps = typeof children === 'function'; // Record for real component render
var updateRef = react["useRef"](0);
updateRef.current += 1;
if (!hasName && !isRenderProps && !dependencies) {
return renderLayout(children);
}
var variables = {};
if (typeof label === 'string') {
variables.label = label;
}
return /*#__PURE__*/react["createElement"](es["a" /* Field */], extends_default()({}, props, {
messageVariables: variables,
trigger: trigger,
validateTrigger: mergedValidateTrigger,
onReset: function onReset() {
setDomErrorVisible(false);
}
}), function (control, meta, context) {
var errors = meta.errors;
var mergedName = toArray(name).length && meta ? meta.name : [];
var fieldId = getFieldId(mergedName, formName);
if (noStyle) {
nameRef.current = toConsumableArray_default()(mergedName);
if (fieldKey) {
var fieldKeys = Array.isArray(fieldKey) ? fieldKey : [fieldKey];
nameRef.current = [].concat(toConsumableArray_default()(mergedName.slice(0, -1)), toConsumableArray_default()(fieldKeys));
}
updateItemErrors(nameRef.current.join('__SPLIT__'), errors);
}
var isRequired = required !== undefined ? required : !!(rules && rules.some(function (rule) {
if (rule && typeof_default()(rule) === 'object' && rule.required) {
return true;
}
if (typeof rule === 'function') {
var ruleEntity = rule(context);
return ruleEntity && ruleEntity.required;
}
return false;
})); // ======================= Children =======================
var mergedControl = extends_default()({}, control);
var childNode = null;
Object(devWarning["a" /* default */])(!(shouldUpdate && dependencies), 'Form.Item', "`shouldUpdate` and `dependencies` shouldn't be used together. See https://ant.design/components/form/#dependencies.");
if (Array.isArray(children) && hasName) {
Object(devWarning["a" /* default */])(false, 'Form.Item', '`children` is array of render props cannot have `name`.');
childNode = children;
} else if (isRenderProps && (!(shouldUpdate || dependencies) || hasName)) {
Object(devWarning["a" /* default */])(!!(shouldUpdate || dependencies), 'Form.Item', '`children` of render props only work with `shouldUpdate` or `dependencies`.');
Object(devWarning["a" /* default */])(!hasName, 'Form.Item', "Do not use `name` with `children` of render props since it's not a field.");
} else if (dependencies && !isRenderProps && !hasName) {
Object(devWarning["a" /* default */])(false, 'Form.Item', 'Must set `name` or use render props when `dependencies` is set.');
} else if (Object(reactNode["b" /* isValidElement */])(children)) {
Object(devWarning["a" /* default */])(children.props.defaultValue === undefined, 'Form.Item', '`defaultValue` will not work on controlled Field. You should use `initialValues` of Form instead.');
var childProps = extends_default()(extends_default()({}, children.props), mergedControl);
if (!childProps.id) {
childProps.id = fieldId;
}
if (Object(es_ref["c" /* supportRef */])(children)) {
childProps.ref = getItemRef(mergedName, children);
} // We should keep user origin event handler
var triggers = new Set([].concat(toConsumableArray_default()(toArray(trigger)), toConsumableArray_default()(toArray(mergedValidateTrigger))));
triggers.forEach(function (eventName) {
childProps[eventName] = function () {
var _a2, _c2;
var _a, _b, _c;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
(_a = mergedControl[eventName]) === null || _a === void 0 ? void 0 : (_a2 = _a).call.apply(_a2, [mergedControl].concat(args));
(_c = (_b = children.props)[eventName]) === null || _c === void 0 ? void 0 : (_c2 = _c).call.apply(_c2, [_b].concat(args));
};
});
childNode = /*#__PURE__*/react["createElement"](MemoInput, {
value: mergedControl[props.valuePropName || 'value'],
update: updateRef.current
}, Object(reactNode["a" /* cloneElement */])(children, childProps));
} else if (isRenderProps && (shouldUpdate || dependencies) && !hasName) {
childNode = children(context);
} else {
Object(devWarning["a" /* default */])(!mergedName.length, 'Form.Item', '`name` is only used for validate React element. If you are using Form.Item as layout display, please remove `name` instead.');
childNode = children;
}
return renderLayout(childNode, fieldId, meta, isRequired);
});
}
/* harmony default export */ var form_FormItem = (FormItem);
// CONCATENATED MODULE: ./node_modules/antd/es/form/FormList.js
var FormList_rest = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
var FormList_FormList = function FormList(_a) {
var children = _a.children,
props = FormList_rest(_a, ["children"]);
Object(devWarning["a" /* default */])(!!props.name, 'Form.List', 'Miss `name` prop.');
return /*#__PURE__*/react["createElement"](es["c" /* List */], props, function (fields, operation) {
return children(fields.map(function (field) {
return extends_default()(extends_default()({}, field), {
fieldKey: field.key
});
}), operation);
});
};
/* harmony default export */ var form_FormList = (FormList_FormList);
// CONCATENATED MODULE: ./node_modules/antd/es/form/index.js
var es_form_Form = form_Form;
es_form_Form.Item = form_FormItem;
es_form_Form.List = form_FormList;
es_form_Form.useForm = useForm;
es_form_Form.Provider = context_FormProvider;
es_form_Form.create = function () {
Object(devWarning["a" /* default */])(false, 'Form', 'antd v4 removed `Form.create`. Please remove or use `@ant-design/compatible` instead.');
};
/* harmony default export */ var es_form = __webpack_exports__["a"] = (es_form_Form);
/***/ }),
/***/ "VrN/":
/*!***************************************************!*\
!*** ./node_modules/codemirror/lib/codemirror.js ***!
\***************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
// This is CodeMirror (https://codemirror.net), a code editor
// implemented in JavaScript on top of the browser's DOM.
//
// You can find some technical background for some of the code below
// at http://marijnhaverbeke.nl/blog/#cm-internals .
(function (global, factory) {
true ? module.exports = factory() :
undefined;
}(this, (function () { 'use strict';
// Kludges for bugs and behavior differences that can't be feature
// detected are enabled based on userAgent etc sniffing.
var userAgent = navigator.userAgent;
var platform = navigator.platform;
var gecko = /gecko\/\d/i.test(userAgent);
var ie_upto10 = /MSIE \d/.test(userAgent);
var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
var edge = /Edge\/(\d+)/.exec(userAgent);
var ie = ie_upto10 || ie_11up || edge;
var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);
var webkit = !edge && /WebKit\//.test(userAgent);
var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
var chrome = !edge && /Chrome\//.test(userAgent);
var presto = /Opera\//.test(userAgent);
var safari = /Apple Computer/.test(navigator.vendor);
var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
var phantom = /PhantomJS/.test(userAgent);
var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
var android = /Android/.test(userAgent);
// This is woefully incomplete. Suggestions for alternative methods welcome.
var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
var mac = ios || /Mac/.test(platform);
var chromeOS = /\bCrOS\b/.test(userAgent);
var windows = /win/i.test(platform);
var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
if (presto_version) { presto_version = Number(presto_version[1]); }
if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
// Some browsers use the wrong event properties to signal cmd/ctrl on OS X
var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
var captureRightClick = gecko || (ie && ie_version >= 9);
function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
var rmClass = function(node, cls) {
var current = node.className;
var match = classTest(cls).exec(current);
if (match) {
var after = current.slice(match.index + match[0].length);
node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
}
};
function removeChildren(e) {
for (var count = e.childNodes.length; count > 0; --count)
{ e.removeChild(e.firstChild); }
return e
}
function removeChildrenAndAdd(parent, e) {
return removeChildren(parent).appendChild(e)
}
function elt(tag, content, className, style) {
var e = document.createElement(tag);
if (className) { e.className = className; }
if (style) { e.style.cssText = style; }
if (typeof content == "string") { e.appendChild(document.createTextNode(content)); }
else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }
return e
}
// wrapper for elt, which removes the elt from the accessibility tree
function eltP(tag, content, className, style) {
var e = elt(tag, content, className, style);
e.setAttribute("role", "presentation");
return e
}
var range;
if (document.createRange) { range = function(node, start, end, endNode) {
var r = document.createRange();
r.setEnd(endNode || node, end);
r.setStart(node, start);
return r
}; }
else { range = function(node, start, end) {
var r = document.body.createTextRange();
try { r.moveToElementText(node.parentNode); }
catch(e) { return r }
r.collapse(true);
r.moveEnd("character", end);
r.moveStart("character", start);
return r
}; }
function contains(parent, child) {
if (child.nodeType == 3) // Android browser always returns false when child is a textnode
{ child = child.parentNode; }
if (parent.contains)
{ return parent.contains(child) }
do {
if (child.nodeType == 11) { child = child.host; }
if (child == parent) { return true }
} while (child = child.parentNode)
}
function activeElt() {
// IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
// IE < 10 will throw when accessed while the page is loading or in an iframe.
// IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
var activeElement;
try {
activeElement = document.activeElement;
} catch(e) {
activeElement = document.body || null;
}
while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
{ activeElement = activeElement.shadowRoot.activeElement; }
return activeElement
}
function addClass(node, cls) {
var current = node.className;
if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; }
}
function joinClasses(a, b) {
var as = a.split(" ");
for (var i = 0; i < as.length; i++)
{ if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } }
return b
}
var selectInput = function(node) { node.select(); };
if (ios) // Mobile Safari apparently has a bug where select() is broken.
{ selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }
else if (ie) // Suppress mysterious IE10 errors
{ selectInput = function(node) { try { node.select(); } catch(_e) {} }; }
function bind(f) {
var args = Array.prototype.slice.call(arguments, 1);
return function(){return f.apply(null, args)}
}
function copyObj(obj, target, overwrite) {
if (!target) { target = {}; }
for (var prop in obj)
{ if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
{ target[prop] = obj[prop]; } }
return target
}
// Counts the column offset in a string, taking tabs into account.
// Used mostly to find indentation.
function countColumn(string, end, tabSize, startIndex, startValue) {
if (end == null) {
end = string.search(/[^\s\u00a0]/);
if (end == -1) { end = string.length; }
}
for (var i = startIndex || 0, n = startValue || 0;;) {
var nextTab = string.indexOf("\t", i);
if (nextTab < 0 || nextTab >= end)
{ return n + (end - i) }
n += nextTab - i;
n += tabSize - (n % tabSize);
i = nextTab + 1;
}
}
var Delayed = function() {
this.id = null;
this.f = null;
this.time = 0;
this.handler = bind(this.onTimeout, this);
};
Delayed.prototype.onTimeout = function (self) {
self.id = 0;
if (self.time <= +new Date) {
self.f();
} else {
setTimeout(self.handler, self.time - +new Date);
}
};
Delayed.prototype.set = function (ms, f) {
this.f = f;
var time = +new Date + ms;
if (!this.id || time < this.time) {
clearTimeout(this.id);
this.id = setTimeout(this.handler, ms);
this.time = time;
}
};
function indexOf(array, elt) {
for (var i = 0; i < array.length; ++i)
{ if (array[i] == elt) { return i } }
return -1
}
// Number of pixels added to scroller and sizer to hide scrollbar
var scrollerGap = 50;
// Returned or thrown by various protocols to signal 'I'm not
// handling this'.
var Pass = {toString: function(){return "CodeMirror.Pass"}};
// Reused option objects for setSelection & friends
var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
// The inverse of countColumn -- find the offset that corresponds to
// a particular column.
function findColumn(string, goal, tabSize) {
for (var pos = 0, col = 0;;) {
var nextTab = string.indexOf("\t", pos);
if (nextTab == -1) { nextTab = string.length; }
var skipped = nextTab - pos;
if (nextTab == string.length || col + skipped >= goal)
{ return pos + Math.min(skipped, goal - col) }
col += nextTab - pos;
col += tabSize - (col % tabSize);
pos = nextTab + 1;
if (col >= goal) { return pos }
}
}
var spaceStrs = [""];
function spaceStr(n) {
while (spaceStrs.length <= n)
{ spaceStrs.push(lst(spaceStrs) + " "); }
return spaceStrs[n]
}
function lst(arr) { return arr[arr.length-1] }
function map(array, f) {
var out = [];
for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
return out
}
function insertSorted(array, value, score) {
var pos = 0, priority = score(value);
while (pos < array.length && score(array[pos]) <= priority) { pos++; }
array.splice(pos, 0, value);
}
function nothing() {}
function createObj(base, props) {
var inst;
if (Object.create) {
inst = Object.create(base);
} else {
nothing.prototype = base;
inst = new nothing();
}
if (props) { copyObj(props, inst); }
return inst
}
var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
function isWordCharBasic(ch) {
return /\w/.test(ch) || ch > "\x80" &&
(ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
}
function isWordChar(ch, helper) {
if (!helper) { return isWordCharBasic(ch) }
if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
return helper.test(ch)
}
function isEmpty(obj) {
for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
return true
}
// Extending unicode characters. A series of a non-extending char +
// any number of extending chars is treated as a single unit as far
// as editing and measuring is concerned. This is not fully correct,
// since some scripts/fonts/browsers also treat other configurations
// of code points as a group.
var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;
function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
// Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
function skipExtendingChars(str, pos, dir) {
while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
return pos
}
// Returns the value from the range [`from`; `to`] that satisfies
// `pred` and is closest to `from`. Assumes that at least `to`
// satisfies `pred`. Supports `from` being greater than `to`.
function findFirst(pred, from, to) {
// At any point we are certain `to` satisfies `pred`, don't know
// whether `from` does.
var dir = from > to ? -1 : 1;
for (;;) {
if (from == to) { return from }
var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
if (mid == from) { return pred(mid) ? from : to }
if (pred(mid)) { to = mid; }
else { from = mid + dir; }
}
}
// BIDI HELPERS
function iterateBidiSections(order, from, to, f) {
if (!order) { return f(from, to, "ltr", 0) }
var found = false;
for (var i = 0; i < order.length; ++i) {
var part = order[i];
if (part.from < to && part.to > from || from == to && part.to == from) {
f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
found = true;
}
}
if (!found) { f(from, to, "ltr"); }
}
var bidiOther = null;
function getBidiPartAt(order, ch, sticky) {
var found;
bidiOther = null;
for (var i = 0; i < order.length; ++i) {
var cur = order[i];
if (cur.from < ch && cur.to > ch) { return i }
if (cur.to == ch) {
if (cur.from != cur.to && sticky == "before") { found = i; }
else { bidiOther = i; }
}
if (cur.from == ch) {
if (cur.from != cur.to && sticky != "before") { found = i; }
else { bidiOther = i; }
}
}
return found != null ? found : bidiOther
}
// Bidirectional ordering algorithm
// See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
// that this (partially) implements.
// One-char codes used for character types:
// L (L): Left-to-Right
// R (R): Right-to-Left
// r (AL): Right-to-Left Arabic
// 1 (EN): European Number
// + (ES): European Number Separator
// % (ET): European Number Terminator
// n (AN): Arabic Number
// , (CS): Common Number Separator
// m (NSM): Non-Spacing Mark
// b (BN): Boundary Neutral
// s (B): Paragraph Separator
// t (S): Segment Separator
// w (WS): Whitespace
// N (ON): Other Neutrals
// Returns null if characters are ordered as they appear
// (left-to-right), or an array of sections ({from, to, level}
// objects) in the order in which they occur visually.
var bidiOrdering = (function() {
// Character types for codepoints 0 to 0xff
var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
// Character types for codepoints 0x600 to 0x6f9
var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
function charType(code) {
if (code <= 0xf7) { return lowTypes.charAt(code) }
else if (0x590 <= code && code <= 0x5f4) { return "R" }
else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
else if (0x6ee <= code && code <= 0x8ac) { return "r" }
else if (0x2000 <= code && code <= 0x200b) { return "w" }
else if (code == 0x200c) { return "b" }
else { return "L" }
}
var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
function BidiSpan(level, from, to) {
this.level = level;
this.from = from; this.to = to;
}
return function(str, direction) {
var outerType = direction == "ltr" ? "L" : "R";
if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
var len = str.length, types = [];
for (var i = 0; i < len; ++i)
{ types.push(charType(str.charCodeAt(i))); }
// W1. Examine each non-spacing mark (NSM) in the level run, and
// change the type of the NSM to the type of the previous
// character. If the NSM is at the start of the level run, it will
// get the type of sor.
for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
var type = types[i$1];
if (type == "m") { types[i$1] = prev; }
else { prev = type; }
}
// W2. Search backwards from each instance of a European number
// until the first strong type (R, L, AL, or sor) is found. If an
// AL is found, change the type of the European number to Arabic
// number.
// W3. Change all ALs to R.
for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
var type$1 = types[i$2];
if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
}
// W4. A single European separator between two European numbers
// changes to a European number. A single common separator between
// two numbers of the same type changes to that type.
for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
var type$2 = types[i$3];
if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
else if (type$2 == "," && prev$1 == types[i$3+1] &&
(prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
prev$1 = type$2;
}
// W5. A sequence of European terminators adjacent to European
// numbers changes to all European numbers.
// W6. Otherwise, separators and terminators change to Other
// Neutral.
for (var i$4 = 0; i$4 < len; ++i$4) {
var type$3 = types[i$4];
if (type$3 == ",") { types[i$4] = "N"; }
else if (type$3 == "%") {
var end = (void 0);
for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
for (var j = i$4; j < end; ++j) { types[j] = replace; }
i$4 = end - 1;
}
}
// W7. Search backwards from each instance of a European number
// until the first strong type (R, L, or sor) is found. If an L is
// found, then change the type of the European number to L.
for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
var type$4 = types[i$5];
if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
else if (isStrong.test(type$4)) { cur$1 = type$4; }
}
// N1. A sequence of neutrals takes the direction of the
// surrounding strong text if the text on both sides has the same
// direction. European and Arabic numbers act as if they were R in
// terms of their influence on neutrals. Start-of-level-run (sor)
// and end-of-level-run (eor) are used at level run boundaries.
// N2. Any remaining neutrals take the embedding direction.
for (var i$6 = 0; i$6 < len; ++i$6) {
if (isNeutral.test(types[i$6])) {
var end$1 = (void 0);
for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
var before = (i$6 ? types[i$6-1] : outerType) == "L";
var after = (end$1 < len ? types[end$1] : outerType) == "L";
var replace$1 = before == after ? (before ? "L" : "R") : outerType;
for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
i$6 = end$1 - 1;
}
}
// Here we depart from the documented algorithm, in order to avoid
// building up an actual levels array. Since there are only three
// levels (0, 1, 2) in an implementation that doesn't take
// explicit embedding into account, we can build up the order on
// the fly, without following the level-based algorithm.
var order = [], m;
for (var i$7 = 0; i$7 < len;) {
if (countsAsLeft.test(types[i$7])) {
var start = i$7;
for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
order.push(new BidiSpan(0, start, i$7));
} else {
var pos = i$7, at = order.length, isRTL = direction == "rtl" ? 1 : 0;
for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
for (var j$2 = pos; j$2 < i$7;) {
if (countsAsNum.test(types[j$2])) {
if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); at += isRTL; }
var nstart = j$2;
for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
order.splice(at, 0, new BidiSpan(2, nstart, j$2));
at += isRTL;
pos = j$2;
} else { ++j$2; }
}
if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
}
}
if (direction == "ltr") {
if (order[0].level == 1 && (m = str.match(/^\s+/))) {
order[0].from = m[0].length;
order.unshift(new BidiSpan(0, 0, m[0].length));
}
if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
lst(order).to -= m[0].length;
order.push(new BidiSpan(0, len - m[0].length, len));
}
}
return direction == "rtl" ? order.reverse() : order
}
})();
// Get the bidi ordering for the given line (and cache it). Returns
// false for lines that are fully left-to-right, and an array of
// BidiSpan objects otherwise.
function getOrder(line, direction) {
var order = line.order;
if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
return order
}
// EVENT HANDLING
// Lightweight event framework. on/off also work on DOM nodes,
// registering native DOM handlers.
var noHandlers = [];
var on = function(emitter, type, f) {
if (emitter.addEventListener) {
emitter.addEventListener(type, f, false);
} else if (emitter.attachEvent) {
emitter.attachEvent("on" + type, f);
} else {
var map = emitter._handlers || (emitter._handlers = {});
map[type] = (map[type] || noHandlers).concat(f);
}
};
function getHandlers(emitter, type) {
return emitter._handlers && emitter._handlers[type] || noHandlers
}
function off(emitter, type, f) {
if (emitter.removeEventListener) {
emitter.removeEventListener(type, f, false);
} else if (emitter.detachEvent) {
emitter.detachEvent("on" + type, f);
} else {
var map = emitter._handlers, arr = map && map[type];
if (arr) {
var index = indexOf(arr, f);
if (index > -1)
{ map[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
}
}
}
function signal(emitter, type /*, values...*/) {
var handlers = getHandlers(emitter, type);
if (!handlers.length) { return }
var args = Array.prototype.slice.call(arguments, 2);
for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
}
// The DOM events that CodeMirror handles can be overridden by
// registering a (non-DOM) handler on the editor for the event name,
// and preventDefault-ing the event in that handler.
function signalDOMEvent(cm, e, override) {
if (typeof e == "string")
{ e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
signal(cm, override || e.type, cm, e);
return e_defaultPrevented(e) || e.codemirrorIgnore
}
function signalCursorActivity(cm) {
var arr = cm._handlers && cm._handlers.cursorActivity;
if (!arr) { return }
var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
{ set.push(arr[i]); } }
}
function hasHandler(emitter, type) {
return getHandlers(emitter, type).length > 0
}
// Add on and off methods to a constructor's prototype, to make
// registering events on such objects more convenient.
function eventMixin(ctor) {
ctor.prototype.on = function(type, f) {on(this, type, f);};
ctor.prototype.off = function(type, f) {off(this, type, f);};
}
// Due to the fact that we still support jurassic IE versions, some
// compatibility wrappers are needed.
function e_preventDefault(e) {
if (e.preventDefault) { e.preventDefault(); }
else { e.returnValue = false; }
}
function e_stopPropagation(e) {
if (e.stopPropagation) { e.stopPropagation(); }
else { e.cancelBubble = true; }
}
function e_defaultPrevented(e) {
return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
}
function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
function e_target(e) {return e.target || e.srcElement}
function e_button(e) {
var b = e.which;
if (b == null) {
if (e.button & 1) { b = 1; }
else if (e.button & 2) { b = 3; }
else if (e.button & 4) { b = 2; }
}
if (mac && e.ctrlKey && b == 1) { b = 3; }
return b
}
// Detect drag-and-drop
var dragAndDrop = function() {
// There is *some* kind of drag-and-drop support in IE6-8, but I
// couldn't get it to work yet.
if (ie && ie_version < 9) { return false }
var div = elt('div');
return "draggable" in div || "dragDrop" in div
}();
var zwspSupported;
function zeroWidthElement(measure) {
if (zwspSupported == null) {
var test = elt("span", "\u200b");
removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
if (measure.firstChild.offsetHeight != 0)
{ zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
}
var node = zwspSupported ? elt("span", "\u200b") :
elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
node.setAttribute("cm-text", "");
return node
}
// Feature-detect IE's crummy client rect reporting for bidi text
var badBidiRects;
function hasBadBidiRects(measure) {
if (badBidiRects != null) { return badBidiRects }
var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
var r0 = range(txt, 0, 1).getBoundingClientRect();
var r1 = range(txt, 1, 2).getBoundingClientRect();
removeChildren(measure);
if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
return badBidiRects = (r1.right - r0.right < 3)
}
// See if "".split is the broken IE version, if so, provide an
// alternative way to split lines.
var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
var pos = 0, result = [], l = string.length;
while (pos <= l) {
var nl = string.indexOf("\n", pos);
if (nl == -1) { nl = string.length; }
var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
var rt = line.indexOf("\r");
if (rt != -1) {
result.push(line.slice(0, rt));
pos += rt + 1;
} else {
result.push(line);
pos = nl + 1;
}
}
return result
} : function (string) { return string.split(/\r\n?|\n/); };
var hasSelection = window.getSelection ? function (te) {
try { return te.selectionStart != te.selectionEnd }
catch(e) { return false }
} : function (te) {
var range;
try {range = te.ownerDocument.selection.createRange();}
catch(e) {}
if (!range || range.parentElement() != te) { return false }
return range.compareEndPoints("StartToEnd", range) != 0
};
var hasCopyEvent = (function () {
var e = elt("div");
if ("oncopy" in e) { return true }
e.setAttribute("oncopy", "return;");
return typeof e.oncopy == "function"
})();
var badZoomedRects = null;
function hasBadZoomedRects(measure) {
if (badZoomedRects != null) { return badZoomedRects }
var node = removeChildrenAndAdd(measure, elt("span", "x"));
var normal = node.getBoundingClientRect();
var fromRange = range(node, 0, 1).getBoundingClientRect();
return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
}
// Known modes, by name and by MIME
var modes = {}, mimeModes = {};
// Extra arguments are stored as the mode's dependencies, which is
// used by (legacy) mechanisms like loadmode.js to automatically
// load a mode. (Preferred mechanism is the require/define calls.)
function defineMode(name, mode) {
if (arguments.length > 2)
{ mode.dependencies = Array.prototype.slice.call(arguments, 2); }
modes[name] = mode;
}
function defineMIME(mime, spec) {
mimeModes[mime] = spec;
}
// Given a MIME type, a {name, ...options} config object, or a name
// string, return a mode config object.
function resolveMode(spec) {
if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
spec = mimeModes[spec];
} else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
var found = mimeModes[spec.name];
if (typeof found == "string") { found = {name: found}; }
spec = createObj(found, spec);
spec.name = found.name;
} else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
return resolveMode("application/xml")
} else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
return resolveMode("application/json")
}
if (typeof spec == "string") { return {name: spec} }
else { return spec || {name: "null"} }
}
// Given a mode spec (anything that resolveMode accepts), find and
// initialize an actual mode object.
function getMode(options, spec) {
spec = resolveMode(spec);
var mfactory = modes[spec.name];
if (!mfactory) { return getMode(options, "text/plain") }
var modeObj = mfactory(options, spec);
if (modeExtensions.hasOwnProperty(spec.name)) {
var exts = modeExtensions[spec.name];
for (var prop in exts) {
if (!exts.hasOwnProperty(prop)) { continue }
if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
modeObj[prop] = exts[prop];
}
}
modeObj.name = spec.name;
if (spec.helperType) { modeObj.helperType = spec.helperType; }
if (spec.modeProps) { for (var prop$1 in spec.modeProps)
{ modeObj[prop$1] = spec.modeProps[prop$1]; } }
return modeObj
}
// This can be used to attach properties to mode objects from
// outside the actual mode definition.
var modeExtensions = {};
function extendMode(mode, properties) {
var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
copyObj(properties, exts);
}
function copyState(mode, state) {
if (state === true) { return state }
if (mode.copyState) { return mode.copyState(state) }
var nstate = {};
for (var n in state) {
var val = state[n];
if (val instanceof Array) { val = val.concat([]); }
nstate[n] = val;
}
return nstate
}
// Given a mode and a state (for that mode), find the inner mode and
// state at the position that the state refers to.
function innerMode(mode, state) {
var info;
while (mode.innerMode) {
info = mode.innerMode(state);
if (!info || info.mode == mode) { break }
state = info.state;
mode = info.mode;
}
return info || {mode: mode, state: state}
}
function startState(mode, a1, a2) {
return mode.startState ? mode.startState(a1, a2) : true
}
// STRING STREAM
// Fed to the mode parsers, provides helper functions to make
// parsers more succinct.
var StringStream = function(string, tabSize, lineOracle) {
this.pos = this.start = 0;
this.string = string;
this.tabSize = tabSize || 8;
this.lastColumnPos = this.lastColumnValue = 0;
this.lineStart = 0;
this.lineOracle = lineOracle;
};
StringStream.prototype.eol = function () {return this.pos >= this.string.length};
StringStream.prototype.sol = function () {return this.pos == this.lineStart};
StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
StringStream.prototype.next = function () {
if (this.pos < this.string.length)
{ return this.string.charAt(this.pos++) }
};
StringStream.prototype.eat = function (match) {
var ch = this.string.charAt(this.pos);
var ok;
if (typeof match == "string") { ok = ch == match; }
else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
if (ok) {++this.pos; return ch}
};
StringStream.prototype.eatWhile = function (match) {
var start = this.pos;
while (this.eat(match)){}
return this.pos > start
};
StringStream.prototype.eatSpace = function () {
var start = this.pos;
while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this.pos; }
return this.pos > start
};
StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
StringStream.prototype.skipTo = function (ch) {
var found = this.string.indexOf(ch, this.pos);
if (found > -1) {this.pos = found; return true}
};
StringStream.prototype.backUp = function (n) {this.pos -= n;};
StringStream.prototype.column = function () {
if (this.lastColumnPos < this.start) {
this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
this.lastColumnPos = this.start;
}
return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
};
StringStream.prototype.indentation = function () {
return countColumn(this.string, null, this.tabSize) -
(this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
};
StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
if (typeof pattern == "string") {
var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
var substr = this.string.substr(this.pos, pattern.length);
if (cased(substr) == cased(pattern)) {
if (consume !== false) { this.pos += pattern.length; }
return true
}
} else {
var match = this.string.slice(this.pos).match(pattern);
if (match && match.index > 0) { return null }
if (match && consume !== false) { this.pos += match[0].length; }
return match
}
};
StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
StringStream.prototype.hideFirstChars = function (n, inner) {
this.lineStart += n;
try { return inner() }
finally { this.lineStart -= n; }
};
StringStream.prototype.lookAhead = function (n) {
var oracle = this.lineOracle;
return oracle && oracle.lookAhead(n)
};
StringStream.prototype.baseToken = function () {
var oracle = this.lineOracle;
return oracle && oracle.baseToken(this.pos)
};
// Find the line object corresponding to the given line number.
function getLine(doc, n) {
n -= doc.first;
if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
var chunk = doc;
while (!chunk.lines) {
for (var i = 0;; ++i) {
var child = chunk.children[i], sz = child.chunkSize();
if (n < sz) { chunk = child; break }
n -= sz;
}
}
return chunk.lines[n]
}
// Get the part of a document between two positions, as an array of
// strings.
function getBetween(doc, start, end) {
var out = [], n = start.line;
doc.iter(start.line, end.line + 1, function (line) {
var text = line.text;
if (n == end.line) { text = text.slice(0, end.ch); }
if (n == start.line) { text = text.slice(start.ch); }
out.push(text);
++n;
});
return out
}
// Get the lines between from and to, as array of strings.
function getLines(doc, from, to) {
var out = [];
doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
return out
}
// Update the height of a line, propagating the height change
// upwards to parent nodes.
function updateLineHeight(line, height) {
var diff = height - line.height;
if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
}
// Given a line object, find its line number by walking up through
// its parent links.
function lineNo(line) {
if (line.parent == null) { return null }
var cur = line.parent, no = indexOf(cur.lines, line);
for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
for (var i = 0;; ++i) {
if (chunk.children[i] == cur) { break }
no += chunk.children[i].chunkSize();
}
}
return no + cur.first
}
// Find the line at the given vertical position, using the height
// information in the document tree.
function lineAtHeight(chunk, h) {
var n = chunk.first;
outer: do {
for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
var child = chunk.children[i$1], ch = child.height;
if (h < ch) { chunk = child; continue outer }
h -= ch;
n += child.chunkSize();
}
return n
} while (!chunk.lines)
var i = 0;
for (; i < chunk.lines.length; ++i) {
var line = chunk.lines[i], lh = line.height;
if (h < lh) { break }
h -= lh;
}
return n + i
}
function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
function lineNumberFor(options, i) {
return String(options.lineNumberFormatter(i + options.firstLineNumber))
}
// A Pos instance represents a position within the text.
function Pos(line, ch, sticky) {
if ( sticky === void 0 ) sticky = null;
if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
this.line = line;
this.ch = ch;
this.sticky = sticky;
}
// Compare two positions, return 0 if they are the same, a negative
// number when a is less, and a positive number otherwise.
function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
function copyPos(x) {return Pos(x.line, x.ch)}
function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
// Most of the external API clips given positions to make sure they
// actually exist within the document.
function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
function clipPos(doc, pos) {
if (pos.line < doc.first) { return Pos(doc.first, 0) }
var last = doc.first + doc.size - 1;
if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
return clipToLen(pos, getLine(doc, pos.line).text.length)
}
function clipToLen(pos, linelen) {
var ch = pos.ch;
if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
else if (ch < 0) { return Pos(pos.line, 0) }
else { return pos }
}
function clipPosArray(doc, array) {
var out = [];
for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
return out
}
var SavedContext = function(state, lookAhead) {
this.state = state;
this.lookAhead = lookAhead;
};
var Context = function(doc, state, line, lookAhead) {
this.state = state;
this.doc = doc;
this.line = line;
this.maxLookAhead = lookAhead || 0;
this.baseTokens = null;
this.baseTokenPos = 1;
};
Context.prototype.lookAhead = function (n) {
var line = this.doc.getLine(this.line + n);
if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
return line
};
Context.prototype.baseToken = function (n) {
if (!this.baseTokens) { return null }
while (this.baseTokens[this.baseTokenPos] <= n)
{ this.baseTokenPos += 2; }
var type = this.baseTokens[this.baseTokenPos + 1];
return {type: type && type.replace(/( |^)overlay .*/, ""),
size: this.baseTokens[this.baseTokenPos] - n}
};
Context.prototype.nextLine = function () {
this.line++;
if (this.maxLookAhead > 0) { this.maxLookAhead--; }
};
Context.fromSaved = function (doc, saved, line) {
if (saved instanceof SavedContext)
{ return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
else
{ return new Context(doc, copyState(doc.mode, saved), line) }
};
Context.prototype.save = function (copy) {
var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
};
// Compute a style array (an array starting with a mode generation
// -- for invalidation -- followed by pairs of end positions and
// style strings), which is used to highlight the tokens on the
// line.
function highlightLine(cm, line, context, forceToEnd) {
// A styles array always starts with a number identifying the
// mode/overlays that it is based on (for easy invalidation).
var st = [cm.state.modeGen], lineClasses = {};
// Compute the base array of styles
runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
lineClasses, forceToEnd);
var state = context.state;
// Run overlays, adjust style array.
var loop = function ( o ) {
context.baseTokens = st;
var overlay = cm.state.overlays[o], i = 1, at = 0;
context.state = true;
runMode(cm, line.text, overlay.mode, context, function (end, style) {
var start = i;
// Ensure there's a token end at the current position, and that i points at it
while (at < end) {
var i_end = st[i];
if (i_end > end)
{ st.splice(i, 1, end, st[i+1], i_end); }
i += 2;
at = Math.min(end, i_end);
}
if (!style) { return }
if (overlay.opaque) {
st.splice(start, i - start, end, "overlay " + style);
i = start + 2;
} else {
for (; start < i; start += 2) {
var cur = st[start+1];
st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
}
}
}, lineClasses);
context.state = state;
context.baseTokens = null;
context.baseTokenPos = 1;
};
for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
}
function getLineStyles(cm, line, updateFrontier) {
if (!line.styles || line.styles[0] != cm.state.modeGen) {
var context = getContextBefore(cm, lineNo(line));
var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
var result = highlightLine(cm, line, context);
if (resetState) { context.state = resetState; }
line.stateAfter = context.save(!resetState);
line.styles = result.styles;
if (result.classes) { line.styleClasses = result.classes; }
else if (line.styleClasses) { line.styleClasses = null; }
if (updateFrontier === cm.doc.highlightFrontier)
{ cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
}
return line.styles
}
function getContextBefore(cm, n, precise) {
var doc = cm.doc, display = cm.display;
if (!doc.mode.startState) { return new Context(doc, true, n) }
var start = findStartLine(cm, n, precise);
var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
doc.iter(start, n, function (line) {
processLine(cm, line.text, context);
var pos = context.line;
line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
context.nextLine();
});
if (precise) { doc.modeFrontier = context.line; }
return context
}
// Lightweight form of highlight -- proceed over this line and
// update state, but don't save a style array. Used for lines that
// aren't currently visible.
function processLine(cm, text, context, startAt) {
var mode = cm.doc.mode;
var stream = new StringStream(text, cm.options.tabSize, context);
stream.start = stream.pos = startAt || 0;
if (text == "") { callBlankLine(mode, context.state); }
while (!stream.eol()) {
readToken(mode, stream, context.state);
stream.start = stream.pos;
}
}
function callBlankLine(mode, state) {
if (mode.blankLine) { return mode.blankLine(state) }
if (!mode.innerMode) { return }
var inner = innerMode(mode, state);
if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
}
function readToken(mode, stream, state, inner) {
for (var i = 0; i < 10; i++) {
if (inner) { inner[0] = innerMode(mode, state).mode; }
var style = mode.token(stream, state);
if (stream.pos > stream.start) { return style }
}
throw new Error("Mode " + mode.name + " failed to advance stream.")
}
var Token = function(stream, type, state) {
this.start = stream.start; this.end = stream.pos;
this.string = stream.current();
this.type = type || null;
this.state = state;
};
// Utility for getTokenAt and getLineTokens
function takeToken(cm, pos, precise, asArray) {
var doc = cm.doc, mode = doc.mode, style;
pos = clipPos(doc, pos);
var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
if (asArray) { tokens = []; }
while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
stream.start = stream.pos;
style = readToken(mode, stream, context.state);
if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
}
return asArray ? tokens : new Token(stream, style, context.state)
}
function extractLineClasses(type, output) {
if (type) { for (;;) {
var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
if (!lineClass) { break }
type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
var prop = lineClass[1] ? "bgClass" : "textClass";
if (output[prop] == null)
{ output[prop] = lineClass[2]; }
else if (!(new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)")).test(output[prop]))
{ output[prop] += " " + lineClass[2]; }
} }
return type
}
// Run the given mode's parser over a line, calling f for each token.
function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
var flattenSpans = mode.flattenSpans;
if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
var curStart = 0, curStyle = null;
var stream = new StringStream(text, cm.options.tabSize, context), style;
var inner = cm.options.addModeClass && [null];
if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
while (!stream.eol()) {
if (stream.pos > cm.options.maxHighlightLength) {
flattenSpans = false;
if (forceToEnd) { processLine(cm, text, context, stream.pos); }
stream.pos = text.length;
style = null;
} else {
style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
}
if (inner) {
var mName = inner[0].name;
if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
}
if (!flattenSpans || curStyle != style) {
while (curStart < stream.start) {
curStart = Math.min(stream.start, curStart + 5000);
f(curStart, curStyle);
}
curStyle = style;
}
stream.start = stream.pos;
}
while (curStart < stream.pos) {
// Webkit seems to refuse to render text nodes longer than 57444
// characters, and returns inaccurate measurements in nodes
// starting around 5000 chars.
var pos = Math.min(stream.pos, curStart + 5000);
f(pos, curStyle);
curStart = pos;
}
}
// Finds the line to start with when starting a parse. Tries to
// find a line with a stateAfter, so that it can start with a
// valid state. If that fails, it returns the line with the
// smallest indentation, which tends to need the least context to
// parse correctly.
function findStartLine(cm, n, precise) {
var minindent, minline, doc = cm.doc;
var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
for (var search = n; search > lim; --search) {
if (search <= doc.first) { return doc.first }
var line = getLine(doc, search - 1), after = line.stateAfter;
if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
{ return search }
var indented = countColumn(line.text, null, cm.options.tabSize);
if (minline == null || minindent > indented) {
minline = search - 1;
minindent = indented;
}
}
return minline
}
function retreatFrontier(doc, n) {
doc.modeFrontier = Math.min(doc.modeFrontier, n);
if (doc.highlightFrontier < n - 10) { return }
var start = doc.first;
for (var line = n - 1; line > start; line--) {
var saved = getLine(doc, line).stateAfter;
// change is on 3
// state on line 1 looked ahead 2 -- so saw 3
// test 1 + 2 < 3 should cover this
if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
start = line + 1;
break
}
}
doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
}
// Optimize some code when these features are not used.
var sawReadOnlySpans = false, sawCollapsedSpans = false;
function seeReadOnlySpans() {
sawReadOnlySpans = true;
}
function seeCollapsedSpans() {
sawCollapsedSpans = true;
}
// TEXTMARKER SPANS
function MarkedSpan(marker, from, to) {
this.marker = marker;
this.from = from; this.to = to;
}
// Search an array of spans for a span matching the given marker.
function getMarkedSpanFor(spans, marker) {
if (spans) { for (var i = 0; i < spans.length; ++i) {
var span = spans[i];
if (span.marker == marker) { return span }
} }
}
// Remove a span from an array, returning undefined if no spans are
// left (we don't store arrays for lines without spans).
function removeMarkedSpan(spans, span) {
var r;
for (var i = 0; i < spans.length; ++i)
{ if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
return r
}
// Add a span to a line.
function addMarkedSpan(line, span) {
line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
span.marker.attachLine(line);
}
// Used for the algorithm that adjusts markers for a change in the
// document. These functions cut an array of spans at a given
// character position, returning an array of remaining chunks (or
// undefined if nothing remains).
function markedSpansBefore(old, startCh, isInsert) {
var nw;
if (old) { for (var i = 0; i < old.length; ++i) {
var span = old[i], marker = span.marker;
var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
}
} }
return nw
}
function markedSpansAfter(old, endCh, isInsert) {
var nw;
if (old) { for (var i = 0; i < old.length; ++i) {
var span = old[i], marker = span.marker;
var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
span.to == null ? null : span.to - endCh));
}
} }
return nw
}
// Given a change object, compute the new set of marker spans that
// cover the line in which the change took place. Removes spans
// entirely within the change, reconnects spans belonging to the
// same marker that appear on both sides of the change, and cuts off
// spans partially within the change. Returns an array of span
// arrays with one element for each line in (after) the change.
function stretchSpansOverChange(doc, change) {
if (change.full) { return null }
var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
if (!oldFirst && !oldLast) { return null }
var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
// Get the spans that 'stick out' on both sides
var first = markedSpansBefore(oldFirst, startCh, isInsert);
var last = markedSpansAfter(oldLast, endCh, isInsert);
// Next, merge those two ends
var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
if (first) {
// Fix up .to properties of first
for (var i = 0; i < first.length; ++i) {
var span = first[i];
if (span.to == null) {
var found = getMarkedSpanFor(last, span.marker);
if (!found) { span.to = startCh; }
else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
}
}
}
if (last) {
// Fix up .from in last (or move them into first in case of sameLine)
for (var i$1 = 0; i$1 < last.length; ++i$1) {
var span$1 = last[i$1];
if (span$1.to != null) { span$1.to += offset; }
if (span$1.from == null) {
var found$1 = getMarkedSpanFor(first, span$1.marker);
if (!found$1) {
span$1.from = offset;
if (sameLine) { (first || (first = [])).push(span$1); }
}
} else {
span$1.from += offset;
if (sameLine) { (first || (first = [])).push(span$1); }
}
}
}
// Make sure we didn't create any zero-length spans
if (first) { first = clearEmptySpans(first); }
if (last && last != first) { last = clearEmptySpans(last); }
var newMarkers = [first];
if (!sameLine) {
// Fill gap with whole-line-spans
var gap = change.text.length - 2, gapMarkers;
if (gap > 0 && first)
{ for (var i$2 = 0; i$2 < first.length; ++i$2)
{ if (first[i$2].to == null)
{ (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
for (var i$3 = 0; i$3 < gap; ++i$3)
{ newMarkers.push(gapMarkers); }
newMarkers.push(last);
}
return newMarkers
}
// Remove spans that are empty and don't have a clearWhenEmpty
// option of false.
function clearEmptySpans(spans) {
for (var i = 0; i < spans.length; ++i) {
var span = spans[i];
if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
{ spans.splice(i--, 1); }
}
if (!spans.length) { return null }
return spans
}
// Used to 'clip' out readOnly ranges when making a change.
function removeReadOnlyRanges(doc, from, to) {
var markers = null;
doc.iter(from.line, to.line + 1, function (line) {
if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
var mark = line.markedSpans[i].marker;
if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
{ (markers || (markers = [])).push(mark); }
} }
});
if (!markers) { return null }
var parts = [{from: from, to: to}];
for (var i = 0; i < markers.length; ++i) {
var mk = markers[i], m = mk.find(0);
for (var j = 0; j < parts.length; ++j) {
var p = parts[j];
if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
{ newParts.push({from: p.from, to: m.from}); }
if (dto > 0 || !mk.inclusiveRight && !dto)
{ newParts.push({from: m.to, to: p.to}); }
parts.splice.apply(parts, newParts);
j += newParts.length - 3;
}
}
return parts
}
// Connect or disconnect spans from a line.
function detachMarkedSpans(line) {
var spans = line.markedSpans;
if (!spans) { return }
for (var i = 0; i < spans.length; ++i)
{ spans[i].marker.detachLine(line); }
line.markedSpans = null;
}
function attachMarkedSpans(line, spans) {
if (!spans) { return }
for (var i = 0; i < spans.length; ++i)
{ spans[i].marker.attachLine(line); }
line.markedSpans = spans;
}
// Helpers used when computing which overlapping collapsed span
// counts as the larger one.
function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
// Returns a number indicating which of two overlapping collapsed
// spans is larger (and thus includes the other). Falls back to
// comparing ids when the spans cover exactly the same range.
function compareCollapsedMarkers(a, b) {
var lenDiff = a.lines.length - b.lines.length;
if (lenDiff != 0) { return lenDiff }
var aPos = a.find(), bPos = b.find();
var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
if (fromCmp) { return -fromCmp }
var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
if (toCmp) { return toCmp }
return b.id - a.id
}
// Find out whether a line ends or starts in a collapsed span. If
// so, return the marker for that span.
function collapsedSpanAtSide(line, start) {
var sps = sawCollapsedSpans && line.markedSpans, found;
if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
sp = sps[i];
if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
(!found || compareCollapsedMarkers(found, sp.marker) < 0))
{ found = sp.marker; }
} }
return found
}
function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
function collapsedSpanAround(line, ch) {
var sps = sawCollapsedSpans && line.markedSpans, found;
if (sps) { for (var i = 0; i < sps.length; ++i) {
var sp = sps[i];
if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&
(!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; }
} }
return found
}
// Test whether there exists a collapsed span that partially
// overlaps (covers the start or end, but not both) of a new span.
// Such overlap is not allowed.
function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
var line = getLine(doc, lineNo);
var sps = sawCollapsedSpans && line.markedSpans;
if (sps) { for (var i = 0; i < sps.length; ++i) {
var sp = sps[i];
if (!sp.marker.collapsed) { continue }
var found = sp.marker.find(0);
var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
{ return true }
} }
}
// A visual line is a line as drawn on the screen. Folding, for
// example, can cause multiple logical lines to appear on the same
// visual line. This finds the start of the visual line that the
// given line is part of (usually that is the line itself).
function visualLine(line) {
var merged;
while (merged = collapsedSpanAtStart(line))
{ line = merged.find(-1, true).line; }
return line
}
function visualLineEnd(line) {
var merged;
while (merged = collapsedSpanAtEnd(line))
{ line = merged.find(1, true).line; }
return line
}
// Returns an array of logical lines that continue the visual line
// started by the argument, or undefined if there are no such lines.
function visualLineContinued(line) {
var merged, lines;
while (merged = collapsedSpanAtEnd(line)) {
line = merged.find(1, true).line
;(lines || (lines = [])).push(line);
}
return lines
}
// Get the line number of the start of the visual line that the
// given line number is part of.
function visualLineNo(doc, lineN) {
var line = getLine(doc, lineN), vis = visualLine(line);
if (line == vis) { return lineN }
return lineNo(vis)
}
// Get the line number of the start of the next visual line after
// the given line.
function visualLineEndNo(doc, lineN) {
if (lineN > doc.lastLine()) { return lineN }
var line = getLine(doc, lineN), merged;
if (!lineIsHidden(doc, line)) { return lineN }
while (merged = collapsedSpanAtEnd(line))
{ line = merged.find(1, true).line; }
return lineNo(line) + 1
}
// Compute whether a line is hidden. Lines count as hidden when they
// are part of a visual line that starts with another line, or when
// they are entirely covered by collapsed, non-widget span.
function lineIsHidden(doc, line) {
var sps = sawCollapsedSpans && line.markedSpans;
if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
sp = sps[i];
if (!sp.marker.collapsed) { continue }
if (sp.from == null) { return true }
if (sp.marker.widgetNode) { continue }
if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
{ return true }
} }
}
function lineIsHiddenInner(doc, line, span) {
if (span.to == null) {
var end = span.marker.find(1, true);
return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
}
if (span.marker.inclusiveRight && span.to == line.text.length)
{ return true }
for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
sp = line.markedSpans[i];
if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
(sp.to == null || sp.to != span.from) &&
(sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
lineIsHiddenInner(doc, line, sp)) { return true }
}
}
// Find the height above the given line.
function heightAtLine(lineObj) {
lineObj = visualLine(lineObj);
var h = 0, chunk = lineObj.parent;
for (var i = 0; i < chunk.lines.length; ++i) {
var line = chunk.lines[i];
if (line == lineObj) { break }
else { h += line.height; }
}
for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
var cur = p.children[i$1];
if (cur == chunk) { break }
else { h += cur.height; }
}
}
return h
}
// Compute the character length of a line, taking into account
// collapsed ranges (see markText) that might hide parts, and join
// other lines onto it.
function lineLength(line) {
if (line.height == 0) { return 0 }
var len = line.text.length, merged, cur = line;
while (merged = collapsedSpanAtStart(cur)) {
var found = merged.find(0, true);
cur = found.from.line;
len += found.from.ch - found.to.ch;
}
cur = line;
while (merged = collapsedSpanAtEnd(cur)) {
var found$1 = merged.find(0, true);
len -= cur.text.length - found$1.from.ch;
cur = found$1.to.line;
len += cur.text.length - found$1.to.ch;
}
return len
}
// Find the longest line in the document.
function findMaxLine(cm) {
var d = cm.display, doc = cm.doc;
d.maxLine = getLine(doc, doc.first);
d.maxLineLength = lineLength(d.maxLine);
d.maxLineChanged = true;
doc.iter(function (line) {
var len = lineLength(line);
if (len > d.maxLineLength) {
d.maxLineLength = len;
d.maxLine = line;
}
});
}
// LINE DATA STRUCTURE
// Line objects. These hold state related to a line, including
// highlighting info (the styles array).
var Line = function(text, markedSpans, estimateHeight) {
this.text = text;
attachMarkedSpans(this, markedSpans);
this.height = estimateHeight ? estimateHeight(this) : 1;
};
Line.prototype.lineNo = function () { return lineNo(this) };
eventMixin(Line);
// Change the content (text, markers) of a line. Automatically
// invalidates cached information and tries to re-estimate the
// line's height.
function updateLine(line, text, markedSpans, estimateHeight) {
line.text = text;
if (line.stateAfter) { line.stateAfter = null; }
if (line.styles) { line.styles = null; }
if (line.order != null) { line.order = null; }
detachMarkedSpans(line);
attachMarkedSpans(line, markedSpans);
var estHeight = estimateHeight ? estimateHeight(line) : 1;
if (estHeight != line.height) { updateLineHeight(line, estHeight); }
}
// Detach a line from the document tree and its markers.
function cleanUpLine(line) {
line.parent = null;
detachMarkedSpans(line);
}
// Convert a style as returned by a mode (either null, or a string
// containing one or more styles) to a CSS style. This is cached,
// and also looks for line-wide styles.
var styleToClassCache = {}, styleToClassCacheWithMode = {};
function interpretTokenStyle(style, options) {
if (!style || /^\s*$/.test(style)) { return null }
var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
return cache[style] ||
(cache[style] = style.replace(/\S+/g, "cm-$&"))
}
// Render the DOM representation of the text of a line. Also builds
// up a 'line map', which points at the DOM nodes that represent
// specific stretches of text, and is used by the measuring code.
// The returned object contains the DOM node, this map, and
// information about line-wide styles that were set by the mode.
function buildLineContent(cm, lineView) {
// The padding-right forces the element to have a 'border', which
// is needed on Webkit to be able to get line-level bounding
// rectangles for it (in measureChar).
var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
col: 0, pos: 0, cm: cm,
trailingSpace: false,
splitSpaces: cm.getOption("lineWrapping")};
lineView.measure = {};
// Iterate over the logical lines that make up this visual line.
for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
builder.pos = 0;
builder.addToken = buildToken;
// Optionally wire in some hacks into the token-rendering
// algorithm, to deal with browser quirks.
if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
{ builder.addToken = buildTokenBadBidi(builder.addToken, order); }
builder.map = [];
var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
if (line.styleClasses) {
if (line.styleClasses.bgClass)
{ builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
if (line.styleClasses.textClass)
{ builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
}
// Ensure at least a single node is present, for measuring.
if (builder.map.length == 0)
{ builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
// Store the map and a cache object for the current logical line
if (i == 0) {
lineView.measure.map = builder.map;
lineView.measure.cache = {};
} else {
(lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
}
}
// See issue #2901
if (webkit) {
var last = builder.content.lastChild;
if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
{ builder.content.className = "cm-tab-wrap-hack"; }
}
signal(cm, "renderLine", cm, lineView.line, builder.pre);
if (builder.pre.className)
{ builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
return builder
}
function defaultSpecialCharPlaceholder(ch) {
var token = elt("span", "\u2022", "cm-invalidchar");
token.title = "\\u" + ch.charCodeAt(0).toString(16);
token.setAttribute("aria-label", token.title);
return token
}
// Build up the DOM representation for a single token, and add it to
// the line map. Takes care to render special characters separately.
function buildToken(builder, text, style, startStyle, endStyle, css, attributes) {
if (!text) { return }
var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
var special = builder.cm.state.specialChars, mustWrap = false;
var content;
if (!special.test(text)) {
builder.col += text.length;
content = document.createTextNode(displayText);
builder.map.push(builder.pos, builder.pos + text.length, content);
if (ie && ie_version < 9) { mustWrap = true; }
builder.pos += text.length;
} else {
content = document.createDocumentFragment();
var pos = 0;
while (true) {
special.lastIndex = pos;
var m = special.exec(text);
var skipped = m ? m.index - pos : text.length - pos;
if (skipped) {
var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
else { content.appendChild(txt); }
builder.map.push(builder.pos, builder.pos + skipped, txt);
builder.col += skipped;
builder.pos += skipped;
}
if (!m) { break }
pos += skipped + 1;
var txt$1 = (void 0);
if (m[0] == "\t") {
var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
txt$1.setAttribute("role", "presentation");
txt$1.setAttribute("cm-text", "\t");
builder.col += tabWidth;
} else if (m[0] == "\r" || m[0] == "\n") {
txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
txt$1.setAttribute("cm-text", m[0]);
builder.col += 1;
} else {
txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
txt$1.setAttribute("cm-text", m[0]);
if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
else { content.appendChild(txt$1); }
builder.col += 1;
}
builder.map.push(builder.pos, builder.pos + 1, txt$1);
builder.pos++;
}
}
builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
if (style || startStyle || endStyle || mustWrap || css || attributes) {
var fullStyle = style || "";
if (startStyle) { fullStyle += startStyle; }
if (endStyle) { fullStyle += endStyle; }
var token = elt("span", [content], fullStyle, css);
if (attributes) {
for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class")
{ token.setAttribute(attr, attributes[attr]); } }
}
return builder.content.appendChild(token)
}
builder.content.appendChild(content);
}
// Change some spaces to NBSP to prevent the browser from collapsing
// trailing spaces at the end of a line when rendering text (issue #1362).
function splitSpaces(text, trailingBefore) {
if (text.length > 1 && !/ /.test(text)) { return text }
var spaceBefore = trailingBefore, result = "";
for (var i = 0; i < text.length; i++) {
var ch = text.charAt(i);
if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
{ ch = "\u00a0"; }
result += ch;
spaceBefore = ch == " ";
}
return result
}
// Work around nonsense dimensions being reported for stretches of
// right-to-left text.
function buildTokenBadBidi(inner, order) {
return function (builder, text, style, startStyle, endStyle, css, attributes) {
style = style ? style + " cm-force-border" : "cm-force-border";
var start = builder.pos, end = start + text.length;
for (;;) {
// Find the part that overlaps with the start of this text
var part = (void 0);
for (var i = 0; i < order.length; i++) {
part = order[i];
if (part.to > start && part.from <= start) { break }
}
if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) }
inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes);
startStyle = null;
text = text.slice(part.to - start);
start = part.to;
}
}
}
function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
var widget = !ignoreWidget && marker.widgetNode;
if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
if (!widget)
{ widget = builder.content.appendChild(document.createElement("span")); }
widget.setAttribute("cm-marker", marker.id);
}
if (widget) {
builder.cm.display.input.setUneditable(widget);
builder.content.appendChild(widget);
}
builder.pos += size;
builder.trailingSpace = false;
}
// Outputs a number of spans to make up a line, taking highlighting
// and marked text into account.
function insertLineContent(line, builder, styles) {
var spans = line.markedSpans, allText = line.text, at = 0;
if (!spans) {
for (var i$1 = 1; i$1 < styles.length; i$1+=2)
{ builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
return
}
var len = allText.length, pos = 0, i = 1, text = "", style, css;
var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes;
for (;;) {
if (nextChange == pos) { // Update current marker set
spanStyle = spanEndStyle = spanStartStyle = css = "";
attributes = null;
collapsed = null; nextChange = Infinity;
var foundBookmarks = [], endStyles = (void 0);
for (var j = 0; j < spans.length; ++j) {
var sp = spans[j], m = sp.marker;
if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
foundBookmarks.push(m);
} else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
if (sp.to != null && sp.to != pos && nextChange > sp.to) {
nextChange = sp.to;
spanEndStyle = "";
}
if (m.className) { spanStyle += " " + m.className; }
if (m.css) { css = (css ? css + ";" : "") + m.css; }
if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
// support for the old title property
// https://github.com/codemirror/CodeMirror/pull/5673
if (m.title) { (attributes || (attributes = {})).title = m.title; }
if (m.attributes) {
for (var attr in m.attributes)
{ (attributes || (attributes = {}))[attr] = m.attributes[attr]; }
}
if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
{ collapsed = sp; }
} else if (sp.from > pos && nextChange > sp.from) {
nextChange = sp.from;
}
}
if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
{ if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
{ buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
if (collapsed && (collapsed.from || 0) == pos) {
buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
collapsed.marker, collapsed.from == null);
if (collapsed.to == null) { return }
if (collapsed.to == pos) { collapsed = false; }
}
}
if (pos >= len) { break }
var upto = Math.min(len, nextChange);
while (true) {
if (text) {
var end = pos + text.length;
if (!collapsed) {
var tokenText = end > upto ? text.slice(0, upto - pos) : text;
builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes);
}
if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
pos = end;
spanStartStyle = "";
}
text = allText.slice(at, at = styles[i++]);
style = interpretTokenStyle(styles[i++], builder.cm.options);
}
}
}
// These objects are used to represent the visible (currently drawn)
// part of the document. A LineView may correspond to multiple
// logical lines, if those are connected by collapsed ranges.
function LineView(doc, line, lineN) {
// The starting line
this.line = line;
// Continuing lines, if any
this.rest = visualLineContinued(line);
// Number of logical lines in this visual line
this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
this.node = this.text = null;
this.hidden = lineIsHidden(doc, line);
}
// Create a range of LineView objects for the given lines.
function buildViewArray(cm, from, to) {
var array = [], nextPos;
for (var pos = from; pos < to; pos = nextPos) {
var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
nextPos = pos + view.size;
array.push(view);
}
return array
}
var operationGroup = null;
function pushOperation(op) {
if (operationGroup) {
operationGroup.ops.push(op);
} else {
op.ownsGroup = operationGroup = {
ops: [op],
delayedCallbacks: []
};
}
}
function fireCallbacksForOps(group) {
// Calls delayed callbacks and cursorActivity handlers until no
// new ones appear
var callbacks = group.delayedCallbacks, i = 0;
do {
for (; i < callbacks.length; i++)
{ callbacks[i].call(null); }
for (var j = 0; j < group.ops.length; j++) {
var op = group.ops[j];
if (op.cursorActivityHandlers)
{ while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
{ op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
}
} while (i < callbacks.length)
}
function finishOperation(op, endCb) {
var group = op.ownsGroup;
if (!group) { return }
try { fireCallbacksForOps(group); }
finally {
operationGroup = null;
endCb(group);
}
}
var orphanDelayedCallbacks = null;
// Often, we want to signal events at a point where we are in the
// middle of some work, but don't want the handler to start calling
// other methods on the editor, which might be in an inconsistent
// state or simply not expect any other events to happen.
// signalLater looks whether there are any handlers, and schedules
// them to be executed when the last operation ends, or, if no
// operation is active, when a timeout fires.
function signalLater(emitter, type /*, values...*/) {
var arr = getHandlers(emitter, type);
if (!arr.length) { return }
var args = Array.prototype.slice.call(arguments, 2), list;
if (operationGroup) {
list = operationGroup.delayedCallbacks;
} else if (orphanDelayedCallbacks) {
list = orphanDelayedCallbacks;
} else {
list = orphanDelayedCallbacks = [];
setTimeout(fireOrphanDelayed, 0);
}
var loop = function ( i ) {
list.push(function () { return arr[i].apply(null, args); });
};
for (var i = 0; i < arr.length; ++i)
loop( i );
}
function fireOrphanDelayed() {
var delayed = orphanDelayedCallbacks;
orphanDelayedCallbacks = null;
for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
}
// When an aspect of a line changes, a string is added to
// lineView.changes. This updates the relevant part of the line's
// DOM structure.
function updateLineForChanges(cm, lineView, lineN, dims) {
for (var j = 0; j < lineView.changes.length; j++) {
var type = lineView.changes[j];
if (type == "text") { updateLineText(cm, lineView); }
else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
else if (type == "class") { updateLineClasses(cm, lineView); }
else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
}
lineView.changes = null;
}
// Lines with gutter elements, widgets or a background class need to
// be wrapped, and have the extra elements added to the wrapper div
function ensureLineWrapped(lineView) {
if (lineView.node == lineView.text) {
lineView.node = elt("div", null, null, "position: relative");
if (lineView.text.parentNode)
{ lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
lineView.node.appendChild(lineView.text);
if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
}
return lineView.node
}
function updateLineBackground(cm, lineView) {
var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
if (cls) { cls += " CodeMirror-linebackground"; }
if (lineView.background) {
if (cls) { lineView.background.className = cls; }
else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
} else if (cls) {
var wrap = ensureLineWrapped(lineView);
lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
cm.display.input.setUneditable(lineView.background);
}
}
// Wrapper around buildLineContent which will reuse the structure
// in display.externalMeasured when possible.
function getLineContent(cm, lineView) {
var ext = cm.display.externalMeasured;
if (ext && ext.line == lineView.line) {
cm.display.externalMeasured = null;
lineView.measure = ext.measure;
return ext.built
}
return buildLineContent(cm, lineView)
}
// Redraw the line's text. Interacts with the background and text
// classes because the mode may output tokens that influence these
// classes.
function updateLineText(cm, lineView) {
var cls = lineView.text.className;
var built = getLineContent(cm, lineView);
if (lineView.text == lineView.node) { lineView.node = built.pre; }
lineView.text.parentNode.replaceChild(built.pre, lineView.text);
lineView.text = built.pre;
if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
lineView.bgClass = built.bgClass;
lineView.textClass = built.textClass;
updateLineClasses(cm, lineView);
} else if (cls) {
lineView.text.className = cls;
}
}
function updateLineClasses(cm, lineView) {
updateLineBackground(cm, lineView);
if (lineView.line.wrapClass)
{ ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
else if (lineView.node != lineView.text)
{ lineView.node.className = ""; }
var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
lineView.text.className = textClass || "";
}
function updateLineGutter(cm, lineView, lineN, dims) {
if (lineView.gutter) {
lineView.node.removeChild(lineView.gutter);
lineView.gutter = null;
}
if (lineView.gutterBackground) {
lineView.node.removeChild(lineView.gutterBackground);
lineView.gutterBackground = null;
}
if (lineView.line.gutterClass) {
var wrap = ensureLineWrapped(lineView);
lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
cm.display.input.setUneditable(lineView.gutterBackground);
wrap.insertBefore(lineView.gutterBackground, lineView.text);
}
var markers = lineView.line.gutterMarkers;
if (cm.options.lineNumbers || markers) {
var wrap$1 = ensureLineWrapped(lineView);
var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
cm.display.input.setUneditable(gutterWrap);
wrap$1.insertBefore(gutterWrap, lineView.text);
if (lineView.line.gutterClass)
{ gutterWrap.className += " " + lineView.line.gutterClass; }
if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
{ lineView.lineNumber = gutterWrap.appendChild(
elt("div", lineNumberFor(cm.options, lineN),
"CodeMirror-linenumber CodeMirror-gutter-elt",
("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
if (markers) { for (var k = 0; k < cm.display.gutterSpecs.length; ++k) {
var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id];
if (found)
{ gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
} }
}
}
function updateLineWidgets(cm, lineView, dims) {
if (lineView.alignable) { lineView.alignable = null; }
var isWidget = classTest("CodeMirror-linewidget");
for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
next = node.nextSibling;
if (isWidget.test(node.className)) { lineView.node.removeChild(node); }
}
insertLineWidgets(cm, lineView, dims);
}
// Build a line's DOM representation from scratch
function buildLineElement(cm, lineView, lineN, dims) {
var built = getLineContent(cm, lineView);
lineView.text = lineView.node = built.pre;
if (built.bgClass) { lineView.bgClass = built.bgClass; }
if (built.textClass) { lineView.textClass = built.textClass; }
updateLineClasses(cm, lineView);
updateLineGutter(cm, lineView, lineN, dims);
insertLineWidgets(cm, lineView, dims);
return lineView.node
}
// A lineView may contain multiple logical lines (when merged by
// collapsed spans). The widgets for all of them need to be drawn.
function insertLineWidgets(cm, lineView, dims) {
insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
{ insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
}
function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
if (!line.widgets) { return }
var wrap = ensureLineWrapped(lineView);
for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : ""));
if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
positionLineWidget(widget, node, lineView, dims);
cm.display.input.setUneditable(node);
if (allowAbove && widget.above)
{ wrap.insertBefore(node, lineView.gutter || lineView.text); }
else
{ wrap.appendChild(node); }
signalLater(widget, "redraw");
}
}
function positionLineWidget(widget, node, lineView, dims) {
if (widget.noHScroll) {
(lineView.alignable || (lineView.alignable = [])).push(node);
var width = dims.wrapperWidth;
node.style.left = dims.fixedPos + "px";
if (!widget.coverGutter) {
width -= dims.gutterTotalWidth;
node.style.paddingLeft = dims.gutterTotalWidth + "px";
}
node.style.width = width + "px";
}
if (widget.coverGutter) {
node.style.zIndex = 5;
node.style.position = "relative";
if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
}
}
function widgetHeight(widget) {
if (widget.height != null) { return widget.height }
var cm = widget.doc.cm;
if (!cm) { return 0 }
if (!contains(document.body, widget.node)) {
var parentStyle = "position: relative;";
if (widget.coverGutter)
{ parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
if (widget.noHScroll)
{ parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
}
return widget.height = widget.node.parentNode.offsetHeight
}
// Return true when the given mouse event happened in a widget
function eventInWidget(display, e) {
for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
(n.parentNode == display.sizer && n != display.mover))
{ return true }
}
}
// POSITION MEASUREMENT
function paddingTop(display) {return display.lineSpace.offsetTop}
function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
function paddingH(display) {
if (display.cachedPaddingH) { return display.cachedPaddingH }
var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like"));
var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
return data
}
function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
function displayWidth(cm) {
return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
}
function displayHeight(cm) {
return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
}
// Ensure the lineView.wrapping.heights array is populated. This is
// an array of bottom offsets for the lines that make up a drawn
// line. When lineWrapping is on, there might be more than one
// height.
function ensureLineHeights(cm, lineView, rect) {
var wrapping = cm.options.lineWrapping;
var curWidth = wrapping && displayWidth(cm);
if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
var heights = lineView.measure.heights = [];
if (wrapping) {
lineView.measure.width = curWidth;
var rects = lineView.text.firstChild.getClientRects();
for (var i = 0; i < rects.length - 1; i++) {
var cur = rects[i], next = rects[i + 1];
if (Math.abs(cur.bottom - next.bottom) > 2)
{ heights.push((cur.bottom + next.top) / 2 - rect.top); }
}
}
heights.push(rect.bottom - rect.top);
}
}
// Find a line map (mapping character offsets to text nodes) and a
// measurement cache for the given line number. (A line view might
// contain multiple lines when collapsed ranges are present.)
function mapFromLineView(lineView, line, lineN) {
if (lineView.line == line)
{ return {map: lineView.measure.map, cache: lineView.measure.cache} }
for (var i = 0; i < lineView.rest.length; i++)
{ if (lineView.rest[i] == line)
{ return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
{ if (lineNo(lineView.rest[i$1]) > lineN)
{ return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
}
// Render a line into the hidden node display.externalMeasured. Used
// when measurement is needed for a line that's not in the viewport.
function updateExternalMeasurement(cm, line) {
line = visualLine(line);
var lineN = lineNo(line);
var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
view.lineN = lineN;
var built = view.built = buildLineContent(cm, view);
view.text = built.pre;
removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
return view
}
// Get a {top, bottom, left, right} box (in line-local coordinates)
// for a given character.
function measureChar(cm, line, ch, bias) {
return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
}
// Find a line view that corresponds to the given line number.
function findViewForLine(cm, lineN) {
if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
{ return cm.display.view[findViewIndex(cm, lineN)] }
var ext = cm.display.externalMeasured;
if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
{ return ext }
}
// Measurement can be split in two steps, the set-up work that
// applies to the whole line, and the measurement of the actual
// character. Functions like coordsChar, that need to do a lot of
// measurements in a row, can thus ensure that the set-up work is
// only done once.
function prepareMeasureForLine(cm, line) {
var lineN = lineNo(line);
var view = findViewForLine(cm, lineN);
if (view && !view.text) {
view = null;
} else if (view && view.changes) {
updateLineForChanges(cm, view, lineN, getDimensions(cm));
cm.curOp.forceUpdate = true;
}
if (!view)
{ view = updateExternalMeasurement(cm, line); }
var info = mapFromLineView(view, line, lineN);
return {
line: line, view: view, rect: null,
map: info.map, cache: info.cache, before: info.before,
hasHeights: false
}
}
// Given a prepared measurement object, measures the position of an
// actual character (or fetches it from the cache).
function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
if (prepared.before) { ch = -1; }
var key = ch + (bias || ""), found;
if (prepared.cache.hasOwnProperty(key)) {
found = prepared.cache[key];
} else {
if (!prepared.rect)
{ prepared.rect = prepared.view.text.getBoundingClientRect(); }
if (!prepared.hasHeights) {
ensureLineHeights(cm, prepared.view, prepared.rect);
prepared.hasHeights = true;
}
found = measureCharInner(cm, prepared, ch, bias);
if (!found.bogus) { prepared.cache[key] = found; }
}
return {left: found.left, right: found.right,
top: varHeight ? found.rtop : found.top,
bottom: varHeight ? found.rbottom : found.bottom}
}
var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
function nodeAndOffsetInLineMap(map, ch, bias) {
var node, start, end, collapse, mStart, mEnd;
// First, search the line map for the text node corresponding to,
// or closest to, the target character.
for (var i = 0; i < map.length; i += 3) {
mStart = map[i];
mEnd = map[i + 1];
if (ch < mStart) {
start = 0; end = 1;
collapse = "left";
} else if (ch < mEnd) {
start = ch - mStart;
end = start + 1;
} else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
end = mEnd - mStart;
start = end - 1;
if (ch >= mEnd) { collapse = "right"; }
}
if (start != null) {
node = map[i + 2];
if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
{ collapse = bias; }
if (bias == "left" && start == 0)
{ while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
node = map[(i -= 3) + 2];
collapse = "left";
} }
if (bias == "right" && start == mEnd - mStart)
{ while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
node = map[(i += 3) + 2];
collapse = "right";
} }
break
}
}
return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
}
function getUsefulRect(rects, bias) {
var rect = nullRect;
if (bias == "left") { for (var i = 0; i < rects.length; i++) {
if ((rect = rects[i]).left != rect.right) { break }
} } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
if ((rect = rects[i$1]).left != rect.right) { break }
} }
return rect
}
function measureCharInner(cm, prepared, ch, bias) {
var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
var rect;
if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
{ rect = node.parentNode.getBoundingClientRect(); }
else
{ rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
if (rect.left || rect.right || start == 0) { break }
end = start;
start = start - 1;
collapse = "right";
}
if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
} else { // If it is a widget, simply get the box for the whole widget.
if (start > 0) { collapse = bias = "right"; }
var rects;
if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
{ rect = rects[bias == "right" ? rects.length - 1 : 0]; }
else
{ rect = node.getBoundingClientRect(); }
}
if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
var rSpan = node.parentNode.getClientRects()[0];
if (rSpan)
{ rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
else
{ rect = nullRect; }
}
var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
var mid = (rtop + rbot) / 2;
var heights = prepared.view.measure.heights;
var i = 0;
for (; i < heights.length - 1; i++)
{ if (mid < heights[i]) { break } }
var top = i ? heights[i - 1] : 0, bot = heights[i];
var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
top: top, bottom: bot};
if (!rect.left && !rect.right) { result.bogus = true; }
if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
return result
}
// Work around problem with bounding client rects on ranges being
// returned incorrectly when zoomed on IE10 and below.
function maybeUpdateRectForZooming(measure, rect) {
if (!window.screen || screen.logicalXDPI == null ||
screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
{ return rect }
var scaleX = screen.logicalXDPI / screen.deviceXDPI;
var scaleY = screen.logicalYDPI / screen.deviceYDPI;
return {left: rect.left * scaleX, right: rect.right * scaleX,
top: rect.top * scaleY, bottom: rect.bottom * scaleY}
}
function clearLineMeasurementCacheFor(lineView) {
if (lineView.measure) {
lineView.measure.cache = {};
lineView.measure.heights = null;
if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
{ lineView.measure.caches[i] = {}; } }
}
}
function clearLineMeasurementCache(cm) {
cm.display.externalMeasure = null;
removeChildren(cm.display.lineMeasure);
for (var i = 0; i < cm.display.view.length; i++)
{ clearLineMeasurementCacheFor(cm.display.view[i]); }
}
function clearCaches(cm) {
clearLineMeasurementCache(cm);
cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
cm.display.lineNumChars = null;
}
function pageScrollX() {
// Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
// which causes page_Offset and bounding client rects to use
// different reference viewports and invalidate our calculations.
if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
return window.pageXOffset || (document.documentElement || document.body).scrollLeft
}
function pageScrollY() {
if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
return window.pageYOffset || (document.documentElement || document.body).scrollTop
}
function widgetTopHeight(lineObj) {
var height = 0;
if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above)
{ height += widgetHeight(lineObj.widgets[i]); } } }
return height
}
// Converts a {top, bottom, left, right} box from line-local
// coordinates into another coordinate system. Context may be one of
// "line", "div" (display.lineDiv), "local"./null (editor), "window",
// or "page".
function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
if (!includeWidgets) {
var height = widgetTopHeight(lineObj);
rect.top += height; rect.bottom += height;
}
if (context == "line") { return rect }
if (!context) { context = "local"; }
var yOff = heightAtLine(lineObj);
if (context == "local") { yOff += paddingTop(cm.display); }
else { yOff -= cm.display.viewOffset; }
if (context == "page" || context == "window") {
var lOff = cm.display.lineSpace.getBoundingClientRect();
yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
rect.left += xOff; rect.right += xOff;
}
rect.top += yOff; rect.bottom += yOff;
return rect
}
// Coverts a box from "div" coords to another coordinate system.
// Context may be "window", "page", "div", or "local"./null.
function fromCoordSystem(cm, coords, context) {
if (context == "div") { return coords }
var left = coords.left, top = coords.top;
// First move into "page" coordinate system
if (context == "page") {
left -= pageScrollX();
top -= pageScrollY();
} else if (context == "local" || !context) {
var localBox = cm.display.sizer.getBoundingClientRect();
left += localBox.left;
top += localBox.top;
}
var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
}
function charCoords(cm, pos, context, lineObj, bias) {
if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
}
// Returns a box for a given cursor position, which may have an
// 'other' property containing the position of the secondary cursor
// on a bidi boundary.
// A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
// and after `char - 1` in writing order of `char - 1`
// A cursor Pos(line, char, "after") is on the same visual line as `char`
// and before `char` in writing order of `char`
// Examples (upper-case letters are RTL, lower-case are LTR):
// Pos(0, 1, ...)
// before after
// ab a|b a|b
// aB a|B aB|
// Ab |Ab A|b
// AB B|A B|A
// Every position after the last character on a line is considered to stick
// to the last character on the line.
function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
lineObj = lineObj || getLine(cm.doc, pos.line);
if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
function get(ch, right) {
var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
if (right) { m.left = m.right; } else { m.right = m.left; }
return intoCoordSystem(cm, lineObj, m, context)
}
var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
if (ch >= lineObj.text.length) {
ch = lineObj.text.length;
sticky = "before";
} else if (ch <= 0) {
ch = 0;
sticky = "after";
}
if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
function getBidi(ch, partPos, invert) {
var part = order[partPos], right = part.level == 1;
return get(invert ? ch - 1 : ch, right != invert)
}
var partPos = getBidiPartAt(order, ch, sticky);
var other = bidiOther;
var val = getBidi(ch, partPos, sticky == "before");
if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
return val
}
// Used to cheaply estimate the coordinates for a position. Used for
// intermediate scroll updates.
function estimateCoords(cm, pos) {
var left = 0;
pos = clipPos(cm.doc, pos);
if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
var lineObj = getLine(cm.doc, pos.line);
var top = heightAtLine(lineObj) + paddingTop(cm.display);
return {left: left, right: left, top: top, bottom: top + lineObj.height}
}
// Positions returned by coordsChar contain some extra information.
// xRel is the relative x position of the input coordinates compared
// to the found position (so xRel > 0 means the coordinates are to
// the right of the character position, for example). When outside
// is true, that means the coordinates lie outside the line's
// vertical range.
function PosWithInfo(line, ch, sticky, outside, xRel) {
var pos = Pos(line, ch, sticky);
pos.xRel = xRel;
if (outside) { pos.outside = outside; }
return pos
}
// Compute the character position closest to the given coordinates.
// Input must be lineSpace-local ("div" coordinate system).
function coordsChar(cm, x, y) {
var doc = cm.doc;
y += cm.display.viewOffset;
if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }
var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
if (lineN > last)
{ return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }
if (x < 0) { x = 0; }
var lineObj = getLine(doc, lineN);
for (;;) {
var found = coordsCharInner(cm, lineObj, lineN, x, y);
var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));
if (!collapsed) { return found }
var rangeEnd = collapsed.find(1);
if (rangeEnd.line == lineN) { return rangeEnd }
lineObj = getLine(doc, lineN = rangeEnd.line);
}
}
function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
y -= widgetTopHeight(lineObj);
var end = lineObj.text.length;
var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
return {begin: begin, end: end}
}
function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
}
// Returns true if the given side of a box is after the given
// coordinates, in top-to-bottom, left-to-right order.
function boxIsAfter(box, x, y, left) {
return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
}
function coordsCharInner(cm, lineObj, lineNo, x, y) {
// Move y into line-local coordinate space
y -= heightAtLine(lineObj);
var preparedMeasure = prepareMeasureForLine(cm, lineObj);
// When directly calling `measureCharPrepared`, we have to adjust
// for the widgets at this line.
var widgetHeight = widgetTopHeight(lineObj);
var begin = 0, end = lineObj.text.length, ltr = true;
var order = getOrder(lineObj, cm.doc.direction);
// If the line isn't plain left-to-right text, first figure out
// which bidi section the coordinates fall into.
if (order) {
var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
(cm, lineObj, lineNo, preparedMeasure, order, x, y);
ltr = part.level != 1;
// The awkward -1 offsets are needed because findFirst (called
// on these below) will treat its first bound as inclusive,
// second as exclusive, but we want to actually address the
// characters in the part's range
begin = ltr ? part.from : part.to - 1;
end = ltr ? part.to : part.from - 1;
}
// A binary search to find the first character whose bounding box
// starts after the coordinates. If we run across any whose box wrap
// the coordinates, store that.
var chAround = null, boxAround = null;
var ch = findFirst(function (ch) {
var box = measureCharPrepared(cm, preparedMeasure, ch);
box.top += widgetHeight; box.bottom += widgetHeight;
if (!boxIsAfter(box, x, y, false)) { return false }
if (box.top <= y && box.left <= x) {
chAround = ch;
boxAround = box;
}
return true
}, begin, end);
var baseX, sticky, outside = false;
// If a box around the coordinates was found, use that
if (boxAround) {
// Distinguish coordinates nearer to the left or right side of the box
var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
ch = chAround + (atStart ? 0 : 1);
sticky = atStart ? "after" : "before";
baseX = atLeft ? boxAround.left : boxAround.right;
} else {
// (Adjust for extended bound, if necessary.)
if (!ltr && (ch == end || ch == begin)) { ch++; }
// To determine which side to associate with, get the box to the
// left of the character and compare it's vertical position to the
// coordinates
sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
(measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ?
"after" : "before";
// Now get accurate coordinates for this place, in order to get a
// base X position
var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure);
baseX = coords.left;
outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0;
}
ch = skipExtendingChars(lineObj.text, ch, 1);
return PosWithInfo(lineNo, ch, sticky, outside, x - baseX)
}
function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) {
// Bidi parts are sorted left-to-right, and in a non-line-wrapping
// situation, we can take this ordering to correspond to the visual
// ordering. This finds the first part whose end is after the given
// coordinates.
var index = findFirst(function (i) {
var part = order[i], ltr = part.level != 1;
return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"),
"line", lineObj, preparedMeasure), x, y, true)
}, 0, order.length - 1);
var part = order[index];
// If this isn't the first part, the part's start is also after
// the coordinates, and the coordinates aren't on the same line as
// that start, move one part back.
if (index > 0) {
var ltr = part.level != 1;
var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"),
"line", lineObj, preparedMeasure);
if (boxIsAfter(start, x, y, true) && start.top > y)
{ part = order[index - 1]; }
}
return part
}
function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
// In a wrapped line, rtl text on wrapping boundaries can do things
// that don't correspond to the ordering in our `order` array at
// all, so a binary search doesn't work, and we want to return a
// part that only spans one line so that the binary search in
// coordsCharInner is safe. As such, we first find the extent of the
// wrapped line, and then do a flat search in which we discard any
// spans that aren't on the line.
var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
var begin = ref.begin;
var end = ref.end;
if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
var part = null, closestDist = null;
for (var i = 0; i < order.length; i++) {
var p = order[i];
if (p.from >= end || p.to <= begin) { continue }
var ltr = p.level != 1;
var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
// Weigh against spans ending before this, so that they are only
// picked if nothing ends after
var dist = endX < x ? x - endX + 1e9 : endX - x;
if (!part || closestDist > dist) {
part = p;
closestDist = dist;
}
}
if (!part) { part = order[order.length - 1]; }
// Clip the part to the wrapped line.
if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
return part
}
var measureText;
// Compute the default text height.
function textHeight(display) {
if (display.cachedTextHeight != null) { return display.cachedTextHeight }
if (measureText == null) {
measureText = elt("pre", null, "CodeMirror-line-like");
// Measure a bunch of lines, for browsers that compute
// fractional heights.
for (var i = 0; i < 49; ++i) {
measureText.appendChild(document.createTextNode("x"));
measureText.appendChild(elt("br"));
}
measureText.appendChild(document.createTextNode("x"));
}
removeChildrenAndAdd(display.measure, measureText);
var height = measureText.offsetHeight / 50;
if (height > 3) { display.cachedTextHeight = height; }
removeChildren(display.measure);
return height || 1
}
// Compute the default character width.
function charWidth(display) {
if (display.cachedCharWidth != null) { return display.cachedCharWidth }
var anchor = elt("span", "xxxxxxxxxx");
var pre = elt("pre", [anchor], "CodeMirror-line-like");
removeChildrenAndAdd(display.measure, pre);
var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
if (width > 2) { display.cachedCharWidth = width; }
return width || 10
}
// Do a bulk-read of the DOM positions and sizes needed to draw the
// view, so that we don't interleave reading and writing to the DOM.
function getDimensions(cm) {
var d = cm.display, left = {}, width = {};
var gutterLeft = d.gutters.clientLeft;
for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
var id = cm.display.gutterSpecs[i].className;
left[id] = n.offsetLeft + n.clientLeft + gutterLeft;
width[id] = n.clientWidth;
}
return {fixedPos: compensateForHScroll(d),
gutterTotalWidth: d.gutters.offsetWidth,
gutterLeft: left,
gutterWidth: width,
wrapperWidth: d.wrapper.clientWidth}
}
// Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
// but using getBoundingClientRect to get a sub-pixel-accurate
// result.
function compensateForHScroll(display) {
return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
}
// Returns a function that estimates the height of a line, to use as
// first approximation until the line becomes visible (and is thus
// properly measurable).
function estimateHeight(cm) {
var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
return function (line) {
if (lineIsHidden(cm.doc, line)) { return 0 }
var widgetsHeight = 0;
if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
} }
if (wrapping)
{ return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
else
{ return widgetsHeight + th }
}
}
function estimateLineHeights(cm) {
var doc = cm.doc, est = estimateHeight(cm);
doc.iter(function (line) {
var estHeight = est(line);
if (estHeight != line.height) { updateLineHeight(line, estHeight); }
});
}
// Given a mouse event, find the corresponding position. If liberal
// is false, it checks whether a gutter or scrollbar was clicked,
// and returns null if it was. forRect is used by rectangular
// selections, and tries to estimate a character position even for
// coordinates beyond the right of the text.
function posFromMouse(cm, e, liberal, forRect) {
var display = cm.display;
if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
var x, y, space = display.lineSpace.getBoundingClientRect();
// Fails unpredictably on IE[67] when mouse is dragged around quickly.
try { x = e.clientX - space.left; y = e.clientY - space.top; }
catch (e$1) { return null }
var coords = coordsChar(cm, x, y), line;
if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
}
return coords
}
// Find the view element corresponding to a given line. Return null
// when the line isn't visible.
function findViewIndex(cm, n) {
if (n >= cm.display.viewTo) { return null }
n -= cm.display.viewFrom;
if (n < 0) { return null }
var view = cm.display.view;
for (var i = 0; i < view.length; i++) {
n -= view[i].size;
if (n < 0) { return i }
}
}
// Updates the display.view data structure for a given change to the
// document. From and to are in pre-change coordinates. Lendiff is
// the amount of lines added or subtracted by the change. This is
// used for changes that span multiple lines, or change the way
// lines are divided into visual lines. regLineChange (below)
// registers single-line changes.
function regChange(cm, from, to, lendiff) {
if (from == null) { from = cm.doc.first; }
if (to == null) { to = cm.doc.first + cm.doc.size; }
if (!lendiff) { lendiff = 0; }
var display = cm.display;
if (lendiff && to < display.viewTo &&
(display.updateLineNumbers == null || display.updateLineNumbers > from))
{ display.updateLineNumbers = from; }
cm.curOp.viewChanged = true;
if (from >= display.viewTo) { // Change after
if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
{ resetView(cm); }
} else if (to <= display.viewFrom) { // Change before
if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
resetView(cm);
} else {
display.viewFrom += lendiff;
display.viewTo += lendiff;
}
} else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
resetView(cm);
} else if (from <= display.viewFrom) { // Top overlap
var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
if (cut) {
display.view = display.view.slice(cut.index);
display.viewFrom = cut.lineN;
display.viewTo += lendiff;
} else {
resetView(cm);
}
} else if (to >= display.viewTo) { // Bottom overlap
var cut$1 = viewCuttingPoint(cm, from, from, -1);
if (cut$1) {
display.view = display.view.slice(0, cut$1.index);
display.viewTo = cut$1.lineN;
} else {
resetView(cm);
}
} else { // Gap in the middle
var cutTop = viewCuttingPoint(cm, from, from, -1);
var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
if (cutTop && cutBot) {
display.view = display.view.slice(0, cutTop.index)
.concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
.concat(display.view.slice(cutBot.index));
display.viewTo += lendiff;
} else {
resetView(cm);
}
}
var ext = display.externalMeasured;
if (ext) {
if (to < ext.lineN)
{ ext.lineN += lendiff; }
else if (from < ext.lineN + ext.size)
{ display.externalMeasured = null; }
}
}
// Register a change to a single line. Type must be one of "text",
// "gutter", "class", "widget"
function regLineChange(cm, line, type) {
cm.curOp.viewChanged = true;
var display = cm.display, ext = cm.display.externalMeasured;
if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
{ display.externalMeasured = null; }
if (line < display.viewFrom || line >= display.viewTo) { return }
var lineView = display.view[findViewIndex(cm, line)];
if (lineView.node == null) { return }
var arr = lineView.changes || (lineView.changes = []);
if (indexOf(arr, type) == -1) { arr.push(type); }
}
// Clear the view.
function resetView(cm) {
cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
cm.display.view = [];
cm.display.viewOffset = 0;
}
function viewCuttingPoint(cm, oldN, newN, dir) {
var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
{ return {index: index, lineN: newN} }
var n = cm.display.viewFrom;
for (var i = 0; i < index; i++)
{ n += view[i].size; }
if (n != oldN) {
if (dir > 0) {
if (index == view.length - 1) { return null }
diff = (n + view[index].size) - oldN;
index++;
} else {
diff = n - oldN;
}
oldN += diff; newN += diff;
}
while (visualLineNo(cm.doc, newN) != newN) {
if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
index += dir;
}
return {index: index, lineN: newN}
}
// Force the view to cover a given range, adding empty view element
// or clipping off existing ones as needed.
function adjustView(cm, from, to) {
var display = cm.display, view = display.view;
if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
display.view = buildViewArray(cm, from, to);
display.viewFrom = from;
} else {
if (display.viewFrom > from)
{ display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
else if (display.viewFrom < from)
{ display.view = display.view.slice(findViewIndex(cm, from)); }
display.viewFrom = from;
if (display.viewTo < to)
{ display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
else if (display.viewTo > to)
{ display.view = display.view.slice(0, findViewIndex(cm, to)); }
}
display.viewTo = to;
}
// Count the number of lines in the view whose DOM representation is
// out of date (or nonexistent).
function countDirtyView(cm) {
var view = cm.display.view, dirty = 0;
for (var i = 0; i < view.length; i++) {
var lineView = view[i];
if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
}
return dirty
}
function updateSelection(cm) {
cm.display.input.showSelection(cm.display.input.prepareSelection());
}
function prepareSelection(cm, primary) {
if ( primary === void 0 ) primary = true;
var doc = cm.doc, result = {};
var curFragment = result.cursors = document.createDocumentFragment();
var selFragment = result.selection = document.createDocumentFragment();
for (var i = 0; i < doc.sel.ranges.length; i++) {
if (!primary && i == doc.sel.primIndex) { continue }
var range = doc.sel.ranges[i];
if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue }
var collapsed = range.empty();
if (collapsed || cm.options.showCursorWhenSelecting)
{ drawSelectionCursor(cm, range.head, curFragment); }
if (!collapsed)
{ drawSelectionRange(cm, range, selFragment); }
}
return result
}
// Draws a cursor for the given range
function drawSelectionCursor(cm, head, output) {
var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
cursor.style.left = pos.left + "px";
cursor.style.top = pos.top + "px";
cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
if (pos.other) {
// Secondary cursor, shown when on a 'jump' in bi-directional text
var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
otherCursor.style.display = "";
otherCursor.style.left = pos.other.left + "px";
otherCursor.style.top = pos.other.top + "px";
otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
}
}
function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
// Draws the given range as a highlighted selection
function drawSelectionRange(cm, range, output) {
var display = cm.display, doc = cm.doc;
var fragment = document.createDocumentFragment();
var padding = paddingH(cm.display), leftSide = padding.left;
var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
var docLTR = doc.direction == "ltr";
function add(left, top, width, bottom) {
if (top < 0) { top = 0; }
top = Math.round(top);
bottom = Math.round(bottom);
fragment.appendChild(elt("div", null, "CodeMirror-selected", ("position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px")));
}
function drawForLine(line, fromArg, toArg) {
var lineObj = getLine(doc, line);
var lineLen = lineObj.text.length;
var start, end;
function coords(ch, bias) {
return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
}
function wrapX(pos, dir, side) {
var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
return coords(ch, prop)[prop]
}
var order = getOrder(lineObj, doc.direction);
iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
var ltr = dir == "ltr";
var fromPos = coords(from, ltr ? "left" : "right");
var toPos = coords(to - 1, ltr ? "right" : "left");
var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
var first = i == 0, last = !order || i == order.length - 1;
if (toPos.top - fromPos.top <= 3) { // Single line
var openLeft = (docLTR ? openStart : openEnd) && first;
var openRight = (docLTR ? openEnd : openStart) && last;
var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
add(left, fromPos.top, right - left, fromPos.bottom);
} else { // Multiple lines
var topLeft, topRight, botLeft, botRight;
if (ltr) {
topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
topRight = docLTR ? rightSide : wrapX(from, dir, "before");
botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
botRight = docLTR && openEnd && last ? rightSide : toPos.right;
} else {
topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
}
add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
}
if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
if (cmpCoords(toPos, start) < 0) { start = toPos; }
if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
if (cmpCoords(toPos, end) < 0) { end = toPos; }
});
return {start: start, end: end}
}
var sFrom = range.from(), sTo = range.to();
if (sFrom.line == sTo.line) {
drawForLine(sFrom.line, sFrom.ch, sTo.ch);
} else {
var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
var singleVLine = visualLine(fromLine) == visualLine(toLine);
var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
if (singleVLine) {
if (leftEnd.top < rightStart.top - 2) {
add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
} else {
add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
}
}
if (leftEnd.bottom < rightStart.top)
{ add(leftSide, leftEnd.bottom, null, rightStart.top); }
}
output.appendChild(fragment);
}
// Cursor-blinking
function restartBlink(cm) {
if (!cm.state.focused) { return }
var display = cm.display;
clearInterval(display.blinker);
var on = true;
display.cursorDiv.style.visibility = "";
if (cm.options.cursorBlinkRate > 0)
{ display.blinker = setInterval(function () {
if (!cm.hasFocus()) { onBlur(cm); }
display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
}, cm.options.cursorBlinkRate); }
else if (cm.options.cursorBlinkRate < 0)
{ display.cursorDiv.style.visibility = "hidden"; }
}
function ensureFocus(cm) {
if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
}
function delayBlurEvent(cm) {
cm.state.delayingBlurEvent = true;
setTimeout(function () { if (cm.state.delayingBlurEvent) {
cm.state.delayingBlurEvent = false;
onBlur(cm);
} }, 100);
}
function onFocus(cm, e) {
if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; }
if (cm.options.readOnly == "nocursor") { return }
if (!cm.state.focused) {
signal(cm, "focus", cm, e);
cm.state.focused = true;
addClass(cm.display.wrapper, "CodeMirror-focused");
// This test prevents this from firing when a context
// menu is closed (since the input reset would kill the
// select-all detection hack)
if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
cm.display.input.reset();
if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
}
cm.display.input.receivedFocus();
}
restartBlink(cm);
}
function onBlur(cm, e) {
if (cm.state.delayingBlurEvent) { return }
if (cm.state.focused) {
signal(cm, "blur", cm, e);
cm.state.focused = false;
rmClass(cm.display.wrapper, "CodeMirror-focused");
}
clearInterval(cm.display.blinker);
setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
}
// Read the actual heights of the rendered lines, and update their
// stored heights to match.
function updateHeightsInViewport(cm) {
var display = cm.display;
var prevBottom = display.lineDiv.offsetTop;
for (var i = 0; i < display.view.length; i++) {
var cur = display.view[i], wrapping = cm.options.lineWrapping;
var height = (void 0), width = 0;
if (cur.hidden) { continue }
if (ie && ie_version < 8) {
var bot = cur.node.offsetTop + cur.node.offsetHeight;
height = bot - prevBottom;
prevBottom = bot;
} else {
var box = cur.node.getBoundingClientRect();
height = box.bottom - box.top;
// Check that lines don't extend past the right of the current
// editor width
if (!wrapping && cur.text.firstChild)
{ width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; }
}
var diff = cur.line.height - height;
if (diff > .005 || diff < -.005) {
updateLineHeight(cur.line, height);
updateWidgetHeight(cur.line);
if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
{ updateWidgetHeight(cur.rest[j]); } }
}
if (width > cm.display.sizerWidth) {
var chWidth = Math.ceil(width / charWidth(cm.display));
if (chWidth > cm.display.maxLineLength) {
cm.display.maxLineLength = chWidth;
cm.display.maxLine = cur.line;
cm.display.maxLineChanged = true;
}
}
}
}
// Read and store the height of line widgets associated with the
// given line.
function updateWidgetHeight(line) {
if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
var w = line.widgets[i], parent = w.node.parentNode;
if (parent) { w.height = parent.offsetHeight; }
} }
}
// Compute the lines that are visible in a given viewport (defaults
// the the current scroll position). viewport may contain top,
// height, and ensure (see op.scrollToPos) properties.
function visibleLines(display, doc, viewport) {
var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
top = Math.floor(top - paddingTop(display));
var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
// Ensure is a {from: {line, ch}, to: {line, ch}} object, and
// forces those lines into the viewport (if possible).
if (viewport && viewport.ensure) {
var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
if (ensureFrom < from) {
from = ensureFrom;
to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
} else if (Math.min(ensureTo, doc.lastLine()) >= to) {
from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
to = ensureTo;
}
}
return {from: from, to: Math.max(to, from + 1)}
}
// SCROLLING THINGS INTO VIEW
// If an editor sits on the top or bottom of the window, partially
// scrolled out of view, this ensures that the cursor is visible.
function maybeScrollWindow(cm, rect) {
if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
if (rect.top + box.top < 0) { doScroll = true; }
else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }
if (doScroll != null && !phantom) {
var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (rect.left) + "px; width: " + (Math.max(2, rect.right - rect.left)) + "px;"));
cm.display.lineSpace.appendChild(scrollNode);
scrollNode.scrollIntoView(doScroll);
cm.display.lineSpace.removeChild(scrollNode);
}
}
// Scroll a given position into view (immediately), verifying that
// it actually became visible (as line heights are accurately
// measured, the position of something may 'drift' during drawing).
function scrollPosIntoView(cm, pos, end, margin) {
if (margin == null) { margin = 0; }
var rect;
if (!cm.options.lineWrapping && pos == end) {
// Set pos and end to the cursor positions around the character pos sticks to
// If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
// If pos == Pos(_, 0, "before"), pos and end are unchanged
pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
}
for (var limit = 0; limit < 5; limit++) {
var changed = false;
var coords = cursorCoords(cm, pos);
var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
rect = {left: Math.min(coords.left, endCoords.left),
top: Math.min(coords.top, endCoords.top) - margin,
right: Math.max(coords.left, endCoords.left),
bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
var scrollPos = calculateScrollPos(cm, rect);
var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
if (scrollPos.scrollTop != null) {
updateScrollTop(cm, scrollPos.scrollTop);
if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
}
if (scrollPos.scrollLeft != null) {
setScrollLeft(cm, scrollPos.scrollLeft);
if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
}
if (!changed) { break }
}
return rect
}
// Scroll a given set of coordinates into view (immediately).
function scrollIntoView(cm, rect) {
var scrollPos = calculateScrollPos(cm, rect);
if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
}
// Calculate a new scroll position needed to scroll the given
// rectangle into view. Returns an object with scrollTop and
// scrollLeft properties. When these are undefined, the
// vertical/horizontal position does not need to be adjusted.
function calculateScrollPos(cm, rect) {
var display = cm.display, snapMargin = textHeight(cm.display);
if (rect.top < 0) { rect.top = 0; }
var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
var screen = displayHeight(cm), result = {};
if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
var docBottom = cm.doc.height + paddingVert(display);
var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
if (rect.top < screentop) {
result.scrollTop = atTop ? 0 : rect.top;
} else if (rect.bottom > screentop + screen) {
var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
if (newTop != screentop) { result.scrollTop = newTop; }
}
var gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth;
var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace;
var screenw = displayWidth(cm) - display.gutters.offsetWidth;
var tooWide = rect.right - rect.left > screenw;
if (tooWide) { rect.right = rect.left + screenw; }
if (rect.left < 10)
{ result.scrollLeft = 0; }
else if (rect.left < screenleft)
{ result.scrollLeft = Math.max(0, rect.left + gutterSpace - (tooWide ? 0 : 10)); }
else if (rect.right > screenw + screenleft - 3)
{ result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
return result
}
// Store a relative adjustment to the scroll position in the current
// operation (to be applied when the operation finishes).
function addToScrollTop(cm, top) {
if (top == null) { return }
resolveScrollToPos(cm);
cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
}
// Make sure that at the end of the operation the current cursor is
// shown.
function ensureCursorVisible(cm) {
resolveScrollToPos(cm);
var cur = cm.getCursor();
cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
}
function scrollToCoords(cm, x, y) {
if (x != null || y != null) { resolveScrollToPos(cm); }
if (x != null) { cm.curOp.scrollLeft = x; }
if (y != null) { cm.curOp.scrollTop = y; }
}
function scrollToRange(cm, range) {
resolveScrollToPos(cm);
cm.curOp.scrollToPos = range;
}
// When an operation has its scrollToPos property set, and another
// scroll action is applied before the end of the operation, this
// 'simulates' scrolling that position into view in a cheap way, so
// that the effect of intermediate scroll commands is not ignored.
function resolveScrollToPos(cm) {
var range = cm.curOp.scrollToPos;
if (range) {
cm.curOp.scrollToPos = null;
var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
scrollToCoordsRange(cm, from, to, range.margin);
}
}
function scrollToCoordsRange(cm, from, to, margin) {
var sPos = calculateScrollPos(cm, {
left: Math.min(from.left, to.left),
top: Math.min(from.top, to.top) - margin,
right: Math.max(from.right, to.right),
bottom: Math.max(from.bottom, to.bottom) + margin
});
scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
}
// Sync the scrollable area and scrollbars, ensure the viewport
// covers the visible area.
function updateScrollTop(cm, val) {
if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
if (!gecko) { updateDisplaySimple(cm, {top: val}); }
setScrollTop(cm, val, true);
if (gecko) { updateDisplaySimple(cm); }
startWorker(cm, 100);
}
function setScrollTop(cm, val, forceScroll) {
val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val));
if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
cm.doc.scrollTop = val;
cm.display.scrollbars.setScrollTop(val);
if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
}
// Sync scroller and scrollbar, ensure the gutter elements are
// aligned.
function setScrollLeft(cm, val, isScroller, forceScroll) {
val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth));
if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
cm.doc.scrollLeft = val;
alignHorizontally(cm);
if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
cm.display.scrollbars.setScrollLeft(val);
}
// SCROLLBARS
// Prepare DOM reads needed to update the scrollbars. Done in one
// shot to minimize update/measure roundtrips.
function measureForScrollbars(cm) {
var d = cm.display, gutterW = d.gutters.offsetWidth;
var docH = Math.round(cm.doc.height + paddingVert(cm.display));
return {
clientHeight: d.scroller.clientHeight,
viewHeight: d.wrapper.clientHeight,
scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
viewWidth: d.wrapper.clientWidth,
barLeft: cm.options.fixedGutter ? gutterW : 0,
docHeight: docH,
scrollHeight: docH + scrollGap(cm) + d.barHeight,
nativeBarWidth: d.nativeBarWidth,
gutterWidth: gutterW
}
}
var NativeScrollbars = function(place, scroll, cm) {
this.cm = cm;
var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
vert.tabIndex = horiz.tabIndex = -1;
place(vert); place(horiz);
on(vert, "scroll", function () {
if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
});
on(horiz, "scroll", function () {
if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
});
this.checkedZeroWidth = false;
// Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
};
NativeScrollbars.prototype.update = function (measure) {
var needsH = measure.scrollWidth > measure.clientWidth + 1;
var needsV = measure.scrollHeight > measure.clientHeight + 1;
var sWidth = measure.nativeBarWidth;
if (needsV) {
this.vert.style.display = "block";
this.vert.style.bottom = needsH ? sWidth + "px" : "0";
var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
// A bug in IE8 can cause this value to be negative, so guard it.
this.vert.firstChild.style.height =
Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
} else {
this.vert.style.display = "";
this.vert.firstChild.style.height = "0";
}
if (needsH) {
this.horiz.style.display = "block";
this.horiz.style.right = needsV ? sWidth + "px" : "0";
this.horiz.style.left = measure.barLeft + "px";
var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
this.horiz.firstChild.style.width =
Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
} else {
this.horiz.style.display = "";
this.horiz.firstChild.style.width = "0";
}
if (!this.checkedZeroWidth && measure.clientHeight > 0) {
if (sWidth == 0) { this.zeroWidthHack(); }
this.checkedZeroWidth = true;
}
return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
};
NativeScrollbars.prototype.setScrollLeft = function (pos) {
if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
};
NativeScrollbars.prototype.setScrollTop = function (pos) {
if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
};
NativeScrollbars.prototype.zeroWidthHack = function () {
var w = mac && !mac_geMountainLion ? "12px" : "18px";
this.horiz.style.height = this.vert.style.width = w;
this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
this.disableHoriz = new Delayed;
this.disableVert = new Delayed;
};
NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
bar.style.pointerEvents = "auto";
function maybeDisable() {
// To find out whether the scrollbar is still visible, we
// check whether the element under the pixel in the bottom
// right corner of the scrollbar box is the scrollbar box
// itself (when the bar is still visible) or its filler child
// (when the bar is hidden). If it is still visible, we keep
// it enabled, if it's hidden, we disable pointer events.
var box = bar.getBoundingClientRect();
var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
: document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
if (elt != bar) { bar.style.pointerEvents = "none"; }
else { delay.set(1000, maybeDisable); }
}
delay.set(1000, maybeDisable);
};
NativeScrollbars.prototype.clear = function () {
var parent = this.horiz.parentNode;
parent.removeChild(this.horiz);
parent.removeChild(this.vert);
};
var NullScrollbars = function () {};
NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
NullScrollbars.prototype.setScrollLeft = function () {};
NullScrollbars.prototype.setScrollTop = function () {};
NullScrollbars.prototype.clear = function () {};
function updateScrollbars(cm, measure) {
if (!measure) { measure = measureForScrollbars(cm); }
var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
updateScrollbarsInner(cm, measure);
for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
{ updateHeightsInViewport(cm); }
updateScrollbarsInner(cm, measureForScrollbars(cm));
startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
}
}
// Re-synchronize the fake scrollbars with the actual size of the
// content.
function updateScrollbarsInner(cm, measure) {
var d = cm.display;
var sizes = d.scrollbars.update(measure);
d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
if (sizes.right && sizes.bottom) {
d.scrollbarFiller.style.display = "block";
d.scrollbarFiller.style.height = sizes.bottom + "px";
d.scrollbarFiller.style.width = sizes.right + "px";
} else { d.scrollbarFiller.style.display = ""; }
if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
d.gutterFiller.style.display = "block";
d.gutterFiller.style.height = sizes.bottom + "px";
d.gutterFiller.style.width = measure.gutterWidth + "px";
} else { d.gutterFiller.style.display = ""; }
}
var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
function initScrollbars(cm) {
if (cm.display.scrollbars) {
cm.display.scrollbars.clear();
if (cm.display.scrollbars.addClass)
{ rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
}
cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
// Prevent clicks in the scrollbars from killing focus
on(node, "mousedown", function () {
if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
});
node.setAttribute("cm-not-content", "true");
}, function (pos, axis) {
if (axis == "horizontal") { setScrollLeft(cm, pos); }
else { updateScrollTop(cm, pos); }
}, cm);
if (cm.display.scrollbars.addClass)
{ addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
}
// Operations are used to wrap a series of changes to the editor
// state in such a way that each change won't have to update the
// cursor and display (which would be awkward, slow, and
// error-prone). Instead, display updates are batched and then all
// combined and executed at once.
var nextOpId = 0;
// Start a new operation.
function startOperation(cm) {
cm.curOp = {
cm: cm,
viewChanged: false, // Flag that indicates that lines might need to be redrawn
startHeight: cm.doc.height, // Used to detect need to update scrollbar
forceUpdate: false, // Used to force a redraw
updateInput: 0, // Whether to reset the input textarea
typing: false, // Whether this reset should be careful to leave existing text (for compositing)
changeObjs: null, // Accumulated changes, for firing change events
cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
selectionChanged: false, // Whether the selection needs to be redrawn
updateMaxLine: false, // Set when the widest line needs to be determined anew
scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
scrollToPos: null, // Used to scroll to a specific position
focus: false,
id: ++nextOpId // Unique ID
};
pushOperation(cm.curOp);
}
// Finish an operation, updating the display and signalling delayed events
function endOperation(cm) {
var op = cm.curOp;
if (op) { finishOperation(op, function (group) {
for (var i = 0; i < group.ops.length; i++)
{ group.ops[i].cm.curOp = null; }
endOperations(group);
}); }
}
// The DOM updates done when an operation finishes are batched so
// that the minimum number of relayouts are required.
function endOperations(group) {
var ops = group.ops;
for (var i = 0; i < ops.length; i++) // Read DOM
{ endOperation_R1(ops[i]); }
for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
{ endOperation_W1(ops[i$1]); }
for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
{ endOperation_R2(ops[i$2]); }
for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
{ endOperation_W2(ops[i$3]); }
for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
{ endOperation_finish(ops[i$4]); }
}
function endOperation_R1(op) {
var cm = op.cm, display = cm.display;
maybeClipScrollbars(cm);
if (op.updateMaxLine) { findMaxLine(cm); }
op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
op.scrollToPos.to.line >= display.viewTo) ||
display.maxLineChanged && cm.options.lineWrapping;
op.update = op.mustUpdate &&
new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
}
function endOperation_W1(op) {
op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
}
function endOperation_R2(op) {
var cm = op.cm, display = cm.display;
if (op.updatedDisplay) { updateHeightsInViewport(cm); }
op.barMeasure = measureForScrollbars(cm);
// If the max line changed since it was last measured, measure it,
// and ensure the document's width matches it.
// updateDisplay_W2 will use these properties to do the actual resizing
if (display.maxLineChanged && !cm.options.lineWrapping) {
op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
cm.display.sizerWidth = op.adjustWidthTo;
op.barMeasure.scrollWidth =
Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
}
if (op.updatedDisplay || op.selectionChanged)
{ op.preparedSelection = display.input.prepareSelection(); }
}
function endOperation_W2(op) {
var cm = op.cm;
if (op.adjustWidthTo != null) {
cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
if (op.maxScrollLeft < cm.doc.scrollLeft)
{ setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
cm.display.maxLineChanged = false;
}
var takeFocus = op.focus && op.focus == activeElt();
if (op.preparedSelection)
{ cm.display.input.showSelection(op.preparedSelection, takeFocus); }
if (op.updatedDisplay || op.startHeight != cm.doc.height)
{ updateScrollbars(cm, op.barMeasure); }
if (op.updatedDisplay)
{ setDocumentHeight(cm, op.barMeasure); }
if (op.selectionChanged) { restartBlink(cm); }
if (cm.state.focused && op.updateInput)
{ cm.display.input.reset(op.typing); }
if (takeFocus) { ensureFocus(op.cm); }
}
function endOperation_finish(op) {
var cm = op.cm, display = cm.display, doc = cm.doc;
if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
// Abort mouse wheel delta measurement, when scrolling explicitly
if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
{ display.wheelStartX = display.wheelStartY = null; }
// Propagate the scroll position to the actual DOM scroller
if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
// If we need to scroll a specific position into view, do so.
if (op.scrollToPos) {
var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
maybeScrollWindow(cm, rect);
}
// Fire events for markers that are hidden/unidden by editing or
// undoing
var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
if (hidden) { for (var i = 0; i < hidden.length; ++i)
{ if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
{ if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
if (display.wrapper.offsetHeight)
{ doc.scrollTop = cm.display.scroller.scrollTop; }
// Fire change events, and delayed event handlers
if (op.changeObjs)
{ signal(cm, "changes", cm, op.changeObjs); }
if (op.update)
{ op.update.finish(); }
}
// Run the given function in an operation
function runInOp(cm, f) {
if (cm.curOp) { return f() }
startOperation(cm);
try { return f() }
finally { endOperation(cm); }
}
// Wraps a function in an operation. Returns the wrapped function.
function operation(cm, f) {
return function() {
if (cm.curOp) { return f.apply(cm, arguments) }
startOperation(cm);
try { return f.apply(cm, arguments) }
finally { endOperation(cm); }
}
}
// Used to add methods to editor and doc instances, wrapping them in
// operations.
function methodOp(f) {
return function() {
if (this.curOp) { return f.apply(this, arguments) }
startOperation(this);
try { return f.apply(this, arguments) }
finally { endOperation(this); }
}
}
function docMethodOp(f) {
return function() {
var cm = this.cm;
if (!cm || cm.curOp) { return f.apply(this, arguments) }
startOperation(cm);
try { return f.apply(this, arguments) }
finally { endOperation(cm); }
}
}
// HIGHLIGHT WORKER
function startWorker(cm, time) {
if (cm.doc.highlightFrontier < cm.display.viewTo)
{ cm.state.highlight.set(time, bind(highlightWorker, cm)); }
}
function highlightWorker(cm) {
var doc = cm.doc;
if (doc.highlightFrontier >= cm.display.viewTo) { return }
var end = +new Date + cm.options.workTime;
var context = getContextBefore(cm, doc.highlightFrontier);
var changedLines = [];
doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
if (context.line >= cm.display.viewFrom) { // Visible
var oldStyles = line.styles;
var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
var highlighted = highlightLine(cm, line, context, true);
if (resetState) { context.state = resetState; }
line.styles = highlighted.styles;
var oldCls = line.styleClasses, newCls = highlighted.classes;
if (newCls) { line.styleClasses = newCls; }
else if (oldCls) { line.styleClasses = null; }
var ischange = !oldStyles || oldStyles.length != line.styles.length ||
oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
if (ischange) { changedLines.push(context.line); }
line.stateAfter = context.save();
context.nextLine();
} else {
if (line.text.length <= cm.options.maxHighlightLength)
{ processLine(cm, line.text, context); }
line.stateAfter = context.line % 5 == 0 ? context.save() : null;
context.nextLine();
}
if (+new Date > end) {
startWorker(cm, cm.options.workDelay);
return true
}
});
doc.highlightFrontier = context.line;
doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
if (changedLines.length) { runInOp(cm, function () {
for (var i = 0; i < changedLines.length; i++)
{ regLineChange(cm, changedLines[i], "text"); }
}); }
}
// DISPLAY DRAWING
var DisplayUpdate = function(cm, viewport, force) {
var display = cm.display;
this.viewport = viewport;
// Store some values that we'll need later (but don't want to force a relayout for)
this.visible = visibleLines(display, cm.doc, viewport);
this.editorIsHidden = !display.wrapper.offsetWidth;
this.wrapperHeight = display.wrapper.clientHeight;
this.wrapperWidth = display.wrapper.clientWidth;
this.oldDisplayWidth = displayWidth(cm);
this.force = force;
this.dims = getDimensions(cm);
this.events = [];
};
DisplayUpdate.prototype.signal = function (emitter, type) {
if (hasHandler(emitter, type))
{ this.events.push(arguments); }
};
DisplayUpdate.prototype.finish = function () {
for (var i = 0; i < this.events.length; i++)
{ signal.apply(null, this.events[i]); }
};
function maybeClipScrollbars(cm) {
var display = cm.display;
if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
display.heightForcer.style.height = scrollGap(cm) + "px";
display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
display.scrollbarsClipped = true;
}
}
function selectionSnapshot(cm) {
if (cm.hasFocus()) { return null }
var active = activeElt();
if (!active || !contains(cm.display.lineDiv, active)) { return null }
var result = {activeElt: active};
if (window.getSelection) {
var sel = window.getSelection();
if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
result.anchorNode = sel.anchorNode;
result.anchorOffset = sel.anchorOffset;
result.focusNode = sel.focusNode;
result.focusOffset = sel.focusOffset;
}
}
return result
}
function restoreSelection(snapshot) {
if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }
snapshot.activeElt.focus();
if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) &&
snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
var sel = window.getSelection(), range = document.createRange();
range.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
sel.extend(snapshot.focusNode, snapshot.focusOffset);
}
}
// Does the actual updating of the line display. Bails out
// (returning false) when there is nothing to be done and forced is
// false.
function updateDisplayIfNeeded(cm, update) {
var display = cm.display, doc = cm.doc;
if (update.editorIsHidden) {
resetView(cm);
return false
}
// Bail out if the visible area is already rendered and nothing changed.
if (!update.force &&
update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
(display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
display.renderedView == display.view && countDirtyView(cm) == 0)
{ return false }
if (maybeUpdateLineNumberWidth(cm)) {
resetView(cm);
update.dims = getDimensions(cm);
}
// Compute a suitable new viewport (from & to)
var end = doc.first + doc.size;
var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
if (sawCollapsedSpans) {
from = visualLineNo(cm.doc, from);
to = visualLineEndNo(cm.doc, to);
}
var different = from != display.viewFrom || to != display.viewTo ||
display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
adjustView(cm, from, to);
display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
// Position the mover div to align with the current scroll position
cm.display.mover.style.top = display.viewOffset + "px";
var toUpdate = countDirtyView(cm);
if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
(display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
{ return false }
// For big changes, we hide the enclosing element during the
// update, since that speeds up the operations on most browsers.
var selSnapshot = selectionSnapshot(cm);
if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
patchDisplay(cm, display.updateLineNumbers, update.dims);
if (toUpdate > 4) { display.lineDiv.style.display = ""; }
display.renderedView = display.view;
// There might have been a widget with a focused element that got
// hidden or updated, if so re-focus it.
restoreSelection(selSnapshot);
// Prevent selection and cursors from interfering with the scroll
// width and height.
removeChildren(display.cursorDiv);
removeChildren(display.selectionDiv);
display.gutters.style.height = display.sizer.style.minHeight = 0;
if (different) {
display.lastWrapHeight = update.wrapperHeight;
display.lastWrapWidth = update.wrapperWidth;
startWorker(cm, 400);
}
display.updateLineNumbers = null;
return true
}
function postUpdateDisplay(cm, update) {
var viewport = update.viewport;
for (var first = true;; first = false) {
if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
// Clip forced viewport to actual scrollable area.
if (viewport && viewport.top != null)
{ viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
// Updated line heights might result in the drawn area not
// actually covering the viewport. Keep looping until it does.
update.visible = visibleLines(cm.display, cm.doc, viewport);
if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
{ break }
} else if (first) {
update.visible = visibleLines(cm.display, cm.doc, viewport);
}
if (!updateDisplayIfNeeded(cm, update)) { break }
updateHeightsInViewport(cm);
var barMeasure = measureForScrollbars(cm);
updateSelection(cm);
updateScrollbars(cm, barMeasure);
setDocumentHeight(cm, barMeasure);
update.force = false;
}
update.signal(cm, "update", cm);
if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
}
}
function updateDisplaySimple(cm, viewport) {
var update = new DisplayUpdate(cm, viewport);
if (updateDisplayIfNeeded(cm, update)) {
updateHeightsInViewport(cm);
postUpdateDisplay(cm, update);
var barMeasure = measureForScrollbars(cm);
updateSelection(cm);
updateScrollbars(cm, barMeasure);
setDocumentHeight(cm, barMeasure);
update.finish();
}
}
// Sync the actual display DOM structure with display.view, removing
// nodes for lines that are no longer in view, and creating the ones
// that are not there yet, and updating the ones that are out of
// date.
function patchDisplay(cm, updateNumbersFrom, dims) {
var display = cm.display, lineNumbers = cm.options.lineNumbers;
var container = display.lineDiv, cur = container.firstChild;
function rm(node) {
var next = node.nextSibling;
// Works around a throw-scroll bug in OS X Webkit
if (webkit && mac && cm.display.currentWheelTarget == node)
{ node.style.display = "none"; }
else
{ node.parentNode.removeChild(node); }
return next
}
var view = display.view, lineN = display.viewFrom;
// Loop over the elements in the view, syncing cur (the DOM nodes
// in display.lineDiv) with the view as we go.
for (var i = 0; i < view.length; i++) {
var lineView = view[i];
if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
var node = buildLineElement(cm, lineView, lineN, dims);
container.insertBefore(node, cur);
} else { // Already drawn
while (cur != lineView.node) { cur = rm(cur); }
var updateNumber = lineNumbers && updateNumbersFrom != null &&
updateNumbersFrom <= lineN && lineView.lineNumber;
if (lineView.changes) {
if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
updateLineForChanges(cm, lineView, lineN, dims);
}
if (updateNumber) {
removeChildren(lineView.lineNumber);
lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
}
cur = lineView.node.nextSibling;
}
lineN += lineView.size;
}
while (cur) { cur = rm(cur); }
}
function updateGutterSpace(display) {
var width = display.gutters.offsetWidth;
display.sizer.style.marginLeft = width + "px";
}
function setDocumentHeight(cm, measure) {
cm.display.sizer.style.minHeight = measure.docHeight + "px";
cm.display.heightForcer.style.top = measure.docHeight + "px";
cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
}
// Re-align line numbers and gutter marks to compensate for
// horizontal scrolling.
function alignHorizontally(cm) {
var display = cm.display, view = display.view;
if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
var gutterW = display.gutters.offsetWidth, left = comp + "px";
for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
if (cm.options.fixedGutter) {
if (view[i].gutter)
{ view[i].gutter.style.left = left; }
if (view[i].gutterBackground)
{ view[i].gutterBackground.style.left = left; }
}
var align = view[i].alignable;
if (align) { for (var j = 0; j < align.length; j++)
{ align[j].style.left = left; } }
} }
if (cm.options.fixedGutter)
{ display.gutters.style.left = (comp + gutterW) + "px"; }
}
// Used to ensure that the line number gutter is still the right
// size for the current document size. Returns true when an update
// is needed.
function maybeUpdateLineNumberWidth(cm) {
if (!cm.options.lineNumbers) { return false }
var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
if (last.length != display.lineNumChars) {
var test = display.measure.appendChild(elt("div", [elt("div", last)],
"CodeMirror-linenumber CodeMirror-gutter-elt"));
var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
display.lineGutter.style.width = "";
display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
display.lineNumWidth = display.lineNumInnerWidth + padding;
display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
display.lineGutter.style.width = display.lineNumWidth + "px";
updateGutterSpace(cm.display);
return true
}
return false
}
function getGutters(gutters, lineNumbers) {
var result = [], sawLineNumbers = false;
for (var i = 0; i < gutters.length; i++) {
var name = gutters[i], style = null;
if (typeof name != "string") { style = name.style; name = name.className; }
if (name == "CodeMirror-linenumbers") {
if (!lineNumbers) { continue }
else { sawLineNumbers = true; }
}
result.push({className: name, style: style});
}
if (lineNumbers && !sawLineNumbers) { result.push({className: "CodeMirror-linenumbers", style: null}); }
return result
}
// Rebuild the gutter elements, ensure the margin to the left of the
// code matches their width.
function renderGutters(display) {
var gutters = display.gutters, specs = display.gutterSpecs;
removeChildren(gutters);
display.lineGutter = null;
for (var i = 0; i < specs.length; ++i) {
var ref = specs[i];
var className = ref.className;
var style = ref.style;
var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className));
if (style) { gElt.style.cssText = style; }
if (className == "CodeMirror-linenumbers") {
display.lineGutter = gElt;
gElt.style.width = (display.lineNumWidth || 1) + "px";
}
}
gutters.style.display = specs.length ? "" : "none";
updateGutterSpace(display);
}
function updateGutters(cm) {
renderGutters(cm.display);
regChange(cm);
alignHorizontally(cm);
}
// The display handles the DOM integration, both for input reading
// and content drawing. It holds references to DOM nodes and
// display-related state.
function Display(place, doc, input, options) {
var d = this;
this.input = input;
// Covers bottom-right square when both scrollbars are present.
d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
d.scrollbarFiller.setAttribute("cm-not-content", "true");
// Covers bottom of gutter when coverGutterNextToScrollbar is on
// and h scrollbar is present.
d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
d.gutterFiller.setAttribute("cm-not-content", "true");
// Will contain the actual code, positioned to cover the viewport.
d.lineDiv = eltP("div", null, "CodeMirror-code");
// Elements are added to these to represent selection and cursors.
d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
d.cursorDiv = elt("div", null, "CodeMirror-cursors");
// A visibility: hidden element used to find the size of things.
d.measure = elt("div", null, "CodeMirror-measure");
// When lines outside of the viewport are measured, they are drawn in this.
d.lineMeasure = elt("div", null, "CodeMirror-measure");
// Wraps everything that needs to exist inside the vertically-padded coordinate system
d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
null, "position: relative; outline: none");
var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
// Moved around its parent to cover visible view.
d.mover = elt("div", [lines], null, "position: relative");
// Set to the height of the document, allowing scrolling.
d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
d.sizerWidth = null;
// Behavior of elts with overflow: auto and padding is
// inconsistent across browsers. This is used to ensure the
// scrollable area is big enough.
d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
// Will contain the gutters, if any.
d.gutters = elt("div", null, "CodeMirror-gutters");
d.lineGutter = null;
// Actual scrollable element.
d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
d.scroller.setAttribute("tabIndex", "-1");
// The element in which the editor lives.
d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
// Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
if (place) {
if (place.appendChild) { place.appendChild(d.wrapper); }
else { place(d.wrapper); }
}
// Current rendered range (may be bigger than the view window).
d.viewFrom = d.viewTo = doc.first;
d.reportedViewFrom = d.reportedViewTo = doc.first;
// Information about the rendered lines.
d.view = [];
d.renderedView = null;
// Holds info about a single rendered line when it was rendered
// for measurement, while not in view.
d.externalMeasured = null;
// Empty space (in pixels) above the view
d.viewOffset = 0;
d.lastWrapHeight = d.lastWrapWidth = 0;
d.updateLineNumbers = null;
d.nativeBarWidth = d.barHeight = d.barWidth = 0;
d.scrollbarsClipped = false;
// Used to only resize the line number gutter when necessary (when
// the amount of lines crosses a boundary that makes its width change)
d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
// Set to true when a non-horizontal-scrolling line widget is
// added. As an optimization, line widget aligning is skipped when
// this is false.
d.alignWidgets = false;
d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
// Tracks the maximum line length so that the horizontal scrollbar
// can be kept static when scrolling.
d.maxLine = null;
d.maxLineLength = 0;
d.maxLineChanged = false;
// Used for measuring wheel scrolling granularity
d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
// True when shift is held down.
d.shift = false;
// Used to track whether anything happened since the context menu
// was opened.
d.selForContextMenu = null;
d.activeTouch = null;
d.gutterSpecs = getGutters(options.gutters, options.lineNumbers);
renderGutters(d);
input.init(d);
}
// Since the delta values reported on mouse wheel events are
// unstandardized between browsers and even browser versions, and
// generally horribly unpredictable, this code starts by measuring
// the scroll effect that the first few mouse wheel events have,
// and, from that, detects the way it can convert deltas to pixel
// offsets afterwards.
//
// The reason we want to know the amount a wheel event will scroll
// is that it gives us a chance to update the display before the
// actual scrolling happens, reducing flickering.
var wheelSamples = 0, wheelPixelsPerUnit = null;
// Fill in a browser-detected starting value on browsers where we
// know one. These don't have to be accurate -- the result of them
// being wrong would just be a slight flicker on the first wheel
// scroll (if it is large enough).
if (ie) { wheelPixelsPerUnit = -.53; }
else if (gecko) { wheelPixelsPerUnit = 15; }
else if (chrome) { wheelPixelsPerUnit = -.7; }
else if (safari) { wheelPixelsPerUnit = -1/3; }
function wheelEventDelta(e) {
var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
else if (dy == null) { dy = e.wheelDelta; }
return {x: dx, y: dy}
}
function wheelEventPixels(e) {
var delta = wheelEventDelta(e);
delta.x *= wheelPixelsPerUnit;
delta.y *= wheelPixelsPerUnit;
return delta
}
function onScrollWheel(cm, e) {
var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
var display = cm.display, scroll = display.scroller;
// Quit if there's nothing to scroll here
var canScrollX = scroll.scrollWidth > scroll.clientWidth;
var canScrollY = scroll.scrollHeight > scroll.clientHeight;
if (!(dx && canScrollX || dy && canScrollY)) { return }
// Webkit browsers on OS X abort momentum scrolls when the target
// of the scroll event is removed from the scrollable element.
// This hack (see related code in patchDisplay) makes sure the
// element is kept around.
if (dy && mac && webkit) {
outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
for (var i = 0; i < view.length; i++) {
if (view[i].node == cur) {
cm.display.currentWheelTarget = cur;
break outer
}
}
}
}
// On some browsers, horizontal scrolling will cause redraws to
// happen before the gutter has been realigned, causing it to
// wriggle around in a most unseemly way. When we have an
// estimated pixels/delta value, we just handle horizontal
// scrolling entirely here. It'll be slightly off from native, but
// better than glitching out.
if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
if (dy && canScrollY)
{ updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); }
setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit));
// Only prevent default scrolling if vertical scrolling is
// actually possible. Otherwise, it causes vertical scroll
// jitter on OSX trackpads when deltaX is small and deltaY
// is large (issue #3579)
if (!dy || (dy && canScrollY))
{ e_preventDefault(e); }
display.wheelStartX = null; // Abort measurement, if in progress
return
}
// 'Project' the visible viewport to cover the area that is being
// scrolled into view (if we know enough to estimate it).
if (dy && wheelPixelsPerUnit != null) {
var pixels = dy * wheelPixelsPerUnit;
var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
updateDisplaySimple(cm, {top: top, bottom: bot});
}
if (wheelSamples < 20) {
if (display.wheelStartX == null) {
display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
display.wheelDX = dx; display.wheelDY = dy;
setTimeout(function () {
if (display.wheelStartX == null) { return }
var movedX = scroll.scrollLeft - display.wheelStartX;
var movedY = scroll.scrollTop - display.wheelStartY;
var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
(movedX && display.wheelDX && movedX / display.wheelDX);
display.wheelStartX = display.wheelStartY = null;
if (!sample) { return }
wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
++wheelSamples;
}, 200);
} else {
display.wheelDX += dx; display.wheelDY += dy;
}
}
}
// Selection objects are immutable. A new one is created every time
// the selection changes. A selection is one or more non-overlapping
// (and non-touching) ranges, sorted, and an integer that indicates
// which one is the primary selection (the one that's scrolled into
// view, that getCursor returns, etc).
var Selection = function(ranges, primIndex) {
this.ranges = ranges;
this.primIndex = primIndex;
};
Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
Selection.prototype.equals = function (other) {
if (other == this) { return true }
if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
for (var i = 0; i < this.ranges.length; i++) {
var here = this.ranges[i], there = other.ranges[i];
if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
}
return true
};
Selection.prototype.deepCopy = function () {
var out = [];
for (var i = 0; i < this.ranges.length; i++)
{ out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); }
return new Selection(out, this.primIndex)
};
Selection.prototype.somethingSelected = function () {
for (var i = 0; i < this.ranges.length; i++)
{ if (!this.ranges[i].empty()) { return true } }
return false
};
Selection.prototype.contains = function (pos, end) {
if (!end) { end = pos; }
for (var i = 0; i < this.ranges.length; i++) {
var range = this.ranges[i];
if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
{ return i }
}
return -1
};
var Range = function(anchor, head) {
this.anchor = anchor; this.head = head;
};
Range.prototype.from = function () { return minPos(this.anchor, this.head) };
Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
// Take an unsorted, potentially overlapping set of ranges, and
// build a selection out of it. 'Consumes' ranges array (modifying
// it).
function normalizeSelection(cm, ranges, primIndex) {
var mayTouch = cm && cm.options.selectionsMayTouch;
var prim = ranges[primIndex];
ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
primIndex = indexOf(ranges, prim);
for (var i = 1; i < ranges.length; i++) {
var cur = ranges[i], prev = ranges[i - 1];
var diff = cmp(prev.to(), cur.from());
if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {
var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
if (i <= primIndex) { --primIndex; }
ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
}
}
return new Selection(ranges, primIndex)
}
function simpleSelection(anchor, head) {
return new Selection([new Range(anchor, head || anchor)], 0)
}
// Compute the position of the end of a change (its 'to' property
// refers to the pre-change end).
function changeEnd(change) {
if (!change.text) { return change.to }
return Pos(change.from.line + change.text.length - 1,
lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
}
// Adjust a position to refer to the post-change position of the
// same text, or the end of the change if the change covers it.
function adjustForChange(pos, change) {
if (cmp(pos, change.from) < 0) { return pos }
if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
return Pos(line, ch)
}
function computeSelAfterChange(doc, change) {
var out = [];
for (var i = 0; i < doc.sel.ranges.length; i++) {
var range = doc.sel.ranges[i];
out.push(new Range(adjustForChange(range.anchor, change),
adjustForChange(range.head, change)));
}
return normalizeSelection(doc.cm, out, doc.sel.primIndex)
}
function offsetPos(pos, old, nw) {
if (pos.line == old.line)
{ return Pos(nw.line, pos.ch - old.ch + nw.ch) }
else
{ return Pos(nw.line + (pos.line - old.line), pos.ch) }
}
// Used by replaceSelections to allow moving the selection to the
// start or around the replaced test. Hint may be "start" or "around".
function computeReplacedSel(doc, changes, hint) {
var out = [];
var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
for (var i = 0; i < changes.length; i++) {
var change = changes[i];
var from = offsetPos(change.from, oldPrev, newPrev);
var to = offsetPos(changeEnd(change), oldPrev, newPrev);
oldPrev = change.to;
newPrev = to;
if (hint == "around") {
var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
out[i] = new Range(inv ? to : from, inv ? from : to);
} else {
out[i] = new Range(from, from);
}
}
return new Selection(out, doc.sel.primIndex)
}
// Used to get the editor into a consistent state again when options change.
function loadMode(cm) {
cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
resetModeState(cm);
}
function resetModeState(cm) {
cm.doc.iter(function (line) {
if (line.stateAfter) { line.stateAfter = null; }
if (line.styles) { line.styles = null; }
});
cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
startWorker(cm, 100);
cm.state.modeGen++;
if (cm.curOp) { regChange(cm); }
}
// DOCUMENT DATA STRUCTURE
// By default, updates that start and end at the beginning of a line
// are treated specially, in order to make the association of line
// widgets and marker elements with the text behave more intuitive.
function isWholeLineUpdate(doc, change) {
return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
(!doc.cm || doc.cm.options.wholeLineUpdateBefore)
}
// Perform a change on the document data structure.
function updateDoc(doc, change, markedSpans, estimateHeight) {
function spansFor(n) {return markedSpans ? markedSpans[n] : null}
function update(line, text, spans) {
updateLine(line, text, spans, estimateHeight);
signalLater(line, "change", line, change);
}
function linesFor(start, end) {
var result = [];
for (var i = start; i < end; ++i)
{ result.push(new Line(text[i], spansFor(i), estimateHeight)); }
return result
}
var from = change.from, to = change.to, text = change.text;
var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
// Adjust the line structure
if (change.full) {
doc.insert(0, linesFor(0, text.length));
doc.remove(text.length, doc.size - text.length);
} else if (isWholeLineUpdate(doc, change)) {
// This is a whole-line replace. Treated specially to make
// sure line objects move the way they are supposed to.
var added = linesFor(0, text.length - 1);
update(lastLine, lastLine.text, lastSpans);
if (nlines) { doc.remove(from.line, nlines); }
if (added.length) { doc.insert(from.line, added); }
} else if (firstLine == lastLine) {
if (text.length == 1) {
update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
} else {
var added$1 = linesFor(1, text.length - 1);
added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
doc.insert(from.line + 1, added$1);
}
} else if (text.length == 1) {
update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
doc.remove(from.line + 1, nlines);
} else {
update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
var added$2 = linesFor(1, text.length - 1);
if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
doc.insert(from.line + 1, added$2);
}
signalLater(doc, "change", doc, change);
}
// Call f for all linked documents.
function linkedDocs(doc, f, sharedHistOnly) {
function propagate(doc, skip, sharedHist) {
if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
var rel = doc.linked[i];
if (rel.doc == skip) { continue }
var shared = sharedHist && rel.sharedHist;
if (sharedHistOnly && !shared) { continue }
f(rel.doc, shared);
propagate(rel.doc, doc, shared);
} }
}
propagate(doc, null, true);
}
// Attach a document to an editor.
function attachDoc(cm, doc) {
if (doc.cm) { throw new Error("This document is already in use.") }
cm.doc = doc;
doc.cm = cm;
estimateLineHeights(cm);
loadMode(cm);
setDirectionClass(cm);
if (!cm.options.lineWrapping) { findMaxLine(cm); }
cm.options.mode = doc.modeOption;
regChange(cm);
}
function setDirectionClass(cm) {
(cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
}
function directionChanged(cm) {
runInOp(cm, function () {
setDirectionClass(cm);
regChange(cm);
});
}
function History(startGen) {
// Arrays of change events and selections. Doing something adds an
// event to done and clears undo. Undoing moves events from done
// to undone, redoing moves them in the other direction.
this.done = []; this.undone = [];
this.undoDepth = Infinity;
// Used to track when changes can be merged into a single undo
// event
this.lastModTime = this.lastSelTime = 0;
this.lastOp = this.lastSelOp = null;
this.lastOrigin = this.lastSelOrigin = null;
// Used by the isClean() method
this.generation = this.maxGeneration = startGen || 1;
}
// Create a history change event from an updateDoc-style change
// object.
function historyChangeFromChange(doc, change) {
var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
return histChange
}
// Pop all selection events off the end of a history array. Stop at
// a change event.
function clearSelectionEvents(array) {
while (array.length) {
var last = lst(array);
if (last.ranges) { array.pop(); }
else { break }
}
}
// Find the top change event in the history. Pop off selection
// events that are in the way.
function lastChangeEvent(hist, force) {
if (force) {
clearSelectionEvents(hist.done);
return lst(hist.done)
} else if (hist.done.length && !lst(hist.done).ranges) {
return lst(hist.done)
} else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
hist.done.pop();
return lst(hist.done)
}
}
// Register a change in the history. Merges changes that are within
// a single operation, or are close together with an origin that
// allows merging (starting with "+") into a single event.
function addChangeToHistory(doc, change, selAfter, opId) {
var hist = doc.history;
hist.undone.length = 0;
var time = +new Date, cur;
var last;
if ((hist.lastOp == opId ||
hist.lastOrigin == change.origin && change.origin &&
((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||
change.origin.charAt(0) == "*")) &&
(cur = lastChangeEvent(hist, hist.lastOp == opId))) {
// Merge this change into the last event
last = lst(cur.changes);
if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
// Optimized case for simple insertion -- don't want to add
// new changesets for every character typed
last.to = changeEnd(change);
} else {
// Add new sub-event
cur.changes.push(historyChangeFromChange(doc, change));
}
} else {
// Can not be merged, start a new event.
var before = lst(hist.done);
if (!before || !before.ranges)
{ pushSelectionToHistory(doc.sel, hist.done); }
cur = {changes: [historyChangeFromChange(doc, change)],
generation: hist.generation};
hist.done.push(cur);
while (hist.done.length > hist.undoDepth) {
hist.done.shift();
if (!hist.done[0].ranges) { hist.done.shift(); }
}
}
hist.done.push(selAfter);
hist.generation = ++hist.maxGeneration;
hist.lastModTime = hist.lastSelTime = time;
hist.lastOp = hist.lastSelOp = opId;
hist.lastOrigin = hist.lastSelOrigin = change.origin;
if (!last) { signal(doc, "historyAdded"); }
}
function selectionEventCanBeMerged(doc, origin, prev, sel) {
var ch = origin.charAt(0);
return ch == "*" ||
ch == "+" &&
prev.ranges.length == sel.ranges.length &&
prev.somethingSelected() == sel.somethingSelected() &&
new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
}
// Called whenever the selection changes, sets the new selection as
// the pending selection in the history, and pushes the old pending
// selection into the 'done' array when it was significantly
// different (in number of selected ranges, emptiness, or time).
function addSelectionToHistory(doc, sel, opId, options) {
var hist = doc.history, origin = options && options.origin;
// A new event is started when the previous origin does not match
// the current, or the origins don't allow matching. Origins
// starting with * are always merged, those starting with + are
// merged when similar and close together in time.
if (opId == hist.lastSelOp ||
(origin && hist.lastSelOrigin == origin &&
(hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
{ hist.done[hist.done.length - 1] = sel; }
else
{ pushSelectionToHistory(sel, hist.done); }
hist.lastSelTime = +new Date;
hist.lastSelOrigin = origin;
hist.lastSelOp = opId;
if (options && options.clearRedo !== false)
{ clearSelectionEvents(hist.undone); }
}
function pushSelectionToHistory(sel, dest) {
var top = lst(dest);
if (!(top && top.ranges && top.equals(sel)))
{ dest.push(sel); }
}
// Used to store marked span information in the history.
function attachLocalSpans(doc, change, from, to) {
var existing = change["spans_" + doc.id], n = 0;
doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
if (line.markedSpans)
{ (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
++n;
});
}
// When un/re-doing restores text containing marked spans, those
// that have been explicitly cleared should not be restored.
function removeClearedSpans(spans) {
if (!spans) { return null }
var out;
for (var i = 0; i < spans.length; ++i) {
if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
else if (out) { out.push(spans[i]); }
}
return !out ? spans : out.length ? out : null
}
// Retrieve and filter the old marked spans stored in a change event.
function getOldSpans(doc, change) {
var found = change["spans_" + doc.id];
if (!found) { return null }
var nw = [];
for (var i = 0; i < change.text.length; ++i)
{ nw.push(removeClearedSpans(found[i])); }
return nw
}
// Used for un/re-doing changes from the history. Combines the
// result of computing the existing spans with the set of spans that
// existed in the history (so that deleting around a span and then
// undoing brings back the span).
function mergeOldSpans(doc, change) {
var old = getOldSpans(doc, change);
var stretched = stretchSpansOverChange(doc, change);
if (!old) { return stretched }
if (!stretched) { return old }
for (var i = 0; i < old.length; ++i) {
var oldCur = old[i], stretchCur = stretched[i];
if (oldCur && stretchCur) {
spans: for (var j = 0; j < stretchCur.length; ++j) {
var span = stretchCur[j];
for (var k = 0; k < oldCur.length; ++k)
{ if (oldCur[k].marker == span.marker) { continue spans } }
oldCur.push(span);
}
} else if (stretchCur) {
old[i] = stretchCur;
}
}
return old
}
// Used both to provide a JSON-safe object in .getHistory, and, when
// detaching a document, to split the history in two
function copyHistoryArray(events, newGroup, instantiateSel) {
var copy = [];
for (var i = 0; i < events.length; ++i) {
var event = events[i];
if (event.ranges) {
copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
continue
}
var changes = event.changes, newChanges = [];
copy.push({changes: newChanges});
for (var j = 0; j < changes.length; ++j) {
var change = changes[j], m = (void 0);
newChanges.push({from: change.from, to: change.to, text: change.text});
if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
if (indexOf(newGroup, Number(m[1])) > -1) {
lst(newChanges)[prop] = change[prop];
delete change[prop];
}
} } }
}
}
return copy
}
// The 'scroll' parameter given to many of these indicated whether
// the new cursor position should be scrolled into view after
// modifying the selection.
// If shift is held or the extend flag is set, extends a range to
// include a given position (and optionally a second position).
// Otherwise, simply returns the range between the given positions.
// Used for cursor motion and such.
function extendRange(range, head, other, extend) {
if (extend) {
var anchor = range.anchor;
if (other) {
var posBefore = cmp(head, anchor) < 0;
if (posBefore != (cmp(other, anchor) < 0)) {
anchor = head;
head = other;
} else if (posBefore != (cmp(head, other) < 0)) {
head = other;
}
}
return new Range(anchor, head)
} else {
return new Range(other || head, head)
}
}
// Extend the primary selection range, discard the rest.
function extendSelection(doc, head, other, options, extend) {
if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
}
// Extend all selections (pos is an array of selections with length
// equal the number of selections)
function extendSelections(doc, heads, options) {
var out = [];
var extend = doc.cm && (doc.cm.display.shift || doc.extend);
for (var i = 0; i < doc.sel.ranges.length; i++)
{ out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex);
setSelection(doc, newSel, options);
}
// Updates a single range in the selection.
function replaceOneSelection(doc, i, range, options) {
var ranges = doc.sel.ranges.slice(0);
ranges[i] = range;
setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options);
}
// Reset the selection to a single range.
function setSimpleSelection(doc, anchor, head, options) {
setSelection(doc, simpleSelection(anchor, head), options);
}
// Give beforeSelectionChange handlers a change to influence a
// selection update.
function filterSelectionChange(doc, sel, options) {
var obj = {
ranges: sel.ranges,
update: function(ranges) {
this.ranges = [];
for (var i = 0; i < ranges.length; i++)
{ this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
clipPos(doc, ranges[i].head)); }
},
origin: options && options.origin
};
signal(doc, "beforeSelectionChange", doc, obj);
if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) }
else { return sel }
}
function setSelectionReplaceHistory(doc, sel, options) {
var done = doc.history.done, last = lst(done);
if (last && last.ranges) {
done[done.length - 1] = sel;
setSelectionNoUndo(doc, sel, options);
} else {
setSelection(doc, sel, options);
}
}
// Set a new selection.
function setSelection(doc, sel, options) {
setSelectionNoUndo(doc, sel, options);
addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
}
function setSelectionNoUndo(doc, sel, options) {
if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
{ sel = filterSelectionChange(doc, sel, options); }
var bias = options && options.bias ||
(cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
if (!(options && options.scroll === false) && doc.cm)
{ ensureCursorVisible(doc.cm); }
}
function setSelectionInner(doc, sel) {
if (sel.equals(doc.sel)) { return }
doc.sel = sel;
if (doc.cm) {
doc.cm.curOp.updateInput = 1;
doc.cm.curOp.selectionChanged = true;
signalCursorActivity(doc.cm);
}
signalLater(doc, "cursorActivity", doc);
}
// Verify that the selection does not partially select any atomic
// marked ranges.
function reCheckSelection(doc) {
setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
}
// Return a selection that does not partially select any atomic
// ranges.
function skipAtomicInSelection(doc, sel, bias, mayClear) {
var out;
for (var i = 0; i < sel.ranges.length; i++) {
var range = sel.ranges[i];
var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
if (out || newAnchor != range.anchor || newHead != range.head) {
if (!out) { out = sel.ranges.slice(0, i); }
out[i] = new Range(newAnchor, newHead);
}
}
return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel
}
function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
var line = getLine(doc, pos.line);
if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
var sp = line.markedSpans[i], m = sp.marker;
// Determine if we should prevent the cursor being placed to the left/right of an atomic marker
// Historically this was determined using the inclusiveLeft/Right option, but the new way to control it
// is with selectLeft/Right
var preventCursorLeft = ("selectLeft" in m) ? !m.selectLeft : m.inclusiveLeft;
var preventCursorRight = ("selectRight" in m) ? !m.selectRight : m.inclusiveRight;
if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
(sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
if (mayClear) {
signal(m, "beforeCursorEnter");
if (m.explicitlyCleared) {
if (!line.markedSpans) { break }
else {--i; continue}
}
}
if (!m.atomic) { continue }
if (oldPos) {
var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
if (dir < 0 ? preventCursorRight : preventCursorLeft)
{ near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
{ return skipAtomicInner(doc, near, pos, dir, mayClear) }
}
var far = m.find(dir < 0 ? -1 : 1);
if (dir < 0 ? preventCursorLeft : preventCursorRight)
{ far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
}
} }
return pos
}
// Ensure a given position is not inside an atomic range.
function skipAtomic(doc, pos, oldPos, bias, mayClear) {
var dir = bias || 1;
var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
(!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
(!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
if (!found) {
doc.cantEdit = true;
return Pos(doc.first, 0)
}
return found
}
function movePos(doc, pos, dir, line) {
if (dir < 0 && pos.ch == 0) {
if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
else { return null }
} else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
else { return null }
} else {
return new Pos(pos.line, pos.ch + dir)
}
}
function selectAll(cm) {
cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
}
// UPDATING
// Allow "beforeChange" event handlers to influence a change
function filterChange(doc, change, update) {
var obj = {
canceled: false,
from: change.from,
to: change.to,
text: change.text,
origin: change.origin,
cancel: function () { return obj.canceled = true; }
};
if (update) { obj.update = function (from, to, text, origin) {
if (from) { obj.from = clipPos(doc, from); }
if (to) { obj.to = clipPos(doc, to); }
if (text) { obj.text = text; }
if (origin !== undefined) { obj.origin = origin; }
}; }
signal(doc, "beforeChange", doc, obj);
if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
if (obj.canceled) {
if (doc.cm) { doc.cm.curOp.updateInput = 2; }
return null
}
return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
}
// Apply a change to a document, and add it to the document's
// history, and propagating it to all linked documents.
function makeChange(doc, change, ignoreReadOnly) {
if (doc.cm) {
if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
if (doc.cm.state.suppressEdits) { return }
}
if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
change = filterChange(doc, change, true);
if (!change) { return }
}
// Possibly split or suppress the update based on the presence
// of read-only spans in its range.
var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
if (split) {
for (var i = split.length - 1; i >= 0; --i)
{ makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); }
} else {
makeChangeInner(doc, change);
}
}
function makeChangeInner(doc, change) {
if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
var selAfter = computeSelAfterChange(doc, change);
addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
var rebased = [];
linkedDocs(doc, function (doc, sharedHist) {
if (!sharedHist && indexOf(rebased, doc.history) == -1) {
rebaseHist(doc.history, change);
rebased.push(doc.history);
}
makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
});
}
// Revert a change stored in a document's history.
function makeChangeFromHistory(doc, type, allowSelectionOnly) {
var suppress = doc.cm && doc.cm.state.suppressEdits;
if (suppress && !allowSelectionOnly) { return }
var hist = doc.history, event, selAfter = doc.sel;
var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
// Verify that there is a useable event (so that ctrl-z won't
// needlessly clear selection events)
var i = 0;
for (; i < source.length; i++) {
event = source[i];
if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
{ break }
}
if (i == source.length) { return }
hist.lastOrigin = hist.lastSelOrigin = null;
for (;;) {
event = source.pop();
if (event.ranges) {
pushSelectionToHistory(event, dest);
if (allowSelectionOnly && !event.equals(doc.sel)) {
setSelection(doc, event, {clearRedo: false});
return
}
selAfter = event;
} else if (suppress) {
source.push(event);
return
} else { break }
}
// Build up a reverse change object to add to the opposite history
// stack (redo when undoing, and vice versa).
var antiChanges = [];
pushSelectionToHistory(selAfter, dest);
dest.push({changes: antiChanges, generation: hist.generation});
hist.generation = event.generation || ++hist.maxGeneration;
var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
var loop = function ( i ) {
var change = event.changes[i];
change.origin = type;
if (filter && !filterChange(doc, change, false)) {
source.length = 0;
return {}
}
antiChanges.push(historyChangeFromChange(doc, change));
var after = i ? computeSelAfterChange(doc, change) : lst(source);
makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
var rebased = [];
// Propagate to the linked documents
linkedDocs(doc, function (doc, sharedHist) {
if (!sharedHist && indexOf(rebased, doc.history) == -1) {
rebaseHist(doc.history, change);
rebased.push(doc.history);
}
makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
});
};
for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
var returned = loop( i$1 );
if ( returned ) return returned.v;
}
}
// Sub-views need their line numbers shifted when text is added
// above or below them in the parent document.
function shiftDoc(doc, distance) {
if (distance == 0) { return }
doc.first += distance;
doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
Pos(range.anchor.line + distance, range.anchor.ch),
Pos(range.head.line + distance, range.head.ch)
); }), doc.sel.primIndex);
if (doc.cm) {
regChange(doc.cm, doc.first, doc.first - distance, distance);
for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
{ regLineChange(doc.cm, l, "gutter"); }
}
}
// More lower-level change function, handling only a single document
// (not linked ones).
function makeChangeSingleDoc(doc, change, selAfter, spans) {
if (doc.cm && !doc.cm.curOp)
{ return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
if (change.to.line < doc.first) {
shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
return
}
if (change.from.line > doc.lastLine()) { return }
// Clip the change to the size of this doc
if (change.from.line < doc.first) {
var shift = change.text.length - 1 - (doc.first - change.from.line);
shiftDoc(doc, shift);
change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
text: [lst(change.text)], origin: change.origin};
}
var last = doc.lastLine();
if (change.to.line > last) {
change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
text: [change.text[0]], origin: change.origin};
}
change.removed = getBetween(doc, change.from, change.to);
if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
else { updateDoc(doc, change, spans); }
setSelectionNoUndo(doc, selAfter, sel_dontScroll);
if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0)))
{ doc.cantEdit = false; }
}
// Handle the interaction of a change to a document with the editor
// that this document is part of.
function makeChangeSingleDocInEditor(cm, change, spans) {
var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
var recomputeMaxLength = false, checkWidthStart = from.line;
if (!cm.options.lineWrapping) {
checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
doc.iter(checkWidthStart, to.line + 1, function (line) {
if (line == display.maxLine) {
recomputeMaxLength = true;
return true
}
});
}
if (doc.sel.contains(change.from, change.to) > -1)
{ signalCursorActivity(cm); }
updateDoc(doc, change, spans, estimateHeight(cm));
if (!cm.options.lineWrapping) {
doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
var len = lineLength(line);
if (len > display.maxLineLength) {
display.maxLine = line;
display.maxLineLength = len;
display.maxLineChanged = true;
recomputeMaxLength = false;
}
});
if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
}
retreatFrontier(doc, from.line);
startWorker(cm, 400);
var lendiff = change.text.length - (to.line - from.line) - 1;
// Remember that these lines changed, for updating the display
if (change.full)
{ regChange(cm); }
else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
{ regLineChange(cm, from.line, "text"); }
else
{ regChange(cm, from.line, to.line + 1, lendiff); }
var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
if (changeHandler || changesHandler) {
var obj = {
from: from, to: to,
text: change.text,
removed: change.removed,
origin: change.origin
};
if (changeHandler) { signalLater(cm, "change", cm, obj); }
if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
}
cm.display.selForContextMenu = null;
}
function replaceRange(doc, code, from, to, origin) {
var assign;
if (!to) { to = from; }
if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); }
if (typeof code == "string") { code = doc.splitLines(code); }
makeChange(doc, {from: from, to: to, text: code, origin: origin});
}
// Rebasing/resetting history to deal with externally-sourced changes
function rebaseHistSelSingle(pos, from, to, diff) {
if (to < pos.line) {
pos.line += diff;
} else if (from < pos.line) {
pos.line = from;
pos.ch = 0;
}
}
// Tries to rebase an array of history events given a change in the
// document. If the change touches the same lines as the event, the
// event, and everything 'behind' it, is discarded. If the change is
// before the event, the event's positions are updated. Uses a
// copy-on-write scheme for the positions, to avoid having to
// reallocate them all on every rebase, but also avoid problems with
// shared position objects being unsafely updated.
function rebaseHistArray(array, from, to, diff) {
for (var i = 0; i < array.length; ++i) {
var sub = array[i], ok = true;
if (sub.ranges) {
if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
for (var j = 0; j < sub.ranges.length; j++) {
rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
}
continue
}
for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
var cur = sub.changes[j$1];
if (to < cur.from.line) {
cur.from = Pos(cur.from.line + diff, cur.from.ch);
cur.to = Pos(cur.to.line + diff, cur.to.ch);
} else if (from <= cur.to.line) {
ok = false;
break
}
}
if (!ok) {
array.splice(0, i + 1);
i = 0;
}
}
}
function rebaseHist(hist, change) {
var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
rebaseHistArray(hist.done, from, to, diff);
rebaseHistArray(hist.undone, from, to, diff);
}
// Utility for applying a change to a line by handle or number,
// returning the number and optionally registering the line as
// changed.
function changeLine(doc, handle, changeType, op) {
var no = handle, line = handle;
if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
else { no = lineNo(handle); }
if (no == null) { return null }
if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
return line
}
// The document is represented as a BTree consisting of leaves, with
// chunk of lines in them, and branches, with up to ten leaves or
// other branch nodes below them. The top node is always a branch
// node, and is the document object itself (meaning it has
// additional methods and properties).
//
// All nodes have parent links. The tree is used both to go from
// line numbers to line objects, and to go from objects to numbers.
// It also indexes by height, and is used to convert between height
// and line object, and to find the total height of the document.
//
// See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
function LeafChunk(lines) {
this.lines = lines;
this.parent = null;
var height = 0;
for (var i = 0; i < lines.length; ++i) {
lines[i].parent = this;
height += lines[i].height;
}
this.height = height;
}
LeafChunk.prototype = {
chunkSize: function() { return this.lines.length },
// Remove the n lines at offset 'at'.
removeInner: function(at, n) {
for (var i = at, e = at + n; i < e; ++i) {
var line = this.lines[i];
this.height -= line.height;
cleanUpLine(line);
signalLater(line, "delete");
}
this.lines.splice(at, n);
},
// Helper used to collapse a small branch into a single leaf.
collapse: function(lines) {
lines.push.apply(lines, this.lines);
},
// Insert the given array of lines at offset 'at', count them as
// having the given height.
insertInner: function(at, lines, height) {
this.height += height;
this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
for (var i = 0; i < lines.length; ++i) { lines[i].parent = this; }
},
// Used to iterate over a part of the tree.
iterN: function(at, n, op) {
for (var e = at + n; at < e; ++at)
{ if (op(this.lines[at])) { return true } }
}
};
function BranchChunk(children) {
this.children = children;
var size = 0, height = 0;
for (var i = 0; i < children.length; ++i) {
var ch = children[i];
size += ch.chunkSize(); height += ch.height;
ch.parent = this;
}
this.size = size;
this.height = height;
this.parent = null;
}
BranchChunk.prototype = {
chunkSize: function() { return this.size },
removeInner: function(at, n) {
this.size -= n;
for (var i = 0; i < this.children.length; ++i) {
var child = this.children[i], sz = child.chunkSize();
if (at < sz) {
var rm = Math.min(n, sz - at), oldHeight = child.height;
child.removeInner(at, rm);
this.height -= oldHeight - child.height;
if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
if ((n -= rm) == 0) { break }
at = 0;
} else { at -= sz; }
}
// If the result is smaller than 25 lines, ensure that it is a
// single leaf node.
if (this.size - n < 25 &&
(this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
var lines = [];
this.collapse(lines);
this.children = [new LeafChunk(lines)];
this.children[0].parent = this;
}
},
collapse: function(lines) {
for (var i = 0; i < this.children.length; ++i) { this.children[i].collapse(lines); }
},
insertInner: function(at, lines, height) {
this.size += lines.length;
this.height += height;
for (var i = 0; i < this.children.length; ++i) {
var child = this.children[i], sz = child.chunkSize();
if (at <= sz) {
child.insertInner(at, lines, height);
if (child.lines && child.lines.length > 50) {
// To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
// Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
var remaining = child.lines.length % 25 + 25;
for (var pos = remaining; pos < child.lines.length;) {
var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
child.height -= leaf.height;
this.children.splice(++i, 0, leaf);
leaf.parent = this;
}
child.lines = child.lines.slice(0, remaining);
this.maybeSpill();
}
break
}
at -= sz;
}
},
// When a node has grown, check whether it should be split.
maybeSpill: function() {
if (this.children.length <= 10) { return }
var me = this;
do {
var spilled = me.children.splice(me.children.length - 5, 5);
var sibling = new BranchChunk(spilled);
if (!me.parent) { // Become the parent node
var copy = new BranchChunk(me.children);
copy.parent = me;
me.children = [copy, sibling];
me = copy;
} else {
me.size -= sibling.size;
me.height -= sibling.height;
var myIndex = indexOf(me.parent.children, me);
me.parent.children.splice(myIndex + 1, 0, sibling);
}
sibling.parent = me.parent;
} while (me.children.length > 10)
me.parent.maybeSpill();
},
iterN: function(at, n, op) {
for (var i = 0; i < this.children.length; ++i) {
var child = this.children[i], sz = child.chunkSize();
if (at < sz) {
var used = Math.min(n, sz - at);
if (child.iterN(at, used, op)) { return true }
if ((n -= used) == 0) { break }
at = 0;
} else { at -= sz; }
}
}
};
// Line widgets are block elements displayed above or below a line.
var LineWidget = function(doc, node, options) {
if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
{ this[opt] = options[opt]; } } }
this.doc = doc;
this.node = node;
};
LineWidget.prototype.clear = function () {
var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
if (no == null || !ws) { return }
for (var i = 0; i < ws.length; ++i) { if (ws[i] == this) { ws.splice(i--, 1); } }
if (!ws.length) { line.widgets = null; }
var height = widgetHeight(this);
updateLineHeight(line, Math.max(0, line.height - height));
if (cm) {
runInOp(cm, function () {
adjustScrollWhenAboveVisible(cm, line, -height);
regLineChange(cm, no, "widget");
});
signalLater(cm, "lineWidgetCleared", cm, this, no);
}
};
LineWidget.prototype.changed = function () {
var this$1 = this;
var oldH = this.height, cm = this.doc.cm, line = this.line;
this.height = null;
var diff = widgetHeight(this) - oldH;
if (!diff) { return }
if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); }
if (cm) {
runInOp(cm, function () {
cm.curOp.forceUpdate = true;
adjustScrollWhenAboveVisible(cm, line, diff);
signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
});
}
};
eventMixin(LineWidget);
function adjustScrollWhenAboveVisible(cm, line, diff) {
if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
{ addToScrollTop(cm, diff); }
}
function addLineWidget(doc, handle, node, options) {
var widget = new LineWidget(doc, node, options);
var cm = doc.cm;
if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
changeLine(doc, handle, "widget", function (line) {
var widgets = line.widgets || (line.widgets = []);
if (widget.insertAt == null) { widgets.push(widget); }
else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); }
widget.line = line;
if (cm && !lineIsHidden(doc, line)) {
var aboveVisible = heightAtLine(line) < doc.scrollTop;
updateLineHeight(line, line.height + widgetHeight(widget));
if (aboveVisible) { addToScrollTop(cm, widget.height); }
cm.curOp.forceUpdate = true;
}
return true
});
if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); }
return widget
}
// TEXTMARKERS
// Created with markText and setBookmark methods. A TextMarker is a
// handle that can be used to clear or find a marked position in the
// document. Line objects hold arrays (markedSpans) containing
// {from, to, marker} object pointing to such marker objects, and
// indicating that such a marker is present on that line. Multiple
// lines may point to the same marker when it spans across lines.
// The spans will have null for their from/to properties when the
// marker continues beyond the start/end of the line. Markers have
// links back to the lines they currently touch.
// Collapsed markers have unique ids, in order to be able to order
// them, which is needed for uniquely determining an outer marker
// when they overlap (they may nest, but not partially overlap).
var nextMarkerId = 0;
var TextMarker = function(doc, type) {
this.lines = [];
this.type = type;
this.doc = doc;
this.id = ++nextMarkerId;
};
// Clear the marker.
TextMarker.prototype.clear = function () {
if (this.explicitlyCleared) { return }
var cm = this.doc.cm, withOp = cm && !cm.curOp;
if (withOp) { startOperation(cm); }
if (hasHandler(this, "clear")) {
var found = this.find();
if (found) { signalLater(this, "clear", found.from, found.to); }
}
var min = null, max = null;
for (var i = 0; i < this.lines.length; ++i) {
var line = this.lines[i];
var span = getMarkedSpanFor(line.markedSpans, this);
if (cm && !this.collapsed) { regLineChange(cm, lineNo(line), "text"); }
else if (cm) {
if (span.to != null) { max = lineNo(line); }
if (span.from != null) { min = lineNo(line); }
}
line.markedSpans = removeMarkedSpan(line.markedSpans, span);
if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
{ updateLineHeight(line, textHeight(cm.display)); }
}
if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
var visual = visualLine(this.lines[i$1]), len = lineLength(visual);
if (len > cm.display.maxLineLength) {
cm.display.maxLine = visual;
cm.display.maxLineLength = len;
cm.display.maxLineChanged = true;
}
} }
if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
this.lines.length = 0;
this.explicitlyCleared = true;
if (this.atomic && this.doc.cantEdit) {
this.doc.cantEdit = false;
if (cm) { reCheckSelection(cm.doc); }
}
if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
if (withOp) { endOperation(cm); }
if (this.parent) { this.parent.clear(); }
};
// Find the position of the marker in the document. Returns a {from,
// to} object by default. Side can be passed to get a specific side
// -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
// Pos objects returned contain a line object, rather than a line
// number (used to prevent looking up the same line twice).
TextMarker.prototype.find = function (side, lineObj) {
if (side == null && this.type == "bookmark") { side = 1; }
var from, to;
for (var i = 0; i < this.lines.length; ++i) {
var line = this.lines[i];
var span = getMarkedSpanFor(line.markedSpans, this);
if (span.from != null) {
from = Pos(lineObj ? line : lineNo(line), span.from);
if (side == -1) { return from }
}
if (span.to != null) {
to = Pos(lineObj ? line : lineNo(line), span.to);
if (side == 1) { return to }
}
}
return from && {from: from, to: to}
};
// Signals that the marker's widget changed, and surrounding layout
// should be recomputed.
TextMarker.prototype.changed = function () {
var this$1 = this;
var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
if (!pos || !cm) { return }
runInOp(cm, function () {
var line = pos.line, lineN = lineNo(pos.line);
var view = findViewForLine(cm, lineN);
if (view) {
clearLineMeasurementCacheFor(view);
cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
}
cm.curOp.updateMaxLine = true;
if (!lineIsHidden(widget.doc, line) && widget.height != null) {
var oldHeight = widget.height;
widget.height = null;
var dHeight = widgetHeight(widget) - oldHeight;
if (dHeight)
{ updateLineHeight(line, line.height + dHeight); }
}
signalLater(cm, "markerChanged", cm, this$1);
});
};
TextMarker.prototype.attachLine = function (line) {
if (!this.lines.length && this.doc.cm) {
var op = this.doc.cm.curOp;
if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
{ (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
}
this.lines.push(line);
};
TextMarker.prototype.detachLine = function (line) {
this.lines.splice(indexOf(this.lines, line), 1);
if (!this.lines.length && this.doc.cm) {
var op = this.doc.cm.curOp
;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
}
};
eventMixin(TextMarker);
// Create a marker, wire it up to the right lines, and
function markText(doc, from, to, options, type) {
// Shared markers (across linked documents) are handled separately
// (markTextShared will call out to this again, once per
// document).
if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
// Ensure we are in an operation.
if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
var marker = new TextMarker(doc, type), diff = cmp(from, to);
if (options) { copyObj(options, marker, false); }
// Don't connect empty markers unless clearWhenEmpty is false
if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
{ return marker }
if (marker.replacedWith) {
// Showing up as a widget implies collapsed (widget replaces text)
marker.collapsed = true;
marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
}
if (marker.collapsed) {
if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
{ throw new Error("Inserting collapsed marker partially overlapping an existing one") }
seeCollapsedSpans();
}
if (marker.addToHistory)
{ addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
var curLine = from.line, cm = doc.cm, updateMaxLine;
doc.iter(curLine, to.line + 1, function (line) {
if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
{ updateMaxLine = true; }
if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
addMarkedSpan(line, new MarkedSpan(marker,
curLine == from.line ? from.ch : null,
curLine == to.line ? to.ch : null));
++curLine;
});
// lineIsHidden depends on the presence of the spans, so needs a second pass
if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
}); }
if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
if (marker.readOnly) {
seeReadOnlySpans();
if (doc.history.done.length || doc.history.undone.length)
{ doc.clearHistory(); }
}
if (marker.collapsed) {
marker.id = ++nextMarkerId;
marker.atomic = true;
}
if (cm) {
// Sync editor state
if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
if (marker.collapsed)
{ regChange(cm, from.line, to.line + 1); }
else if (marker.className || marker.startStyle || marker.endStyle || marker.css ||
marker.attributes || marker.title)
{ for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
if (marker.atomic) { reCheckSelection(cm.doc); }
signalLater(cm, "markerAdded", cm, marker);
}
return marker
}
// SHARED TEXTMARKERS
// A shared marker spans multiple linked documents. It is
// implemented as a meta-marker-object controlling multiple normal
// markers.
var SharedTextMarker = function(markers, primary) {
this.markers = markers;
this.primary = primary;
for (var i = 0; i < markers.length; ++i)
{ markers[i].parent = this; }
};
SharedTextMarker.prototype.clear = function () {
if (this.explicitlyCleared) { return }
this.explicitlyCleared = true;
for (var i = 0; i < this.markers.length; ++i)
{ this.markers[i].clear(); }
signalLater(this, "clear");
};
SharedTextMarker.prototype.find = function (side, lineObj) {
return this.primary.find(side, lineObj)
};
eventMixin(SharedTextMarker);
function markTextShared(doc, from, to, options, type) {
options = copyObj(options);
options.shared = false;
var markers = [markText(doc, from, to, options, type)], primary = markers[0];
var widget = options.widgetNode;
linkedDocs(doc, function (doc) {
if (widget) { options.widgetNode = widget.cloneNode(true); }
markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
for (var i = 0; i < doc.linked.length; ++i)
{ if (doc.linked[i].isParent) { return } }
primary = lst(markers);
});
return new SharedTextMarker(markers, primary)
}
function findSharedMarkers(doc) {
return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
}
function copySharedMarkers(doc, markers) {
for (var i = 0; i < markers.length; i++) {
var marker = markers[i], pos = marker.find();
var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
if (cmp(mFrom, mTo)) {
var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
marker.markers.push(subMark);
subMark.parent = marker;
}
}
}
function detachSharedMarkers(markers) {
var loop = function ( i ) {
var marker = markers[i], linked = [marker.primary.doc];
linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
for (var j = 0; j < marker.markers.length; j++) {
var subMarker = marker.markers[j];
if (indexOf(linked, subMarker.doc) == -1) {
subMarker.parent = null;
marker.markers.splice(j--, 1);
}
}
};
for (var i = 0; i < markers.length; i++) loop( i );
}
var nextDocId = 0;
var Doc = function(text, mode, firstLine, lineSep, direction) {
if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
if (firstLine == null) { firstLine = 0; }
BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
this.first = firstLine;
this.scrollTop = this.scrollLeft = 0;
this.cantEdit = false;
this.cleanGeneration = 1;
this.modeFrontier = this.highlightFrontier = firstLine;
var start = Pos(firstLine, 0);
this.sel = simpleSelection(start);
this.history = new History(null);
this.id = ++nextDocId;
this.modeOption = mode;
this.lineSep = lineSep;
this.direction = (direction == "rtl") ? "rtl" : "ltr";
this.extend = false;
if (typeof text == "string") { text = this.splitLines(text); }
updateDoc(this, {from: start, to: start, text: text});
setSelection(this, simpleSelection(start), sel_dontScroll);
};
Doc.prototype = createObj(BranchChunk.prototype, {
constructor: Doc,
// Iterate over the document. Supports two forms -- with only one
// argument, it calls that for each line in the document. With
// three, it iterates over the range given by the first two (with
// the second being non-inclusive).
iter: function(from, to, op) {
if (op) { this.iterN(from - this.first, to - from, op); }
else { this.iterN(this.first, this.first + this.size, from); }
},
// Non-public interface for adding and removing lines.
insert: function(at, lines) {
var height = 0;
for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
this.insertInner(at - this.first, lines, height);
},
remove: function(at, n) { this.removeInner(at - this.first, n); },
// From here, the methods are part of the public interface. Most
// are also available from CodeMirror (editor) instances.
getValue: function(lineSep) {
var lines = getLines(this, this.first, this.first + this.size);
if (lineSep === false) { return lines }
return lines.join(lineSep || this.lineSeparator())
},
setValue: docMethodOp(function(code) {
var top = Pos(this.first, 0), last = this.first + this.size - 1;
makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
text: this.splitLines(code), origin: "setValue", full: true}, true);
if (this.cm) { scrollToCoords(this.cm, 0, 0); }
setSelection(this, simpleSelection(top), sel_dontScroll);
}),
replaceRange: function(code, from, to, origin) {
from = clipPos(this, from);
to = to ? clipPos(this, to) : from;
replaceRange(this, code, from, to, origin);
},
getRange: function(from, to, lineSep) {
var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
if (lineSep === false) { return lines }
return lines.join(lineSep || this.lineSeparator())
},
getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
getLineNumber: function(line) {return lineNo(line)},
getLineHandleVisualStart: function(line) {
if (typeof line == "number") { line = getLine(this, line); }
return visualLine(line)
},
lineCount: function() {return this.size},
firstLine: function() {return this.first},
lastLine: function() {return this.first + this.size - 1},
clipPos: function(pos) {return clipPos(this, pos)},
getCursor: function(start) {
var range = this.sel.primary(), pos;
if (start == null || start == "head") { pos = range.head; }
else if (start == "anchor") { pos = range.anchor; }
else if (start == "end" || start == "to" || start === false) { pos = range.to(); }
else { pos = range.from(); }
return pos
},
listSelections: function() { return this.sel.ranges },
somethingSelected: function() {return this.sel.somethingSelected()},
setCursor: docMethodOp(function(line, ch, options) {
setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
}),
setSelection: docMethodOp(function(anchor, head, options) {
setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
}),
extendSelection: docMethodOp(function(head, other, options) {
extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
}),
extendSelections: docMethodOp(function(heads, options) {
extendSelections(this, clipPosArray(this, heads), options);
}),
extendSelectionsBy: docMethodOp(function(f, options) {
var heads = map(this.sel.ranges, f);
extendSelections(this, clipPosArray(this, heads), options);
}),
setSelections: docMethodOp(function(ranges, primary, options) {
if (!ranges.length) { return }
var out = [];
for (var i = 0; i < ranges.length; i++)
{ out[i] = new Range(clipPos(this, ranges[i].anchor),
clipPos(this, ranges[i].head)); }
if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
setSelection(this, normalizeSelection(this.cm, out, primary), options);
}),
addSelection: docMethodOp(function(anchor, head, options) {
var ranges = this.sel.ranges.slice(0);
ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options);
}),
getSelection: function(lineSep) {
var ranges = this.sel.ranges, lines;
for (var i = 0; i < ranges.length; i++) {
var sel = getBetween(this, ranges[i].from(), ranges[i].to());
lines = lines ? lines.concat(sel) : sel;
}
if (lineSep === false) { return lines }
else { return lines.join(lineSep || this.lineSeparator()) }
},
getSelections: function(lineSep) {
var parts = [], ranges = this.sel.ranges;
for (var i = 0; i < ranges.length; i++) {
var sel = getBetween(this, ranges[i].from(), ranges[i].to());
if (lineSep !== false) { sel = sel.join(lineSep || this.lineSeparator()); }
parts[i] = sel;
}
return parts
},
replaceSelection: function(code, collapse, origin) {
var dup = [];
for (var i = 0; i < this.sel.ranges.length; i++)
{ dup[i] = code; }
this.replaceSelections(dup, collapse, origin || "+input");
},
replaceSelections: docMethodOp(function(code, collapse, origin) {
var changes = [], sel = this.sel;
for (var i = 0; i < sel.ranges.length; i++) {
var range = sel.ranges[i];
changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
}
var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
{ makeChange(this, changes[i$1]); }
if (newSel) { setSelectionReplaceHistory(this, newSel); }
else if (this.cm) { ensureCursorVisible(this.cm); }
}),
undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
setExtending: function(val) {this.extend = val;},
getExtending: function() {return this.extend},
historySize: function() {
var hist = this.history, done = 0, undone = 0;
for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
return {undo: done, redo: undone}
},
clearHistory: function() {
var this$1 = this;
this.history = new History(this.history.maxGeneration);
linkedDocs(this, function (doc) { return doc.history = this$1.history; }, true);
},
markClean: function() {
this.cleanGeneration = this.changeGeneration(true);
},
changeGeneration: function(forceSplit) {
if (forceSplit)
{ this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
return this.history.generation
},
isClean: function (gen) {
return this.history.generation == (gen || this.cleanGeneration)
},
getHistory: function() {
return {done: copyHistoryArray(this.history.done),
undone: copyHistoryArray(this.history.undone)}
},
setHistory: function(histData) {
var hist = this.history = new History(this.history.maxGeneration);
hist.done = copyHistoryArray(histData.done.slice(0), null, true);
hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
},
setGutterMarker: docMethodOp(function(line, gutterID, value) {
return changeLine(this, line, "gutter", function (line) {
var markers = line.gutterMarkers || (line.gutterMarkers = {});
markers[gutterID] = value;
if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
return true
})
}),
clearGutter: docMethodOp(function(gutterID) {
var this$1 = this;
this.iter(function (line) {
if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
changeLine(this$1, line, "gutter", function () {
line.gutterMarkers[gutterID] = null;
if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
return true
});
}
});
}),
lineInfo: function(line) {
var n;
if (typeof line == "number") {
if (!isLine(this, line)) { return null }
n = line;
line = getLine(this, line);
if (!line) { return null }
} else {
n = lineNo(line);
if (n == null) { return null }
}
return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
widgets: line.widgets}
},
addLineClass: docMethodOp(function(handle, where, cls) {
return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
var prop = where == "text" ? "textClass"
: where == "background" ? "bgClass"
: where == "gutter" ? "gutterClass" : "wrapClass";
if (!line[prop]) { line[prop] = cls; }
else if (classTest(cls).test(line[prop])) { return false }
else { line[prop] += " " + cls; }
return true
})
}),
removeLineClass: docMethodOp(function(handle, where, cls) {
return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
var prop = where == "text" ? "textClass"
: where == "background" ? "bgClass"
: where == "gutter" ? "gutterClass" : "wrapClass";
var cur = line[prop];
if (!cur) { return false }
else if (cls == null) { line[prop] = null; }
else {
var found = cur.match(classTest(cls));
if (!found) { return false }
var end = found.index + found[0].length;
line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
}
return true
})
}),
addLineWidget: docMethodOp(function(handle, node, options) {
return addLineWidget(this, handle, node, options)
}),
removeLineWidget: function(widget) { widget.clear(); },
markText: function(from, to, options) {
return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
},
setBookmark: function(pos, options) {
var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
insertLeft: options && options.insertLeft,
clearWhenEmpty: false, shared: options && options.shared,
handleMouseEvents: options && options.handleMouseEvents};
pos = clipPos(this, pos);
return markText(this, pos, pos, realOpts, "bookmark")
},
findMarksAt: function(pos) {
pos = clipPos(this, pos);
var markers = [], spans = getLine(this, pos.line).markedSpans;
if (spans) { for (var i = 0; i < spans.length; ++i) {
var span = spans[i];
if ((span.from == null || span.from <= pos.ch) &&
(span.to == null || span.to >= pos.ch))
{ markers.push(span.marker.parent || span.marker); }
} }
return markers
},
findMarks: function(from, to, filter) {
from = clipPos(this, from); to = clipPos(this, to);
var found = [], lineNo = from.line;
this.iter(from.line, to.line + 1, function (line) {
var spans = line.markedSpans;
if (spans) { for (var i = 0; i < spans.length; i++) {
var span = spans[i];
if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
span.from == null && lineNo != from.line ||
span.from != null && lineNo == to.line && span.from >= to.ch) &&
(!filter || filter(span.marker)))
{ found.push(span.marker.parent || span.marker); }
} }
++lineNo;
});
return found
},
getAllMarks: function() {
var markers = [];
this.iter(function (line) {
var sps = line.markedSpans;
if (sps) { for (var i = 0; i < sps.length; ++i)
{ if (sps[i].from != null) { markers.push(sps[i].marker); } } }
});
return markers
},
posFromIndex: function(off) {
var ch, lineNo = this.first, sepSize = this.lineSeparator().length;
this.iter(function (line) {
var sz = line.text.length + sepSize;
if (sz > off) { ch = off; return true }
off -= sz;
++lineNo;
});
return clipPos(this, Pos(lineNo, ch))
},
indexFromPos: function (coords) {
coords = clipPos(this, coords);
var index = coords.ch;
if (coords.line < this.first || coords.ch < 0) { return 0 }
var sepSize = this.lineSeparator().length;
this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
index += line.text.length + sepSize;
});
return index
},
copy: function(copyHistory) {
var doc = new Doc(getLines(this, this.first, this.first + this.size),
this.modeOption, this.first, this.lineSep, this.direction);
doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
doc.sel = this.sel;
doc.extend = false;
if (copyHistory) {
doc.history.undoDepth = this.history.undoDepth;
doc.setHistory(this.getHistory());
}
return doc
},
linkedDoc: function(options) {
if (!options) { options = {}; }
var from = this.first, to = this.first + this.size;
if (options.from != null && options.from > from) { from = options.from; }
if (options.to != null && options.to < to) { to = options.to; }
var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
if (options.sharedHist) { copy.history = this.history
; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
copySharedMarkers(copy, findSharedMarkers(this));
return copy
},
unlinkDoc: function(other) {
if (other instanceof CodeMirror) { other = other.doc; }
if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
var link = this.linked[i];
if (link.doc != other) { continue }
this.linked.splice(i, 1);
other.unlinkDoc(this);
detachSharedMarkers(findSharedMarkers(this));
break
} }
// If the histories were shared, split them again
if (other.history == this.history) {
var splitIds = [other.id];
linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
other.history = new History(null);
other.history.done = copyHistoryArray(this.history.done, splitIds);
other.history.undone = copyHistoryArray(this.history.undone, splitIds);
}
},
iterLinkedDocs: function(f) {linkedDocs(this, f);},
getMode: function() {return this.mode},
getEditor: function() {return this.cm},
splitLines: function(str) {
if (this.lineSep) { return str.split(this.lineSep) }
return splitLinesAuto(str)
},
lineSeparator: function() { return this.lineSep || "\n" },
setDirection: docMethodOp(function (dir) {
if (dir != "rtl") { dir = "ltr"; }
if (dir == this.direction) { return }
this.direction = dir;
this.iter(function (line) { return line.order = null; });
if (this.cm) { directionChanged(this.cm); }
})
});
// Public alias.
Doc.prototype.eachLine = Doc.prototype.iter;
// Kludge to work around strange IE behavior where it'll sometimes
// re-fire a series of drag-related events right after the drop (#1551)
var lastDrop = 0;
function onDrop(e) {
var cm = this;
clearDragCursor(cm);
if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
{ return }
e_preventDefault(e);
if (ie) { lastDrop = +new Date; }
var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
if (!pos || cm.isReadOnly()) { return }
// Might be a file drop, in which case we simply extract the text
// and insert it.
if (files && files.length && window.FileReader && window.File) {
var n = files.length, text = Array(n), read = 0;
var markAsReadAndPasteIfAllFilesAreRead = function () {
if (++read == n) {
operation(cm, function () {
pos = clipPos(cm.doc, pos);
var change = {from: pos, to: pos,
text: cm.doc.splitLines(
text.filter(function (t) { return t != null; }).join(cm.doc.lineSeparator())),
origin: "paste"};
makeChange(cm.doc, change);
setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change))));
})();
}
};
var readTextFromFile = function (file, i) {
if (cm.options.allowDropFileTypes &&
indexOf(cm.options.allowDropFileTypes, file.type) == -1) {
markAsReadAndPasteIfAllFilesAreRead();
return
}
var reader = new FileReader;
reader.onerror = function () { return markAsReadAndPasteIfAllFilesAreRead(); };
reader.onload = function () {
var content = reader.result;
if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) {
markAsReadAndPasteIfAllFilesAreRead();
return
}
text[i] = content;
markAsReadAndPasteIfAllFilesAreRead();
};
reader.readAsText(file);
};
for (var i = 0; i < files.length; i++) { readTextFromFile(files[i], i); }
} else { // Normal drop
// Don't do a replace if the drop happened inside of the selected text.
if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
cm.state.draggingText(e);
// Ensure the editor is re-focused
setTimeout(function () { return cm.display.input.focus(); }, 20);
return
}
try {
var text$1 = e.dataTransfer.getData("Text");
if (text$1) {
var selected;
if (cm.state.draggingText && !cm.state.draggingText.copy)
{ selected = cm.listSelections(); }
setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
{ replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
cm.replaceSelection(text$1, "around", "paste");
cm.display.input.focus();
}
}
catch(e$1){}
}
}
function onDragStart(cm, e) {
if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
e.dataTransfer.setData("Text", cm.getSelection());
e.dataTransfer.effectAllowed = "copyMove";
// Use dummy image instead of default browsers image.
// Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
if (e.dataTransfer.setDragImage && !safari) {
var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
if (presto) {
img.width = img.height = 1;
cm.display.wrapper.appendChild(img);
// Force a relayout, or Opera won't use our image for some obscure reason
img._top = img.offsetTop;
}
e.dataTransfer.setDragImage(img, 0, 0);
if (presto) { img.parentNode.removeChild(img); }
}
}
function onDragOver(cm, e) {
var pos = posFromMouse(cm, e);
if (!pos) { return }
var frag = document.createDocumentFragment();
drawSelectionCursor(cm, pos, frag);
if (!cm.display.dragCursor) {
cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
}
removeChildrenAndAdd(cm.display.dragCursor, frag);
}
function clearDragCursor(cm) {
if (cm.display.dragCursor) {
cm.display.lineSpace.removeChild(cm.display.dragCursor);
cm.display.dragCursor = null;
}
}
// These must be handled carefully, because naively registering a
// handler for each editor will cause the editors to never be
// garbage collected.
function forEachCodeMirror(f) {
if (!document.getElementsByClassName) { return }
var byClass = document.getElementsByClassName("CodeMirror"), editors = [];
for (var i = 0; i < byClass.length; i++) {
var cm = byClass[i].CodeMirror;
if (cm) { editors.push(cm); }
}
if (editors.length) { editors[0].operation(function () {
for (var i = 0; i < editors.length; i++) { f(editors[i]); }
}); }
}
var globalsRegistered = false;
function ensureGlobalHandlers() {
if (globalsRegistered) { return }
registerGlobalHandlers();
globalsRegistered = true;
}
function registerGlobalHandlers() {
// When the window resizes, we need to refresh active editors.
var resizeTimer;
on(window, "resize", function () {
if (resizeTimer == null) { resizeTimer = setTimeout(function () {
resizeTimer = null;
forEachCodeMirror(onResize);
}, 100); }
});
// When the window loses focus, we want to show the editor as blurred
on(window, "blur", function () { return forEachCodeMirror(onBlur); });
}
// Called when the window resizes
function onResize(cm) {
var d = cm.display;
// Might be a text scaling operation, clear size caches.
d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
d.scrollbarsClipped = false;
cm.setSize();
}
var keyNames = {
3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 145: "ScrollLock",
173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
221: "]", 222: "'", 224: "Mod", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
};
// Number keys
for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
// Alphabetic keys
for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
// Function keys
for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
var keyMap = {};
keyMap.basic = {
"Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
"End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
"Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
"Tab": "defaultTab", "Shift-Tab": "indentAuto",
"Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
"Esc": "singleSelection"
};
// Note that the save and find-related commands aren't defined by
// default. User code or addons can define them. Unknown commands
// are simply ignored.
keyMap.pcDefault = {
"Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
"Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
"Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
"Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
"Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
"Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
"Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
"fallthrough": "basic"
};
// Very basic readline/emacs-style bindings, which are standard on Mac.
keyMap.emacsy = {
"Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
"Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
"Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
"Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
"Ctrl-O": "openLine"
};
keyMap.macDefault = {
"Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
"Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
"Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
"Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
"Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
"Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
"Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
"fallthrough": ["basic", "emacsy"]
};
keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
// KEYMAP DISPATCH
function normalizeKeyName(name) {
var parts = name.split(/-(?!$)/);
name = parts[parts.length - 1];
var alt, ctrl, shift, cmd;
for (var i = 0; i < parts.length - 1; i++) {
var mod = parts[i];
if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
else if (/^a(lt)?$/i.test(mod)) { alt = true; }
else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
else if (/^s(hift)?$/i.test(mod)) { shift = true; }
else { throw new Error("Unrecognized modifier name: " + mod) }
}
if (alt) { name = "Alt-" + name; }
if (ctrl) { name = "Ctrl-" + name; }
if (cmd) { name = "Cmd-" + name; }
if (shift) { name = "Shift-" + name; }
return name
}
// This is a kludge to keep keymaps mostly working as raw objects
// (backwards compatibility) while at the same time support features
// like normalization and multi-stroke key bindings. It compiles a
// new normalized keymap, and then updates the old object to reflect
// this.
function normalizeKeyMap(keymap) {
var copy = {};
for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
var value = keymap[keyname];
if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
if (value == "...") { delete keymap[keyname]; continue }
var keys = map(keyname.split(" "), normalizeKeyName);
for (var i = 0; i < keys.length; i++) {
var val = (void 0), name = (void 0);
if (i == keys.length - 1) {
name = keys.join(" ");
val = value;
} else {
name = keys.slice(0, i + 1).join(" ");
val = "...";
}
var prev = copy[name];
if (!prev) { copy[name] = val; }
else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
}
delete keymap[keyname];
} }
for (var prop in copy) { keymap[prop] = copy[prop]; }
return keymap
}
function lookupKey(key, map, handle, context) {
map = getKeyMap(map);
var found = map.call ? map.call(key, context) : map[key];
if (found === false) { return "nothing" }
if (found === "...") { return "multi" }
if (found != null && handle(found)) { return "handled" }
if (map.fallthrough) {
if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
{ return lookupKey(key, map.fallthrough, handle, context) }
for (var i = 0; i < map.fallthrough.length; i++) {
var result = lookupKey(key, map.fallthrough[i], handle, context);
if (result) { return result }
}
}
}
// Modifier key presses don't count as 'real' key presses for the
// purpose of keymap fallthrough.
function isModifierKey(value) {
var name = typeof value == "string" ? value : keyNames[value.keyCode];
return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
}
function addModifierNames(name, event, noShift) {
var base = name;
if (event.altKey && base != "Alt") { name = "Alt-" + name; }
if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Mod") { name = "Cmd-" + name; }
if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
return name
}
// Look up the name of a key as indicated by an event object.
function keyName(event, noShift) {
if (presto && event.keyCode == 34 && event["char"]) { return false }
var name = keyNames[event.keyCode];
if (name == null || event.altGraphKey) { return false }
// Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
// so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
if (event.keyCode == 3 && event.code) { name = event.code; }
return addModifierNames(name, event, noShift)
}
function getKeyMap(val) {
return typeof val == "string" ? keyMap[val] : val
}
// Helper for deleting text near the selection(s), used to implement
// backspace, delete, and similar functionality.
function deleteNearSelection(cm, compute) {
var ranges = cm.doc.sel.ranges, kill = [];
// Build up a set of ranges to kill first, merging overlapping
// ranges.
for (var i = 0; i < ranges.length; i++) {
var toKill = compute(ranges[i]);
while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
var replaced = kill.pop();
if (cmp(replaced.from, toKill.from) < 0) {
toKill.from = replaced.from;
break
}
}
kill.push(toKill);
}
// Next, remove those actual ranges.
runInOp(cm, function () {
for (var i = kill.length - 1; i >= 0; i--)
{ replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
ensureCursorVisible(cm);
});
}
function moveCharLogically(line, ch, dir) {
var target = skipExtendingChars(line.text, ch + dir, dir);
return target < 0 || target > line.text.length ? null : target
}
function moveLogically(line, start, dir) {
var ch = moveCharLogically(line, start.ch, dir);
return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
}
function endOfLine(visually, cm, lineObj, lineNo, dir) {
if (visually) {
if (cm.doc.direction == "rtl") { dir = -dir; }
var order = getOrder(lineObj, cm.doc.direction);
if (order) {
var part = dir < 0 ? lst(order) : order[0];
var moveInStorageOrder = (dir < 0) == (part.level == 1);
var sticky = moveInStorageOrder ? "after" : "before";
var ch;
// With a wrapped rtl chunk (possibly spanning multiple bidi parts),
// it could be that the last bidi part is not on the last visual line,
// since visual lines contain content order-consecutive chunks.
// Thus, in rtl, we are looking for the first (content-order) character
// in the rtl chunk that is on the last line (that is, the same line
// as the last (content-order) character).
if (part.level > 0 || cm.doc.direction == "rtl") {
var prep = prepareMeasureForLine(cm, lineObj);
ch = dir < 0 ? lineObj.text.length - 1 : 0;
var targetTop = measureCharPrepared(cm, prep, ch).top;
ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
} else { ch = dir < 0 ? part.to : part.from; }
return new Pos(lineNo, ch, sticky)
}
}
return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
}
function moveVisually(cm, line, start, dir) {
var bidi = getOrder(line, cm.doc.direction);
if (!bidi) { return moveLogically(line, start, dir) }
if (start.ch >= line.text.length) {
start.ch = line.text.length;
start.sticky = "before";
} else if (start.ch <= 0) {
start.ch = 0;
start.sticky = "after";
}
var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
// Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
// nothing interesting happens.
return moveLogically(line, start, dir)
}
var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
var prep;
var getWrappedLineExtent = function (ch) {
if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
prep = prep || prepareMeasureForLine(cm, line);
return wrappedLineExtentChar(cm, line, prep, ch)
};
var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
if (cm.doc.direction == "rtl" || part.level == 1) {
var moveInStorageOrder = (part.level == 1) == (dir < 0);
var ch = mv(start, moveInStorageOrder ? 1 : -1);
if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
// Case 2: We move within an rtl part or in an rtl editor on the same visual line
var sticky = moveInStorageOrder ? "before" : "after";
return new Pos(start.line, ch, sticky)
}
}
// Case 3: Could not move within this bidi part in this visual line, so leave
// the current bidi part
var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
? new Pos(start.line, mv(ch, 1), "before")
: new Pos(start.line, ch, "after"); };
for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
var part = bidi[partPos];
var moveInStorageOrder = (dir > 0) == (part.level != 1);
var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
ch = moveInStorageOrder ? part.from : mv(part.to, -1);
if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
}
};
// Case 3a: Look for other bidi parts on the same visual line
var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
if (res) { return res }
// Case 3b: Look for other bidi parts on the next visual line
var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
if (res) { return res }
}
// Case 4: Nowhere to move
return null
}
// Commands are parameter-less actions that can be performed on an
// editor, mostly used for keybindings.
var commands = {
selectAll: selectAll,
singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
killLine: function (cm) { return deleteNearSelection(cm, function (range) {
if (range.empty()) {
var len = getLine(cm.doc, range.head.line).text.length;
if (range.head.ch == len && range.head.line < cm.lastLine())
{ return {from: range.head, to: Pos(range.head.line + 1, 0)} }
else
{ return {from: range.head, to: Pos(range.head.line, len)} }
} else {
return {from: range.from(), to: range.to()}
}
}); },
deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
from: Pos(range.from().line, 0),
to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
}); }); },
delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
from: Pos(range.from().line, 0), to: range.from()
}); }); },
delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
var top = cm.charCoords(range.head, "div").top + 5;
var leftPos = cm.coordsChar({left: 0, top: top}, "div");
return {from: leftPos, to: range.from()}
}); },
delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
var top = cm.charCoords(range.head, "div").top + 5;
var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
return {from: range.from(), to: rightPos }
}); },
undo: function (cm) { return cm.undo(); },
redo: function (cm) { return cm.redo(); },
undoSelection: function (cm) { return cm.undoSelection(); },
redoSelection: function (cm) { return cm.redoSelection(); },
goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
{origin: "+move", bias: 1}
); },
goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
{origin: "+move", bias: 1}
); },
goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
{origin: "+move", bias: -1}
); },
goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
var top = cm.cursorCoords(range.head, "div").top + 5;
return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
}, sel_move); },
goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
var top = cm.cursorCoords(range.head, "div").top + 5;
return cm.coordsChar({left: 0, top: top}, "div")
}, sel_move); },
goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
var top = cm.cursorCoords(range.head, "div").top + 5;
var pos = cm.coordsChar({left: 0, top: top}, "div");
if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
return pos
}, sel_move); },
goLineUp: function (cm) { return cm.moveV(-1, "line"); },
goLineDown: function (cm) { return cm.moveV(1, "line"); },
goPageUp: function (cm) { return cm.moveV(-1, "page"); },
goPageDown: function (cm) { return cm.moveV(1, "page"); },
goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
goCharRight: function (cm) { return cm.moveH(1, "char"); },
goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
goColumnRight: function (cm) { return cm.moveH(1, "column"); },
goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
goGroupRight: function (cm) { return cm.moveH(1, "group"); },
goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
goWordRight: function (cm) { return cm.moveH(1, "word"); },
delCharBefore: function (cm) { return cm.deleteH(-1, "codepoint"); },
delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
indentAuto: function (cm) { return cm.indentSelection("smart"); },
indentMore: function (cm) { return cm.indentSelection("add"); },
indentLess: function (cm) { return cm.indentSelection("subtract"); },
insertTab: function (cm) { return cm.replaceSelection("\t"); },
insertSoftTab: function (cm) {
var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
for (var i = 0; i < ranges.length; i++) {
var pos = ranges[i].from();
var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
spaces.push(spaceStr(tabSize - col % tabSize));
}
cm.replaceSelections(spaces);
},
defaultTab: function (cm) {
if (cm.somethingSelected()) { cm.indentSelection("add"); }
else { cm.execCommand("insertTab"); }
},
// Swap the two chars left and right of each selection's head.
// Move cursor behind the two swapped characters afterwards.
//
// Doesn't consider line feeds a character.
// Doesn't scan more than one line above to find a character.
// Doesn't do anything on an empty line.
// Doesn't do anything with non-empty selections.
transposeChars: function (cm) { return runInOp(cm, function () {
var ranges = cm.listSelections(), newSel = [];
for (var i = 0; i < ranges.length; i++) {
if (!ranges[i].empty()) { continue }
var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
if (line) {
if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
if (cur.ch > 0) {
cur = new Pos(cur.line, cur.ch + 1);
cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
Pos(cur.line, cur.ch - 2), cur, "+transpose");
} else if (cur.line > cm.doc.first) {
var prev = getLine(cm.doc, cur.line - 1).text;
if (prev) {
cur = new Pos(cur.line, 1);
cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
prev.charAt(prev.length - 1),
Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
}
}
}
newSel.push(new Range(cur, cur));
}
cm.setSelections(newSel);
}); },
newlineAndIndent: function (cm) { return runInOp(cm, function () {
var sels = cm.listSelections();
for (var i = sels.length - 1; i >= 0; i--)
{ cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
sels = cm.listSelections();
for (var i$1 = 0; i$1 < sels.length; i$1++)
{ cm.indentLine(sels[i$1].from().line, null, true); }
ensureCursorVisible(cm);
}); },
openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
};
function lineStart(cm, lineN) {
var line = getLine(cm.doc, lineN);
var visual = visualLine(line);
if (visual != line) { lineN = lineNo(visual); }
return endOfLine(true, cm, visual, lineN, 1)
}
function lineEnd(cm, lineN) {
var line = getLine(cm.doc, lineN);
var visual = visualLineEnd(line);
if (visual != line) { lineN = lineNo(visual); }
return endOfLine(true, cm, line, lineN, -1)
}
function lineStartSmart(cm, pos) {
var start = lineStart(cm, pos.line);
var line = getLine(cm.doc, start.line);
var order = getOrder(line, cm.doc.direction);
if (!order || order[0].level == 0) {
var firstNonWS = Math.max(start.ch, line.text.search(/\S/));
var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
}
return start
}
// Run a handler that was bound to a key.
function doHandleBinding(cm, bound, dropShift) {
if (typeof bound == "string") {
bound = commands[bound];
if (!bound) { return false }
}
// Ensure previous input has been read, so that the handler sees a
// consistent view of the document
cm.display.input.ensurePolled();
var prevShift = cm.display.shift, done = false;
try {
if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
if (dropShift) { cm.display.shift = false; }
done = bound(cm) != Pass;
} finally {
cm.display.shift = prevShift;
cm.state.suppressEdits = false;
}
return done
}
function lookupKeyForEditor(cm, name, handle) {
for (var i = 0; i < cm.state.keyMaps.length; i++) {
var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
if (result) { return result }
}
return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
|| lookupKey(name, cm.options.keyMap, handle, cm)
}
// Note that, despite the name, this function is also used to check
// for bound mouse clicks.
var stopSeq = new Delayed;
function dispatchKey(cm, name, e, handle) {
var seq = cm.state.keySeq;
if (seq) {
if (isModifierKey(name)) { return "handled" }
if (/\'$/.test(name))
{ cm.state.keySeq = null; }
else
{ stopSeq.set(50, function () {
if (cm.state.keySeq == seq) {
cm.state.keySeq = null;
cm.display.input.reset();
}
}); }
if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
}
return dispatchKeyInner(cm, name, e, handle)
}
function dispatchKeyInner(cm, name, e, handle) {
var result = lookupKeyForEditor(cm, name, handle);
if (result == "multi")
{ cm.state.keySeq = name; }
if (result == "handled")
{ signalLater(cm, "keyHandled", cm, name, e); }
if (result == "handled" || result == "multi") {
e_preventDefault(e);
restartBlink(cm);
}
return !!result
}
// Handle a key from the keydown event.
function handleKeyBinding(cm, e) {
var name = keyName(e, true);
if (!name) { return false }
if (e.shiftKey && !cm.state.keySeq) {
// First try to resolve full name (including 'Shift-'). Failing
// that, see if there is a cursor-motion command (starting with
// 'go') bound to the keyname without 'Shift-'.
return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
|| dispatchKey(cm, name, e, function (b) {
if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
{ return doHandleBinding(cm, b) }
})
} else {
return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
}
}
// Handle a key from the keypress event
function handleCharBinding(cm, e, ch) {
return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
}
var lastStoppedKey = null;
function onKeyDown(e) {
var cm = this;
if (e.target && e.target != cm.display.input.getField()) { return }
cm.curOp.focus = activeElt();
if (signalDOMEvent(cm, e)) { return }
// IE does strange things with escape.
if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
var code = e.keyCode;
cm.display.shift = code == 16 || e.shiftKey;
var handled = handleKeyBinding(cm, e);
if (presto) {
lastStoppedKey = handled ? code : null;
// Opera has no cut event... we try to at least catch the key combo
if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
{ cm.replaceSelection("", null, "cut"); }
}
if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand)
{ document.execCommand("cut"); }
// Turn mouse into crosshair when Alt is held on Mac.
if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
{ showCrossHair(cm); }
}
function showCrossHair(cm) {
var lineDiv = cm.display.lineDiv;
addClass(lineDiv, "CodeMirror-crosshair");
function up(e) {
if (e.keyCode == 18 || !e.altKey) {
rmClass(lineDiv, "CodeMirror-crosshair");
off(document, "keyup", up);
off(document, "mouseover", up);
}
}
on(document, "keyup", up);
on(document, "mouseover", up);
}
function onKeyUp(e) {
if (e.keyCode == 16) { this.doc.sel.shift = false; }
signalDOMEvent(this, e);
}
function onKeyPress(e) {
var cm = this;
if (e.target && e.target != cm.display.input.getField()) { return }
if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
var keyCode = e.keyCode, charCode = e.charCode;
if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
// Some browsers fire keypress events for backspace
if (ch == "\x08") { return }
if (handleCharBinding(cm, e, ch)) { return }
cm.display.input.onKeyPress(e);
}
var DOUBLECLICK_DELAY = 400;
var PastClick = function(time, pos, button) {
this.time = time;
this.pos = pos;
this.button = button;
};
PastClick.prototype.compare = function (time, pos, button) {
return this.time + DOUBLECLICK_DELAY > time &&
cmp(pos, this.pos) == 0 && button == this.button
};
var lastClick, lastDoubleClick;
function clickRepeat(pos, button) {
var now = +new Date;
if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
lastClick = lastDoubleClick = null;
return "triple"
} else if (lastClick && lastClick.compare(now, pos, button)) {
lastDoubleClick = new PastClick(now, pos, button);
lastClick = null;
return "double"
} else {
lastClick = new PastClick(now, pos, button);
lastDoubleClick = null;
return "single"
}
}
// A mouse down can be a single click, double click, triple click,
// start of selection drag, start of text drag, new cursor
// (ctrl-click), rectangle drag (alt-drag), or xwin
// middle-click-paste. Or it might be a click on something we should
// not interfere with, such as a scrollbar or widget.
function onMouseDown(e) {
var cm = this, display = cm.display;
if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
display.input.ensurePolled();
display.shift = e.shiftKey;
if (eventInWidget(display, e)) {
if (!webkit) {
// Briefly turn off draggability, to allow widgets to do
// normal dragging things.
display.scroller.draggable = false;
setTimeout(function () { return display.scroller.draggable = true; }, 100);
}
return
}
if (clickInGutter(cm, e)) { return }
var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
window.focus();
// #3261: make sure, that we're not starting a second selection
if (button == 1 && cm.state.selectingText)
{ cm.state.selectingText(e); }
if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
if (button == 1) {
if (pos) { leftButtonDown(cm, pos, repeat, e); }
else if (e_target(e) == display.scroller) { e_preventDefault(e); }
} else if (button == 2) {
if (pos) { extendSelection(cm.doc, pos); }
setTimeout(function () { return display.input.focus(); }, 20);
} else if (button == 3) {
if (captureRightClick) { cm.display.input.onContextMenu(e); }
else { delayBlurEvent(cm); }
}
}
function handleMappedButton(cm, button, pos, repeat, event) {
var name = "Click";
if (repeat == "double") { name = "Double" + name; }
else if (repeat == "triple") { name = "Triple" + name; }
name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
if (typeof bound == "string") { bound = commands[bound]; }
if (!bound) { return false }
var done = false;
try {
if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
done = bound(cm, pos) != Pass;
} finally {
cm.state.suppressEdits = false;
}
return done
})
}
function configureMouse(cm, repeat, event) {
var option = cm.getOption("configureMouse");
var value = option ? option(cm, repeat, event) : {};
if (value.unit == null) {
var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
}
if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
return value
}
function leftButtonDown(cm, pos, repeat, event) {
if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
else { cm.curOp.focus = activeElt(); }
var behavior = configureMouse(cm, repeat, event);
var sel = cm.doc.sel, contained;
if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
repeat == "single" && (contained = sel.contains(pos)) > -1 &&
(cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
(cmp(contained.to(), pos) > 0 || pos.xRel < 0))
{ leftButtonStartDrag(cm, event, pos, behavior); }
else
{ leftButtonSelect(cm, event, pos, behavior); }
}
// Start a text drag. When it ends, see if any dragging actually
// happen, and treat as a click if it didn't.
function leftButtonStartDrag(cm, event, pos, behavior) {
var display = cm.display, moved = false;
var dragEnd = operation(cm, function (e) {
if (webkit) { display.scroller.draggable = false; }
cm.state.draggingText = false;
off(display.wrapper.ownerDocument, "mouseup", dragEnd);
off(display.wrapper.ownerDocument, "mousemove", mouseMove);
off(display.scroller, "dragstart", dragStart);
off(display.scroller, "drop", dragEnd);
if (!moved) {
e_preventDefault(e);
if (!behavior.addNew)
{ extendSelection(cm.doc, pos, null, null, behavior.extend); }
// Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
if ((webkit && !safari) || ie && ie_version == 9)
{ setTimeout(function () {display.wrapper.ownerDocument.body.focus({preventScroll: true}); display.input.focus();}, 20); }
else
{ display.input.focus(); }
}
});
var mouseMove = function(e2) {
moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
};
var dragStart = function () { return moved = true; };
// Let the drag handler handle this.
if (webkit) { display.scroller.draggable = true; }
cm.state.draggingText = dragEnd;
dragEnd.copy = !behavior.moveOnDrag;
// IE's approach to draggable
if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
on(display.wrapper.ownerDocument, "mouseup", dragEnd);
on(display.wrapper.ownerDocument, "mousemove", mouseMove);
on(display.scroller, "dragstart", dragStart);
on(display.scroller, "drop", dragEnd);
delayBlurEvent(cm);
setTimeout(function () { return display.input.focus(); }, 20);
}
function rangeForUnit(cm, pos, unit) {
if (unit == "char") { return new Range(pos, pos) }
if (unit == "word") { return cm.findWordAt(pos) }
if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
var result = unit(cm, pos);
return new Range(result.from, result.to)
}
// Normal selection, as opposed to text dragging.
function leftButtonSelect(cm, event, start, behavior) {
var display = cm.display, doc = cm.doc;
e_preventDefault(event);
var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
if (behavior.addNew && !behavior.extend) {
ourIndex = doc.sel.contains(start);
if (ourIndex > -1)
{ ourRange = ranges[ourIndex]; }
else
{ ourRange = new Range(start, start); }
} else {
ourRange = doc.sel.primary();
ourIndex = doc.sel.primIndex;
}
if (behavior.unit == "rectangle") {
if (!behavior.addNew) { ourRange = new Range(start, start); }
start = posFromMouse(cm, event, true, true);
ourIndex = -1;
} else {
var range = rangeForUnit(cm, start, behavior.unit);
if (behavior.extend)
{ ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend); }
else
{ ourRange = range; }
}
if (!behavior.addNew) {
ourIndex = 0;
setSelection(doc, new Selection([ourRange], 0), sel_mouse);
startSel = doc.sel;
} else if (ourIndex == -1) {
ourIndex = ranges.length;
setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),
{scroll: false, origin: "*mouse"});
} else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
{scroll: false, origin: "*mouse"});
startSel = doc.sel;
} else {
replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
}
var lastPos = start;
function extendTo(pos) {
if (cmp(lastPos, pos) == 0) { return }
lastPos = pos;
if (behavior.unit == "rectangle") {
var ranges = [], tabSize = cm.options.tabSize;
var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
line <= end; line++) {
var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
if (left == right)
{ ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
else if (text.length > leftPos)
{ ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
}
if (!ranges.length) { ranges.push(new Range(start, start)); }
setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
{origin: "*mouse", scroll: false});
cm.scrollIntoView(pos);
} else {
var oldRange = ourRange;
var range = rangeForUnit(cm, pos, behavior.unit);
var anchor = oldRange.anchor, head;
if (cmp(range.anchor, anchor) > 0) {
head = range.head;
anchor = minPos(oldRange.from(), range.anchor);
} else {
head = range.anchor;
anchor = maxPos(oldRange.to(), range.head);
}
var ranges$1 = startSel.ranges.slice(0);
ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);
}
}
var editorSize = display.wrapper.getBoundingClientRect();
// Used to ensure timeout re-tries don't fire when another extend
// happened in the meantime (clearTimeout isn't reliable -- at
// least on Chrome, the timeouts still happen even when cleared,
// if the clear happens after their scheduled firing time).
var counter = 0;
function extend(e) {
var curCount = ++counter;
var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
if (!cur) { return }
if (cmp(cur, lastPos) != 0) {
cm.curOp.focus = activeElt();
extendTo(cur);
var visible = visibleLines(display, doc);
if (cur.line >= visible.to || cur.line < visible.from)
{ setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
} else {
var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
if (outside) { setTimeout(operation(cm, function () {
if (counter != curCount) { return }
display.scroller.scrollTop += outside;
extend(e);
}), 50); }
}
}
function done(e) {
cm.state.selectingText = false;
counter = Infinity;
// If e is null or undefined we interpret this as someone trying
// to explicitly cancel the selection rather than the user
// letting go of the mouse button.
if (e) {
e_preventDefault(e);
display.input.focus();
}
off(display.wrapper.ownerDocument, "mousemove", move);
off(display.wrapper.ownerDocument, "mouseup", up);
doc.history.lastSelOrigin = null;
}
var move = operation(cm, function (e) {
if (e.buttons === 0 || !e_button(e)) { done(e); }
else { extend(e); }
});
var up = operation(cm, done);
cm.state.selectingText = up;
on(display.wrapper.ownerDocument, "mousemove", move);
on(display.wrapper.ownerDocument, "mouseup", up);
}
// Used when mouse-selecting to adjust the anchor to the proper side
// of a bidi jump depending on the visual position of the head.
function bidiSimplify(cm, range) {
var anchor = range.anchor;
var head = range.head;
var anchorLine = getLine(cm.doc, anchor.line);
if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range }
var order = getOrder(anchorLine);
if (!order) { return range }
var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
if (part.from != anchor.ch && part.to != anchor.ch) { return range }
var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
if (boundary == 0 || boundary == order.length) { return range }
// Compute the relative visual position of the head compared to the
// anchor (<0 is to the left, >0 to the right)
var leftSide;
if (head.line != anchor.line) {
leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
} else {
var headIndex = getBidiPartAt(order, head.ch, head.sticky);
var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
if (headIndex == boundary - 1 || headIndex == boundary)
{ leftSide = dir < 0; }
else
{ leftSide = dir > 0; }
}
var usePart = order[boundary + (leftSide ? -1 : 0)];
var from = leftSide == (usePart.level == 1);
var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head)
}
// Determines whether an event happened in the gutter, and fires the
// handlers for the corresponding event.
function gutterEvent(cm, e, type, prevent) {
var mX, mY;
if (e.touches) {
mX = e.touches[0].clientX;
mY = e.touches[0].clientY;
} else {
try { mX = e.clientX; mY = e.clientY; }
catch(e$1) { return false }
}
if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
if (prevent) { e_preventDefault(e); }
var display = cm.display;
var lineBox = display.lineDiv.getBoundingClientRect();
if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
mY -= lineBox.top - display.viewOffset;
for (var i = 0; i < cm.display.gutterSpecs.length; ++i) {
var g = display.gutters.childNodes[i];
if (g && g.getBoundingClientRect().right >= mX) {
var line = lineAtHeight(cm.doc, mY);
var gutter = cm.display.gutterSpecs[i];
signal(cm, type, cm, line, gutter.className, e);
return e_defaultPrevented(e)
}
}
}
function clickInGutter(cm, e) {
return gutterEvent(cm, e, "gutterClick", true)
}
// CONTEXT MENU HANDLING
// To make the context menu work, we need to briefly unhide the
// textarea (making it as unobtrusive as possible) to let the
// right-click take effect on it.
function onContextMenu(cm, e) {
if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
if (signalDOMEvent(cm, e, "contextmenu")) { return }
if (!captureRightClick) { cm.display.input.onContextMenu(e); }
}
function contextMenuInGutter(cm, e) {
if (!hasHandler(cm, "gutterContextMenu")) { return false }
return gutterEvent(cm, e, "gutterContextMenu", false)
}
function themeChanged(cm) {
cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
clearCaches(cm);
}
var Init = {toString: function(){return "CodeMirror.Init"}};
var defaults = {};
var optionHandlers = {};
function defineOptions(CodeMirror) {
var optionHandlers = CodeMirror.optionHandlers;
function option(name, deflt, handle, notOnInit) {
CodeMirror.defaults[name] = deflt;
if (handle) { optionHandlers[name] =
notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
}
CodeMirror.defineOption = option;
// Passed to option handlers when there is no old value.
CodeMirror.Init = Init;
// These two are, on init, called from the constructor because they
// have to be initialized before the editor can start at all.
option("value", "", function (cm, val) { return cm.setValue(val); }, true);
option("mode", null, function (cm, val) {
cm.doc.modeOption = val;
loadMode(cm);
}, true);
option("indentUnit", 2, loadMode, true);
option("indentWithTabs", false);
option("smartIndent", true);
option("tabSize", 4, function (cm) {
resetModeState(cm);
clearCaches(cm);
regChange(cm);
}, true);
option("lineSeparator", null, function (cm, val) {
cm.doc.lineSep = val;
if (!val) { return }
var newBreaks = [], lineNo = cm.doc.first;
cm.doc.iter(function (line) {
for (var pos = 0;;) {
var found = line.text.indexOf(val, pos);
if (found == -1) { break }
pos = found + val.length;
newBreaks.push(Pos(lineNo, found));
}
lineNo++;
});
for (var i = newBreaks.length - 1; i >= 0; i--)
{ replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
});
option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200c\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, function (cm, val, old) {
cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
if (old != Init) { cm.refresh(); }
});
option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
option("electricChars", true);
option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
}, true);
option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true);
option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true);
option("rtlMoveVisually", !windows);
option("wholeLineUpdateBefore", true);
option("theme", "default", function (cm) {
themeChanged(cm);
updateGutters(cm);
}, true);
option("keyMap", "default", function (cm, val, old) {
var next = getKeyMap(val);
var prev = old != Init && getKeyMap(old);
if (prev && prev.detach) { prev.detach(cm, next); }
if (next.attach) { next.attach(cm, prev || null); }
});
option("extraKeys", null);
option("configureMouse", null);
option("lineWrapping", false, wrappingChanged, true);
option("gutters", [], function (cm, val) {
cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers);
updateGutters(cm);
}, true);
option("fixedGutter", true, function (cm, val) {
cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
cm.refresh();
}, true);
option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
option("scrollbarStyle", "native", function (cm) {
initScrollbars(cm);
updateScrollbars(cm);
cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
}, true);
option("lineNumbers", false, function (cm, val) {
cm.display.gutterSpecs = getGutters(cm.options.gutters, val);
updateGutters(cm);
}, true);
option("firstLineNumber", 1, updateGutters, true);
option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true);
option("showCursorWhenSelecting", false, updateSelection, true);
option("resetSelectionOnContextMenu", true);
option("lineWiseCopyCut", true);
option("pasteLinesPerSelection", true);
option("selectionsMayTouch", false);
option("readOnly", false, function (cm, val) {
if (val == "nocursor") {
onBlur(cm);
cm.display.input.blur();
}
cm.display.input.readOnlyChanged(val);
});
option("screenReaderLabel", null, function (cm, val) {
val = (val === '') ? null : val;
cm.display.input.screenReaderLabelChanged(val);
});
option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
option("dragDrop", true, dragDropChanged);
option("allowDropFileTypes", null);
option("cursorBlinkRate", 530);
option("cursorScrollMargin", 0);
option("cursorHeight", 1, updateSelection, true);
option("singleCursorHeightPerLine", true, updateSelection, true);
option("workTime", 100);
option("workDelay", 100);
option("flattenSpans", true, resetModeState, true);
option("addModeClass", false, resetModeState, true);
option("pollInterval", 100);
option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
option("historyEventDelay", 1250);
option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
option("maxHighlightLength", 10000, resetModeState, true);
option("moveInputWithCursor", true, function (cm, val) {
if (!val) { cm.display.input.resetPosition(); }
});
option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
option("autofocus", null);
option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
option("phrases", null);
}
function dragDropChanged(cm, value, old) {
var wasOn = old && old != Init;
if (!value != !wasOn) {
var funcs = cm.display.dragFunctions;
var toggle = value ? on : off;
toggle(cm.display.scroller, "dragstart", funcs.start);
toggle(cm.display.scroller, "dragenter", funcs.enter);
toggle(cm.display.scroller, "dragover", funcs.over);
toggle(cm.display.scroller, "dragleave", funcs.leave);
toggle(cm.display.scroller, "drop", funcs.drop);
}
}
function wrappingChanged(cm) {
if (cm.options.lineWrapping) {
addClass(cm.display.wrapper, "CodeMirror-wrap");
cm.display.sizer.style.minWidth = "";
cm.display.sizerWidth = null;
} else {
rmClass(cm.display.wrapper, "CodeMirror-wrap");
findMaxLine(cm);
}
estimateLineHeights(cm);
regChange(cm);
clearCaches(cm);
setTimeout(function () { return updateScrollbars(cm); }, 100);
}
// A CodeMirror instance represents an editor. This is the object
// that user code is usually dealing with.
function CodeMirror(place, options) {
var this$1 = this;
if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
this.options = options = options ? copyObj(options) : {};
// Determine effective options based on given values and defaults.
copyObj(defaults, options, false);
var doc = options.value;
if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
else if (options.mode) { doc.modeOption = options.mode; }
this.doc = doc;
var input = new CodeMirror.inputStyles[options.inputStyle](this);
var display = this.display = new Display(place, doc, input, options);
display.wrapper.CodeMirror = this;
themeChanged(this);
if (options.lineWrapping)
{ this.display.wrapper.className += " CodeMirror-wrap"; }
initScrollbars(this);
this.state = {
keyMaps: [], // stores maps added by addKeyMap
overlays: [], // highlighting overlays, as added by addOverlay
modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
overwrite: false,
delayingBlurEvent: false,
focused: false,
suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll
selectingText: false,
draggingText: false,
highlight: new Delayed(), // stores highlight worker timeout
keySeq: null, // Unfinished key sequence
specialChars: null
};
if (options.autofocus && !mobile) { display.input.focus(); }
// Override magic textarea content restore that IE sometimes does
// on our hidden textarea on reload
if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
registerEventHandlers(this);
ensureGlobalHandlers();
startOperation(this);
this.curOp.forceUpdate = true;
attachDoc(this, doc);
if ((options.autofocus && !mobile) || this.hasFocus())
{ setTimeout(function () {
if (this$1.hasFocus() && !this$1.state.focused) { onFocus(this$1); }
}, 20); }
else
{ onBlur(this); }
for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
{ optionHandlers[opt](this, options[opt], Init); } }
maybeUpdateLineNumberWidth(this);
if (options.finishInit) { options.finishInit(this); }
for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this); }
endOperation(this);
// Suppress optimizelegibility in Webkit, since it breaks text
// measuring on line wrapping boundaries.
if (webkit && options.lineWrapping &&
getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
{ display.lineDiv.style.textRendering = "auto"; }
}
// The default configuration options.
CodeMirror.defaults = defaults;
// Functions to run when options are changed.
CodeMirror.optionHandlers = optionHandlers;
// Attach the necessary event handlers when initializing the editor
function registerEventHandlers(cm) {
var d = cm.display;
on(d.scroller, "mousedown", operation(cm, onMouseDown));
// Older IE's will not fire a second mousedown for a double click
if (ie && ie_version < 11)
{ on(d.scroller, "dblclick", operation(cm, function (e) {
if (signalDOMEvent(cm, e)) { return }
var pos = posFromMouse(cm, e);
if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
e_preventDefault(e);
var word = cm.findWordAt(pos);
extendSelection(cm.doc, word.anchor, word.head);
})); }
else
{ on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
// Some browsers fire contextmenu *after* opening the menu, at
// which point we can't mess with it anymore. Context menu is
// handled in onMouseDown for these browsers.
on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); });
on(d.input.getField(), "contextmenu", function (e) {
if (!d.scroller.contains(e.target)) { onContextMenu(cm, e); }
});
// Used to suppress mouse event handling when a touch happens
var touchFinished, prevTouch = {end: 0};
function finishTouch() {
if (d.activeTouch) {
touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
prevTouch = d.activeTouch;
prevTouch.end = +new Date;
}
}
function isMouseLikeTouchEvent(e) {
if (e.touches.length != 1) { return false }
var touch = e.touches[0];
return touch.radiusX <= 1 && touch.radiusY <= 1
}
function farAway(touch, other) {
if (other.left == null) { return true }
var dx = other.left - touch.left, dy = other.top - touch.top;
return dx * dx + dy * dy > 20 * 20
}
on(d.scroller, "touchstart", function (e) {
if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
d.input.ensurePolled();
clearTimeout(touchFinished);
var now = +new Date;
d.activeTouch = {start: now, moved: false,
prev: now - prevTouch.end <= 300 ? prevTouch : null};
if (e.touches.length == 1) {
d.activeTouch.left = e.touches[0].pageX;
d.activeTouch.top = e.touches[0].pageY;
}
}
});
on(d.scroller, "touchmove", function () {
if (d.activeTouch) { d.activeTouch.moved = true; }
});
on(d.scroller, "touchend", function (e) {
var touch = d.activeTouch;
if (touch && !eventInWidget(d, e) && touch.left != null &&
!touch.moved && new Date - touch.start < 300) {
var pos = cm.coordsChar(d.activeTouch, "page"), range;
if (!touch.prev || farAway(touch, touch.prev)) // Single tap
{ range = new Range(pos, pos); }
else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
{ range = cm.findWordAt(pos); }
else // Triple tap
{ range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
cm.setSelection(range.anchor, range.head);
cm.focus();
e_preventDefault(e);
}
finishTouch();
});
on(d.scroller, "touchcancel", finishTouch);
// Sync scrolling between fake scrollbars and real scrollable
// area, ensure viewport is updated when scrolling.
on(d.scroller, "scroll", function () {
if (d.scroller.clientHeight) {
updateScrollTop(cm, d.scroller.scrollTop);
setScrollLeft(cm, d.scroller.scrollLeft, true);
signal(cm, "scroll", cm);
}
});
// Listen to wheel events in order to try and update the viewport on time.
on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
// Prevent wrapper from ever scrolling
on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
d.dragFunctions = {
enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
start: function (e) { return onDragStart(cm, e); },
drop: operation(cm, onDrop),
leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
};
var inp = d.input.getField();
on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
on(inp, "keydown", operation(cm, onKeyDown));
on(inp, "keypress", operation(cm, onKeyPress));
on(inp, "focus", function (e) { return onFocus(cm, e); });
on(inp, "blur", function (e) { return onBlur(cm, e); });
}
var initHooks = [];
CodeMirror.defineInitHook = function (f) { return initHooks.push(f); };
// Indent the given line. The how parameter can be "smart",
// "add"/null, "subtract", or "prev". When aggressive is false
// (typically set to true for forced single-line indents), empty
// lines are not indented, and places where the mode returns Pass
// are left alone.
function indentLine(cm, n, how, aggressive) {
var doc = cm.doc, state;
if (how == null) { how = "add"; }
if (how == "smart") {
// Fall back to "prev" when the mode doesn't have an indentation
// method.
if (!doc.mode.indent) { how = "prev"; }
else { state = getContextBefore(cm, n).state; }
}
var tabSize = cm.options.tabSize;
var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
if (line.stateAfter) { line.stateAfter = null; }
var curSpaceString = line.text.match(/^\s*/)[0], indentation;
if (!aggressive && !/\S/.test(line.text)) {
indentation = 0;
how = "not";
} else if (how == "smart") {
indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
if (indentation == Pass || indentation > 150) {
if (!aggressive) { return }
how = "prev";
}
}
if (how == "prev") {
if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
else { indentation = 0; }
} else if (how == "add") {
indentation = curSpace + cm.options.indentUnit;
} else if (how == "subtract") {
indentation = curSpace - cm.options.indentUnit;
} else if (typeof how == "number") {
indentation = curSpace + how;
}
indentation = Math.max(0, indentation);
var indentString = "", pos = 0;
if (cm.options.indentWithTabs)
{ for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
if (pos < indentation) { indentString += spaceStr(indentation - pos); }
if (indentString != curSpaceString) {
replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
line.stateAfter = null;
return true
} else {
// Ensure that, if the cursor was in the whitespace at the start
// of the line, it is moved to the end of that space.
for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
var range = doc.sel.ranges[i$1];
if (range.head.line == n && range.head.ch < curSpaceString.length) {
var pos$1 = Pos(n, curSpaceString.length);
replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
break
}
}
}
}
// This will be set to a {lineWise: bool, text: [string]} object, so
// that, when pasting, we know what kind of selections the copied
// text was made out of.
var lastCopied = null;
function setLastCopied(newLastCopied) {
lastCopied = newLastCopied;
}
function applyTextInput(cm, inserted, deleted, sel, origin) {
var doc = cm.doc;
cm.display.shift = false;
if (!sel) { sel = doc.sel; }
var recent = +new Date - 200;
var paste = origin == "paste" || cm.state.pasteIncoming > recent;
var textLines = splitLinesAuto(inserted), multiPaste = null;
// When pasting N lines into N selections, insert one line per selection
if (paste && sel.ranges.length > 1) {
if (lastCopied && lastCopied.text.join("\n") == inserted) {
if (sel.ranges.length % lastCopied.text.length == 0) {
multiPaste = [];
for (var i = 0; i < lastCopied.text.length; i++)
{ multiPaste.push(doc.splitLines(lastCopied.text[i])); }
}
} else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
multiPaste = map(textLines, function (l) { return [l]; });
}
}
var updateInput = cm.curOp.updateInput;
// Normal behavior is to insert the new text into every selection
for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
var range = sel.ranges[i$1];
var from = range.from(), to = range.to();
if (range.empty()) {
if (deleted && deleted > 0) // Handle deletion
{ from = Pos(from.line, from.ch - deleted); }
else if (cm.state.overwrite && !paste) // Handle overwrite
{ to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n"))
{ from = to = Pos(from.line, 0); }
}
var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")};
makeChange(cm.doc, changeEvent);
signalLater(cm, "inputRead", cm, changeEvent);
}
if (inserted && !paste)
{ triggerElectric(cm, inserted); }
ensureCursorVisible(cm);
if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; }
cm.curOp.typing = true;
cm.state.pasteIncoming = cm.state.cutIncoming = -1;
}
function handlePaste(e, cm) {
var pasted = e.clipboardData && e.clipboardData.getData("Text");
if (pasted) {
e.preventDefault();
if (!cm.isReadOnly() && !cm.options.disableInput)
{ runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
return true
}
}
function triggerElectric(cm, inserted) {
// When an 'electric' character is inserted, immediately trigger a reindent
if (!cm.options.electricChars || !cm.options.smartIndent) { return }
var sel = cm.doc.sel;
for (var i = sel.ranges.length - 1; i >= 0; i--) {
var range = sel.ranges[i];
if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue }
var mode = cm.getModeAt(range.head);
var indented = false;
if (mode.electricChars) {
for (var j = 0; j < mode.electricChars.length; j++)
{ if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
indented = indentLine(cm, range.head.line, "smart");
break
} }
} else if (mode.electricInput) {
if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
{ indented = indentLine(cm, range.head.line, "smart"); }
}
if (indented) { signalLater(cm, "electricInput", cm, range.head.line); }
}
}
function copyableRanges(cm) {
var text = [], ranges = [];
for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
var line = cm.doc.sel.ranges[i].head.line;
var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
ranges.push(lineRange);
text.push(cm.getRange(lineRange.anchor, lineRange.head));
}
return {text: text, ranges: ranges}
}
function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {
field.setAttribute("autocorrect", autocorrect ? "" : "off");
field.setAttribute("autocapitalize", autocapitalize ? "" : "off");
field.setAttribute("spellcheck", !!spellcheck);
}
function hiddenTextarea() {
var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none");
var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
// The textarea is kept positioned near the cursor to prevent the
// fact that it'll be scrolled into view on input from scrolling
// our fake cursor out of view. On webkit, when wrap=off, paste is
// very slow. So make the area wide instead.
if (webkit) { te.style.width = "1000px"; }
else { te.setAttribute("wrap", "off"); }
// If border: 0; -- iOS fails to open keyboard (issue #1287)
if (ios) { te.style.border = "1px solid black"; }
disableBrowserMagic(te);
return div
}
// The publicly visible API. Note that methodOp(f) means
// 'wrap f in an operation, performed on its `this` parameter'.
// This is not the complete set of editor methods. Most of the
// methods defined on the Doc type are also injected into
// CodeMirror.prototype, for backwards compatibility and
// convenience.
function addEditorMethods(CodeMirror) {
var optionHandlers = CodeMirror.optionHandlers;
var helpers = CodeMirror.helpers = {};
CodeMirror.prototype = {
constructor: CodeMirror,
focus: function(){window.focus(); this.display.input.focus();},
setOption: function(option, value) {
var options = this.options, old = options[option];
if (options[option] == value && option != "mode") { return }
options[option] = value;
if (optionHandlers.hasOwnProperty(option))
{ operation(this, optionHandlers[option])(this, value, old); }
signal(this, "optionChange", this, option);
},
getOption: function(option) {return this.options[option]},
getDoc: function() {return this.doc},
addKeyMap: function(map, bottom) {
this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
},
removeKeyMap: function(map) {
var maps = this.state.keyMaps;
for (var i = 0; i < maps.length; ++i)
{ if (maps[i] == map || maps[i].name == map) {
maps.splice(i, 1);
return true
} }
},
addOverlay: methodOp(function(spec, options) {
var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
if (mode.startState) { throw new Error("Overlays may not be stateful.") }
insertSorted(this.state.overlays,
{mode: mode, modeSpec: spec, opaque: options && options.opaque,
priority: (options && options.priority) || 0},
function (overlay) { return overlay.priority; });
this.state.modeGen++;
regChange(this);
}),
removeOverlay: methodOp(function(spec) {
var overlays = this.state.overlays;
for (var i = 0; i < overlays.length; ++i) {
var cur = overlays[i].modeSpec;
if (cur == spec || typeof spec == "string" && cur.name == spec) {
overlays.splice(i, 1);
this.state.modeGen++;
regChange(this);
return
}
}
}),
indentLine: methodOp(function(n, dir, aggressive) {
if (typeof dir != "string" && typeof dir != "number") {
if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
else { dir = dir ? "add" : "subtract"; }
}
if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
}),
indentSelection: methodOp(function(how) {
var ranges = this.doc.sel.ranges, end = -1;
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
if (!range.empty()) {
var from = range.from(), to = range.to();
var start = Math.max(end, from.line);
end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
for (var j = start; j < end; ++j)
{ indentLine(this, j, how); }
var newRanges = this.doc.sel.ranges;
if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
{ replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
} else if (range.head.line > end) {
indentLine(this, range.head.line, how, true);
end = range.head.line;
if (i == this.doc.sel.primIndex) { ensureCursorVisible(this); }
}
}
}),
// Fetch the parser token for a given character. Useful for hacks
// that want to inspect the mode state (say, for completion).
getTokenAt: function(pos, precise) {
return takeToken(this, pos, precise)
},
getLineTokens: function(line, precise) {
return takeToken(this, Pos(line), precise, true)
},
getTokenTypeAt: function(pos) {
pos = clipPos(this.doc, pos);
var styles = getLineStyles(this, getLine(this.doc, pos.line));
var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
var type;
if (ch == 0) { type = styles[2]; }
else { for (;;) {
var mid = (before + after) >> 1;
if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
else { type = styles[mid * 2 + 2]; break }
} }
var cut = type ? type.indexOf("overlay ") : -1;
return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
},
getModeAt: function(pos) {
var mode = this.doc.mode;
if (!mode.innerMode) { return mode }
return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
},
getHelper: function(pos, type) {
return this.getHelpers(pos, type)[0]
},
getHelpers: function(pos, type) {
var found = [];
if (!helpers.hasOwnProperty(type)) { return found }
var help = helpers[type], mode = this.getModeAt(pos);
if (typeof mode[type] == "string") {
if (help[mode[type]]) { found.push(help[mode[type]]); }
} else if (mode[type]) {
for (var i = 0; i < mode[type].length; i++) {
var val = help[mode[type][i]];
if (val) { found.push(val); }
}
} else if (mode.helperType && help[mode.helperType]) {
found.push(help[mode.helperType]);
} else if (help[mode.name]) {
found.push(help[mode.name]);
}
for (var i$1 = 0; i$1 < help._global.length; i$1++) {
var cur = help._global[i$1];
if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
{ found.push(cur.val); }
}
return found
},
getStateAfter: function(line, precise) {
var doc = this.doc;
line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
return getContextBefore(this, line + 1, precise).state
},
cursorCoords: function(start, mode) {
var pos, range = this.doc.sel.primary();
if (start == null) { pos = range.head; }
else if (typeof start == "object") { pos = clipPos(this.doc, start); }
else { pos = start ? range.from() : range.to(); }
return cursorCoords(this, pos, mode || "page")
},
charCoords: function(pos, mode) {
return charCoords(this, clipPos(this.doc, pos), mode || "page")
},
coordsChar: function(coords, mode) {
coords = fromCoordSystem(this, coords, mode || "page");
return coordsChar(this, coords.left, coords.top)
},
lineAtHeight: function(height, mode) {
height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
return lineAtHeight(this.doc, height + this.display.viewOffset)
},
heightAtLine: function(line, mode, includeWidgets) {
var end = false, lineObj;
if (typeof line == "number") {
var last = this.doc.first + this.doc.size - 1;
if (line < this.doc.first) { line = this.doc.first; }
else if (line > last) { line = last; end = true; }
lineObj = getLine(this.doc, line);
} else {
lineObj = line;
}
return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
(end ? this.doc.height - heightAtLine(lineObj) : 0)
},
defaultTextHeight: function() { return textHeight(this.display) },
defaultCharWidth: function() { return charWidth(this.display) },
getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
addWidget: function(pos, node, scroll, vert, horiz) {
var display = this.display;
pos = cursorCoords(this, clipPos(this.doc, pos));
var top = pos.bottom, left = pos.left;
node.style.position = "absolute";
node.setAttribute("cm-ignore-events", "true");
this.display.input.setUneditable(node);
display.sizer.appendChild(node);
if (vert == "over") {
top = pos.top;
} else if (vert == "above" || vert == "near") {
var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
// Default to positioning above (if specified and possible); otherwise default to positioning below
if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
{ top = pos.top - node.offsetHeight; }
else if (pos.bottom + node.offsetHeight <= vspace)
{ top = pos.bottom; }
if (left + node.offsetWidth > hspace)
{ left = hspace - node.offsetWidth; }
}
node.style.top = top + "px";
node.style.left = node.style.right = "";
if (horiz == "right") {
left = display.sizer.clientWidth - node.offsetWidth;
node.style.right = "0px";
} else {
if (horiz == "left") { left = 0; }
else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
node.style.left = left + "px";
}
if (scroll)
{ scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
},
triggerOnKeyDown: methodOp(onKeyDown),
triggerOnKeyPress: methodOp(onKeyPress),
triggerOnKeyUp: onKeyUp,
triggerOnMouseDown: methodOp(onMouseDown),
execCommand: function(cmd) {
if (commands.hasOwnProperty(cmd))
{ return commands[cmd].call(null, this) }
},
triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
findPosH: function(from, amount, unit, visually) {
var dir = 1;
if (amount < 0) { dir = -1; amount = -amount; }
var cur = clipPos(this.doc, from);
for (var i = 0; i < amount; ++i) {
cur = findPosH(this.doc, cur, dir, unit, visually);
if (cur.hitSide) { break }
}
return cur
},
moveH: methodOp(function(dir, unit) {
var this$1 = this;
this.extendSelectionsBy(function (range) {
if (this$1.display.shift || this$1.doc.extend || range.empty())
{ return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) }
else
{ return dir < 0 ? range.from() : range.to() }
}, sel_move);
}),
deleteH: methodOp(function(dir, unit) {
var sel = this.doc.sel, doc = this.doc;
if (sel.somethingSelected())
{ doc.replaceSelection("", null, "+delete"); }
else
{ deleteNearSelection(this, function (range) {
var other = findPosH(doc, range.head, dir, unit, false);
return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}
}); }
}),
findPosV: function(from, amount, unit, goalColumn) {
var dir = 1, x = goalColumn;
if (amount < 0) { dir = -1; amount = -amount; }
var cur = clipPos(this.doc, from);
for (var i = 0; i < amount; ++i) {
var coords = cursorCoords(this, cur, "div");
if (x == null) { x = coords.left; }
else { coords.left = x; }
cur = findPosV(this, coords, dir, unit);
if (cur.hitSide) { break }
}
return cur
},
moveV: methodOp(function(dir, unit) {
var this$1 = this;
var doc = this.doc, goals = [];
var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
doc.extendSelectionsBy(function (range) {
if (collapse)
{ return dir < 0 ? range.from() : range.to() }
var headPos = cursorCoords(this$1, range.head, "div");
if (range.goalColumn != null) { headPos.left = range.goalColumn; }
goals.push(headPos.left);
var pos = findPosV(this$1, headPos, dir, unit);
if (unit == "page" && range == doc.sel.primary())
{ addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
return pos
}, sel_move);
if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
{ doc.sel.ranges[i].goalColumn = goals[i]; } }
}),
// Find the word at the given position (as returned by coordsChar).
findWordAt: function(pos) {
var doc = this.doc, line = getLine(doc, pos.line).text;
var start = pos.ch, end = pos.ch;
if (line) {
var helper = this.getHelper(pos, "wordChars");
if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
var startChar = line.charAt(start);
var check = isWordChar(startChar, helper)
? function (ch) { return isWordChar(ch, helper); }
: /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
: function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
while (start > 0 && check(line.charAt(start - 1))) { --start; }
while (end < line.length && check(line.charAt(end))) { ++end; }
}
return new Range(Pos(pos.line, start), Pos(pos.line, end))
},
toggleOverwrite: function(value) {
if (value != null && value == this.state.overwrite) { return }
if (this.state.overwrite = !this.state.overwrite)
{ addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
else
{ rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
signal(this, "overwriteToggle", this, this.state.overwrite);
},
hasFocus: function() { return this.display.input.getField() == activeElt() },
isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
getScrollInfo: function() {
var scroller = this.display.scroller;
return {left: scroller.scrollLeft, top: scroller.scrollTop,
height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
},
scrollIntoView: methodOp(function(range, margin) {
if (range == null) {
range = {from: this.doc.sel.primary().head, to: null};
if (margin == null) { margin = this.options.cursorScrollMargin; }
} else if (typeof range == "number") {
range = {from: Pos(range, 0), to: null};
} else if (range.from == null) {
range = {from: range, to: null};
}
if (!range.to) { range.to = range.from; }
range.margin = margin || 0;
if (range.from.line != null) {
scrollToRange(this, range);
} else {
scrollToCoordsRange(this, range.from, range.to, range.margin);
}
}),
setSize: methodOp(function(width, height) {
var this$1 = this;
var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
if (width != null) { this.display.wrapper.style.width = interpret(width); }
if (height != null) { this.display.wrapper.style.height = interpret(height); }
if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
var lineNo = this.display.viewFrom;
this.doc.iter(lineNo, this.display.viewTo, function (line) {
if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
{ if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } } }
++lineNo;
});
this.curOp.forceUpdate = true;
signal(this, "refresh", this);
}),
operation: function(f){return runInOp(this, f)},
startOperation: function(){return startOperation(this)},
endOperation: function(){return endOperation(this)},
refresh: methodOp(function() {
var oldHeight = this.display.cachedTextHeight;
regChange(this);
this.curOp.forceUpdate = true;
clearCaches(this);
scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
updateGutterSpace(this.display);
if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5 || this.options.lineWrapping)
{ estimateLineHeights(this); }
signal(this, "refresh", this);
}),
swapDoc: methodOp(function(doc) {
var old = this.doc;
old.cm = null;
// Cancel the current text selection if any (#5821)
if (this.state.selectingText) { this.state.selectingText(); }
attachDoc(this, doc);
clearCaches(this);
this.display.input.reset();
scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
this.curOp.forceScroll = true;
signalLater(this, "swapDoc", this, old);
return old
}),
phrase: function(phraseText) {
var phrases = this.options.phrases;
return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText
},
getInputField: function(){return this.display.input.getField()},
getWrapperElement: function(){return this.display.wrapper},
getScrollerElement: function(){return this.display.scroller},
getGutterElement: function(){return this.display.gutters}
};
eventMixin(CodeMirror);
CodeMirror.registerHelper = function(type, name, value) {
if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
helpers[type][name] = value;
};
CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
CodeMirror.registerHelper(type, name, value);
helpers[type]._global.push({pred: predicate, val: value});
};
}
// Used for horizontal relative motion. Dir is -1 or 1 (left or
// right), unit can be "codepoint", "char", "column" (like char, but
// doesn't cross line boundaries), "word" (across next word), or
// "group" (to the start of next group of word or
// non-word-non-whitespace chars). The visually param controls
// whether, in right-to-left text, direction 1 means to move towards
// the next index in the string, or towards the character to the right
// of the current position. The resulting position will have a
// hitSide=true property if it reached the end of the document.
function findPosH(doc, pos, dir, unit, visually) {
var oldPos = pos;
var origDir = dir;
var lineObj = getLine(doc, pos.line);
var lineDir = visually && doc.direction == "rtl" ? -dir : dir;
function findNextLine() {
var l = pos.line + lineDir;
if (l < doc.first || l >= doc.first + doc.size) { return false }
pos = new Pos(l, pos.ch, pos.sticky);
return lineObj = getLine(doc, l)
}
function moveOnce(boundToLine) {
var next;
if (unit == "codepoint") {
var ch = lineObj.text.charCodeAt(pos.ch + (unit > 0 ? 0 : -1));
if (isNaN(ch)) { next = null; }
else { next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (ch >= 0xD800 && ch < 0xDC00 ? 2 : 1))),
-dir); }
} else if (visually) {
next = moveVisually(doc.cm, lineObj, pos, dir);
} else {
next = moveLogically(lineObj, pos, dir);
}
if (next == null) {
if (!boundToLine && findNextLine())
{ pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir); }
else
{ return false }
} else {
pos = next;
}
return true
}
if (unit == "char" || unit == "codepoint") {
moveOnce();
} else if (unit == "column") {
moveOnce(true);
} else if (unit == "word" || unit == "group") {
var sawType = null, group = unit == "group";
var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
for (var first = true;; first = false) {
if (dir < 0 && !moveOnce(!first)) { break }
var cur = lineObj.text.charAt(pos.ch) || "\n";
var type = isWordChar(cur, helper) ? "w"
: group && cur == "\n" ? "n"
: !group || /\s/.test(cur) ? null
: "p";
if (group && !first && !type) { type = "s"; }
if (sawType && sawType != type) {
if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
break
}
if (type) { sawType = type; }
if (dir > 0 && !moveOnce(!first)) { break }
}
}
var result = skipAtomic(doc, pos, oldPos, origDir, true);
if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
return result
}
// For relative vertical movement. Dir may be -1 or 1. Unit can be
// "page" or "line". The resulting position will have a hitSide=true
// property if it reached the end of the document.
function findPosV(cm, pos, dir, unit) {
var doc = cm.doc, x = pos.left, y;
if (unit == "page") {
var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
} else if (unit == "line") {
y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
}
var target;
for (;;) {
target = coordsChar(cm, x, y);
if (!target.outside) { break }
if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
y += dir * 5;
}
return target
}
// CONTENTEDITABLE INPUT STYLE
var ContentEditableInput = function(cm) {
this.cm = cm;
this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
this.polling = new Delayed();
this.composing = null;
this.gracePeriod = false;
this.readDOMTimeout = null;
};
ContentEditableInput.prototype.init = function (display) {
var this$1 = this;
var input = this, cm = input.cm;
var div = input.div = display.lineDiv;
disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize);
function belongsToInput(e) {
for (var t = e.target; t; t = t.parentNode) {
if (t == div) { return true }
if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { break }
}
return false
}
on(div, "paste", function (e) {
if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
// IE doesn't fire input events, so we schedule a read for the pasted content in this way
if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
});
on(div, "compositionstart", function (e) {
this$1.composing = {data: e.data, done: false};
});
on(div, "compositionupdate", function (e) {
if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
});
on(div, "compositionend", function (e) {
if (this$1.composing) {
if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
this$1.composing.done = true;
}
});
on(div, "touchstart", function () { return input.forceCompositionEnd(); });
on(div, "input", function () {
if (!this$1.composing) { this$1.readFromDOMSoon(); }
});
function onCopyCut(e) {
if (!belongsToInput(e) || signalDOMEvent(cm, e)) { return }
if (cm.somethingSelected()) {
setLastCopied({lineWise: false, text: cm.getSelections()});
if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
} else if (!cm.options.lineWiseCopyCut) {
return
} else {
var ranges = copyableRanges(cm);
setLastCopied({lineWise: true, text: ranges.text});
if (e.type == "cut") {
cm.operation(function () {
cm.setSelections(ranges.ranges, 0, sel_dontScroll);
cm.replaceSelection("", null, "cut");
});
}
}
if (e.clipboardData) {
e.clipboardData.clearData();
var content = lastCopied.text.join("\n");
// iOS exposes the clipboard API, but seems to discard content inserted into it
e.clipboardData.setData("Text", content);
if (e.clipboardData.getData("Text") == content) {
e.preventDefault();
return
}
}
// Old-fashioned briefly-focus-a-textarea hack
var kludge = hiddenTextarea(), te = kludge.firstChild;
cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
te.value = lastCopied.text.join("\n");
var hadFocus = document.activeElement;
selectInput(te);
setTimeout(function () {
cm.display.lineSpace.removeChild(kludge);
hadFocus.focus();
if (hadFocus == div) { input.showPrimarySelection(); }
}, 50);
}
on(div, "copy", onCopyCut);
on(div, "cut", onCopyCut);
};
ContentEditableInput.prototype.screenReaderLabelChanged = function (label) {
// Label for screenreaders, accessibility
if(label) {
this.div.setAttribute('aria-label', label);
} else {
this.div.removeAttribute('aria-label');
}
};
ContentEditableInput.prototype.prepareSelection = function () {
var result = prepareSelection(this.cm, false);
result.focus = document.activeElement == this.div;
return result
};
ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
if (!info || !this.cm.display.view.length) { return }
if (info.focus || takeFocus) { this.showPrimarySelection(); }
this.showMultipleSelections(info);
};
ContentEditableInput.prototype.getSelection = function () {
return this.cm.display.wrapper.ownerDocument.getSelection()
};
ContentEditableInput.prototype.showPrimarySelection = function () {
var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
var from = prim.from(), to = prim.to();
if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
sel.removeAllRanges();
return
}
var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
cmp(minPos(curAnchor, curFocus), from) == 0 &&
cmp(maxPos(curAnchor, curFocus), to) == 0)
{ return }
var view = cm.display.view;
var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
{node: view[0].measure.map[2], offset: 0};
var end = to.line < cm.display.viewTo && posToDOM(cm, to);
if (!end) {
var measure = view[view.length - 1].measure;
var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
}
if (!start || !end) {
sel.removeAllRanges();
return
}
var old = sel.rangeCount && sel.getRangeAt(0), rng;
try { rng = range(start.node, start.offset, end.offset, end.node); }
catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
if (rng) {
if (!gecko && cm.state.focused) {
sel.collapse(start.node, start.offset);
if (!rng.collapsed) {
sel.removeAllRanges();
sel.addRange(rng);
}
} else {
sel.removeAllRanges();
sel.addRange(rng);
}
if (old && sel.anchorNode == null) { sel.addRange(old); }
else if (gecko) { this.startGracePeriod(); }
}
this.rememberSelection();
};
ContentEditableInput.prototype.startGracePeriod = function () {
var this$1 = this;
clearTimeout(this.gracePeriod);
this.gracePeriod = setTimeout(function () {
this$1.gracePeriod = false;
if (this$1.selectionChanged())
{ this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
}, 20);
};
ContentEditableInput.prototype.showMultipleSelections = function (info) {
removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
};
ContentEditableInput.prototype.rememberSelection = function () {
var sel = this.getSelection();
this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
};
ContentEditableInput.prototype.selectionInEditor = function () {
var sel = this.getSelection();
if (!sel.rangeCount) { return false }
var node = sel.getRangeAt(0).commonAncestorContainer;
return contains(this.div, node)
};
ContentEditableInput.prototype.focus = function () {
if (this.cm.options.readOnly != "nocursor") {
if (!this.selectionInEditor() || document.activeElement != this.div)
{ this.showSelection(this.prepareSelection(), true); }
this.div.focus();
}
};
ContentEditableInput.prototype.blur = function () { this.div.blur(); };
ContentEditableInput.prototype.getField = function () { return this.div };
ContentEditableInput.prototype.supportsTouch = function () { return true };
ContentEditableInput.prototype.receivedFocus = function () {
var input = this;
if (this.selectionInEditor())
{ this.pollSelection(); }
else
{ runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
function poll() {
if (input.cm.state.focused) {
input.pollSelection();
input.polling.set(input.cm.options.pollInterval, poll);
}
}
this.polling.set(this.cm.options.pollInterval, poll);
};
ContentEditableInput.prototype.selectionChanged = function () {
var sel = this.getSelection();
return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
};
ContentEditableInput.prototype.pollSelection = function () {
if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
var sel = this.getSelection(), cm = this.cm;
// On Android Chrome (version 56, at least), backspacing into an
// uneditable block element will put the cursor in that element,
// and then, because it's not editable, hide the virtual keyboard.
// Because Android doesn't allow us to actually detect backspace
// presses in a sane way, this code checks for when that happens
// and simulates a backspace press in this case.
if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) {
this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
this.blur();
this.focus();
return
}
if (this.composing) { return }
this.rememberSelection();
var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
var head = domToPos(cm, sel.focusNode, sel.focusOffset);
if (anchor && head) { runInOp(cm, function () {
setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
}); }
};
ContentEditableInput.prototype.pollContent = function () {
if (this.readDOMTimeout != null) {
clearTimeout(this.readDOMTimeout);
this.readDOMTimeout = null;
}
var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
var from = sel.from(), to = sel.to();
if (from.ch == 0 && from.line > cm.firstLine())
{ from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
{ to = Pos(to.line + 1, 0); }
if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
var fromIndex, fromLine, fromNode;
if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
fromLine = lineNo(display.view[0].line);
fromNode = display.view[0].node;
} else {
fromLine = lineNo(display.view[fromIndex].line);
fromNode = display.view[fromIndex - 1].node.nextSibling;
}
var toIndex = findViewIndex(cm, to.line);
var toLine, toNode;
if (toIndex == display.view.length - 1) {
toLine = display.viewTo - 1;
toNode = display.lineDiv.lastChild;
} else {
toLine = lineNo(display.view[toIndex + 1].line) - 1;
toNode = display.view[toIndex + 1].node.previousSibling;
}
if (!fromNode) { return false }
var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
while (newText.length > 1 && oldText.length > 1) {
if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
else { break }
}
var cutFront = 0, cutEnd = 0;
var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
{ ++cutFront; }
var newBot = lst(newText), oldBot = lst(oldText);
var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
oldBot.length - (oldText.length == 1 ? cutFront : 0));
while (cutEnd < maxCutEnd &&
newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
{ ++cutEnd; }
// Try to move start of change to start of selection if ambiguous
if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
while (cutFront && cutFront > from.ch &&
newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
cutFront--;
cutEnd++;
}
}
newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
var chFrom = Pos(fromLine, cutFront);
var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
replaceRange(cm.doc, newText, chFrom, chTo, "+input");
return true
}
};
ContentEditableInput.prototype.ensurePolled = function () {
this.forceCompositionEnd();
};
ContentEditableInput.prototype.reset = function () {
this.forceCompositionEnd();
};
ContentEditableInput.prototype.forceCompositionEnd = function () {
if (!this.composing) { return }
clearTimeout(this.readDOMTimeout);
this.composing = null;
this.updateFromDOM();
this.div.blur();
this.div.focus();
};
ContentEditableInput.prototype.readFromDOMSoon = function () {
var this$1 = this;
if (this.readDOMTimeout != null) { return }
this.readDOMTimeout = setTimeout(function () {
this$1.readDOMTimeout = null;
if (this$1.composing) {
if (this$1.composing.done) { this$1.composing = null; }
else { return }
}
this$1.updateFromDOM();
}, 80);
};
ContentEditableInput.prototype.updateFromDOM = function () {
var this$1 = this;
if (this.cm.isReadOnly() || !this.pollContent())
{ runInOp(this.cm, function () { return regChange(this$1.cm); }); }
};
ContentEditableInput.prototype.setUneditable = function (node) {
node.contentEditable = "false";
};
ContentEditableInput.prototype.onKeyPress = function (e) {
if (e.charCode == 0 || this.composing) { return }
e.preventDefault();
if (!this.cm.isReadOnly())
{ operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
};
ContentEditableInput.prototype.readOnlyChanged = function (val) {
this.div.contentEditable = String(val != "nocursor");
};
ContentEditableInput.prototype.onContextMenu = function () {};
ContentEditableInput.prototype.resetPosition = function () {};
ContentEditableInput.prototype.needsContentAttribute = true;
function posToDOM(cm, pos) {
var view = findViewForLine(cm, pos.line);
if (!view || view.hidden) { return null }
var line = getLine(cm.doc, pos.line);
var info = mapFromLineView(view, line, pos.line);
var order = getOrder(line, cm.doc.direction), side = "left";
if (order) {
var partPos = getBidiPartAt(order, pos.ch);
side = partPos % 2 ? "right" : "left";
}
var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
result.offset = result.collapse == "right" ? result.end : result.start;
return result
}
function isInGutter(node) {
for (var scan = node; scan; scan = scan.parentNode)
{ if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
return false
}
function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
function domTextBetween(cm, from, to, fromLine, toLine) {
var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;
function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
function close() {
if (closing) {
text += lineSep;
if (extraLinebreak) { text += lineSep; }
closing = extraLinebreak = false;
}
}
function addText(str) {
if (str) {
close();
text += str;
}
}
function walk(node) {
if (node.nodeType == 1) {
var cmText = node.getAttribute("cm-text");
if (cmText) {
addText(cmText);
return
}
var markerID = node.getAttribute("cm-marker"), range;
if (markerID) {
var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
if (found.length && (range = found[0].find(0)))
{ addText(getBetween(cm.doc, range.from, range.to).join(lineSep)); }
return
}
if (node.getAttribute("contenteditable") == "false") { return }
var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);
if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }
if (isBlock) { close(); }
for (var i = 0; i < node.childNodes.length; i++)
{ walk(node.childNodes[i]); }
if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; }
if (isBlock) { closing = true; }
} else if (node.nodeType == 3) {
addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "));
}
}
for (;;) {
walk(from);
if (from == to) { break }
from = from.nextSibling;
extraLinebreak = false;
}
return text
}
function domToPos(cm, node, offset) {
var lineNode;
if (node == cm.display.lineDiv) {
lineNode = cm.display.lineDiv.childNodes[offset];
if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
node = null; offset = 0;
} else {
for (lineNode = node;; lineNode = lineNode.parentNode) {
if (!lineNode || lineNode == cm.display.lineDiv) { return null }
if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
}
}
for (var i = 0; i < cm.display.view.length; i++) {
var lineView = cm.display.view[i];
if (lineView.node == lineNode)
{ return locateNodeInLineView(lineView, node, offset) }
}
}
function locateNodeInLineView(lineView, node, offset) {
var wrapper = lineView.text.firstChild, bad = false;
if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
if (node == wrapper) {
bad = true;
node = wrapper.childNodes[offset];
offset = 0;
if (!node) {
var line = lineView.rest ? lst(lineView.rest) : lineView.line;
return badPos(Pos(lineNo(line), line.text.length), bad)
}
}
var textNode = node.nodeType == 3 ? node : null, topNode = node;
if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
textNode = node.firstChild;
if (offset) { offset = textNode.nodeValue.length; }
}
while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
var measure = lineView.measure, maps = measure.maps;
function find(textNode, topNode, offset) {
for (var i = -1; i < (maps ? maps.length : 0); i++) {
var map = i < 0 ? measure.map : maps[i];
for (var j = 0; j < map.length; j += 3) {
var curNode = map[j + 2];
if (curNode == textNode || curNode == topNode) {
var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
var ch = map[j] + offset;
if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)]; }
return Pos(line, ch)
}
}
}
}
var found = find(textNode, topNode, offset);
if (found) { return badPos(found, bad) }
// FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
found = find(after, after.firstChild, 0);
if (found)
{ return badPos(Pos(found.line, found.ch - dist), bad) }
else
{ dist += after.textContent.length; }
}
for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
found = find(before, before.firstChild, -1);
if (found)
{ return badPos(Pos(found.line, found.ch + dist$1), bad) }
else
{ dist$1 += before.textContent.length; }
}
}
// TEXTAREA INPUT STYLE
var TextareaInput = function(cm) {
this.cm = cm;
// See input.poll and input.reset
this.prevInput = "";
// Flag that indicates whether we expect input to appear real soon
// now (after some event like 'keypress' or 'input') and are
// polling intensively.
this.pollingFast = false;
// Self-resetting timeout for the poller
this.polling = new Delayed();
// Used to work around IE issue with selection being forgotten when focus moves away from textarea
this.hasSelection = false;
this.composing = null;
};
TextareaInput.prototype.init = function (display) {
var this$1 = this;
var input = this, cm = this.cm;
this.createField(display);
var te = this.textarea;
display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);
// Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
if (ios) { te.style.width = "0px"; }
on(te, "input", function () {
if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
input.poll();
});
on(te, "paste", function (e) {
if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
cm.state.pasteIncoming = +new Date;
input.fastPoll();
});
function prepareCopyCut(e) {
if (signalDOMEvent(cm, e)) { return }
if (cm.somethingSelected()) {
setLastCopied({lineWise: false, text: cm.getSelections()});
} else if (!cm.options.lineWiseCopyCut) {
return
} else {
var ranges = copyableRanges(cm);
setLastCopied({lineWise: true, text: ranges.text});
if (e.type == "cut") {
cm.setSelections(ranges.ranges, null, sel_dontScroll);
} else {
input.prevInput = "";
te.value = ranges.text.join("\n");
selectInput(te);
}
}
if (e.type == "cut") { cm.state.cutIncoming = +new Date; }
}
on(te, "cut", prepareCopyCut);
on(te, "copy", prepareCopyCut);
on(display.scroller, "paste", function (e) {
if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
if (!te.dispatchEvent) {
cm.state.pasteIncoming = +new Date;
input.focus();
return
}
// Pass the `paste` event to the textarea so it's handled by its event listener.
var event = new Event("paste");
event.clipboardData = e.clipboardData;
te.dispatchEvent(event);
});
// Prevent normal selection in the editor (we handle our own)
on(display.lineSpace, "selectstart", function (e) {
if (!eventInWidget(display, e)) { e_preventDefault(e); }
});
on(te, "compositionstart", function () {
var start = cm.getCursor("from");
if (input.composing) { input.composing.range.clear(); }
input.composing = {
start: start,
range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
};
});
on(te, "compositionend", function () {
if (input.composing) {
input.poll();
input.composing.range.clear();
input.composing = null;
}
});
};
TextareaInput.prototype.createField = function (_display) {
// Wraps and hides input textarea
this.wrapper = hiddenTextarea();
// The semihidden textarea that is focused when the editor is
// focused, and receives input.
this.textarea = this.wrapper.firstChild;
};
TextareaInput.prototype.screenReaderLabelChanged = function (label) {
// Label for screenreaders, accessibility
if(label) {
this.textarea.setAttribute('aria-label', label);
} else {
this.textarea.removeAttribute('aria-label');
}
};
TextareaInput.prototype.prepareSelection = function () {
// Redraw the selection and/or cursor
var cm = this.cm, display = cm.display, doc = cm.doc;
var result = prepareSelection(cm);
// Move the hidden textarea near the cursor to prevent scrolling artifacts
if (cm.options.moveInputWithCursor) {
var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
headPos.top + lineOff.top - wrapOff.top));
result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
headPos.left + lineOff.left - wrapOff.left));
}
return result
};
TextareaInput.prototype.showSelection = function (drawn) {
var cm = this.cm, display = cm.display;
removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
removeChildrenAndAdd(display.selectionDiv, drawn.selection);
if (drawn.teTop != null) {
this.wrapper.style.top = drawn.teTop + "px";
this.wrapper.style.left = drawn.teLeft + "px";
}
};
// Reset the input to correspond to the selection (or to be empty,
// when not typing and nothing is selected)
TextareaInput.prototype.reset = function (typing) {
if (this.contextMenuPending || this.composing) { return }
var cm = this.cm;
if (cm.somethingSelected()) {
this.prevInput = "";
var content = cm.getSelection();
this.textarea.value = content;
if (cm.state.focused) { selectInput(this.textarea); }
if (ie && ie_version >= 9) { this.hasSelection = content; }
} else if (!typing) {
this.prevInput = this.textarea.value = "";
if (ie && ie_version >= 9) { this.hasSelection = null; }
}
};
TextareaInput.prototype.getField = function () { return this.textarea };
TextareaInput.prototype.supportsTouch = function () { return false };
TextareaInput.prototype.focus = function () {
if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
try { this.textarea.focus(); }
catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
}
};
TextareaInput.prototype.blur = function () { this.textarea.blur(); };
TextareaInput.prototype.resetPosition = function () {
this.wrapper.style.top = this.wrapper.style.left = 0;
};
TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
// Poll for input changes, using the normal rate of polling. This
// runs as long as the editor is focused.
TextareaInput.prototype.slowPoll = function () {
var this$1 = this;
if (this.pollingFast) { return }
this.polling.set(this.cm.options.pollInterval, function () {
this$1.poll();
if (this$1.cm.state.focused) { this$1.slowPoll(); }
});
};
// When an event has just come in that is likely to add or change
// something in the input textarea, we poll faster, to ensure that
// the change appears on the screen quickly.
TextareaInput.prototype.fastPoll = function () {
var missed = false, input = this;
input.pollingFast = true;
function p() {
var changed = input.poll();
if (!changed && !missed) {missed = true; input.polling.set(60, p);}
else {input.pollingFast = false; input.slowPoll();}
}
input.polling.set(20, p);
};
// Read input from the textarea, and update the document to match.
// When something is selected, it is present in the textarea, and
// selected (unless it is huge, in which case a placeholder is
// used). When nothing is selected, the cursor sits after previously
// seen text (can be empty), which is stored in prevInput (we must
// not reset the textarea when typing, because that breaks IME).
TextareaInput.prototype.poll = function () {
var this$1 = this;
var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
// Since this is called a *lot*, try to bail out as cheaply as
// possible when it is clear that nothing happened. hasSelection
// will be the case when there is a lot of text in the textarea,
// in which case reading its value would be expensive.
if (this.contextMenuPending || !cm.state.focused ||
(hasSelection(input) && !prevInput && !this.composing) ||
cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
{ return false }
var text = input.value;
// If nothing changed, bail.
if (text == prevInput && !cm.somethingSelected()) { return false }
// Work around nonsensical selection resetting in IE9/10, and
// inexplicable appearance of private area unicode characters on
// some key combos in Mac (#2689).
if (ie && ie_version >= 9 && this.hasSelection === text ||
mac && /[\uf700-\uf7ff]/.test(text)) {
cm.display.input.reset();
return false
}
if (cm.doc.sel == cm.display.selForContextMenu) {
var first = text.charCodeAt(0);
if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
}
// Find the part of the input that is actually new
var same = 0, l = Math.min(prevInput.length, text.length);
while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
runInOp(cm, function () {
applyTextInput(cm, text.slice(same), prevInput.length - same,
null, this$1.composing ? "*compose" : null);
// Don't leave long text in the textarea, since it makes further polling slow
if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
else { this$1.prevInput = text; }
if (this$1.composing) {
this$1.composing.range.clear();
this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
{className: "CodeMirror-composing"});
}
});
return true
};
TextareaInput.prototype.ensurePolled = function () {
if (this.pollingFast && this.poll()) { this.pollingFast = false; }
};
TextareaInput.prototype.onKeyPress = function () {
if (ie && ie_version >= 9) { this.hasSelection = null; }
this.fastPoll();
};
TextareaInput.prototype.onContextMenu = function (e) {
var input = this, cm = input.cm, display = cm.display, te = input.textarea;
if (input.contextMenuPending) { input.contextMenuPending(); }
var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
if (!pos || presto) { return } // Opera is difficult.
// Reset the current text selection only if the click is done outside of the selection
// and 'resetSelectionOnContextMenu' option is true.
var reset = cm.options.resetSelectionOnContextMenu;
if (reset && cm.doc.sel.contains(pos) == -1)
{ operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect();
input.wrapper.style.cssText = "position: static";
te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
var oldScrollY;
if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)
display.input.focus();
if (webkit) { window.scrollTo(null, oldScrollY); }
display.input.reset();
// Adds "Select all" to context menu in FF
if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
input.contextMenuPending = rehide;
display.selForContextMenu = cm.doc.sel;
clearTimeout(display.detectingSelectAll);
// Select-all will be greyed out if there's nothing to select, so
// this adds a zero-width space so that we can later check whether
// it got selected.
function prepareSelectAllHack() {
if (te.selectionStart != null) {
var selected = cm.somethingSelected();
var extval = "\u200b" + (selected ? te.value : "");
te.value = "\u21da"; // Used to catch context-menu undo
te.value = extval;
input.prevInput = selected ? "" : "\u200b";
te.selectionStart = 1; te.selectionEnd = extval.length;
// Re-set this, in case some other handler touched the
// selection in the meantime.
display.selForContextMenu = cm.doc.sel;
}
}
function rehide() {
if (input.contextMenuPending != rehide) { return }
input.contextMenuPending = false;
input.wrapper.style.cssText = oldWrapperCSS;
te.style.cssText = oldCSS;
if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
// Try to detect the user choosing select-all
if (te.selectionStart != null) {
if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
var i = 0, poll = function () {
if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
te.selectionEnd > 0 && input.prevInput == "\u200b") {
operation(cm, selectAll)(cm);
} else if (i++ < 10) {
display.detectingSelectAll = setTimeout(poll, 500);
} else {
display.selForContextMenu = null;
display.input.reset();
}
};
display.detectingSelectAll = setTimeout(poll, 200);
}
}
if (ie && ie_version >= 9) { prepareSelectAllHack(); }
if (captureRightClick) {
e_stop(e);
var mouseup = function () {
off(window, "mouseup", mouseup);
setTimeout(rehide, 20);
};
on(window, "mouseup", mouseup);
} else {
setTimeout(rehide, 50);
}
};
TextareaInput.prototype.readOnlyChanged = function (val) {
if (!val) { this.reset(); }
this.textarea.disabled = val == "nocursor";
this.textarea.readOnly = !!val;
};
TextareaInput.prototype.setUneditable = function () {};
TextareaInput.prototype.needsContentAttribute = false;
function fromTextArea(textarea, options) {
options = options ? copyObj(options) : {};
options.value = textarea.value;
if (!options.tabindex && textarea.tabIndex)
{ options.tabindex = textarea.tabIndex; }
if (!options.placeholder && textarea.placeholder)
{ options.placeholder = textarea.placeholder; }
// Set autofocus to true if this textarea is focused, or if it has
// autofocus and no other element is focused.
if (options.autofocus == null) {
var hasFocus = activeElt();
options.autofocus = hasFocus == textarea ||
textarea.getAttribute("autofocus") != null && hasFocus == document.body;
}
function save() {textarea.value = cm.getValue();}
var realSubmit;
if (textarea.form) {
on(textarea.form, "submit", save);
// Deplorable hack to make the submit method do the right thing.
if (!options.leaveSubmitMethodAlone) {
var form = textarea.form;
realSubmit = form.submit;
try {
var wrappedSubmit = form.submit = function () {
save();
form.submit = realSubmit;
form.submit();
form.submit = wrappedSubmit;
};
} catch(e) {}
}
}
options.finishInit = function (cm) {
cm.save = save;
cm.getTextArea = function () { return textarea; };
cm.toTextArea = function () {
cm.toTextArea = isNaN; // Prevent this from being ran twice
save();
textarea.parentNode.removeChild(cm.getWrapperElement());
textarea.style.display = "";
if (textarea.form) {
off(textarea.form, "submit", save);
if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function")
{ textarea.form.submit = realSubmit; }
}
};
};
textarea.style.display = "none";
var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
options);
return cm
}
function addLegacyProps(CodeMirror) {
CodeMirror.off = off;
CodeMirror.on = on;
CodeMirror.wheelEventPixels = wheelEventPixels;
CodeMirror.Doc = Doc;
CodeMirror.splitLines = splitLinesAuto;
CodeMirror.countColumn = countColumn;
CodeMirror.findColumn = findColumn;
CodeMirror.isWordChar = isWordCharBasic;
CodeMirror.Pass = Pass;
CodeMirror.signal = signal;
CodeMirror.Line = Line;
CodeMirror.changeEnd = changeEnd;
CodeMirror.scrollbarModel = scrollbarModel;
CodeMirror.Pos = Pos;
CodeMirror.cmpPos = cmp;
CodeMirror.modes = modes;
CodeMirror.mimeModes = mimeModes;
CodeMirror.resolveMode = resolveMode;
CodeMirror.getMode = getMode;
CodeMirror.modeExtensions = modeExtensions;
CodeMirror.extendMode = extendMode;
CodeMirror.copyState = copyState;
CodeMirror.startState = startState;
CodeMirror.innerMode = innerMode;
CodeMirror.commands = commands;
CodeMirror.keyMap = keyMap;
CodeMirror.keyName = keyName;
CodeMirror.isModifierKey = isModifierKey;
CodeMirror.lookupKey = lookupKey;
CodeMirror.normalizeKeyMap = normalizeKeyMap;
CodeMirror.StringStream = StringStream;
CodeMirror.SharedTextMarker = SharedTextMarker;
CodeMirror.TextMarker = TextMarker;
CodeMirror.LineWidget = LineWidget;
CodeMirror.e_preventDefault = e_preventDefault;
CodeMirror.e_stopPropagation = e_stopPropagation;
CodeMirror.e_stop = e_stop;
CodeMirror.addClass = addClass;
CodeMirror.contains = contains;
CodeMirror.rmClass = rmClass;
CodeMirror.keyNames = keyNames;
}
// EDITOR CONSTRUCTOR
defineOptions(CodeMirror);
addEditorMethods(CodeMirror);
// Set up methods on CodeMirror's prototype to redirect to the editor's document.
var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
{ CodeMirror.prototype[prop] = (function(method) {
return function() {return method.apply(this.doc, arguments)}
})(Doc.prototype[prop]); } }
eventMixin(Doc);
CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
// Extra arguments are stored as the mode's dependencies, which is
// used by (legacy) mechanisms like loadmode.js to automatically
// load a mode. (Preferred mechanism is the require/define calls.)
CodeMirror.defineMode = function(name/*, mode, …*/) {
if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; }
defineMode.apply(this, arguments);
};
CodeMirror.defineMIME = defineMIME;
// Minimal default mode.
CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
CodeMirror.defineMIME("text/plain", "null");
// EXTENSIONS
CodeMirror.defineExtension = function (name, func) {
CodeMirror.prototype[name] = func;
};
CodeMirror.defineDocExtension = function (name, func) {
Doc.prototype[name] = func;
};
CodeMirror.fromTextArea = fromTextArea;
addLegacyProps(CodeMirror);
CodeMirror.version = "5.58.2";
return CodeMirror;
})));
/***/ }),
/***/ "W6BS":
/*!************************************************!*\
!*** ./src/assets/images/icons/weibaitong.png ***!
\************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports) {
module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADgAAAA4CAYAAACohjseAAAVs0lEQVRoQ+2aa6xlZ3nff++677Xv+9zPHM/YHo+xwQ4E14GKKESkiFsSM8bYQBIEkaBEAkqbRmo/9FulSoX2Qz9GVVQJqUJBhKKA1KRJCIlowwdDDDa+jOd65syc275f1v1d1fOufYYE2ZhJZKRWXjOjvffaa6/1/p//8/yfyzuqLMuS/48P9RrA/8fZfY3B2yXQBHQpf185tBUK+SvH8uV2H/eK1/+jGfwRIBC5ks/Vq/yplq2Wqz+B/ONg5LNlrlz+Qhnot373iih+wgX/YIAivrJgjTKA9BKcYa/Uy/MnUEpD0S2AyzdKkMslZYklbwVYWZpXQSygrSVoc+4fcPzUAKtsom4xpIGiLCkMZbJGs1LkvOHPfJbrhRX5/CM/NDwJZlXiqBKlc7AEjg1aI2iVDXZpoeS9AFXlkmV1W8z+VACLE7dbMiWLE2CFADLgqig6SakCSs4jizcvAvBHMVkqxxhKkePqAs8S1mxyLUxqw6AYKLdtbMtGINpiKKUM07bc96dk9BUBykIFoNYVC/JewMkCDDh18p0so6w+GzfT+FoWC7Yl11curQpFVCoyJQsvDThP6crNdVldi0KLcwogyzJGssVrxYWXAOWzwWg84eXd92UByoK0WHEJqBCA4oC6ChstYHRJIW6lZHWQlsoYQH6rypyOLZ5Xuahx3NIi1TAvLBIcHIlUw8rfcWFLFmzhmPBUxi0NKIRdAVi5qmPAL88LrS9z/AigmHBpCcOaCIUA1BVj4ma6LCi1FkjLBZRoVRrLR9piXjhkysI2mqJxhY2lQUrDjG3iVv5k5YmgyHI1ngLPBqfUxg21nC5LbGUhHJbGUPKu8hTbUthKGcZP3Palks3fY/BECQVQLoDk0QWURYFVFuTaNudtS+Pb8mCNZcQEYmMQi8KymCSQGLJLIx7zKCFKi1uuJNZvNXxDvLBVszUtW5xSm0WL8Mh9hV0xoGFfKRItVzjYJmaFSQtHAFqVwY3i/pi7Kl2e6N9SOJaxkJk4q0CmqcZVBaGtybFY5OIaCscqKqsaUYBE6LYU08Jimi/dxrIYjudM5ynCohzCyvZaw3iCLEviqW3ntDxR1SreTDCbQ1OI65c2qZKQsY0RKlUVFoVxWcsS5DLdnHisKk6iX1iTeBOXlNgqK4kXxmTdgapAVlWKYpKLsuVYykSJictxVtKPNMq1K0saFiym8wWzKKkiSnKeDSud9i1llOe0XE3PrUTMLEmerys1zpVEYCVWIjqVS1aGEjYlJKrvKvYrAVoWGcKgxIkBYmKuurlRTuOqmkIrdCEOJ8qpyIuc/iInL7R5oAEoOVEXRv0cx8HyHBZxZAySJilplqFE8i3bGLHXqZvFlEp4qOJOKM6zrJKkUuN7Lp6t8GxxxcqIEtfCsnFNw1yViuQuxlVNbJ6AFNUuSjEUmbFWBfJEZITF6rywalW5ryyJc21czpSSy/RmErpSFIU2bJWWRRTFVcqwHPOdo3I8HbO60mVi1Y31qwqmYkN+Ox5Nl/Kv2V7t4DhWJWoSfZZFzy3whTUJCxNA4m02meVWgAWcASr31Kgk1+XJwitfl3ykDaPyWdzTiIeW9xKDBWlREkkgVmloWTdWorBIcwajiTlryZOkJClSVDRARUN0HvPut7+NuarxbD8hKqrEbcJTjDePTfiJiKy267iOu8yBot6KrgC0xWMkHiUMSiNsri2GqAoCCYETJlWU6VJcRpiTxUp6yMU1JQ7lPMJKFZvGXUXic4ijtKodxY7KIs8LFlFElC4rEbFwFsGsTzk74sbNI/70UsQDd67zyXe9mSKes3XnnVxZKK7sz8yzxcWWkWMW3mk3cB1xzyqXmtRg2LRMvMn13tItxXVFeBwJF0kfAlIqHgEoYPJSJFjyU0kugITJQlVgTYo4UVlFlmvyRFxUtNliMl2wWLqlZTuUyZxkvE/Wv8rFG2P+aq/g/yR1Um+dT53L+MyvvoUXD2esFGPO7qyhWqs8f3PGMMEsrCpQFM1miOvYOLbCtW2U5EgKE2+uFANWWamnI6AroTEKWyocAxDULClKEXsBUrEkqlm5ZxQXZLkIx7INEoYtG5NC4qxSYsthOJ+RZZp8MSUeXGF84wYv7A74q8OSZ4Yp+dadnGpYvKkW88vr8L5feQffGyo8yyU/usIDpwJ2du7gRuJyaRBRaI1rKxqdLkVekC5mzIaHnFnv4DRWsFWBrWxciTeTSKRIKAlcSTlV2hG3NwAnaVFKjFUsanItLiklmMUsTsky0dOTvk5R2DapUaXCKKhtW+xd36W/+zyH13Z5+uox3+6XXKWH17D4OTfi/tWQerLg2qjgvtNNPvbrv8K1m4c49R5Huk6jHtCY3eTcVkh9ZZtn+xnXb+4zH+9x/cJFJkf7BI7iNz78OO3tc9xc5NSEIaEsLxhNMpo1m9W2Z0SryqXiriVqnIjICIPaMJMLuKIqdhdJsgQoNQMMo4RUa0rbMbknGRxwcOUZLj73It/dnfA3U8U4Vpzq+Lxho8YOBcPpnCuJy1z5lG6Dd52Gjzx+nmf6BSvJDWppjFrZ5jj2qLs5O/6cuzZX+fZ3nuS//+GXTBz11k/R7K7yofe/lzu21om8JoeLAlvUM8lJC00YWKw0PcNelUbEVUvUKClLkf7MKKcxyDIdWEQnDJYWgac4mMdEGYz3d7n5/JNcuHCZJ/cWPD0u0Y7L2Y0G9wXgZDHXJhl7sUWSlnTXemzVYcsvOde1eeyD57kwUEROm3h0zE4zJcgXxO0dJrGibo24by0kmy/4ytf+mJuHx3RX1njiA49gez5NV+H1Nrl0nOFIzyhdia/otURxJVVonGUNqwaxLiVXSb4TIalctYrJJMlMvSe+/fyFF/iDL/1PvLCGH+3zv184Znde0Gp1eF3PYtWF/qzg4njBOLOot2qcabqc8nNCzyaKNLtzhwd26nzqo49xae+ItZpN4nWIW6tMR2N27DmBnTMPegwjm1P1jJ265vf/4IvYrsfjH3iUYPUU2XxA09J47TVujIQQi1oAnaazLCGlIKjKctWP88pFDbglwEK0o2oFnn3+Al/6+p/x7aeukRSKaf8Kd6+vMCngbCekKHN2+ykHixw3CNgRUC2bhl0yTkpuTguGqkFpe4jCvn1b87GPfYQfzBp0VETQ32WzV6OwA7LmNkk8o82Y0C4ZuqvU0hHf/PrXSCn5zQ9+AK97iv7xDVp1H0+VtFpdrs5sfNun2zzpMERdq/e3AIqWSCKXMksi8LtPP88Xv/a/+NZTV8nckE5vlWQ8ZHF4kbee7nF5EHMwzU2SXW/4nGo51FyYRQV7EfQz1whVqFLarQYbtYL1oGDdhw9/8AOo+ip7WY3RPKPXaaCm+3TtCK/WQNfXiZKYlrWg6RR8+ctfQyv40KPncbobFOni1vjEL2Ka7R6TMsCWErEs8BwIPZMt/w5AuUNZ8L3v/5D/9kd/yp8/dY1ZaRHW5IeKmhdiJxGL4R4bjYBpUrDTklbHYZzAzUXJsLDNA9qBzXrDZTVMWbczPJWT5jAvA+qBy71ntui26txz5gy9nTNE3gr9eY5da6KSEV0VmfxXNnqo6JBvfPUbaKX4yGOP0tjc4ehgn3araepbycV2HtNqNJmoJnkSUQsCVpoOlkwNbrmoFMXzOe/55L/nuVFCKwywpf6TYrdWJ2h2SKcT5jee5+c26xzNcg4XmrEWkCVrocVGqFi1clyVkOUpi8Iz8ZSqOkVjg6y+wYP+DX73n3+YZy5cZTE6IjoesNkOWNvcpLW6Req0SLyAdD6l5cQ0SPnDr3wdbdt86PwjWO0ViiTC93ziNMb1fMosMa+DhUWjXqfmO6w07R8HqEgWc9772f/M1cEY31Km0pdaUqoL16uhkgXp+AYrgccwKdgKNWtuQSiAsoJRDlOrSeT2SFtr0tNj1+u4cUJYU0S5zZnkAr/z6c8xi2BnewWdxswnxyz6+4wPbtDwLLa3t2msbuGvbZH29/jjr3wV7Xg88egjhJtnGPf3qbmeSc8iMKpIsL0ax4uSXqtJ4Dn0mnZVthkGpZBGkUYR7/7MF7g6nOJL3yWjBNfFDgLCRodiPjYJ/RdWC/L5hJG2megaU7tDFrSw7Rp23aNt2fRaHuuhzXY7pBfa3H/XFg/9k7dw/dJz2BtneXFvhvbq6DwhsApWuy08pyAeDTjcvUg02SdUDmfvOcuf/OW3cJ2Ax87/GrG3SjQfs73eIY1j07WUeY7teAwSixWpX215vsx8LNQgLpbdBESLiPd++j9ydTjDcaW6kxYILFtUyiFfLJiOD+gGAX4yZNy+h17DpRf6bPd8tkOHjW6dhqcME4WCRZwxj1LuP3c373/fO43r1ms1U8DPEs3hLGV3MKe/kM8JUvkHrk27XuNo90W+9T++SKfbpdXu8eivvYeodZpo2qfu26gix5f8kEZYtscwdel1mqau3Oh4+I6NGsZSqkFSwmgScf53/xPX+hPDoJQ7ruPg+QFOo0OnXKDGN7h7Z53NsKTVWaHpS5uSsUil77N5dnfI6TWfb//wiMZaB3824Wri8W/Pv4kHf+k9PHPtJg+tWBzqBmE559RaD6U1YehXRUSiORhF9Oea4+Njvvnl368YWVvn8fe/jwNrnWgyYLXbrCZudombx3h+jWHqGE+QY7O9BDgyAEtSA3DB+c99gWujObbkQXFyS4avVWvyxBtabDUcRrOUSVS1TtcOI06thTy1N+EX7+rx/Rsj3nhmhfF0SiMMaDnC4oI3PvB6nnjsPP3RhHbD5zD2IBkztQLy+QisOg07QzkO6w1PujrT9gyPjti7ecizL77Im99wP/vuafJkTCusUeYyJbDwSHFdj1R5rHVbpszcarumWVaTWGpRTYZiNIt55LNf4NJghGu7ph0x/ZhfpxO43FeLqXslea6o+VIO2SRFSTdUHExj1kOPZ/s59/U8vrM7YbXXppgOuZGF/Kt338tb3/M437uyyy+s+xxlLr4V0wzqFDqiXu9CnphFinpHmSbRBTXXIQzrXHnuaXScct2/h2S+T7veQBUpjhuaKYHjunhByEq3bXjZ7Mj9S9Q0LctqyFRw4dI1/sV/+K8cLyK6niKwLZM0m3aKVh5d1yJzfKJE5iZVz9Wf5ex0PK4Mc16/6nBtmnNn1zV5re471FTGPNE8/MbX8Vsf/U1GozHtekA/d3CKiKT0ydMZuRXg6oyFVrQ8mftUfZ909rWgxqXnnyXPUi6rM+hE7tEwY/6isPDLBa4XENbrZqxhpgwWPHimi5qnupQkOhsN+czv/TuSLEZJ01qYmbXpEeVGMq5r1VxKp40uJcFKV20xiXN6fsneXHNHy+IHfYsHVkue2Yuot+t48Zy9LOR33nGGdz72cf724lUe2nA50CENEiyvgU6m1MI6vjTctk3o2qSZNN/g26IZFrsXLpDGC75nvw4VjWj5MrbQxvA15vhuwFqnUc1mtAzKSt567ypqkelSW4pR/5hPfvbfEEuBbfYKSjKkMpFZSEGuLDphCH6DPNfVwMjCjCg6gc0gUWzVUo5ih9VAM4+1WV1YZIzTkrf9/Dk+8clPMZjO6dUcxri42YKs9CjSOTpo4Ocps1yKe5uiyMhKaXxdiiJl/9JFoijiyDmFThY4gWcmfalWODrFdXy2N1bJZcBVajNyfMu5VVSSlbJlwHH/iI9/4tNMU/BktKRcclVgaRtLi2UVnaAOQYM0l8FrhrJtJqliJdDsRTZ3hylPj33e0Em51M+pd3uEi0P2dIPf/qen+PWPfoKnL+/x4JrPXuYTFlMIOuTRGK/eoVbGLAqLRijViSbTOTU3QArR65dfZL6IcdbvIs1TdocF3bpPJ3RMzGWzASvr22C7ZpIn/x6+W+LUzPXgsN/nN574CEmSUtrVjo4lvaFTYDlSiSt6Gx1Cv0vhxliJTe6UlEnN7CRpw7QiLmVvopoOoF0sO2MclfzSm+/hM//y95guUtpShARtnCJmEeUoFeM1mziZJo4WeEHN7EUUSUpk73P95vfZvTYAvUa+ukGez9g7njPqF7Rd6RwKiugKi/llHMfHsnwzZG76ddTBwWGZZinD4YjPfvpzTGYzijwxsxBJxt07MlpnE1RmYbuKQG+iuhP0wEe1c+ILr8d2UhOrWldjDKu7TznaJFjbZX58Cqt2mTfd+y5+6+Nv53jyIr3mvYRunX5ymZ71MK6q4Qc+cVYwi2IaNR/PtdGpx7Xoqzx3+CeE84d54NR5IYhWo8Zf/s03+Oo3/wtrvW1Ct0PgrhA6K9TcDqV2jSAJc+rzn/98OZ1Ol/MVl7IsiOOINM0YTw4ZRJeJ9ZDpZEzQ9fGKDexmRJkVqMBn+twOyo5pNJsEYcjx8QG9h55kcel1hGcvMnvhHGrlBR66/1f55X+2zQvX/5q13r2QOQzzH/Lz7X/NYfEAvaZiePOQsrfOSnJIOwiNmz23+xccHr3AweGc8RjCIOD05lksakyjIzrBnRRimNmYXGdmHTs7pzh37pypadW1a9dKqRgODg7Y399nMhmTZZm5ecIxUTpgkR4yiQ+IFhPiLCeOZpSFB3GTXDdwdIv17hmarR4//MGT3PGL+1z/bo/em6/S/84pmg89zwPrj/COd55mMDkirNWwkx3G0QsUB2/Ba57jjq0OZTxGOS46ryYJ82jApetPcTDYJ6yt4tshtVoIuUMz7NI/HqJ1SthscMfOHZy9+y62trbwPO/WbuHf3z7TmvlcLDVmMBgwHIwYjSbMJ3Nm0ZxI5p3JjHk6RkbCgVfDsgN8ArP3N5juM5jdJD26xrOjq9TzCcfzkGYYcXrrbTz6xDs5OrrMeHzIjck+2eiA65OYdrjOPace5NzOw/hO10zW5ZDm27VDUxdLnMtwOctSk+NqtYDNzU3W1tfpdbvm2pc6bgE0u7IvsRUs56M4Yj6dmfJrOhwyGE8YjkaMxkNmszlpLDGbkeUx02RAlC2Y5UeUSZ+pdYyaz1k4Y9OdhE4D5dVoB6dZWbuLlneaXm2DPC1NR5BGCbF0CWVJEAQ0GnXanTb1sE69Xmdzc4uNjQ1ardZy4+dlN3fNF6+4R/9SP5eHJ0nMYhEh8TscDun3+0aoJuMJi8WCJMnRZgRZkJOR5FMKvWBz/QyN2gqqsEjTBE1q7iU5znZsfN83i2+32zSbTXq9HisrK6yurtJoNH4ympf49rYAvhzL1b5JSZqmZqGTyZT+4Jj+cd+4+mg4Yh7F5Kk0xqK4Jb7rVP87w1KGpU6nR6vVNMAEkPzrdDqGxX/McVsAb/dBsh0mKWgxnzMajxgOhhwf9+n3j5nNZ7RbbbrdrgElYE5Aua57u4962etfNYAvx7YISJIkxrXFxdvtlnFJW+Yiy+MnecrtIn/VAN7uQl6t618D+GpZ9md139cY/FlZ+tV6zmsMvlqW/Vnd9/8CAe3hZpCQX/4AAAAASUVORK5CYII="
/***/ }),
/***/ "WYAk":
/*!****************************************!*\
!*** ./node_modules/crypto-js/hmac.js ***!
\****************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"));
}
else {}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var C_algo = C.algo;
/**
* HMAC algorithm.
*/
var HMAC = C_algo.HMAC = Base.extend({
/**
* Initializes a newly created HMAC.
*
* @param {Hasher} hasher The hash algorithm to use.
* @param {WordArray|string} key The secret key.
*
* @example
*
* var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
*/
init: function (hasher, key) {
// Init hasher
hasher = this._hasher = new hasher.init();
// Convert string to WordArray, else assume WordArray already
if (typeof key == 'string') {
key = Utf8.parse(key);
}
// Shortcuts
var hasherBlockSize = hasher.blockSize;
var hasherBlockSizeBytes = hasherBlockSize * 4;
// Allow arbitrary length keys
if (key.sigBytes > hasherBlockSizeBytes) {
key = hasher.finalize(key);
}
// Clamp excess bits
key.clamp();
// Clone key for inner and outer pads
var oKey = this._oKey = key.clone();
var iKey = this._iKey = key.clone();
// Shortcuts
var oKeyWords = oKey.words;
var iKeyWords = iKey.words;
// XOR keys with pad constants
for (var i = 0; i < hasherBlockSize; i++) {
oKeyWords[i] ^= 0x5c5c5c5c;
iKeyWords[i] ^= 0x36363636;
}
oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes;
// Set initial values
this.reset();
},
/**
* Resets this HMAC to its initial state.
*
* @example
*
* hmacHasher.reset();
*/
reset: function () {
// Shortcut
var hasher = this._hasher;
// Reset
hasher.reset();
hasher.update(this._iKey);
},
/**
* Updates this HMAC with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {HMAC} This HMAC instance.
*
* @example
*
* hmacHasher.update('message');
* hmacHasher.update(wordArray);
*/
update: function (messageUpdate) {
this._hasher.update(messageUpdate);
// Chainable
return this;
},
/**
* Finalizes the HMAC computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The HMAC.
*
* @example
*
* var hmac = hmacHasher.finalize();
* var hmac = hmacHasher.finalize('message');
* var hmac = hmacHasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Shortcut
var hasher = this._hasher;
// Compute HMAC
var innerHash = hasher.finalize(messageUpdate);
hasher.reset();
var hmac = hasher.finalize(this._oKey.clone().concat(innerHash));
return hmac;
}
});
}());
}));
/***/ }),
/***/ "WdTA":
/*!******************************************!*\
!*** ./src/assets/images/studnetqun.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/studnetqun.598eeb43.png";
/***/ }),
/***/ "X+im":
/*!**********************************************************************!*\
!*** ./node_modules/@ant-design/icons/lib/icons/DownloadOutlined.js ***!
\**********************************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireWildcard = __webpack_require__(/*! @babel/runtime/helpers/interopRequireWildcard */ "284h");
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "TqRt");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/objectSpread2 */ "3tO9"));
var React = _interopRequireWildcard(__webpack_require__(/*! react */ "q1tI"));
var _DownloadOutlined = _interopRequireDefault(__webpack_require__(/*! @ant-design/icons-svg/lib/asn/DownloadOutlined */ "KQeH"));
var _AntdIcon = _interopRequireDefault(__webpack_require__(/*! ../components/AntdIcon */ "KQxl"));
// GENERATE BY ./scripts/generate.ts
// DON NOT EDIT IT MANUALLY
var DownloadOutlined = function DownloadOutlined(props, ref) {
return /*#__PURE__*/React.createElement(_AntdIcon.default, (0, _objectSpread2.default)((0, _objectSpread2.default)({}, props), {}, {
ref: ref,
icon: _DownloadOutlined.default
}));
};
DownloadOutlined.displayName = 'DownloadOutlined';
var _default = /*#__PURE__*/React.forwardRef(DownloadOutlined);
exports.default = _default;
/***/ }),
/***/ "XAae":
/*!**********************************************************!*\
!*** ./node_modules/@ant-design/icons/PictureTwoTone.js ***!
\**********************************************************/
/*! no static exports found */
/*! exports used: default */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _PictureTwoTone = _interopRequireDefault(__webpack_require__(/*! ./lib/icons/PictureTwoTone */ "hwYd"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _default = _PictureTwoTone;
exports.default = _default;
module.exports = _default;
/***/ }),
/***/ "Xsq0":
/*!*************************************************!*\
!*** ./src/assets/images/banner/mainbanner.jpg ***!
\*************************************************/
/*! 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/mainbanner.569b9fb1.jpg";
/***/ }),
/***/ "Ywus":
/*!********************************************************************!*\
!*** ./node_modules/@ant-design/icons/lib/icons/DeleteOutlined.js ***!
\********************************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireWildcard = __webpack_require__(/*! @babel/runtime/helpers/interopRequireWildcard */ "284h");
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "TqRt");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/objectSpread2 */ "3tO9"));
var React = _interopRequireWildcard(__webpack_require__(/*! react */ "q1tI"));
var _DeleteOutlined = _interopRequireDefault(__webpack_require__(/*! @ant-design/icons-svg/lib/asn/DeleteOutlined */ "DO2E"));
var _AntdIcon = _interopRequireDefault(__webpack_require__(/*! ../components/AntdIcon */ "KQxl"));
// GENERATE BY ./scripts/generate.ts
// DON NOT EDIT IT MANUALLY
var DeleteOutlined = function DeleteOutlined(props, ref) {
return /*#__PURE__*/React.createElement(_AntdIcon.default, (0, _objectSpread2.default)((0, _objectSpread2.default)({}, props), {}, {
ref: ref,
icon: _DeleteOutlined.default
}));
};
DeleteOutlined.displayName = 'DeleteOutlined';
var _default = /*#__PURE__*/React.forwardRef(DeleteOutlined);
exports.default = _default;
/***/ }),
/***/ "ZMnZ":
/*!****************************************************************!*\
!*** ./node_modules/@ant-design/icons/lib/icons/UpOutlined.js ***!
\****************************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireWildcard = __webpack_require__(/*! @babel/runtime/helpers/interopRequireWildcard */ "284h");
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "TqRt");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/objectSpread2 */ "3tO9"));
var React = _interopRequireWildcard(__webpack_require__(/*! react */ "q1tI"));
var _UpOutlined = _interopRequireDefault(__webpack_require__(/*! @ant-design/icons-svg/lib/asn/UpOutlined */ "2oIt"));
var _AntdIcon = _interopRequireDefault(__webpack_require__(/*! ../components/AntdIcon */ "KQxl"));
// GENERATE BY ./scripts/generate.ts
// DON NOT EDIT IT MANUALLY
var UpOutlined = function UpOutlined(props, ref) {
return /*#__PURE__*/React.createElement(_AntdIcon.default, (0, _objectSpread2.default)((0, _objectSpread2.default)({}, props), {}, {
ref: ref,
icon: _UpOutlined.default
}));
};
UpOutlined.displayName = 'UpOutlined';
var _default = /*#__PURE__*/React.forwardRef(UpOutlined);
exports.default = _default;
/***/ }),
/***/ "ZSFt":
/*!********************************************************!*\
!*** ./src/pages/Competitions/components/ClaModal.tsx ***!
\********************************************************/
/*! exports provided: default */
/*! exports used: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _Users_xxq_node_forgeplus_react_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/regenerator */ "WmNS");
/* harmony import */ var _Users_xxq_node_forgeplus_react_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_Users_xxq_node_forgeplus_react_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var antd_es_message_style__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! antd/es/message/style */ "miYZ");
/* harmony import */ var antd_es_message__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! antd/es/message */ "tsqr");
/* harmony import */ var antd_es_modal_style__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! antd/es/modal/style */ "2qtc");
/* harmony import */ var antd_es_modal__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! antd/es/modal */ "kLXV");
/* harmony import */ var antd_es_button_style__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! antd/es/button/style */ "+L6B");
/* harmony import */ var antd_es_button__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! antd/es/button */ "2/Rp");
/* harmony import */ var antd_es_checkbox_style__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! antd/es/checkbox/style */ "sRBo");
/* harmony import */ var antd_es_checkbox__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! antd/es/checkbox */ "kaz8");
/* harmony import */ var antd_es_input_style__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! antd/es/input/style */ "5NDa");
/* harmony import */ var antd_es_input__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! antd/es/input */ "5rEg");
/* harmony import */ var _Users_xxq_node_forgeplus_react_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 antd_es_form_style__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! antd/es/form/style */ "y8nQ");
/* harmony import */ var antd_es_form__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! antd/es/form */ "Vl3Y");
/* harmony import */ var _Users_xxq_node_forgeplus_react_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/slicedToArray */ "tJVT");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! react */ "q1tI");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_15__);
/* harmony import */ var umi__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! umi */ "9kvl");
/* harmony import */ var _Cla_less_modules__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./Cla.less?modules */ "+KIT");
/* harmony import */ var _Cla_less_modules__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_Cla_less_modules__WEBPACK_IMPORTED_MODULE_17__);
/* harmony import */ var _assets_images_competition_cla_png__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! @/assets/images/competition/cla.png */ "qtz/");
/* harmony import */ var _assets_images_competition_cla_png__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_assets_images_competition_cla_png__WEBPACK_IMPORTED_MODULE_18__);
var AddClamodal = function AddClamodal(_ref) {
var competitions = _ref.competitions,
globalSetting = _ref.globalSetting,
loading = _ref.loading,
dispatch = _ref.dispatch,
user = _ref.user,
visible = _ref.visible,
_ref$onCancel = _ref.onCancel,
onCancel = _ref$onCancel === void 0 ? function () {} : _ref$onCancel,
_ref$onOk = _ref.onOk,
onOk = _ref$onOk === void 0 ? function () {} : _ref$onOk;
var _Form$useForm = antd_es_form__WEBPACK_IMPORTED_MODULE_13__[/* default */ "a"].useForm(),
_Form$useForm2 = Object(_Users_xxq_node_forgeplus_react_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_14__[/* default */ "a"])(_Form$useForm, 1),
form = _Form$useForm2[0];
var setFieldsValue = form.setFieldsValue,
getFieldsValue = form.getFieldsValue,
validateFields = form.validateFields;
var _useState = Object(react__WEBPACK_IMPORTED_MODULE_15__["useState"])(false),
_useState2 = Object(_Users_xxq_node_forgeplus_react_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_14__[/* default */ "a"])(_useState, 2),
checkCla = _useState2[0],
setCheckCla = _useState2[1];
var _useState3 = Object(react__WEBPACK_IMPORTED_MODULE_15__["useState"])(false),
_useState4 = Object(_Users_xxq_node_forgeplus_react_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_14__[/* default */ "a"])(_useState3, 2),
checkClaFlag = _useState4[0],
setCheckClaFlag = _useState4[1];
Object(react__WEBPACK_IMPORTED_MODULE_15__["useEffect"])(function () {
if (user === null || user === void 0 ? void 0 : user.userInfo) {
var info = user === null || user === void 0 ? void 0 : user.userInfo;
setFieldsValue({
GitLinkID: info.login,
email: info.email,
name: info.nickname,
phoneNumber: info.phone,
address: info.province
});
}
}, [user === null || user === void 0 ? void 0 : user.userInfo]);
function getCla() {
return _getCla.apply(this, arguments);
}
function _getCla() {
_getCla = Object(_Users_xxq_node_forgeplus_react_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_asyncToGenerator__WEBPACK_IMPORTED_MODULE_11__[/* default */ "a"])( /*#__PURE__*/_Users_xxq_node_forgeplus_react_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {
var values, phoneReg, emailReg, _user$userInfo, _user$userInfo2, data;
return _Users_xxq_node_forgeplus_react_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return validateFields();
case 2:
values = getFieldsValue();
phoneReg = /^1\d{10}$/;
emailReg = /^[a-zA-Z0-9]+([.\-_\\]*[a-zA-Z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/;
if (phoneReg.test(values === null || values === void 0 ? void 0 : values.phoneNumber)) {
_context.next = 8;
break;
}
antd_es_message__WEBPACK_IMPORTED_MODULE_2__[/* default */ "b"].info('请输入正确的手机号码');
return _context.abrupt("return");
case 8:
if (emailReg.test(values === null || values === void 0 ? void 0 : values.email)) {
_context.next = 11;
break;
}
antd_es_message__WEBPACK_IMPORTED_MODULE_2__[/* default */ "b"].info('请输入正确的邮箱地址');
return _context.abrupt("return");
case 11:
if (!(!checkClaFlag && checkCla)) {
_context.next = 19;
break;
}
_context.next = 14;
return dispatch({
type: 'competitions/SignCLA',
payload: {
owner: user === null || user === void 0 ? void 0 : (_user$userInfo = user.userInfo) === null || _user$userInfo === void 0 ? void 0 : _user$userInfo.login,
login: user === null || user === void 0 ? void 0 : (_user$userInfo2 = user.userInfo) === null || _user$userInfo2 === void 0 ? void 0 : _user$userInfo2.login,
email: values === null || values === void 0 ? void 0 : values.email,
nickname: values === null || values === void 0 ? void 0 : values.name,
phone: values === null || values === void 0 ? void 0 : values.phoneNumber,
address: values === null || values === void 0 ? void 0 : values.address
}
});
case 14:
data = _context.sent;
if (data && data.status === 0) {
onOk();
}
onCancel();
_context.next = 20;
break;
case 19:
setCheckClaFlag(true);
case 20:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return _getCla.apply(this, arguments);
}
return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement(antd_es_modal__WEBPACK_IMPORTED_MODULE_4__[/* default */ "a"], {
visible: visible,
title: "",
footer: null,
width: "85em",
wrapClassName: _Cla_less_modules__WEBPACK_IMPORTED_MODULE_17___default.a.claBox,
onCancel: onCancel
}, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement("div", {
className: _Cla_less_modules__WEBPACK_IMPORTED_MODULE_17___default.a.box
}, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement("div", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement("p", {
className: _Cla_less_modules__WEBPACK_IMPORTED_MODULE_17___default.a.title
}, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement("img", {
src: _assets_images_competition_cla_png__WEBPACK_IMPORTED_MODULE_18___default.a,
width: "21px",
style: {
marginRight: "14px"
}
}), "\u7B7E\u7F72 Openkylin CLA"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement("div", {
style: {
height: "4.5em"
}
}), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement("div", {
className: _Cla_less_modules__WEBPACK_IMPORTED_MODULE_17___default.a.content
}, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement("p", null, "\u611F\u8C22\u60A8\u5BF9\u5411 GitLink \u793E\u533A\u62E5\u6709\u6216\u7BA1\u7406\u7684\u9879\u76EE\u8D21\u732E\u8F6F\u4EF6\u4EE3\u7801\u7684\u5174\u8DA3\u3002\u4E3A\u660E\u786E\u4EFB\u4F55\u4E2A\u4EBA\u6216\u5B9E\u4F53\u8D21\u732E\u5185\u5BB9\u800C\u6388\u4E88\u7684\u77E5\u8BC6\u4EA7\u6743\u8BB8\u53EF\uFF0CGitLink \u5FC5\u987B\u5BF9\u6BCF\u4F4D\u8D21\u732E\u8005\u7B7E\u7F72\u7684\u8D21\u732E\u8005\u8BB8\u53EF\u534F\u8BAE\u8FDB\u884C\u5F52\u6863\uFF0C\u4EE5\u8BC1\u660E\u5C31\u4EE5\u4E0B\u8BB8\u53EF\u6761\u4EF6\u8FBE\u6210\u7684\u4E00\u81F4\u3002\u672C\u534F\u8BAE\u662F\u4E3A\u4E86\u4FDD\u62A4\u4F5C\u4E3A\u8D21\u732E\u8005\u7684\u60A8\uFF0C\u4E5F\u662F\u4E3A\u4E86\u4FDD\u62A4\u793E\u533A\u548C\u5B83\u7684\u7528\u6237\uFF0C\u5B83\u4E0D\u4F1A\u6539\u53D8\u60A8\u5C06\u81EA\u5DF1\u7684\u8D21\u732E\u7528\u4E8E\u4EFB\u4F55\u5176\u4ED6\u76EE\u7684\u7684\u6743\u5229\u3002"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement("p", null, "\u8BF7\u5728\u7B7E\u7F72\u4E4B\u524D\u4ED4\u7EC6\u9605\u8BFB\u672C\u6587\u4EF6\uFF0C\u5E76\u81EA\u884C\u4FDD\u7559\u4E00\u4EFD\u526F\u672C\u4F5C\u4E3A\u60A8\u7684\u8BB0\u5F55\u3002\u5C31\u60A8\u76EE\u524D\u548C\u5C06\u6765\u5411 GitLink \u793E\u533A\u63D0\u4EA4\u7684\u8D21\u732E\u5185\u5BB9\uFF0C\u60A8\u63A5\u53D7\u5E76\u540C\u610F\u4EE5\u4E0B\u6761\u6B3E\u3002\u9664\u4E86\u6839\u636E\u672C\u534F\u8BAE\u6388\u4E88 GitLink \u793E\u533A\u3001GitLink \u793E\u533A\u6240\u5206\u53D1\u8F6F\u4EF6\u7684\u63A5\u6536\u8005\u7684\u8BB8\u53EF\u5916\uFF0C\u60A8\u5BF9\u4E8E\u60A8\u7684\u8D21\u732E\u5185\u5BB9\u4FDD\u7559\u6240\u6709\u6743\u5229\u3001\u6240\u6709\u6743\u548C\u6743\u76CA\u3002"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement("p", null, "1. \u5B9A\u4E49\u201C\u60A8\u201D\uFF08\u6216\u201C\u60A8\u7684\u201D\uFF09\u6307\u4E0E GitLink \u793E\u533A\u7B7E\u7F72\u672C\u534F\u8BAE\u7684\u8457\u4F5C\u6743\u4EBA\u6216\u7ECF\u8457\u4F5C\u6743\u4EBA\u6388\u6743\u7684\u6CD5\u5F8B\u5B9E\u4F53\u3002\u5BF9\u4E8E\u6CD5\u5F8B\u5B9E\u4F53\u800C\u8A00\uFF0C\u63D0\u4EA4\u8D21\u732E\u5185\u5BB9\u7684\u5B9E\u4F53\u4EE5\u53CA\u5176\u4ED6\u4EFB\u4F55\u63A7\u5236\u8BE5\u5B9E\u4F53\u3001\u53D7\u5176\u63A7\u5236\u6216\u4E0E\u5176\u53D7\u5230\u540C\u4E00\u4E3B\u4F53\u63A7\u5236\u7684\u5B9E\u4F53\u88AB\u89C6\u4E3A\u5355\u4E2A\u8D21\u732E\u8005\u3002\u4E3A\u672C\u5B9A\u4E49\u4E4B\u76EE\u7684\uFF0C\u201C\u63A7\u5236\u201D\u662F\u6307\uFF1A\uFF08i\uFF09\u901A\u8FC7\u5408\u540C\u6216\u5176\u4ED6\u65B9\u5F0F\uFF0C\u76F4\u63A5\u6216\u95F4\u63A5\u6307\u5BFC\u6216\u7BA1\u7406\u8BE5\u5B9E\u4F53\u7684\u6743\u5229\uFF0C\u6216\uFF08ii\uFF09\u6301\u6709\u8BE5\u5B9E\u4F53 50%\u6216\u4EE5\u4E0A\u7684\u53D1\u884C\u80A1\u4EFD\uFF0C\u6216\uFF08iii\uFF09\u95F4\u63A5\u6301\u6709\u8BE5\u5B9E\u4F53\u6743\u76CA\u3002"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement("p", null, "\u201C\u8D21\u732E\u201D\u662F\u6307\u7531\u60A8\u6709\u610F\u5730\u5411 GitLink \u793E\u533A\u63D0\u4EA4\uFF0C\u4EE5\u4FBF\u88AB\u5305\u542B\u6216\u8BB0\u8F7D\u5728\u4EFB\u4F55GitLink \u793E\u533A\u62E5\u6709\u6216\u7BA1\u7406\u7684\u4EA7\u54C1\u6216\u9879\u76EE\u4E2D\u7684\u4EFB\u4F55\u539F\u521B\u4F5C\u54C1\uFF0C\u5305\u62EC\u5BF9\u65E2\u5B58\u4F5C\u54C1\u7684\u4EFB\u4F55\u4FEE\u6539\u548C\u589E\u52A0\u3002\u4E3A\u672C\u5B9A\u4E49\u4E4B\u76EE\u7684\uFF0C\u201C\u63D0\u4EA4\u201D\u662F\u6307\u5411 GitLink \u793E\u533A\u6216\u5176\u4EE3\u8868\u8FDB\u884C\u7684\u4EFB\u4F55\u5F62\u5F0F\u7684\u7535\u5B50\u6216\u4E66\u9762\u4EA4\u6D41\uFF0C\u5305\u62EC\u4F46\u4E0D\u9650\u4E8E\u4E3A\u8BA8\u8BBA\u548C\u6539\u5584\u4F5C\u54C1\u4E3A\u76EE\u7684\uFF0C\u901A\u8FC7GitLink \u793E\u533A\u7BA1\u7406\u7684\uFF08\u6216\u4EE5 GitLink \u793E\u533A\u540D\u4E49\u7BA1\u7406\u7684\uFF09\u7535\u5B50\u90AE\u4EF6\u5217\u8868\u3001\u6E90\u4EE3\u7801\u63A7\u5236\u7CFB\u7EDF\u548C\u95EE\u9898\u8DDF\u8E2A\u7CFB\u7EDF\u8FDB\u884C\u7684\u4EA4\u6D41\u3002"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement("p", null, "2. \u8457\u4F5C\u6743\u8BB8\u53EF\u6388\u4E88"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement("p", null, "\u53D7\u9650\u4E8E\u672C\u534F\u8BAE\u7684\u6761\u6B3E\u548C\u6761\u4EF6\uFF0C\u60A8\u5728\u6B64\u6388\u4E88 GitLink \u793E\u533A\u4EE5\u53CAGitLink \u793E\u533A\u53D1\u5E03\u8F6F\u4EF6\u7684\u63A5\u6536\u65B9\u6C38\u4E45\u6027\u7684\u3001\u5168\u7403\u8303\u56F4\u5185\u7684\u3001\u975E\u72EC\u5360\u7684\u3001\u514D\u8BB8\u53EF\u8D39\u7684\u3001\u514D\u7248\u6743\u8D39\u7684\u548C\u4E0D\u53EF\u64A4\u9500\u7684\u8457\u4F5C\u6743\u8BB8\u53EF\uFF0C\u4EE5\u590D\u5236\u3001\u884D\u751F\u3001\u516C\u5F00\u5C55\u793A\u3001\u516C\u5F00\u6267\u884C\u3001\u8F6C\u6388\u6743\u548C\u53D1\u5E03\u60A8\u7684\u8D21\u732E\u53CA\u5176\u884D\u751F\u4F5C\u54C1\u3002"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement("p", null, "3. \u4E13\u5229\u8BB8\u53EF\u7684\u6388\u4E88"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement("p", null, "\u53D7\u9650\u4E8E\u672C\u534F\u8BAE\u7684\u6761\u6B3E\u548C\u6761\u4EF6\uFF0C\u60A8\u5728\u6B64\u6388\u4E88 GitLink \u793E\u533A\u4EE5\u53CAGitLink \u793E\u533A\u53D1\u5E03\u8F6F\u4EF6\u7684\u63A5\u6536\u65B9\u6C38\u4E45\u6027\u7684\u3001\u5168\u7403\u8303\u56F4\u5185\u7684\u3001\u975E\u72EC\u5360\u7684\u3001\u514D\u8BB8\u53EF\u8D39\u7684\u3001\u514D\u7248\u6743\u8D39\u7684\u548C\u4E0D\u53EF\u64A4\u9500\uFF08\u672C\u8282\u89C4\u5B9A\u7684\u60C5\u5F62\u9664\u5916\uFF09\u7684\u4E13\u5229\u8BB8\u53EF\uFF0C\u4EE5\u5F00\u53D1\u3001\u5229\u7528\u3001\u8981\u7EA6\u51FA\u552E\u3001\u51FA\u552E\u3001\u5BFC\u5165\u6216\u4EE5\u5176\u4ED6\u65B9\u5F0F\u8F6C\u8BA9\u4F5C\u54C1\uFF0C\u4F46\u8BE5\u8BB8\u53EF\u4EC5\u9002\u7528\u4E8E\u60A8\u6709\u6743\u8BB8\u53EF\u7684\uFF0C\u4E14\u5FC5\u7136\u4F1A\u88AB\u60A8\u7684\u8D21\u732E\u5185\u5BB9\u4FB5\u6743\uFF08\u8D21\u732E\u5185\u5BB9\u5355\u72EC\u6784\u6210\u4FB5\u6743\u3001\u6216\u4E0E\u8D21\u732E\u5185\u5BB9\u7684\u76F8\u5173\u4F5C\u54C1\u4E00\u540C\u6784\u6210 \u4FB5\u6743\uFF09\u7684\u4E13\u5229\u7533\u8BF7\u8303\u56F4\u3002\u5982\u679C\u4EFB\u4F55\u5B9E\u4F53\u9488\u5BF9\u60A8\u6216\u5176\u4ED6\u5B9E\u4F53\u63D0\u8D77\u4E13\u5229\u8BC9\u8BBC\uFF08\u5305\u62EC\u8BC9\u8BBC\u4E2D\u7684\u4EA4\u53C9\u8BF7\u6C42\u6216\u53CD\u8BC9\uFF09\uFF0C\u4E3B\u5F20\u60A8\u7684\u8D21\u732E\u5185\u5BB9\uFF08\u6216\u60A8\u53C2\u4E0E\u8D21\u732E\u7684\u4F5C\u54C1\uFF09\u9020\u6210\u4E86\u76F4\u63A5\u6027\u6216\u8F85\u52A9\u6027\u7684\u4E13\u5229\u4FB5\u6743\uFF0C\u5219\u4EFB\u4F55\u6839\u636E\u672C\u534F\u8BAE\u9488\u5BF9\u8BE5\u8D21\u732E\u5185\u5BB9\u6216\u4F5C\u54C1\u6388\u4E88\u8BE5\u5B9E\u4F53\u7684\u4E13\u5229\u8BB8\u53EF\u5E94\u5F53\u5728\u8D77\u8BC9\u4E4B\u65E5\u7EC8\u6B62\u3002"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement("p", null, "4. \u60A8\u4FDD\u8BC1\u60A8\u4F9D\u6CD5\u6709\u6743\u6388\u4E88\u4E0A\u8FF0\u8BB8\u53EF\u3002\u5982\u679C\u60A8\u7684\u96C7\u4E3B\u5BF9\u60A8\u521B\u9020\u7684\u77E5\u8BC6\u4EA7\u6743\u62E5\u6709\u6743\u5229\uFF0C\u5176\u4E2D\u5305\u62EC\u60A8\u7684\u8D21\u732E\uFF0C\u60A8\u627F\u8BFA\u60A8\u7684\u96C7\u4E3B\u5DF2\u6388\u6743\u60A8\u63D0\u4EA4\u8BE5\u8D21\u732E\uFF0C\u60A8\u7684\u96C7\u4E3B\u5DF2\u653E\u5F03\u60A8\u5BF9 GitLink \u793E\u533A\u7684\u8D21\u732E\u7684\u6743\u5229\uFF0C\u6216\u60A8\u7684\u96C7\u4E3B\u5DF2\u4E0E GitLink \u793E\u533A\u7B7E\u8BA2\u5355\u72EC\u7684\u4F01\u4E1A\u8D21\u732E\u8005\u8BB8\u53EF\u534F\u8BAE\u3002"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement("p", null, "5. \u60A8\u4FDD\u8BC1\u60A8\u6240\u6709\u7684\u8D21\u732E\u5185\u5BB9\u5747\u4E3A\u60A8\u7684\u539F\u521B\u4F5C\u54C1\uFF08\u5173\u4E8E\u4E3A\u4ED6\u4EBA\u63D0\u4EA4\u4F5C\u54C1\u7684\u89C4\u5B9A\uFF0C\u53EF\u53C2\u89C1\u7B2C 7 \u8282\uFF09\u3002\u60A8\u4FDD\u8BC1\u60A8\u63D0\u4EA4\u7684\u8D21\u732E\u5185\u5BB9\u5305\u62EC\u4EFB\u4F55\u7B2C\u4E09\u65B9\u8BB8\u53EF\u6216\u5176\u4ED6\u9650\u5236\uFF08\u5305\u62EC\u4F46\u4E0D\u9650\u4E8E\u76F8\u5173\u4E13\u5229\u6216\u5546\u6807\uFF09\u7684\u5168\u90E8\u7EC6\u8282\uFF0C\u53EA\u8981\u8BE5\u7B49\u8BB8\u53EF\u6216\u5176\u4ED6\u9650\u5236\u4E3A\u60A8\u4E2A\u4EBA\u6240\u77E5\u6089\u4E14\u4E0E\u60A8\u7684\u8D21\u732E\u5185\u5BB9\u7684\u4EFB\u4F55\u90E8\u5206\u76F8\u5173\u3002\u5982\u53D1\u751F\u4E0D\u53D7\u672C\u534F\u8BAE\u7EA6\u675F\u7684\u7B2C\u4E09\u65B9\u6307\u63A7\u60A8\u6240\u8D21\u732E\u5185\u5BB9\u5B58\u5728\u77E5\u8BC6\u4EA7\u6743\uFF08\u5305\u62EC\u5E76\u4E0D\u9650\u4E8E\u8457\u4F5C\u6743\u3001\u4E13\u5229\u6743\uFF09\u6CD5\u5F8B\u7455\u75B5\u65F6\uFF0C\u5219\u7531\u60A8\u8D1F\u8D23\u4E0E\u8BE5\u7B2C\u4E09\u65B9\u4EA4\u6D89\uFF0CGitLink \u793E\u533A\u4E0D\u627F\u62C5\u7531\u6B64\u5F15\u8D77\u7684\u4E00\u5207\u6CD5\u5F8B\u548C\u7ECF\u6D4E\u4E0A\u7684\u8D23\u4EFB\u3002"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement("p", null, "6. \u5728\u60A8\u81EA\u613F\u63D0\u4F9B\u652F\u6301\u7684\u8303\u56F4\u4E4B\u5916\uFF0C\u60A8\u65E0\u9700\u5BF9\u60A8\u7684\u8D21\u732E\u5185\u5BB9\u63D0\u4F9B\u652F\u6301\u3002\u60A8\u53EF\u4EE5\u63D0\u4F9B\u514D\u8D39\u652F\u6301\u6216\u6536\u8D39\u652F\u6301\uFF0C\u4E5F\u53EF\u4EE5\u5B8C\u5168\u4E0D\u63D0\u4F9B\u652F\u6301\u3002\u9664\u975E\u9002\u7528\u6CD5\u5F8B\u53E6\u6709\u89C4\u5B9A\u6216\u53E6\u6709\u4E66\u9762\u7EA6\u5B9A\uFF0C\u60A8\u201C\u6309\u7167\u73B0\u72B6\u201D\u63D0\u4F9B\u60A8\u7684\u8D21\u732E\u5185\u5BB9\uFF0C\u800C\u4E0D\u5BF9\u5176\u63D0\u4F9B\u4EFB\u4F55\u7C7B\u578B\u7684\u4FDD\u8BC1\u6216\u6761\u4EF6\uFF0C\u65E0\u8BBA\u660E\u793A\u8FD8\u662F\u9ED8\u793A\uFF0C\u5305\u62EC\u4F46\u4E0D\u9650\u4E8E\u4E3A\u4EFB\u4F55\u7279\u5B9A\u76EE\u7684\u5BF9\u6240\u6709\u6743\u3001\u65E0\u4FB5\u6743\u3001\u9002\u9500\u6027\u6216\u9002\u5F53\u6027\u7684\u4FDD\u8BC1\u6216\u6761\u4EF6\u3002"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement("p", null, "7. \u5982\u679C\u60A8\u5E0C\u671B\u63D0\u4EA4\u5E76\u975E\u60A8\u539F\u521B\u7684\u4F5C\u54C1\uFF0C\u60A8\u53EF\u4EE5\u5728\u4EFB\u4F55\u8D21\u732E\u5185\u5BB9\u4E4B\u5916\u5355\u72EC\u5411GitLink \u793E\u533A\u63D0\u4EA4\uFF0C\u6807\u6CE8\u5173\u4E8E\u5176\u6765\u6E90\u548C\u60A8\u4E2A\u4EBA\u6240\u77E5\u6089\u7684\u4EFB\u4F55\u8BB8\u53EF\u6216\u5176\u4ED6\u9650\u5236\uFF08\u5305\u62EC\u4F46\u4E0D\u9650\u4E8E\u76F8\u5173\u4E13\u5229\u3001\u5546\u6807\u548C\u8BB8\u53EF\u534F\u8BAE\uFF09\u7684\u5B8C\u6574\u4FE1\u606F\uFF0C\u5E76\u4EE5\u663E\u8457\u65B9\u5F0F\u6807\u660E\u8BE5\u4F5C\u54C1\u5C5E\u4E8E\u201C\u4EE5\u7B2C\u4E09\u65B9\u540D\u4E49\u63D0\u4EA4\uFF1A\u3010\u586B\u5199\u59D3\u540D\u3011\u201D\u3002"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement("p", null, "8. \u60A8\u540C\u610F\u5728\u60A8\u83B7\u6089\u4EFB\u4F55\u53EF\u80FD\u5BFC\u81F4\u4E0A\u8FF0\u4FDD\u8BC1\u5728\u4EFB\u4F55\u65B9\u9762\u4E0D\u51C6\u786E\u7684\u4E8B\u5B9E\u6216\u60C5\u51B5\u4E4B\u65F6\u901A\u77E5 GitLink \u793E\u533A\u3002"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement("p", null, "9. \u672C\u534F\u8BAE\u53D7\u4E2D\u534E\u4EBA\u6C11\u5171\u548C\u56FD\u6CD5\u5F8B\u7BA1\u8F96\uFF0C\u5E76\u4F9D\u636E\u5176\u8FDB\u884C\u89E3\u91CA\uFF0C\u4F46\u51B2\u7A81\u6CD5\u89C4\u5219\u9664\u5916\u3002\u4EFB\u4F55\u7531\u672C\u534F\u8BAE\u4EA7\u751F\u7684\u6CD5\u5F8B\u8BC9\u8BBC\u6216\u7A0B\u5E8F\u5747\u5E94\u6392\u4ED6\u6027\u5730\u63D0\u4EA4\u81F3\u4E2D\u56FD\u957F\u6C99\u7684\u6CD5\u9662\u8FDB\u884C\u5BA1\u7406\uFF0C\u4E14\u5404\u65B9\u5728\u6B64\u4E0D\u53EF\u64A4\u9500\u5730\u540C\u610F\u8BE5\u7B49\u5173\u4E8E\u5C5E\u4EBA\u7BA1\u8F96\u548C\u6CD5\u9662\u5730\u7684\u5B89\u6392\u3002"))), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement("div", {
className: _Cla_less_modules__WEBPACK_IMPORTED_MODULE_17___default.a.rightBox
}, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement("div", {
className: _Cla_less_modules__WEBPACK_IMPORTED_MODULE_17___default.a.desc
}, "1\u3001\u5728\u62A5\u540D\u524D\uFF0C\u8BF7\u786E\u4FDD\u5DF2\u7B7E\u7F72openkylin\u9879\u76EEcla\u534F\u8BAE", /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement("br", null), "2\u3001\u5B8C\u6210\u7B7E\u7F72\u540E\uFF0C\u60A8\u5C06\u540C\u6B65\u6CE8\u518C\u4E00\u4E2Aopenkylin\u8D26\u53F7"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement(antd_es_form__WEBPACK_IMPORTED_MODULE_13__[/* default */ "a"], {
form: form,
className: _Cla_less_modules__WEBPACK_IMPORTED_MODULE_17___default.a.formWrap,
scrollToFirstError: true,
layout: "vertical"
}, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement(antd_es_form__WEBPACK_IMPORTED_MODULE_13__[/* default */ "a"].Item, {
name: "GitLinkID",
label: "GitLinkID",
rules: [{
required: true,
message: 'GitLinkID不能为空'
}]
}, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement(antd_es_input__WEBPACK_IMPORTED_MODULE_10__[/* default */ "a"], {
placeholder: "\u8BF7\u8F93\u5165GitLinkID",
disabled: true
})), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement(antd_es_form__WEBPACK_IMPORTED_MODULE_13__[/* default */ "a"].Item, {
name: "email",
label: "\u90AE\u7BB1",
rules: [{
required: true,
message: '邮箱不能为空'
}]
}, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement(antd_es_input__WEBPACK_IMPORTED_MODULE_10__[/* default */ "a"], {
placeholder: "\u8BF7\u8F93\u5165\u90AE\u7BB1\u8D26\u53F7"
})), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement(antd_es_form__WEBPACK_IMPORTED_MODULE_13__[/* default */ "a"].Item, {
name: "name",
label: "\u59D3\u540D",
rules: [{
required: true,
message: '姓名不能为空'
}]
}, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement(antd_es_input__WEBPACK_IMPORTED_MODULE_10__[/* default */ "a"], {
maxLength: 32,
placeholder: "\u8BF7\u8F93\u5165\u59D3\u540D"
})), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement(antd_es_form__WEBPACK_IMPORTED_MODULE_13__[/* default */ "a"].Item, {
name: "phoneNumber",
label: "\u624B\u673A\u53F7\u7801",
rules: [{
required: true,
message: '手机号码不能为空'
}]
}, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement(antd_es_input__WEBPACK_IMPORTED_MODULE_10__[/* default */ "a"], {
maxLength: 11,
placeholder: "\u8BF7\u8F93\u5165\u624B\u673A\u53F7\u7801"
})), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement(antd_es_form__WEBPACK_IMPORTED_MODULE_13__[/* default */ "a"].Item, {
name: "address",
label: "\u8054\u7CFB\u5730\u5740",
rules: [{
required: true,
message: '联系地址不能为空'
}]
}, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement(antd_es_input__WEBPACK_IMPORTED_MODULE_10__[/* default */ "a"], {
maxLength: 100,
placeholder: "\u8BF7\u8F93\u5165\u8054\u7CFB\u5730\u5740\uFF08\u4E0D\u8D85\u8FC7100\u4E2A\u5B57\uFF09"
})), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement(antd_es_checkbox__WEBPACK_IMPORTED_MODULE_8__[/* default */ "a"], {
value: "readed",
checked: checkCla,
onChange: function onChange(e) {
setCheckCla(e.target.checked);
if (!e.target.checked) {
setCheckClaFlag(true);
} else {
setCheckClaFlag(false);
}
}
}, "\u6211\u5DF2\u9605\u8BFB\u5E76\u540C\u610F\u7B7E\u7F72"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement("div", {
style: {
color: "#ff4d4f",
height: "20px"
}
}, checkClaFlag && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement("p", {
style: {
margin: "0px"
}
}, "\u8BF7\u9605\u8BFB\u5E76\u540C\u610F\u7B7E\u7F72CLA\u534F\u8BAE")), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_15___default.a.createElement(antd_es_button__WEBPACK_IMPORTED_MODULE_6__[/* default */ "a"], {
type: "primary",
onClick: getCla,
style: {
width: "100%",
height: "36px",
backgroundColor: "#466aff"
}
}, "\u7B7E\u7F72")))));
};
/* harmony default export */ __webpack_exports__["a"] = (Object(umi__WEBPACK_IMPORTED_MODULE_16__[/* connect */ "a"])(function (_ref2) {
var competitions = _ref2.competitions,
loading = _ref2.loading,
globalSetting = _ref2.globalSetting,
user = _ref2.user;
return {
competitions: competitions,
globalSetting: globalSetting,
loading: loading.models.competitions,
user: user
};
})(AddClamodal));
/***/ }),
/***/ "ZTPi":
/*!*********************************************************!*\
!*** ./node_modules/antd/es/tabs/index.js + 51 modules ***!
\*********************************************************/
/*! exports provided: default */
/*! exports used: default */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/CloseOutlined.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/EllipsisOutlined.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/PlusOutlined.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/defineProperty.js (<- Module is not an ECMAScript module) */
/*! 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/helpers/extends.js (<- Module is not an ECMAScript module) */
/*! 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/antd/es/_util/devWarning.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/config-provider/context.js */
/*! 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/react-dom/index.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/react/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 ./node_modules/shallowequal/index.js (<- Module is not an ECMAScript module) */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/extends.js
var helpers_extends = __webpack_require__("pVnL");
var extends_default = /*#__PURE__*/__webpack_require__.n(helpers_extends);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/defineProperty.js
var defineProperty = __webpack_require__("lSNA");
var defineProperty_default = /*#__PURE__*/__webpack_require__.n(defineProperty);
// EXTERNAL MODULE: ./node_modules/react/index.js
var react = __webpack_require__("q1tI");
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/defineProperty.js
var esm_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: ./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(react["useRef"])();
var removedRef = Object(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(react["useEffect"])(function () {
return function () {
removedRef.current = true;
raf_default.a.cancel(rafRef.current);
};
}, []);
return trigger;
}
function useRafState(defaultState) {
var batchRef = Object(react["useRef"])([]);
var _useState = Object(react["useState"])({}),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
forceUpdate = _useState2[1];
var state = Object(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");
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 = react["createElement"]("div", {
key: key,
ref: ref,
className: classnames_default()(tabPrefix, (_classNames = {}, Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(tabPrefix, "-with-remove"), removable), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(tabPrefix, "-active"), active), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(tabPrefix, "-disabled"), disabled), _classNames)),
style: nodeStyle,
onClick: onInternalClick
}, 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 && 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 = (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(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(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;
react["Children"].forEach(children, function (c) {
index += 1;
if (c && c.type && c.type.isMenuItemGroup) {
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;
}
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: ./node_modules/react-dom/index.js
var react_dom = __webpack_require__("i8i4");
var react_dom_default = /*#__PURE__*/__webpack_require__.n(react_dom);
// 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(react["useRef"])(false);
var _useState = Object(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(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 */])() ? react["useLayoutEffect"] : 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 = 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;
}
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 = 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]);
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(react["useRef"])(); // Cache callback
var callbackRef = Object(react["useRef"])(callback);
callbackRef.current = callback; // Internal motion event handler
var onInternalMotionEnd = 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
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(react["useRef"])(false);
var deadlineRef = Object(react["useRef"])(null);
var destroyedRef = Object(react["useRef"])(false); // =========================== Dom Node ===========================
var cacheElementRef = Object(react["useRef"])(null);
function getDomElement() {
var element = getElement();
return element || cacheElementRef.current;
} // ========================== Motion End ==========================
var activeRef = Object(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 = react["useMemo"](function () {
var _ref2, _ref3, _ref4;
switch (status) {
case 'appear':
return _ref2 = {}, Object(esm_defineProperty["a" /* default */])(_ref2, STEP_PREPARE, onAppearPrepare), Object(esm_defineProperty["a" /* default */])(_ref2, STEP_START, onAppearStart), Object(esm_defineProperty["a" /* default */])(_ref2, STEP_ACTIVE, onAppearActive), _ref2;
case 'enter':
return _ref3 = {}, Object(esm_defineProperty["a" /* default */])(_ref3, STEP_PREPARE, onEnterPrepare), Object(esm_defineProperty["a" /* default */])(_ref3, STEP_START, onEnterStart), Object(esm_defineProperty["a" /* default */])(_ref3, STEP_ACTIVE, onEnterActive), _ref3;
case 'leave':
return _ref4 = {}, Object(esm_defineProperty["a" /* default */])(_ref4, STEP_PREPARE, onLeavePrepare), Object(esm_defineProperty["a" /* default */])(_ref4, STEP_START, onLeaveStart), Object(esm_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(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(react["useEffect"])(function () {
return function () {
clearTimeout(deadlineRef.current);
destroyedRef.current = true;
};
}, []); // Trigger `onVisibleChanged`
Object(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;
}(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__*/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(react["useRef"])(); // Ref to the dom wrapper in case ref can not pass to HTMLElement
var wrapperNodeRef = Object(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 = react["useRef"](mergedVisible);
if (mergedVisible) {
renderedRef.current = true;
} // ====================== Refs ======================
var originRef = Object(react["useRef"])(ref);
originRef.current = ref;
var setNodeRef = 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(esm_defineProperty["a" /* default */])(_classNames, getTransitionName(motionName, "".concat(status, "-").concat(statusSuffix)), statusSuffix), Object(esm_defineProperty["a" /* default */])(_classNames, motionName, typeof motionName === 'string'), _classNames)),
style: statusStyle
}), setNodeRef);
}
return /*#__PURE__*/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 || react["Fragment"];
var motionProps = {};
MOTION_PROP_NAMES.forEach(function (prop) {
motionProps[prop] = restProps[prop];
delete restProps[prop];
});
delete restProps.keys;
return /*#__PURE__*/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__*/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;
}(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__*/react["createElement"](rc_motion_es, Object(esm_extends["a" /* default */])({}, motion, {
visible: visible,
removeOnLeave: true
}), function (_ref) {
var className = _ref.className;
return /*#__PURE__*/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(react["useState"])(null),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
status = _useState2[0],
setInternalStatus = _useState2[1];
var rafRef = Object(react["useRef"])();
var destroyRef = Object(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(react["useEffect"])(function () {
setStatus('measure');
}, [visible]); // Go next status
Object(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(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 = 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 = 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__*/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(react["useRef"])();
var elementRef = Object(react["useRef"])();
var _useState = Object(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(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
react["useEffect"](function () {
if (!motion.motionName && status === 'motion') {
goNextStatus();
}
}, [motion.motionName, status]); // ========================= Refs =========================
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 (react["Children"].count(children) > 1) {
childNode = /*#__PURE__*/react["createElement"]("div", {
className: "".concat(prefixCls, "-content")
}, children);
}
return /*#__PURE__*/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__*/react["createElement"](rc_align_es["a" /* default */], {
target: getAlignTarget(),
key: "popup",
ref: alignRef,
monitorWindowResize: true,
disabled: alignDisabled,
align: align,
onAlign: onInternalAlign
}, /*#__PURE__*/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__*/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 = react["useRef"](); // ========================= Refs =========================
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 (react["Children"].count(children) > 1) {
childNode = /*#__PURE__*/react["createElement"]("div", {
className: "".concat(prefixCls, "-content")
}, children);
} // Mobile support additional render
if (popupRender) {
childNode = popupRender(childNode);
}
return /*#__PURE__*/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__*/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__*/react["forwardRef"](function (_ref, ref) {
var visible = _ref.visible,
mobile = _ref.mobile,
props = Object(objectWithoutProperties["a" /* default */])(_ref, _excluded);
var _useState = Object(react["useState"])(visible),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
innerVisible = _useState2[0],
serInnerVisible = _useState2[1];
var _useState3 = Object(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(react["useEffect"])(function () {
serInnerVisible(visible);
if (visible && mobile) {
setInMobile(es_isMobile());
}
}, [visible, mobile]);
var popupNode = inMobile ? /*#__PURE__*/react["createElement"](Popup_MobilePopupInner, Object(esm_extends["a" /* default */])({}, cloneProps, {
mobile: mobile,
ref: ref
})) : /*#__PURE__*/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__*/react["createElement"]("div", null, /*#__PURE__*/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__*/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__*/react["createRef"]();
_this.triggerRef = /*#__PURE__*/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 react_dom_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__*/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 = 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__*/react["cloneElement"](child, cloneProps);
var portal; // prevent unmounting after it's rendered
if (popupVisible || this.popupRef.current || forceRender) {
portal = /*#__PURE__*/react["createElement"](PortalComponent, {
key: "portal",
getContainer: this.getContainer,
didUpdate: this.handlePortalUpdate
}, this.getComponent());
}
if (!popupVisible && autoDestroy) {
portal = null;
}
return /*#__PURE__*/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;
}(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(esm_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 = react_dom["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__*/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__*/react["createElement"]("div", null);
}
var sharedClassName = classnames_default()("".concat(baseProps.prefixCls, "-sub"), Object(esm_defineProperty["a" /* default */])({}, "".concat(baseProps.prefixCls, "-rtl"), direction === 'rtl'));
if (!this.isInlineMode()) {
return this.renderPopupMenu(sharedClassName);
}
return /*#__PURE__*/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(esm_defineProperty["a" /* default */])(_classNames2, props.className, !!props.className), Object(esm_defineProperty["a" /* default */])(_classNames2, this.getOpenClassName(), visible), Object(esm_defineProperty["a" /* default */])(_classNames2, this.getActiveClassName(), props.active || visible && !inline), Object(esm_defineProperty["a" /* default */])(_classNames2, this.getDisabledClassName(), props.disabled), Object(esm_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__*/react["createElement"](this.props.expandIcon, Object(objectSpread2["a" /* default */])({}, this.props));
}
}
var title = /*#__PURE__*/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__*/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(esm_defineProperty["a" /* default */])(_classNames3, props.popupClassName, props.popupClassName && !inline), Object(esm_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__*/react["createElement"]("li", Object(esm_extends["a" /* default */])({}, props, mouseEvents, {
className: className,
role: "menuitem"
}), /*#__PURE__*/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;
}(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__*/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__*/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__*/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__*/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__*/react["createElement"](Tag, Object(esm_extends["a" /* default */])({
ref: this.childRef
}, rest), this.renderChildren(children));
}
}]);
return DOMWrap;
}(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(esm_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__*/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(esm_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__*/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;
}(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__*/react["createElement"](esm["a" /* Provider */], {
store: this.store
}, /*#__PURE__*/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;
}(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__*/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(esm_defineProperty["a" /* default */])(_classNames, this.getActiveClassName(), !props.disabled && props.active), Object(esm_defineProperty["a" /* default */])(_classNames, this.getSelectedClassName(), props.isSelected), Object(esm_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__*/react["createElement"](this.props.itemIcon, this.props);
}
return /*#__PURE__*/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;
}(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__*/react["createElement"]("li", Object(esm_extends["a" /* default */])({}, props, {
onClick: function onClick(e) {
return e.stopPropagation();
},
className: "".concat(className, " ").concat(rootPrefixCls, "-item-group")
}), /*#__PURE__*/react["createElement"]("div", {
className: titleClassName,
title: typeof title === 'string' ? title : undefined
}, title), /*#__PURE__*/react["createElement"]("ul", {
className: listClassName
}, react["Children"].map(children, this.renderInnerMenuItem)));
}
}]);
return MenuItemGroup;
}(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__*/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 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 = (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(react["useState"])(false),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
open = _useState2[0],
setOpen = _useState2[1];
var _useState3 = Object(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 = 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 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(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(react["useEffect"])(function () {
if (!open) {
setSelectedKey(null);
}
}, [open]); // ========================= Render =========================
var moreStyle = Object(esm_defineProperty["a" /* default */])({}, rtl ? 'marginLeft' : 'marginRight', tabBarGutter);
if (!tabs.length) {
moreStyle.visibility = 'hidden';
moreStyle.order = 1;
}
var overlayClassName = classnames_default()(Object(esm_defineProperty["a" /* default */])({}, "".concat(dropdownPrefix, "-rtl"), rtl));
var moreNode = mobile ? null : 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
}, 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 react["createElement"]("div", {
className: classnames_default()("".concat(prefixCls, "-nav-operations"), className),
style: style,
ref: ref
}, moreNode, react["createElement"](TabNavList_AddButton, {
prefixCls: prefixCls,
locale: locale,
editable: editable
}));
}
/* harmony default export */ var TabNavList_OperationNode = (react["forwardRef"](OperationNode));
// CONCATENATED MODULE: ./node_modules/rc-tabs/es/TabContext.js
/* harmony default export */ var TabContext = (Object(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(react["useState"])(),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
touchPosition = _useState2[0],
setTouchPosition = _useState2[1];
var _useState3 = Object(react["useState"])(0),
_useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
lastTimestamp = _useState4[0],
setLastTimestamp = _useState4[1];
var _useState5 = Object(react["useState"])(0),
_useState6 = Object(slicedToArray["a" /* default */])(_useState5, 2),
lastTimeDiff = _useState6[0],
setLastTimeDiff = _useState6[1];
var _useState7 = Object(react["useState"])(),
_useState8 = Object(slicedToArray["a" /* default */])(_useState7, 2),
lastOffset = _useState8[0],
setLastOffset = _useState8[1];
var motionRef = Object(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(react["useRef"])(0);
var lastWheelPreventRef = Object(react["useRef"])(false);
var lastWheelDirectionRef = Object(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(react["useRef"])(null);
touchEventsRef.current = {
onTouchStart: onTouchStart,
onTouchMove: onTouchMove,
onTouchEnd: onTouchEnd,
onWheel: onWheel
};
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(react["useRef"])(new Map());
function getRef(key) {
if (!cacheRefs.current.has(key)) {
cacheRefs.current.set(key, 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 = react["useRef"](defaultState);
var _React$useState = 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 ? react["createElement"]("div", {
className: "".concat(prefixCls, "-extra-content")
}, content) : null;
};
function TabNavList(props, ref) {
var _classNames;
var _React$useContext = 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(react["useRef"])();
var tabListRef = Object(react["useRef"])();
var operationsRef = Object(react["useRef"])();
var innerAddButtonRef = Object(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(react["useState"])(0),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
wrapperScrollWidth = _useState2[0],
setWrapperScrollWidth = _useState2[1];
var _useState3 = Object(react["useState"])(0),
_useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
wrapperScrollHeight = _useState4[0],
setWrapperScrollHeight = _useState4[1];
var _useState5 = Object(react["useState"])(0),
_useState6 = Object(slicedToArray["a" /* default */])(_useState5, 2),
wrapperContentWidth = _useState6[0],
setWrapperContentWidth = _useState6[1];
var _useState7 = Object(react["useState"])(0),
_useState8 = Object(slicedToArray["a" /* default */])(_useState7, 2),
wrapperContentHeight = _useState8[0],
setWrapperContentHeight = _useState8[1];
var _useState9 = Object(react["useState"])(null),
_useState10 = Object(slicedToArray["a" /* default */])(_useState9, 2),
wrapperWidth = _useState10[0],
setWrapperWidth = _useState10[1];
var _useState11 = Object(react["useState"])(null),
_useState12 = Object(slicedToArray["a" /* default */])(_useState11, 2),
wrapperHeight = _useState12[0],
setWrapperHeight = _useState12[1];
var _useState13 = Object(react["useState"])(0),
_useState14 = Object(slicedToArray["a" /* default */])(_useState13, 2),
addWidth = _useState14[0],
setAddWidth = _useState14[1];
var _useState15 = Object(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(react["useRef"])();
var _useState17 = Object(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(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 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(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(react["useRef"])();
function cleanInkBarRaf() {
raf_default.a.cancel(inkBarRafRef.current);
}
Object(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(react["useEffect"])(function () {
scrollToTab();
}, [activeKey, activeTabOffset, tabOffsets, tabPositionTopOrBottom]); // Should recalculate when rtl changed
Object(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 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();
}
}, react["createElement"](TabNavList_ExtraContent, {
position: "left",
extra: extra,
prefixCls: prefixCls
}), react["createElement"](es["a" /* default */], {
onResize: onListHolderResize
}, react["createElement"]("div", {
className: classnames_default()(wrapPrefix, (_classNames = {}, Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(wrapPrefix, "-ping-left"), pingLeft), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(wrapPrefix, "-ping-right"), pingRight), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(wrapPrefix, "-ping-top"), pingTop), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(wrapPrefix, "-ping-bottom"), pingBottom), _classNames)),
ref: tabsWrapperRef
}, react["createElement"](es["a" /* default */], {
onResize: onListHolderResize
}, react["createElement"]("div", {
ref: tabListRef,
className: "".concat(prefixCls, "-nav-list"),
style: {
transform: "translate(".concat(transformLeft, "px, ").concat(transformTop, "px)"),
transition: lockAnimation ? 'none' : undefined
}
}, tabNodes, react["createElement"](TabNavList_AddButton, {
ref: innerAddButtonRef,
prefixCls: prefixCls,
locale: locale,
editable: editable,
style: {
visibility: hasDropdown ? 'hidden' : null
}
}), react["createElement"]("div", {
className: classnames_default()("".concat(prefixCls, "-ink-bar"), Object(esm_defineProperty["a" /* default */])({}, "".concat(prefixCls, "-ink-bar-animated"), animated.inkBar)),
style: inkStyle
}))))), react["createElement"](TabNavList_OperationNode, Object.assign({}, props, {
ref: operationsRef,
prefixCls: prefixCls,
tabs: hiddenTabs,
className: !hasDropdown && operationsHiddenClassName
})), react["createElement"](TabNavList_ExtraContent, {
position: "right",
extra: extra,
prefixCls: prefixCls
}));
/* eslint-enable */
}
/* harmony default export */ var es_TabNavList = (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 = 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 react["createElement"]("div", {
className: classnames_default()("".concat(prefixCls, "-content-holder"))
}, react["createElement"]("div", {
className: classnames_default()("".concat(prefixCls, "-content"), "".concat(prefixCls, "-content-").concat(tabPosition), Object(esm_defineProperty["a" /* default */])({}, "".concat(prefixCls, "-content-animated"), tabPaneAnimated)),
style: activeIndex && tabPaneAnimated ? Object(esm_defineProperty["a" /* default */])({}, rtl ? 'marginRight' : 'marginLeft', "-".concat(activeIndex, "00%")) : null
}, tabs.map(function (tab) {
return 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 = react["useState"](forceRender),
_React$useState2 = Object(slicedToArray["a" /* default */])(_React$useState, 2),
visited = _React$useState2[0],
setVisited = _React$useState2[1];
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 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 (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(react["useState"])(false),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
mobile = _useState2[0],
setMobile = _useState2[1];
Object(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(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(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(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 = react["createElement"](es_TabNavList, Object.assign({}, tabNavBarProps));
}
return react["createElement"](TabContext.Provider, {
value: {
tabs: tabs,
prefixCls: prefixCls
}
}, react["createElement"]("div", Object.assign({
ref: ref,
id: id,
className: classnames_default()(prefixCls, "".concat(prefixCls, "-").concat(mergedTabPosition), (_classNames = {}, Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-mobile"), mobile), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-editable"), editable), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-rtl"), rtl), _classNames), className)
}, restProps), tabNavBar, react["createElement"](TabPanelList, Object.assign({
destroyInactiveTabPane: destroyInactiveTabPane
}, sharedProps, {
animated: mergedAnimated
}))));
}
var ForwardTabs = 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 = (es_Tabs);
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/EllipsisOutlined.js
var EllipsisOutlined = __webpack_require__("cCPh");
var EllipsisOutlined_default = /*#__PURE__*/__webpack_require__.n(EllipsisOutlined);
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/PlusOutlined.js
var PlusOutlined = __webpack_require__("fNCr");
var PlusOutlined_default = /*#__PURE__*/__webpack_require__.n(PlusOutlined);
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/CloseOutlined.js
var CloseOutlined = __webpack_require__("V/uB");
var CloseOutlined_default = /*#__PURE__*/__webpack_require__.n(CloseOutlined);
// EXTERNAL MODULE: ./node_modules/antd/es/_util/devWarning.js
var devWarning = __webpack_require__("uaoM");
// EXTERNAL MODULE: ./node_modules/antd/es/config-provider/context.js + 1 modules
var config_provider_context = __webpack_require__("H84U");
// CONCATENATED MODULE: ./node_modules/antd/es/tabs/index.js
var __rest = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
function tabs_Tabs(_a) {
var _classNames;
var type = _a.type,
className = _a.className,
size = _a.size,
_onEdit = _a.onEdit,
hideAdd = _a.hideAdd,
centered = _a.centered,
addIcon = _a.addIcon,
props = __rest(_a, ["type", "className", "size", "onEdit", "hideAdd", "centered", "addIcon"]);
var customizePrefixCls = props.prefixCls;
var _React$useContext = react["useContext"](config_provider_context["b" /* ConfigContext */]),
getPrefixCls = _React$useContext.getPrefixCls,
direction = _React$useContext.direction;
var prefixCls = getPrefixCls('tabs', customizePrefixCls);
var editable;
if (type === 'editable-card') {
editable = {
onEdit: function onEdit(editType, _ref) {
var key = _ref.key,
event = _ref.event;
_onEdit === null || _onEdit === void 0 ? void 0 : _onEdit(editType === 'add' ? event : key, editType);
},
removeIcon: /*#__PURE__*/react["createElement"](CloseOutlined_default.a, null),
addIcon: addIcon || /*#__PURE__*/react["createElement"](PlusOutlined_default.a, null),
showAdd: hideAdd !== true
};
}
Object(devWarning["a" /* default */])(!('onPrevClick' in props) && !('onNextClick' in props), 'Tabs', '`onPrevClick` and `onNextClick` has been removed. Please use `onTabScroll` instead.');
return /*#__PURE__*/react["createElement"](rc_tabs_es, extends_default()({
direction: direction
}, props, {
moreTransitionName: "slide-up",
className: classnames_default()(className, (_classNames = {}, defineProperty_default()(_classNames, "".concat(prefixCls, "-").concat(size), size), defineProperty_default()(_classNames, "".concat(prefixCls, "-card"), ['card', 'editable-card'].includes(type)), defineProperty_default()(_classNames, "".concat(prefixCls, "-editable-card"), type === 'editable-card'), defineProperty_default()(_classNames, "".concat(prefixCls, "-centered"), centered), _classNames)),
editable: editable,
moreIcon: /*#__PURE__*/react["createElement"](EllipsisOutlined_default.a, null),
prefixCls: prefixCls
}));
}
tabs_Tabs.TabPane = TabPane;
/* harmony default export */ var es_tabs = __webpack_exports__["a"] = (tabs_Tabs);
/***/ }),
/***/ "Znn+":
/*!**************************************************!*\
!*** ./node_modules/antd/es/tabs/style/index.js ***!
\**************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _style_index_less__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../style/index.less */ "cIOH");
/* harmony import */ var _style_index_less__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_style_index_less__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _index_less__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./index.less */ "9ama");
/* harmony import */ var _index_less__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_index_less__WEBPACK_IMPORTED_MODULE_1__);
/***/ }),
/***/ "Zss7":
/*!**********************************************!*\
!*** ./node_modules/tinycolor2/tinycolor.js ***!
\**********************************************/
/*! no static exports found */
/*! exports used: default */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;// TinyColor v1.4.2
// https://github.com/bgrins/TinyColor
// Brian Grinstead, MIT License
(function(Math) {
var trimLeft = /^\s+/,
trimRight = /\s+$/,
tinyCounter = 0,
mathRound = Math.round,
mathMin = Math.min,
mathMax = Math.max,
mathRandom = Math.random;
function tinycolor (color, opts) {
color = (color) ? color : '';
opts = opts || { };
// If input is already a tinycolor, return itself
if (color instanceof tinycolor) {
return color;
}
// If we are called as a function, call using new instead
if (!(this instanceof tinycolor)) {
return new tinycolor(color, opts);
}
var rgb = inputToRGB(color);
this._originalInput = color,
this._r = rgb.r,
this._g = rgb.g,
this._b = rgb.b,
this._a = rgb.a,
this._roundA = mathRound(100*this._a) / 100,
this._format = opts.format || rgb.format;
this._gradientType = opts.gradientType;
// Don't let the range of [0,255] come back in [0,1].
// Potentially lose a little bit of precision here, but will fix issues where
// .5 gets interpreted as half of the total, instead of half of 1
// If it was supposed to be 128, this was already taken care of by `inputToRgb`
if (this._r < 1) { this._r = mathRound(this._r); }
if (this._g < 1) { this._g = mathRound(this._g); }
if (this._b < 1) { this._b = mathRound(this._b); }
this._ok = rgb.ok;
this._tc_id = tinyCounter++;
}
tinycolor.prototype = {
isDark: function() {
return this.getBrightness() < 128;
},
isLight: function() {
return !this.isDark();
},
isValid: function() {
return this._ok;
},
getOriginalInput: function() {
return this._originalInput;
},
getFormat: function() {
return this._format;
},
getAlpha: function() {
return this._a;
},
getBrightness: function() {
//http://www.w3.org/TR/AERT#color-contrast
var rgb = this.toRgb();
return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;
},
getLuminance: function() {
//http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
var rgb = this.toRgb();
var RsRGB, GsRGB, BsRGB, R, G, B;
RsRGB = rgb.r/255;
GsRGB = rgb.g/255;
BsRGB = rgb.b/255;
if (RsRGB <= 0.03928) {R = RsRGB / 12.92;} else {R = Math.pow(((RsRGB + 0.055) / 1.055), 2.4);}
if (GsRGB <= 0.03928) {G = GsRGB / 12.92;} else {G = Math.pow(((GsRGB + 0.055) / 1.055), 2.4);}
if (BsRGB <= 0.03928) {B = BsRGB / 12.92;} else {B = Math.pow(((BsRGB + 0.055) / 1.055), 2.4);}
return (0.2126 * R) + (0.7152 * G) + (0.0722 * B);
},
setAlpha: function(value) {
this._a = boundAlpha(value);
this._roundA = mathRound(100*this._a) / 100;
return this;
},
toHsv: function() {
var hsv = rgbToHsv(this._r, this._g, this._b);
return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a };
},
toHsvString: function() {
var hsv = rgbToHsv(this._r, this._g, this._b);
var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100);
return (this._a == 1) ?
"hsv(" + h + ", " + s + "%, " + v + "%)" :
"hsva(" + h + ", " + s + "%, " + v + "%, "+ this._roundA + ")";
},
toHsl: function() {
var hsl = rgbToHsl(this._r, this._g, this._b);
return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a };
},
toHslString: function() {
var hsl = rgbToHsl(this._r, this._g, this._b);
var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100);
return (this._a == 1) ?
"hsl(" + h + ", " + s + "%, " + l + "%)" :
"hsla(" + h + ", " + s + "%, " + l + "%, "+ this._roundA + ")";
},
toHex: function(allow3Char) {
return rgbToHex(this._r, this._g, this._b, allow3Char);
},
toHexString: function(allow3Char) {
return '#' + this.toHex(allow3Char);
},
toHex8: function(allow4Char) {
return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char);
},
toHex8String: function(allow4Char) {
return '#' + this.toHex8(allow4Char);
},
toRgb: function() {
return { r: mathRound(this._r), g: mathRound(this._g), b: mathRound(this._b), a: this._a };
},
toRgbString: function() {
return (this._a == 1) ?
"rgb(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ")" :
"rgba(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ", " + this._roundA + ")";
},
toPercentageRgb: function() {
return { r: mathRound(bound01(this._r, 255) * 100) + "%", g: mathRound(bound01(this._g, 255) * 100) + "%", b: mathRound(bound01(this._b, 255) * 100) + "%", a: this._a };
},
toPercentageRgbString: function() {
return (this._a == 1) ?
"rgb(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%)" :
"rgba(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")";
},
toName: function() {
if (this._a === 0) {
return "transparent";
}
if (this._a < 1) {
return false;
}
return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false;
},
toFilter: function(secondColor) {
var hex8String = '#' + rgbaToArgbHex(this._r, this._g, this._b, this._a);
var secondHex8String = hex8String;
var gradientType = this._gradientType ? "GradientType = 1, " : "";
if (secondColor) {
var s = tinycolor(secondColor);
secondHex8String = '#' + rgbaToArgbHex(s._r, s._g, s._b, s._a);
}
return "progid:DXImageTransform.Microsoft.gradient("+gradientType+"startColorstr="+hex8String+",endColorstr="+secondHex8String+")";
},
toString: function(format) {
var formatSet = !!format;
format = format || this._format;
var formattedString = false;
var hasAlpha = this._a < 1 && this._a >= 0;
var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "hex4" || format === "hex8" || format === "name");
if (needsAlphaFormat) {
// Special case for "transparent", all other non-alpha formats
// will return rgba when there is transparency.
if (format === "name" && this._a === 0) {
return this.toName();
}
return this.toRgbString();
}
if (format === "rgb") {
formattedString = this.toRgbString();
}
if (format === "prgb") {
formattedString = this.toPercentageRgbString();
}
if (format === "hex" || format === "hex6") {
formattedString = this.toHexString();
}
if (format === "hex3") {
formattedString = this.toHexString(true);
}
if (format === "hex4") {
formattedString = this.toHex8String(true);
}
if (format === "hex8") {
formattedString = this.toHex8String();
}
if (format === "name") {
formattedString = this.toName();
}
if (format === "hsl") {
formattedString = this.toHslString();
}
if (format === "hsv") {
formattedString = this.toHsvString();
}
return formattedString || this.toHexString();
},
clone: function() {
return tinycolor(this.toString());
},
_applyModification: function(fn, args) {
var color = fn.apply(null, [this].concat([].slice.call(args)));
this._r = color._r;
this._g = color._g;
this._b = color._b;
this.setAlpha(color._a);
return this;
},
lighten: function() {
return this._applyModification(lighten, arguments);
},
brighten: function() {
return this._applyModification(brighten, arguments);
},
darken: function() {
return this._applyModification(darken, arguments);
},
desaturate: function() {
return this._applyModification(desaturate, arguments);
},
saturate: function() {
return this._applyModification(saturate, arguments);
},
greyscale: function() {
return this._applyModification(greyscale, arguments);
},
spin: function() {
return this._applyModification(spin, arguments);
},
_applyCombination: function(fn, args) {
return fn.apply(null, [this].concat([].slice.call(args)));
},
analogous: function() {
return this._applyCombination(analogous, arguments);
},
complement: function() {
return this._applyCombination(complement, arguments);
},
monochromatic: function() {
return this._applyCombination(monochromatic, arguments);
},
splitcomplement: function() {
return this._applyCombination(splitcomplement, arguments);
},
triad: function() {
return this._applyCombination(triad, arguments);
},
tetrad: function() {
return this._applyCombination(tetrad, arguments);
}
};
// If input is an object, force 1 into "1.0" to handle ratios properly
// String input requires "1.0" as input, so 1 will be treated as 1
tinycolor.fromRatio = function(color, opts) {
if (typeof color == "object") {
var newColor = {};
for (var i in color) {
if (color.hasOwnProperty(i)) {
if (i === "a") {
newColor[i] = color[i];
}
else {
newColor[i] = convertToPercentage(color[i]);
}
}
}
color = newColor;
}
return tinycolor(color, opts);
};
// Given a string or object, convert that input to RGB
// Possible string inputs:
//
// "red"
// "#f00" or "f00"
// "#ff0000" or "ff0000"
// "#ff000000" or "ff000000"
// "rgb 255 0 0" or "rgb (255, 0, 0)"
// "rgb 1.0 0 0" or "rgb (1, 0, 0)"
// "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1"
// "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1"
// "hsl(0, 100%, 50%)" or "hsl 0 100% 50%"
// "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1"
// "hsv(0, 100%, 100%)" or "hsv 0 100% 100%"
//
function inputToRGB(color) {
var rgb = { r: 0, g: 0, b: 0 };
var a = 1;
var s = null;
var v = null;
var l = null;
var ok = false;
var format = false;
if (typeof color == "string") {
color = stringInputToObject(color);
}
if (typeof color == "object") {
if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) {
rgb = rgbToRgb(color.r, color.g, color.b);
ok = true;
format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb";
}
else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) {
s = convertToPercentage(color.s);
v = convertToPercentage(color.v);
rgb = hsvToRgb(color.h, s, v);
ok = true;
format = "hsv";
}
else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) {
s = convertToPercentage(color.s);
l = convertToPercentage(color.l);
rgb = hslToRgb(color.h, s, l);
ok = true;
format = "hsl";
}
if (color.hasOwnProperty("a")) {
a = color.a;
}
}
a = boundAlpha(a);
return {
ok: ok,
format: color.format || format,
r: mathMin(255, mathMax(rgb.r, 0)),
g: mathMin(255, mathMax(rgb.g, 0)),
b: mathMin(255, mathMax(rgb.b, 0)),
a: a
};
}
// Conversion Functions
// --------------------
// `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:
// <http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript>
// `rgbToRgb`
// Handle bounds / percentage checking to conform to CSS color spec
// <http://www.w3.org/TR/css3-color/>
// *Assumes:* r, g, b in [0, 255] or [0, 1]
// *Returns:* { r, g, b } in [0, 255]
function rgbToRgb(r, g, b){
return {
r: bound01(r, 255) * 255,
g: bound01(g, 255) * 255,
b: bound01(b, 255) * 255
};
}
// `rgbToHsl`
// Converts an RGB color value to HSL.
// *Assumes:* r, g, and b are contained in [0, 255] or [0, 1]
// *Returns:* { h, s, l } in [0,1]
function rgbToHsl(r, g, b) {
r = bound01(r, 255);
g = bound01(g, 255);
b = bound01(b, 255);
var max = mathMax(r, g, b), min = mathMin(r, g, b);
var h, s, l = (max + min) / 2;
if(max == min) {
h = s = 0; // achromatic
}
else {
var d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch(max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return { h: h, s: s, l: l };
}
// `hslToRgb`
// Converts an HSL color value to RGB.
// *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100]
// *Returns:* { r, g, b } in the set [0, 255]
function hslToRgb(h, s, l) {
var r, g, b;
h = bound01(h, 360);
s = bound01(s, 100);
l = bound01(l, 100);
function hue2rgb(p, q, t) {
if(t < 0) t += 1;
if(t > 1) t -= 1;
if(t < 1/6) return p + (q - p) * 6 * t;
if(t < 1/2) return q;
if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
}
if(s === 0) {
r = g = b = l; // achromatic
}
else {
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hue2rgb(p, q, h + 1/3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1/3);
}
return { r: r * 255, g: g * 255, b: b * 255 };
}
// `rgbToHsv`
// Converts an RGB color value to HSV
// *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1]
// *Returns:* { h, s, v } in [0,1]
function rgbToHsv(r, g, b) {
r = bound01(r, 255);
g = bound01(g, 255);
b = bound01(b, 255);
var max = mathMax(r, g, b), min = mathMin(r, g, b);
var h, s, v = max;
var d = max - min;
s = max === 0 ? 0 : d / max;
if(max == min) {
h = 0; // achromatic
}
else {
switch(max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return { h: h, s: s, v: v };
}
// `hsvToRgb`
// Converts an HSV color value to RGB.
// *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100]
// *Returns:* { r, g, b } in the set [0, 255]
function hsvToRgb(h, s, v) {
h = bound01(h, 360) * 6;
s = bound01(s, 100);
v = bound01(v, 100);
var i = Math.floor(h),
f = h - i,
p = v * (1 - s),
q = v * (1 - f * s),
t = v * (1 - (1 - f) * s),
mod = i % 6,
r = [v, q, p, p, t, v][mod],
g = [t, v, v, q, p, p][mod],
b = [p, p, t, v, v, q][mod];
return { r: r * 255, g: g * 255, b: b * 255 };
}
// `rgbToHex`
// Converts an RGB color to hex
// Assumes r, g, and b are contained in the set [0, 255]
// Returns a 3 or 6 character hex
function rgbToHex(r, g, b, allow3Char) {
var hex = [
pad2(mathRound(r).toString(16)),
pad2(mathRound(g).toString(16)),
pad2(mathRound(b).toString(16))
];
// Return a 3 character hex if possible
if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {
return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
}
return hex.join("");
}
// `rgbaToHex`
// Converts an RGBA color plus alpha transparency to hex
// Assumes r, g, b are contained in the set [0, 255] and
// a in [0, 1]. Returns a 4 or 8 character rgba hex
function rgbaToHex(r, g, b, a, allow4Char) {
var hex = [
pad2(mathRound(r).toString(16)),
pad2(mathRound(g).toString(16)),
pad2(mathRound(b).toString(16)),
pad2(convertDecimalToHex(a))
];
// Return a 4 character hex if possible
if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) {
return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0);
}
return hex.join("");
}
// `rgbaToArgbHex`
// Converts an RGBA color to an ARGB Hex8 string
// Rarely used, but required for "toFilter()"
function rgbaToArgbHex(r, g, b, a) {
var hex = [
pad2(convertDecimalToHex(a)),
pad2(mathRound(r).toString(16)),
pad2(mathRound(g).toString(16)),
pad2(mathRound(b).toString(16))
];
return hex.join("");
}
// `equals`
// Can be called with any tinycolor input
tinycolor.equals = function (color1, color2) {
if (!color1 || !color2) { return false; }
return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();
};
tinycolor.random = function() {
return tinycolor.fromRatio({
r: mathRandom(),
g: mathRandom(),
b: mathRandom()
});
};
// Modification Functions
// ----------------------
// Thanks to less.js for some of the basics here
// <https://github.com/cloudhead/less.js/blob/master/lib/less/functions.js>
function desaturate(color, amount) {
amount = (amount === 0) ? 0 : (amount || 10);
var hsl = tinycolor(color).toHsl();
hsl.s -= amount / 100;
hsl.s = clamp01(hsl.s);
return tinycolor(hsl);
}
function saturate(color, amount) {
amount = (amount === 0) ? 0 : (amount || 10);
var hsl = tinycolor(color).toHsl();
hsl.s += amount / 100;
hsl.s = clamp01(hsl.s);
return tinycolor(hsl);
}
function greyscale(color) {
return tinycolor(color).desaturate(100);
}
function lighten (color, amount) {
amount = (amount === 0) ? 0 : (amount || 10);
var hsl = tinycolor(color).toHsl();
hsl.l += amount / 100;
hsl.l = clamp01(hsl.l);
return tinycolor(hsl);
}
function brighten(color, amount) {
amount = (amount === 0) ? 0 : (amount || 10);
var rgb = tinycolor(color).toRgb();
rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100))));
rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100))));
rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100))));
return tinycolor(rgb);
}
function darken (color, amount) {
amount = (amount === 0) ? 0 : (amount || 10);
var hsl = tinycolor(color).toHsl();
hsl.l -= amount / 100;
hsl.l = clamp01(hsl.l);
return tinycolor(hsl);
}
// Spin takes a positive or negative amount within [-360, 360] indicating the change of hue.
// Values outside of this range will be wrapped into this range.
function spin(color, amount) {
var hsl = tinycolor(color).toHsl();
var hue = (hsl.h + amount) % 360;
hsl.h = hue < 0 ? 360 + hue : hue;
return tinycolor(hsl);
}
// Combination Functions
// ---------------------
// Thanks to jQuery xColor for some of the ideas behind these
// <https://github.com/infusion/jQuery-xcolor/blob/master/jquery.xcolor.js>
function complement(color) {
var hsl = tinycolor(color).toHsl();
hsl.h = (hsl.h + 180) % 360;
return tinycolor(hsl);
}
function triad(color) {
var hsl = tinycolor(color).toHsl();
var h = hsl.h;
return [
tinycolor(color),
tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }),
tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l })
];
}
function tetrad(color) {
var hsl = tinycolor(color).toHsl();
var h = hsl.h;
return [
tinycolor(color),
tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }),
tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }),
tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l })
];
}
function splitcomplement(color) {
var hsl = tinycolor(color).toHsl();
var h = hsl.h;
return [
tinycolor(color),
tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}),
tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l})
];
}
function analogous(color, results, slices) {
results = results || 6;
slices = slices || 30;
var hsl = tinycolor(color).toHsl();
var part = 360 / slices;
var ret = [tinycolor(color)];
for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) {
hsl.h = (hsl.h + part) % 360;
ret.push(tinycolor(hsl));
}
return ret;
}
function monochromatic(color, results) {
results = results || 6;
var hsv = tinycolor(color).toHsv();
var h = hsv.h, s = hsv.s, v = hsv.v;
var ret = [];
var modification = 1 / results;
while (results--) {
ret.push(tinycolor({ h: h, s: s, v: v}));
v = (v + modification) % 1;
}
return ret;
}
// Utility Functions
// ---------------------
tinycolor.mix = function(color1, color2, amount) {
amount = (amount === 0) ? 0 : (amount || 50);
var rgb1 = tinycolor(color1).toRgb();
var rgb2 = tinycolor(color2).toRgb();
var p = amount / 100;
var rgba = {
r: ((rgb2.r - rgb1.r) * p) + rgb1.r,
g: ((rgb2.g - rgb1.g) * p) + rgb1.g,
b: ((rgb2.b - rgb1.b) * p) + rgb1.b,
a: ((rgb2.a - rgb1.a) * p) + rgb1.a
};
return tinycolor(rgba);
};
// Readability Functions
// ---------------------
// <http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef (WCAG Version 2)
// `contrast`
// Analyze the 2 colors and returns the color contrast defined by (WCAG Version 2)
tinycolor.readability = function(color1, color2) {
var c1 = tinycolor(color1);
var c2 = tinycolor(color2);
return (Math.max(c1.getLuminance(),c2.getLuminance())+0.05) / (Math.min(c1.getLuminance(),c2.getLuminance())+0.05);
};
// `isReadable`
// Ensure that foreground and background color combinations meet WCAG2 guidelines.
// The third argument is an optional Object.
// the 'level' property states 'AA' or 'AAA' - if missing or invalid, it defaults to 'AA';
// the 'size' property states 'large' or 'small' - if missing or invalid, it defaults to 'small'.
// If the entire object is absent, isReadable defaults to {level:"AA",size:"small"}.
// *Example*
// tinycolor.isReadable("#000", "#111") => false
// tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false
tinycolor.isReadable = function(color1, color2, wcag2) {
var readability = tinycolor.readability(color1, color2);
var wcag2Parms, out;
out = false;
wcag2Parms = validateWCAG2Parms(wcag2);
switch (wcag2Parms.level + wcag2Parms.size) {
case "AAsmall":
case "AAAlarge":
out = readability >= 4.5;
break;
case "AAlarge":
out = readability >= 3;
break;
case "AAAsmall":
out = readability >= 7;
break;
}
return out;
};
// `mostReadable`
// Given a base color and a list of possible foreground or background
// colors for that base, returns the most readable color.
// Optionally returns Black or White if the most readable color is unreadable.
// *Example*
// tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255"
// tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString(); // "#ffffff"
// tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3"
// tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff"
tinycolor.mostReadable = function(baseColor, colorList, args) {
var bestColor = null;
var bestScore = 0;
var readability;
var includeFallbackColors, level, size ;
args = args || {};
includeFallbackColors = args.includeFallbackColors ;
level = args.level;
size = args.size;
for (var i= 0; i < colorList.length ; i++) {
readability = tinycolor.readability(baseColor, colorList[i]);
if (readability > bestScore) {
bestScore = readability;
bestColor = tinycolor(colorList[i]);
}
}
if (tinycolor.isReadable(baseColor, bestColor, {"level":level,"size":size}) || !includeFallbackColors) {
return bestColor;
}
else {
args.includeFallbackColors=false;
return tinycolor.mostReadable(baseColor,["#fff", "#000"],args);
}
};
// Big List of Colors
// ------------------
// <http://www.w3.org/TR/css3-color/#svg-color>
var names = tinycolor.names = {
aliceblue: "f0f8ff",
antiquewhite: "faebd7",
aqua: "0ff",
aquamarine: "7fffd4",
azure: "f0ffff",
beige: "f5f5dc",
bisque: "ffe4c4",
black: "000",
blanchedalmond: "ffebcd",
blue: "00f",
blueviolet: "8a2be2",
brown: "a52a2a",
burlywood: "deb887",
burntsienna: "ea7e5d",
cadetblue: "5f9ea0",
chartreuse: "7fff00",
chocolate: "d2691e",
coral: "ff7f50",
cornflowerblue: "6495ed",
cornsilk: "fff8dc",
crimson: "dc143c",
cyan: "0ff",
darkblue: "00008b",
darkcyan: "008b8b",
darkgoldenrod: "b8860b",
darkgray: "a9a9a9",
darkgreen: "006400",
darkgrey: "a9a9a9",
darkkhaki: "bdb76b",
darkmagenta: "8b008b",
darkolivegreen: "556b2f",
darkorange: "ff8c00",
darkorchid: "9932cc",
darkred: "8b0000",
darksalmon: "e9967a",
darkseagreen: "8fbc8f",
darkslateblue: "483d8b",
darkslategray: "2f4f4f",
darkslategrey: "2f4f4f",
darkturquoise: "00ced1",
darkviolet: "9400d3",
deeppink: "ff1493",
deepskyblue: "00bfff",
dimgray: "696969",
dimgrey: "696969",
dodgerblue: "1e90ff",
firebrick: "b22222",
floralwhite: "fffaf0",
forestgreen: "228b22",
fuchsia: "f0f",
gainsboro: "dcdcdc",
ghostwhite: "f8f8ff",
gold: "ffd700",
goldenrod: "daa520",
gray: "808080",
green: "008000",
greenyellow: "adff2f",
grey: "808080",
honeydew: "f0fff0",
hotpink: "ff69b4",
indianred: "cd5c5c",
indigo: "4b0082",
ivory: "fffff0",
khaki: "f0e68c",
lavender: "e6e6fa",
lavenderblush: "fff0f5",
lawngreen: "7cfc00",
lemonchiffon: "fffacd",
lightblue: "add8e6",
lightcoral: "f08080",
lightcyan: "e0ffff",
lightgoldenrodyellow: "fafad2",
lightgray: "d3d3d3",
lightgreen: "90ee90",
lightgrey: "d3d3d3",
lightpink: "ffb6c1",
lightsalmon: "ffa07a",
lightseagreen: "20b2aa",
lightskyblue: "87cefa",
lightslategray: "789",
lightslategrey: "789",
lightsteelblue: "b0c4de",
lightyellow: "ffffe0",
lime: "0f0",
limegreen: "32cd32",
linen: "faf0e6",
magenta: "f0f",
maroon: "800000",
mediumaquamarine: "66cdaa",
mediumblue: "0000cd",
mediumorchid: "ba55d3",
mediumpurple: "9370db",
mediumseagreen: "3cb371",
mediumslateblue: "7b68ee",
mediumspringgreen: "00fa9a",
mediumturquoise: "48d1cc",
mediumvioletred: "c71585",
midnightblue: "191970",
mintcream: "f5fffa",
mistyrose: "ffe4e1",
moccasin: "ffe4b5",
navajowhite: "ffdead",
navy: "000080",
oldlace: "fdf5e6",
olive: "808000",
olivedrab: "6b8e23",
orange: "ffa500",
orangered: "ff4500",
orchid: "da70d6",
palegoldenrod: "eee8aa",
palegreen: "98fb98",
paleturquoise: "afeeee",
palevioletred: "db7093",
papayawhip: "ffefd5",
peachpuff: "ffdab9",
peru: "cd853f",
pink: "ffc0cb",
plum: "dda0dd",
powderblue: "b0e0e6",
purple: "800080",
rebeccapurple: "663399",
red: "f00",
rosybrown: "bc8f8f",
royalblue: "4169e1",
saddlebrown: "8b4513",
salmon: "fa8072",
sandybrown: "f4a460",
seagreen: "2e8b57",
seashell: "fff5ee",
sienna: "a0522d",
silver: "c0c0c0",
skyblue: "87ceeb",
slateblue: "6a5acd",
slategray: "708090",
slategrey: "708090",
snow: "fffafa",
springgreen: "00ff7f",
steelblue: "4682b4",
tan: "d2b48c",
teal: "008080",
thistle: "d8bfd8",
tomato: "ff6347",
turquoise: "40e0d0",
violet: "ee82ee",
wheat: "f5deb3",
white: "fff",
whitesmoke: "f5f5f5",
yellow: "ff0",
yellowgreen: "9acd32"
};
// Make it easy to access colors via `hexNames[hex]`
var hexNames = tinycolor.hexNames = flip(names);
// Utilities
// ---------
// `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }`
function flip(o) {
var flipped = { };
for (var i in o) {
if (o.hasOwnProperty(i)) {
flipped[o[i]] = i;
}
}
return flipped;
}
// Return a valid alpha value [0,1] with all invalid values being set to 1
function boundAlpha(a) {
a = parseFloat(a);
if (isNaN(a) || a < 0 || a > 1) {
a = 1;
}
return a;
}
// Take input from [0, n] and return it as [0, 1]
function bound01(n, max) {
if (isOnePointZero(n)) { n = "100%"; }
var processPercent = isPercentage(n);
n = mathMin(max, mathMax(0, parseFloat(n)));
// Automatically convert percentage into number
if (processPercent) {
n = parseInt(n * max, 10) / 100;
}
// Handle floating point rounding errors
if ((Math.abs(n - max) < 0.000001)) {
return 1;
}
// Convert into [0, 1] range if it isn't already
return (n % max) / parseFloat(max);
}
// Force a number between 0 and 1
function clamp01(val) {
return mathMin(1, mathMax(0, val));
}
// Parse a base-16 hex value into a base-10 integer
function parseIntFromHex(val) {
return parseInt(val, 16);
}
// Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1
// <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0>
function isOnePointZero(n) {
return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1;
}
// Check to see if string passed in is a percentage
function isPercentage(n) {
return typeof n === "string" && n.indexOf('%') != -1;
}
// Force a hex value to have 2 characters
function pad2(c) {
return c.length == 1 ? '0' + c : '' + c;
}
// Replace a decimal with it's percentage value
function convertToPercentage(n) {
if (n <= 1) {
n = (n * 100) + "%";
}
return n;
}
// Converts a decimal to a hex value
function convertDecimalToHex(d) {
return Math.round(parseFloat(d) * 255).toString(16);
}
// Converts a hex value to a decimal
function convertHexToDecimal(h) {
return (parseIntFromHex(h) / 255);
}
var matchers = (function() {
// <http://www.w3.org/TR/css3-values/#integers>
var CSS_INTEGER = "[-\\+]?\\d+%?";
// <http://www.w3.org/TR/css3-values/#number-value>
var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?";
// Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome.
var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")";
// Actual matching.
// Parentheses and commas are optional, but not required.
// Whitespace can take the place of commas or opening paren
var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
return {
CSS_UNIT: new RegExp(CSS_UNIT),
rgb: new RegExp("rgb" + PERMISSIVE_MATCH3),
rgba: new RegExp("rgba" + PERMISSIVE_MATCH4),
hsl: new RegExp("hsl" + PERMISSIVE_MATCH3),
hsla: new RegExp("hsla" + PERMISSIVE_MATCH4),
hsv: new RegExp("hsv" + PERMISSIVE_MATCH3),
hsva: new RegExp("hsva" + PERMISSIVE_MATCH4),
hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/
};
})();
// `isValidCSSUnit`
// Take in a single string / number and check to see if it looks like a CSS unit
// (see `matchers` above for definition).
function isValidCSSUnit(color) {
return !!matchers.CSS_UNIT.exec(color);
}
// `stringInputToObject`
// Permissive string parsing. Take in a number of formats, and output an object
// based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}`
function stringInputToObject(color) {
color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase();
var named = false;
if (names[color]) {
color = names[color];
named = true;
}
else if (color == 'transparent') {
return { r: 0, g: 0, b: 0, a: 0, format: "name" };
}
// Try to match string input using regular expressions.
// Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360]
// Just return an object and let the conversion functions handle that.
// This way the result will be the same whether the tinycolor is initialized with string or object.
var match;
if ((match = matchers.rgb.exec(color))) {
return { r: match[1], g: match[2], b: match[3] };
}
if ((match = matchers.rgba.exec(color))) {
return { r: match[1], g: match[2], b: match[3], a: match[4] };
}
if ((match = matchers.hsl.exec(color))) {
return { h: match[1], s: match[2], l: match[3] };
}
if ((match = matchers.hsla.exec(color))) {
return { h: match[1], s: match[2], l: match[3], a: match[4] };
}
if ((match = matchers.hsv.exec(color))) {
return { h: match[1], s: match[2], v: match[3] };
}
if ((match = matchers.hsva.exec(color))) {
return { h: match[1], s: match[2], v: match[3], a: match[4] };
}
if ((match = matchers.hex8.exec(color))) {
return {
r: parseIntFromHex(match[1]),
g: parseIntFromHex(match[2]),
b: parseIntFromHex(match[3]),
a: convertHexToDecimal(match[4]),
format: named ? "name" : "hex8"
};
}
if ((match = matchers.hex6.exec(color))) {
return {
r: parseIntFromHex(match[1]),
g: parseIntFromHex(match[2]),
b: parseIntFromHex(match[3]),
format: named ? "name" : "hex"
};
}
if ((match = matchers.hex4.exec(color))) {
return {
r: parseIntFromHex(match[1] + '' + match[1]),
g: parseIntFromHex(match[2] + '' + match[2]),
b: parseIntFromHex(match[3] + '' + match[3]),
a: convertHexToDecimal(match[4] + '' + match[4]),
format: named ? "name" : "hex8"
};
}
if ((match = matchers.hex3.exec(color))) {
return {
r: parseIntFromHex(match[1] + '' + match[1]),
g: parseIntFromHex(match[2] + '' + match[2]),
b: parseIntFromHex(match[3] + '' + match[3]),
format: named ? "name" : "hex"
};
}
return false;
}
function validateWCAG2Parms(parms) {
// return valid WCAG2 parms for isReadable.
// If input parms are invalid, return {"level":"AA", "size":"small"}
var level, size;
parms = parms || {"level":"AA", "size":"small"};
level = (parms.level || "AA").toUpperCase();
size = (parms.size || "small").toLowerCase();
if (level !== "AA" && level !== "AAA") {
level = "AA";
}
if (size !== "small" && size !== "large") {
size = "small";
}
return {"level":level, "size":size};
}
// Node: Export function
if ( true && module.exports) {
module.exports = tinycolor;
}
// AMD/requirejs: Define the module
else if (true) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {return tinycolor;}).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
// Browser: Expose to window
else {}
})(Math);
/***/ }),
/***/ "a7Wl":
/*!***********************************************************************!*\
!*** ./node_modules/@ant-design/icons-svg/lib/asn/CaretUpOutlined.js ***!
\***********************************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// This icon file is generated automatically.
Object.defineProperty(exports, "__esModule", { value: true });
var CaretUpOutlined = { "icon": { "tag": "svg", "attrs": { "viewBox": "0 0 1024 1024", "focusable": "false" }, "children": [{ "tag": "path", "attrs": { "d": "M858.9 689L530.5 308.2c-9.4-10.9-27.5-10.9-37 0L165.1 689c-12.2 14.2-1.2 35 18.5 35h656.8c19.7 0 30.7-20.8 18.5-35z" } }] }, "name": "caret-up", "theme": "outlined" };
exports.default = CaretUpOutlined;
/***/ }),
/***/ "bE4E":
/*!*******************************************************!*\
!*** ./node_modules/antd/es/divider/style/index.less ***!
\*******************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/***/ "bE4q":
/*!**************************************************************!*\
!*** ./node_modules/antd/es/breadcrumb/index.js + 3 modules ***!
\**************************************************************/
/*! exports provided: default */
/*! exports used: default */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/DownOutlined.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/defineProperty.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/extends.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/toConsumableArray.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/_util/devWarning.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/_util/reactNode.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/config-provider/context.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/dropdown/dropdown.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/menu/index.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/react/index.js (<- Module is not an ECMAScript module) */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/extends.js
var helpers_extends = __webpack_require__("pVnL");
var extends_default = /*#__PURE__*/__webpack_require__.n(helpers_extends);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/defineProperty.js
var defineProperty = __webpack_require__("lSNA");
var defineProperty_default = /*#__PURE__*/__webpack_require__.n(defineProperty);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/toConsumableArray.js
var toConsumableArray = __webpack_require__("RIqP");
var toConsumableArray_default = /*#__PURE__*/__webpack_require__.n(toConsumableArray);
// EXTERNAL MODULE: ./node_modules/react/index.js
var react = __webpack_require__("q1tI");
// 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/@ant-design/icons/DownOutlined.js
var DownOutlined = __webpack_require__("HQEm");
var DownOutlined_default = /*#__PURE__*/__webpack_require__.n(DownOutlined);
// EXTERNAL MODULE: ./node_modules/antd/es/dropdown/dropdown.js + 1 modules
var dropdown = __webpack_require__("XBQK");
// EXTERNAL MODULE: ./node_modules/antd/es/config-provider/context.js + 1 modules
var context = __webpack_require__("H84U");
// CONCATENATED MODULE: ./node_modules/antd/es/breadcrumb/BreadcrumbItem.js
var __rest = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
var BreadcrumbItem_BreadcrumbItem = function BreadcrumbItem(_a) {
var customizePrefixCls = _a.prefixCls,
_a$separator = _a.separator,
separator = _a$separator === void 0 ? '/' : _a$separator,
children = _a.children,
overlay = _a.overlay,
dropdownProps = _a.dropdownProps,
restProps = __rest(_a, ["prefixCls", "separator", "children", "overlay", "dropdownProps"]);
var _React$useContext = react["useContext"](context["b" /* ConfigContext */]),
getPrefixCls = _React$useContext.getPrefixCls;
var prefixCls = getPrefixCls('breadcrumb', customizePrefixCls);
/**
* if overlay is have
* Wrap a DropDown
*/
var renderBreadcrumbNode = function renderBreadcrumbNode(breadcrumbItem) {
if (overlay) {
return /*#__PURE__*/react["createElement"](dropdown["a" /* default */], extends_default()({
overlay: overlay,
placement: "bottomCenter"
}, dropdownProps), /*#__PURE__*/react["createElement"]("span", {
className: "".concat(prefixCls, "-overlay-link")
}, breadcrumbItem, /*#__PURE__*/react["createElement"](DownOutlined_default.a, null)));
}
return breadcrumbItem;
};
var link;
if ('href' in restProps) {
link = /*#__PURE__*/react["createElement"]("a", extends_default()({
className: "".concat(prefixCls, "-link")
}, restProps), children);
} else {
link = /*#__PURE__*/react["createElement"]("span", extends_default()({
className: "".concat(prefixCls, "-link")
}, restProps), children);
} // wrap to dropDown
link = renderBreadcrumbNode(link);
if (children) {
return /*#__PURE__*/react["createElement"]("span", null, link, separator && separator !== '' && /*#__PURE__*/react["createElement"]("span", {
className: "".concat(prefixCls, "-separator")
}, separator));
}
return null;
};
BreadcrumbItem_BreadcrumbItem.__ANT_BREADCRUMB_ITEM = true;
/* harmony default export */ var breadcrumb_BreadcrumbItem = (BreadcrumbItem_BreadcrumbItem);
// CONCATENATED MODULE: ./node_modules/antd/es/breadcrumb/BreadcrumbSeparator.js
var BreadcrumbSeparator_BreadcrumbSeparator = function BreadcrumbSeparator(_ref) {
var children = _ref.children;
var _React$useContext = react["useContext"](context["b" /* ConfigContext */]),
getPrefixCls = _React$useContext.getPrefixCls;
var prefixCls = getPrefixCls('breadcrumb');
return /*#__PURE__*/react["createElement"]("span", {
className: "".concat(prefixCls, "-separator")
}, children || '/');
};
BreadcrumbSeparator_BreadcrumbSeparator.__ANT_BREADCRUMB_SEPARATOR = true;
/* harmony default export */ var breadcrumb_BreadcrumbSeparator = (BreadcrumbSeparator_BreadcrumbSeparator);
// EXTERNAL MODULE: ./node_modules/antd/es/menu/index.js + 16 modules
var menu = __webpack_require__("BvKs");
// EXTERNAL MODULE: ./node_modules/antd/es/_util/devWarning.js
var devWarning = __webpack_require__("uaoM");
// EXTERNAL MODULE: ./node_modules/antd/es/_util/reactNode.js
var reactNode = __webpack_require__("0n0R");
// CONCATENATED MODULE: ./node_modules/antd/es/breadcrumb/Breadcrumb.js
var Breadcrumb_rest = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
function getBreadcrumbName(route, params) {
if (!route.breadcrumbName) {
return null;
}
var paramsKeys = Object.keys(params).join('|');
var name = route.breadcrumbName.replace(new RegExp(":(".concat(paramsKeys, ")"), 'g'), function (replacement, key) {
return params[key] || replacement;
});
return name;
}
function defaultItemRender(route, params, routes, paths) {
var isLastItem = routes.indexOf(route) === routes.length - 1;
var name = getBreadcrumbName(route, params);
return isLastItem ? /*#__PURE__*/react["createElement"]("span", null, name) : /*#__PURE__*/react["createElement"]("a", {
href: "#/".concat(paths.join('/'))
}, name);
}
var getPath = function getPath(path, params) {
path = (path || '').replace(/^\//, '');
Object.keys(params).forEach(function (key) {
path = path.replace(":".concat(key), params[key]);
});
return path;
};
var Breadcrumb_addChildPath = function addChildPath(paths) {
var childPath = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var params = arguments.length > 2 ? arguments[2] : undefined;
var originalPaths = toConsumableArray_default()(paths);
var path = getPath(childPath, params);
if (path) {
originalPaths.push(path);
}
return originalPaths;
};
var Breadcrumb_Breadcrumb = function Breadcrumb(_a) {
var customizePrefixCls = _a.prefixCls,
_a$separator = _a.separator,
separator = _a$separator === void 0 ? '/' : _a$separator,
style = _a.style,
className = _a.className,
routes = _a.routes,
children = _a.children,
_a$itemRender = _a.itemRender,
itemRender = _a$itemRender === void 0 ? defaultItemRender : _a$itemRender,
_a$params = _a.params,
params = _a$params === void 0 ? {} : _a$params,
restProps = Breadcrumb_rest(_a, ["prefixCls", "separator", "style", "className", "routes", "children", "itemRender", "params"]);
var _React$useContext = react["useContext"](context["b" /* ConfigContext */]),
getPrefixCls = _React$useContext.getPrefixCls,
direction = _React$useContext.direction;
var crumbs;
var prefixCls = getPrefixCls('breadcrumb', customizePrefixCls);
if (routes && routes.length > 0) {
// generated by route
var paths = [];
crumbs = routes.map(function (route) {
var path = getPath(route.path, params);
if (path) {
paths.push(path);
} // generated overlay by route.children
var overlay;
if (route.children && route.children.length) {
overlay = /*#__PURE__*/react["createElement"](menu["a" /* default */], null, route.children.map(function (child) {
return /*#__PURE__*/react["createElement"](menu["a" /* default */].Item, {
key: child.path || child.breadcrumbName
}, itemRender(child, params, routes, Breadcrumb_addChildPath(paths, child.path, params)));
}));
}
return /*#__PURE__*/react["createElement"](breadcrumb_BreadcrumbItem, {
overlay: overlay,
separator: separator,
key: path || route.breadcrumbName
}, itemRender(route, params, routes, paths));
});
} else if (children) {
crumbs = Object(toArray["a" /* default */])(children).map(function (element, index) {
if (!element) {
return element;
}
Object(devWarning["a" /* default */])(element.type && (element.type.__ANT_BREADCRUMB_ITEM === true || element.type.__ANT_BREADCRUMB_SEPARATOR === true), 'Breadcrumb', "Only accepts Breadcrumb.Item and Breadcrumb.Separator as it's children");
return Object(reactNode["a" /* cloneElement */])(element, {
separator: separator,
key: index
});
});
}
var breadcrumbClassName = classnames_default()(className, prefixCls, defineProperty_default()({}, "".concat(prefixCls, "-rtl"), direction === 'rtl'));
return /*#__PURE__*/react["createElement"]("div", extends_default()({
className: breadcrumbClassName,
style: style
}, restProps), crumbs);
};
Breadcrumb_Breadcrumb.Item = breadcrumb_BreadcrumbItem;
Breadcrumb_Breadcrumb.Separator = breadcrumb_BreadcrumbSeparator;
/* harmony default export */ var breadcrumb_Breadcrumb = (Breadcrumb_Breadcrumb);
// CONCATENATED MODULE: ./node_modules/antd/es/breadcrumb/index.js
/* harmony default export */ var breadcrumb = __webpack_exports__["a"] = (breadcrumb_Breadcrumb);
/***/ }),
/***/ "bQjk":
/*!**********************************************!*\
!*** ./node_modules/crypto-js/format-hex.js ***!
\**********************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory, undef) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"), __webpack_require__(/*! ./cipher-core */ "OLod"));
}
else {}
}(this, function (CryptoJS) {
(function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var CipherParams = C_lib.CipherParams;
var C_enc = C.enc;
var Hex = C_enc.Hex;
var C_format = C.format;
var HexFormatter = C_format.Hex = {
/**
* Converts the ciphertext of a cipher params object to a hexadecimally encoded string.
*
* @param {CipherParams} cipherParams The cipher params object.
*
* @return {string} The hexadecimally encoded string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.format.Hex.stringify(cipherParams);
*/
stringify: function (cipherParams) {
return cipherParams.ciphertext.toString(Hex);
},
/**
* Converts a hexadecimally encoded ciphertext string to a cipher params object.
*
* @param {string} input The hexadecimally encoded string.
*
* @return {CipherParams} The cipher params object.
*
* @static
*
* @example
*
* var cipherParams = CryptoJS.format.Hex.parse(hexString);
*/
parse: function (input) {
var ciphertext = Hex.parse(input);
return CipherParams.create({ ciphertext: ciphertext });
}
};
}());
return CryptoJS.format.Hex;
}));
/***/ }),
/***/ "bUJZ":
/*!**************************************************!*\
!*** ./src/assets/images/cert/zhiyerenzheng.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,iVBORw0KGgoAAAANSUhEUgAAACQAAAAkCAYAAADhAJiYAAAAAXNSR0IArs4c6QAABq1JREFUWAmVWGuIVVUU/vaZ2zjjOC9TwzFtwAjKHlJBNj4IYgJp/hghIWEE/ahAlCypqB8JoSiRJljQw6KoEGz6oQmNvxqdoB9hailZoZbj2xlndHzMvWf3rX3OOnefc888XLDv2nvttdda+1tr73PONbhJsnZdM64NPsll7YCZBYQtQMAmFPayz2ZPcNCFmvpdxrzR56bG+WPGqQc79PoShOEKGLMQ1hbcOstfsSA8j4wpcrIbQbDFTFzfmaeSlY0ZkB14bT5suIFBtGUXMzj6YzTChbQvXMifN+ghemtMw8Z90WT+74gBWbu9Cv0979HJyvyllI6JkKcjRkQ/MJvR1LbamKUlEWUpNyDbt6oJpeJ2GmCdeDQaAp7ayN14B4b1VVVYapo39Wd1KwJywVy/Tnjt3VnlcsHosixEIleZrNa+cCF/3hzGhOq2bFBq2am7NJ3q2l1GZgSDQTMw9U2gqsmty/0pXQTOrmVMQ950xp4xXZjevthPX3RadMl/u1kzmTTpnM/Dy9xsDZ2FwBXWqG7L+aPJukepHQBF6oE6I5Ex7RCfwCpVUVOwx5/jabJ7dSKX+xucvBxoeBw4vRG4djBSl1M1kcFMfRHo5ym/9H3aTLYGNYVBsMDc8YU7fdxGTMXiBhR5bZTYhOe1kAdD5MIv/RgtrH+MY6IgTebqGaQl799DW7G+8LwmdpxOaYOG4RCyfz3DS89+p8Jx8xlvEZF7GcyN8pKgGhjkmTj9QVk2nl5gnjJ3ftsZ1VBxeIU7EAqhFkUWYv+iEydnPgcmd7BTJaOIBJ0LOyKkVZZw2b/mXbrsJzaxgpJOY48va8bg0FkO0gVOQQUli+PS8w1WKN+0oIj6idMKGBjsYNBRMBq8cKHMhlI7ijSAFhZwze06Aq6fBE5+FI/HMJi2z1iGOgoYLrVrhnIdll1VBjihFZjCB39xgCm6yszVAZMeAM7/AFz9hyvTHsvpinecjTcotRd4Yma6QMRxxXqu0DS5eSpommRc/6D8Akff5n10GGheBMxmodc9xMI+yomsx4yDzJAHa6YE1JIEpM6EC2UXRNLyb8PDRGeQzhmMXID9vzAGHuVGBtT7VY6BMQJkARR4d7REOyn7GVcvqGV6eOQv/sR0xce+xNQN/k7k7qEJ3uSlK2lTFRvOIA7DgMJhCytQCGV3EElzfxtZKwHPwsWf6ZioOOJ6GTfcz6Dm8vgz2MRmrJJiGX/G2IDGTrnbWW5od3PGXG9R5dmbtukR+qLBCxIQ17jGwM67JwAg8ypL5lVPOfUTHdc/VWBAvTR8VypwHWhBCxfyIW+eB1z+k6fpDCfieWEDR3j0z/HC5LxsQmQChKMKRMo2Zd6glwgVTyTPIjEgz6QEDdmJ7oJ9N0deMwuonR6hoTIfBUFpwjTqtMYIxIiornBp7rkY8+jZeSLgK8SeCDZxGDsXLs0tiLn0xalw2b3Que5IpvpuQ9QXuZCipPPF4dguud/XeRt2FXAj3IkgLDIdlY+ODMIJ/LfOB4b5rnPhV0LOADVlWsBn99Ix5VOo9/enLrb8H80nuXyh1Jldgek42Me0dJfTxB1qyiRy3bXfb+JxL/JIy9F3utxxSZrok+MWzjPgxjmxTG0ySKcjvKJ1m4UH+6L3oVK4JUehcpELioYOrWcdsUbmfRY9LrQmxEmBr7XztgHV5KKXciyBSSAaoM8ZA0kwc2R3tO4j4m1JWkTqIRopebLZy4G57/De2Q90PxshVt0ILPqGyPD74MBaPlIYmNoY3V6PefoY8+tefIUJhWtShSxoZIval4mz395l4fICbCNS1VOABV/GwRCZIx9HaOhhSJDxEYr7hr5jShCSsf16xiaYcGVyb+juEq2sgFU/5xXgvlfp/BrTV8M0vc+2Ue2nOdVTiLnZYLNZdnKVKkY1pKNC22reD10OKb+Ik5x7hSvFK7s/wNfhQ5uiYP7YCuxfV64Rh06MtI+22JbGYw7x6VGyd5XZztYmDPKl2OZ9KKpWDq+9Lb61/bkcRBUiww/F+vo2s+RYf3aFP3Z9u62pieHzU9q2pzAe7VHiVo4SgD8vH4gwS83z/algRCWdMreIqqJY98Ripm9z6phWpCC+9v1jL3096tr350GbtJ0XjLivSFkcU8LsJ7Xz+e6V/3dMRZFmBD6ixvRw+2vMC1f5oBuZxgxIl9oPq5ewCOVzaSFl0WPGd+gUMwEh/sPK8A+rl250qq3R+LgDUiN2a2Mzwsv8GJP6sjMp5xuna6LSGzXzL8HvQjBpp3n5Up9MjJf+B5WVB7lfjXHfAAAAAElFTkSuQmCC"
/***/ }),
/***/ "c5Ni":
/*!******************************************************!*\
!*** ./node_modules/codemirror/theme/blackboard.css ***!
\******************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/***/ "cRFk":
/*!**************************************************!*\
!*** ./src/assets/images/RepositoryNoneData.png ***!
\**************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/RepositoryNoneData.828085a8.png";
/***/ }),
/***/ "cZFH":
/*!*******************************************************************!*\
!*** ./node_modules/@ant-design/react-slick/lib/default-props.js ***!
\*******************************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "TqRt");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _react = _interopRequireDefault(__webpack_require__(/*! react */ "q1tI"));
var defaultProps = {
accessibility: true,
adaptiveHeight: false,
afterChange: null,
appendDots: function appendDots(dots) {
return /*#__PURE__*/_react["default"].createElement("ul", {
style: {
display: "block"
}
}, dots);
},
arrows: true,
autoplay: false,
autoplaySpeed: 3000,
beforeChange: null,
centerMode: false,
centerPadding: "50px",
className: "",
cssEase: "ease",
customPaging: function customPaging(i) {
return /*#__PURE__*/_react["default"].createElement("button", null, i + 1);
},
dots: false,
dotsClass: "slick-dots",
draggable: true,
easing: "linear",
edgeFriction: 0.35,
fade: false,
focusOnSelect: false,
infinite: true,
initialSlide: 0,
lazyLoad: null,
nextArrow: null,
onEdge: null,
onInit: null,
onLazyLoadError: null,
onReInit: null,
pauseOnDotsHover: false,
pauseOnFocus: false,
pauseOnHover: true,
prevArrow: null,
responsive: null,
rows: 1,
rtl: false,
slide: "div",
slidesPerRow: 1,
slidesToScroll: 1,
slidesToShow: 1,
speed: 500,
swipe: true,
swipeEvent: null,
swipeToSlide: false,
touchMove: true,
touchThreshold: 5,
useCSS: true,
useTransform: true,
variableWidth: false,
vertical: false,
waitForAnimate: true
};
var _default = defaultProps;
exports["default"] = _default;
/***/ }),
/***/ "coqV":
/*!**********************************************************!*\
!*** ./node_modules/@ant-design/react-slick/lib/dots.js ***!
\**********************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "TqRt");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Dots = void 0;
var _objectSpread2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/objectSpread2 */ "3tO9"));
var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "lwsE"));
var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "W8MJ"));
var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "7W2i"));
var _createSuper2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createSuper */ "LQ03"));
var _react = _interopRequireDefault(__webpack_require__(/*! react */ "q1tI"));
var _classnames = _interopRequireDefault(__webpack_require__(/*! classnames */ "TSYQ"));
var _innerSliderUtils = __webpack_require__(/*! ./utils/innerSliderUtils */ "3K4p");
var getDotCount = function getDotCount(spec) {
var dots;
if (spec.infinite) {
dots = Math.ceil(spec.slideCount / spec.slidesToScroll);
} else {
dots = Math.ceil((spec.slideCount - spec.slidesToShow) / spec.slidesToScroll) + 1;
}
return dots;
};
var Dots = /*#__PURE__*/function (_React$PureComponent) {
(0, _inherits2["default"])(Dots, _React$PureComponent);
var _super = (0, _createSuper2["default"])(Dots);
function Dots() {
(0, _classCallCheck2["default"])(this, Dots);
return _super.apply(this, arguments);
}
(0, _createClass2["default"])(Dots, [{
key: "clickHandler",
value: function clickHandler(options, e) {
// In Autoplay the focus stays on clicked button even after transition
// to next slide. That only goes away by click somewhere outside
e.preventDefault();
this.props.clickHandler(options);
}
}, {
key: "render",
value: function render() {
var _this$props = this.props,
onMouseEnter = _this$props.onMouseEnter,
onMouseOver = _this$props.onMouseOver,
onMouseLeave = _this$props.onMouseLeave,
infinite = _this$props.infinite,
slidesToScroll = _this$props.slidesToScroll,
slidesToShow = _this$props.slidesToShow,
slideCount = _this$props.slideCount,
currentSlide = _this$props.currentSlide;
var dotCount = getDotCount({
slideCount: slideCount,
slidesToScroll: slidesToScroll,
slidesToShow: slidesToShow,
infinite: infinite
});
var mouseEvents = {
onMouseEnter: onMouseEnter,
onMouseOver: onMouseOver,
onMouseLeave: onMouseLeave
};
var dots = [];
for (var i = 0; i < dotCount; i++) {
var _rightBound = (i + 1) * slidesToScroll - 1;
var rightBound = infinite ? _rightBound : (0, _innerSliderUtils.clamp)(_rightBound, 0, slideCount - 1);
var _leftBound = rightBound - (slidesToScroll - 1);
var leftBound = infinite ? _leftBound : (0, _innerSliderUtils.clamp)(_leftBound, 0, slideCount - 1);
var className = (0, _classnames["default"])({
"slick-active": infinite ? currentSlide >= leftBound && currentSlide <= rightBound : currentSlide === leftBound
});
var dotOptions = {
message: "dots",
index: i,
slidesToScroll: slidesToScroll,
currentSlide: currentSlide
};
var onClick = this.clickHandler.bind(this, dotOptions);
dots = dots.concat( /*#__PURE__*/_react["default"].createElement("li", {
key: i,
className: className
}, /*#__PURE__*/_react["default"].cloneElement(this.props.customPaging(i), {
onClick: onClick
})));
}
return /*#__PURE__*/_react["default"].cloneElement(this.props.appendDots(dots), (0, _objectSpread2["default"])({
className: this.props.dotsClass
}, mouseEvents));
}
}]);
return Dots;
}(_react["default"].PureComponent);
exports.Dots = Dots;
/***/ }),
/***/ "csWT":
/*!********************************************!*\
!*** ./src/assets/images/icons/choose.svg ***!
\********************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/choose.4ad1045f.svg";
/***/ }),
/***/ "cv67":
/*!***************************************!*\
!*** ./node_modules/crypto-js/md5.js ***!
\***************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"));
}
else {}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Constants table
var T = [];
// Compute constants
(function () {
for (var i = 0; i < 64; i++) {
T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0;
}
}());
/**
* MD5 hash algorithm.
*/
var MD5 = C_algo.MD5 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476
]);
},
_doProcessBlock: function (M, offset) {
// Swap endian
for (var i = 0; i < 16; i++) {
// Shortcuts
var offset_i = offset + i;
var M_offset_i = M[offset_i];
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Shortcuts
var H = this._hash.words;
var M_offset_0 = M[offset + 0];
var M_offset_1 = M[offset + 1];
var M_offset_2 = M[offset + 2];
var M_offset_3 = M[offset + 3];
var M_offset_4 = M[offset + 4];
var M_offset_5 = M[offset + 5];
var M_offset_6 = M[offset + 6];
var M_offset_7 = M[offset + 7];
var M_offset_8 = M[offset + 8];
var M_offset_9 = M[offset + 9];
var M_offset_10 = M[offset + 10];
var M_offset_11 = M[offset + 11];
var M_offset_12 = M[offset + 12];
var M_offset_13 = M[offset + 13];
var M_offset_14 = M[offset + 14];
var M_offset_15 = M[offset + 15];
// Working varialbes
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
// Computation
a = FF(a, b, c, d, M_offset_0, 7, T[0]);
d = FF(d, a, b, c, M_offset_1, 12, T[1]);
c = FF(c, d, a, b, M_offset_2, 17, T[2]);
b = FF(b, c, d, a, M_offset_3, 22, T[3]);
a = FF(a, b, c, d, M_offset_4, 7, T[4]);
d = FF(d, a, b, c, M_offset_5, 12, T[5]);
c = FF(c, d, a, b, M_offset_6, 17, T[6]);
b = FF(b, c, d, a, M_offset_7, 22, T[7]);
a = FF(a, b, c, d, M_offset_8, 7, T[8]);
d = FF(d, a, b, c, M_offset_9, 12, T[9]);
c = FF(c, d, a, b, M_offset_10, 17, T[10]);
b = FF(b, c, d, a, M_offset_11, 22, T[11]);
a = FF(a, b, c, d, M_offset_12, 7, T[12]);
d = FF(d, a, b, c, M_offset_13, 12, T[13]);
c = FF(c, d, a, b, M_offset_14, 17, T[14]);
b = FF(b, c, d, a, M_offset_15, 22, T[15]);
a = GG(a, b, c, d, M_offset_1, 5, T[16]);
d = GG(d, a, b, c, M_offset_6, 9, T[17]);
c = GG(c, d, a, b, M_offset_11, 14, T[18]);
b = GG(b, c, d, a, M_offset_0, 20, T[19]);
a = GG(a, b, c, d, M_offset_5, 5, T[20]);
d = GG(d, a, b, c, M_offset_10, 9, T[21]);
c = GG(c, d, a, b, M_offset_15, 14, T[22]);
b = GG(b, c, d, a, M_offset_4, 20, T[23]);
a = GG(a, b, c, d, M_offset_9, 5, T[24]);
d = GG(d, a, b, c, M_offset_14, 9, T[25]);
c = GG(c, d, a, b, M_offset_3, 14, T[26]);
b = GG(b, c, d, a, M_offset_8, 20, T[27]);
a = GG(a, b, c, d, M_offset_13, 5, T[28]);
d = GG(d, a, b, c, M_offset_2, 9, T[29]);
c = GG(c, d, a, b, M_offset_7, 14, T[30]);
b = GG(b, c, d, a, M_offset_12, 20, T[31]);
a = HH(a, b, c, d, M_offset_5, 4, T[32]);
d = HH(d, a, b, c, M_offset_8, 11, T[33]);
c = HH(c, d, a, b, M_offset_11, 16, T[34]);
b = HH(b, c, d, a, M_offset_14, 23, T[35]);
a = HH(a, b, c, d, M_offset_1, 4, T[36]);
d = HH(d, a, b, c, M_offset_4, 11, T[37]);
c = HH(c, d, a, b, M_offset_7, 16, T[38]);
b = HH(b, c, d, a, M_offset_10, 23, T[39]);
a = HH(a, b, c, d, M_offset_13, 4, T[40]);
d = HH(d, a, b, c, M_offset_0, 11, T[41]);
c = HH(c, d, a, b, M_offset_3, 16, T[42]);
b = HH(b, c, d, a, M_offset_6, 23, T[43]);
a = HH(a, b, c, d, M_offset_9, 4, T[44]);
d = HH(d, a, b, c, M_offset_12, 11, T[45]);
c = HH(c, d, a, b, M_offset_15, 16, T[46]);
b = HH(b, c, d, a, M_offset_2, 23, T[47]);
a = II(a, b, c, d, M_offset_0, 6, T[48]);
d = II(d, a, b, c, M_offset_7, 10, T[49]);
c = II(c, d, a, b, M_offset_14, 15, T[50]);
b = II(b, c, d, a, M_offset_5, 21, T[51]);
a = II(a, b, c, d, M_offset_12, 6, T[52]);
d = II(d, a, b, c, M_offset_3, 10, T[53]);
c = II(c, d, a, b, M_offset_10, 15, T[54]);
b = II(b, c, d, a, M_offset_1, 21, T[55]);
a = II(a, b, c, d, M_offset_8, 6, T[56]);
d = II(d, a, b, c, M_offset_15, 10, T[57]);
c = II(c, d, a, b, M_offset_6, 15, T[58]);
b = II(b, c, d, a, M_offset_13, 21, T[59]);
a = II(a, b, c, d, M_offset_4, 6, T[60]);
d = II(d, a, b, c, M_offset_11, 10, T[61]);
c = II(c, d, a, b, M_offset_2, 15, T[62]);
b = II(b, c, d, a, M_offset_9, 21, T[63]);
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000);
var nBitsTotalL = nBitsTotal;
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = (
(((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) |
(((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00)
);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) |
(((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00)
);
data.sigBytes = (dataWords.length + 1) * 4;
// Hash final blocks
this._process();
// Shortcuts
var hash = this._hash;
var H = hash.words;
// Swap endian
for (var i = 0; i < 4; i++) {
// Shortcut
var H_i = H[i];
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
}
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
function FF(a, b, c, d, x, s, t) {
var n = a + ((b & c) | (~b & d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function GG(a, b, c, d, x, s, t) {
var n = a + ((b & d) | (c & ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function HH(a, b, c, d, x, s, t) {
var n = a + (b ^ c ^ d) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function II(a, b, c, d, x, s, t) {
var n = a + (c ^ (b | ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.MD5('message');
* var hash = CryptoJS.MD5(wordArray);
*/
C.MD5 = Hasher._createHelper(MD5);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacMD5(message, key);
*/
C.HmacMD5 = Hasher._createHmacHelper(MD5);
}(Math));
return CryptoJS.MD5;
}));
/***/ }),
/***/ "dejd":
/*!***********************************************************!*\
!*** ./src/components/markdown-editor/toolbar/index.less ***!
\***********************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/***/ "digP":
/*!*******************************************************************!*\
!*** ./node_modules/@ant-design/icons-svg/lib/asn/FileTwoTone.js ***!
\*******************************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// This icon file is generated automatically.
Object.defineProperty(exports, "__esModule", { value: true });
var FileTwoTone = { "icon": function render(primaryColor, secondaryColor) { return { "tag": "svg", "attrs": { "viewBox": "64 64 896 896", "focusable": "false" }, "children": [{ "tag": "path", "attrs": { "d": "M534 352V136H232v752h560V394H576a42 42 0 01-42-42z", "fill": secondaryColor } }, { "tag": "path", "attrs": { "d": "M854.6 288.6L639.4 73.4c-6-6-14.1-9.4-22.6-9.4H192c-17.7 0-32 14.3-32 32v832c0 17.7 14.3 32 32 32h640c17.7 0 32-14.3 32-32V311.3c0-8.5-3.4-16.7-9.4-22.7zM602 137.8L790.2 326H602V137.8zM792 888H232V136h302v216a42 42 0 0042 42h216v494z", "fill": primaryColor } }] }; }, "name": "file", "theme": "twotone" };
exports.default = FileTwoTone;
/***/ }),
/***/ "djh8":
/*!********************************************!*\
!*** ./src/assets/images/icons/qrCode.png ***!
\********************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/qrCode.42927872.png";
/***/ }),
/***/ "e7zE":
/*!******************************************!*\
!*** ./node_modules/crypto-js/pbkdf2.js ***!
\******************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory, undef) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"), __webpack_require__(/*! ./sha1 */ "3y9D"), __webpack_require__(/*! ./hmac */ "WYAk"));
}
else {}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var SHA1 = C_algo.SHA1;
var HMAC = C_algo.HMAC;
/**
* Password-Based Key Derivation Function 2 algorithm.
*/
var PBKDF2 = C_algo.PBKDF2 = Base.extend({
/**
* Configuration options.
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hasher to use. Default: SHA1
* @property {number} iterations The number of iterations to perform. Default: 1
*/
cfg: Base.extend({
keySize: 128/32,
hasher: SHA1,
iterations: 1
}),
/**
* Initializes a newly created key derivation function.
*
* @param {Object} cfg (Optional) The configuration options to use for the derivation.
*
* @example
*
* var kdf = CryptoJS.algo.PBKDF2.create();
* var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 });
* var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 });
*/
init: function (cfg) {
this.cfg = this.cfg.extend(cfg);
},
/**
* Computes the Password-Based Key Derivation Function 2.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
*
* @return {WordArray} The derived key.
*
* @example
*
* var key = kdf.compute(password, salt);
*/
compute: function (password, salt) {
// Shortcut
var cfg = this.cfg;
// Init HMAC
var hmac = HMAC.create(cfg.hasher, password);
// Initial values
var derivedKey = WordArray.create();
var blockIndex = WordArray.create([0x00000001]);
// Shortcuts
var derivedKeyWords = derivedKey.words;
var blockIndexWords = blockIndex.words;
var keySize = cfg.keySize;
var iterations = cfg.iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
var block = hmac.update(salt).finalize(blockIndex);
hmac.reset();
// Shortcuts
var blockWords = block.words;
var blockWordsLength = blockWords.length;
// Iterations
var intermediate = block;
for (var i = 1; i < iterations; i++) {
intermediate = hmac.finalize(intermediate);
hmac.reset();
// Shortcut
var intermediateWords = intermediate.words;
// XOR intermediate with block
for (var j = 0; j < blockWordsLength; j++) {
blockWords[j] ^= intermediateWords[j];
}
}
derivedKey.concat(block);
blockIndexWords[0]++;
}
derivedKey.sigBytes = keySize * 4;
return derivedKey;
}
});
/**
* Computes the Password-Based Key Derivation Function 2.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
* @param {Object} cfg (Optional) The configuration options to use for this computation.
*
* @return {WordArray} The derived key.
*
* @static
*
* @example
*
* var key = CryptoJS.PBKDF2(password, salt);
* var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 });
* var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 });
*/
C.PBKDF2 = function (password, salt, cfg) {
return PBKDF2.create(cfg).compute(password, salt);
};
}());
return CryptoJS.PBKDF2;
}));
/***/ }),
/***/ "fNCr":
/*!********************************************************!*\
!*** ./node_modules/@ant-design/icons/PlusOutlined.js ***!
\********************************************************/
/*! no static exports found */
/*! exports used: default */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _PlusOutlined = _interopRequireDefault(__webpack_require__(/*! ./lib/icons/PlusOutlined */ "tSko"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _default = _PlusOutlined;
exports.default = _default;
module.exports = _default;
/***/ }),
/***/ "fV52":
/*!******************************************************!*\
!*** ./node_modules/antd/es/carousel/style/index.js ***!
\******************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _style_index_less__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../style/index.less */ "cIOH");
/* harmony import */ var _style_index_less__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_style_index_less__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _index_less__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./index.less */ "6/k+");
/* harmony import */ var _index_less__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_index_less__WEBPACK_IMPORTED_MODULE_1__);
/***/ }),
/***/ "g9YV":
/*!***************************************************!*\
!*** ./node_modules/antd/es/table/style/index.js ***!
\***************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _style_index_less__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../style/index.less */ "cIOH");
/* harmony import */ var _style_index_less__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_style_index_less__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _index_less__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./index.less */ "pED+");
/* harmony import */ var _index_less__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_index_less__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _button_style__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../button/style */ "+L6B");
/* harmony import */ var _empty_style__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../empty/style */ "R9oj");
/* harmony import */ var _radio_style__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../radio/style */ "7Kak");
/* harmony import */ var _checkbox_style__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../checkbox/style */ "sRBo");
/* harmony import */ var _dropdown_style__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../dropdown/style */ "qVdP");
/* harmony import */ var _spin_style__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../spin/style */ "T2oS");
/* harmony import */ var _pagination_style__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../pagination/style */ "DjyN");
/* harmony import */ var _tooltip_style__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../tooltip/style */ "5Dmo");
// style dependencies
// deps-lint-skip: menu
// deps-lint-skip: grid
/***/ }),
/***/ "gb/T":
/*!********************************************!*\
!*** ./node_modules/crypto-js/mode-ecb.js ***!
\********************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory, undef) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"), __webpack_require__(/*! ./cipher-core */ "OLod"));
}
else {}
}(this, function (CryptoJS) {
/**
* Electronic Codebook block mode.
*/
CryptoJS.mode.ECB = (function () {
var ECB = CryptoJS.lib.BlockCipherMode.extend();
ECB.Encryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.encryptBlock(words, offset);
}
});
ECB.Decryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.decryptBlock(words, offset);
}
});
return ECB;
}());
return CryptoJS.mode.ECB;
}));
/***/ }),
/***/ "gwTy":
/*!****************************************************!*\
!*** ./node_modules/antd/es/form/style/index.less ***!
\****************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/***/ "hQUZ":
/*!******************************************************************!*\
!*** ./node_modules/@ant-design/react-slick/lib/inner-slider.js ***!
\******************************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "TqRt");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.InnerSlider = void 0;
var _typeof2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/typeof */ "cDf5"));
var _extends2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/extends */ "pVnL"));
var _objectWithoutProperties2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/objectWithoutProperties */ "QILm"));
var _objectSpread2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/objectSpread2 */ "3tO9"));
var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "lwsE"));
var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "W8MJ"));
var _assertThisInitialized2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "PJYZ"));
var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "7W2i"));
var _createSuper2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createSuper */ "LQ03"));
var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "lSNA"));
var _react = _interopRequireDefault(__webpack_require__(/*! react */ "q1tI"));
var _initialState = _interopRequireDefault(__webpack_require__(/*! ./initial-state */ "F1Ou"));
var _debounce = _interopRequireDefault(__webpack_require__(/*! lodash/debounce */ "sEfC"));
var _classnames = _interopRequireDefault(__webpack_require__(/*! classnames */ "TSYQ"));
var _innerSliderUtils = __webpack_require__(/*! ./utils/innerSliderUtils */ "3K4p");
var _track = __webpack_require__(/*! ./track */ "+uyH");
var _dots = __webpack_require__(/*! ./dots */ "coqV");
var _arrows = __webpack_require__(/*! ./arrows */ "3Fjq");
var _resizeObserverPolyfill = _interopRequireDefault(__webpack_require__(/*! resize-observer-polyfill */ "bdgK"));
var InnerSlider = /*#__PURE__*/function (_React$Component) {
(0, _inherits2["default"])(InnerSlider, _React$Component);
var _super = (0, _createSuper2["default"])(InnerSlider);
function InnerSlider(props) {
var _this;
(0, _classCallCheck2["default"])(this, InnerSlider);
_this = _super.call(this, props);
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "listRefHandler", function (ref) {
return _this.list = ref;
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "trackRefHandler", function (ref) {
return _this.track = ref;
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "adaptHeight", function () {
if (_this.props.adaptiveHeight && _this.list) {
var elem = _this.list.querySelector("[data-index=\"".concat(_this.state.currentSlide, "\"]"));
_this.list.style.height = (0, _innerSliderUtils.getHeight)(elem) + "px";
}
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "componentDidMount", function () {
_this.props.onInit && _this.props.onInit();
if (_this.props.lazyLoad) {
var slidesToLoad = (0, _innerSliderUtils.getOnDemandLazySlides)((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, _this.props), _this.state));
if (slidesToLoad.length > 0) {
_this.setState(function (prevState) {
return {
lazyLoadedList: prevState.lazyLoadedList.concat(slidesToLoad)
};
});
if (_this.props.onLazyLoad) {
_this.props.onLazyLoad(slidesToLoad);
}
}
}
var spec = (0, _objectSpread2["default"])({
listRef: _this.list,
trackRef: _this.track
}, _this.props);
_this.updateState(spec, true, function () {
_this.adaptHeight();
_this.props.autoplay && _this.autoPlay("update");
});
if (_this.props.lazyLoad === "progressive") {
_this.lazyLoadTimer = setInterval(_this.progressiveLazyLoad, 1000);
}
_this.ro = new _resizeObserverPolyfill["default"](function () {
if (_this.state.animating) {
_this.onWindowResized(false); // don't set trackStyle hence don't break animation
_this.callbackTimers.push(setTimeout(function () {
return _this.onWindowResized();
}, _this.props.speed));
} else {
_this.onWindowResized();
}
});
_this.ro.observe(_this.list);
Array.prototype.forEach.call(document.querySelectorAll(".slick-slide"), function (slide) {
slide.onfocus = _this.props.pauseOnFocus ? _this.onSlideFocus : null;
slide.onblur = _this.props.pauseOnFocus ? _this.onSlideBlur : null;
});
if (window.addEventListener) {
window.addEventListener("resize", _this.onWindowResized);
} else {
window.attachEvent("onresize", _this.onWindowResized);
}
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "componentWillUnmount", function () {
if (_this.animationEndCallback) {
clearTimeout(_this.animationEndCallback);
}
if (_this.lazyLoadTimer) {
clearInterval(_this.lazyLoadTimer);
}
if (_this.callbackTimers.length) {
_this.callbackTimers.forEach(function (timer) {
return clearTimeout(timer);
});
_this.callbackTimers = [];
}
if (window.addEventListener) {
window.removeEventListener("resize", _this.onWindowResized);
} else {
window.detachEvent("onresize", _this.onWindowResized);
}
if (_this.autoplayTimer) {
clearInterval(_this.autoplayTimer);
}
_this.ro.disconnect();
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "componentDidUpdate", function (prevProps) {
_this.checkImagesLoad();
_this.props.onReInit && _this.props.onReInit();
if (_this.props.lazyLoad) {
var slidesToLoad = (0, _innerSliderUtils.getOnDemandLazySlides)((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, _this.props), _this.state));
if (slidesToLoad.length > 0) {
_this.setState(function (prevState) {
return {
lazyLoadedList: prevState.lazyLoadedList.concat(slidesToLoad)
};
});
if (_this.props.onLazyLoad) {
_this.props.onLazyLoad(slidesToLoad);
}
}
} // if (this.props.onLazyLoad) {
// this.props.onLazyLoad([leftMostSlide])
// }
_this.adaptHeight();
var spec = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({
listRef: _this.list,
trackRef: _this.track
}, _this.props), _this.state);
var setTrackStyle = _this.didPropsChange(prevProps);
setTrackStyle && _this.updateState(spec, setTrackStyle, function () {
if (_this.state.currentSlide >= _react["default"].Children.count(_this.props.children)) {
_this.changeSlide({
message: "index",
index: _react["default"].Children.count(_this.props.children) - _this.props.slidesToShow,
currentSlide: _this.state.currentSlide
});
}
if (prevProps.autoplay !== _this.props.autoplay || prevProps.autoplaySpeed !== _this.props.autoplaySpeed) {
if (_this.props.autoplay) {
_this.autoPlay("update");
} else {
_this.pause("paused");
}
}
});
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onWindowResized", function (setTrackStyle) {
if (_this.debouncedResize) _this.debouncedResize.cancel();
_this.debouncedResize = (0, _debounce["default"])(function () {
return _this.resizeWindow(setTrackStyle);
}, 50);
_this.debouncedResize();
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "resizeWindow", function () {
var setTrackStyle = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
var isTrackMounted = Boolean(_this.track && _this.track.node); // prevent warning: setting state on unmounted component (server side rendering)
if (!isTrackMounted) return;
var spec = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({
listRef: _this.list,
trackRef: _this.track
}, _this.props), _this.state);
_this.updateState(spec, setTrackStyle, function () {
if (_this.props.autoplay) _this.autoPlay("update");else _this.pause("paused");
}); // animating state should be cleared while resizing, otherwise autoplay stops working
_this.setState({
animating: false
});
clearTimeout(_this.animationEndCallback);
delete _this.animationEndCallback;
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "updateState", function (spec, setTrackStyle, callback) {
var updatedState = (0, _innerSliderUtils.initializedState)(spec);
spec = (0, _objectSpread2["default"])((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, spec), updatedState), {}, {
slideIndex: updatedState.currentSlide
});
var targetLeft = (0, _innerSliderUtils.getTrackLeft)(spec);
spec = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, spec), {}, {
left: targetLeft
});
var trackStyle = (0, _innerSliderUtils.getTrackCSS)(spec);
if (setTrackStyle || _react["default"].Children.count(_this.props.children) !== _react["default"].Children.count(spec.children)) {
updatedState["trackStyle"] = trackStyle;
}
_this.setState(updatedState, callback);
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "ssrInit", function () {
if (_this.props.variableWidth) {
var _trackWidth = 0,
_trackLeft = 0;
var childrenWidths = [];
var preClones = (0, _innerSliderUtils.getPreClones)((0, _objectSpread2["default"])((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, _this.props), _this.state), {}, {
slideCount: _this.props.children.length
}));
var postClones = (0, _innerSliderUtils.getPostClones)((0, _objectSpread2["default"])((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, _this.props), _this.state), {}, {
slideCount: _this.props.children.length
}));
_this.props.children.forEach(function (child) {
childrenWidths.push(child.props.style.width);
_trackWidth += child.props.style.width;
});
for (var i = 0; i < preClones; i++) {
_trackLeft += childrenWidths[childrenWidths.length - 1 - i];
_trackWidth += childrenWidths[childrenWidths.length - 1 - i];
}
for (var _i = 0; _i < postClones; _i++) {
_trackWidth += childrenWidths[_i];
}
for (var _i2 = 0; _i2 < _this.state.currentSlide; _i2++) {
_trackLeft += childrenWidths[_i2];
}
var _trackStyle = {
width: _trackWidth + "px",
left: -_trackLeft + "px"
};
if (_this.props.centerMode) {
var currentWidth = "".concat(childrenWidths[_this.state.currentSlide], "px");
_trackStyle.left = "calc(".concat(_trackStyle.left, " + (100% - ").concat(currentWidth, ") / 2 ) ");
}
return {
trackStyle: _trackStyle
};
}
var childrenCount = _react["default"].Children.count(_this.props.children);
var spec = (0, _objectSpread2["default"])((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, _this.props), _this.state), {}, {
slideCount: childrenCount
});
var slideCount = (0, _innerSliderUtils.getPreClones)(spec) + (0, _innerSliderUtils.getPostClones)(spec) + childrenCount;
var trackWidth = 100 / _this.props.slidesToShow * slideCount;
var slideWidth = 100 / slideCount;
var trackLeft = -slideWidth * ((0, _innerSliderUtils.getPreClones)(spec) + _this.state.currentSlide) * trackWidth / 100;
if (_this.props.centerMode) {
trackLeft += (100 - slideWidth * trackWidth / 100) / 2;
}
var trackStyle = {
width: trackWidth + "%",
left: trackLeft + "%"
};
return {
slideWidth: slideWidth + "%",
trackStyle: trackStyle
};
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "checkImagesLoad", function () {
var images = _this.list.querySelectorAll(".slick-slide img");
var imagesCount = images.length,
loadedCount = 0;
Array.prototype.forEach.call(images, function (image) {
var handler = function handler() {
return ++loadedCount && loadedCount >= imagesCount && _this.onWindowResized();
};
if (!image.onclick) {
image.onclick = function () {
return image.parentNode.focus();
};
} else {
var prevClickHandler = image.onclick;
image.onclick = function () {
prevClickHandler();
image.parentNode.focus();
};
}
if (!image.onload) {
if (_this.props.lazyLoad) {
image.onload = function () {
_this.adaptHeight();
_this.callbackTimers.push(setTimeout(_this.onWindowResized, _this.props.speed));
};
} else {
image.onload = handler;
image.onerror = function () {
handler();
_this.props.onLazyLoadError && _this.props.onLazyLoadError();
};
}
}
});
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "progressiveLazyLoad", function () {
var slidesToLoad = [];
var spec = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, _this.props), _this.state);
for (var index = _this.state.currentSlide; index < _this.state.slideCount + (0, _innerSliderUtils.getPostClones)(spec); index++) {
if (_this.state.lazyLoadedList.indexOf(index) < 0) {
slidesToLoad.push(index);
break;
}
}
for (var _index = _this.state.currentSlide - 1; _index >= -(0, _innerSliderUtils.getPreClones)(spec); _index--) {
if (_this.state.lazyLoadedList.indexOf(_index) < 0) {
slidesToLoad.push(_index);
break;
}
}
if (slidesToLoad.length > 0) {
_this.setState(function (state) {
return {
lazyLoadedList: state.lazyLoadedList.concat(slidesToLoad)
};
});
if (_this.props.onLazyLoad) {
_this.props.onLazyLoad(slidesToLoad);
}
} else {
if (_this.lazyLoadTimer) {
clearInterval(_this.lazyLoadTimer);
delete _this.lazyLoadTimer;
}
}
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "slideHandler", function (index) {
var dontAnimate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var _this$props = _this.props,
asNavFor = _this$props.asNavFor,
beforeChange = _this$props.beforeChange,
onLazyLoad = _this$props.onLazyLoad,
speed = _this$props.speed,
afterChange = _this$props.afterChange; // capture currentslide before state is updated
var currentSlide = _this.state.currentSlide;
var _slideHandler = (0, _innerSliderUtils.slideHandler)((0, _objectSpread2["default"])((0, _objectSpread2["default"])((0, _objectSpread2["default"])({
index: index
}, _this.props), _this.state), {}, {
trackRef: _this.track,
useCSS: _this.props.useCSS && !dontAnimate
})),
state = _slideHandler.state,
nextState = _slideHandler.nextState;
if (!state) return;
beforeChange && beforeChange(currentSlide, state.currentSlide);
var slidesToLoad = state.lazyLoadedList.filter(function (value) {
return _this.state.lazyLoadedList.indexOf(value) < 0;
});
onLazyLoad && slidesToLoad.length > 0 && onLazyLoad(slidesToLoad);
if (!_this.props.waitForAnimate && _this.animationEndCallback) {
clearTimeout(_this.animationEndCallback);
afterChange && afterChange(currentSlide);
delete _this.animationEndCallback;
}
_this.setState(state, function () {
// asNavForIndex check is to avoid recursive calls of slideHandler in waitForAnimate=false mode
if (asNavFor && _this.asNavForIndex !== index) {
_this.asNavForIndex = index;
asNavFor.innerSlider.slideHandler(index);
}
if (!nextState) return;
_this.animationEndCallback = setTimeout(function () {
var animating = nextState.animating,
firstBatch = (0, _objectWithoutProperties2["default"])(nextState, ["animating"]);
_this.setState(firstBatch, function () {
_this.callbackTimers.push(setTimeout(function () {
return _this.setState({
animating: animating
});
}, 10));
afterChange && afterChange(state.currentSlide);
delete _this.animationEndCallback;
});
}, speed);
});
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "changeSlide", function (options) {
var dontAnimate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var spec = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, _this.props), _this.state);
var targetSlide = (0, _innerSliderUtils.changeSlide)(spec, options);
if (targetSlide !== 0 && !targetSlide) return;
if (dontAnimate === true) {
_this.slideHandler(targetSlide, dontAnimate);
} else {
_this.slideHandler(targetSlide);
}
_this.props.autoplay && _this.autoPlay("update");
if (_this.props.focusOnSelect) {
var nodes = _this.list.querySelectorAll(".slick-current");
nodes[0] && nodes[0].focus();
}
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "clickHandler", function (e) {
if (_this.clickable === false) {
e.stopPropagation();
e.preventDefault();
}
_this.clickable = true;
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "keyHandler", function (e) {
var dir = (0, _innerSliderUtils.keyHandler)(e, _this.props.accessibility, _this.props.rtl);
dir !== "" && _this.changeSlide({
message: dir
});
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "selectHandler", function (options) {
_this.changeSlide(options);
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "disableBodyScroll", function () {
var preventDefault = function preventDefault(e) {
e = e || window.event;
if (e.preventDefault) e.preventDefault();
e.returnValue = false;
};
window.ontouchmove = preventDefault;
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "enableBodyScroll", function () {
window.ontouchmove = null;
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "swipeStart", function (e) {
if (_this.props.verticalSwiping) {
_this.disableBodyScroll();
}
var state = (0, _innerSliderUtils.swipeStart)(e, _this.props.swipe, _this.props.draggable);
state !== "" && _this.setState(state);
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "swipeMove", function (e) {
var state = (0, _innerSliderUtils.swipeMove)(e, (0, _objectSpread2["default"])((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, _this.props), _this.state), {}, {
trackRef: _this.track,
listRef: _this.list,
slideIndex: _this.state.currentSlide
}));
if (!state) return;
if (state["swiping"]) {
_this.clickable = false;
}
_this.setState(state);
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "swipeEnd", function (e) {
var state = (0, _innerSliderUtils.swipeEnd)(e, (0, _objectSpread2["default"])((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, _this.props), _this.state), {}, {
trackRef: _this.track,
listRef: _this.list,
slideIndex: _this.state.currentSlide
}));
if (!state) return;
var triggerSlideHandler = state["triggerSlideHandler"];
delete state["triggerSlideHandler"];
_this.setState(state);
if (triggerSlideHandler === undefined) return;
_this.slideHandler(triggerSlideHandler);
if (_this.props.verticalSwiping) {
_this.enableBodyScroll();
}
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "touchEnd", function (e) {
_this.swipeEnd(e);
_this.clickable = true;
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "slickPrev", function () {
// this and fellow methods are wrapped in setTimeout
// to make sure initialize setState has happened before
// any of such methods are called
_this.callbackTimers.push(setTimeout(function () {
return _this.changeSlide({
message: "previous"
});
}, 0));
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "slickNext", function () {
_this.callbackTimers.push(setTimeout(function () {
return _this.changeSlide({
message: "next"
});
}, 0));
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "slickGoTo", function (slide) {
var dontAnimate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
slide = Number(slide);
if (isNaN(slide)) return "";
_this.callbackTimers.push(setTimeout(function () {
return _this.changeSlide({
message: "index",
index: slide,
currentSlide: _this.state.currentSlide
}, dontAnimate);
}, 0));
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "play", function () {
var nextIndex;
if (_this.props.rtl) {
nextIndex = _this.state.currentSlide - _this.props.slidesToScroll;
} else {
if ((0, _innerSliderUtils.canGoNext)((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, _this.props), _this.state))) {
nextIndex = _this.state.currentSlide + _this.props.slidesToScroll;
} else {
return false;
}
}
_this.slideHandler(nextIndex);
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "autoPlay", function (playType) {
if (_this.autoplayTimer) {
clearInterval(_this.autoplayTimer);
}
var autoplaying = _this.state.autoplaying;
if (playType === "update") {
if (autoplaying === "hovered" || autoplaying === "focused" || autoplaying === "paused") {
return;
}
} else if (playType === "leave") {
if (autoplaying === "paused" || autoplaying === "focused") {
return;
}
} else if (playType === "blur") {
if (autoplaying === "paused" || autoplaying === "hovered") {
return;
}
}
_this.autoplayTimer = setInterval(_this.play, _this.props.autoplaySpeed + 50);
_this.setState({
autoplaying: "playing"
});
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "pause", function (pauseType) {
if (_this.autoplayTimer) {
clearInterval(_this.autoplayTimer);
_this.autoplayTimer = null;
}
var autoplaying = _this.state.autoplaying;
if (pauseType === "paused") {
_this.setState({
autoplaying: "paused"
});
} else if (pauseType === "focused") {
if (autoplaying === "hovered" || autoplaying === "playing") {
_this.setState({
autoplaying: "focused"
});
}
} else {
// pauseType is 'hovered'
if (autoplaying === "playing") {
_this.setState({
autoplaying: "hovered"
});
}
}
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onDotsOver", function () {
return _this.props.autoplay && _this.pause("hovered");
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onDotsLeave", function () {
return _this.props.autoplay && _this.state.autoplaying === "hovered" && _this.autoPlay("leave");
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onTrackOver", function () {
return _this.props.autoplay && _this.pause("hovered");
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onTrackLeave", function () {
return _this.props.autoplay && _this.state.autoplaying === "hovered" && _this.autoPlay("leave");
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onSlideFocus", function () {
return _this.props.autoplay && _this.pause("focused");
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onSlideBlur", function () {
return _this.props.autoplay && _this.state.autoplaying === "focused" && _this.autoPlay("blur");
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "render", function () {
var className = (0, _classnames["default"])("slick-slider", _this.props.className, {
"slick-vertical": _this.props.vertical,
"slick-initialized": true
});
var spec = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, _this.props), _this.state);
var trackProps = (0, _innerSliderUtils.extractObject)(spec, ["fade", "cssEase", "speed", "infinite", "centerMode", "focusOnSelect", "currentSlide", "lazyLoad", "lazyLoadedList", "rtl", "slideWidth", "slideHeight", "listHeight", "vertical", "slidesToShow", "slidesToScroll", "slideCount", "trackStyle", "variableWidth", "unslick", "centerPadding", "targetSlide", "useCSS"]);
var pauseOnHover = _this.props.pauseOnHover;
trackProps = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, trackProps), {}, {
onMouseEnter: pauseOnHover ? _this.onTrackOver : null,
onMouseLeave: pauseOnHover ? _this.onTrackLeave : null,
onMouseOver: pauseOnHover ? _this.onTrackOver : null,
focusOnSelect: _this.props.focusOnSelect && _this.clickable ? _this.selectHandler : null
});
var dots;
if (_this.props.dots === true && _this.state.slideCount >= _this.props.slidesToShow) {
var dotProps = (0, _innerSliderUtils.extractObject)(spec, ["dotsClass", "slideCount", "slidesToShow", "currentSlide", "slidesToScroll", "clickHandler", "children", "customPaging", "infinite", "appendDots"]);
var pauseOnDotsHover = _this.props.pauseOnDotsHover;
dotProps = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, dotProps), {}, {
clickHandler: _this.changeSlide,
onMouseEnter: pauseOnDotsHover ? _this.onDotsLeave : null,
onMouseOver: pauseOnDotsHover ? _this.onDotsOver : null,
onMouseLeave: pauseOnDotsHover ? _this.onDotsLeave : null
});
dots = /*#__PURE__*/_react["default"].createElement(_dots.Dots, dotProps);
}
var prevArrow, nextArrow;
var arrowProps = (0, _innerSliderUtils.extractObject)(spec, ["infinite", "centerMode", "currentSlide", "slideCount", "slidesToShow", "prevArrow", "nextArrow"]);
arrowProps.clickHandler = _this.changeSlide;
if (_this.props.arrows) {
prevArrow = /*#__PURE__*/_react["default"].createElement(_arrows.PrevArrow, arrowProps);
nextArrow = /*#__PURE__*/_react["default"].createElement(_arrows.NextArrow, arrowProps);
}
var verticalHeightStyle = null;
if (_this.props.vertical) {
verticalHeightStyle = {
height: _this.state.listHeight
};
}
var centerPaddingStyle = null;
if (_this.props.vertical === false) {
if (_this.props.centerMode === true) {
centerPaddingStyle = {
padding: "0px " + _this.props.centerPadding
};
}
} else {
if (_this.props.centerMode === true) {
centerPaddingStyle = {
padding: _this.props.centerPadding + " 0px"
};
}
}
var listStyle = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, verticalHeightStyle), centerPaddingStyle);
var touchMove = _this.props.touchMove;
var listProps = {
className: "slick-list",
style: listStyle,
onClick: _this.clickHandler,
onMouseDown: touchMove ? _this.swipeStart : null,
onMouseMove: _this.state.dragging && touchMove ? _this.swipeMove : null,
onMouseUp: touchMove ? _this.swipeEnd : null,
onMouseLeave: _this.state.dragging && touchMove ? _this.swipeEnd : null,
onTouchStart: touchMove ? _this.swipeStart : null,
onTouchMove: _this.state.dragging && touchMove ? _this.swipeMove : null,
onTouchEnd: touchMove ? _this.touchEnd : null,
onTouchCancel: _this.state.dragging && touchMove ? _this.swipeEnd : null,
onKeyDown: _this.props.accessibility ? _this.keyHandler : null
};
var innerSliderProps = {
className: className,
dir: "ltr",
style: _this.props.style
};
if (_this.props.unslick) {
listProps = {
className: "slick-list"
};
innerSliderProps = {
className: className
};
}
return /*#__PURE__*/_react["default"].createElement("div", innerSliderProps, !_this.props.unslick ? prevArrow : "", /*#__PURE__*/_react["default"].createElement("div", (0, _extends2["default"])({
ref: _this.listRefHandler
}, listProps), /*#__PURE__*/_react["default"].createElement(_track.Track, (0, _extends2["default"])({
ref: _this.trackRefHandler
}, trackProps), _this.props.children)), !_this.props.unslick ? nextArrow : "", !_this.props.unslick ? dots : "");
});
_this.list = null;
_this.track = null;
_this.state = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, _initialState["default"]), {}, {
currentSlide: _this.props.initialSlide,
slideCount: _react["default"].Children.count(_this.props.children)
});
_this.callbackTimers = [];
_this.clickable = true;
_this.debouncedResize = null;
var ssrState = _this.ssrInit();
_this.state = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, _this.state), ssrState);
return _this;
}
(0, _createClass2["default"])(InnerSlider, [{
key: "didPropsChange",
value: function didPropsChange(prevProps) {
var setTrackStyle = false;
for (var _i3 = 0, _Object$keys = Object.keys(this.props); _i3 < _Object$keys.length; _i3++) {
var key = _Object$keys[_i3];
// eslint-disable-next-line no-prototype-builtins
if (!prevProps.hasOwnProperty(key)) {
setTrackStyle = true;
break;
}
if ((0, _typeof2["default"])(prevProps[key]) === "object" || typeof prevProps[key] === "function") {
continue;
}
if (prevProps[key] !== this.props[key]) {
setTrackStyle = true;
break;
}
}
return setTrackStyle || _react["default"].Children.count(this.props.children) !== _react["default"].Children.count(prevProps.children);
}
}]);
return InnerSlider;
}(_react["default"].Component);
exports.InnerSlider = InnerSlider;
/***/ }),
/***/ "hkKa":
/*!************************************************************!*\
!*** ./node_modules/antd/es/_util/hooks/useForceUpdate.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 useForceUpdate; });
/* harmony import */ var _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/slicedToArray */ "J4zp");
/* harmony import */ var _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "q1tI");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
function useForceUpdate() {
var _React$useReducer = react__WEBPACK_IMPORTED_MODULE_1__["useReducer"](function (x) {
return x + 1;
}, 0),
_React$useReducer2 = _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_0___default()(_React$useReducer, 2),
forceUpdate = _React$useReducer2[1];
return forceUpdate;
}
/***/ }),
/***/ "hwYd":
/*!********************************************************************!*\
!*** ./node_modules/@ant-design/icons/lib/icons/PictureTwoTone.js ***!
\********************************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireWildcard = __webpack_require__(/*! @babel/runtime/helpers/interopRequireWildcard */ "284h");
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "TqRt");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/objectSpread2 */ "3tO9"));
var React = _interopRequireWildcard(__webpack_require__(/*! react */ "q1tI"));
var _PictureTwoTone = _interopRequireDefault(__webpack_require__(/*! @ant-design/icons-svg/lib/asn/PictureTwoTone */ "Nu4q"));
var _AntdIcon = _interopRequireDefault(__webpack_require__(/*! ../components/AntdIcon */ "KQxl"));
// GENERATE BY ./scripts/generate.ts
// DON NOT EDIT IT MANUALLY
var PictureTwoTone = function PictureTwoTone(props, ref) {
return /*#__PURE__*/React.createElement(_AntdIcon.default, (0, _objectSpread2.default)((0, _objectSpread2.default)({}, props), {}, {
ref: ref,
icon: _PictureTwoTone.default
}));
};
PictureTwoTone.displayName = 'PictureTwoTone';
var _default = /*#__PURE__*/React.forwardRef(PictureTwoTone);
exports.default = _default;
/***/ }),
/***/ "i8CU":
/*!***********************************************************!*\
!*** ./node_modules/@ant-design/icons/CaretUpOutlined.js ***!
\***********************************************************/
/*! no static exports found */
/*! exports used: default */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _CaretUpOutlined = _interopRequireDefault(__webpack_require__(/*! ./lib/icons/CaretUpOutlined */ "Fm1+"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _default = _CaretUpOutlined;
exports.default = _default;
module.exports = _default;
/***/ }),
/***/ "jO9C":
/*!************************************************!*\
!*** ./node_modules/crypto-js/pad-iso97971.js ***!
\************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory, undef) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"), __webpack_require__(/*! ./cipher-core */ "OLod"));
}
else {}
}(this, function (CryptoJS) {
/**
* ISO/IEC 9797-1 Padding Method 2.
*/
CryptoJS.pad.Iso97971 = {
pad: function (data, blockSize) {
// Add 0x80 byte
data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1));
// Zero pad the rest
CryptoJS.pad.ZeroPadding.pad(data, blockSize);
},
unpad: function (data) {
// Remove zero padding
CryptoJS.pad.ZeroPadding.unpad(data);
// Remove one more byte -- the 0x80 byte
data.sigBytes--;
}
};
return CryptoJS.pad.Iso97971;
}));
/***/ }),
/***/ "ji0R":
/*!*******************************************!*\
!*** ./src/assets/images/icons/douyu.jpg ***!
\*******************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/douyu.3e6df9ee.jpg";
/***/ }),
/***/ "jwmR":
/*!***************************************************************************************!*\
!*** ./src/pages/Competitions/Detail/components/AppplySchoolModal/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 = {"flexRow":"flexRow___3nMh-","flexColumn":"flexColumn___Xpn5L","formWrap":"formWrap___3t9mN","example":"example___5c8Eu","footerWrap":"footerWrap___20Wal"};
/***/ }),
/***/ "kPWJ":
/*!****************************************!*\
!*** ./src/assets/images/question.gif ***!
\****************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/question.cb52bef9.gif";
/***/ }),
/***/ "kPYp":
/*!******************************************!*\
!*** ./src/assets/images/icons/zoom.png ***!
\******************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports) {
module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAF8AAAAUCAYAAADr0+FaAAANEklEQVRYR8WZe5RX1XXHP/vce3/zHoaXgFp5DQyOQLRgUTEtDW1qYyVmZUGNklRdiRpKE3lHfPyc4TngIBgfC0wx1ixt1NRWal2kotbE2lbRiCIISBCGhzDAvGd+87v37K5z5zfDzMCM46pr9fw1a+45+5zz3fvs/d3fn4yr1F8Do0UIUb74UFR8Gm3IO/Wf8MThat7mOYnaDZUmNUF/htpWLlePK4xwCcoQICHQbOGoKDuM4U1p5r0Px1DNrDPrezzQs+qNPUh/o4xXj6tRJhlhGEqeQNrCCYXdGvGfFt5JNHLoozJp7WyvdI0OtR4LEK7CstUIWyJLTSRcLfCnvlAiUKSgCEfV8o6NeMVE/G53itOUiXX3Sxcx2ov4qhG+qjBWoFChWYUqIt6VgFeblR0H5lEL0oGyjKvU1yHezPviyHdZ0Ro180basvD398n77svIFTokK5vrgW8LTELJRwgA6bTSHcaBckot/yWGX2YZtv5untT0dJ7SpOZrAX9mLTeIYarAIIQEYLrZTQNNFj7A8rx6/GrPfDncPmdihV6Y9nkA+Ot4nrIXaDSGElH6KfjdzpBSpVo8ttVU8Xitx/7hw/imWmYD4wXy6Iqjje9mOGYj/uX0bjYf/5nsaLcpY9fqDZ5hNTD8/wi+27bB+CzfOVcqSiq0BMPdRpiBUNANmHNvJUQo1ZFls0lTuXupnOw+0UVamMsCz+eHCuf3MWgUjZ3w76kUZQeW8j4iOnadXmCUNQI3xvsIbl7bX70MEdKpFLutcCA7iz/BxvfrfY2hNVXDb2v2s/TkU/Lf8SZXrtOcUxFfF8P1AiNVSYj0aihUGOoCu/vFFVpQlpmQX1iflQg3dMxxR1OaVHERfUIglXFKf6AIIbs97SnUq7I5VFZ+skiOt+NwSVIHpAu4wwgLBAZ04COkUGoytusEAhUGi9APyO+UTlWVfyPkrt0/kQ8y4FcI3NQF6zYnNAEn1VKtQuAJg1XiPRPOnnggFmwmicTIC/VqOa5wCiFHhCFGGGAtnkNUBGyaLVGKJXvvZXe8ZlpS/UP5DAh8cgPt8nTP8n+LZbS7vIHpdH2WzcBzUZp1njCTgB/HacYNQxS1sluFF4zwmgpHEpa09ckOleGkuUaEa70sRmrU4fgGG7L8VBOPnCiThgvXaU5ByE14rAGcwxA/vsxha3lJPF4ylv0mpCVKYBCGRRFXm5BvedlMcEEVgyY0hSHP+nn8XZiin1G6gu+At3watfC0l8MWIk5GBs+0UhxZbvSyuM545Gvn+ijYsIU9GvKkyeLVIOBUypIwKSbSyt94RUxHCeIgMNRFEauaDBt6fSrdkS+p0MnisUpgGtIlH7rc9nOU8pQyPmF4XGBY5v2G6RRvtp7irkFjeGf7bYTuyXfYVpUhi8gtLOCaoJA1KKPaL2aVHXjM+XievFm6Ti+JlE0GrupIDMqRps+4z6vh+f3DqHcF8MyZVSbdhl9lKCm8gBVBPn+pNq43qHBSlTujgNeDkJUo3+3Iw9BYF3F3i7K5eonUd9hLqhm2lz/IG8OaYADflgjPndMBGHkcqD3B4mMn+Gc2iaszbSOpZtDbFBdN4uFgINOJMAqOjGxLW77bJ/BHJDU7kcfXjOEeEa7s9NzdM65WeNK0sC5dQGjSrPDgB+1zVNiRqmbh7wO2dQWnm2tv0+C8Zq7rfxkbjOEC3AsQmtSyYnc9q8cW8kMDSYHB7saqHGs+xvLgQ36272VJ9Zajh92ukwtH8JCXxxWajvFSC1sjZYEPC0W4pT3RG3jj0xQ/qF8qe86ymVRTbLg2KOQxLBdkvkdWeLoR7qyaL6fOWqMqI+9jZvYAHsEyKP7eVtj//HPBn5bU7CP9uN4oi4GvSFdGcRhhgybYvHuunByzXqd4IZtEmNi2BzZSklrPQ/vKpK43gOJvEzWvZDZrvYCb1ZIDhBZeyE3xt01ZrDRwc5zqhCiyPNtaxZwD63tmRe37jbhZs/1i5iQKSGpIYeZs+7HcKYYZwPfb50bwSK2l/LNOtabzuUet0TGB4VdGmJD5f0qFiro6Ko7cL65OnDVcxjA+zwDFmY9H/TY62/OYuFbzQphthXIRzus8U4kLy10DhGfemi8u3zOuUv9K4Km4gLaF14kIbty7SF75XOAzE0rW6iwxPBxHOFiUt0Plx77HvSjXZiLntI0o/3iJrO+bXZWSCibh8QsjlMRnE06IZYWjiEgb+CLo6RQrm1t4oKbs3E4dnNSh/fLYkvCZHNtRmppDysOAh6oyOHQ/0+i1Ot6HZzyPS1TjunvcRFzVI/gZjn6rKPORzHNps+ro4A6F5aaef+1oXFSl9EFmqvIEkBunBstea5i9Z778T99AgnFr1dWTp0S4sO1u7ETj1LCItiLvEu1RQn6ya7H8Q5/tJnWEzecFz+PSDPtxKWIdMMJFvkNEDHq4iuU1dVSySWrPZXvkeh2SHfEi8EfGQBTRWFdLecLw0IEyaTnXmovX6ng1PC3CeNeuifCZCeP+5OxRXKEXGp95hrgouAjsGBZ+KxHLTCOvd+0YVUrXMUMVB0j70z4cRty0b7H8R19BKqnUGQY20kZnXU1511rm+R5LFa7J2KmOQpJ7lsijfbU7brVOwOcfRSiNIxaqjbBaLeNc5HeAf5DlNQ1fAPyQxoY6yv0vA/xxq3QEAcvFMCumR2eG476vRsKCPQvY0blNbp9y8Xr9YxvyhBFGZS4YRSFzCot4YvvtnVhAT4hN0mDsDSz1PRaoUuCYgcLWAO4IYbXAdzLNTGgtmz5exNxzneMs80n1i7P4TpDLOokY5KiWKlXAYhG+1iXyPw/8FTokO7tT5H8p4CfVlBbyFassFeE6IKvTJRqt5QVfWLVzoXzUE3bOcZpgjYGZmfTgmpBt0UkW71vJe70CNVO9QZbLBl7J3xufCY7tZJq29UPrufdIAYtNG1j9XEqzyq7mwyw+eIiXO2tJ5zrbebfoqKIxVPr5zNB03AOoVd6KWpkbJJwDubXPkf9lgz9powaNdUw1HveqMrUz8Erc6W0OI9bvW8T+Lhy9+003alDcyPd8pVKIu0uHU2O6medaPmP5oZ/KJ+d03DT1i6cy2eSzzE8wTV0P4agS7DeWH+1aJC+VPKhTRXlUNMOkhEhb2d58jLsPHuYNnusqmrXvM2i2DisazeKgkFsRCp1dFRpUWGYifolQDnzv/wV8p5XYfP5CPMpRLu0GzlGrrB9g+Gltbdwc9Dhyzke3HyEqzmKgn2CDSCxWuShzmk86XcvrErDR+vxGsqhNnESbwHiFDJYGvi4+3w8KmEK6Q/azqjzWYLjP8efipBb6eSwQj6XtnbVJQNTEzqiVjZ7PlpYWjuWCbR2ImFYKwkamGMstWf3jBivXVW91+lHIG4W5zKxpJbu9w+0r+CPW6NBcjxcVLo8Lbl/TjvCMmFjRPVNwix/Q0kDiAuc6xy6qoAqHULaKpVGlZ9WzLQtwysLbrR5vZaco1SDO0a6ixzbFgLUcUdhllE+d5OpSiIXhpq0IDnShHrMkSClsM5YluxbJh7HHVWXCaka2BpQb4Vsxo2pr192C084uzq5y2mk7GEaIk4SFi1xHlUmDroC/Z5V79iyUlztrOw58l45OVbMsFbLudEUPbGeFDsnJjsFvYzt9Bf9cbKe0Ui8DnlYY1z2sXcETzfSavdMKB0OI4/7C42EtD5tcLhef+w1c0U0DcpYcXXUauYOus8Mdns1W2eIpy3Y18FGXrjipZmzAMLIoM4ZZQqwmdh7Oaltv3E0id1lMlR1hRJnk8PK+H0mqu7DmHBDB4vw6HtneQ8N06YNalIp4HmF6X8EfV6ljRfk5EmNxJvIdn09ksdYIs7oV2d7h7uGrhUOEzP14ibzoNgXmC3wjQx3dbwZdwM6YcbHpNJFDKjxr4dHOunv3rcY9rANNC7dbR4WFkbhIP7ddFxSxTK3Cr0nzgFMz2+05Su37saTsWJRVS5VnuHnnAnmtp8vPnKne+1NY4jlZwtDfWpob6ijzhQ098fyLVmn/bJ97PMPtQJ5r8Dxck5VUMyqXP0wEzEHjNFHQR438rPPZtuyiKpTtmsdjrji7SGmJmBJrGYZSlIsyfYD7oaJVlVqEAwbejSJeafR5t6dOsfOGTuXMTTHeBExHmCzCaDTurLPEFWOlXqFKlI+s8prfwG92lnXVXkoq9HwTcD/KdSp8mGrmyVSaf+pJJmjff/gKHZaTxR3G8E1rKWyoY4MvbOwJfIdIcSUX+8Ic1yg6yT6Eb7Q1Wc4BORRk+RQZQ2DD3n8Y+Lwn4edT/cEcOd0xL6nmyn5knWghPzuL7JQQJMC0umjzafUbaG5J0XigjFSfeHuHYZXSJIH0Iz+VJtczBL6H58pLZAhTaVqKCmnYfoSWc4l6Tko/nscg8clvMtQPyOFUn/oRVCauJZcs+jeHJFLHOX1wFTW9MkEnyg0kP2EpitJ4+YVU/S8v1xqrW4H9MAAAAABJRU5ErkJggg=="
/***/ }),
/***/ "kSUc":
/*!***************************************************!*\
!*** ./src/components/markdown-editor/index.less ***!
\***************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/***/ "l2Kq":
/*!***********************************************!*\
!*** ./src/assets/images/forums/match_ad.jpg ***!
\***********************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/match_ad.24dc22fd.jpg";
/***/ }),
/***/ "lPiR":
/*!******************************************!*\
!*** ./node_modules/crypto-js/sha256.js ***!
\******************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"));
}
else {}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Initialization and round constants tables
var H = [];
var K = [];
// Compute constants
(function () {
function isPrime(n) {
var sqrtN = Math.sqrt(n);
for (var factor = 2; factor <= sqrtN; factor++) {
if (!(n % factor)) {
return false;
}
}
return true;
}
function getFractionalBits(n) {
return ((n - (n | 0)) * 0x100000000) | 0;
}
var n = 2;
var nPrime = 0;
while (nPrime < 64) {
if (isPrime(n)) {
if (nPrime < 8) {
H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
}
K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));
nPrime++;
}
n++;
}
}());
// Reusable object
var W = [];
/**
* SHA-256 hash algorithm.
*/
var SHA256 = C_algo.SHA256 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init(H.slice(0));
},
_doProcessBlock: function (M, offset) {
// Shortcut
var H = this._hash.words;
// Working variables
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
var f = H[5];
var g = H[6];
var h = H[7];
// Computation
for (var i = 0; i < 64; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var gamma0x = W[i - 15];
var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^
((gamma0x << 14) | (gamma0x >>> 18)) ^
(gamma0x >>> 3);
var gamma1x = W[i - 2];
var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^
((gamma1x << 13) | (gamma1x >>> 19)) ^
(gamma1x >>> 10);
W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
}
var ch = (e & f) ^ (~e & g);
var maj = (a & b) ^ (a & c) ^ (b & c);
var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));
var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25));
var t1 = h + sigma1 + ch + K[i] + W[i];
var t2 = sigma0 + maj;
h = g;
g = f;
f = e;
e = (d + t1) | 0;
d = c;
c = b;
b = a;
a = (t1 + t2) | 0;
}
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
H[4] = (H[4] + e) | 0;
H[5] = (H[5] + f) | 0;
H[6] = (H[6] + g) | 0;
H[7] = (H[7] + h) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Return final computed hash
return this._hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA256('message');
* var hash = CryptoJS.SHA256(wordArray);
*/
C.SHA256 = Hasher._createHelper(SHA256);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA256(message, key);
*/
C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
}(Math));
return CryptoJS.SHA256;
}));
/***/ }),
/***/ "lZu9":
/*!***********************************************************!*\
!*** ./node_modules/codemirror/mode/markdown/markdown.js ***!
\***********************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (true) // CommonJS
mod(__webpack_require__(/*! ../../lib/codemirror */ "VrN/"), __webpack_require__(/*! ../xml/xml */ "1eCo"), __webpack_require__(/*! ../meta */ "8EBN"));
else {}
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("markdown", function(cmCfg, modeCfg) {
var htmlMode = CodeMirror.getMode(cmCfg, "text/html");
var htmlModeMissing = htmlMode.name == "null"
function getMode(name) {
if (CodeMirror.findModeByName) {
var found = CodeMirror.findModeByName(name);
if (found) name = found.mime || found.mimes[0];
}
var mode = CodeMirror.getMode(cmCfg, name);
return mode.name == "null" ? null : mode;
}
// Should characters that affect highlighting be highlighted separate?
// Does not include characters that will be output (such as `1.` and `-` for lists)
if (modeCfg.highlightFormatting === undefined)
modeCfg.highlightFormatting = false;
// Maximum number of nested blockquotes. Set to 0 for infinite nesting.
// Excess `>` will emit `error` token.
if (modeCfg.maxBlockquoteDepth === undefined)
modeCfg.maxBlockquoteDepth = 0;
// Turn on task lists? ("- [ ] " and "- [x] ")
if (modeCfg.taskLists === undefined) modeCfg.taskLists = false;
// Turn on strikethrough syntax
if (modeCfg.strikethrough === undefined)
modeCfg.strikethrough = false;
if (modeCfg.emoji === undefined)
modeCfg.emoji = false;
if (modeCfg.fencedCodeBlockHighlighting === undefined)
modeCfg.fencedCodeBlockHighlighting = true;
if (modeCfg.fencedCodeBlockDefaultMode === undefined)
modeCfg.fencedCodeBlockDefaultMode = 'text/plain';
if (modeCfg.xml === undefined)
modeCfg.xml = true;
// Allow token types to be overridden by user-provided token types.
if (modeCfg.tokenTypeOverrides === undefined)
modeCfg.tokenTypeOverrides = {};
var tokenTypes = {
header: "header",
code: "comment",
quote: "quote",
list1: "variable-2",
list2: "variable-3",
list3: "keyword",
hr: "hr",
image: "image",
imageAltText: "image-alt-text",
imageMarker: "image-marker",
formatting: "formatting",
linkInline: "link",
linkEmail: "link",
linkText: "link",
linkHref: "string",
em: "em",
strong: "strong",
strikethrough: "strikethrough",
emoji: "builtin"
};
for (var tokenType in tokenTypes) {
if (tokenTypes.hasOwnProperty(tokenType) && modeCfg.tokenTypeOverrides[tokenType]) {
tokenTypes[tokenType] = modeCfg.tokenTypeOverrides[tokenType];
}
}
var hrRE = /^([*\-_])(?:\s*\1){2,}\s*$/
, listRE = /^(?:[*\-+]|^[0-9]+([.)]))\s+/
, taskListRE = /^\[(x| )\](?=\s)/i // Must follow listRE
, atxHeaderRE = modeCfg.allowAtxHeaderWithoutSpace ? /^(#+)/ : /^(#+)(?: |$)/
, setextHeaderRE = /^ {0,3}(?:\={1,}|-{2,})\s*$/
, textRE = /^[^#!\[\]*_\\<>` "'(~:]+/
, fencedCodeRE = /^(~~~+|```+)[ \t]*([\w\/+#-]*)[^\n`]*$/
, linkDefRE = /^\s*\[[^\]]+?\]:.*$/ // naive link-definition
, punctuation = /[!"#$%&'()*+,\-.\/:;<=>?@\[\\\]^_`{|}~\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0AF0\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E42\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC9\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDF3C-\uDF3E]|\uD809[\uDC70-\uDC74]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]/
, expandedTab = " " // CommonMark specifies tab as 4 spaces
function switchInline(stream, state, f) {
state.f = state.inline = f;
return f(stream, state);
}
function switchBlock(stream, state, f) {
state.f = state.block = f;
return f(stream, state);
}
function lineIsEmpty(line) {
return !line || !/\S/.test(line.string)
}
// Blocks
function blankLine(state) {
// Reset linkTitle state
state.linkTitle = false;
state.linkHref = false;
state.linkText = false;
// Reset EM state
state.em = false;
// Reset STRONG state
state.strong = false;
// Reset strikethrough state
state.strikethrough = false;
// Reset state.quote
state.quote = 0;
// Reset state.indentedCode
state.indentedCode = false;
if (state.f == htmlBlock) {
var exit = htmlModeMissing
if (!exit) {
var inner = CodeMirror.innerMode(htmlMode, state.htmlState)
exit = inner.mode.name == "xml" && inner.state.tagStart === null &&
(!inner.state.context && inner.state.tokenize.isInText)
}
if (exit) {
state.f = inlineNormal;
state.block = blockNormal;
state.htmlState = null;
}
}
// Reset state.trailingSpace
state.trailingSpace = 0;
state.trailingSpaceNewLine = false;
// Mark this line as blank
state.prevLine = state.thisLine
state.thisLine = {stream: null}
return null;
}
function blockNormal(stream, state) {
var firstTokenOnLine = stream.column() === state.indentation;
var prevLineLineIsEmpty = lineIsEmpty(state.prevLine.stream);
var prevLineIsIndentedCode = state.indentedCode;
var prevLineIsHr = state.prevLine.hr;
var prevLineIsList = state.list !== false;
var maxNonCodeIndentation = (state.listStack[state.listStack.length - 1] || 0) + 3;
state.indentedCode = false;
var lineIndentation = state.indentation;
// compute once per line (on first token)
if (state.indentationDiff === null) {
state.indentationDiff = state.indentation;
if (prevLineIsList) {
state.list = null;
// While this list item's marker's indentation is less than the deepest
// list item's content's indentation,pop the deepest list item
// indentation off the stack, and update block indentation state
while (lineIndentation < state.listStack[state.listStack.length - 1]) {
state.listStack.pop();
if (state.listStack.length) {
state.indentation = state.listStack[state.listStack.length - 1];
// less than the first list's indent -> the line is no longer a list
} else {
state.list = false;
}
}
if (state.list !== false) {
state.indentationDiff = lineIndentation - state.listStack[state.listStack.length - 1]
}
}
}
// not comprehensive (currently only for setext detection purposes)
var allowsInlineContinuation = (
!prevLineLineIsEmpty && !prevLineIsHr && !state.prevLine.header &&
(!prevLineIsList || !prevLineIsIndentedCode) &&
!state.prevLine.fencedCodeEnd
);
var isHr = (state.list === false || prevLineIsHr || prevLineLineIsEmpty) &&
state.indentation <= maxNonCodeIndentation && stream.match(hrRE);
var match = null;
if (state.indentationDiff >= 4 && (prevLineIsIndentedCode || state.prevLine.fencedCodeEnd ||
state.prevLine.header || prevLineLineIsEmpty)) {
stream.skipToEnd();
state.indentedCode = true;
return tokenTypes.code;
} else if (stream.eatSpace()) {
return null;
} else if (firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(atxHeaderRE)) && match[1].length <= 6) {
state.quote = 0;
state.header = match[1].length;
state.thisLine.header = true;
if (modeCfg.highlightFormatting) state.formatting = "header";
state.f = state.inline;
return getType(state);
} else if (state.indentation <= maxNonCodeIndentation && stream.eat('>')) {
state.quote = firstTokenOnLine ? 1 : state.quote + 1;
if (modeCfg.highlightFormatting) state.formatting = "quote";
stream.eatSpace();
return getType(state);
} else if (!isHr && !state.setext && firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(listRE))) {
var listType = match[1] ? "ol" : "ul";
state.indentation = lineIndentation + stream.current().length;
state.list = true;
state.quote = 0;
// Add this list item's content's indentation to the stack
state.listStack.push(state.indentation);
// Reset inline styles which shouldn't propagate aross list items
state.em = false;
state.strong = false;
state.code = false;
state.strikethrough = false;
if (modeCfg.taskLists && stream.match(taskListRE, false)) {
state.taskList = true;
}
state.f = state.inline;
if (modeCfg.highlightFormatting) state.formatting = ["list", "list-" + listType];
return getType(state);
} else if (firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(fencedCodeRE, true))) {
state.quote = 0;
state.fencedEndRE = new RegExp(match[1] + "+ *$");
// try switching mode
state.localMode = modeCfg.fencedCodeBlockHighlighting && getMode(match[2] || modeCfg.fencedCodeBlockDefaultMode );
if (state.localMode) state.localState = CodeMirror.startState(state.localMode);
state.f = state.block = local;
if (modeCfg.highlightFormatting) state.formatting = "code-block";
state.code = -1
return getType(state);
// SETEXT has lowest block-scope precedence after HR, so check it after
// the others (code, blockquote, list...)
} else if (
// if setext set, indicates line after ---/===
state.setext || (
// line before ---/===
(!allowsInlineContinuation || !prevLineIsList) && !state.quote && state.list === false &&
!state.code && !isHr && !linkDefRE.test(stream.string) &&
(match = stream.lookAhead(1)) && (match = match.match(setextHeaderRE))
)
) {
if ( !state.setext ) {
state.header = match[0].charAt(0) == '=' ? 1 : 2;
state.setext = state.header;
} else {
state.header = state.setext;
// has no effect on type so we can reset it now
state.setext = 0;
stream.skipToEnd();
if (modeCfg.highlightFormatting) state.formatting = "header";
}
state.thisLine.header = true;
state.f = state.inline;
return getType(state);
} else if (isHr) {
stream.skipToEnd();
state.hr = true;
state.thisLine.hr = true;
return tokenTypes.hr;
} else if (stream.peek() === '[') {
return switchInline(stream, state, footnoteLink);
}
return switchInline(stream, state, state.inline);
}
function htmlBlock(stream, state) {
var style = htmlMode.token(stream, state.htmlState);
if (!htmlModeMissing) {
var inner = CodeMirror.innerMode(htmlMode, state.htmlState)
if ((inner.mode.name == "xml" && inner.state.tagStart === null &&
(!inner.state.context && inner.state.tokenize.isInText)) ||
(state.md_inside && stream.current().indexOf(">") > -1)) {
state.f = inlineNormal;
state.block = blockNormal;
state.htmlState = null;
}
}
return style;
}
function local(stream, state) {
var currListInd = state.listStack[state.listStack.length - 1] || 0;
var hasExitedList = state.indentation < currListInd;
var maxFencedEndInd = currListInd + 3;
if (state.fencedEndRE && state.indentation <= maxFencedEndInd && (hasExitedList || stream.match(state.fencedEndRE))) {
if (modeCfg.highlightFormatting) state.formatting = "code-block";
var returnType;
if (!hasExitedList) returnType = getType(state)
state.localMode = state.localState = null;
state.block = blockNormal;
state.f = inlineNormal;
state.fencedEndRE = null;
state.code = 0
state.thisLine.fencedCodeEnd = true;
if (hasExitedList) return switchBlock(stream, state, state.block);
return returnType;
} else if (state.localMode) {
return state.localMode.token(stream, state.localState);
} else {
stream.skipToEnd();
return tokenTypes.code;
}
}
// Inline
function getType(state) {
var styles = [];
if (state.formatting) {
styles.push(tokenTypes.formatting);
if (typeof state.formatting === "string") state.formatting = [state.formatting];
for (var i = 0; i < state.formatting.length; i++) {
styles.push(tokenTypes.formatting + "-" + state.formatting[i]);
if (state.formatting[i] === "header") {
styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.header);
}
// Add `formatting-quote` and `formatting-quote-#` for blockquotes
// Add `error` instead if the maximum blockquote nesting depth is passed
if (state.formatting[i] === "quote") {
if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) {
styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.quote);
} else {
styles.push("error");
}
}
}
}
if (state.taskOpen) {
styles.push("meta");
return styles.length ? styles.join(' ') : null;
}
if (state.taskClosed) {
styles.push("property");
return styles.length ? styles.join(' ') : null;
}
if (state.linkHref) {
styles.push(tokenTypes.linkHref, "url");
} else { // Only apply inline styles to non-url text
if (state.strong) { styles.push(tokenTypes.strong); }
if (state.em) { styles.push(tokenTypes.em); }
if (state.strikethrough) { styles.push(tokenTypes.strikethrough); }
if (state.emoji) { styles.push(tokenTypes.emoji); }
if (state.linkText) { styles.push(tokenTypes.linkText); }
if (state.code) { styles.push(tokenTypes.code); }
if (state.image) { styles.push(tokenTypes.image); }
if (state.imageAltText) { styles.push(tokenTypes.imageAltText, "link"); }
if (state.imageMarker) { styles.push(tokenTypes.imageMarker); }
}
if (state.header) { styles.push(tokenTypes.header, tokenTypes.header + "-" + state.header); }
if (state.quote) {
styles.push(tokenTypes.quote);
// Add `quote-#` where the maximum for `#` is modeCfg.maxBlockquoteDepth
if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) {
styles.push(tokenTypes.quote + "-" + state.quote);
} else {
styles.push(tokenTypes.quote + "-" + modeCfg.maxBlockquoteDepth);
}
}
if (state.list !== false) {
var listMod = (state.listStack.length - 1) % 3;
if (!listMod) {
styles.push(tokenTypes.list1);
} else if (listMod === 1) {
styles.push(tokenTypes.list2);
} else {
styles.push(tokenTypes.list3);
}
}
if (state.trailingSpaceNewLine) {
styles.push("trailing-space-new-line");
} else if (state.trailingSpace) {
styles.push("trailing-space-" + (state.trailingSpace % 2 ? "a" : "b"));
}
return styles.length ? styles.join(' ') : null;
}
function handleText(stream, state) {
if (stream.match(textRE, true)) {
return getType(state);
}
return undefined;
}
function inlineNormal(stream, state) {
var style = state.text(stream, state);
if (typeof style !== 'undefined')
return style;
if (state.list) { // List marker (*, +, -, 1., etc)
state.list = null;
return getType(state);
}
if (state.taskList) {
var taskOpen = stream.match(taskListRE, true)[1] === " ";
if (taskOpen) state.taskOpen = true;
else state.taskClosed = true;
if (modeCfg.highlightFormatting) state.formatting = "task";
state.taskList = false;
return getType(state);
}
state.taskOpen = false;
state.taskClosed = false;
if (state.header && stream.match(/^#+$/, true)) {
if (modeCfg.highlightFormatting) state.formatting = "header";
return getType(state);
}
var ch = stream.next();
// Matches link titles present on next line
if (state.linkTitle) {
state.linkTitle = false;
var matchCh = ch;
if (ch === '(') {
matchCh = ')';
}
matchCh = (matchCh+'').replace(/([.?*+^\[\]\\(){}|-])/g, "\\$1");
var regex = '^\\s*(?:[^' + matchCh + '\\\\]+|\\\\\\\\|\\\\.)' + matchCh;
if (stream.match(new RegExp(regex), true)) {
return tokenTypes.linkHref;
}
}
// If this block is changed, it may need to be updated in GFM mode
if (ch === '`') {
var previousFormatting = state.formatting;
if (modeCfg.highlightFormatting) state.formatting = "code";
stream.eatWhile('`');
var count = stream.current().length
if (state.code == 0 && (!state.quote || count == 1)) {
state.code = count
return getType(state)
} else if (count == state.code) { // Must be exact
var t = getType(state)
state.code = 0
return t
} else {
state.formatting = previousFormatting
return getType(state)
}
} else if (state.code) {
return getType(state);
}
if (ch === '\\') {
stream.next();
if (modeCfg.highlightFormatting) {
var type = getType(state);
var formattingEscape = tokenTypes.formatting + "-escape";
return type ? type + " " + formattingEscape : formattingEscape;
}
}
if (ch === '!' && stream.match(/\[[^\]]*\] ?(?:\(|\[)/, false)) {
state.imageMarker = true;
state.image = true;
if (modeCfg.highlightFormatting) state.formatting = "image";
return getType(state);
}
if (ch === '[' && state.imageMarker && stream.match(/[^\]]*\](\(.*?\)| ?\[.*?\])/, false)) {
state.imageMarker = false;
state.imageAltText = true
if (modeCfg.highlightFormatting) state.formatting = "image";
return getType(state);
}
if (ch === ']' && state.imageAltText) {
if (modeCfg.highlightFormatting) state.formatting = "image";
var type = getType(state);
state.imageAltText = false;
state.image = false;
state.inline = state.f = linkHref;
return type;
}
if (ch === '[' && !state.image) {
if (state.linkText && stream.match(/^.*?\]/)) return getType(state)
state.linkText = true;
if (modeCfg.highlightFormatting) state.formatting = "link";
return getType(state);
}
if (ch === ']' && state.linkText) {
if (modeCfg.highlightFormatting) state.formatting = "link";
var type = getType(state);
state.linkText = false;
state.inline = state.f = stream.match(/\(.*?\)| ?\[.*?\]/, false) ? linkHref : inlineNormal
return type;
}
if (ch === '<' && stream.match(/^(https?|ftps?):\/\/(?:[^\\>]|\\.)+>/, false)) {
state.f = state.inline = linkInline;
if (modeCfg.highlightFormatting) state.formatting = "link";
var type = getType(state);
if (type){
type += " ";
} else {
type = "";
}
return type + tokenTypes.linkInline;
}
if (ch === '<' && stream.match(/^[^> \\]+@(?:[^\\>]|\\.)+>/, false)) {
state.f = state.inline = linkInline;
if (modeCfg.highlightFormatting) state.formatting = "link";
var type = getType(state);
if (type){
type += " ";
} else {
type = "";
}
return type + tokenTypes.linkEmail;
}
if (modeCfg.xml && ch === '<' && stream.match(/^(!--|\?|!\[CDATA\[|[a-z][a-z0-9-]*(?:\s+[a-z_:.\-]+(?:\s*=\s*[^>]+)?)*\s*(?:>|$))/i, false)) {
var end = stream.string.indexOf(">", stream.pos);
if (end != -1) {
var atts = stream.string.substring(stream.start, end);
if (/markdown\s*=\s*('|"){0,1}1('|"){0,1}/.test(atts)) state.md_inside = true;
}
stream.backUp(1);
state.htmlState = CodeMirror.startState(htmlMode);
return switchBlock(stream, state, htmlBlock);
}
if (modeCfg.xml && ch === '<' && stream.match(/^\/\w*?>/)) {
state.md_inside = false;
return "tag";
} else if (ch === "*" || ch === "_") {
var len = 1, before = stream.pos == 1 ? " " : stream.string.charAt(stream.pos - 2)
while (len < 3 && stream.eat(ch)) len++
var after = stream.peek() || " "
// See http://spec.commonmark.org/0.27/#emphasis-and-strong-emphasis
var leftFlanking = !/\s/.test(after) && (!punctuation.test(after) || /\s/.test(before) || punctuation.test(before))
var rightFlanking = !/\s/.test(before) && (!punctuation.test(before) || /\s/.test(after) || punctuation.test(after))
var setEm = null, setStrong = null
if (len % 2) { // Em
if (!state.em && leftFlanking && (ch === "*" || !rightFlanking || punctuation.test(before)))
setEm = true
else if (state.em == ch && rightFlanking && (ch === "*" || !leftFlanking || punctuation.test(after)))
setEm = false
}
if (len > 1) { // Strong
if (!state.strong && leftFlanking && (ch === "*" || !rightFlanking || punctuation.test(before)))
setStrong = true
else if (state.strong == ch && rightFlanking && (ch === "*" || !leftFlanking || punctuation.test(after)))
setStrong = false
}
if (setStrong != null || setEm != null) {
if (modeCfg.highlightFormatting) state.formatting = setEm == null ? "strong" : setStrong == null ? "em" : "strong em"
if (setEm === true) state.em = ch
if (setStrong === true) state.strong = ch
var t = getType(state)
if (setEm === false) state.em = false
if (setStrong === false) state.strong = false
return t
}
} else if (ch === ' ') {
if (stream.eat('*') || stream.eat('_')) { // Probably surrounded by spaces
if (stream.peek() === ' ') { // Surrounded by spaces, ignore
return getType(state);
} else { // Not surrounded by spaces, back up pointer
stream.backUp(1);
}
}
}
if (modeCfg.strikethrough) {
if (ch === '~' && stream.eatWhile(ch)) {
if (state.strikethrough) {// Remove strikethrough
if (modeCfg.highlightFormatting) state.formatting = "strikethrough";
var t = getType(state);
state.strikethrough = false;
return t;
} else if (stream.match(/^[^\s]/, false)) {// Add strikethrough
state.strikethrough = true;
if (modeCfg.highlightFormatting) state.formatting = "strikethrough";
return getType(state);
}
} else if (ch === ' ') {
if (stream.match(/^~~/, true)) { // Probably surrounded by space
if (stream.peek() === ' ') { // Surrounded by spaces, ignore
return getType(state);
} else { // Not surrounded by spaces, back up pointer
stream.backUp(2);
}
}
}
}
if (modeCfg.emoji && ch === ":" && stream.match(/^(?:[a-z_\d+][a-z_\d+-]*|\-[a-z_\d+][a-z_\d+-]*):/)) {
state.emoji = true;
if (modeCfg.highlightFormatting) state.formatting = "emoji";
var retType = getType(state);
state.emoji = false;
return retType;
}
if (ch === ' ') {
if (stream.match(/^ +$/, false)) {
state.trailingSpace++;
} else if (state.trailingSpace) {
state.trailingSpaceNewLine = true;
}
}
return getType(state);
}
function linkInline(stream, state) {
var ch = stream.next();
if (ch === ">") {
state.f = state.inline = inlineNormal;
if (modeCfg.highlightFormatting) state.formatting = "link";
var type = getType(state);
if (type){
type += " ";
} else {
type = "";
}
return type + tokenTypes.linkInline;
}
stream.match(/^[^>]+/, true);
return tokenTypes.linkInline;
}
function linkHref(stream, state) {
// Check if space, and return NULL if so (to avoid marking the space)
if(stream.eatSpace()){
return null;
}
var ch = stream.next();
if (ch === '(' || ch === '[') {
state.f = state.inline = getLinkHrefInside(ch === "(" ? ")" : "]");
if (modeCfg.highlightFormatting) state.formatting = "link-string";
state.linkHref = true;
return getType(state);
}
return 'error';
}
var linkRE = {
")": /^(?:[^\\\(\)]|\\.|\((?:[^\\\(\)]|\\.)*\))*?(?=\))/,
"]": /^(?:[^\\\[\]]|\\.|\[(?:[^\\\[\]]|\\.)*\])*?(?=\])/
}
function getLinkHrefInside(endChar) {
return function(stream, state) {
var ch = stream.next();
if (ch === endChar) {
state.f = state.inline = inlineNormal;
if (modeCfg.highlightFormatting) state.formatting = "link-string";
var returnState = getType(state);
state.linkHref = false;
return returnState;
}
stream.match(linkRE[endChar])
state.linkHref = true;
return getType(state);
};
}
function footnoteLink(stream, state) {
if (stream.match(/^([^\]\\]|\\.)*\]:/, false)) {
state.f = footnoteLinkInside;
stream.next(); // Consume [
if (modeCfg.highlightFormatting) state.formatting = "link";
state.linkText = true;
return getType(state);
}
return switchInline(stream, state, inlineNormal);
}
function footnoteLinkInside(stream, state) {
if (stream.match(/^\]:/, true)) {
state.f = state.inline = footnoteUrl;
if (modeCfg.highlightFormatting) state.formatting = "link";
var returnType = getType(state);
state.linkText = false;
return returnType;
}
stream.match(/^([^\]\\]|\\.)+/, true);
return tokenTypes.linkText;
}
function footnoteUrl(stream, state) {
// Check if space, and return NULL if so (to avoid marking the space)
if(stream.eatSpace()){
return null;
}
// Match URL
stream.match(/^[^\s]+/, true);
// Check for link title
if (stream.peek() === undefined) { // End of line, set flag to check next line
state.linkTitle = true;
} else { // More content on line, check if link title
stream.match(/^(?:\s+(?:"(?:[^"\\]|\\\\|\\.)+"|'(?:[^'\\]|\\\\|\\.)+'|\((?:[^)\\]|\\\\|\\.)+\)))?/, true);
}
state.f = state.inline = inlineNormal;
return tokenTypes.linkHref + " url";
}
var mode = {
startState: function() {
return {
f: blockNormal,
prevLine: {stream: null},
thisLine: {stream: null},
block: blockNormal,
htmlState: null,
indentation: 0,
inline: inlineNormal,
text: handleText,
formatting: false,
linkText: false,
linkHref: false,
linkTitle: false,
code: 0,
em: false,
strong: false,
header: 0,
setext: 0,
hr: false,
taskList: false,
list: false,
listStack: [],
quote: 0,
trailingSpace: 0,
trailingSpaceNewLine: false,
strikethrough: false,
emoji: false,
fencedEndRE: null
};
},
copyState: function(s) {
return {
f: s.f,
prevLine: s.prevLine,
thisLine: s.thisLine,
block: s.block,
htmlState: s.htmlState && CodeMirror.copyState(htmlMode, s.htmlState),
indentation: s.indentation,
localMode: s.localMode,
localState: s.localMode ? CodeMirror.copyState(s.localMode, s.localState) : null,
inline: s.inline,
text: s.text,
formatting: false,
linkText: s.linkText,
linkTitle: s.linkTitle,
linkHref: s.linkHref,
code: s.code,
em: s.em,
strong: s.strong,
strikethrough: s.strikethrough,
emoji: s.emoji,
header: s.header,
setext: s.setext,
hr: s.hr,
taskList: s.taskList,
list: s.list,
listStack: s.listStack.slice(0),
quote: s.quote,
indentedCode: s.indentedCode,
trailingSpace: s.trailingSpace,
trailingSpaceNewLine: s.trailingSpaceNewLine,
md_inside: s.md_inside,
fencedEndRE: s.fencedEndRE
};
},
token: function(stream, state) {
// Reset state.formatting
state.formatting = false;
if (stream != state.thisLine.stream) {
state.header = 0;
state.hr = false;
if (stream.match(/^\s*$/, true)) {
blankLine(state);
return null;
}
state.prevLine = state.thisLine
state.thisLine = {stream: stream}
// Reset state.taskList
state.taskList = false;
// Reset state.trailingSpace
state.trailingSpace = 0;
state.trailingSpaceNewLine = false;
if (!state.localState) {
state.f = state.block;
if (state.f != htmlBlock) {
var indentation = stream.match(/^\s*/, true)[0].replace(/\t/g, expandedTab).length;
state.indentation = indentation;
state.indentationDiff = null;
if (indentation > 0) return null;
}
}
}
return state.f(stream, state);
},
innerMode: function(state) {
if (state.block == htmlBlock) return {state: state.htmlState, mode: htmlMode};
if (state.localState) return {state: state.localState, mode: state.localMode};
return {state: state, mode: mode};
},
indent: function(state, textAfter, line) {
if (state.block == htmlBlock && htmlMode.indent) return htmlMode.indent(state.htmlState, textAfter, line)
if (state.localState && state.localMode.indent) return state.localMode.indent(state.localState, textAfter, line)
return CodeMirror.Pass
},
blankLine: blankLine,
getType: getType,
blockCommentStart: "<!--",
blockCommentEnd: "-->",
closeBrackets: "()[]{}''\"\"``",
fold: "markdown"
};
return mode;
}, "xml");
CodeMirror.defineMIME("text/markdown", "markdown");
CodeMirror.defineMIME("text/x-markdown", "markdown");
});
/***/ }),
/***/ "lnY3":
/*!****************************************************!*\
!*** ./node_modules/antd/es/card/style/index.less ***!
\****************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/***/ "lzim":
/*!********************************************!*\
!*** ./src/components/ImagesIcon/index.ts ***!
\********************************************/
/*! exports provided: qrCode, searchIcon, search1Icon, noDataIcon, smallProgramIcon, anonyIcon, errIcon, chromeIcon, firefoxIcon, exportExerciseTemplate, txLiveIcon, blibliIcon, douyuIcon, weibaitongIcon, zoomIcon, groups1Icon, groups2Icon, groups3Icon, matchAdIcon, hbIcon, lockcloseIcon, teacherQQIcon, emptyIcon, charpterWhiteIcon, mainbannerBg, certificateIcon, chooseIcon, emptyIcon2, repositoryNoneDataIcon, questionIcon, noticeIcon, qrCodeIcon, done1Icon, done2Icon, done3Icon, UserQrCode */
/*! exports used: certificateIcon, mainbannerBg, teacherQQIcon */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _assets_images_icons_search_png__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @/assets/images/icons/search.png */ "E7E6");
/* harmony import */ var _assets_images_icons_search_png__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_assets_images_icons_search_png__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _assets_images_icons_search1_png__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @/assets/images/icons/search1.png */ "/GNS");
/* harmony import */ var _assets_images_icons_search1_png__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_assets_images_icons_search1_png__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _assets_images_icons_nodata_png__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @/assets/images/icons/nodata.png */ "FOrL");
/* harmony import */ var _assets_images_icons_nodata_png__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_assets_images_icons_nodata_png__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _assets_images_classrooms_small_program_png__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @/assets/images/classrooms/small_program.png */ "HpTS");
/* harmony import */ var _assets_images_classrooms_small_program_png__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_assets_images_classrooms_small_program_png__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _assets_images_icons_anony_png__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @/assets/images/icons/anony.png */ "tWlo");
/* harmony import */ var _assets_images_icons_anony_png__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_assets_images_icons_anony_png__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _assets_images_classrooms_err_png__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/assets/images/classrooms/err.png */ "7ZXX");
/* harmony import */ var _assets_images_classrooms_err_png__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_assets_images_classrooms_err_png__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _assets_images_icons_chrome_png__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @/assets/images/icons/chrome.png */ "GABl");
/* harmony import */ var _assets_images_icons_chrome_png__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_assets_images_icons_chrome_png__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _assets_images_icons_firefox_png__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @/assets/images/icons/firefox.png */ "onxn");
/* harmony import */ var _assets_images_icons_firefox_png__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_assets_images_icons_firefox_png__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _assets_images_classrooms_export_exercise_template_png__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/assets/images/classrooms/export_exercise-template.png */ "nKGa");
/* harmony import */ var _assets_images_classrooms_export_exercise_template_png__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_assets_images_classrooms_export_exercise_template_png__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _assets_images_icons_tx_live_png__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @/assets/images/icons/tx-live.png */ "4qgm");
/* harmony import */ var _assets_images_icons_tx_live_png__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_assets_images_icons_tx_live_png__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _assets_images_icons_blibli_png__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @/assets/images/icons/blibli.png */ "JeFH");
/* harmony import */ var _assets_images_icons_blibli_png__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_assets_images_icons_blibli_png__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _assets_images_icons_douyu_jpg__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @/assets/images/icons/douyu.jpg */ "ji0R");
/* harmony import */ var _assets_images_icons_douyu_jpg__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_assets_images_icons_douyu_jpg__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _assets_images_icons_weibaitong_png__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @/assets/images/icons/weibaitong.png */ "W6BS");
/* harmony import */ var _assets_images_icons_weibaitong_png__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_assets_images_icons_weibaitong_png__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var _assets_images_icons_zoom_png__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! @/assets/images/icons/zoom.png */ "kPYp");
/* harmony import */ var _assets_images_icons_zoom_png__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(_assets_images_icons_zoom_png__WEBPACK_IMPORTED_MODULE_13__);
/* harmony import */ var _assets_images_icons_groups1_png__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! @/assets/images/icons/groups1.png */ "nukY");
/* harmony import */ var _assets_images_icons_groups1_png__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_assets_images_icons_groups1_png__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _assets_images_icons_groups2_png__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! @/assets/images/icons/groups2.png */ "4u4S");
/* harmony import */ var _assets_images_icons_groups2_png__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_assets_images_icons_groups2_png__WEBPACK_IMPORTED_MODULE_15__);
/* harmony import */ var _assets_images_icons_groups3_png__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! @/assets/images/icons/groups3.png */ "yslc");
/* harmony import */ var _assets_images_icons_groups3_png__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(_assets_images_icons_groups3_png__WEBPACK_IMPORTED_MODULE_16__);
/* harmony import */ var _assets_images_forums_match_ad_jpg__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! @/assets/images/forums/match_ad.jpg */ "l2Kq");
/* harmony import */ var _assets_images_forums_match_ad_jpg__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_assets_images_forums_match_ad_jpg__WEBPACK_IMPORTED_MODULE_17__);
/* harmony import */ var _assets_images_hb_png__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! @/assets/images/hb.png */ "RMFE");
/* harmony import */ var _assets_images_hb_png__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(_assets_images_hb_png__WEBPACK_IMPORTED_MODULE_18__);
/* harmony import */ var _assets_images_icons_lockclose_svg__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! @/assets/images/icons/lockclose.svg */ "TGq3");
/* harmony import */ var _assets_images_icons_lockclose_svg__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(_assets_images_icons_lockclose_svg__WEBPACK_IMPORTED_MODULE_19__);
/* harmony import */ var _assets_images_teacherQQ_png__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! @/assets/images/teacherQQ.png */ "SMhR");
/* harmony import */ var _assets_images_teacherQQ_png__WEBPACK_IMPORTED_MODULE_20___default = /*#__PURE__*/__webpack_require__.n(_assets_images_teacherQQ_png__WEBPACK_IMPORTED_MODULE_20__);
/* harmony reexport (default from non-harmony) */ __webpack_require__.d(__webpack_exports__, "c", function() { return _assets_images_teacherQQ_png__WEBPACK_IMPORTED_MODULE_20___default.a; });
/* harmony import */ var _assets_images_empty_png__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! @/assets/images/empty.png */ "8/bI");
/* harmony import */ var _assets_images_empty_png__WEBPACK_IMPORTED_MODULE_21___default = /*#__PURE__*/__webpack_require__.n(_assets_images_empty_png__WEBPACK_IMPORTED_MODULE_21__);
/* harmony import */ var _assets_images_icons_charpter_white_svg__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! @/assets/images/icons/charpter-white.svg */ "JWDV");
/* harmony import */ var _assets_images_icons_charpter_white_svg__WEBPACK_IMPORTED_MODULE_22___default = /*#__PURE__*/__webpack_require__.n(_assets_images_icons_charpter_white_svg__WEBPACK_IMPORTED_MODULE_22__);
/* harmony import */ var _assets_images_banner_mainbanner_jpg__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! @/assets/images/banner/mainbanner.jpg */ "Xsq0");
/* harmony import */ var _assets_images_banner_mainbanner_jpg__WEBPACK_IMPORTED_MODULE_23___default = /*#__PURE__*/__webpack_require__.n(_assets_images_banner_mainbanner_jpg__WEBPACK_IMPORTED_MODULE_23__);
/* harmony reexport (default from non-harmony) */ __webpack_require__.d(__webpack_exports__, "b", function() { return _assets_images_banner_mainbanner_jpg__WEBPACK_IMPORTED_MODULE_23___default.a; });
/* harmony import */ var _assets_images_certificate_jpg__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! @/assets/images/certificate.jpg */ "Ohmc");
/* harmony import */ var _assets_images_certificate_jpg__WEBPACK_IMPORTED_MODULE_24___default = /*#__PURE__*/__webpack_require__.n(_assets_images_certificate_jpg__WEBPACK_IMPORTED_MODULE_24__);
/* harmony reexport (default from non-harmony) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _assets_images_certificate_jpg__WEBPACK_IMPORTED_MODULE_24___default.a; });
/* harmony import */ var _assets_images_icons_choose_svg__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! @/assets/images/icons/choose.svg */ "csWT");
/* harmony import */ var _assets_images_icons_choose_svg__WEBPACK_IMPORTED_MODULE_25___default = /*#__PURE__*/__webpack_require__.n(_assets_images_icons_choose_svg__WEBPACK_IMPORTED_MODULE_25__);
/* harmony import */ var _assets_images_empty2_png__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! @/assets/images/empty2.png */ "7v3h");
/* harmony import */ var _assets_images_empty2_png__WEBPACK_IMPORTED_MODULE_26___default = /*#__PURE__*/__webpack_require__.n(_assets_images_empty2_png__WEBPACK_IMPORTED_MODULE_26__);
/* harmony import */ var _assets_images_RepositoryNoneData_png__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! @/assets/images/RepositoryNoneData.png */ "cRFk");
/* harmony import */ var _assets_images_RepositoryNoneData_png__WEBPACK_IMPORTED_MODULE_27___default = /*#__PURE__*/__webpack_require__.n(_assets_images_RepositoryNoneData_png__WEBPACK_IMPORTED_MODULE_27__);
/* harmony import */ var _assets_images_question_gif__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! @/assets/images/question.gif */ "kPWJ");
/* harmony import */ var _assets_images_question_gif__WEBPACK_IMPORTED_MODULE_28___default = /*#__PURE__*/__webpack_require__.n(_assets_images_question_gif__WEBPACK_IMPORTED_MODULE_28__);
/* harmony import */ var _assets_images_notice_gif__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! @/assets/images/notice.gif */ "qgvg");
/* harmony import */ var _assets_images_notice_gif__WEBPACK_IMPORTED_MODULE_29___default = /*#__PURE__*/__webpack_require__.n(_assets_images_notice_gif__WEBPACK_IMPORTED_MODULE_29__);
/* harmony import */ var _assets_images_qrCode_png__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! @/assets/images/qrCode.png */ "FPkq");
/* harmony import */ var _assets_images_qrCode_png__WEBPACK_IMPORTED_MODULE_30___default = /*#__PURE__*/__webpack_require__.n(_assets_images_qrCode_png__WEBPACK_IMPORTED_MODULE_30__);
/* harmony import */ var _assets_images_icons_done1_png__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! @/assets/images/icons/done1.png */ "A/g1");
/* harmony import */ var _assets_images_icons_done1_png__WEBPACK_IMPORTED_MODULE_31___default = /*#__PURE__*/__webpack_require__.n(_assets_images_icons_done1_png__WEBPACK_IMPORTED_MODULE_31__);
/* harmony import */ var _assets_images_icons_done2_png__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! @/assets/images/icons/done2.png */ "Nmxd");
/* harmony import */ var _assets_images_icons_done2_png__WEBPACK_IMPORTED_MODULE_32___default = /*#__PURE__*/__webpack_require__.n(_assets_images_icons_done2_png__WEBPACK_IMPORTED_MODULE_32__);
/* harmony import */ var _assets_images_icons_done3_png__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! @/assets/images/icons/done3.png */ "5D2P");
/* harmony import */ var _assets_images_icons_done3_png__WEBPACK_IMPORTED_MODULE_33___default = /*#__PURE__*/__webpack_require__.n(_assets_images_icons_done3_png__WEBPACK_IMPORTED_MODULE_33__);
/* harmony import */ var _assets_images_icons_qrCode_png__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! @/assets/images/icons/qrCode.png */ "djh8");
/* harmony import */ var _assets_images_icons_qrCode_png__WEBPACK_IMPORTED_MODULE_34___default = /*#__PURE__*/__webpack_require__.n(_assets_images_icons_qrCode_png__WEBPACK_IMPORTED_MODULE_34__);
/* harmony import */ var _assets_images_user_qrcode_png__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! @/assets/images/user/qrcode.png */ "Jq4h");
/* harmony import */ var _assets_images_user_qrcode_png__WEBPACK_IMPORTED_MODULE_35___default = /*#__PURE__*/__webpack_require__.n(_assets_images_user_qrcode_png__WEBPACK_IMPORTED_MODULE_35__);
// import x from '';
// import x from '';
// import x from '';
// import x from '';
// import x from '';
/***/ }),
/***/ "mOS8":
/*!*****************************************!*\
!*** ./src/assets/images/403Qrcode.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/403Qrcode.6c17b6f4.png";
/***/ }),
/***/ "mxV5":
/*!*****************************************************!*\
!*** ./node_modules/ali-oss/dist/aliyun-oss-sdk.js ***!
\*****************************************************/
/*! no static exports found */
/*! exports used: default */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {var require;var require;// Aliyun OSS SDK for JavaScript v6.10.0
// Copyright Aliyun.com, Inc. or its affiliates. All Rights Reserved.
// License at https://github.com/ali-sdk/ali-oss/blob/master/LICENSE
(function(f){if(true){module.exports=f()}else { var g; }})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return require(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
'use strict';
var OSS = require('./browser/client');
OSS.Buffer = require('buffer').Buffer;
OSS.urllib = require('../shims/xhr');
OSS.version = require('./browser/version').version;
module.exports = OSS;
},{"../shims/xhr":291,"./browser/client":2,"./browser/version":5,"buffer":73}],2:[function(require,module,exports){
(function (Buffer,process){
'use strict';
var _promise = require('babel-runtime/core-js/promise');
var _promise2 = _interopRequireDefault(_promise);
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _assign = require('babel-runtime/core-js/object/assign');
var _assign2 = _interopRequireDefault(_assign);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var debug = require('debug')('ali-oss');
var copy = require('copy-to');
var xml = require('xml2js');
var AgentKeepalive = require('agentkeepalive');
var merge = require('merge-descriptors');
var urlutil = require('url');
var is = require('is-type-of');
var platform = require('platform');
var utility = require('utility');
var urllib = require('urllib');
var pkg = require('./version');
var bowser = require('bowser');
var signUtils = require('../common/signUtils');
var _require = require('../common/utils/isIP'),
_isIP = _require.isIP;
var _initOptions = require('../common/client/initOptions');
var _require2 = require('../common/utils/createRequest'),
createRequest = _require2.createRequest;
var globalHttpAgent = new AgentKeepalive();
function _unSupportBrowserTip() {
var name = platform.name,
version = platform.version;
if (name && name.toLowerCase && name.toLowerCase() === 'ie' && version.split('.')[0] < 10) {
// eslint-disable-next-line no-console
console.warn('ali-oss does not support the current browser');
}
}
// check local web protocol,if https secure default set true , if http secure default set false
function isHttpsWebProtocol() {
// for web worker not use window.location.
// eslint-disable-next-line no-restricted-globals
return location && location.protocol === 'https:';
}
function Client(options, ctx) {
_unSupportBrowserTip();
if (!(this instanceof Client)) {
return new Client(options, ctx);
}
if (options && options.inited) {
this.options = options;
} else {
this.options = Client.initOptions(options);
}
this.options.cancelFlag = false; // cancel flag: if true need to be cancelled, default false
// support custom agent and urllib client
if (this.options.urllib) {
this.urllib = this.options.urllib;
} else {
this.urllib = urllib;
this.agent = this.options.agent || globalHttpAgent;
}
this.ctx = ctx;
this.userAgent = this._getUserAgent();
// record the time difference between client and server
this.options.amendTimeSkewed = 0;
}
/**
* Expose `Client`
*/
module.exports = Client;
Client.initOptions = function initOptions(options) {
if (!options.stsToken) {
console.warn('Please use STS Token for safety, see more details at https://help.aliyun.com/document_detail/32077.html');
}
var opts = (0, _assign2.default)({
secure: isHttpsWebProtocol(),
// for browser compatibility disable fetch.
useFetch: false
}, options);
return _initOptions(opts);
};
/**
* prototype
*/
var proto = Client.prototype;
// mount debug on proto
proto.debug = debug;
/**
* Object operations
*/
merge(proto, require('./object'));
/**
* Bucket operations
*/
merge(proto, require('../common/bucket/getBucketWebsite'));
merge(proto, require('../common/bucket/putBucketWebsite'));
merge(proto, require('../common/bucket/deleteBucketWebsite'));
// lifecycle
merge(proto, require('../common/bucket/getBucketLifecycle'));
merge(proto, require('../common/bucket/putBucketLifecycle'));
merge(proto, require('../common/bucket/deleteBucketLifecycle'));
// multiversion
merge(proto, require('../common/bucket/putBucketVersioning'));
merge(proto, require('../common/bucket/getBucketVersioning'));
// multipart upload
merge(proto, require('./managed-upload'));
/**
* Multipart operations
*/
merge(proto, require('../common/multipart'));
/**
* Common module parallel
*/
merge(proto, require('../common/parallel'));
/**
* get OSS signature
* @param {String} stringToSign
* @return {String} the signature
*/
proto.signature = function signature(stringToSign) {
this.debug('authorization stringToSign: %s', stringToSign, 'info');
return signUtils.computeSignature(this.options.accessKeySecret, stringToSign);
};
/**
* get author header
*
* "Authorization: OSS " + Access Key Id + ":" + Signature
*
* Signature = base64(hmac-sha1(Access Key Secret + "\n"
* + VERB + "\n"
* + CONTENT-MD5 + "\n"
* + CONTENT-TYPE + "\n"
* + DATE + "\n"
* + CanonicalizedOSSHeaders
* + CanonicalizedResource))
*
* @param {String} method
* @param {String} resource
* @param {Object} header
* @return {String}
*
* @api private
*/
proto.authorization = function authorization(method, resource, subres, headers) {
var stringToSign = signUtils.buildCanonicalString(method.toUpperCase(), resource, {
headers: headers,
parameters: subres
});
return signUtils.authorization(this.options.accessKeyId, this.options.accessKeySecret, stringToSign);
};
/**
* request oss server
* @param {Object} params
* - {String} object
* - {String} bucket
* - {Object} [headers]
* - {Object} [query]
* - {Buffer} [content]
* - {Stream} [stream]
* - {Stream} [writeStream]
* - {String} [mime]
* - {Boolean} [xmlResponse]
* - {Boolean} [customResponse]
* - {Number} [timeout]
* - {Object} [ctx] request context, default is `this.ctx`
*
* @api private
*/
proto.request = function request(params) {
var reqParams, result, reqErr, useStream, err, parseData;
return _regenerator2.default.async(function request$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
reqParams = createRequest.call(this, params);
if (!this.options.useFetch) {
reqParams.params.mode = 'disable-fetch';
}
result = void 0;
reqErr = void 0;
useStream = !!params.stream;
_context.prev = 5;
_context.next = 8;
return _regenerator2.default.awrap(this.urllib.request(reqParams.url, reqParams.params));
case 8:
result = _context.sent;
this.debug('response %s %s, got %s, headers: %j', params.method, reqParams.url, result.status, result.headers, 'info');
_context.next = 15;
break;
case 12:
_context.prev = 12;
_context.t0 = _context['catch'](5);
reqErr = _context.t0;
case 15:
err = void 0;
if (!(result && params.successStatuses && params.successStatuses.indexOf(result.status) === -1)) {
_context.next = 28;
break;
}
_context.next = 19;
return _regenerator2.default.awrap(this.requestError(result));
case 19:
err = _context.sent;
if (!(err.code === 'RequestTimeTooSkewed' && !useStream)) {
_context.next = 25;
break;
}
this.options.amendTimeSkewed = +new Date(err.serverTime) - new Date();
_context.next = 24;
return _regenerator2.default.awrap(this.request(params));
case 24:
return _context.abrupt('return', _context.sent);
case 25:
err.params = params;
_context.next = 32;
break;
case 28:
if (!reqErr) {
_context.next = 32;
break;
}
_context.next = 31;
return _regenerator2.default.awrap(this.requestError(reqErr));
case 31:
err = _context.sent;
case 32:
if (!err) {
_context.next = 34;
break;
}
throw err;
case 34:
if (!params.xmlResponse) {
_context.next = 39;
break;
}
_context.next = 37;
return _regenerator2.default.awrap(this.parseXML(result.data));
case 37:
parseData = _context.sent;
result.data = parseData;
case 39:
return _context.abrupt('return', result);
case 40:
case 'end':
return _context.stop();
}
}
}, null, this, [[5, 12]]);
};
proto._getResource = function _getResource(params) {
var resource = '/';
if (params.bucket) resource += params.bucket + '/';
if (params.object) resource += params.object;
return resource;
};
proto._isIP = _isIP;
proto._escape = function _escape(name) {
return utility.encodeURIComponent(name).replace(/%2F/g, '/');
};
proto._getReqUrl = function _getReqUrl(params) {
var ep = {};
copy(this.options.endpoint).to(ep);
var isIP = this._isIP(ep.hostname);
var isCname = this.options.cname;
if (params.bucket && !isCname && !isIP) {
ep.host = params.bucket + '.' + ep.host;
}
var reourcePath = '/';
if (params.bucket && isIP) {
reourcePath += params.bucket + '/';
}
if (params.object) {
// Preserve '/' in result url
reourcePath += this._escape(params.object).replace(/\+/g, '%2B');
}
ep.pathname = reourcePath;
var query = {};
if (params.query) {
merge(query, params.query);
}
if (params.subres) {
var subresAsQuery = {};
if (is.string(params.subres)) {
subresAsQuery[params.subres] = '';
} else if (is.array(params.subres)) {
params.subres.forEach(function (k) {
subresAsQuery[k] = '';
});
} else {
subresAsQuery = params.subres;
}
merge(query, subresAsQuery);
}
ep.query = query;
return urlutil.format(ep);
};
/*
* Get User-Agent for browser & node.js
* @example
* aliyun-sdk-nodejs/4.1.2 Node.js 5.3.0 on Darwin 64-bit
* aliyun-sdk-js/4.1.2 Safari 9.0 on Apple iPhone(iOS 9.2.1)
* aliyun-sdk-js/4.1.2 Chrome 43.0.2357.134 32-bit on Windows Server 2008 R2 / 7 64-bit
*/
proto._getUserAgent = function _getUserAgent() {
var agent = process && process.browser ? 'js' : 'nodejs';
var sdk = 'aliyun-sdk-' + agent + '/' + pkg.version;
var plat = platform.description;
if (!plat && process) {
plat = 'Node.js ' + process.version.slice(1) + ' on ' + process.platform + ' ' + process.arch;
}
return this._checkUserAgent(sdk + ' ' + plat);
};
proto._checkUserAgent = function _checkUserAgent(ua) {
var userAgent = ua.replace(/\u03b1/, 'alpha').replace(/\u03b2/, 'beta');
return userAgent;
};
/*
* Check Browser And Version
* @param {String} [name] browser name: like IE, Chrome, Firefox
* @param {String} [version] browser major version: like 10(IE 10.x), 55(Chrome 55.x), 50(Firefox 50.x)
* @return {Bool} true or false
* @api private
*/
proto.checkBrowserAndVersion = function checkBrowserAndVersion(name, version) {
return bowser.name === name && bowser.version.split('.')[0] === version;
};
/**
* thunkify xml.parseString
* @param {String|Buffer} str
*
* @api private
*/
proto.parseXML = function parseXMLThunk(str) {
return new _promise2.default(function (resolve, reject) {
if (Buffer.isBuffer(str)) {
str = str.toString();
}
xml.parseString(str, {
explicitRoot: false,
explicitArray: false
}, function (err, result) {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
};
/**
* generater a request error with request response
* @param {Object} result
*
* @api private
*/
proto.requestError = function requestError(result) {
var err, message, info, msg;
return _regenerator2.default.async(function requestError$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
err = null;
if (!(!result.data || !result.data.length)) {
_context2.next = 5;
break;
}
if (result.status === -1 || result.status === -2) {
// -1 is net error , -2 is timeout
err = new Error(result.message);
err.name = result.name;
err.status = result.status;
err.code = result.name;
} else {
// HEAD not exists resource
if (result.status === 404) {
err = new Error('Object not exists');
err.name = 'NoSuchKeyError';
err.status = 404;
err.code = 'NoSuchKey';
} else if (result.status === 412) {
err = new Error('Pre condition failed');
err.name = 'PreconditionFailedError';
err.status = 412;
err.code = 'PreconditionFailed';
} else {
err = new Error('Unknow error, status: ' + result.status);
err.name = 'UnknowError';
err.status = result.status;
}
err.requestId = result.headers['x-oss-request-id'];
err.host = '';
}
_context2.next = 33;
break;
case 5:
message = String(result.data);
this.debug('request response error data: %s', message, 'error');
info = void 0;
_context2.prev = 8;
_context2.next = 11;
return _regenerator2.default.awrap(this.parseXML(message));
case 11:
_context2.t0 = _context2.sent;
if (_context2.t0) {
_context2.next = 14;
break;
}
_context2.t0 = {};
case 14:
info = _context2.t0;
_context2.next = 24;
break;
case 17:
_context2.prev = 17;
_context2.t1 = _context2['catch'](8);
this.debug(message, 'error');
_context2.t1.message += '\nraw xml: ' + message;
_context2.t1.status = result.status;
_context2.t1.requestId = result.headers['x-oss-request-id'];
return _context2.abrupt('return', _context2.t1);
case 24:
msg = info.Message || 'unknow request error, status: ' + result.status;
if (info.Condition) {
msg += ' (condition: ' + info.Condition + ')';
}
err = new Error(msg);
err.name = info.Code ? info.Code + 'Error' : 'UnknowError';
err.status = result.status;
err.code = info.Code;
err.requestId = info.RequestId;
err.hostId = info.HostId;
err.serverTime = info.ServerTime;
case 33:
this.debug('generate error %j', err, 'error');
return _context2.abrupt('return', err);
case 35:
case 'end':
return _context2.stop();
}
}
}, null, this, [[8, 17]]);
};
}).call(this,{"isBuffer":require("../../node_modules/is-buffer/index.js")},require('_process'))
},{"../../node_modules/is-buffer/index.js":197,"../common/bucket/deleteBucketLifecycle":6,"../common/bucket/deleteBucketWebsite":7,"../common/bucket/getBucketLifecycle":8,"../common/bucket/getBucketVersioning":9,"../common/bucket/getBucketWebsite":10,"../common/bucket/putBucketLifecycle":11,"../common/bucket/putBucketVersioning":12,"../common/bucket/putBucketWebsite":13,"../common/client/initOptions":15,"../common/multipart":18,"../common/parallel":33,"../common/signUtils":34,"../common/utils/createRequest":38,"../common/utils/isIP":45,"./managed-upload":3,"./object":4,"./version":5,"_process":208,"agentkeepalive":48,"babel-runtime/core-js/object/assign":54,"babel-runtime/core-js/promise":61,"babel-runtime/regenerator":68,"bowser":70,"copy-to":76,"debug":288,"is-type-of":289,"merge-descriptors":200,"platform":206,"url":238,"urllib":291,"utility":290,"xml2js":249}],3:[function(require,module,exports){
(function (Buffer){
'use strict';
var _from = require('babel-runtime/core-js/array/from');
var _from2 = _interopRequireDefault(_from);
var _promise = require('babel-runtime/core-js/promise');
var _promise2 = _interopRequireDefault(_promise);
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// var debug = require('debug')('ali-oss:multipart');
var is = require('is-type-of');
var util = require('util');
var path = require('path');
var mime = require('mime');
var copy = require('copy-to');
var _require = require('../common/utils/isBlob'),
isBlob = _require.isBlob;
var _require2 = require('../common/utils/isFile'),
isFile = _require2.isFile;
var proto = exports;
/**
* Multipart operations
*/
/**
* Upload a file to OSS using multipart uploads
* @param {String} name
* @param {String|File} file
* @param {Object} options
* {Object} options.callback The callback parameter is composed of a JSON string encoded in Base64
* {String} options.callback.url the OSS sends a callback request to this URL
* {String} options.callback.host The host header value for initiating callback requests
* {String} options.callback.body The value of the request body when a callback is initiated
* {String} options.callback.contentType The Content-Type of the callback requests initiatiated
* {Object} options.callback.customValue Custom parameters are a map of key-values, e.g:
* customValue = {
* key1: 'value1',
* key2: 'value2'
* }
*/
proto.multipartUpload = function multipartUpload(name, file, options) {
var minPartSize, fileSize, stream, result, ret, initResult, uploadId, partSize, checkpoint;
return _regenerator2.default.async(function multipartUpload$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
this.resetCancelFlag();
options = options || {};
if (!(options.checkpoint && options.checkpoint.uploadId)) {
_context.next = 6;
break;
}
_context.next = 5;
return _regenerator2.default.awrap(this._resumeMultipart(options.checkpoint, options));
case 5:
return _context.abrupt('return', _context.sent);
case 6:
minPartSize = 100 * 1024;
if (!options.mime) {
if (isFile(file)) {
options.mime = mime.getType(path.extname(file.name));
} else if (isBlob(file)) {
options.mime = file.type;
} else {
options.mime = mime.getType(path.extname(file));
}
}
options.headers = options.headers || {};
this._convertMetaToHeaders(options.meta, options.headers);
_context.next = 12;
return _regenerator2.default.awrap(this._getFileSize(file));
case 12:
fileSize = _context.sent;
if (!(fileSize < minPartSize)) {
_context.next = 25;
break;
}
stream = this._createStream(file, 0, fileSize);
options.contentLength = fileSize;
_context.next = 18;
return _regenerator2.default.awrap(this.putStream(name, stream, options));
case 18:
result = _context.sent;
if (!(options && options.progress)) {
_context.next = 22;
break;
}
_context.next = 22;
return _regenerator2.default.awrap(options.progress(1));
case 22:
ret = {
res: result.res,
bucket: this.options.bucket,
name: name,
etag: result.res.headers.etag
};
if (options.headers && options.headers['x-oss-callback'] || options.callback) {
ret.data = result.data;
}
return _context.abrupt('return', ret);
case 25:
if (!(options.partSize && !(parseInt(options.partSize, 10) === options.partSize))) {
_context.next = 27;
break;
}
throw new Error('partSize must be int number');
case 27:
if (!(options.partSize && options.partSize < minPartSize)) {
_context.next = 29;
break;
}
throw new Error('partSize must not be smaller than ' + minPartSize);
case 29:
_context.next = 31;
return _regenerator2.default.awrap(this.initMultipartUpload(name, options));
case 31:
initResult = _context.sent;
uploadId = initResult.uploadId;
partSize = this._getPartSize(fileSize, options.partSize);
checkpoint = {
file: file,
name: name,
fileSize: fileSize,
partSize: partSize,
uploadId: uploadId,
doneParts: []
};
if (!(options && options.progress)) {
_context.next = 38;
break;
}
_context.next = 38;
return _regenerator2.default.awrap(options.progress(0, checkpoint, initResult.res));
case 38:
_context.next = 40;
return _regenerator2.default.awrap(this._resumeMultipart(checkpoint, options));
case 40:
return _context.abrupt('return', _context.sent);
case 41:
case 'end':
return _context.stop();
}
}
}, null, this);
};
/*
* Resume multipart upload from checkpoint. The checkpoint will be
* updated after each successful part upload.
* @param {Object} checkpoint the checkpoint
* @param {Object} options
*/
proto._resumeMultipart = function _resumeMultipart(checkpoint, options) {
var that, file, fileSize, partSize, uploadId, doneParts, name, internalDoneParts, partOffs, numParts, multipartFinish, uploadPartJob, all, done, todo, defaultParallel, parallel, jobErr;
return _regenerator2.default.async(function _resumeMultipart$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
that = this;
if (!this.isCancel()) {
_context3.next = 3;
break;
}
throw this._makeCancelEvent();
case 3:
file = checkpoint.file, fileSize = checkpoint.fileSize, partSize = checkpoint.partSize, uploadId = checkpoint.uploadId, doneParts = checkpoint.doneParts, name = checkpoint.name;
internalDoneParts = [];
if (doneParts.length > 0) {
copy(doneParts).to(internalDoneParts);
}
partOffs = this._divideParts(fileSize, partSize);
numParts = partOffs.length;
multipartFinish = false;
uploadPartJob = function uploadPartJob(self, partNo) {
var _this = this;
// eslint-disable-next-line no-async-promise-executor
return new _promise2.default(function _callee(resolve, reject) {
var pi, data, result, tempErr;
return _regenerator2.default.async(function _callee$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.prev = 0;
if (self.isCancel()) {
_context2.next = 18;
break;
}
pi = partOffs[partNo - 1];
data = {
stream: self._createStream(file, pi.start, pi.end),
size: pi.end - pi.start
};
_context2.next = 6;
return _regenerator2.default.awrap(self._uploadPart(name, uploadId, partNo, data));
case 6:
result = _context2.sent;
if (!(!self.isCancel() && !multipartFinish)) {
_context2.next = 15;
break;
}
checkpoint.doneParts.push({
number: partNo,
etag: result.res.headers.etag
});
if (!options.progress) {
_context2.next = 12;
break;
}
_context2.next = 12;
return _regenerator2.default.awrap(options.progress(doneParts.length / numParts, checkpoint, result.res));
case 12:
resolve({
number: partNo,
etag: result.res.headers.etag
});
_context2.next = 16;
break;
case 15:
resolve();
case 16:
_context2.next = 19;
break;
case 18:
resolve();
case 19:
_context2.next = 30;
break;
case 21:
_context2.prev = 21;
_context2.t0 = _context2['catch'](0);
tempErr = new Error();
tempErr.name = _context2.t0.name;
tempErr.message = _context2.t0.message;
tempErr.stack = _context2.t0.stack;
tempErr.partNum = partNo;
copy(_context2.t0).to(tempErr);
reject(tempErr);
case 30:
case 'end':
return _context2.stop();
}
}
}, null, _this, [[0, 21]]);
});
};
all = (0, _from2.default)(new Array(numParts), function (x, i) {
return i + 1;
});
done = internalDoneParts.map(function (p) {
return p.number;
});
todo = all.filter(function (p) {
return done.indexOf(p) < 0;
});
defaultParallel = 5;
parallel = options.parallel || defaultParallel;
// upload in parallel
_context3.next = 17;
return _regenerator2.default.awrap(this._parallel(todo, parallel, function (value) {
return new _promise2.default(function (resolve, reject) {
uploadPartJob(that, value).then(function (result) {
if (result) {
internalDoneParts.push(result);
}
resolve();
}).catch(function (err) {
reject(err);
});
});
}));
case 17:
jobErr = _context3.sent;
multipartFinish = true;
if (!this.isCancel()) {
_context3.next = 22;
break;
}
uploadPartJob = null;
throw this._makeCancelEvent();
case 22:
if (!(jobErr && jobErr.length > 0)) {
_context3.next = 25;
break;
}
jobErr[0].message = 'Failed to upload some parts with error: ' + jobErr[0].toString() + ' part_num: ' + jobErr[0].partNum;
throw jobErr[0];
case 25:
_context3.next = 27;
return _regenerator2.default.awrap(this.completeMultipartUpload(name, uploadId, internalDoneParts, options));
case 27:
return _context3.abrupt('return', _context3.sent);
case 28:
case 'end':
return _context3.stop();
}
}
}, null, this);
};
/**
* Get file size
*/
proto._getFileSize = function _getFileSize(file) {
return _regenerator2.default.async(function _getFileSize$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
if (!is.buffer(file)) {
_context4.next = 4;
break;
}
return _context4.abrupt('return', file.length);
case 4:
if (!(isBlob(file) || isFile(file))) {
_context4.next = 6;
break;
}
return _context4.abrupt('return', file.size);
case 6:
throw new Error('_getFileSize requires Buffer/File/Blob.');
case 7:
case 'end':
return _context4.stop();
}
}
}, null, this);
};
/*
* Readable stream for Web File
*/
var _require3 = require('stream'),
Readable = _require3.Readable;
function WebFileReadStream(file, options) {
if (!(this instanceof WebFileReadStream)) {
return new WebFileReadStream(file, options);
}
Readable.call(this, options);
this.file = file;
this.reader = new FileReader();
this.start = 0;
this.finish = false;
this.fileBuffer = null;
}
util.inherits(WebFileReadStream, Readable);
WebFileReadStream.prototype.readFileAndPush = function readFileAndPush(size) {
if (this.fileBuffer) {
var pushRet = true;
while (pushRet && this.fileBuffer && this.start < this.fileBuffer.length) {
var start = this.start;
var end = start + size;
end = end > this.fileBuffer.length ? this.fileBuffer.length : end;
this.start = end;
pushRet = this.push(this.fileBuffer.slice(start, end));
}
}
};
WebFileReadStream.prototype._read = function _read(size) {
if (this.file && this.start >= this.file.size || this.fileBuffer && this.start >= this.fileBuffer.length || this.finish || this.start === 0 && !this.file) {
if (!this.finish) {
this.fileBuffer = null;
this.finish = true;
}
this.push(null);
return;
}
var defaultReadSize = 16 * 1024;
size = size || defaultReadSize;
var that = this;
this.reader.onload = function onload(e) {
that.fileBuffer = Buffer.from(new Uint8Array(e.target.result));
that.file = null;
that.readFileAndPush(size);
};
if (this.start === 0) {
this.reader.readAsArrayBuffer(this.file);
} else {
this.readFileAndPush(size);
}
};
proto._createStream = function _createStream(file, start, end) {
if (isBlob(file) || isFile(file)) {
return new WebFileReadStream(file.slice(start, end));
}
throw new Error('_createStream requires File/Blob.');
};
proto._getPartSize = function _getPartSize(fileSize, partSize) {
var maxNumParts = 10 * 1000;
var defaultPartSize = 1024 * 1024;
if (!partSize) {
return defaultPartSize;
}
return Math.max(Math.ceil(fileSize / maxNumParts), partSize);
};
proto._divideParts = function _divideParts(fileSize, partSize) {
var numParts = Math.ceil(fileSize / partSize);
var partOffs = [];
for (var i = 0; i < numParts; i++) {
var start = partSize * i;
var end = Math.min(start + partSize, fileSize);
partOffs.push({
start: start,
end: end
});
}
return partOffs;
};
}).call(this,require("buffer").Buffer)
},{"../common/utils/isBlob":43,"../common/utils/isFile":44,"babel-runtime/core-js/array/from":52,"babel-runtime/core-js/promise":61,"babel-runtime/regenerator":68,"buffer":73,"copy-to":76,"is-type-of":289,"mime":202,"path":205,"stream":230,"util":243}],4:[function(require,module,exports){
'use strict';
var _promise = require('babel-runtime/core-js/promise');
var _promise2 = _interopRequireDefault(_promise);
var _keys = require('babel-runtime/core-js/object/keys');
var _keys2 = _interopRequireDefault(_keys);
var _assign = require('babel-runtime/core-js/object/assign');
var _assign2 = _interopRequireDefault(_assign);
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// const debug = require('debug')('ali-oss:object');
var utility = require('utility');
var fs = require('fs');
var is = require('is-type-of');
var urlutil = require('url');
var copy = require('copy-to');
var path = require('path');
var mime = require('mime');
var callback = require('../common/callback');
var signHelper = require('../common/signUtils');
var merge = require('merge-descriptors');
var _require = require('../common/utils/isBlob'),
isBlob = _require.isBlob;
var _require2 = require('../common/utils/isFile'),
isFile = _require2.isFile;
// var assert = require('assert');
var proto = exports;
/**
* Object operations
*/
/**
* append an object from String(file path)/Buffer/ReadableStream
* @param {String} name the object key
* @param {Mixed} file String(file path)/Buffer/ReadableStream
* @param {Object} options
* @return {Object}
*/
proto.append = function append(name, file, options) {
var result;
return _regenerator2.default.async(function append$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
options = options || {};
if (options.position === undefined) options.position = '0';
options.subres = {
append: '',
position: options.position
};
options.method = 'POST';
_context.next = 6;
return _regenerator2.default.awrap(this.put(name, file, options));
case 6:
result = _context.sent;
result.nextAppendPosition = result.res.headers['x-oss-next-append-position'];
return _context.abrupt('return', result);
case 9:
case 'end':
return _context.stop();
}
}
}, null, this);
};
/**
* put an object from String(file path)/Buffer/ReadableStream
* @param {String} name the object key
* @param {Mixed} file String(file path)/Buffer/ReadableStream
* @param {Object} options
* {Object} options.callback The callback parameter is composed of a JSON string encoded in Base64
* {String} options.callback.url the OSS sends a callback request to this URL
* {String} options.callback.host The host header value for initiating callback requests
* {String} options.callback.body The value of the request body when a callback is initiated
* {String} options.callback.contentType The Content-Type of the callback requests initiatiated
* {Object} options.callback.customValue Custom parameters are a map of key-values, e.g:
* customValue = {
* key1: 'value1',
* key2: 'value2'
* }
* @return {Object}
*/
proto.put = function put(name, file, options) {
var content, stream, _result, method, params, result, ret;
return _regenerator2.default.async(function put$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
content = void 0;
options = options || {};
name = this._objectName(name);
if (!is.buffer(file)) {
_context2.next = 7;
break;
}
content = file;
_context2.next = 33;
break;
case 7:
if (!(isBlob(file) || isFile(file))) {
_context2.next = 32;
break;
}
if (!options.mime) {
if (isFile(file)) {
options.mime = mime.getType(path.extname(file.name));
} else {
options.mime = file.type;
}
}
stream = this._createStream(file, 0, file.size);
_context2.next = 12;
return _regenerator2.default.awrap(this._getFileSize(file));
case 12:
options.contentLength = _context2.sent;
_context2.prev = 13;
_context2.next = 16;
return _regenerator2.default.awrap(this.putStream(name, stream, options));
case 16:
_result = _context2.sent;
return _context2.abrupt('return', _result);
case 20:
_context2.prev = 20;
_context2.t0 = _context2['catch'](13);
if (!(_context2.t0.code === 'RequestTimeTooSkewed')) {
_context2.next = 29;
break;
}
this.options.amendTimeSkewed = +new Date(_context2.t0.serverTime) - new Date();
_context2.next = 26;
return _regenerator2.default.awrap(this.put(name, file, options));
case 26:
return _context2.abrupt('return', _context2.sent);
case 29:
throw _context2.t0;
case 30:
_context2.next = 33;
break;
case 32:
throw new TypeError('Must provide Buffer/Blob/File for put.');
case 33:
options.headers = options.headers || {};
this._convertMetaToHeaders(options.meta, options.headers);
method = options.method || 'PUT';
params = this._objectRequestParams(method, name, options);
callback.encodeCallback(params, options);
params.mime = options.mime;
params.content = content;
params.successStatuses = [200];
_context2.next = 43;
return _regenerator2.default.awrap(this.request(params));
case 43:
result = _context2.sent;
ret = {
name: name,
url: this._objectUrl(name),
res: result.res
};
if (params.headers && params.headers['x-oss-callback']) {
ret.data = JSON.parse(result.data.toString());
}
return _context2.abrupt('return', ret);
case 47:
case 'end':
return _context2.stop();
}
}
}, null, this, [[13, 20]]);
};
/**
* put an object from ReadableStream. If `options.contentLength` is
* not provided, chunked encoding is used.
* @param {String} name the object key
* @param {Readable} stream the ReadableStream
* @param {Object} options
* @return {Object}
*/
proto.putStream = function putStream(name, stream, options) {
var method, params, result, ret;
return _regenerator2.default.async(function putStream$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
options = options || {};
options.headers = options.headers || {};
name = this._objectName(name);
if (options.contentLength) {
options.headers['Content-Length'] = options.contentLength;
} else {
options.headers['Transfer-Encoding'] = 'chunked';
}
this._convertMetaToHeaders(options.meta, options.headers);
method = options.method || 'PUT';
params = this._objectRequestParams(method, name, options);
callback.encodeCallback(params, options);
params.mime = options.mime;
params.stream = stream;
params.successStatuses = [200];
_context3.next = 13;
return _regenerator2.default.awrap(this.request(params));
case 13:
result = _context3.sent;
ret = {
name: name,
url: this._objectUrl(name),
res: result.res
};
if (params.headers && params.headers['x-oss-callback']) {
ret.data = JSON.parse(result.data.toString());
}
return _context3.abrupt('return', ret);
case 17:
case 'end':
return _context3.stop();
}
}
}, null, this);
};
merge(proto, require('../common/object/copyObject'));
merge(proto, require('../common/object/getObjectTagging'));
merge(proto, require('../common/object/putObjectTagging'));
merge(proto, require('../common/object/deleteObjectTagging'));
merge(proto, require('../common/image'));
merge(proto, require('../common/object/getBucketVersions'));
merge(proto, require('../common/object/getACL'));
merge(proto, require('../common/object/putACL'));
merge(proto, require('../common/object/head'));
merge(proto, require('../common/object/delete'));
merge(proto, require('../common/object/get'));
merge(proto, require('../common/object/putSymlink'));
merge(proto, require('../common/object/getSymlink'));
merge(proto, require('../common/object/deleteMulti'));
merge(proto, require('../common/object/getObjectMeta'));
proto.putMeta = function putMeta(name, meta, options) {
var copyResult;
return _regenerator2.default.async(function putMeta$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
_context4.next = 2;
return _regenerator2.default.awrap(this.copy(name, name, {
meta: meta || {},
timeout: options && options.timeout,
ctx: options && options.ctx
}));
case 2:
copyResult = _context4.sent;
return _context4.abrupt('return', copyResult);
case 4:
case 'end':
return _context4.stop();
}
}
}, null, this);
};
proto.list = function list(query, options) {
var params, result, objects, that, prefixes;
return _regenerator2.default.async(function list$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
// prefix, marker, max-keys, delimiter
params = this._objectRequestParams('GET', '', options);
params.query = query;
params.xmlResponse = true;
params.successStatuses = [200];
_context5.next = 6;
return _regenerator2.default.awrap(this.request(params));
case 6:
result = _context5.sent;
objects = result.data.Contents;
that = this;
if (objects) {
if (!Array.isArray(objects)) {
objects = [objects];
}
objects = objects.map(function (obj) {
return {
name: obj.Key,
url: that._objectUrl(obj.Key),
lastModified: obj.LastModified,
etag: obj.ETag,
type: obj.Type,
size: Number(obj.Size),
storageClass: obj.StorageClass,
owner: {
id: obj.Owner.ID,
displayName: obj.Owner.DisplayName
}
};
});
}
prefixes = result.data.CommonPrefixes || null;
if (prefixes) {
if (!Array.isArray(prefixes)) {
prefixes = [prefixes];
}
prefixes = prefixes.map(function (item) {
return item.Prefix;
});
}
return _context5.abrupt('return', {
res: result.res,
objects: objects,
prefixes: prefixes,
nextMarker: result.data.NextMarker || null,
isTruncated: result.data.IsTruncated === 'true'
});
case 13:
case 'end':
return _context5.stop();
}
}
}, null, this);
};
/**
* Restore Object
* @param {String} name the object key
* @param {Object} options
* @returns {{res}}
*/
proto.restore = function restore(name, options) {
var params, result;
return _regenerator2.default.async(function restore$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
options = options || {};
options.subres = (0, _assign2.default)({ restore: '' }, options.subres);
if (options.versionId) {
options.subres.versionId = options.versionId;
}
params = this._objectRequestParams('POST', name, options);
params.successStatuses = [202];
_context6.next = 7;
return _regenerator2.default.awrap(this.request(params));
case 7:
result = _context6.sent;
return _context6.abrupt('return', {
res: result.res
});
case 9:
case 'end':
return _context6.stop();
}
}
}, null, this);
};
proto.signatureUrl = function signatureUrl(name, options) {
options = options || {};
name = this._objectName(name);
options.method = options.method || 'GET';
var expires = utility.timestamp() + (options.expires || 1800);
var params = {
bucket: this.options.bucket,
object: name
};
var resource = this._getResource(params);
if (this.options.stsToken) {
options['security-token'] = this.options.stsToken;
}
var signRes = signHelper._signatureForURL(this.options.accessKeySecret, options, resource, expires);
var url = urlutil.parse(this._getReqUrl(params));
url.query = {
OSSAccessKeyId: this.options.accessKeyId,
Expires: expires,
Signature: signRes.Signature
};
copy(signRes.subResource).to(url.query);
return url.format();
};
/**
* Get Object url by name
* @param {String} name - object name
* @param {String} [baseUrl] - If provide `baseUrl`,
* will use `baseUrl` instead the default `endpoint`.
* @return {String} object url
*/
proto.getObjectUrl = function getObjectUrl(name, baseUrl) {
if (!baseUrl) {
baseUrl = this.options.endpoint.format();
} else if (baseUrl[baseUrl.length - 1] !== '/') {
baseUrl += '/';
}
return baseUrl + this._escape(this._objectName(name));
};
proto._objectUrl = function _objectUrl(name) {
return this._getReqUrl({ bucket: this.options.bucket, object: name });
};
/**
* Get Object url by name
* @param {String} name - object name
* @param {String} [baseUrl] - If provide `baseUrl`, will use `baseUrl` instead the default `endpoint and bucket`.
* @return {String} object url include bucket
*/
proto.generateObjectUrl = function (name, baseUrl) {
if (!baseUrl) {
baseUrl = this.options.endpoint.format();
var copyUrl = urlutil.parse(baseUrl);
var bucket = this.options.bucket;
copyUrl.hostname = bucket + '.' + copyUrl.hostname;
copyUrl.host = bucket + '.' + copyUrl.host;
baseUrl = copyUrl.format();
} else if (baseUrl[baseUrl.length - 1] !== '/') {
baseUrl += '/';
}
return baseUrl + this._escape(this._objectName(name));
};
/**
* generator request params
* @return {Object} params
*
* @api private
*/
proto._objectRequestParams = function _objectRequestParams(method, name, options) {
if (!this.options.bucket) {
throw new Error('Please create a bucket first');
}
options = options || {};
name = this._objectName(name);
var params = {
object: name,
bucket: this.options.bucket,
method: method,
subres: options && options.subres,
timeout: options && options.timeout,
ctx: options && options.ctx
};
if (options.headers) {
params.headers = {};
copy(options.headers).to(params.headers);
}
return params;
};
proto._objectName = function _objectName(name) {
return name.replace(/^\/+/, '');
};
proto._convertMetaToHeaders = function _convertMetaToHeaders(meta, headers) {
if (!meta) {
return;
}
(0, _keys2.default)(meta).forEach(function (k) {
headers['x-oss-meta-' + k] = meta[k];
});
};
proto._deleteFileSafe = function _deleteFileSafe(filepath) {
var _this = this;
return new _promise2.default(function (resolve) {
fs.exists(filepath, function (exists) {
if (!exists) {
resolve();
} else {
fs.unlink(filepath, function (err) {
if (err) {
_this.debug('unlink %j error: %s', filepath, err, 'error');
}
resolve();
});
}
});
});
};
},{"../common/callback":14,"../common/image":16,"../common/object/copyObject":19,"../common/object/delete":20,"../common/object/deleteMulti":21,"../common/object/deleteObjectTagging":22,"../common/object/get":23,"../common/object/getACL":24,"../common/object/getBucketVersions":25,"../common/object/getObjectMeta":26,"../common/object/getObjectTagging":27,"../common/object/getSymlink":28,"../common/object/head":29,"../common/object/putACL":30,"../common/object/putObjectTagging":31,"../common/object/putSymlink":32,"../common/signUtils":34,"../common/utils/isBlob":43,"../common/utils/isFile":44,"babel-runtime/core-js/object/assign":54,"babel-runtime/core-js/object/keys":60,"babel-runtime/core-js/promise":61,"babel-runtime/regenerator":68,"copy-to":76,"fs":71,"is-type-of":289,"merge-descriptors":200,"mime":202,"path":205,"url":238,"utility":290}],5:[function(require,module,exports){
"use strict";
exports.version = "6.10.0";
},{}],6:[function(require,module,exports){
'use strict';
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _require = require('../utils/checkBucketName'),
_checkBucketName = _require.checkBucketName;
var proto = exports;
proto.deleteBucketLifecycle = function deleteBucketLifecycle(name, options) {
var params, result;
return _regenerator2.default.async(function deleteBucketLifecycle$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_checkBucketName(name);
params = this._bucketRequestParams('DELETE', name, 'lifecycle', options);
params.successStatuses = [204];
_context.next = 5;
return _regenerator2.default.awrap(this.request(params));
case 5:
result = _context.sent;
return _context.abrupt('return', {
res: result.res
});
case 7:
case 'end':
return _context.stop();
}
}
}, null, this);
};
},{"../utils/checkBucketName":35,"babel-runtime/regenerator":68}],7:[function(require,module,exports){
'use strict';
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _require = require('../utils/checkBucketName'),
_checkBucketName = _require.checkBucketName;
var proto = exports;
proto.deleteBucketWebsite = function deleteBucketWebsite(name, options) {
var params, result;
return _regenerator2.default.async(function deleteBucketWebsite$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_checkBucketName(name);
params = this._bucketRequestParams('DELETE', name, 'website', options);
params.successStatuses = [204];
_context.next = 5;
return _regenerator2.default.awrap(this.request(params));
case 5:
result = _context.sent;
return _context.abrupt('return', {
res: result.res
});
case 7:
case 'end':
return _context.stop();
}
}
}, null, this);
};
},{"../utils/checkBucketName":35,"babel-runtime/regenerator":68}],8:[function(require,module,exports){
'use strict';
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _require = require('../utils/checkBucketName'),
_checkBucketName = _require.checkBucketName;
var _require2 = require('../utils/isArray'),
isArray = _require2.isArray;
var _require3 = require('../utils/formatObjKey'),
formatObjKey = _require3.formatObjKey;
var proto = exports;
proto.getBucketLifecycle = function getBucketLifecycle(name, options) {
var params, result, rules;
return _regenerator2.default.async(function getBucketLifecycle$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_checkBucketName(name);
params = this._bucketRequestParams('GET', name, 'lifecycle', options);
params.successStatuses = [200];
params.xmlResponse = true;
_context.next = 6;
return _regenerator2.default.awrap(this.request(params));
case 6:
result = _context.sent;
rules = result.data.Rule || null;
if (rules) {
if (!isArray(rules)) {
rules = [rules];
}
rules = rules.map(function (_) {
if (_.ID) {
_.id = _.ID;
delete _.ID;
}
if (_.Tag && !isArray(_.Tag)) {
_.Tag = [_.Tag];
}
return formatObjKey(_, 'firstLowerCase');
});
}
return _context.abrupt('return', {
rules: rules,
res: result.res
});
case 10:
case 'end':
return _context.stop();
}
}
}, null, this);
};
},{"../utils/checkBucketName":35,"../utils/formatObjKey":40,"../utils/isArray":42,"babel-runtime/regenerator":68}],9:[function(require,module,exports){
'use strict';
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _require = require('../utils/checkBucketName'),
_checkBucketName = _require.checkBucketName;
var proto = exports;
/**
* getBucketVersioning
* @param {String} bucketName - bucket name
*/
proto.getBucketVersioning = function getBucketVersioning(bucketName, options) {
var params, result, versionStatus;
return _regenerator2.default.async(function getBucketVersioning$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_checkBucketName(bucketName);
params = this._bucketRequestParams('GET', bucketName, 'versioning', options);
params.xmlResponse = true;
params.successStatuses = [200];
_context.next = 6;
return _regenerator2.default.awrap(this.request(params));
case 6:
result = _context.sent;
versionStatus = result.data.Status;
return _context.abrupt('return', {
status: result.status,
versionStatus: versionStatus,
res: result.res
});
case 9:
case 'end':
return _context.stop();
}
}
}, null, this);
};
},{"../utils/checkBucketName":35,"babel-runtime/regenerator":68}],10:[function(require,module,exports){
'use strict';
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _require = require('../utils/checkBucketName'),
_checkBucketName = _require.checkBucketName;
var _require2 = require('../utils/isObject'),
isObject = _require2.isObject;
var proto = exports;
proto.getBucketWebsite = function getBucketWebsite(name, options) {
var params, result, routingRules;
return _regenerator2.default.async(function getBucketWebsite$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_checkBucketName(name);
params = this._bucketRequestParams('GET', name, 'website', options);
params.successStatuses = [200];
params.xmlResponse = true;
_context.next = 6;
return _regenerator2.default.awrap(this.request(params));
case 6:
result = _context.sent;
routingRules = [];
if (result.data.RoutingRules && result.data.RoutingRules.RoutingRule) {
if (isObject(result.data.RoutingRules.RoutingRule)) {
routingRules = [result.data.RoutingRules.RoutingRule];
} else {
routingRules = result.data.RoutingRules.RoutingRule;
}
}
return _context.abrupt('return', {
index: result.data.IndexDocument && result.data.IndexDocument.Suffix || '',
supportSubDir: result.data.IndexDocument && result.data.IndexDocument.SupportSubDir || 'false',
type: result.data.IndexDocument && result.data.IndexDocument.Type,
routingRules: routingRules,
error: result.data.ErrorDocument && result.data.ErrorDocument.Key || null,
res: result.res
});
case 10:
case 'end':
return _context.stop();
}
}
}, null, this);
};
},{"../utils/checkBucketName":35,"../utils/isObject":46,"babel-runtime/regenerator":68}],11:[function(require,module,exports){
'use strict';
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable no-use-before-define */
var _require = require('../utils/checkBucketName'),
_checkBucketName = _require.checkBucketName;
var _require2 = require('../utils/isArray'),
isArray = _require2.isArray;
var _require3 = require('../utils/deepCopy'),
deepCopy = _require3.deepCopy;
var _require4 = require('../utils/isObject'),
isObject = _require4.isObject;
var _require5 = require('../utils/obj2xml'),
obj2xml = _require5.obj2xml;
var _require6 = require('../utils/checkObjectTag'),
checkObjectTag = _require6.checkObjectTag;
var _require7 = require('../utils/getStrBytesCount'),
getStrBytesCount = _require7.getStrBytesCount;
var proto = exports;
proto.putBucketLifecycle = function putBucketLifecycle(name, rules, options) {
var params, Rule, paramXMLObj, paramXML, result;
return _regenerator2.default.async(function putBucketLifecycle$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_checkBucketName(name);
if (isArray(rules)) {
_context.next = 3;
break;
}
throw new Error('rules must be Array');
case 3:
params = this._bucketRequestParams('PUT', name, 'lifecycle', options);
Rule = [];
paramXMLObj = {
LifecycleConfiguration: {
Rule: Rule
}
};
rules.forEach(function (_) {
defaultDaysAndDate2Expiration(_); // todo delete, 兼容旧版本
checkRule(_);
if (_.id) {
_.ID = _.id;
delete _.id;
}
Rule.push(_);
});
paramXML = obj2xml(paramXMLObj, {
headers: true,
firstUpperCase: true
});
params.content = paramXML;
params.mime = 'xml';
params.successStatuses = [200];
_context.next = 13;
return _regenerator2.default.awrap(this.request(params));
case 13:
result = _context.sent;
return _context.abrupt('return', {
res: result.res
});
case 15:
case 'end':
return _context.stop();
}
}
}, null, this);
};
// todo delete, 兼容旧版本
function defaultDaysAndDate2Expiration(obj) {
if (obj.days) {
obj.expiration = {
days: obj.days
};
}
if (obj.date) {
obj.expiration = {
createdBeforeDate: obj.date
};
}
}
function checkDaysAndDate(obj, key) {
var days = obj.days,
createdBeforeDate = obj.createdBeforeDate;
if (!days && !createdBeforeDate) {
throw new Error(key + ' must includes days or createdBeforeDate');
} else if (days && !/^[1-9][0-9]*$/.test(days)) {
throw new Error('days must be a positive integer');
} else if (createdBeforeDate && !/\d{4}-\d{2}-\d{2}T00:00:00.000Z/.test(createdBeforeDate)) {
throw new Error('createdBeforeDate must be date and conform to iso8601 format');
}
}
function handleCheckTag(tag) {
if (!isArray(tag) && !isObject(tag)) {
throw new Error('tag must be Object or Array');
}
tag = isObject(tag) ? [tag] : tag;
var tagObj = {};
var tagClone = deepCopy(tag);
tagClone.forEach(function (v) {
tagObj[v.key] = v.value;
});
checkObjectTag(tagObj);
}
function checkRule(rule) {
if (rule.id && getStrBytesCount(rule.id) > 255) throw new Error('ID is composed of 255 bytes at most');
if (rule.prefix === '' || rule.prefix === undefined) throw new Error('Rule must includes prefix');
if (!['Enabled', 'Disabled'].includes(rule.status)) throw new Error('Status must be Enabled or Disabled');
if (rule.transition) {
if (!['IA', 'Archive'].includes(rule.transition.storageClass)) throw new Error('StorageClass must be IA or Archive');
checkDaysAndDate(rule.transition, 'Transition');
}
if (rule.expiration) {
if (!rule.expiration.expiredObjectDeleteMarker) {
checkDaysAndDate(rule.expiration, 'Expiration');
} else if (rule.expiration.days || rule.expiration.createdBeforeDate) {
throw new Error('expiredObjectDeleteMarker cannot be used with days or createdBeforeDate');
}
}
if (rule.abortMultipartUpload) {
checkDaysAndDate(rule.abortMultipartUpload, 'AbortMultipartUpload');
}
if (!rule.expiration && !rule.abortMultipartUpload && !rule.transition && !rule.noncurrentVersionTransition) {
throw new Error('Rule must includes expiration or abortMultipartUpload or transition or noncurrentVersionTransition');
}
if (rule.tag) {
if (rule.abortMultipartUpload) {
throw new Error('Tag cannot be used with abortMultipartUpload');
}
handleCheckTag(rule.tag);
}
}
},{"../utils/checkBucketName":35,"../utils/checkObjectTag":36,"../utils/deepCopy":39,"../utils/getStrBytesCount":41,"../utils/isArray":42,"../utils/isObject":46,"../utils/obj2xml":47,"babel-runtime/regenerator":68}],12:[function(require,module,exports){
'use strict';
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _require = require('../utils/checkBucketName'),
_checkBucketName = _require.checkBucketName;
var _require2 = require('../utils/obj2xml'),
obj2xml = _require2.obj2xml;
var proto = exports;
/**
* putBucketVersioning
* @param {String} name - bucket name
* @param {String} status
* @param {Object} options
*/
proto.putBucketVersioning = function putBucketVersioning(name, status) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var params, paramXMLObj, result;
return _regenerator2.default.async(function putBucketVersioning$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_checkBucketName(name);
if (['Enabled', 'Suspended'].includes(status)) {
_context.next = 3;
break;
}
throw new Error('status must be Enabled or Suspended');
case 3:
params = this._bucketRequestParams('PUT', name, 'versioning', options);
paramXMLObj = {
VersioningConfiguration: {
Status: status
}
};
params.mime = 'xml';
params.content = obj2xml(paramXMLObj, {
headers: true
});
_context.next = 9;
return _regenerator2.default.awrap(this.request(params));
case 9:
result = _context.sent;
return _context.abrupt('return', {
res: result.res,
status: result.status
});
case 11:
case 'end':
return _context.stop();
}
}
}, null, this);
};
},{"../utils/checkBucketName":35,"../utils/obj2xml":47,"babel-runtime/regenerator":68}],13:[function(require,module,exports){
'use strict';
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _require = require('../utils/checkBucketName'),
_checkBucketName = _require.checkBucketName;
var _require2 = require('../utils/obj2xml'),
obj2xml = _require2.obj2xml;
var _require3 = require('../utils/isArray'),
isArray = _require3.isArray;
var proto = exports;
proto.putBucketWebsite = function putBucketWebsite(name) {
var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var options = arguments[2];
var params, IndexDocument, WebsiteConfiguration, website, result;
return _regenerator2.default.async(function putBucketWebsite$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_checkBucketName(name);
params = this._bucketRequestParams('PUT', name, 'website', options);
IndexDocument = {
Suffix: config.index || 'index.html'
};
WebsiteConfiguration = {
IndexDocument: IndexDocument
};
website = {
WebsiteConfiguration: WebsiteConfiguration
};
if (config.supportSubDir) {
IndexDocument.SupportSubDir = config.supportSubDir;
}
if (config.type) {
IndexDocument.Type = config.type;
}
if (config.error) {
WebsiteConfiguration.ErrorDocument = {
Key: config.error
};
}
if (!(config.routingRules !== undefined)) {
_context.next = 12;
break;
}
if (isArray(config.routingRules)) {
_context.next = 11;
break;
}
throw new Error('RoutingRules must be Array');
case 11:
WebsiteConfiguration.RoutingRules = {
RoutingRule: config.routingRules
};
case 12:
website = obj2xml(website);
params.content = website;
params.mime = 'xml';
params.successStatuses = [200];
_context.next = 18;
return _regenerator2.default.awrap(this.request(params));
case 18:
result = _context.sent;
return _context.abrupt('return', {
res: result.res
});
case 20:
case 'end':
return _context.stop();
}
}
}, null, this);
};
},{"../utils/checkBucketName":35,"../utils/isArray":42,"../utils/obj2xml":47,"babel-runtime/regenerator":68}],14:[function(require,module,exports){
(function (Buffer){
'use strict';
var _keys = require('babel-runtime/core-js/object/keys');
var _keys2 = _interopRequireDefault(_keys);
var _stringify = require('babel-runtime/core-js/json/stringify');
var _stringify2 = _interopRequireDefault(_stringify);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.encodeCallback = function encodeCallback(reqParams, options) {
reqParams.headers = reqParams.headers || {};
if (!Object.prototype.hasOwnProperty.call(reqParams.headers, 'x-oss-callback')) {
if (options.callback) {
var json = {
callbackUrl: encodeURI(options.callback.url),
callbackBody: options.callback.body
};
if (options.callback.host) {
json.callbackHost = options.callback.host;
}
if (options.callback.contentType) {
json.callbackBodyType = options.callback.contentType;
}
var callback = Buffer.from((0, _stringify2.default)(json)).toString('base64');
reqParams.headers['x-oss-callback'] = callback;
if (options.callback.customValue) {
var callbackVar = {};
(0, _keys2.default)(options.callback.customValue).forEach(function (key) {
callbackVar['x:' + key] = options.callback.customValue[key];
});
reqParams.headers['x-oss-callback-var'] = Buffer.from((0, _stringify2.default)(callbackVar)).toString('base64');
}
}
}
};
}).call(this,require("buffer").Buffer)
},{"babel-runtime/core-js/json/stringify":53,"babel-runtime/core-js/object/keys":60,"buffer":73}],15:[function(require,module,exports){
'use strict';
var _assign = require('babel-runtime/core-js/object/assign');
var _assign2 = _interopRequireDefault(_assign);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var ms = require('humanize-ms');
var urlutil = require('url');
var _require = require('../utils/checkBucketName'),
_checkBucketName = _require.checkBucketName;
function setEndpoint(endpoint, secure) {
var url = urlutil.parse(endpoint);
if (!url.protocol) {
url = urlutil.parse('http' + (secure ? 's' : '') + '://' + endpoint);
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
throw new Error('Endpoint protocol must be http or https.');
}
return url;
}
function setRegion(region, internal, secure) {
var protocol = secure ? 'https://' : 'http://';
var suffix = internal ? '-internal.aliyuncs.com' : '.aliyuncs.com';
var prefix = 'vpc100-oss-cn-';
// aliyun VPC region: https://help.aliyun.com/knowledge_detail/38740.html
if (region.substr(0, prefix.length) === prefix) {
suffix = '.aliyuncs.com';
}
return urlutil.parse(protocol + region + suffix);
}
module.exports = function (options) {
if (!options || !options.accessKeyId || !options.accessKeySecret) {
throw new Error('require accessKeyId, accessKeySecret');
}
if (options.bucket) {
_checkBucketName(options.bucket);
}
var opts = (0, _assign2.default)({
region: 'oss-cn-hangzhou',
internal: false,
secure: false,
timeout: 60000,
bucket: null,
endpoint: null,
cname: false,
isRequestPay: false,
sldEnable: false
}, options);
opts.accessKeyId = opts.accessKeyId.trim();
opts.accessKeySecret = opts.accessKeySecret.trim();
if (opts.timeout) {
opts.timeout = ms(opts.timeout);
}
if (opts.endpoint) {
opts.endpoint = setEndpoint(opts.endpoint, opts.secure);
} else if (opts.region) {
opts.endpoint = setRegion(opts.region, opts.internal, opts.secure);
} else {
throw new Error('require options.endpoint or options.region');
}
opts.inited = true;
return opts;
};
},{"../utils/checkBucketName":35,"babel-runtime/core-js/object/assign":54,"humanize-ms":194,"url":238}],16:[function(require,module,exports){
'use strict';
var merge = require('merge-descriptors');
var proto = exports;
merge(proto, require('./processObjectSave'));
},{"./processObjectSave":17,"merge-descriptors":200}],17:[function(require,module,exports){
'use strict';
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable no-use-before-define */
var _require = require('../utils/checkBucketName'),
_checkBucketName = _require.checkBucketName;
var querystring = require('querystring');
var _require2 = require('js-base64'),
str2Base64 = _require2.Base64.encode;
var proto = exports;
proto.processObjectSave = function processObjectSave(sourceObject, targetObject, process, targetBucket) {
var params, bucketParam, content, result;
return _regenerator2.default.async(function processObjectSave$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
checkArgs(sourceObject, 'sourceObject');
checkArgs(targetObject, 'targetObject');
checkArgs(process, 'process');
targetObject = this._objectName(targetObject);
if (targetBucket) {
_checkBucketName(targetBucket);
}
params = this._objectRequestParams('POST', sourceObject, {
subres: 'x-oss-process'
});
bucketParam = targetBucket ? ',b_' + str2Base64(targetBucket) : '';
targetObject = str2Base64(targetObject);
content = {
'x-oss-process': process + '|sys/saveas,o_' + targetObject + bucketParam
};
params.content = querystring.stringify(content);
_context.next = 12;
return _regenerator2.default.awrap(this.request(params));
case 12:
result = _context.sent;
return _context.abrupt('return', {
res: result.res,
status: result.res.status
});
case 14:
case 'end':
return _context.stop();
}
}
}, null, this);
};
function checkArgs(name, key) {
if (!name) {
throw new Error(key + ' is required');
}
if (typeof name !== 'string') {
throw new Error(key + ' must be String');
}
}
},{"../utils/checkBucketName":35,"babel-runtime/regenerator":68,"js-base64":199,"querystring":212}],18:[function(require,module,exports){
'use strict';
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var copy = require('copy-to');
var callback = require('./callback');
var _require = require('./utils/deepCopy'),
deepCopy = _require.deepCopy;
var proto = exports;
/**
* List the on-going multipart uploads
* https://help.aliyun.com/document_detail/31997.html
* @param {Object} options
* @return {Array} the multipart uploads
*/
proto.listUploads = function listUploads(query, options) {
var opt, params, result, uploads;
return _regenerator2.default.async(function listUploads$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
options = options || {};
opt = {};
copy(options).to(opt);
opt.subres = 'uploads';
params = this._objectRequestParams('GET', '', opt);
params.query = query;
params.xmlResponse = true;
params.successStatuses = [200];
_context.next = 10;
return _regenerator2.default.awrap(this.request(params));
case 10:
result = _context.sent;
uploads = result.data.Upload || [];
if (!Array.isArray(uploads)) {
uploads = [uploads];
}
uploads = uploads.map(function (up) {
return {
name: up.Key,
uploadId: up.UploadId,
initiated: up.Initiated
};
});
return _context.abrupt('return', {
res: result.res,
uploads: uploads,
bucket: result.data.Bucket,
nextKeyMarker: result.data.NextKeyMarker,
nextUploadIdMarker: result.data.NextUploadIdMarker,
isTruncated: result.data.IsTruncated === 'true'
});
case 15:
case 'end':
return _context.stop();
}
}
}, null, this);
};
/**
* List the done uploadPart parts
* @param {String} name object name
* @param {String} uploadId multipart upload id
* @param {Object} query
* {Number} query.max-parts The maximum part number in the response of the OSS. Default value: 1000
* {Number} query.part-number-marker Starting position of a specific list.
* {String} query.encoding-type Specify the encoding of the returned content and the encoding type.
* @param {Object} options
* @return {Object} result
*/
proto.listParts = function listParts(name, uploadId, query, options) {
var opt, params, result;
return _regenerator2.default.async(function listParts$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
options = options || {};
opt = {};
copy(options).to(opt);
opt.subres = {
uploadId: uploadId
};
params = this._objectRequestParams('GET', name, opt);
params.query = query;
params.xmlResponse = true;
params.successStatuses = [200];
_context2.next = 10;
return _regenerator2.default.awrap(this.request(params));
case 10:
result = _context2.sent;
return _context2.abrupt('return', {
res: result.res,
uploadId: result.data.UploadId,
bucket: result.data.Bucket,
name: result.data.Key,
partNumberMarker: result.data.PartNumberMarker,
nextPartNumberMarker: result.data.NextPartNumberMarker,
maxParts: result.data.MaxParts,
isTruncated: result.data.IsTruncated,
parts: result.data.Part || []
});
case 12:
case 'end':
return _context2.stop();
}
}
}, null, this);
};
/**
* Abort a multipart upload transaction
* @param {String} name the object name
* @param {String} uploadId the upload id
* @param {Object} options
*/
proto.abortMultipartUpload = function abortMultipartUpload(name, uploadId, options) {
var opt, params, result;
return _regenerator2.default.async(function abortMultipartUpload$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
this._stop();
options = options || {};
opt = {};
copy(options).to(opt);
opt.subres = { uploadId: uploadId };
params = this._objectRequestParams('DELETE', name, opt);
params.successStatuses = [204];
_context3.next = 9;
return _regenerator2.default.awrap(this.request(params));
case 9:
result = _context3.sent;
return _context3.abrupt('return', {
res: result.res
});
case 11:
case 'end':
return _context3.stop();
}
}
}, null, this);
};
/**
* Initiate a multipart upload transaction
* @param {String} name the object name
* @param {Object} options
* @return {String} upload id
*/
proto.initMultipartUpload = function initMultipartUpload(name, options) {
var opt, params, result;
return _regenerator2.default.async(function initMultipartUpload$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
options = options || {};
opt = {};
copy(options).to(opt);
opt.headers = opt.headers || {};
this._convertMetaToHeaders(options.meta, opt.headers);
opt.subres = 'uploads';
params = this._objectRequestParams('POST', name, opt);
params.mime = options.mime;
params.xmlResponse = true;
params.successStatuses = [200];
_context4.next = 12;
return _regenerator2.default.awrap(this.request(params));
case 12:
result = _context4.sent;
return _context4.abrupt('return', {
res: result.res,
bucket: result.data.Bucket,
name: result.data.Key,
uploadId: result.data.UploadId
});
case 14:
case 'end':
return _context4.stop();
}
}
}, null, this);
};
/**
* Upload a part in a multipart upload transaction
* @param {String} name the object name
* @param {String} uploadId the upload id
* @param {Integer} partNo the part number
* @param {File} file upload File, whole File
* @param {Integer} start part start bytes e.g: 102400
* @param {Integer} end part end bytes e.g: 204800
* @param {Object} options
*/
proto.uploadPart = function uploadPart(name, uploadId, partNo, file, start, end, options) {
var data;
return _regenerator2.default.async(function uploadPart$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
data = {
stream: this._createStream(file, start, end),
size: end - start
};
_context5.next = 3;
return _regenerator2.default.awrap(this._uploadPart(name, uploadId, partNo, data, options));
case 3:
return _context5.abrupt('return', _context5.sent);
case 4:
case 'end':
return _context5.stop();
}
}
}, null, this);
};
/**
* Complete a multipart upload transaction
* @param {String} name the object name
* @param {String} uploadId the upload id
* @param {Array} parts the uploaded parts, each in the structure:
* {Integer} number partNo
* {String} etag part etag uploadPartCopy result.res.header.etag
* @param {Object} options
* {Object} options.callback The callback parameter is composed of a JSON string encoded in Base64
* {String} options.callback.url the OSS sends a callback request to this URL
* {String} options.callback.host The host header value for initiating callback requests
* {String} options.callback.body The value of the request body when a callback is initiated
* {String} options.callback.contentType The Content-Type of the callback requests initiatiated
* {Object} options.callback.customValue Custom parameters are a map of key-values, e.g:
* customValue = {
* key1: 'value1',
* key2: 'value2'
* }
*/
proto.completeMultipartUpload = function completeMultipartUpload(name, uploadId, parts, options) {
var completeParts, xml, i, p, opt, params, result, ret;
return _regenerator2.default.async(function completeMultipartUpload$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
completeParts = parts.concat().sort(function (a, b) {
return a.number - b.number;
}).filter(function (item, index, arr) {
return !index || item.number !== arr[index - 1].number;
});
xml = '<?xml version="1.0" encoding="UTF-8"?>\n<CompleteMultipartUpload>\n';
for (i = 0; i < completeParts.length; i++) {
p = completeParts[i];
xml += '<Part>\n';
xml += '<PartNumber>' + p.number + '</PartNumber>\n';
xml += '<ETag>' + p.etag + '</ETag>\n';
xml += '</Part>\n';
}
xml += '</CompleteMultipartUpload>';
options = options || {};
opt = {};
opt = deepCopy(options);
if (opt.headers) delete opt.headers['x-oss-server-side-encryption'];
opt.subres = { uploadId: uploadId };
params = this._objectRequestParams('POST', name, opt);
callback.encodeCallback(params, opt);
params.mime = 'xml';
params.content = xml;
if (!(params.headers && params.headers['x-oss-callback'])) {
params.xmlResponse = true;
}
params.successStatuses = [200];
_context6.next = 17;
return _regenerator2.default.awrap(this.request(params));
case 17:
result = _context6.sent;
ret = {
res: result.res,
bucket: params.bucket,
name: name,
etag: result.res.headers.etag
};
if (params.headers && params.headers['x-oss-callback']) {
ret.data = JSON.parse(result.data.toString());
}
return _context6.abrupt('return', ret);
case 21:
case 'end':
return _context6.stop();
}
}
}, null, this);
};
/**
* Upload a part in a multipart upload transaction
* @param {String} name the object name
* @param {String} uploadId the upload id
* @param {Integer} partNo the part number
* @param {Object} data the body data
* @param {Object} options
*/
proto._uploadPart = function _uploadPart(name, uploadId, partNo, data, options) {
var opt, params, result;
return _regenerator2.default.async(function _uploadPart$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
options = options || {};
opt = {};
copy(options).to(opt);
opt.headers = {
'Content-Length': data.size
};
opt.subres = {
partNumber: partNo,
uploadId: uploadId
};
params = this._objectRequestParams('PUT', name, opt);
params.mime = opt.mime;
params.stream = data.stream;
params.successStatuses = [200];
_context7.next = 11;
return _regenerator2.default.awrap(this.request(params));
case 11:
result = _context7.sent;
if (result.res.headers.etag) {
_context7.next = 14;
break;
}
throw new Error('Please set the etag of expose-headers in OSS \n https://help.aliyun.com/document_detail/32069.html');
case 14:
data.stream = null;
params.stream = null;
return _context7.abrupt('return', {
name: name,
etag: result.res.headers.etag,
res: result.res
});
case 17:
case 'end':
return _context7.stop();
}
}
}, null, this);
};
},{"./callback":14,"./utils/deepCopy":39,"babel-runtime/regenerator":68,"copy-to":76}],19:[function(require,module,exports){
'use strict';
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _keys = require('babel-runtime/core-js/object/keys');
var _keys2 = _interopRequireDefault(_keys);
var _typeof2 = require('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _require = require('../utils/checkBucketName'),
_checkBucketName = _require.checkBucketName;
var proto = exports;
proto.copy = function copy(name, sourceName, bucketName, options) {
var params, result, data;
return _regenerator2.default.async(function copy$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if ((typeof bucketName === 'undefined' ? 'undefined' : (0, _typeof3.default)(bucketName)) === 'object') {
options = bucketName; // 兼容旧版本旧版本第三个参数为options
}
options = options || {};
options.headers = options.headers || {};
(0, _keys2.default)(options.headers).forEach(function (key) {
options.headers['x-oss-copy-source-' + key.toLowerCase()] = options.headers[key];
});
if (options.meta) {
options.headers['x-oss-metadata-directive'] = 'REPLACE';
}
this._convertMetaToHeaders(options.meta, options.headers);
sourceName = this._getSourceName(sourceName, bucketName);
if (options.versionId) {
sourceName = sourceName + '?versionId=' + options.versionId;
}
options.headers['x-oss-copy-source'] = sourceName;
params = this._objectRequestParams('PUT', name, options);
params.xmlResponse = true;
params.successStatuses = [200, 304];
_context.next = 14;
return _regenerator2.default.awrap(this.request(params));
case 14:
result = _context.sent;
data = result.data;
if (data) {
data = {
etag: data.ETag,
lastModified: data.LastModified
};
}
return _context.abrupt('return', {
data: data,
res: result.res
});
case 18:
case 'end':
return _context.stop();
}
}
}, null, this);
};
// todo delete
proto._getSourceName = function _getSourceName(sourceName, bucketName) {
if (typeof bucketName === 'string') {
sourceName = this._objectName(sourceName);
} else if (sourceName[0] !== '/') {
bucketName = this.options.bucket;
} else {
bucketName = sourceName.replace(/\/(.+?)(\/.*)/, '$1');
sourceName = sourceName.replace(/(\/.+?\/)(.*)/, '$2');
}
_checkBucketName(bucketName);
sourceName = encodeURI(sourceName);
sourceName = '/' + bucketName + '/' + sourceName;
return sourceName;
};
},{"../utils/checkBucketName":35,"babel-runtime/core-js/object/keys":60,"babel-runtime/helpers/typeof":67,"babel-runtime/regenerator":68}],20:[function(require,module,exports){
'use strict';
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _assign = require('babel-runtime/core-js/object/assign');
var _assign2 = _interopRequireDefault(_assign);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var proto = exports;
/**
* delete
* @param {String} name - object name
* @param {Object} options
* @param {{res}}
*/
proto.delete = function _delete(name) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var params, result;
return _regenerator2.default.async(function _delete$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
options.subres = (0, _assign2.default)({}, options.subres);
if (options.versionId) {
options.subres.versionId = options.versionId;
}
params = this._objectRequestParams('DELETE', name, options);
params.successStatuses = [204];
_context.next = 6;
return _regenerator2.default.awrap(this.request(params));
case 6:
result = _context.sent;
return _context.abrupt('return', {
res: result.res
});
case 8:
case 'end':
return _context.stop();
}
}
}, null, this);
};
},{"babel-runtime/core-js/object/assign":54,"babel-runtime/regenerator":68}],21:[function(require,module,exports){
'use strict';
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _assign = require('babel-runtime/core-js/object/assign');
var _assign2 = _interopRequireDefault(_assign);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable object-curly-newline */
var utility = require('utility');
var _require = require('../utils/obj2xml'),
obj2xml = _require.obj2xml;
var proto = exports;
proto.deleteMulti = function deleteMulti(names) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var objects, i, object, _names$i, key, versionId, paramXMLObj, paramXML, params, result, r, deleted;
return _regenerator2.default.async(function deleteMulti$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
objects = [];
if (!(!names || !names.length)) {
_context.next = 3;
break;
}
throw new Error('names is required');
case 3:
for (i = 0; i < names.length; i++) {
object = {};
if (typeof names[i] === 'string') {
object.Key = utility.escape(this._objectName(names[i]));
} else {
_names$i = names[i], key = _names$i.key, versionId = _names$i.versionId;
object.Key = utility.escape(this._objectName(key));
object.VersionId = versionId;
}
objects.push(object);
}
paramXMLObj = {
Delete: {
Quiet: !!options.quiet,
Object: objects
}
};
paramXML = obj2xml(paramXMLObj, {
headers: true
});
options.subres = (0, _assign2.default)({ delete: '' }, options.subres);
if (options.versionId) {
options.subres.versionId = options.versionId;
}
params = this._objectRequestParams('POST', '', options);
params.mime = 'xml';
params.content = paramXML;
params.xmlResponse = true;
params.successStatuses = [200];
_context.next = 15;
return _regenerator2.default.awrap(this.request(params));
case 15:
result = _context.sent;
r = result.data;
deleted = r && r.Deleted || null;
if (deleted) {
if (!Array.isArray(deleted)) {
deleted = [deleted];
}
}
return _context.abrupt('return', {
res: result.res,
deleted: deleted || []
});
case 20:
case 'end':
return _context.stop();
}
}
}, null, this);
};
},{"../utils/obj2xml":47,"babel-runtime/core-js/object/assign":54,"babel-runtime/regenerator":68,"utility":290}],22:[function(require,module,exports){
'use strict';
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _assign = require('babel-runtime/core-js/object/assign');
var _assign2 = _interopRequireDefault(_assign);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var proto = exports;
/**
* deleteObjectTagging
* @param {String} name - object name
* @param {Object} options
*/
proto.deleteObjectTagging = function deleteObjectTagging(name) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var params, result;
return _regenerator2.default.async(function deleteObjectTagging$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
options.subres = (0, _assign2.default)({ tagging: '' }, options.subres);
if (options.versionId) {
options.subres.versionId = options.versionId;
}
name = this._objectName(name);
params = this._objectRequestParams('DELETE', name, options);
params.successStatuses = [204];
_context.next = 7;
return _regenerator2.default.awrap(this.request(params));
case 7:
result = _context.sent;
return _context.abrupt('return', {
status: result.status,
res: result.res
});
case 9:
case 'end':
return _context.stop();
}
}
}, null, this);
};
},{"babel-runtime/core-js/object/assign":54,"babel-runtime/regenerator":68}],23:[function(require,module,exports){
'use strict';
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _assign = require('babel-runtime/core-js/object/assign');
var _assign2 = _interopRequireDefault(_assign);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var fs = require('fs');
var is = require('is-type-of');
var proto = exports;
/**
* get
* @param {String} name - object name
* @param {String | Stream} file
* @param {Object} options
* @param {{res}}
*/
proto.get = function get(name, file) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var writeStream, needDestroy, result, params;
return _regenerator2.default.async(function get$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
writeStream = null;
needDestroy = false;
if (is.writableStream(file)) {
writeStream = file;
} else if (is.string(file)) {
writeStream = fs.createWriteStream(file);
needDestroy = true;
} else {
// get(name, options)
options = file;
}
options = options || {};
options.subres = (0, _assign2.default)({}, options.subres);
if (options.versionId) {
options.subres.versionId = options.versionId;
}
if (options.process) {
options.subres['x-oss-process'] = options.process;
}
result = void 0;
_context.prev = 8;
params = this._objectRequestParams('GET', name, options);
params.writeStream = writeStream;
params.successStatuses = [200, 206, 304];
_context.next = 14;
return _regenerator2.default.awrap(this.request(params));
case 14:
result = _context.sent;
if (needDestroy) {
writeStream.destroy();
}
_context.next = 25;
break;
case 18:
_context.prev = 18;
_context.t0 = _context['catch'](8);
if (!needDestroy) {
_context.next = 24;
break;
}
writeStream.destroy();
// should delete the exists file before throw error
_context.next = 24;
return _regenerator2.default.awrap(this._deleteFileSafe(file));
case 24:
throw _context.t0;
case 25:
return _context.abrupt('return', {
res: result.res,
content: result.data
});
case 26:
case 'end':
return _context.stop();
}
}
}, null, this, [[8, 18]]);
};
},{"babel-runtime/core-js/object/assign":54,"babel-runtime/regenerator":68,"fs":71,"is-type-of":289}],24:[function(require,module,exports){
'use strict';
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _assign = require('babel-runtime/core-js/object/assign');
var _assign2 = _interopRequireDefault(_assign);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var proto = exports;
/*
* Get object's ACL
* @param {String} name the object key
* @param {Object} options
* @return {Object}
*/
proto.getACL = function getACL(name) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var params, result;
return _regenerator2.default.async(function getACL$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
options.subres = (0, _assign2.default)({ acl: '' }, options.subres);
if (options.versionId) {
options.subres.versionId = options.versionId;
}
name = this._objectName(name);
params = this._objectRequestParams('GET', name, options);
params.successStatuses = [200];
params.xmlResponse = true;
_context.next = 8;
return _regenerator2.default.awrap(this.request(params));
case 8:
result = _context.sent;
return _context.abrupt('return', {
acl: result.data.AccessControlList.Grant,
owner: {
id: result.data.Owner.ID,
displayName: result.data.Owner.DisplayName
},
res: result.res
});
case 10:
case 'end':
return _context.stop();
}
}
}, null, this);
};
},{"babel-runtime/core-js/object/assign":54,"babel-runtime/regenerator":68}],25:[function(require,module,exports){
'use strict';
var _keys = require('babel-runtime/core-js/object/keys');
var _keys2 = _interopRequireDefault(_keys);
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _assign = require('babel-runtime/core-js/object/assign');
var _assign2 = _interopRequireDefault(_assign);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable no-use-before-define */
var proto = exports;
var _require = require('../utils/isObject'),
isObject = _require.isObject;
var _require2 = require('../utils/isArray'),
isArray = _require2.isArray;
proto.getBucketVersions = getBucketVersions;
proto.listObjectVersions = getBucketVersions;
function getBucketVersions() {
var query = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var params, result, objects, deleteMarker, that, prefixes;
return _regenerator2.default.async(function getBucketVersions$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (!(query.versionIdMarker && query.keyMarker === undefined)) {
_context.next = 2;
break;
}
throw new Error('A version-id marker cannot be specified without a key marker');
case 2:
options.subres = (0, _assign2.default)({ versions: '' }, options.subres);
if (options.versionId) {
options.subres.versionId = options.versionId;
}
params = this._objectRequestParams('GET', '', options);
params.xmlResponse = true;
params.successStatuses = [200];
params.query = formatQuery(query);
_context.next = 10;
return _regenerator2.default.awrap(this.request(params));
case 10:
result = _context.sent;
objects = result.data.Version || [];
deleteMarker = result.data.DeleteMarker || [];
that = this;
if (objects) {
if (!Array.isArray(objects)) {
objects = [objects];
}
objects = objects.map(function (obj) {
return {
name: obj.Key,
url: that._objectUrl(obj.Key),
lastModified: obj.LastModified,
isLatest: obj.IsLatest === 'true',
versionId: obj.VersionId,
etag: obj.ETag,
type: obj.Type,
size: Number(obj.Size),
storageClass: obj.StorageClass,
owner: {
id: obj.Owner.ID,
displayName: obj.Owner.DisplayName
}
};
});
}
if (deleteMarker) {
if (!isArray(deleteMarker)) {
deleteMarker = [deleteMarker];
}
deleteMarker = deleteMarker.map(function (obj) {
return {
name: obj.Key,
lastModified: obj.LastModified,
versionId: obj.VersionId,
owner: {
id: obj.Owner.ID,
displayName: obj.Owner.DisplayName
}
};
});
}
prefixes = result.data.CommonPrefixes || null;
if (prefixes) {
if (!isArray(prefixes)) {
prefixes = [prefixes];
}
prefixes = prefixes.map(function (item) {
return item.Prefix;
});
}
return _context.abrupt('return', {
res: result.res,
objects: objects,
deleteMarker: deleteMarker,
prefixes: prefixes,
nextMarker: result.data.NextMarker || null,
NextVersionIdMarker: result.data.NextVersionIdMarker || null,
isTruncated: result.data.IsTruncated === 'true'
});
case 19:
case 'end':
return _context.stop();
}
}
}, null, this);
}
function camel2Line(name) {
return name.replace(/([A-Z])/g, '-$1').toLowerCase();
}
function formatQuery() {
var query = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var obj = {};
if (isObject(query)) {
(0, _keys2.default)(query).forEach(function (key) {
obj[camel2Line(key)] = query[key];
});
}
return obj;
}
},{"../utils/isArray":42,"../utils/isObject":46,"babel-runtime/core-js/object/assign":54,"babel-runtime/core-js/object/keys":60,"babel-runtime/regenerator":68}],26:[function(require,module,exports){
'use strict';
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _assign = require('babel-runtime/core-js/object/assign');
var _assign2 = _interopRequireDefault(_assign);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var proto = exports;
/**
* getObjectMeta
* @param {String} name - object name
* @param {Object} options
* @param {{res}}
*/
proto.getObjectMeta = function getObjectMeta(name, options) {
var params, result;
return _regenerator2.default.async(function getObjectMeta$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
options = options || {};
name = this._objectName(name);
options.subres = (0, _assign2.default)({ objectMeta: '' }, options.subres);
if (options.versionId) {
options.subres.versionId = options.versionId;
}
params = this._objectRequestParams('HEAD', name, options);
params.successStatuses = [200];
_context.next = 8;
return _regenerator2.default.awrap(this.request(params));
case 8:
result = _context.sent;
return _context.abrupt('return', {
status: result.status,
res: result.res
});
case 10:
case 'end':
return _context.stop();
}
}
}, null, this);
};
},{"babel-runtime/core-js/object/assign":54,"babel-runtime/regenerator":68}],27:[function(require,module,exports){
'use strict';
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _assign = require('babel-runtime/core-js/object/assign');
var _assign2 = _interopRequireDefault(_assign);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var proto = exports;
var _require = require('../utils/isObject'),
isObject = _require.isObject;
/**
* getObjectTagging
* @param {String} name - object name
* @param {Object} options
* @return {Object}
*/
proto.getObjectTagging = function getObjectTagging(name) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var params, result, Tagging, Tag, tag;
return _regenerator2.default.async(function getObjectTagging$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
options.subres = (0, _assign2.default)({ tagging: '' }, options.subres);
if (options.versionId) {
options.subres.versionId = options.versionId;
}
name = this._objectName(name);
params = this._objectRequestParams('GET', name, options);
params.successStatuses = [200];
_context.next = 7;
return _regenerator2.default.awrap(this.request(params));
case 7:
result = _context.sent;
_context.next = 10;
return _regenerator2.default.awrap(this.parseXML(result.data));
case 10:
Tagging = _context.sent;
Tag = Tagging.TagSet.Tag;
Tag = Tag && isObject(Tag) ? [Tag] : Tag || [];
tag = {};
Tag.forEach(function (item) {
tag[item.Key] = item.Value;
});
return _context.abrupt('return', {
status: result.status,
res: result.res,
tag: tag
});
case 16:
case 'end':
return _context.stop();
}
}
}, null, this);
};
},{"../utils/isObject":46,"babel-runtime/core-js/object/assign":54,"babel-runtime/regenerator":68}],28:[function(require,module,exports){
'use strict';
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _assign = require('babel-runtime/core-js/object/assign');
var _assign2 = _interopRequireDefault(_assign);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var proto = exports;
/**
* getSymlink
* @param {String} name - object name
* @param {Object} options
* @param {{res}}
*/
proto.getSymlink = function getSymlink(name) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var params, result, target;
return _regenerator2.default.async(function getSymlink$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
options.subres = (0, _assign2.default)({ symlink: '' }, options.subres);
if (options.versionId) {
options.subres.versionId = options.versionId;
}
name = this._objectName(name);
params = this._objectRequestParams('GET', name, options);
params.successStatuses = [200];
_context.next = 7;
return _regenerator2.default.awrap(this.request(params));
case 7:
result = _context.sent;
target = result.res.headers['x-oss-symlink-target'];
return _context.abrupt('return', {
targetName: decodeURIComponent(target),
res: result.res
});
case 10:
case 'end':
return _context.stop();
}
}
}, null, this);
};
},{"babel-runtime/core-js/object/assign":54,"babel-runtime/regenerator":68}],29:[function(require,module,exports){
'use strict';
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _keys = require('babel-runtime/core-js/object/keys');
var _keys2 = _interopRequireDefault(_keys);
var _assign = require('babel-runtime/core-js/object/assign');
var _assign2 = _interopRequireDefault(_assign);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var proto = exports;
/**
* head
* @param {String} name - object name
* @param {Object} options
* @param {{res}}
*/
proto.head = function head(name) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var params, result, data;
return _regenerator2.default.async(function head$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
options.subres = (0, _assign2.default)({}, options.subres);
if (options.versionId) {
options.subres.versionId = options.versionId;
}
params = this._objectRequestParams('HEAD', name, options);
params.successStatuses = [200, 304];
_context.next = 6;
return _regenerator2.default.awrap(this.request(params));
case 6:
result = _context.sent;
data = {
meta: null,
res: result.res,
status: result.status
};
if (result.status === 200) {
(0, _keys2.default)(result.headers).forEach(function (k) {
if (k.indexOf('x-oss-meta-') === 0) {
if (!data.meta) {
data.meta = {};
}
data.meta[k.substring(11)] = result.headers[k];
}
});
}
return _context.abrupt('return', data);
case 10:
case 'end':
return _context.stop();
}
}
}, null, this);
};
},{"babel-runtime/core-js/object/assign":54,"babel-runtime/core-js/object/keys":60,"babel-runtime/regenerator":68}],30:[function(require,module,exports){
'use strict';
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _assign = require('babel-runtime/core-js/object/assign');
var _assign2 = _interopRequireDefault(_assign);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var proto = exports;
/*
* Set object's ACL
* @param {String} name the object key
* @param {String} acl the object ACL
* @param {Object} options
*/
proto.putACL = function putACL(name, acl, options) {
var params, result;
return _regenerator2.default.async(function putACL$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
options = options || {};
options.subres = (0, _assign2.default)({ acl: '' }, options.subres);
if (options.versionId) {
options.subres.versionId = options.versionId;
}
options.headers = options.headers || {};
options.headers['x-oss-object-acl'] = acl;
name = this._objectName(name);
params = this._objectRequestParams('PUT', name, options);
params.successStatuses = [200];
_context.next = 10;
return _regenerator2.default.awrap(this.request(params));
case 10:
result = _context.sent;
return _context.abrupt('return', {
res: result.res
});
case 12:
case 'end':
return _context.stop();
}
}
}, null, this);
};
},{"babel-runtime/core-js/object/assign":54,"babel-runtime/regenerator":68}],31:[function(require,module,exports){
'use strict';
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _keys = require('babel-runtime/core-js/object/keys');
var _keys2 = _interopRequireDefault(_keys);
var _assign = require('babel-runtime/core-js/object/assign');
var _assign2 = _interopRequireDefault(_assign);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _require = require('../utils/obj2xml'),
obj2xml = _require.obj2xml;
var _require2 = require('../utils/checkObjectTag'),
checkObjectTag = _require2.checkObjectTag;
var proto = exports;
/**
* putObjectTagging
* @param {String} name - object name
* @param {Object} tag - object tag, eg: `{a: "1", b: "2"}`
* @param {Object} options
*/
proto.putObjectTagging = function putObjectTagging(name, tag) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var params, paramXMLObj, result;
return _regenerator2.default.async(function putObjectTagging$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
checkObjectTag(tag);
options.subres = (0, _assign2.default)({ tagging: '' }, options.subres);
if (options.versionId) {
options.subres.versionId = options.versionId;
}
name = this._objectName(name);
params = this._objectRequestParams('PUT', name, options);
params.successStatuses = [200];
tag = (0, _keys2.default)(tag).map(function (key) {
return {
Key: key,
Value: tag[key]
};
});
paramXMLObj = {
Tagging: {
TagSet: {
Tag: tag
}
}
};
params.mime = 'xml';
params.content = obj2xml(paramXMLObj);
_context.next = 12;
return _regenerator2.default.awrap(this.request(params));
case 12:
result = _context.sent;
return _context.abrupt('return', {
res: result.res,
status: result.status
});
case 14:
case 'end':
return _context.stop();
}
}
}, null, this);
};
},{"../utils/checkObjectTag":36,"../utils/obj2xml":47,"babel-runtime/core-js/object/assign":54,"babel-runtime/core-js/object/keys":60,"babel-runtime/regenerator":68}],32:[function(require,module,exports){
'use strict';
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _assign = require('babel-runtime/core-js/object/assign');
var _assign2 = _interopRequireDefault(_assign);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var proto = exports;
/**
* putSymlink
* @param {String} name - object name
* @param {String} targetName - target name
* @param {Object} options
* @param {{res}}
*/
proto.putSymlink = function putSymlink(name, targetName, options) {
var params, result;
return _regenerator2.default.async(function putSymlink$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
options = options || {};
options.headers = options.headers || {};
targetName = this._escape(this._objectName(targetName));
this._convertMetaToHeaders(options.meta, options.headers);
options.headers['x-oss-symlink-target'] = targetName;
options.subres = (0, _assign2.default)({ symlink: '' }, options.subres);
if (options.versionId) {
options.subres.versionId = options.versionId;
}
if (options.storageClass) {
options.headers['x-oss-storage-class'] = options.storageClass;
}
name = this._objectName(name);
params = this._objectRequestParams('PUT', name, options);
params.successStatuses = [200];
_context.next = 13;
return _regenerator2.default.awrap(this.request(params));
case 13:
result = _context.sent;
return _context.abrupt('return', {
res: result.res
});
case 15:
case 'end':
return _context.stop();
}
}
}, null, this);
};
},{"babel-runtime/core-js/object/assign":54,"babel-runtime/regenerator":68}],33:[function(require,module,exports){
'use strict';
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _promise = require('babel-runtime/core-js/promise');
var _promise2 = _interopRequireDefault(_promise);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var proto = exports;
proto._parallelNode = function _parallelNode(todo, parallel, fn, sourceData) {
var that, jobErr, jobs, tempBatch, remainder, batch, taskIndex, i;
return _regenerator2.default.async(function _parallelNode$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
that = this;
// upload in parallel
jobErr = [];
jobs = [];
tempBatch = todo.length / parallel;
remainder = todo.length % parallel;
batch = remainder === 0 ? tempBatch : (todo.length - remainder) / parallel + 1;
taskIndex = 1;
i = 0;
case 8:
if (!(i < todo.length)) {
_context.next = 26;
break;
}
if (!that.isCancel()) {
_context.next = 11;
break;
}
return _context.abrupt('break', 26);
case 11:
if (sourceData) {
jobs.push(fn(that, todo[i], sourceData));
} else {
jobs.push(fn(that, todo[i]));
}
if (!(jobs.length === parallel || taskIndex === batch && i === todo.length - 1)) {
_context.next = 23;
break;
}
_context.prev = 13;
taskIndex += 1;
/* eslint no-await-in-loop: [0] */
_context.next = 17;
return _regenerator2.default.awrap(_promise2.default.all(jobs));
case 17:
_context.next = 22;
break;
case 19:
_context.prev = 19;
_context.t0 = _context['catch'](13);
jobErr.push(_context.t0);
case 22:
jobs = [];
case 23:
i++;
_context.next = 8;
break;
case 26:
return _context.abrupt('return', jobErr);
case 27:
case 'end':
return _context.stop();
}
}
}, null, this, [[13, 19]]);
};
proto._parallel = function _parallel(todo, parallel, jobPromise) {
var that = this;
return new _promise2.default(function (resolve) {
var _jobErr = [];
if (parallel <= 0 || !todo) {
resolve(_jobErr);
return;
}
function onlyOnce(fn) {
return function () {
if (fn === null) throw new Error('Callback was already called.');
var callFn = fn;
fn = null;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
callFn.apply(this, args);
};
}
function createArrayIterator(coll) {
var i = -1;
var len = coll.length;
return function next() {
return ++i < len && !that.isCancel() ? { value: coll[i], key: i } : null;
};
}
var nextElem = createArrayIterator(todo);
var done = false;
var running = 0;
var looping = false;
function iterateeCallback(err, value) {
running -= 1;
if (err) {
done = true;
_jobErr.push(err);
resolve(_jobErr);
} else if (value === {} || done && running <= 0) {
done = true;
resolve(_jobErr);
} else if (!looping) {
/* eslint no-use-before-define: [0] */
if (that.isCancel()) {
resolve(_jobErr);
} else {
replenish();
}
}
}
function iteratee(value, callback) {
jobPromise(value).then(function (result) {
callback(null, result);
}).catch(function (err) {
callback(err);
});
}
function replenish() {
looping = true;
while (running < parallel && !done && !that.isCancel()) {
var elem = nextElem();
if (elem === null || _jobErr.length > 0) {
done = true;
if (running <= 0) {
resolve(_jobErr);
}
return;
}
running += 1;
iteratee(elem.value, onlyOnce(iterateeCallback));
}
looping = false;
}
replenish();
});
};
/**
* cancel operation, now can use with multipartUpload
* @param {Object} abort
* {String} anort.name object key
* {String} anort.uploadId upload id
* {String} anort.options timeout
*/
proto.cancel = function cancel(abort) {
this.options.cancelFlag = true;
if (abort) {
this.abortMultipartUpload(abort.name, abort.uploadId, abort.options);
}
};
proto.isCancel = function isCancel() {
return this.options.cancelFlag;
};
proto.resetCancelFlag = function resetCancelFlag() {
this.options.cancelFlag = false;
};
proto._stop = function _stop() {
this.options.cancelFlag = true;
};
// cancel is not error , so create an object
proto._makeCancelEvent = function _makeCancelEvent() {
var cancelEvent = {
status: 0,
name: 'cancel'
};
return cancelEvent;
};
},{"babel-runtime/core-js/promise":61,"babel-runtime/regenerator":68}],34:[function(require,module,exports){
(function (Buffer){
'use strict';
var _stringify = require('babel-runtime/core-js/json/stringify');
var _stringify2 = _interopRequireDefault(_stringify);
var _keys = require('babel-runtime/core-js/object/keys');
var _keys2 = _interopRequireDefault(_keys);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var crypto = require('./../../shims/crypto/crypto.js');
var is = require('is-type-of');
/**
*
* @param {String} resourcePath
* @param {Object} parameters
* @return
*/
exports.buildCanonicalizedResource = function buildCanonicalizedResource(resourcePath, parameters) {
var canonicalizedResource = '' + resourcePath;
var separatorString = '?';
if (is.string(parameters) && parameters.trim() !== '') {
canonicalizedResource += separatorString + parameters;
} else if (is.array(parameters)) {
parameters.sort();
canonicalizedResource += separatorString + parameters.join('&');
} else if (parameters) {
var compareFunc = function compareFunc(entry1, entry2) {
if (entry1[0] > entry2[0]) {
return 1;
} else if (entry1[0] < entry2[0]) {
return -1;
}
return 0;
};
var processFunc = function processFunc(key) {
canonicalizedResource += separatorString + key;
if (parameters[key]) {
canonicalizedResource += '=' + parameters[key];
}
separatorString = '&';
};
(0, _keys2.default)(parameters).sort(compareFunc).forEach(processFunc);
}
return canonicalizedResource;
};
/**
* @param {String} method
* @param {String} resourcePath
* @param {Object} request
* @param {String} expires
* @return {String} canonicalString
*/
exports.buildCanonicalString = function canonicalString(method, resourcePath, request, expires) {
request = request || {};
var headers = request.headers || {};
var OSS_PREFIX = 'x-oss-';
var ossHeaders = [];
var headersToSign = {};
var signContent = [method.toUpperCase(), headers['Content-Md5'] || '', headers['Content-Type'] || headers['Content-Type'.toLowerCase()], expires || headers['x-oss-date']];
(0, _keys2.default)(headers).forEach(function (key) {
var lowerKey = key.toLowerCase();
if (lowerKey.indexOf(OSS_PREFIX) === 0) {
headersToSign[lowerKey] = String(headers[key]).trim();
}
});
(0, _keys2.default)(headersToSign).sort().forEach(function (key) {
ossHeaders.push(key + ':' + headersToSign[key]);
});
signContent = signContent.concat(ossHeaders);
signContent.push(this.buildCanonicalizedResource(resourcePath, request.parameters));
return signContent.join('\n');
};
/**
* @param {String} accessKeySecret
* @param {String} canonicalString
*/
exports.computeSignature = function computeSignature(accessKeySecret, canonicalString) {
var signature = crypto.createHmac('sha1', accessKeySecret);
return signature.update(Buffer.from(canonicalString, 'utf8')).digest('base64');
};
/**
* @param {String} accessKeyId
* @param {String} accessKeySecret
* @param {String} canonicalString
*/
exports.authorization = function authorization(accessKeyId, accessKeySecret, canonicalString) {
return 'OSS ' + accessKeyId + ':' + this.computeSignature(accessKeySecret, canonicalString);
};
/**
*
* @param {String} accessKeySecret
* @param {Object} options
* @param {String} resource
* @param {Number} expires
*/
exports._signatureForURL = function _signatureForURL(accessKeySecret) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var resource = arguments[2];
var expires = arguments[3];
var headers = {};
var _options$subResource = options.subResource,
subResource = _options$subResource === undefined ? {} : _options$subResource;
if (options.process) {
var processKeyword = 'x-oss-process';
subResource[processKeyword] = options.process;
}
if (options.trafficLimit) {
var trafficLimitKey = 'x-oss-traffic-limit';
subResource[trafficLimitKey] = options.trafficLimit;
}
if (options.response) {
(0, _keys2.default)(options.response).forEach(function (k) {
var key = 'response-' + k.toLowerCase();
subResource[key] = options.response[k];
});
}
(0, _keys2.default)(options).forEach(function (key) {
var lowerKey = key.toLowerCase();
var value = options[key];
if (lowerKey.indexOf('x-oss-') === 0) {
headers[lowerKey] = value;
} else if (lowerKey.indexOf('content-md5') === 0) {
headers[key] = value;
} else if (lowerKey.indexOf('content-type') === 0) {
headers[key] = value;
}
});
if (Object.prototype.hasOwnProperty.call(options, 'security-token')) {
subResource['security-token'] = options['security-token'];
}
if (Object.prototype.hasOwnProperty.call(options, 'callback')) {
var json = {
callbackUrl: encodeURI(options.callback.url),
callbackBody: options.callback.body
};
if (options.callback.host) {
json.callbackHost = options.callback.host;
}
if (options.callback.contentType) {
json.callbackBodyType = options.callback.contentType;
}
subResource.callback = Buffer.from((0, _stringify2.default)(json)).toString('base64');
if (options.callback.customValue) {
var callbackVar = {};
(0, _keys2.default)(options.callback.customValue).forEach(function (key) {
callbackVar['x:' + key] = options.callback.customValue[key];
});
subResource['callback-var'] = Buffer.from((0, _stringify2.default)(callbackVar)).toString('base64');
}
}
var canonicalString = this.buildCanonicalString(options.method, resource, {
headers: headers,
parameters: subResource
}, expires.toString());
return {
Signature: this.computeSignature(accessKeySecret, canonicalString),
subResource: subResource
};
};
}).call(this,require("buffer").Buffer)
},{"./../../shims/crypto/crypto.js":284,"babel-runtime/core-js/json/stringify":53,"babel-runtime/core-js/object/keys":60,"buffer":73,"is-type-of":289}],35:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkBucketName = void 0;
exports.checkBucketName = function (name, createBucket) {
var bucketRegex = createBucket ? /^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/ : /^[a-z0-9_][a-z0-9-_]{1,61}[a-z0-9_]$/;
if (!bucketRegex.test(name)) {
throw new Error('The bucket must be conform to the specifications');
}
};
},{}],36:[function(require,module,exports){
"use strict";
var _entries = require("babel-runtime/core-js/object/entries");
var _entries2 = _interopRequireDefault(_entries);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkObjectTag = void 0;
var _require = require('./checkValid'),
checkValid = _require.checkValid;
var _require2 = require('./isObject'),
isObject = _require2.isObject;
var commonRules = [{
validator: function validator(value) {
if (typeof value !== 'string') {
throw new Error('the key and value of the tag must be String');
}
}
}, {
pattern: /^[a-zA-Z0-9 +-=._:/]+$/,
msg: 'tag can contain letters, numbers, spaces, and the following symbols: plus sign (+), hyphen (-), equal sign (=), period (.), underscore (_), colon (:), and forward slash (/)'
}];
var rules = {
key: [].concat(commonRules, [{
pattern: /^.{1,128}$/,
msg: 'tag key can be a maximum of 128 bytes in length'
}]),
value: [].concat(commonRules, [{
pattern: /^.{0,256}$/,
msg: 'tag value can be a maximum of 256 bytes in length'
}])
};
function checkObjectTag(tag) {
if (!isObject(tag)) {
throw new Error('tag must be Object');
}
var entries = (0, _entries2.default)(tag);
if (entries.length > 10) {
throw new Error('maximum of 10 tags for a object');
}
var rulesIndexKey = ['key', 'value'];
entries.forEach(function (keyValue) {
keyValue.forEach(function (item, index) {
checkValid(item, rules[rulesIndexKey[index]]);
});
});
}
exports.checkObjectTag = checkObjectTag;
},{"./checkValid":37,"./isObject":46,"babel-runtime/core-js/object/entries":57}],37:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkValid = void 0;
function checkValid(_value, _rules) {
_rules.forEach(function (rule) {
if (rule.validator) {
rule.validator(_value);
} else if (rule.pattern && !rule.pattern.test(_value)) {
throw new Error(rule.msg);
}
});
}
exports.checkValid = checkValid;
},{}],38:[function(require,module,exports){
(function (Buffer){
"use strict";
var _assign = require("babel-runtime/core-js/object/assign");
var _assign2 = _interopRequireDefault(_assign);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
Object.defineProperty(exports, "__esModule", { value: true });
exports.createRequest = void 0;
var crypto = require('./../../../shims/crypto/crypto.js');
var debug = require('debug')('ali-oss');
var mime = require('mime');
var dateFormat = require('dateformat');
var copy = require('copy-to');
var path = require('path');
function getHeader(headers, name) {
return headers[name] || headers[name.toLowerCase()];
}
function delHeader(headers, name) {
delete headers[name];
delete headers[name.toLowerCase()];
}
function createRequest(params) {
var date = new Date();
if (this.options.amendTimeSkewed) {
date = +new Date() + this.options.amendTimeSkewed;
}
var headers = {
'x-oss-date': dateFormat(date, 'UTC:ddd, dd mmm yyyy HH:MM:ss \'GMT\''),
'x-oss-user-agent': this.userAgent
};
if (this.userAgent.includes('nodejs')) {
headers['User-Agent'] = this.userAgent;
}
if (this.options.isRequestPay) {
(0, _assign2.default)(headers, { 'x-oss-request-payer': 'requester' });
}
if (this.options.stsToken) {
headers['x-oss-security-token'] = this.options.stsToken;
}
copy(params.headers).to(headers);
if (!getHeader(headers, 'Content-Type')) {
if (params.mime && params.mime.indexOf('/') > 0) {
headers['Content-Type'] = params.mime;
} else {
headers['Content-Type'] = mime.getType(params.mime || path.extname(params.object || ''));
}
}
if (!getHeader(headers, 'Content-Type')) {
delHeader(headers, 'Content-Type');
}
if (params.content) {
headers['Content-Md5'] = crypto.createHash('md5').update(Buffer.from(params.content, 'utf8')).digest('base64');
if (!headers['Content-Length']) {
headers['Content-Length'] = params.content.length;
}
}
var authResource = this._getResource(params);
headers.authorization = this.authorization(params.method, authResource, params.subres, headers);
var url = this._getReqUrl(params);
debug('request %s %s, with headers %j, !!stream: %s', params.method, url, headers, !!params.stream);
var timeout = params.timeout || this.options.timeout;
var reqParams = {
method: params.method,
content: params.content,
stream: params.stream,
headers: headers,
timeout: timeout,
writeStream: params.writeStream,
customResponse: params.customResponse,
ctx: params.ctx || this.ctx
};
if (this.agent) {
reqParams.agent = this.agent;
}
if (this.httpsAgent) {
reqParams.httpsAgent = this.httpsAgent;
}
return {
url: url,
params: reqParams
};
}
exports.createRequest = createRequest;
}).call(this,require("buffer").Buffer)
},{"./../../../shims/crypto/crypto.js":284,"babel-runtime/core-js/object/assign":54,"buffer":73,"copy-to":76,"dateformat":190,"debug":288,"mime":202,"path":205}],39:[function(require,module,exports){
"use strict";
var _keys = require("babel-runtime/core-js/object/keys");
var _keys2 = _interopRequireDefault(_keys);
var _typeof2 = require("babel-runtime/helpers/typeof");
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
Object.defineProperty(exports, "__esModule", { value: true });
exports.deepCopy = void 0;
exports.deepCopy = function (obj) {
if (obj === null || (typeof obj === "undefined" ? "undefined" : (0, _typeof3.default)(obj)) !== 'object') {
return obj;
}
var copy = Array.isArray(obj) ? [] : {};
(0, _keys2.default)(obj).forEach(function (key) {
copy[key] = exports.deepCopy(obj[key]);
});
return copy;
};
},{"babel-runtime/core-js/object/keys":60,"babel-runtime/helpers/typeof":67}],40:[function(require,module,exports){
"use strict";
var _keys = require("babel-runtime/core-js/object/keys");
var _keys2 = _interopRequireDefault(_keys);
var _typeof2 = require("babel-runtime/helpers/typeof");
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatObjKey = void 0;
function formatObjKey(obj, type) {
if (obj === null || (typeof obj === "undefined" ? "undefined" : (0, _typeof3.default)(obj)) !== 'object') {
return obj;
}
var o = void 0;
if (Array.isArray(obj)) {
o = [];
for (var i = 0; i < obj.length; i++) {
o.push(formatObjKey(obj[i], type));
}
} else {
o = {};
(0, _keys2.default)(obj).forEach(function (key) {
o[handelFormat(key, type)] = formatObjKey(obj[key], type);
});
}
return o;
}
exports.formatObjKey = formatObjKey;
function handelFormat(key, type) {
if (type === 'firstUpperCase') {
key = key.replace(/^./, function (_) {
return _.toUpperCase();
});
} else if (type === 'firstLowerCase') {
key = key.replace(/^./, function (_) {
return _.toLowerCase();
});
}
return key;
}
},{"babel-runtime/core-js/object/keys":60,"babel-runtime/helpers/typeof":67}],41:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getStrBytesCount = void 0;
function getStrBytesCount(str) {
var bytesCount = 0;
for (var i = 0; i < str.length; i++) {
var c = str.charAt(i);
if (/^[\u00-\uff]$/.test(c)) {
bytesCount += 1;
} else {
bytesCount += 2;
}
}
return bytesCount;
}
exports.getStrBytesCount = getStrBytesCount;
},{}],42:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isArray = void 0;
exports.isArray = function (obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
};
},{}],43:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isBlob = void 0;
function isBlob(blob) {
return typeof Blob !== 'undefined' && blob instanceof Blob;
}
exports.isBlob = isBlob;
},{}],44:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isFile = void 0;
exports.isFile = function (obj) {
return typeof File !== 'undefined' && obj instanceof File;
};
},{}],45:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isIP = void 0;
// it provide commont methods for node and browser , we will add more solutions later in this file
/**
* Judge isIP include ipv4 or ipv6
* @param {String} options
* @return {Array} the multipart uploads
*/
exports.isIP = function (host) {
var ipv4Regex = /^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$/;
var ipv6Regex = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/;
return ipv4Regex.test(host) || ipv6Regex.test(host);
};
},{}],46:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isObject = void 0;
exports.isObject = function (obj) {
return Object.prototype.toString.call(obj) === '[object Object]';
};
},{}],47:[function(require,module,exports){
"use strict";
var _keys = require("babel-runtime/core-js/object/keys");
var _keys2 = _interopRequireDefault(_keys);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
Object.defineProperty(exports, "__esModule", { value: true });
exports.obj2xml = void 0;
var formatObjKey_1 = require("./formatObjKey");
function type(params) {
return Object.prototype.toString.call(params).replace(/(.*? |])/g, '').toLowerCase();
}
function obj2xml(obj, options) {
var s = '';
if (options && options.headers) {
s = '<?xml version="1.0" encoding="UTF-8"?>\n';
}
if (options && options.firstUpperCase) {
obj = formatObjKey_1.formatObjKey(obj, 'firstUpperCase');
}
if (type(obj) === 'object') {
(0, _keys2.default)(obj).forEach(function (key) {
if (type(obj[key]) === 'string' || type(obj[key]) === 'number') {
s += "<" + key + ">" + obj[key] + "</" + key + ">";
} else if (type(obj[key]) === 'object') {
s += "<" + key + ">" + obj2xml(obj[key]) + "</" + key + ">";
} else if (type(obj[key]) === 'array') {
s += obj[key].map(function (keyChild) {
return "<" + key + ">" + obj2xml(keyChild) + "</" + key + ">";
}).join('');
} else {
s += "<" + key + ">" + obj[key].toString() + "</" + key + ">";
}
});
} else {
s += obj.toString();
}
return s;
}
exports.obj2xml = obj2xml;
},{"./formatObjKey":40,"babel-runtime/core-js/object/keys":60}],48:[function(require,module,exports){
module.exports = noop;
module.exports.HttpsAgent = noop;
// Noop function for browser since native api's don't use agents.
function noop () {}
},{}],49:[function(require,module,exports){
module.exports = require('./register')().Promise
},{"./register":51}],50:[function(require,module,exports){
"use strict"
// global key for user preferred registration
var REGISTRATION_KEY = '@@any-promise/REGISTRATION',
// Prior registration (preferred or detected)
registered = null
/**
* Registers the given implementation. An implementation must
* be registered prior to any call to `require("any-promise")`,
* typically on application load.
*
* If called with no arguments, will return registration in
* following priority:
*
* For Node.js:
*
* 1. Previous registration
* 2. global.Promise if node.js version >= 0.12
* 3. Auto detected promise based on first sucessful require of
* known promise libraries. Note this is a last resort, as the
* loaded library is non-deterministic. node.js >= 0.12 will
* always use global.Promise over this priority list.
* 4. Throws error.
*
* For Browser:
*
* 1. Previous registration
* 2. window.Promise
* 3. Throws error.
*
* Options:
*
* Promise: Desired Promise constructor
* global: Boolean - Should the registration be cached in a global variable to
* allow cross dependency/bundle registration? (default true)
*/
module.exports = function(root, loadImplementation){
return function register(implementation, opts){
implementation = implementation || null
opts = opts || {}
// global registration unless explicitly {global: false} in options (default true)
var registerGlobal = opts.global !== false;
// load any previous global registration
if(registered === null && registerGlobal){
registered = root[REGISTRATION_KEY] || null
}
if(registered !== null
&& implementation !== null
&& registered.implementation !== implementation){
// Throw error if attempting to redefine implementation
throw new Error('any-promise already defined as "'+registered.implementation+
'". You can only register an implementation before the first '+
' call to require("any-promise") and an implementation cannot be changed')
}
if(registered === null){
// use provided implementation
if(implementation !== null && typeof opts.Promise !== 'undefined'){
registered = {
Promise: opts.Promise,
implementation: implementation
}
} else {
// require implementation if implementation is specified but not provided
registered = loadImplementation(implementation)
}
if(registerGlobal){
// register preference globally in case multiple installations
root[REGISTRATION_KEY] = registered
}
}
return registered
}
}
},{}],51:[function(require,module,exports){
"use strict";
module.exports = require('./loader')(window, loadImplementation)
/**
* Browser specific loadImplementation. Always uses `window.Promise`
*
* To register a custom implementation, must register with `Promise` option.
*/
function loadImplementation(){
if(typeof window.Promise === 'undefined'){
throw new Error("any-promise browser requires a polyfill or explicit registration"+
" e.g: require('any-promise/register/bluebird')")
}
return {
Promise: window.Promise,
implementation: 'window.Promise'
}
}
},{"./loader":50}],52:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/array/from"), __esModule: true };
},{"core-js/library/fn/array/from":77}],53:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/json/stringify"), __esModule: true };
},{"core-js/library/fn/json/stringify":78}],54:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/object/assign"), __esModule: true };
},{"core-js/library/fn/object/assign":79}],55:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/object/create"), __esModule: true };
},{"core-js/library/fn/object/create":80}],56:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/object/define-property"), __esModule: true };
},{"core-js/library/fn/object/define-property":81}],57:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/object/entries"), __esModule: true };
},{"core-js/library/fn/object/entries":82}],58:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/object/get-own-property-names"), __esModule: true };
},{"core-js/library/fn/object/get-own-property-names":83}],59:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/object/get-prototype-of"), __esModule: true };
},{"core-js/library/fn/object/get-prototype-of":84}],60:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/object/keys"), __esModule: true };
},{"core-js/library/fn/object/keys":85}],61:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/promise"), __esModule: true };
},{"core-js/library/fn/promise":86}],62:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/set-immediate"), __esModule: true };
},{"core-js/library/fn/set-immediate":87}],63:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/string/from-code-point"), __esModule: true };
},{"core-js/library/fn/string/from-code-point":88}],64:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/symbol"), __esModule: true };
},{"core-js/library/fn/symbol":90}],65:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/symbol/has-instance"), __esModule: true };
},{"core-js/library/fn/symbol/has-instance":89}],66:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/symbol/iterator"), __esModule: true };
},{"core-js/library/fn/symbol/iterator":91}],67:[function(require,module,exports){
"use strict";
exports.__esModule = true;
var _iterator = require("../core-js/symbol/iterator");
var _iterator2 = _interopRequireDefault(_iterator);
var _symbol = require("../core-js/symbol");
var _symbol2 = _interopRequireDefault(_symbol);
var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) {
return typeof obj === "undefined" ? "undefined" : _typeof(obj);
} : function (obj) {
return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj);
};
},{"../core-js/symbol":64,"../core-js/symbol/iterator":66}],68:[function(require,module,exports){
module.exports = require("regenerator-runtime");
},{"regenerator-runtime":226}],69:[function(require,module,exports){
'use strict'
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i]
revLookup[code.charCodeAt(i)] = i
}
// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
function getLens (b64) {
var len = b64.length
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// Trim off extra bytes after placeholder bytes are found
// See: https://github.com/beatgammit/base64-js/issues/42
var validLen = b64.indexOf('=')
if (validLen === -1) validLen = len
var placeHoldersLen = validLen === len
? 0
: 4 - (validLen % 4)
return [validLen, placeHoldersLen]
}
// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function _byteLength (b64, validLen, placeHoldersLen) {
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function toByteArray (b64) {
var tmp
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
var curByte = 0
// if there are placeholders, only get up to the last complete 4 chars
var len = placeHoldersLen > 0
? validLen - 4
: validLen
var i
for (i = 0; i < len; i += 4) {
tmp =
(revLookup[b64.charCodeAt(i)] << 18) |
(revLookup[b64.charCodeAt(i + 1)] << 12) |
(revLookup[b64.charCodeAt(i + 2)] << 6) |
revLookup[b64.charCodeAt(i + 3)]
arr[curByte++] = (tmp >> 16) & 0xFF
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 2) {
tmp =
(revLookup[b64.charCodeAt(i)] << 2) |
(revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 1) {
tmp =
(revLookup[b64.charCodeAt(i)] << 10) |
(revLookup[b64.charCodeAt(i + 1)] << 4) |
(revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] +
lookup[num >> 12 & 0x3F] +
lookup[num >> 6 & 0x3F] +
lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp
var output = []
for (var i = start; i < end; i += 3) {
tmp =
((uint8[i] << 16) & 0xFF0000) +
((uint8[i + 1] << 8) & 0xFF00) +
(uint8[i + 2] & 0xFF)
output.push(tripletToBase64(tmp))
}
return output.join('')
}
function fromByteArray (uint8) {
var tmp
var len = uint8.length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var parts = []
var maxChunkLength = 16383 // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(
uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
))
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1]
parts.push(
lookup[tmp >> 2] +
lookup[(tmp << 4) & 0x3F] +
'=='
)
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + uint8[len - 1]
parts.push(
lookup[tmp >> 10] +
lookup[(tmp >> 4) & 0x3F] +
lookup[(tmp << 2) & 0x3F] +
'='
)
}
return parts.join('')
}
},{}],70:[function(require,module,exports){
/*!
* Bowser - a browser detector
* https://github.com/ded/bowser
* MIT License | (c) Dustin Diaz 2015
*/
!function (root, name, definition) {
if (typeof module != 'undefined' && module.exports) module.exports = definition()
else if (typeof define == 'function' && define.amd) define(name, definition)
else root[name] = definition()
}(this, 'bowser', function () {
/**
* See useragents.js for examples of navigator.userAgent
*/
var t = true
function detect(ua) {
function getFirstMatch(regex) {
var match = ua.match(regex);
return (match && match.length > 1 && match[1]) || '';
}
function getSecondMatch(regex) {
var match = ua.match(regex);
return (match && match.length > 1 && match[2]) || '';
}
var iosdevice = getFirstMatch(/(ipod|iphone|ipad)/i).toLowerCase()
, likeAndroid = /like android/i.test(ua)
, android = !likeAndroid && /android/i.test(ua)
, nexusMobile = /nexus\s*[0-6]\s*/i.test(ua)
, nexusTablet = !nexusMobile && /nexus\s*[0-9]+/i.test(ua)
, chromeos = /CrOS/.test(ua)
, silk = /silk/i.test(ua)
, sailfish = /sailfish/i.test(ua)
, tizen = /tizen/i.test(ua)
, webos = /(web|hpw)(o|0)s/i.test(ua)
, windowsphone = /windows phone/i.test(ua)
, samsungBrowser = /SamsungBrowser/i.test(ua)
, windows = !windowsphone && /windows/i.test(ua)
, mac = !iosdevice && !silk && /macintosh/i.test(ua)
, linux = !android && !sailfish && !tizen && !webos && /linux/i.test(ua)
, edgeVersion = getSecondMatch(/edg([ea]|ios)\/(\d+(\.\d+)?)/i)
, versionIdentifier = getFirstMatch(/version\/(\d+(\.\d+)?)/i)
, tablet = /tablet/i.test(ua) && !/tablet pc/i.test(ua)
, mobile = !tablet && /[^-]mobi/i.test(ua)
, xbox = /xbox/i.test(ua)
, result
if (/opera/i.test(ua)) {
// an old Opera
result = {
name: 'Opera'
, opera: t
, version: versionIdentifier || getFirstMatch(/(?:opera|opr|opios)[\s\/](\d+(\.\d+)?)/i)
}
} else if (/opr\/|opios/i.test(ua)) {
// a new Opera
result = {
name: 'Opera'
, opera: t
, version: getFirstMatch(/(?:opr|opios)[\s\/](\d+(\.\d+)?)/i) || versionIdentifier
}
}
else if (/SamsungBrowser/i.test(ua)) {
result = {
name: 'Samsung Internet for Android'
, samsungBrowser: t
, version: versionIdentifier || getFirstMatch(/(?:SamsungBrowser)[\s\/](\d+(\.\d+)?)/i)
}
}
else if (/Whale/i.test(ua)) {
result = {
name: 'NAVER Whale browser'
, whale: t
, version: getFirstMatch(/(?:whale)[\s\/](\d+(?:\.\d+)+)/i)
}
}
else if (/MZBrowser/i.test(ua)) {
result = {
name: 'MZ Browser'
, mzbrowser: t
, version: getFirstMatch(/(?:MZBrowser)[\s\/](\d+(?:\.\d+)+)/i)
}
}
else if (/coast/i.test(ua)) {
result = {
name: 'Opera Coast'
, coast: t
, version: versionIdentifier || getFirstMatch(/(?:coast)[\s\/](\d+(\.\d+)?)/i)
}
}
else if (/focus/i.test(ua)) {
result = {
name: 'Focus'
, focus: t
, version: getFirstMatch(/(?:focus)[\s\/](\d+(?:\.\d+)+)/i)
}
}
else if (/yabrowser/i.test(ua)) {
result = {
name: 'Yandex Browser'
, yandexbrowser: t
, version: versionIdentifier || getFirstMatch(/(?:yabrowser)[\s\/](\d+(\.\d+)?)/i)
}
}
else if (/ucbrowser/i.test(ua)) {
result = {
name: 'UC Browser'
, ucbrowser: t
, version: getFirstMatch(/(?:ucbrowser)[\s\/](\d+(?:\.\d+)+)/i)
}
}
else if (/mxios/i.test(ua)) {
result = {
name: 'Maxthon'
, maxthon: t
, version: getFirstMatch(/(?:mxios)[\s\/](\d+(?:\.\d+)+)/i)
}
}
else if (/epiphany/i.test(ua)) {
result = {
name: 'Epiphany'
, epiphany: t
, version: getFirstMatch(/(?:epiphany)[\s\/](\d+(?:\.\d+)+)/i)
}
}
else if (/puffin/i.test(ua)) {
result = {
name: 'Puffin'
, puffin: t
, version: getFirstMatch(/(?:puffin)[\s\/](\d+(?:\.\d+)?)/i)
}
}
else if (/sleipnir/i.test(ua)) {
result = {
name: 'Sleipnir'
, sleipnir: t
, version: getFirstMatch(/(?:sleipnir)[\s\/](\d+(?:\.\d+)+)/i)
}
}
else if (/k-meleon/i.test(ua)) {
result = {
name: 'K-Meleon'
, kMeleon: t
, version: getFirstMatch(/(?:k-meleon)[\s\/](\d+(?:\.\d+)+)/i)
}
}
else if (windowsphone) {
result = {
name: 'Windows Phone'
, osname: 'Windows Phone'
, windowsphone: t
}
if (edgeVersion) {
result.msedge = t
result.version = edgeVersion
}
else {
result.msie = t
result.version = getFirstMatch(/iemobile\/(\d+(\.\d+)?)/i)
}
}
else if (/msie|trident/i.test(ua)) {
result = {
name: 'Internet Explorer'
, msie: t
, version: getFirstMatch(/(?:msie |rv:)(\d+(\.\d+)?)/i)
}
} else if (chromeos) {
result = {
name: 'Chrome'
, osname: 'Chrome OS'
, chromeos: t
, chromeBook: t
, chrome: t
, version: getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.\d+)?)/i)
}
} else if (/edg([ea]|ios)/i.test(ua)) {
result = {
name: 'Microsoft Edge'
, msedge: t
, version: edgeVersion
}
}
else if (/vivaldi/i.test(ua)) {
result = {
name: 'Vivaldi'
, vivaldi: t
, version: getFirstMatch(/vivaldi\/(\d+(\.\d+)?)/i) || versionIdentifier
}
}
else if (sailfish) {
result = {
name: 'Sailfish'
, osname: 'Sailfish OS'
, sailfish: t
, version: getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i)
}
}
else if (/seamonkey\//i.test(ua)) {
result = {
name: 'SeaMonkey'
, seamonkey: t
, version: getFirstMatch(/seamonkey\/(\d+(\.\d+)?)/i)
}
}
else if (/firefox|iceweasel|fxios/i.test(ua)) {
result = {
name: 'Firefox'
, firefox: t
, version: getFirstMatch(/(?:firefox|iceweasel|fxios)[ \/](\d+(\.\d+)?)/i)
}
if (/\((mobile|tablet);[^\)]*rv:[\d\.]+\)/i.test(ua)) {
result.firefoxos = t
result.osname = 'Firefox OS'
}
}
else if (silk) {
result = {
name: 'Amazon Silk'
, silk: t
, version : getFirstMatch(/silk\/(\d+(\.\d+)?)/i)
}
}
else if (/phantom/i.test(ua)) {
result = {
name: 'PhantomJS'
, phantom: t
, version: getFirstMatch(/phantomjs\/(\d+(\.\d+)?)/i)
}
}
else if (/slimerjs/i.test(ua)) {
result = {
name: 'SlimerJS'
, slimer: t
, version: getFirstMatch(/slimerjs\/(\d+(\.\d+)?)/i)
}
}
else if (/blackberry|\bbb\d+/i.test(ua) || /rim\stablet/i.test(ua)) {
result = {
name: 'BlackBerry'
, osname: 'BlackBerry OS'
, blackberry: t
, version: versionIdentifier || getFirstMatch(/blackberry[\d]+\/(\d+(\.\d+)?)/i)
}
}
else if (webos) {
result = {
name: 'WebOS'
, osname: 'WebOS'
, webos: t
, version: versionIdentifier || getFirstMatch(/w(?:eb)?osbrowser\/(\d+(\.\d+)?)/i)
};
/touchpad\//i.test(ua) && (result.touchpad = t)
}
else if (/bada/i.test(ua)) {
result = {
name: 'Bada'
, osname: 'Bada'
, bada: t
, version: getFirstMatch(/dolfin\/(\d+(\.\d+)?)/i)
};
}
else if (tizen) {
result = {
name: 'Tizen'
, osname: 'Tizen'
, tizen: t
, version: getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.\d+)?)/i) || versionIdentifier
};
}
else if (/qupzilla/i.test(ua)) {
result = {
name: 'QupZilla'
, qupzilla: t
, version: getFirstMatch(/(?:qupzilla)[\s\/](\d+(?:\.\d+)+)/i) || versionIdentifier
}
}
else if (/chromium/i.test(ua)) {
result = {
name: 'Chromium'
, chromium: t
, version: getFirstMatch(/(?:chromium)[\s\/](\d+(?:\.\d+)?)/i) || versionIdentifier
}
}
else if (/chrome|crios|crmo/i.test(ua)) {
result = {
name: 'Chrome'
, chrome: t
, version: getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.\d+)?)/i)
}
}
else if (android) {
result = {
name: 'Android'
, version: versionIdentifier
}
}
else if (/safari|applewebkit/i.test(ua)) {
result = {
name: 'Safari'
, safari: t
}
if (versionIdentifier) {
result.version = versionIdentifier
}
}
else if (iosdevice) {
result = {
name : iosdevice == 'iphone' ? 'iPhone' : iosdevice == 'ipad' ? 'iPad' : 'iPod'
}
// WTF: version is not part of user agent in web apps
if (versionIdentifier) {
result.version = versionIdentifier
}
}
else if(/googlebot/i.test(ua)) {
result = {
name: 'Googlebot'
, googlebot: t
, version: getFirstMatch(/googlebot\/(\d+(\.\d+))/i) || versionIdentifier
}
}
else {
result = {
name: getFirstMatch(/^(.*)\/(.*) /),
version: getSecondMatch(/^(.*)\/(.*) /)
};
}
// set webkit or gecko flag for browsers based on these engines
if (!result.msedge && /(apple)?webkit/i.test(ua)) {
if (/(apple)?webkit\/537\.36/i.test(ua)) {
result.name = result.name || "Blink"
result.blink = t
} else {
result.name = result.name || "Webkit"
result.webkit = t
}
if (!result.version && versionIdentifier) {
result.version = versionIdentifier
}
} else if (!result.opera && /gecko\//i.test(ua)) {
result.name = result.name || "Gecko"
result.gecko = t
result.version = result.version || getFirstMatch(/gecko\/(\d+(\.\d+)?)/i)
}
// set OS flags for platforms that have multiple browsers
if (!result.windowsphone && (android || result.silk)) {
result.android = t
result.osname = 'Android'
} else if (!result.windowsphone && iosdevice) {
result[iosdevice] = t
result.ios = t
result.osname = 'iOS'
} else if (mac) {
result.mac = t
result.osname = 'macOS'
} else if (xbox) {
result.xbox = t
result.osname = 'Xbox'
} else if (windows) {
result.windows = t
result.osname = 'Windows'
} else if (linux) {
result.linux = t
result.osname = 'Linux'
}
function getWindowsVersion (s) {
switch (s) {
case 'NT': return 'NT'
case 'XP': return 'XP'
case 'NT 5.0': return '2000'
case 'NT 5.1': return 'XP'
case 'NT 5.2': return '2003'
case 'NT 6.0': return 'Vista'
case 'NT 6.1': return '7'
case 'NT 6.2': return '8'
case 'NT 6.3': return '8.1'
case 'NT 10.0': return '10'
default: return undefined
}
}
// OS version extraction
var osVersion = '';
if (result.windows) {
osVersion = getWindowsVersion(getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i))
} else if (result.windowsphone) {
osVersion = getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i);
} else if (result.mac) {
osVersion = getFirstMatch(/Mac OS X (\d+([_\.\s]\d+)*)/i);
osVersion = osVersion.replace(/[_\s]/g, '.');
} else if (iosdevice) {
osVersion = getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i);
osVersion = osVersion.replace(/[_\s]/g, '.');
} else if (android) {
osVersion = getFirstMatch(/android[ \/-](\d+(\.\d+)*)/i);
} else if (result.webos) {
osVersion = getFirstMatch(/(?:web|hpw)os\/(\d+(\.\d+)*)/i);
} else if (result.blackberry) {
osVersion = getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i);
} else if (result.bada) {
osVersion = getFirstMatch(/bada\/(\d+(\.\d+)*)/i);
} else if (result.tizen) {
osVersion = getFirstMatch(/tizen[\/\s](\d+(\.\d+)*)/i);
}
if (osVersion) {
result.osversion = osVersion;
}
// device type extraction
var osMajorVersion = !result.windows && osVersion.split('.')[0];
if (
tablet
|| nexusTablet
|| iosdevice == 'ipad'
|| (android && (osMajorVersion == 3 || (osMajorVersion >= 4 && !mobile)))
|| result.silk
) {
result.tablet = t
} else if (
mobile
|| iosdevice == 'iphone'
|| iosdevice == 'ipod'
|| android
|| nexusMobile
|| result.blackberry
|| result.webos
|| result.bada
) {
result.mobile = t
}
// Graded Browser Support
// http://developer.yahoo.com/yui/articles/gbs
if (result.msedge ||
(result.msie && result.version >= 10) ||
(result.yandexbrowser && result.version >= 15) ||
(result.vivaldi && result.version >= 1.0) ||
(result.chrome && result.version >= 20) ||
(result.samsungBrowser && result.version >= 4) ||
(result.whale && compareVersions([result.version, '1.0']) === 1) ||
(result.mzbrowser && compareVersions([result.version, '6.0']) === 1) ||
(result.focus && compareVersions([result.version, '1.0']) === 1) ||
(result.firefox && result.version >= 20.0) ||
(result.safari && result.version >= 6) ||
(result.opera && result.version >= 10.0) ||
(result.ios && result.osversion && result.osversion.split(".")[0] >= 6) ||
(result.blackberry && result.version >= 10.1)
|| (result.chromium && result.version >= 20)
) {
result.a = t;
}
else if ((result.msie && result.version < 10) ||
(result.chrome && result.version < 20) ||
(result.firefox && result.version < 20.0) ||
(result.safari && result.version < 6) ||
(result.opera && result.version < 10.0) ||
(result.ios && result.osversion && result.osversion.split(".")[0] < 6)
|| (result.chromium && result.version < 20)
) {
result.c = t
} else result.x = t
return result
}
var bowser = detect(typeof navigator !== 'undefined' ? navigator.userAgent || '' : '')
bowser.test = function (browserList) {
for (var i = 0; i < browserList.length; ++i) {
var browserItem = browserList[i];
if (typeof browserItem=== 'string') {
if (browserItem in bowser) {
return true;
}
}
}
return false;
}
/**
* Get version precisions count
*
* @example
* getVersionPrecision("1.10.3") // 3
*
* @param {string} version
* @return {number}
*/
function getVersionPrecision(version) {
return version.split(".").length;
}
/**
* Array::map polyfill
*
* @param {Array} arr
* @param {Function} iterator
* @return {Array}
*/
function map(arr, iterator) {
var result = [], i;
if (Array.prototype.map) {
return Array.prototype.map.call(arr, iterator);
}
for (i = 0; i < arr.length; i++) {
result.push(iterator(arr[i]));
}
return result;
}
/**
* Calculate browser version weight
*
* @example
* compareVersions(['1.10.2.1', '1.8.2.1.90']) // 1
* compareVersions(['1.010.2.1', '1.09.2.1.90']); // 1
* compareVersions(['1.10.2.1', '1.10.2.1']); // 0
* compareVersions(['1.10.2.1', '1.0800.2']); // -1
*
* @param {Array<String>} versions versions to compare
* @return {Number} comparison result
*/
function compareVersions(versions) {
// 1) get common precision for both versions, for example for "10.0" and "9" it should be 2
var precision = Math.max(getVersionPrecision(versions[0]), getVersionPrecision(versions[1]));
var chunks = map(versions, function (version) {
var delta = precision - getVersionPrecision(version);
// 2) "9" -> "9.0" (for precision = 2)
version = version + new Array(delta + 1).join(".0");
// 3) "9.0" -> ["000000000"", "000000009"]
return map(version.split("."), function (chunk) {
return new Array(20 - chunk.length).join("0") + chunk;
}).reverse();
});
// iterate in reverse order by reversed chunks array
while (--precision >= 0) {
// 4) compare: "000000009" > "000000010" = false (but "9" > "10" = true)
if (chunks[0][precision] > chunks[1][precision]) {
return 1;
}
else if (chunks[0][precision] === chunks[1][precision]) {
if (precision === 0) {
// all version chunks are same
return 0;
}
}
else {
return -1;
}
}
}
/**
* Check if browser is unsupported
*
* @example
* bowser.isUnsupportedBrowser({
* msie: "10",
* firefox: "23",
* chrome: "29",
* safari: "5.1",
* opera: "16",
* phantom: "534"
* });
*
* @param {Object} minVersions map of minimal version to browser
* @param {Boolean} [strictMode = false] flag to return false if browser wasn't found in map
* @param {String} [ua] user agent string
* @return {Boolean}
*/
function isUnsupportedBrowser(minVersions, strictMode, ua) {
var _bowser = bowser;
// make strictMode param optional with ua param usage
if (typeof strictMode === 'string') {
ua = strictMode;
strictMode = void(0);
}
if (strictMode === void(0)) {
strictMode = false;
}
if (ua) {
_bowser = detect(ua);
}
var version = "" + _bowser.version;
for (var browser in minVersions) {
if (minVersions.hasOwnProperty(browser)) {
if (_bowser[browser]) {
if (typeof minVersions[browser] !== 'string') {
throw new Error('Browser version in the minVersion map should be a string: ' + browser + ': ' + String(minVersions));
}
// browser version and min supported version.
return compareVersions([version, minVersions[browser]]) < 0;
}
}
}
return strictMode; // not found
}
/**
* Check if browser is supported
*
* @param {Object} minVersions map of minimal version to browser
* @param {Boolean} [strictMode = false] flag to return false if browser wasn't found in map
* @param {String} [ua] user agent string
* @return {Boolean}
*/
function check(minVersions, strictMode, ua) {
return !isUnsupportedBrowser(minVersions, strictMode, ua);
}
bowser.isUnsupportedBrowser = isUnsupportedBrowser;
bowser.compareVersions = compareVersions;
bowser.check = check;
/*
* Set our detect method to the main bowser object so we can
* reuse it to test other user agents.
* This is needed to implement future tests.
*/
bowser._detect = detect;
/*
* Set our detect public method to the main bowser object
* This is needed to implement bowser in server side
*/
bowser.detect = detect;
return bowser
});
},{}],71:[function(require,module,exports){
},{}],72:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node 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 Buffer = require('buffer').Buffer;
var isBufferEncoding = Buffer.isEncoding
|| function(encoding) {
switch (encoding && encoding.toLowerCase()) {
case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;
default: return false;
}
}
function assertEncoding(encoding) {
if (encoding && !isBufferEncoding(encoding)) {
throw new Error('Unknown encoding: ' + encoding);
}
}
// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters. CESU-8 is handled as part of the UTF-8 encoding.
//
// @TODO Handling all encodings inside a single object makes it very difficult
// to reason about this code, so it should be split up in the future.
// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
// points as used by CESU-8.
var StringDecoder = exports.StringDecoder = function(encoding) {
this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
assertEncoding(encoding);
switch (this.encoding) {
case 'utf8':
// CESU-8 represents each of Surrogate Pair by 3-bytes
this.surrogateSize = 3;
break;
case 'ucs2':
case 'utf16le':
// UTF-16 represents each of Surrogate Pair by 2-bytes
this.surrogateSize = 2;
this.detectIncompleteChar = utf16DetectIncompleteChar;
break;
case 'base64':
// Base-64 stores 3 bytes in 4 chars, and pads the remainder.
this.surrogateSize = 3;
this.detectIncompleteChar = base64DetectIncompleteChar;
break;
default:
this.write = passThroughWrite;
return;
}
// Enough space to store all bytes of a single character. UTF-8 needs 4
// bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
this.charBuffer = new Buffer(6);
// Number of bytes received for the current incomplete multi-byte character.
this.charReceived = 0;
// Number of bytes expected for the current incomplete multi-byte character.
this.charLength = 0;
};
// write decodes the given buffer and returns it as JS string that is
// guaranteed to not contain any partial multi-byte characters. Any partial
// character found at the end of the buffer is buffered up, and will be
// returned when calling write again with the remaining bytes.
//
// Note: Converting a Buffer containing an orphan surrogate to a String
// currently works, but converting a String to a Buffer (via `new Buffer`, or
// Buffer#write) will replace incomplete surrogates with the unicode
// replacement character. See https://codereview.chromium.org/121173009/ .
StringDecoder.prototype.write = function(buffer) {
var charStr = '';
// if our last write ended with an incomplete multibyte character
while (this.charLength) {
// determine how many remaining bytes this buffer has to offer for this char
var available = (buffer.length >= this.charLength - this.charReceived) ?
this.charLength - this.charReceived :
buffer.length;
// add the new bytes to the char buffer
buffer.copy(this.charBuffer, this.charReceived, 0, available);
this.charReceived += available;
if (this.charReceived < this.charLength) {
// still not enough chars in this buffer? wait for more ...
return '';
}
// remove bytes belonging to the current character from the buffer
buffer = buffer.slice(available, buffer.length);
// get the character that was split
charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
// CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
var charCode = charStr.charCodeAt(charStr.length - 1);
if (charCode >= 0xD800 && charCode <= 0xDBFF) {
this.charLength += this.surrogateSize;
charStr = '';
continue;
}
this.charReceived = this.charLength = 0;
// if there are no more bytes in this buffer, just emit our char
if (buffer.length === 0) {
return charStr;
}
break;
}
// determine and set charLength / charReceived
this.detectIncompleteChar(buffer);
var end = buffer.length;
if (this.charLength) {
// buffer the incomplete character bytes we got
buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
end -= this.charReceived;
}
charStr += buffer.toString(this.encoding, 0, end);
var end = charStr.length - 1;
var charCode = charStr.charCodeAt(end);
// CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
if (charCode >= 0xD800 && charCode <= 0xDBFF) {
var size = this.surrogateSize;
this.charLength += size;
this.charReceived += size;
this.charBuffer.copy(this.charBuffer, size, 0, size);
buffer.copy(this.charBuffer, 0, 0, size);
return charStr.substring(0, end);
}
// or just emit the charStr
return charStr;
};
// detectIncompleteChar determines if there is an incomplete UTF-8 character at
// the end of the given buffer. If so, it sets this.charLength to the byte
// length that character, and sets this.charReceived to the number of bytes
// that are available for this character.
StringDecoder.prototype.detectIncompleteChar = function(buffer) {
// determine how many bytes we have to check at the end of this buffer
var i = (buffer.length >= 3) ? 3 : buffer.length;
// Figure out if one of the last i bytes of our buffer announces an
// incomplete char.
for (; i > 0; i--) {
var c = buffer[buffer.length - i];
// See http://en.wikipedia.org/wiki/UTF-8#Description
// 110XXXXX
if (i == 1 && c >> 5 == 0x06) {
this.charLength = 2;
break;
}
// 1110XXXX
if (i <= 2 && c >> 4 == 0x0E) {
this.charLength = 3;
break;
}
// 11110XXX
if (i <= 3 && c >> 3 == 0x1E) {
this.charLength = 4;
break;
}
}
this.charReceived = i;
};
StringDecoder.prototype.end = function(buffer) {
var res = '';
if (buffer && buffer.length)
res = this.write(buffer);
if (this.charReceived) {
var cr = this.charReceived;
var buf = this.charBuffer;
var enc = this.encoding;
res += buf.slice(0, cr).toString(enc);
}
return res;
};
function passThroughWrite(buffer) {
return buffer.toString(this.encoding);
}
function utf16DetectIncompleteChar(buffer) {
this.charReceived = buffer.length % 2;
this.charLength = this.charReceived ? 2 : 0;
}
function base64DetectIncompleteChar(buffer) {
this.charReceived = buffer.length % 3;
this.charLength = this.charReceived ? 3 : 0;
}
},{"buffer":73}],73:[function(require,module,exports){
(function (global,Buffer){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <http://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
'use strict'
var base64 = require('base64-js')
var ieee754 = require('ieee754')
var isArray = require('isarray')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* Due to various browser bugs, sometimes the Object implementation will be used even
* when the browser supports typed arrays.
*
* Note:
*
* - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
*
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
* incorrect length in some situations.
* We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
* get the Object implementation, which is slower but behaves correctly.
*/
Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
? global.TYPED_ARRAY_SUPPORT
: typedArraySupport()
/*
* Export kMaxLength after typed array support is determined.
*/
exports.kMaxLength = kMaxLength()
function typedArraySupport () {
try {
var arr = new Uint8Array(1)
arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
return arr.foo() === 42 && // typed array instances can be augmented
typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
} catch (e) {
return false
}
}
function kMaxLength () {
return Buffer.TYPED_ARRAY_SUPPORT
? 0x7fffffff
: 0x3fffffff
}
function createBuffer (that, length) {
if (kMaxLength() < length) {
throw new RangeError('Invalid typed array length')
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = new Uint8Array(length)
that.__proto__ = Buffer.prototype
} else {
// Fallback: Return an object instance of the Buffer class
if (that === null) {
that = new Buffer(length)
}
that.length = length
}
return that
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
return new Buffer(arg, encodingOrOffset, length)
}
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new Error(
'If encoding is specified then the first argument must be a string'
)
}
return allocUnsafe(this, arg)
}
return from(this, arg, encodingOrOffset, length)
}
Buffer.poolSize = 8192 // not used by this implementation
// TODO: Legacy, not needed anymore. Remove in next major version.
Buffer._augment = function (arr) {
arr.__proto__ = Buffer.prototype
return arr
}
function from (that, value, encodingOrOffset, length) {
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number')
}
if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
return fromArrayBuffer(that, value, encodingOrOffset, length)
}
if (typeof value === 'string') {
return fromString(that, value, encodingOrOffset)
}
return fromObject(that, value)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(null, value, encodingOrOffset, length)
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
if (typeof Symbol !== 'undefined' && Symbol.species &&
Buffer[Symbol.species] === Buffer) {
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true
})
}
}
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be a number')
} else if (size < 0) {
throw new RangeError('"size" argument must not be negative')
}
}
function alloc (that, size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(that, size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(that, size).fill(fill, encoding)
: createBuffer(that, size).fill(fill)
}
return createBuffer(that, size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(null, size, fill, encoding)
}
function allocUnsafe (that, size) {
assertSize(size)
that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) {
for (var i = 0; i < size; ++i) {
that[i] = 0
}
}
return that
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(null, size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(null, size)
}
function fromString (that, string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('"encoding" must be a valid string encoding')
}
var length = byteLength(string, encoding) | 0
that = createBuffer(that, length)
var actual = that.write(string, encoding)
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
that = that.slice(0, actual)
}
return that
}
function fromArrayLike (that, array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0
that = createBuffer(that, length)
for (var i = 0; i < length; i += 1) {
that[i] = array[i] & 255
}
return that
}
function fromArrayBuffer (that, array, byteOffset, length) {
array.byteLength // this throws if `array` is not a valid ArrayBuffer
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('\'offset\' is out of bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('\'length\' is out of bounds')
}
if (byteOffset === undefined && length === undefined) {
array = new Uint8Array(array)
} else if (length === undefined) {
array = new Uint8Array(array, byteOffset)
} else {
array = new Uint8Array(array, byteOffset, length)
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = array
that.__proto__ = Buffer.prototype
} else {
// Fallback: Return an object instance of the Buffer class
that = fromArrayLike(that, array)
}
return that
}
function fromObject (that, obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
that = createBuffer(that, len)
if (that.length === 0) {
return that
}
obj.copy(that, 0, 0, len)
return that
}
if (obj) {
if ((typeof ArrayBuffer !== 'undefined' &&
obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
if (typeof obj.length !== 'number' || isnan(obj.length)) {
return createBuffer(that, 0)
}
return fromArrayLike(that, obj)
}
if (obj.type === 'Buffer' && isArray(obj.data)) {
return fromArrayLike(that, obj.data)
}
}
throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
}
function checked (length) {
// Note: cannot use `length < kMaxLength()` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= kMaxLength()) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + kMaxLength().toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (length) {
if (+length != length) { // eslint-disable-line eqeqeq
length = 0
}
return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
return !!(b != null && b._isBuffer)
}
Buffer.compare = function compare (a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError('Arguments must be Buffers')
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i]
y = b[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer.alloc(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; ++i) {
length += list[i].length
}
}
var buffer = Buffer.allocUnsafe(length)
var pos = 0
for (i = 0; i < list.length; ++i) {
var buf = list[i]
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
buf.copy(buffer, pos)
pos += buf.length
}
return buffer
}
function byteLength (string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length
}
if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
(ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
return string.byteLength
}
if (typeof string !== 'string') {
string = '' + string
}
var len = string.length
if (len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len
case 'utf8':
case 'utf-8':
case undefined:
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) return utf8ToBytes(string).length // assume utf8
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
function slowToString (encoding, start, end) {
var loweredCase = false
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return ''
}
if (end === undefined || end > this.length) {
end = this.length
}
if (end <= 0) {
return ''
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0
start >>>= 0
if (end <= start) {
return ''
}
if (!encoding) encoding = 'utf8'
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'latin1':
case 'binary':
return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
// Buffer instances.
Buffer.prototype._isBuffer = true
function swap (b, n, m) {
var i = b[n]
b[n] = b[m]
b[m] = i
}
Buffer.prototype.swap16 = function swap16 () {
var len = this.length
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits')
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1)
}
return this
}
Buffer.prototype.swap32 = function swap32 () {
var len = this.length
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits')
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3)
swap(this, i + 1, i + 2)
}
return this
}
Buffer.prototype.swap64 = function swap64 () {
var len = this.length
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits')
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7)
swap(this, i + 1, i + 6)
swap(this, i + 2, i + 5)
swap(this, i + 3, i + 4)
}
return this
}
Buffer.prototype.toString = function toString () {
var length = this.length | 0
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
if (this.length > max) str += ' ... '
}
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (!Buffer.isBuffer(target)) {
throw new TypeError('Argument must be a Buffer')
}
if (start === undefined) {
start = 0
}
if (end === undefined) {
end = target ? target.length : 0
}
if (thisStart === undefined) {
thisStart = 0
}
if (thisEnd === undefined) {
thisEnd = this.length
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index')
}
if (thisStart >= thisEnd && start >= end) {
return 0
}
if (thisStart >= thisEnd) {
return -1
}
if (start >= end) {
return 1
}
start >>>= 0
end >>>= 0
thisStart >>>= 0
thisEnd >>>= 0
if (this === target) return 0
var x = thisEnd - thisStart
var y = end - start
var len = Math.min(x, y)
var thisCopy = this.slice(thisStart, thisEnd)
var targetCopy = target.slice(start, end)
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i]
y = targetCopy[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset
byteOffset = 0
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000
}
byteOffset = +byteOffset // Coerce to Number.
if (isNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : (buffer.length - 1)
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset
if (byteOffset >= buffer.length) {
if (dir) return -1
else byteOffset = buffer.length - 1
} else if (byteOffset < 0) {
if (dir) byteOffset = 0
else return -1
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding)
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
} else if (typeof val === 'number') {
val = val & 0xFF // Search for a byte value [0-255]
if (Buffer.TYPED_ARRAY_SUPPORT &&
typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
}
}
return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
}
throw new TypeError('val must be string, number or Buffer')
}
function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
var indexSize = 1
var arrLength = arr.length
var valLength = val.length
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase()
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1
}
indexSize = 2
arrLength /= 2
valLength /= 2
byteOffset /= 2
}
}
function read (buf, i) {
if (indexSize === 1) {
return buf[i]
} else {
return buf.readUInt16BE(i * indexSize)
}
}
var i
if (dir) {
var foundIndex = -1
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
if (foundIndex !== -1) i -= i - foundIndex
foundIndex = -1
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
for (i = byteOffset; i >= 0; i--) {
var found = true
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false
break
}
}
if (found) return i
}
}
return -1
}
Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}
Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
// must be an even number of digits
var strLen = string.length
if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (isNaN(parsed)) return i
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function latin1Write (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset | 0
if (isFinite(length)) {
length = length | 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
// legacy write(string, encoding, offset, length) - remove in v0.13
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
)
}
var remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
var loweredCase = false
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'latin1':
case 'binary':
return latin1Write(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
var res = []
var i = start
while (i < end) {
var firstByte = buf[i]
var codePoint = null
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
: (firstByte > 0xBF) ? 2
: 1
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
fourthByte = buf[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000
function decodeCodePointsArray (codePoints) {
var len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = ''
var i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function latin1Slice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; ++i) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf
if (Buffer.TYPED_ARRAY_SUPPORT) {
newBuf = this.subarray(start, end)
newBuf.__proto__ = Buffer.prototype
} else {
var sliceLen = end - start
newBuf = new Buffer(sliceLen, undefined)
for (var i = 0; i < sliceLen; ++i) {
newBuf[i] = this[i + start]
}
}
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
this[offset] = (value & 0xff)
return offset + 1
}
function objectWriteUInt16 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
(littleEndian ? i : 1 - i) * 8
}
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
function objectWriteUInt32 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffffffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
}
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = 0
var mul = 1
var sub = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = byteLength - 1
var mul = 1
var sub = 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
if (value < 0) value = 0xff + value + 1
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range')
if (offset < 0) throw new RangeError('Index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
if (!targetStart) targetStart = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start
}
var len = end - start
var i
if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start]
}
} else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
// ascending copy from start
for (i = 0; i < len; ++i) {
target[i + targetStart] = this[i + start]
}
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, start + len),
targetStart
)
}
return len
}
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start
start = 0
end = this.length
} else if (typeof end === 'string') {
encoding = end
end = this.length
}
if (val.length === 1) {
var code = val.charCodeAt(0)
if (code < 256) {
val = code
}
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
} else if (typeof val === 'number') {
val = val & 255
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return this
}
start = start >>> 0
end = end === undefined ? this.length : end >>> 0
if (!val) val = 0
var i
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val
}
} else {
var bytes = Buffer.isBuffer(val)
? val
: utf8ToBytes(new Buffer(val, encoding).toString())
var len = bytes.length
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len]
}
}
return this
}
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
function base64clean (str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = stringtrim(str).replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function stringtrim (str) {
if (str.trim) return str.trim()
return str.replace(/^\s+|\s+$/g, '')
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
function isnan (val) {
return val !== val // eslint-disable-line no-self-compare
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
},{"base64-js":69,"buffer":73,"ieee754":195,"isarray":198}],74:[function(require,module,exports){
module.exports = {
"100": "Continue",
"101": "Switching Protocols",
"102": "Processing",
"200": "OK",
"201": "Created",
"202": "Accepted",
"203": "Non-Authoritative Information",
"204": "No Content",
"205": "Reset Content",
"206": "Partial Content",
"207": "Multi-Status",
"208": "Already Reported",
"226": "IM Used",
"300": "Multiple Choices",
"301": "Moved Permanently",
"302": "Found",
"303": "See Other",
"304": "Not Modified",
"305": "Use Proxy",
"307": "Temporary Redirect",
"308": "Permanent Redirect",
"400": "Bad Request",
"401": "Unauthorized",
"402": "Payment Required",
"403": "Forbidden",
"404": "Not Found",
"405": "Method Not Allowed",
"406": "Not Acceptable",
"407": "Proxy Authentication Required",
"408": "Request Timeout",
"409": "Conflict",
"410": "Gone",
"411": "Length Required",
"412": "Precondition Failed",
"413": "Payload Too Large",
"414": "URI Too Long",
"415": "Unsupported Media Type",
"416": "Range Not Satisfiable",
"417": "Expectation Failed",
"418": "I'm a teapot",
"421": "Misdirected Request",
"422": "Unprocessable Entity",
"423": "Locked",
"424": "Failed Dependency",
"425": "Unordered Collection",
"426": "Upgrade Required",
"428": "Precondition Required",
"429": "Too Many Requests",
"431": "Request Header Fields Too Large",
"451": "Unavailable For Legal Reasons",
"500": "Internal Server Error",
"501": "Not Implemented",
"502": "Bad Gateway",
"503": "Service Unavailable",
"504": "Gateway Timeout",
"505": "HTTP Version Not Supported",
"506": "Variant Also Negotiates",
"507": "Insufficient Storage",
"508": "Loop Detected",
"509": "Bandwidth Limit Exceeded",
"510": "Not Extended",
"511": "Network Authentication Required"
}
},{}],75:[function(require,module,exports){
module.exports={
"O_RDONLY": 0,
"O_WRONLY": 1,
"O_RDWR": 2,
"S_IFMT": 61440,
"S_IFREG": 32768,
"S_IFDIR": 16384,
"S_IFCHR": 8192,
"S_IFBLK": 24576,
"S_IFIFO": 4096,
"S_IFLNK": 40960,
"S_IFSOCK": 49152,
"O_CREAT": 512,
"O_EXCL": 2048,
"O_NOCTTY": 131072,
"O_TRUNC": 1024,
"O_APPEND": 8,
"O_DIRECTORY": 1048576,
"O_NOFOLLOW": 256,
"O_SYNC": 128,
"O_SYMLINK": 2097152,
"O_NONBLOCK": 4,
"S_IRWXU": 448,
"S_IRUSR": 256,
"S_IWUSR": 128,
"S_IXUSR": 64,
"S_IRWXG": 56,
"S_IRGRP": 32,
"S_IWGRP": 16,
"S_IXGRP": 8,
"S_IRWXO": 7,
"S_IROTH": 4,
"S_IWOTH": 2,
"S_IXOTH": 1,
"E2BIG": 7,
"EACCES": 13,
"EADDRINUSE": 48,
"EADDRNOTAVAIL": 49,
"EAFNOSUPPORT": 47,
"EAGAIN": 35,
"EALREADY": 37,
"EBADF": 9,
"EBADMSG": 94,
"EBUSY": 16,
"ECANCELED": 89,
"ECHILD": 10,
"ECONNABORTED": 53,
"ECONNREFUSED": 61,
"ECONNRESET": 54,
"EDEADLK": 11,
"EDESTADDRREQ": 39,
"EDOM": 33,
"EDQUOT": 69,
"EEXIST": 17,
"EFAULT": 14,
"EFBIG": 27,
"EHOSTUNREACH": 65,
"EIDRM": 90,
"EILSEQ": 92,
"EINPROGRESS": 36,
"EINTR": 4,
"EINVAL": 22,
"EIO": 5,
"EISCONN": 56,
"EISDIR": 21,
"ELOOP": 62,
"EMFILE": 24,
"EMLINK": 31,
"EMSGSIZE": 40,
"EMULTIHOP": 95,
"ENAMETOOLONG": 63,
"ENETDOWN": 50,
"ENETRESET": 52,
"ENETUNREACH": 51,
"ENFILE": 23,
"ENOBUFS": 55,
"ENODATA": 96,
"ENODEV": 19,
"ENOENT": 2,
"ENOEXEC": 8,
"ENOLCK": 77,
"ENOLINK": 97,
"ENOMEM": 12,
"ENOMSG": 91,
"ENOPROTOOPT": 42,
"ENOSPC": 28,
"ENOSR": 98,
"ENOSTR": 99,
"ENOSYS": 78,
"ENOTCONN": 57,
"ENOTDIR": 20,
"ENOTEMPTY": 66,
"ENOTSOCK": 38,
"ENOTSUP": 45,
"ENOTTY": 25,
"ENXIO": 6,
"EOPNOTSUPP": 102,
"EOVERFLOW": 84,
"EPERM": 1,
"EPIPE": 32,
"EPROTO": 100,
"EPROTONOSUPPORT": 43,
"EPROTOTYPE": 41,
"ERANGE": 34,
"EROFS": 30,
"ESPIPE": 29,
"ESRCH": 3,
"ESTALE": 70,
"ETIME": 101,
"ETIMEDOUT": 60,
"ETXTBSY": 26,
"EWOULDBLOCK": 35,
"EXDEV": 18,
"SIGHUP": 1,
"SIGINT": 2,
"SIGQUIT": 3,
"SIGILL": 4,
"SIGTRAP": 5,
"SIGABRT": 6,
"SIGIOT": 6,
"SIGBUS": 10,
"SIGFPE": 8,
"SIGKILL": 9,
"SIGUSR1": 30,
"SIGSEGV": 11,
"SIGUSR2": 31,
"SIGPIPE": 13,
"SIGALRM": 14,
"SIGTERM": 15,
"SIGCHLD": 20,
"SIGCONT": 19,
"SIGSTOP": 17,
"SIGTSTP": 18,
"SIGTTIN": 21,
"SIGTTOU": 22,
"SIGURG": 16,
"SIGXCPU": 24,
"SIGXFSZ": 25,
"SIGVTALRM": 26,
"SIGPROF": 27,
"SIGWINCH": 28,
"SIGIO": 23,
"SIGSYS": 12,
"SSL_OP_ALL": 2147486719,
"SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION": 262144,
"SSL_OP_CIPHER_SERVER_PREFERENCE": 4194304,
"SSL_OP_CISCO_ANYCONNECT": 32768,
"SSL_OP_COOKIE_EXCHANGE": 8192,
"SSL_OP_CRYPTOPRO_TLSEXT_BUG": 2147483648,
"SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS": 2048,
"SSL_OP_EPHEMERAL_RSA": 0,
"SSL_OP_LEGACY_SERVER_CONNECT": 4,
"SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER": 32,
"SSL_OP_MICROSOFT_SESS_ID_BUG": 1,
"SSL_OP_MSIE_SSLV2_RSA_PADDING": 0,
"SSL_OP_NETSCAPE_CA_DN_BUG": 536870912,
"SSL_OP_NETSCAPE_CHALLENGE_BUG": 2,
"SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG": 1073741824,
"SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG": 8,
"SSL_OP_NO_COMPRESSION": 131072,
"SSL_OP_NO_QUERY_MTU": 4096,
"SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION": 65536,
"SSL_OP_NO_SSLv2": 16777216,
"SSL_OP_NO_SSLv3": 33554432,
"SSL_OP_NO_TICKET": 16384,
"SSL_OP_NO_TLSv1": 67108864,
"SSL_OP_NO_TLSv1_1": 268435456,
"SSL_OP_NO_TLSv1_2": 134217728,
"SSL_OP_PKCS1_CHECK_1": 0,
"SSL_OP_PKCS1_CHECK_2": 0,
"SSL_OP_SINGLE_DH_USE": 1048576,
"SSL_OP_SINGLE_ECDH_USE": 524288,
"SSL_OP_SSLEAY_080_CLIENT_DH_BUG": 128,
"SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG": 0,
"SSL_OP_TLS_BLOCK_PADDING_BUG": 512,
"SSL_OP_TLS_D5_BUG": 256,
"SSL_OP_TLS_ROLLBACK_BUG": 8388608,
"ENGINE_METHOD_DSA": 2,
"ENGINE_METHOD_DH": 4,
"ENGINE_METHOD_RAND": 8,
"ENGINE_METHOD_ECDH": 16,
"ENGINE_METHOD_ECDSA": 32,
"ENGINE_METHOD_CIPHERS": 64,
"ENGINE_METHOD_DIGESTS": 128,
"ENGINE_METHOD_STORE": 256,
"ENGINE_METHOD_PKEY_METHS": 512,
"ENGINE_METHOD_PKEY_ASN1_METHS": 1024,
"ENGINE_METHOD_ALL": 65535,
"ENGINE_METHOD_NONE": 0,
"DH_CHECK_P_NOT_SAFE_PRIME": 2,
"DH_CHECK_P_NOT_PRIME": 1,
"DH_UNABLE_TO_CHECK_GENERATOR": 4,
"DH_NOT_SUITABLE_GENERATOR": 8,
"NPN_ENABLED": 1,
"RSA_PKCS1_PADDING": 1,
"RSA_SSLV23_PADDING": 2,
"RSA_NO_PADDING": 3,
"RSA_PKCS1_OAEP_PADDING": 4,
"RSA_X931_PADDING": 5,
"RSA_PKCS1_PSS_PADDING": 6,
"POINT_CONVERSION_COMPRESSED": 2,
"POINT_CONVERSION_UNCOMPRESSED": 4,
"POINT_CONVERSION_HYBRID": 6,
"F_OK": 0,
"R_OK": 4,
"W_OK": 2,
"X_OK": 1,
"UV_UDP_REUSEADDR": 4
}
},{}],76:[function(require,module,exports){
/*!
* copy-to - index.js
* Copyright(c) 2014 dead_horse <dead_horse@qq.com>
* MIT Licensed
*/
'use strict';
/**
* slice() reference.
*/
var slice = Array.prototype.slice;
/**
* Expose copy
*
* ```
* copy({foo: 'nar', hello: 'copy'}).to({hello: 'world'});
* copy({foo: 'nar', hello: 'copy'}).toCover({hello: 'world'});
* ```
*
* @param {Object} src
* @return {Copy}
*/
module.exports = Copy;
/**
* Copy
* @param {Object} src
* @param {Boolean} withAccess
*/
function Copy(src, withAccess) {
if (!(this instanceof Copy)) return new Copy(src, withAccess);
this.src = src;
this._withAccess = withAccess;
}
/**
* copy properties include getter and setter
* @param {[type]} val [description]
* @return {[type]} [description]
*/
Copy.prototype.withAccess = function (w) {
this._withAccess = w !== false;
return this;
};
/**
* pick keys in src
*
* @api: public
*/
Copy.prototype.pick = function(keys) {
if (!Array.isArray(keys)) {
keys = slice.call(arguments);
}
if (keys.length) {
this.keys = keys;
}
return this;
};
/**
* copy src to target,
* do not cover any property target has
* @param {Object} to
*
* @api: public
*/
Copy.prototype.to = function(to) {
to = to || {};
if (!this.src) return to;
var keys = this.keys || Object.keys(this.src);
if (!this._withAccess) {
for (var i = 0; i < keys.length; i++) {
key = keys[i];
if (to[key] !== undefined) continue;
to[key] = this.src[key];
}
return to;
}
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!notDefined(to, key)) continue;
var getter = this.src.__lookupGetter__(key);
var setter = this.src.__lookupSetter__(key);
if (getter) to.__defineGetter__(key, getter);
if (setter) to.__defineSetter__(key, setter);
if (!getter && !setter) {
to[key] = this.src[key];
}
}
return to;
};
/**
* copy src to target,
* override any property target has
* @param {Object} to
*
* @api: public
*/
Copy.prototype.toCover = function(to) {
var keys = this.keys || Object.keys(this.src);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
delete to[key];
var getter = this.src.__lookupGetter__(key);
var setter = this.src.__lookupSetter__(key);
if (getter) to.__defineGetter__(key, getter);
if (setter) to.__defineSetter__(key, setter);
if (!getter && !setter) {
to[key] = this.src[key];
}
}
};
Copy.prototype.override = Copy.prototype.toCover;
/**
* append another object to src
* @param {Obj} obj
* @return {Copy}
*/
Copy.prototype.and = function (obj) {
var src = {};
this.to(src);
this.src = obj;
this.to(src);
this.src = src;
return this;
};
/**
* check obj[key] if not defiend
* @param {Object} obj
* @param {String} key
* @return {Boolean}
*/
function notDefined(obj, key) {
return obj[key] === undefined
&& obj.__lookupGetter__(key) === undefined
&& obj.__lookupSetter__(key) === undefined;
}
},{}],77:[function(require,module,exports){
require('../../modules/es6.string.iterator');
require('../../modules/es6.array.from');
module.exports = require('../../modules/_core').Array.from;
},{"../../modules/_core":99,"../../modules/es6.array.from":168,"../../modules/es6.string.iterator":180}],78:[function(require,module,exports){
var core = require('../../modules/_core');
var $JSON = core.JSON || (core.JSON = { stringify: JSON.stringify });
module.exports = function stringify(it) { // eslint-disable-line no-unused-vars
return $JSON.stringify.apply($JSON, arguments);
};
},{"../../modules/_core":99}],79:[function(require,module,exports){
require('../../modules/es6.object.assign');
module.exports = require('../../modules/_core').Object.assign;
},{"../../modules/_core":99,"../../modules/es6.object.assign":171}],80:[function(require,module,exports){
require('../../modules/es6.object.create');
var $Object = require('../../modules/_core').Object;
module.exports = function create(P, D) {
return $Object.create(P, D);
};
},{"../../modules/_core":99,"../../modules/es6.object.create":172}],81:[function(require,module,exports){
require('../../modules/es6.object.define-property');
var $Object = require('../../modules/_core').Object;
module.exports = function defineProperty(it, key, desc) {
return $Object.defineProperty(it, key, desc);
};
},{"../../modules/_core":99,"../../modules/es6.object.define-property":173}],82:[function(require,module,exports){
require('../../modules/es7.object.entries');
module.exports = require('../../modules/_core').Object.entries;
},{"../../modules/_core":99,"../../modules/es7.object.entries":182}],83:[function(require,module,exports){
require('../../modules/es6.object.get-own-property-names');
var $Object = require('../../modules/_core').Object;
module.exports = function getOwnPropertyNames(it) {
return $Object.getOwnPropertyNames(it);
};
},{"../../modules/_core":99,"../../modules/es6.object.get-own-property-names":174}],84:[function(require,module,exports){
require('../../modules/es6.object.get-prototype-of');
module.exports = require('../../modules/_core').Object.getPrototypeOf;
},{"../../modules/_core":99,"../../modules/es6.object.get-prototype-of":175}],85:[function(require,module,exports){
require('../../modules/es6.object.keys');
module.exports = require('../../modules/_core').Object.keys;
},{"../../modules/_core":99,"../../modules/es6.object.keys":176}],86:[function(require,module,exports){
require('../modules/es6.object.to-string');
require('../modules/es6.string.iterator');
require('../modules/web.dom.iterable');
require('../modules/es6.promise');
require('../modules/es7.promise.finally');
require('../modules/es7.promise.try');
module.exports = require('../modules/_core').Promise;
},{"../modules/_core":99,"../modules/es6.object.to-string":177,"../modules/es6.promise":178,"../modules/es6.string.iterator":180,"../modules/es7.promise.finally":183,"../modules/es7.promise.try":184,"../modules/web.dom.iterable":187}],87:[function(require,module,exports){
require('../modules/web.immediate');
module.exports = require('../modules/_core').setImmediate;
},{"../modules/_core":99,"../modules/web.immediate":188}],88:[function(require,module,exports){
require('../../modules/es6.string.from-code-point');
module.exports = require('../../modules/_core').String.fromCodePoint;
},{"../../modules/_core":99,"../../modules/es6.string.from-code-point":179}],89:[function(require,module,exports){
require('../../modules/es6.function.has-instance');
module.exports = require('../../modules/_wks-ext').f('hasInstance');
},{"../../modules/_wks-ext":165,"../../modules/es6.function.has-instance":170}],90:[function(require,module,exports){
require('../../modules/es6.symbol');
require('../../modules/es6.object.to-string');
require('../../modules/es7.symbol.async-iterator');
require('../../modules/es7.symbol.observable');
module.exports = require('../../modules/_core').Symbol;
},{"../../modules/_core":99,"../../modules/es6.object.to-string":177,"../../modules/es6.symbol":181,"../../modules/es7.symbol.async-iterator":185,"../../modules/es7.symbol.observable":186}],91:[function(require,module,exports){
require('../../modules/es6.string.iterator');
require('../../modules/web.dom.iterable');
module.exports = require('../../modules/_wks-ext').f('iterator');
},{"../../modules/_wks-ext":165,"../../modules/es6.string.iterator":180,"../../modules/web.dom.iterable":187}],92:[function(require,module,exports){
module.exports = function (it) {
if (typeof it != 'function') throw TypeError(it + ' is not a function!');
return it;
};
},{}],93:[function(require,module,exports){
module.exports = function () { /* empty */ };
},{}],94:[function(require,module,exports){
module.exports = function (it, Constructor, name, forbiddenField) {
if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) {
throw TypeError(name + ': incorrect invocation!');
} return it;
};
},{}],95:[function(require,module,exports){
var isObject = require('./_is-object');
module.exports = function (it) {
if (!isObject(it)) throw TypeError(it + ' is not an object!');
return it;
};
},{"./_is-object":119}],96:[function(require,module,exports){
// false -> Array#indexOf
// true -> Array#includes
var toIObject = require('./_to-iobject');
var toLength = require('./_to-length');
var toAbsoluteIndex = require('./_to-absolute-index');
module.exports = function (IS_INCLUDES) {
return function ($this, el, fromIndex) {
var O = toIObject($this);
var length = toLength(O.length);
var index = toAbsoluteIndex(fromIndex, length);
var value;
// Array#includes uses SameValueZero equality algorithm
// eslint-disable-next-line no-self-compare
if (IS_INCLUDES && el != el) while (length > index) {
value = O[index++];
// eslint-disable-next-line no-self-compare
if (value != value) return true;
// Array#indexOf ignores holes, Array#includes - not
} else for (;length > index; index++) if (IS_INCLUDES || index in O) {
if (O[index] === el) return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
},{"./_to-absolute-index":156,"./_to-iobject":158,"./_to-length":159}],97:[function(require,module,exports){
// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = require('./_cof');
var TAG = require('./_wks')('toStringTag');
// ES3 wrong here
var ARG = cof(function () { return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function (it, key) {
try {
return it[key];
} catch (e) { /* empty */ }
};
module.exports = function (it) {
var O, T, B;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T
// builtinTag case
: ARG ? cof(O)
// ES3 arguments fallback
: (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};
},{"./_cof":98,"./_wks":166}],98:[function(require,module,exports){
var toString = {}.toString;
module.exports = function (it) {
return toString.call(it).slice(8, -1);
};
},{}],99:[function(require,module,exports){
var core = module.exports = { version: '2.6.11' };
if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef
},{}],100:[function(require,module,exports){
'use strict';
var $defineProperty = require('./_object-dp');
var createDesc = require('./_property-desc');
module.exports = function (object, index, value) {
if (index in object) $defineProperty.f(object, index, createDesc(0, value));
else object[index] = value;
};
},{"./_object-dp":132,"./_property-desc":146}],101:[function(require,module,exports){
// optional / simple context binding
var aFunction = require('./_a-function');
module.exports = function (fn, that, length) {
aFunction(fn);
if (that === undefined) return fn;
switch (length) {
case 1: return function (a) {
return fn.call(that, a);
};
case 2: return function (a, b) {
return fn.call(that, a, b);
};
case 3: return function (a, b, c) {
return fn.call(that, a, b, c);
};
}
return function (/* ...args */) {
return fn.apply(that, arguments);
};
};
},{"./_a-function":92}],102:[function(require,module,exports){
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function (it) {
if (it == undefined) throw TypeError("Can't call method on " + it);
return it;
};
},{}],103:[function(require,module,exports){
// Thank's IE8 for his funny defineProperty
module.exports = !require('./_fails')(function () {
return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;
});
},{"./_fails":108}],104:[function(require,module,exports){
var isObject = require('./_is-object');
var document = require('./_global').document;
// typeof document.createElement is 'object' in old IE
var is = isObject(document) && isObject(document.createElement);
module.exports = function (it) {
return is ? document.createElement(it) : {};
};
},{"./_global":110,"./_is-object":119}],105:[function(require,module,exports){
// IE 8- don't enum bug keys
module.exports = (
'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');
},{}],106:[function(require,module,exports){
// all enumerable object keys, includes symbols
var getKeys = require('./_object-keys');
var gOPS = require('./_object-gops');
var pIE = require('./_object-pie');
module.exports = function (it) {
var result = getKeys(it);
var getSymbols = gOPS.f;
if (getSymbols) {
var symbols = getSymbols(it);
var isEnum = pIE.f;
var i = 0;
var key;
while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key);
} return result;
};
},{"./_object-gops":137,"./_object-keys":140,"./_object-pie":141}],107:[function(require,module,exports){
var global = require('./_global');
var core = require('./_core');
var ctx = require('./_ctx');
var hide = require('./_hide');
var has = require('./_has');
var PROTOTYPE = 'prototype';
var $export = function (type, name, source) {
var IS_FORCED = type & $export.F;
var IS_GLOBAL = type & $export.G;
var IS_STATIC = type & $export.S;
var IS_PROTO = type & $export.P;
var IS_BIND = type & $export.B;
var IS_WRAP = type & $export.W;
var exports = IS_GLOBAL ? core : core[name] || (core[name] = {});
var expProto = exports[PROTOTYPE];
var target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE];
var key, own, out;
if (IS_GLOBAL) source = name;
for (key in source) {
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
if (own && has(exports, key)) continue;
// export native or passed
out = own ? target[key] : source[key];
// prevent global pollution for namespaces
exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
// bind timers to global for call from export context
: IS_BIND && own ? ctx(out, global)
// wrap global constructors for prevent change them in library
: IS_WRAP && target[key] == out ? (function (C) {
var F = function (a, b, c) {
if (this instanceof C) {
switch (arguments.length) {
case 0: return new C();
case 1: return new C(a);
case 2: return new C(a, b);
} return new C(a, b, c);
} return C.apply(this, arguments);
};
F[PROTOTYPE] = C[PROTOTYPE];
return F;
// make static versions for prototype methods
})(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
if (IS_PROTO) {
(exports.virtual || (exports.virtual = {}))[key] = out;
// export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
if (type & $export.R && expProto && !expProto[key]) hide(expProto, key, out);
}
}
};
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
$export.U = 64; // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;
},{"./_core":99,"./_ctx":101,"./_global":110,"./_has":111,"./_hide":112}],108:[function(require,module,exports){
module.exports = function (exec) {
try {
return !!exec();
} catch (e) {
return true;
}
};
},{}],109:[function(require,module,exports){
var ctx = require('./_ctx');
var call = require('./_iter-call');
var isArrayIter = require('./_is-array-iter');
var anObject = require('./_an-object');
var toLength = require('./_to-length');
var getIterFn = require('./core.get-iterator-method');
var BREAK = {};
var RETURN = {};
var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) {
var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable);
var f = ctx(fn, that, entries ? 2 : 1);
var index = 0;
var length, step, iterator, result;
if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!');
// fast case for arrays with default iterator
if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) {
result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);
if (result === BREAK || result === RETURN) return result;
} else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) {
result = call(iterator, f, step.value, entries);
if (result === BREAK || result === RETURN) return result;
}
};
exports.BREAK = BREAK;
exports.RETURN = RETURN;
},{"./_an-object":95,"./_ctx":101,"./_is-array-iter":117,"./_iter-call":120,"./_to-length":159,"./core.get-iterator-method":167}],110:[function(require,module,exports){
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self
// eslint-disable-next-line no-new-func
: Function('return this')();
if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef
},{}],111:[function(require,module,exports){
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function (it, key) {
return hasOwnProperty.call(it, key);
};
},{}],112:[function(require,module,exports){
var dP = require('./_object-dp');
var createDesc = require('./_property-desc');
module.exports = require('./_descriptors') ? function (object, key, value) {
return dP.f(object, key, createDesc(1, value));
} : function (object, key, value) {
object[key] = value;
return object;
};
},{"./_descriptors":103,"./_object-dp":132,"./_property-desc":146}],113:[function(require,module,exports){
var document = require('./_global').document;
module.exports = document && document.documentElement;
},{"./_global":110}],114:[function(require,module,exports){
module.exports = !require('./_descriptors') && !require('./_fails')(function () {
return Object.defineProperty(require('./_dom-create')('div'), 'a', { get: function () { return 7; } }).a != 7;
});
},{"./_descriptors":103,"./_dom-create":104,"./_fails":108}],115:[function(require,module,exports){
// fast apply, http://jsperf.lnkit.com/fast-apply/5
module.exports = function (fn, args, that) {
var un = that === undefined;
switch (args.length) {
case 0: return un ? fn()
: fn.call(that);
case 1: return un ? fn(args[0])
: fn.call(that, args[0]);
case 2: return un ? fn(args[0], args[1])
: fn.call(that, args[0], args[1]);
case 3: return un ? fn(args[0], args[1], args[2])
: fn.call(that, args[0], args[1], args[2]);
case 4: return un ? fn(args[0], args[1], args[2], args[3])
: fn.call(that, args[0], args[1], args[2], args[3]);
} return fn.apply(that, args);
};
},{}],116:[function(require,module,exports){
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = require('./_cof');
// eslint-disable-next-line no-prototype-builtins
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) {
return cof(it) == 'String' ? it.split('') : Object(it);
};
},{"./_cof":98}],117:[function(require,module,exports){
// check on default Array iterator
var Iterators = require('./_iterators');
var ITERATOR = require('./_wks')('iterator');
var ArrayProto = Array.prototype;
module.exports = function (it) {
return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it);
};
},{"./_iterators":125,"./_wks":166}],118:[function(require,module,exports){
// 7.2.2 IsArray(argument)
var cof = require('./_cof');
module.exports = Array.isArray || function isArray(arg) {
return cof(arg) == 'Array';
};
},{"./_cof":98}],119:[function(require,module,exports){
module.exports = function (it) {
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
},{}],120:[function(require,module,exports){
// call something on iterator step with safe closing on error
var anObject = require('./_an-object');
module.exports = function (iterator, fn, value, entries) {
try {
return entries ? fn(anObject(value)[0], value[1]) : fn(value);
// 7.4.6 IteratorClose(iterator, completion)
} catch (e) {
var ret = iterator['return'];
if (ret !== undefined) anObject(ret.call(iterator));
throw e;
}
};
},{"./_an-object":95}],121:[function(require,module,exports){
'use strict';
var create = require('./_object-create');
var descriptor = require('./_property-desc');
var setToStringTag = require('./_set-to-string-tag');
var IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
require('./_hide')(IteratorPrototype, require('./_wks')('iterator'), function () { return this; });
module.exports = function (Constructor, NAME, next) {
Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) });
setToStringTag(Constructor, NAME + ' Iterator');
};
},{"./_hide":112,"./_object-create":131,"./_property-desc":146,"./_set-to-string-tag":150,"./_wks":166}],122:[function(require,module,exports){
'use strict';
var LIBRARY = require('./_library');
var $export = require('./_export');
var redefine = require('./_redefine');
var hide = require('./_hide');
var Iterators = require('./_iterators');
var $iterCreate = require('./_iter-create');
var setToStringTag = require('./_set-to-string-tag');
var getPrototypeOf = require('./_object-gpo');
var ITERATOR = require('./_wks')('iterator');
var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next`
var FF_ITERATOR = '@@iterator';
var KEYS = 'keys';
var VALUES = 'values';
var returnThis = function () { return this; };
module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) {
$iterCreate(Constructor, NAME, next);
var getMethod = function (kind) {
if (!BUGGY && kind in proto) return proto[kind];
switch (kind) {
case KEYS: return function keys() { return new Constructor(this, kind); };
case VALUES: return function values() { return new Constructor(this, kind); };
} return function entries() { return new Constructor(this, kind); };
};
var TAG = NAME + ' Iterator';
var DEF_VALUES = DEFAULT == VALUES;
var VALUES_BUG = false;
var proto = Base.prototype;
var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT];
var $default = $native || getMethod(DEFAULT);
var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined;
var $anyNative = NAME == 'Array' ? proto.entries || $native : $native;
var methods, key, IteratorPrototype;
// Fix native
if ($anyNative) {
IteratorPrototype = getPrototypeOf($anyNative.call(new Base()));
if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) {
// Set @@toStringTag to native iterators
setToStringTag(IteratorPrototype, TAG, true);
// fix for some old engines
if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis);
}
}
// fix Array#{values, @@iterator}.name in V8 / FF
if (DEF_VALUES && $native && $native.name !== VALUES) {
VALUES_BUG = true;
$default = function values() { return $native.call(this); };
}
// Define iterator
if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) {
hide(proto, ITERATOR, $default);
}
// Plug for library
Iterators[NAME] = $default;
Iterators[TAG] = returnThis;
if (DEFAULT) {
methods = {
values: DEF_VALUES ? $default : getMethod(VALUES),
keys: IS_SET ? $default : getMethod(KEYS),
entries: $entries
};
if (FORCED) for (key in methods) {
if (!(key in proto)) redefine(proto, key, methods[key]);
} else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
}
return methods;
};
},{"./_export":107,"./_hide":112,"./_iter-create":121,"./_iterators":125,"./_library":126,"./_object-gpo":138,"./_redefine":148,"./_set-to-string-tag":150,"./_wks":166}],123:[function(require,module,exports){
var ITERATOR = require('./_wks')('iterator');
var SAFE_CLOSING = false;
try {
var riter = [7][ITERATOR]();
riter['return'] = function () { SAFE_CLOSING = true; };
// eslint-disable-next-line no-throw-literal
Array.from(riter, function () { throw 2; });
} catch (e) { /* empty */ }
module.exports = function (exec, skipClosing) {
if (!skipClosing && !SAFE_CLOSING) return false;
var safe = false;
try {
var arr = [7];
var iter = arr[ITERATOR]();
iter.next = function () { return { done: safe = true }; };
arr[ITERATOR] = function () { return iter; };
exec(arr);
} catch (e) { /* empty */ }
return safe;
};
},{"./_wks":166}],124:[function(require,module,exports){
module.exports = function (done, value) {
return { value: value, done: !!done };
};
},{}],125:[function(require,module,exports){
module.exports = {};
},{}],126:[function(require,module,exports){
module.exports = true;
},{}],127:[function(require,module,exports){
var META = require('./_uid')('meta');
var isObject = require('./_is-object');
var has = require('./_has');
var setDesc = require('./_object-dp').f;
var id = 0;
var isExtensible = Object.isExtensible || function () {
return true;
};
var FREEZE = !require('./_fails')(function () {
return isExtensible(Object.preventExtensions({}));
});
var setMeta = function (it) {
setDesc(it, META, { value: {
i: 'O' + ++id, // object ID
w: {} // weak collections IDs
} });
};
var fastKey = function (it, create) {
// return primitive with prefix
if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
if (!has(it, META)) {
// can't set metadata to uncaught frozen object
if (!isExtensible(it)) return 'F';
// not necessary to add metadata
if (!create) return 'E';
// add missing metadata
setMeta(it);
// return object ID
} return it[META].i;
};
var getWeak = function (it, create) {
if (!has(it, META)) {
// can't set metadata to uncaught frozen object
if (!isExtensible(it)) return true;
// not necessary to add metadata
if (!create) return false;
// add missing metadata
setMeta(it);
// return hash weak collections IDs
} return it[META].w;
};
// add metadata on freeze-family methods calling
var onFreeze = function (it) {
if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it);
return it;
};
var meta = module.exports = {
KEY: META,
NEED: false,
fastKey: fastKey,
getWeak: getWeak,
onFreeze: onFreeze
};
},{"./_fails":108,"./_has":111,"./_is-object":119,"./_object-dp":132,"./_uid":162}],128:[function(require,module,exports){
var global = require('./_global');
var macrotask = require('./_task').set;
var Observer = global.MutationObserver || global.WebKitMutationObserver;
var process = global.process;
var Promise = global.Promise;
var isNode = require('./_cof')(process) == 'process';
module.exports = function () {
var head, last, notify;
var flush = function () {
var parent, fn;
if (isNode && (parent = process.domain)) parent.exit();
while (head) {
fn = head.fn;
head = head.next;
try {
fn();
} catch (e) {
if (head) notify();
else last = undefined;
throw e;
}
} last = undefined;
if (parent) parent.enter();
};
// Node.js
if (isNode) {
notify = function () {
process.nextTick(flush);
};
// browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339
} else if (Observer && !(global.navigator && global.navigator.standalone)) {
var toggle = true;
var node = document.createTextNode('');
new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new
notify = function () {
node.data = toggle = !toggle;
};
// environments with maybe non-completely correct, but existent Promise
} else if (Promise && Promise.resolve) {
// Promise.resolve without an argument throws an error in LG WebOS 2
var promise = Promise.resolve(undefined);
notify = function () {
promise.then(flush);
};
// for other environments - macrotask based on:
// - setImmediate
// - MessageChannel
// - window.postMessag
// - onreadystatechange
// - setTimeout
} else {
notify = function () {
// strange IE + webpack dev server bug - use .call(global)
macrotask.call(global, flush);
};
}
return function (fn) {
var task = { fn: fn, next: undefined };
if (last) last.next = task;
if (!head) {
head = task;
notify();
} last = task;
};
};
},{"./_cof":98,"./_global":110,"./_task":155}],129:[function(require,module,exports){
'use strict';
// 25.4.1.5 NewPromiseCapability(C)
var aFunction = require('./_a-function');
function PromiseCapability(C) {
var resolve, reject;
this.promise = new C(function ($$resolve, $$reject) {
if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor');
resolve = $$resolve;
reject = $$reject;
});
this.resolve = aFunction(resolve);
this.reject = aFunction(reject);
}
module.exports.f = function (C) {
return new PromiseCapability(C);
};
},{"./_a-function":92}],130:[function(require,module,exports){
'use strict';
// 19.1.2.1 Object.assign(target, source, ...)
var DESCRIPTORS = require('./_descriptors');
var getKeys = require('./_object-keys');
var gOPS = require('./_object-gops');
var pIE = require('./_object-pie');
var toObject = require('./_to-object');
var IObject = require('./_iobject');
var $assign = Object.assign;
// should work with symbols and should have deterministic property order (V8 bug)
module.exports = !$assign || require('./_fails')(function () {
var A = {};
var B = {};
// eslint-disable-next-line no-undef
var S = Symbol();
var K = 'abcdefghijklmnopqrst';
A[S] = 7;
K.split('').forEach(function (k) { B[k] = k; });
return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
}) ? function assign(target, source) { // eslint-disable-line no-unused-vars
var T = toObject(target);
var aLen = arguments.length;
var index = 1;
var getSymbols = gOPS.f;
var isEnum = pIE.f;
while (aLen > index) {
var S = IObject(arguments[index++]);
var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S);
var length = keys.length;
var j = 0;
var key;
while (length > j) {
key = keys[j++];
if (!DESCRIPTORS || isEnum.call(S, key)) T[key] = S[key];
}
} return T;
} : $assign;
},{"./_descriptors":103,"./_fails":108,"./_iobject":116,"./_object-gops":137,"./_object-keys":140,"./_object-pie":141,"./_to-object":160}],131:[function(require,module,exports){
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var anObject = require('./_an-object');
var dPs = require('./_object-dps');
var enumBugKeys = require('./_enum-bug-keys');
var IE_PROTO = require('./_shared-key')('IE_PROTO');
var Empty = function () { /* empty */ };
var PROTOTYPE = 'prototype';
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var createDict = function () {
// Thrash, waste and sodomy: IE GC bug
var iframe = require('./_dom-create')('iframe');
var i = enumBugKeys.length;
var lt = '<';
var gt = '>';
var iframeDocument;
iframe.style.display = 'none';
require('./_html').appendChild(iframe);
iframe.src = 'javascript:'; // eslint-disable-line no-script-url
// createDict = iframe.contentWindow.Object;
// html.removeChild(iframe);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);
iframeDocument.close();
createDict = iframeDocument.F;
while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]];
return createDict();
};
module.exports = Object.create || function create(O, Properties) {
var result;
if (O !== null) {
Empty[PROTOTYPE] = anObject(O);
result = new Empty();
Empty[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = createDict();
return Properties === undefined ? result : dPs(result, Properties);
};
},{"./_an-object":95,"./_dom-create":104,"./_enum-bug-keys":105,"./_html":113,"./_object-dps":133,"./_shared-key":151}],132:[function(require,module,exports){
var anObject = require('./_an-object');
var IE8_DOM_DEFINE = require('./_ie8-dom-define');
var toPrimitive = require('./_to-primitive');
var dP = Object.defineProperty;
exports.f = require('./_descriptors') ? Object.defineProperty : function defineProperty(O, P, Attributes) {
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if (IE8_DOM_DEFINE) try {
return dP(O, P, Attributes);
} catch (e) { /* empty */ }
if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!');
if ('value' in Attributes) O[P] = Attributes.value;
return O;
};
},{"./_an-object":95,"./_descriptors":103,"./_ie8-dom-define":114,"./_to-primitive":161}],133:[function(require,module,exports){
var dP = require('./_object-dp');
var anObject = require('./_an-object');
var getKeys = require('./_object-keys');
module.exports = require('./_descriptors') ? Object.defineProperties : function defineProperties(O, Properties) {
anObject(O);
var keys = getKeys(Properties);
var length = keys.length;
var i = 0;
var P;
while (length > i) dP.f(O, P = keys[i++], Properties[P]);
return O;
};
},{"./_an-object":95,"./_descriptors":103,"./_object-dp":132,"./_object-keys":140}],134:[function(require,module,exports){
var pIE = require('./_object-pie');
var createDesc = require('./_property-desc');
var toIObject = require('./_to-iobject');
var toPrimitive = require('./_to-primitive');
var has = require('./_has');
var IE8_DOM_DEFINE = require('./_ie8-dom-define');
var gOPD = Object.getOwnPropertyDescriptor;
exports.f = require('./_descriptors') ? gOPD : function getOwnPropertyDescriptor(O, P) {
O = toIObject(O);
P = toPrimitive(P, true);
if (IE8_DOM_DEFINE) try {
return gOPD(O, P);
} catch (e) { /* empty */ }
if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]);
};
},{"./_descriptors":103,"./_has":111,"./_ie8-dom-define":114,"./_object-pie":141,"./_property-desc":146,"./_to-iobject":158,"./_to-primitive":161}],135:[function(require,module,exports){
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var toIObject = require('./_to-iobject');
var gOPN = require('./_object-gopn').f;
var toString = {}.toString;
var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
? Object.getOwnPropertyNames(window) : [];
var getWindowNames = function (it) {
try {
return gOPN(it);
} catch (e) {
return windowNames.slice();
}
};
module.exports.f = function getOwnPropertyNames(it) {
return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it));
};
},{"./_object-gopn":136,"./_to-iobject":158}],136:[function(require,module,exports){
// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
var $keys = require('./_object-keys-internal');
var hiddenKeys = require('./_enum-bug-keys').concat('length', 'prototype');
exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
return $keys(O, hiddenKeys);
};
},{"./_enum-bug-keys":105,"./_object-keys-internal":139}],137:[function(require,module,exports){
exports.f = Object.getOwnPropertySymbols;
},{}],138:[function(require,module,exports){
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
var has = require('./_has');
var toObject = require('./_to-object');
var IE_PROTO = require('./_shared-key')('IE_PROTO');
var ObjectProto = Object.prototype;
module.exports = Object.getPrototypeOf || function (O) {
O = toObject(O);
if (has(O, IE_PROTO)) return O[IE_PROTO];
if (typeof O.constructor == 'function' && O instanceof O.constructor) {
return O.constructor.prototype;
} return O instanceof Object ? ObjectProto : null;
};
},{"./_has":111,"./_shared-key":151,"./_to-object":160}],139:[function(require,module,exports){
var has = require('./_has');
var toIObject = require('./_to-iobject');
var arrayIndexOf = require('./_array-includes')(false);
var IE_PROTO = require('./_shared-key')('IE_PROTO');
module.exports = function (object, names) {
var O = toIObject(object);
var i = 0;
var result = [];
var key;
for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while (names.length > i) if (has(O, key = names[i++])) {
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
},{"./_array-includes":96,"./_has":111,"./_shared-key":151,"./_to-iobject":158}],140:[function(require,module,exports){
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = require('./_object-keys-internal');
var enumBugKeys = require('./_enum-bug-keys');
module.exports = Object.keys || function keys(O) {
return $keys(O, enumBugKeys);
};
},{"./_enum-bug-keys":105,"./_object-keys-internal":139}],141:[function(require,module,exports){
exports.f = {}.propertyIsEnumerable;
},{}],142:[function(require,module,exports){
// most Object methods by ES6 should accept primitives
var $export = require('./_export');
var core = require('./_core');
var fails = require('./_fails');
module.exports = function (KEY, exec) {
var fn = (core.Object || {})[KEY] || Object[KEY];
var exp = {};
exp[KEY] = exec(fn);
$export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp);
};
},{"./_core":99,"./_export":107,"./_fails":108}],143:[function(require,module,exports){
var DESCRIPTORS = require('./_descriptors');
var getKeys = require('./_object-keys');
var toIObject = require('./_to-iobject');
var isEnum = require('./_object-pie').f;
module.exports = function (isEntries) {
return function (it) {
var O = toIObject(it);
var keys = getKeys(O);
var length = keys.length;
var i = 0;
var result = [];
var key;
while (length > i) {
key = keys[i++];
if (!DESCRIPTORS || isEnum.call(O, key)) {
result.push(isEntries ? [key, O[key]] : O[key]);
}
}
return result;
};
};
},{"./_descriptors":103,"./_object-keys":140,"./_object-pie":141,"./_to-iobject":158}],144:[function(require,module,exports){
module.exports = function (exec) {
try {
return { e: false, v: exec() };
} catch (e) {
return { e: true, v: e };
}
};
},{}],145:[function(require,module,exports){
var anObject = require('./_an-object');
var isObject = require('./_is-object');
var newPromiseCapability = require('./_new-promise-capability');
module.exports = function (C, x) {
anObject(C);
if (isObject(x) && x.constructor === C) return x;
var promiseCapability = newPromiseCapability.f(C);
var resolve = promiseCapability.resolve;
resolve(x);
return promiseCapability.promise;
};
},{"./_an-object":95,"./_is-object":119,"./_new-promise-capability":129}],146:[function(require,module,exports){
module.exports = function (bitmap, value) {
return {
enumerable: !(bitmap & 1),
configurable: !(bitmap & 2),
writable: !(bitmap & 4),
value: value
};
};
},{}],147:[function(require,module,exports){
var hide = require('./_hide');
module.exports = function (target, src, safe) {
for (var key in src) {
if (safe && target[key]) target[key] = src[key];
else hide(target, key, src[key]);
} return target;
};
},{"./_hide":112}],148:[function(require,module,exports){
module.exports = require('./_hide');
},{"./_hide":112}],149:[function(require,module,exports){
'use strict';
var global = require('./_global');
var core = require('./_core');
var dP = require('./_object-dp');
var DESCRIPTORS = require('./_descriptors');
var SPECIES = require('./_wks')('species');
module.exports = function (KEY) {
var C = typeof core[KEY] == 'function' ? core[KEY] : global[KEY];
if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, {
configurable: true,
get: function () { return this; }
});
};
},{"./_core":99,"./_descriptors":103,"./_global":110,"./_object-dp":132,"./_wks":166}],150:[function(require,module,exports){
var def = require('./_object-dp').f;
var has = require('./_has');
var TAG = require('./_wks')('toStringTag');
module.exports = function (it, tag, stat) {
if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag });
};
},{"./_has":111,"./_object-dp":132,"./_wks":166}],151:[function(require,module,exports){
var shared = require('./_shared')('keys');
var uid = require('./_uid');
module.exports = function (key) {
return shared[key] || (shared[key] = uid(key));
};
},{"./_shared":152,"./_uid":162}],152:[function(require,module,exports){
var core = require('./_core');
var global = require('./_global');
var SHARED = '__core-js_shared__';
var store = global[SHARED] || (global[SHARED] = {});
(module.exports = function (key, value) {
return store[key] || (store[key] = value !== undefined ? value : {});
})('versions', []).push({
version: core.version,
mode: require('./_library') ? 'pure' : 'global',
copyright: '© 2019 Denis Pushkarev (zloirock.ru)'
});
},{"./_core":99,"./_global":110,"./_library":126}],153:[function(require,module,exports){
// 7.3.20 SpeciesConstructor(O, defaultConstructor)
var anObject = require('./_an-object');
var aFunction = require('./_a-function');
var SPECIES = require('./_wks')('species');
module.exports = function (O, D) {
var C = anObject(O).constructor;
var S;
return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S);
};
},{"./_a-function":92,"./_an-object":95,"./_wks":166}],154:[function(require,module,exports){
var toInteger = require('./_to-integer');
var defined = require('./_defined');
// true -> String#at
// false -> String#codePointAt
module.exports = function (TO_STRING) {
return function (that, pos) {
var s = String(defined(that));
var i = toInteger(pos);
var l = s.length;
var a, b;
if (i < 0 || i >= l) return TO_STRING ? '' : undefined;
a = s.charCodeAt(i);
return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
? TO_STRING ? s.charAt(i) : a
: TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
};
};
},{"./_defined":102,"./_to-integer":157}],155:[function(require,module,exports){
var ctx = require('./_ctx');
var invoke = require('./_invoke');
var html = require('./_html');
var cel = require('./_dom-create');
var global = require('./_global');
var process = global.process;
var setTask = global.setImmediate;
var clearTask = global.clearImmediate;
var MessageChannel = global.MessageChannel;
var Dispatch = global.Dispatch;
var counter = 0;
var queue = {};
var ONREADYSTATECHANGE = 'onreadystatechange';
var defer, channel, port;
var run = function () {
var id = +this;
// eslint-disable-next-line no-prototype-builtins
if (queue.hasOwnProperty(id)) {
var fn = queue[id];
delete queue[id];
fn();
}
};
var listener = function (event) {
run.call(event.data);
};
// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
if (!setTask || !clearTask) {
setTask = function setImmediate(fn) {
var args = [];
var i = 1;
while (arguments.length > i) args.push(arguments[i++]);
queue[++counter] = function () {
// eslint-disable-next-line no-new-func
invoke(typeof fn == 'function' ? fn : Function(fn), args);
};
defer(counter);
return counter;
};
clearTask = function clearImmediate(id) {
delete queue[id];
};
// Node.js 0.8-
if (require('./_cof')(process) == 'process') {
defer = function (id) {
process.nextTick(ctx(run, id, 1));
};
// Sphere (JS game engine) Dispatch API
} else if (Dispatch && Dispatch.now) {
defer = function (id) {
Dispatch.now(ctx(run, id, 1));
};
// Browsers with MessageChannel, includes WebWorkers
} else if (MessageChannel) {
channel = new MessageChannel();
port = channel.port2;
channel.port1.onmessage = listener;
defer = ctx(port.postMessage, port, 1);
// Browsers with postMessage, skip WebWorkers
// IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
} else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) {
defer = function (id) {
global.postMessage(id + '', '*');
};
global.addEventListener('message', listener, false);
// IE8-
} else if (ONREADYSTATECHANGE in cel('script')) {
defer = function (id) {
html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () {
html.removeChild(this);
run.call(id);
};
};
// Rest old browsers
} else {
defer = function (id) {
setTimeout(ctx(run, id, 1), 0);
};
}
}
module.exports = {
set: setTask,
clear: clearTask
};
},{"./_cof":98,"./_ctx":101,"./_dom-create":104,"./_global":110,"./_html":113,"./_invoke":115}],156:[function(require,module,exports){
var toInteger = require('./_to-integer');
var max = Math.max;
var min = Math.min;
module.exports = function (index, length) {
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
},{"./_to-integer":157}],157:[function(require,module,exports){
// 7.1.4 ToInteger
var ceil = Math.ceil;
var floor = Math.floor;
module.exports = function (it) {
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
},{}],158:[function(require,module,exports){
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = require('./_iobject');
var defined = require('./_defined');
module.exports = function (it) {
return IObject(defined(it));
};
},{"./_defined":102,"./_iobject":116}],159:[function(require,module,exports){
// 7.1.15 ToLength
var toInteger = require('./_to-integer');
var min = Math.min;
module.exports = function (it) {
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
},{"./_to-integer":157}],160:[function(require,module,exports){
// 7.1.13 ToObject(argument)
var defined = require('./_defined');
module.exports = function (it) {
return Object(defined(it));
};
},{"./_defined":102}],161:[function(require,module,exports){
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = require('./_is-object');
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function (it, S) {
if (!isObject(it)) return it;
var fn, val;
if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val;
if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
throw TypeError("Can't convert object to primitive value");
};
},{"./_is-object":119}],162:[function(require,module,exports){
var id = 0;
var px = Math.random();
module.exports = function (key) {
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
},{}],163:[function(require,module,exports){
var global = require('./_global');
var navigator = global.navigator;
module.exports = navigator && navigator.userAgent || '';
},{"./_global":110}],164:[function(require,module,exports){
var global = require('./_global');
var core = require('./_core');
var LIBRARY = require('./_library');
var wksExt = require('./_wks-ext');
var defineProperty = require('./_object-dp').f;
module.exports = function (name) {
var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});
if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) });
};
},{"./_core":99,"./_global":110,"./_library":126,"./_object-dp":132,"./_wks-ext":165}],165:[function(require,module,exports){
exports.f = require('./_wks');
},{"./_wks":166}],166:[function(require,module,exports){
var store = require('./_shared')('wks');
var uid = require('./_uid');
var Symbol = require('./_global').Symbol;
var USE_SYMBOL = typeof Symbol == 'function';
var $exports = module.exports = function (name) {
return store[name] || (store[name] =
USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};
$exports.store = store;
},{"./_global":110,"./_shared":152,"./_uid":162}],167:[function(require,module,exports){
var classof = require('./_classof');
var ITERATOR = require('./_wks')('iterator');
var Iterators = require('./_iterators');
module.exports = require('./_core').getIteratorMethod = function (it) {
if (it != undefined) return it[ITERATOR]
|| it['@@iterator']
|| Iterators[classof(it)];
};
},{"./_classof":97,"./_core":99,"./_iterators":125,"./_wks":166}],168:[function(require,module,exports){
'use strict';
var ctx = require('./_ctx');
var $export = require('./_export');
var toObject = require('./_to-object');
var call = require('./_iter-call');
var isArrayIter = require('./_is-array-iter');
var toLength = require('./_to-length');
var createProperty = require('./_create-property');
var getIterFn = require('./core.get-iterator-method');
$export($export.S + $export.F * !require('./_iter-detect')(function (iter) { Array.from(iter); }), 'Array', {
// 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined)
from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) {
var O = toObject(arrayLike);
var C = typeof this == 'function' ? this : Array;
var aLen = arguments.length;
var mapfn = aLen > 1 ? arguments[1] : undefined;
var mapping = mapfn !== undefined;
var index = 0;
var iterFn = getIterFn(O);
var length, result, step, iterator;
if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2);
// if object isn't iterable or it's array with default iterator - use simple case
if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) {
for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) {
createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value);
}
} else {
length = toLength(O.length);
for (result = new C(length); length > index; index++) {
createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]);
}
}
result.length = index;
return result;
}
});
},{"./_create-property":100,"./_ctx":101,"./_export":107,"./_is-array-iter":117,"./_iter-call":120,"./_iter-detect":123,"./_to-length":159,"./_to-object":160,"./core.get-iterator-method":167}],169:[function(require,module,exports){
'use strict';
var addToUnscopables = require('./_add-to-unscopables');
var step = require('./_iter-step');
var Iterators = require('./_iterators');
var toIObject = require('./_to-iobject');
// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
module.exports = require('./_iter-define')(Array, 'Array', function (iterated, kind) {
this._t = toIObject(iterated); // target
this._i = 0; // next index
this._k = kind; // kind
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function () {
var O = this._t;
var kind = this._k;
var index = this._i++;
if (!O || index >= O.length) {
this._t = undefined;
return step(1);
}
if (kind == 'keys') return step(0, index);
if (kind == 'values') return step(0, O[index]);
return step(0, [index, O[index]]);
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators.Arguments = Iterators.Array;
addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');
},{"./_add-to-unscopables":93,"./_iter-define":122,"./_iter-step":124,"./_iterators":125,"./_to-iobject":158}],170:[function(require,module,exports){
'use strict';
var isObject = require('./_is-object');
var getPrototypeOf = require('./_object-gpo');
var HAS_INSTANCE = require('./_wks')('hasInstance');
var FunctionProto = Function.prototype;
// 19.2.3.6 Function.prototype[@@hasInstance](V)
if (!(HAS_INSTANCE in FunctionProto)) require('./_object-dp').f(FunctionProto, HAS_INSTANCE, { value: function (O) {
if (typeof this != 'function' || !isObject(O)) return false;
if (!isObject(this.prototype)) return O instanceof this;
// for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this:
while (O = getPrototypeOf(O)) if (this.prototype === O) return true;
return false;
} });
},{"./_is-object":119,"./_object-dp":132,"./_object-gpo":138,"./_wks":166}],171:[function(require,module,exports){
// 19.1.3.1 Object.assign(target, source)
var $export = require('./_export');
$export($export.S + $export.F, 'Object', { assign: require('./_object-assign') });
},{"./_export":107,"./_object-assign":130}],172:[function(require,module,exports){
var $export = require('./_export');
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
$export($export.S, 'Object', { create: require('./_object-create') });
},{"./_export":107,"./_object-create":131}],173:[function(require,module,exports){
var $export = require('./_export');
// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes)
$export($export.S + $export.F * !require('./_descriptors'), 'Object', { defineProperty: require('./_object-dp').f });
},{"./_descriptors":103,"./_export":107,"./_object-dp":132}],174:[function(require,module,exports){
// 19.1.2.7 Object.getOwnPropertyNames(O)
require('./_object-sap')('getOwnPropertyNames', function () {
return require('./_object-gopn-ext').f;
});
},{"./_object-gopn-ext":135,"./_object-sap":142}],175:[function(require,module,exports){
// 19.1.2.9 Object.getPrototypeOf(O)
var toObject = require('./_to-object');
var $getPrototypeOf = require('./_object-gpo');
require('./_object-sap')('getPrototypeOf', function () {
return function getPrototypeOf(it) {
return $getPrototypeOf(toObject(it));
};
});
},{"./_object-gpo":138,"./_object-sap":142,"./_to-object":160}],176:[function(require,module,exports){
// 19.1.2.14 Object.keys(O)
var toObject = require('./_to-object');
var $keys = require('./_object-keys');
require('./_object-sap')('keys', function () {
return function keys(it) {
return $keys(toObject(it));
};
});
},{"./_object-keys":140,"./_object-sap":142,"./_to-object":160}],177:[function(require,module,exports){
arguments[4][71][0].apply(exports,arguments)
},{"dup":71}],178:[function(require,module,exports){
'use strict';
var LIBRARY = require('./_library');
var global = require('./_global');
var ctx = require('./_ctx');
var classof = require('./_classof');
var $export = require('./_export');
var isObject = require('./_is-object');
var aFunction = require('./_a-function');
var anInstance = require('./_an-instance');
var forOf = require('./_for-of');
var speciesConstructor = require('./_species-constructor');
var task = require('./_task').set;
var microtask = require('./_microtask')();
var newPromiseCapabilityModule = require('./_new-promise-capability');
var perform = require('./_perform');
var userAgent = require('./_user-agent');
var promiseResolve = require('./_promise-resolve');
var PROMISE = 'Promise';
var TypeError = global.TypeError;
var process = global.process;
var versions = process && process.versions;
var v8 = versions && versions.v8 || '';
var $Promise = global[PROMISE];
var isNode = classof(process) == 'process';
var empty = function () { /* empty */ };
var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper;
var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f;
var USE_NATIVE = !!function () {
try {
// correct subclassing with @@species support
var promise = $Promise.resolve(1);
var FakePromise = (promise.constructor = {})[require('./_wks')('species')] = function (exec) {
exec(empty, empty);
};
// unhandled rejections tracking support, NodeJS Promise without it fails @@species test
return (isNode || typeof PromiseRejectionEvent == 'function')
&& promise.then(empty) instanceof FakePromise
// v8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables
// https://bugs.chromium.org/p/chromium/issues/detail?id=830565
// we can't detect it synchronously, so just check versions
&& v8.indexOf('6.6') !== 0
&& userAgent.indexOf('Chrome/66') === -1;
} catch (e) { /* empty */ }
}();
// helpers
var isThenable = function (it) {
var then;
return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
};
var notify = function (promise, isReject) {
if (promise._n) return;
promise._n = true;
var chain = promise._c;
microtask(function () {
var value = promise._v;
var ok = promise._s == 1;
var i = 0;
var run = function (reaction) {
var handler = ok ? reaction.ok : reaction.fail;
var resolve = reaction.resolve;
var reject = reaction.reject;
var domain = reaction.domain;
var result, then, exited;
try {
if (handler) {
if (!ok) {
if (promise._h == 2) onHandleUnhandled(promise);
promise._h = 1;
}
if (handler === true) result = value;
else {
if (domain) domain.enter();
result = handler(value); // may throw
if (domain) {
domain.exit();
exited = true;
}
}
if (result === reaction.promise) {
reject(TypeError('Promise-chain cycle'));
} else if (then = isThenable(result)) {
then.call(result, resolve, reject);
} else resolve(result);
} else reject(value);
} catch (e) {
if (domain && !exited) domain.exit();
reject(e);
}
};
while (chain.length > i) run(chain[i++]); // variable length - can't use forEach
promise._c = [];
promise._n = false;
if (isReject && !promise._h) onUnhandled(promise);
});
};
var onUnhandled = function (promise) {
task.call(global, function () {
var value = promise._v;
var unhandled = isUnhandled(promise);
var result, handler, console;
if (unhandled) {
result = perform(function () {
if (isNode) {
process.emit('unhandledRejection', value, promise);
} else if (handler = global.onunhandledrejection) {
handler({ promise: promise, reason: value });
} else if ((console = global.console) && console.error) {
console.error('Unhandled promise rejection', value);
}
});
// Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
promise._h = isNode || isUnhandled(promise) ? 2 : 1;
} promise._a = undefined;
if (unhandled && result.e) throw result.v;
});
};
var isUnhandled = function (promise) {
return promise._h !== 1 && (promise._a || promise._c).length === 0;
};
var onHandleUnhandled = function (promise) {
task.call(global, function () {
var handler;
if (isNode) {
process.emit('rejectionHandled', promise);
} else if (handler = global.onrejectionhandled) {
handler({ promise: promise, reason: promise._v });
}
});
};
var $reject = function (value) {
var promise = this;
if (promise._d) return;
promise._d = true;
promise = promise._w || promise; // unwrap
promise._v = value;
promise._s = 2;
if (!promise._a) promise._a = promise._c.slice();
notify(promise, true);
};
var $resolve = function (value) {
var promise = this;
var then;
if (promise._d) return;
promise._d = true;
promise = promise._w || promise; // unwrap
try {
if (promise === value) throw TypeError("Promise can't be resolved itself");
if (then = isThenable(value)) {
microtask(function () {
var wrapper = { _w: promise, _d: false }; // wrap
try {
then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));
} catch (e) {
$reject.call(wrapper, e);
}
});
} else {
promise._v = value;
promise._s = 1;
notify(promise, false);
}
} catch (e) {
$reject.call({ _w: promise, _d: false }, e); // wrap
}
};
// constructor polyfill
if (!USE_NATIVE) {
// 25.4.3.1 Promise(executor)
$Promise = function Promise(executor) {
anInstance(this, $Promise, PROMISE, '_h');
aFunction(executor);
Internal.call(this);
try {
executor(ctx($resolve, this, 1), ctx($reject, this, 1));
} catch (err) {
$reject.call(this, err);
}
};
// eslint-disable-next-line no-unused-vars
Internal = function Promise(executor) {
this._c = []; // <- awaiting reactions
this._a = undefined; // <- checked in isUnhandled reactions
this._s = 0; // <- state
this._d = false; // <- done
this._v = undefined; // <- value
this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled
this._n = false; // <- notify
};
Internal.prototype = require('./_redefine-all')($Promise.prototype, {
// 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
then: function then(onFulfilled, onRejected) {
var reaction = newPromiseCapability(speciesConstructor(this, $Promise));
reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
reaction.fail = typeof onRejected == 'function' && onRejected;
reaction.domain = isNode ? process.domain : undefined;
this._c.push(reaction);
if (this._a) this._a.push(reaction);
if (this._s) notify(this, false);
return reaction.promise;
},
// 25.4.5.1 Promise.prototype.catch(onRejected)
'catch': function (onRejected) {
return this.then(undefined, onRejected);
}
});
OwnPromiseCapability = function () {
var promise = new Internal();
this.promise = promise;
this.resolve = ctx($resolve, promise, 1);
this.reject = ctx($reject, promise, 1);
};
newPromiseCapabilityModule.f = newPromiseCapability = function (C) {
return C === $Promise || C === Wrapper
? new OwnPromiseCapability(C)
: newGenericPromiseCapability(C);
};
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise });
require('./_set-to-string-tag')($Promise, PROMISE);
require('./_set-species')(PROMISE);
Wrapper = require('./_core')[PROMISE];
// statics
$export($export.S + $export.F * !USE_NATIVE, PROMISE, {
// 25.4.4.5 Promise.reject(r)
reject: function reject(r) {
var capability = newPromiseCapability(this);
var $$reject = capability.reject;
$$reject(r);
return capability.promise;
}
});
$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, {
// 25.4.4.6 Promise.resolve(x)
resolve: function resolve(x) {
return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x);
}
});
$export($export.S + $export.F * !(USE_NATIVE && require('./_iter-detect')(function (iter) {
$Promise.all(iter)['catch'](empty);
})), PROMISE, {
// 25.4.4.1 Promise.all(iterable)
all: function all(iterable) {
var C = this;
var capability = newPromiseCapability(C);
var resolve = capability.resolve;
var reject = capability.reject;
var result = perform(function () {
var values = [];
var index = 0;
var remaining = 1;
forOf(iterable, false, function (promise) {
var $index = index++;
var alreadyCalled = false;
values.push(undefined);
remaining++;
C.resolve(promise).then(function (value) {
if (alreadyCalled) return;
alreadyCalled = true;
values[$index] = value;
--remaining || resolve(values);
}, reject);
});
--remaining || resolve(values);
});
if (result.e) reject(result.v);
return capability.promise;
},
// 25.4.4.4 Promise.race(iterable)
race: function race(iterable) {
var C = this;
var capability = newPromiseCapability(C);
var reject = capability.reject;
var result = perform(function () {
forOf(iterable, false, function (promise) {
C.resolve(promise).then(capability.resolve, reject);
});
});
if (result.e) reject(result.v);
return capability.promise;
}
});
},{"./_a-function":92,"./_an-instance":94,"./_classof":97,"./_core":99,"./_ctx":101,"./_export":107,"./_for-of":109,"./_global":110,"./_is-object":119,"./_iter-detect":123,"./_library":126,"./_microtask":128,"./_new-promise-capability":129,"./_perform":144,"./_promise-resolve":145,"./_redefine-all":147,"./_set-species":149,"./_set-to-string-tag":150,"./_species-constructor":153,"./_task":155,"./_user-agent":163,"./_wks":166}],179:[function(require,module,exports){
var $export = require('./_export');
var toAbsoluteIndex = require('./_to-absolute-index');
var fromCharCode = String.fromCharCode;
var $fromCodePoint = String.fromCodePoint;
// length should be 1, old FF problem
$export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', {
// 21.1.2.2 String.fromCodePoint(...codePoints)
fromCodePoint: function fromCodePoint(x) { // eslint-disable-line no-unused-vars
var res = [];
var aLen = arguments.length;
var i = 0;
var code;
while (aLen > i) {
code = +arguments[i++];
if (toAbsoluteIndex(code, 0x10ffff) !== code) throw RangeError(code + ' is not a valid code point');
res.push(code < 0x10000
? fromCharCode(code)
: fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00)
);
} return res.join('');
}
});
},{"./_export":107,"./_to-absolute-index":156}],180:[function(require,module,exports){
'use strict';
var $at = require('./_string-at')(true);
// 21.1.3.27 String.prototype[@@iterator]()
require('./_iter-define')(String, 'String', function (iterated) {
this._t = String(iterated); // target
this._i = 0; // next index
// 21.1.5.2.1 %StringIteratorPrototype%.next()
}, function () {
var O = this._t;
var index = this._i;
var point;
if (index >= O.length) return { value: undefined, done: true };
point = $at(O, index);
this._i += point.length;
return { value: point, done: false };
});
},{"./_iter-define":122,"./_string-at":154}],181:[function(require,module,exports){
'use strict';
// ECMAScript 6 symbols shim
var global = require('./_global');
var has = require('./_has');
var DESCRIPTORS = require('./_descriptors');
var $export = require('./_export');
var redefine = require('./_redefine');
var META = require('./_meta').KEY;
var $fails = require('./_fails');
var shared = require('./_shared');
var setToStringTag = require('./_set-to-string-tag');
var uid = require('./_uid');
var wks = require('./_wks');
var wksExt = require('./_wks-ext');
var wksDefine = require('./_wks-define');
var enumKeys = require('./_enum-keys');
var isArray = require('./_is-array');
var anObject = require('./_an-object');
var isObject = require('./_is-object');
var toObject = require('./_to-object');
var toIObject = require('./_to-iobject');
var toPrimitive = require('./_to-primitive');
var createDesc = require('./_property-desc');
var _create = require('./_object-create');
var gOPNExt = require('./_object-gopn-ext');
var $GOPD = require('./_object-gopd');
var $GOPS = require('./_object-gops');
var $DP = require('./_object-dp');
var $keys = require('./_object-keys');
var gOPD = $GOPD.f;
var dP = $DP.f;
var gOPN = gOPNExt.f;
var $Symbol = global.Symbol;
var $JSON = global.JSON;
var _stringify = $JSON && $JSON.stringify;
var PROTOTYPE = 'prototype';
var HIDDEN = wks('_hidden');
var TO_PRIMITIVE = wks('toPrimitive');
var isEnum = {}.propertyIsEnumerable;
var SymbolRegistry = shared('symbol-registry');
var AllSymbols = shared('symbols');
var OPSymbols = shared('op-symbols');
var ObjectProto = Object[PROTOTYPE];
var USE_NATIVE = typeof $Symbol == 'function' && !!$GOPS.f;
var QObject = global.QObject;
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;
// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDesc = DESCRIPTORS && $fails(function () {
return _create(dP({}, 'a', {
get: function () { return dP(this, 'a', { value: 7 }).a; }
})).a != 7;
}) ? function (it, key, D) {
var protoDesc = gOPD(ObjectProto, key);
if (protoDesc) delete ObjectProto[key];
dP(it, key, D);
if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc);
} : dP;
var wrap = function (tag) {
var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]);
sym._k = tag;
return sym;
};
var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) {
return typeof it == 'symbol';
} : function (it) {
return it instanceof $Symbol;
};
var $defineProperty = function defineProperty(it, key, D) {
if (it === ObjectProto) $defineProperty(OPSymbols, key, D);
anObject(it);
key = toPrimitive(key, true);
anObject(D);
if (has(AllSymbols, key)) {
if (!D.enumerable) {
if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {}));
it[HIDDEN][key] = true;
} else {
if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false;
D = _create(D, { enumerable: createDesc(0, false) });
} return setSymbolDesc(it, key, D);
} return dP(it, key, D);
};
var $defineProperties = function defineProperties(it, P) {
anObject(it);
var keys = enumKeys(P = toIObject(P));
var i = 0;
var l = keys.length;
var key;
while (l > i) $defineProperty(it, key = keys[i++], P[key]);
return it;
};
var $create = function create(it, P) {
return P === undefined ? _create(it) : $defineProperties(_create(it), P);
};
var $propertyIsEnumerable = function propertyIsEnumerable(key) {
var E = isEnum.call(this, key = toPrimitive(key, true));
if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false;
return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true;
};
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) {
it = toIObject(it);
key = toPrimitive(key, true);
if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return;
var D = gOPD(it, key);
if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true;
return D;
};
var $getOwnPropertyNames = function getOwnPropertyNames(it) {
var names = gOPN(toIObject(it));
var result = [];
var i = 0;
var key;
while (names.length > i) {
if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key);
} return result;
};
var $getOwnPropertySymbols = function getOwnPropertySymbols(it) {
var IS_OP = it === ObjectProto;
var names = gOPN(IS_OP ? OPSymbols : toIObject(it));
var result = [];
var i = 0;
var key;
while (names.length > i) {
if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]);
} return result;
};
// 19.4.1.1 Symbol([description])
if (!USE_NATIVE) {
$Symbol = function Symbol() {
if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!');
var tag = uid(arguments.length > 0 ? arguments[0] : undefined);
var $set = function (value) {
if (this === ObjectProto) $set.call(OPSymbols, value);
if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false;
setSymbolDesc(this, tag, createDesc(1, value));
};
if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set });
return wrap(tag);
};
redefine($Symbol[PROTOTYPE], 'toString', function toString() {
return this._k;
});
$GOPD.f = $getOwnPropertyDescriptor;
$DP.f = $defineProperty;
require('./_object-gopn').f = gOPNExt.f = $getOwnPropertyNames;
require('./_object-pie').f = $propertyIsEnumerable;
$GOPS.f = $getOwnPropertySymbols;
if (DESCRIPTORS && !require('./_library')) {
redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true);
}
wksExt.f = function (name) {
return wrap(wks(name));
};
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol });
for (var es6Symbols = (
// 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14
'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables'
).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]);
for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]);
$export($export.S + $export.F * !USE_NATIVE, 'Symbol', {
// 19.4.2.1 Symbol.for(key)
'for': function (key) {
return has(SymbolRegistry, key += '')
? SymbolRegistry[key]
: SymbolRegistry[key] = $Symbol(key);
},
// 19.4.2.5 Symbol.keyFor(sym)
keyFor: function keyFor(sym) {
if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!');
for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key;
},
useSetter: function () { setter = true; },
useSimple: function () { setter = false; }
});
$export($export.S + $export.F * !USE_NATIVE, 'Object', {
// 19.1.2.2 Object.create(O [, Properties])
create: $create,
// 19.1.2.4 Object.defineProperty(O, P, Attributes)
defineProperty: $defineProperty,
// 19.1.2.3 Object.defineProperties(O, Properties)
defineProperties: $defineProperties,
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
// 19.1.2.7 Object.getOwnPropertyNames(O)
getOwnPropertyNames: $getOwnPropertyNames,
// 19.1.2.8 Object.getOwnPropertySymbols(O)
getOwnPropertySymbols: $getOwnPropertySymbols
});
// Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives
// https://bugs.chromium.org/p/v8/issues/detail?id=3443
var FAILS_ON_PRIMITIVES = $fails(function () { $GOPS.f(1); });
$export($export.S + $export.F * FAILS_ON_PRIMITIVES, 'Object', {
getOwnPropertySymbols: function getOwnPropertySymbols(it) {
return $GOPS.f(toObject(it));
}
});
// 24.3.2 JSON.stringify(value [, replacer [, space]])
$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () {
var S = $Symbol();
// MS Edge converts symbol values to JSON as {}
// WebKit converts symbol values to JSON as null
// V8 throws on boxed symbols
return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}';
})), 'JSON', {
stringify: function stringify(it) {
var args = [it];
var i = 1;
var replacer, $replacer;
while (arguments.length > i) args.push(arguments[i++]);
$replacer = replacer = args[1];
if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined
if (!isArray(replacer)) replacer = function (key, value) {
if (typeof $replacer == 'function') value = $replacer.call(this, key, value);
if (!isSymbol(value)) return value;
};
args[1] = replacer;
return _stringify.apply($JSON, args);
}
});
// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint)
$Symbol[PROTOTYPE][TO_PRIMITIVE] || require('./_hide')($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);
// 19.4.3.5 Symbol.prototype[@@toStringTag]
setToStringTag($Symbol, 'Symbol');
// 20.2.1.9 Math[@@toStringTag]
setToStringTag(Math, 'Math', true);
// 24.3.3 JSON[@@toStringTag]
setToStringTag(global.JSON, 'JSON', true);
},{"./_an-object":95,"./_descriptors":103,"./_enum-keys":106,"./_export":107,"./_fails":108,"./_global":110,"./_has":111,"./_hide":112,"./_is-array":118,"./_is-object":119,"./_library":126,"./_meta":127,"./_object-create":131,"./_object-dp":132,"./_object-gopd":134,"./_object-gopn":136,"./_object-gopn-ext":135,"./_object-gops":137,"./_object-keys":140,"./_object-pie":141,"./_property-desc":146,"./_redefine":148,"./_set-to-string-tag":150,"./_shared":152,"./_to-iobject":158,"./_to-object":160,"./_to-primitive":161,"./_uid":162,"./_wks":166,"./_wks-define":164,"./_wks-ext":165}],182:[function(require,module,exports){
// https://github.com/tc39/proposal-object-values-entries
var $export = require('./_export');
var $entries = require('./_object-to-array')(true);
$export($export.S, 'Object', {
entries: function entries(it) {
return $entries(it);
}
});
},{"./_export":107,"./_object-to-array":143}],183:[function(require,module,exports){
// https://github.com/tc39/proposal-promise-finally
'use strict';
var $export = require('./_export');
var core = require('./_core');
var global = require('./_global');
var speciesConstructor = require('./_species-constructor');
var promiseResolve = require('./_promise-resolve');
$export($export.P + $export.R, 'Promise', { 'finally': function (onFinally) {
var C = speciesConstructor(this, core.Promise || global.Promise);
var isFunction = typeof onFinally == 'function';
return this.then(
isFunction ? function (x) {
return promiseResolve(C, onFinally()).then(function () { return x; });
} : onFinally,
isFunction ? function (e) {
return promiseResolve(C, onFinally()).then(function () { throw e; });
} : onFinally
);
} });
},{"./_core":99,"./_export":107,"./_global":110,"./_promise-resolve":145,"./_species-constructor":153}],184:[function(require,module,exports){
'use strict';
// https://github.com/tc39/proposal-promise-try
var $export = require('./_export');
var newPromiseCapability = require('./_new-promise-capability');
var perform = require('./_perform');
$export($export.S, 'Promise', { 'try': function (callbackfn) {
var promiseCapability = newPromiseCapability.f(this);
var result = perform(callbackfn);
(result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v);
return promiseCapability.promise;
} });
},{"./_export":107,"./_new-promise-capability":129,"./_perform":144}],185:[function(require,module,exports){
require('./_wks-define')('asyncIterator');
},{"./_wks-define":164}],186:[function(require,module,exports){
require('./_wks-define')('observable');
},{"./_wks-define":164}],187:[function(require,module,exports){
require('./es6.array.iterator');
var global = require('./_global');
var hide = require('./_hide');
var Iterators = require('./_iterators');
var TO_STRING_TAG = require('./_wks')('toStringTag');
var DOMIterables = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' +
'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' +
'MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,' +
'SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,' +
'TextTrackList,TouchList').split(',');
for (var i = 0; i < DOMIterables.length; i++) {
var NAME = DOMIterables[i];
var Collection = global[NAME];
var proto = Collection && Collection.prototype;
if (proto && !proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME);
Iterators[NAME] = Iterators.Array;
}
},{"./_global":110,"./_hide":112,"./_iterators":125,"./_wks":166,"./es6.array.iterator":169}],188:[function(require,module,exports){
var $export = require('./_export');
var $task = require('./_task');
$export($export.G + $export.B, {
setImmediate: $task.set,
clearImmediate: $task.clear
});
},{"./_export":107,"./_task":155}],189:[function(require,module,exports){
(function (Buffer){
'use strict';
var _typeof2 = require('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Copyright Joyent, Inc. and other Node 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.
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(arg) {
if (Array.isArray) {
return Array.isArray(arg);
}
return objectToString(arg) === '[object Array]';
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return (typeof arg === 'undefined' ? 'undefined' : (0, _typeof3.default)(arg)) === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return (typeof arg === 'undefined' ? 'undefined' : (0, _typeof3.default)(arg)) === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return objectToString(e) === '[object Error]' || e instanceof Error;
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || (typeof arg === 'undefined' ? 'undefined' : (0, _typeof3.default)(arg)) === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = Buffer.isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
},{"../../is-buffer/index.js":197,"babel-runtime/helpers/typeof":67}],190:[function(require,module,exports){
'use strict';
var _typeof2 = require('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/*
* Date Format 1.2.3
* (c) 2007-2009 Steven Levithan <stevenlevithan.com>
* MIT license
*
* Includes enhancements by Scott Trenda <scott.trenda.net>
* and Kris Kowal <cixar.com/~kris.kowal/>
*
* Accepts a date, a mask, or a date and a mask.
* Returns a formatted version of the given date.
* The date defaults to the current date/time.
* The mask defaults to dateFormat.masks.default.
*/
(function (global) {
'use strict';
var dateFormat = function () {
var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZWN]|'[^']*'|'[^']*'/g;
var timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g;
var timezoneClip = /[^-+\dA-Z]/g;
// Regexes and supporting functions are cached through closure
return function (date, mask, utc, gmt) {
// You can't provide utc if you skip other args (use the 'UTC:' mask prefix)
if (arguments.length === 1 && kindOf(date) === 'string' && !/\d/.test(date)) {
mask = date;
date = undefined;
}
date = date || new Date();
if (!(date instanceof Date)) {
date = new Date(date);
}
if (isNaN(date)) {
throw TypeError('Invalid date');
}
mask = String(dateFormat.masks[mask] || mask || dateFormat.masks['default']);
// Allow setting the utc/gmt argument via the mask
var maskSlice = mask.slice(0, 4);
if (maskSlice === 'UTC:' || maskSlice === 'GMT:') {
mask = mask.slice(4);
utc = true;
if (maskSlice === 'GMT:') {
gmt = true;
}
}
var _ = utc ? 'getUTC' : 'get';
var d = date[_ + 'Date']();
var D = date[_ + 'Day']();
var m = date[_ + 'Month']();
var y = date[_ + 'FullYear']();
var H = date[_ + 'Hours']();
var M = date[_ + 'Minutes']();
var s = date[_ + 'Seconds']();
var L = date[_ + 'Milliseconds']();
var o = utc ? 0 : date.getTimezoneOffset();
var W = getWeek(date);
var N = getDayOfWeek(date);
var flags = {
d: d,
dd: pad(d),
ddd: dateFormat.i18n.dayNames[D],
dddd: dateFormat.i18n.dayNames[D + 7],
m: m + 1,
mm: pad(m + 1),
mmm: dateFormat.i18n.monthNames[m],
mmmm: dateFormat.i18n.monthNames[m + 12],
yy: String(y).slice(2),
yyyy: y,
h: H % 12 || 12,
hh: pad(H % 12 || 12),
H: H,
HH: pad(H),
M: M,
MM: pad(M),
s: s,
ss: pad(s),
l: pad(L, 3),
L: pad(Math.round(L / 10)),
t: H < 12 ? 'a' : 'p',
tt: H < 12 ? 'am' : 'pm',
T: H < 12 ? 'A' : 'P',
TT: H < 12 ? 'AM' : 'PM',
Z: gmt ? 'GMT' : utc ? 'UTC' : (String(date).match(timezone) || ['']).pop().replace(timezoneClip, ''),
o: (o > 0 ? '-' : '+') + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
S: ['th', 'st', 'nd', 'rd'][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10],
W: W,
N: N
};
return mask.replace(token, function (match) {
if (match in flags) {
return flags[match];
}
return match.slice(1, match.length - 1);
});
};
}();
dateFormat.masks = {
'default': 'ddd mmm dd yyyy HH:MM:ss',
'shortDate': 'm/d/yy',
'mediumDate': 'mmm d, yyyy',
'longDate': 'mmmm d, yyyy',
'fullDate': 'dddd, mmmm d, yyyy',
'shortTime': 'h:MM TT',
'mediumTime': 'h:MM:ss TT',
'longTime': 'h:MM:ss TT Z',
'isoDate': 'yyyy-mm-dd',
'isoTime': 'HH:MM:ss',
'isoDateTime': 'yyyy-mm-dd\'T\'HH:MM:sso',
'isoUtcDateTime': 'UTC:yyyy-mm-dd\'T\'HH:MM:ss\'Z\'',
'expiresHeaderFormat': 'ddd, dd mmm yyyy HH:MM:ss Z'
};
// Internationalization strings
dateFormat.i18n = {
dayNames: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
monthNames: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
};
function pad(val, len) {
val = String(val);
len = len || 2;
while (val.length < len) {
val = '0' + val;
}
return val;
}
/**
* Get the ISO 8601 week number
* Based on comments from
* http://techblog.procurios.nl/k/n618/news/view/33796/14863/Calculate-ISO-8601-week-and-year-in-javascript.html
*
* @param {Object} `date`
* @return {Number}
*/
function getWeek(date) {
// Remove time components of date
var targetThursday = new Date(date.getFullYear(), date.getMonth(), date.getDate());
// Change date to Thursday same week
targetThursday.setDate(targetThursday.getDate() - (targetThursday.getDay() + 6) % 7 + 3);
// Take January 4th as it is always in week 1 (see ISO 8601)
var firstThursday = new Date(targetThursday.getFullYear(), 0, 4);
// Change date to Thursday same week
firstThursday.setDate(firstThursday.getDate() - (firstThursday.getDay() + 6) % 7 + 3);
// Check if daylight-saving-time-switch occurred and correct for it
var ds = targetThursday.getTimezoneOffset() - firstThursday.getTimezoneOffset();
targetThursday.setHours(targetThursday.getHours() - ds);
// Number of weeks between target Thursday and first Thursday
var weekDiff = (targetThursday - firstThursday) / (86400000 * 7);
return 1 + Math.floor(weekDiff);
}
/**
* Get ISO-8601 numeric representation of the day of the week
* 1 (for Monday) through 7 (for Sunday)
*
* @param {Object} `date`
* @return {Number}
*/
function getDayOfWeek(date) {
var dow = date.getDay();
if (dow === 0) {
dow = 7;
}
return dow;
}
/**
* kind-of shortcut
* @param {*} val
* @return {String}
*/
function kindOf(val) {
if (val === null) {
return 'null';
}
if (val === undefined) {
return 'undefined';
}
if ((typeof val === 'undefined' ? 'undefined' : (0, _typeof3.default)(val)) !== 'object') {
return typeof val === 'undefined' ? 'undefined' : (0, _typeof3.default)(val);
}
if (Array.isArray(val)) {
return 'array';
}
return {}.toString.call(val).slice(8, -1).toLowerCase();
};
if (typeof define === 'function' && define.amd) {
define(function () {
return dateFormat;
});
} else if ((typeof exports === 'undefined' ? 'undefined' : (0, _typeof3.default)(exports)) === 'object') {
module.exports = dateFormat;
} else {
global.dateFormat = dateFormat;
}
})(undefined);
},{"babel-runtime/helpers/typeof":67}],191:[function(require,module,exports){
/*!
* escape-html
* Copyright(c) 2012-2013 TJ Holowaychuk
* Copyright(c) 2015 Andreas Lubbe
* Copyright(c) 2015 Tiancheng "Timothy" Gu
* MIT Licensed
*/
'use strict';
/**
* Module variables.
* @private
*/
var matchHtmlRegExp = /["'&<>]/;
/**
* Module exports.
* @public
*/
module.exports = escapeHtml;
/**
* Escape special characters in the given string of html.
*
* @param {string} string The string to escape for inserting into HTML
* @return {string}
* @public
*/
function escapeHtml(string) {
var str = '' + string;
var match = matchHtmlRegExp.exec(str);
if (!match) {
return str;
}
var escape;
var html = '';
var index = 0;
var lastIndex = 0;
for (index = match.index; index < str.length; index++) {
switch (str.charCodeAt(index)) {
case 34: // "
escape = '&quot;';
break;
case 38: // &
escape = '&amp;';
break;
case 39: // '
escape = '&#39;';
break;
case 60: // <
escape = '&lt;';
break;
case 62: // >
escape = '&gt;';
break;
default:
continue;
}
if (lastIndex !== index) {
html += str.substring(lastIndex, index);
}
lastIndex = index + 1;
html += escape;
}
return lastIndex !== index
? html + str.substring(lastIndex, index)
: html;
}
},{}],192:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node 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 EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],193:[function(require,module,exports){
var http = require('http');
var https = module.exports;
for (var key in http) {
if (http.hasOwnProperty(key)) https[key] = http[key];
};
https.request = function (params, cb) {
if (!params) params = {};
params.scheme = 'https';
params.protocol = 'https:';
return http.request.call(this, params, cb);
}
},{"http":231}],194:[function(require,module,exports){
/*!
* humanize-ms - index.js
* Copyright(c) 2014 dead_horse <dead_horse@qq.com>
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
*/
var util = require('util');
var ms = require('ms');
module.exports = function (t) {
if (typeof t === 'number') return t;
var r = ms(t);
if (r === undefined) {
var err = new Error(util.format('humanize-ms(%j) result undefined', t));
console.warn(err.stack);
}
return r;
};
},{"ms":204,"util":243}],195:[function(require,module,exports){
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m
var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var nBits = -7
var i = isLE ? (nBytes - 1) : 0
var d = isLE ? -1 : 1
var s = buffer[offset + i]
i += d
e = s & ((1 << (-nBits)) - 1)
s >>= (-nBits)
nBits += eLen
for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1)
e >>= (-nBits)
nBits += mLen
for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity)
} else {
m = m + Math.pow(2, mLen)
e = e - eBias
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c
var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
var i = isLE ? 0 : (nBytes - 1)
var d = isLE ? 1 : -1
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
value = Math.abs(value)
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0
e = eMax
} else {
e = Math.floor(Math.log(value) / Math.LN2)
if (value * (c = Math.pow(2, -e)) < 1) {
e--
c *= 2
}
if (e + eBias >= 1) {
value += rt / c
} else {
value += rt * Math.pow(2, 1 - eBias)
}
if (value * c >= 2) {
e++
c /= 2
}
if (e + eBias >= eMax) {
m = 0
e = eMax
} else if (e + eBias >= 1) {
m = ((value * c) - 1) * Math.pow(2, mLen)
e = e + eBias
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
e = 0
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m
eLen += mLen
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128
}
},{}],196:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
})
}
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
}
},{}],197:[function(require,module,exports){
/*!
* Determine if an object is a Buffer
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
// The _isBuffer check is for Safari 5-7 support, because it's missing
// Object.prototype.constructor. Remove this eventually
module.exports = function (obj) {
return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
}
function isBuffer (obj) {
return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
}
// For Node v0.10 support. Remove this eventually.
function isSlowBuffer (obj) {
return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
}
},{}],198:[function(require,module,exports){
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
},{}],199:[function(require,module,exports){
(function (global){
/*
* base64.js
*
* Licensed under the BSD 3-Clause License.
* http://opensource.org/licenses/BSD-3-Clause
*
* References:
* http://en.wikipedia.org/wiki/Base64
*/
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
? module.exports = factory(global)
: typeof define === 'function' && define.amd
? define(factory) : factory(global)
}((
typeof self !== 'undefined' ? self
: typeof window !== 'undefined' ? window
: typeof global !== 'undefined' ? global
: this
), function(global) {
'use strict';
// existing version for noConflict()
global = global || {};
var _Base64 = global.Base64;
var version = "2.5.2";
// if node.js and NOT React Native, we use Buffer
var buffer;
if (typeof module !== 'undefined' && module.exports) {
try {
buffer = eval("require('buffer').Buffer");
} catch (err) {
buffer = undefined;
}
}
// constants
var b64chars
= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var b64tab = function(bin) {
var t = {};
for (var i = 0, l = bin.length; i < l; i++) t[bin.charAt(i)] = i;
return t;
}(b64chars);
var fromCharCode = String.fromCharCode;
// encoder stuff
var cb_utob = function(c) {
if (c.length < 2) {
var cc = c.charCodeAt(0);
return cc < 0x80 ? c
: cc < 0x800 ? (fromCharCode(0xc0 | (cc >>> 6))
+ fromCharCode(0x80 | (cc & 0x3f)))
: (fromCharCode(0xe0 | ((cc >>> 12) & 0x0f))
+ fromCharCode(0x80 | ((cc >>> 6) & 0x3f))
+ fromCharCode(0x80 | ( cc & 0x3f)));
} else {
var cc = 0x10000
+ (c.charCodeAt(0) - 0xD800) * 0x400
+ (c.charCodeAt(1) - 0xDC00);
return (fromCharCode(0xf0 | ((cc >>> 18) & 0x07))
+ fromCharCode(0x80 | ((cc >>> 12) & 0x3f))
+ fromCharCode(0x80 | ((cc >>> 6) & 0x3f))
+ fromCharCode(0x80 | ( cc & 0x3f)));
}
};
var re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g;
var utob = function(u) {
return u.replace(re_utob, cb_utob);
};
var cb_encode = function(ccc) {
var padlen = [0, 2, 1][ccc.length % 3],
ord = ccc.charCodeAt(0) << 16
| ((ccc.length > 1 ? ccc.charCodeAt(1) : 0) << 8)
| ((ccc.length > 2 ? ccc.charCodeAt(2) : 0)),
chars = [
b64chars.charAt( ord >>> 18),
b64chars.charAt((ord >>> 12) & 63),
padlen >= 2 ? '=' : b64chars.charAt((ord >>> 6) & 63),
padlen >= 1 ? '=' : b64chars.charAt(ord & 63)
];
return chars.join('');
};
var btoa = global.btoa ? function(b) {
return global.btoa(b);
} : function(b) {
return b.replace(/[\s\S]{1,3}/g, cb_encode);
};
var _encode = function(u) {
var isUint8Array = Object.prototype.toString.call(u) === '[object Uint8Array]';
return isUint8Array ? u.toString('base64')
: btoa(utob(String(u)));
}
var encode = function(u, urisafe) {
return !urisafe
? _encode(u)
: _encode(String(u)).replace(/[+\/]/g, function(m0) {
return m0 == '+' ? '-' : '_';
}).replace(/=/g, '');
};
var encodeURI = function(u) { return encode(u, true) };
// decoder stuff
var re_btou = /[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g;
var cb_btou = function(cccc) {
switch(cccc.length) {
case 4:
var cp = ((0x07 & cccc.charCodeAt(0)) << 18)
| ((0x3f & cccc.charCodeAt(1)) << 12)
| ((0x3f & cccc.charCodeAt(2)) << 6)
| (0x3f & cccc.charCodeAt(3)),
offset = cp - 0x10000;
return (fromCharCode((offset >>> 10) + 0xD800)
+ fromCharCode((offset & 0x3FF) + 0xDC00));
case 3:
return fromCharCode(
((0x0f & cccc.charCodeAt(0)) << 12)
| ((0x3f & cccc.charCodeAt(1)) << 6)
| (0x3f & cccc.charCodeAt(2))
);
default:
return fromCharCode(
((0x1f & cccc.charCodeAt(0)) << 6)
| (0x3f & cccc.charCodeAt(1))
);
}
};
var btou = function(b) {
return b.replace(re_btou, cb_btou);
};
var cb_decode = function(cccc) {
var len = cccc.length,
padlen = len % 4,
n = (len > 0 ? b64tab[cccc.charAt(0)] << 18 : 0)
| (len > 1 ? b64tab[cccc.charAt(1)] << 12 : 0)
| (len > 2 ? b64tab[cccc.charAt(2)] << 6 : 0)
| (len > 3 ? b64tab[cccc.charAt(3)] : 0),
chars = [
fromCharCode( n >>> 16),
fromCharCode((n >>> 8) & 0xff),
fromCharCode( n & 0xff)
];
chars.length -= [0, 0, 2, 1][padlen];
return chars.join('');
};
var _atob = global.atob ? function(a) {
return global.atob(a);
} : function(a){
return a.replace(/\S{1,4}/g, cb_decode);
};
var atob = function(a) {
return _atob(String(a).replace(/[^A-Za-z0-9\+\/]/g, ''));
};
var _decode = buffer ?
buffer.from && Uint8Array && buffer.from !== Uint8Array.from
? function(a) {
return (a.constructor === buffer.constructor
? a : buffer.from(a, 'base64')).toString();
}
: function(a) {
return (a.constructor === buffer.constructor
? a : new buffer(a, 'base64')).toString();
}
: function(a) { return btou(_atob(a)) };
var decode = function(a){
return _decode(
String(a).replace(/[-_]/g, function(m0) { return m0 == '-' ? '+' : '/' })
.replace(/[^A-Za-z0-9\+\/]/g, '')
);
};
var noConflict = function() {
var Base64 = global.Base64;
global.Base64 = _Base64;
return Base64;
};
// export Base64
global.Base64 = {
VERSION: version,
atob: atob,
btoa: btoa,
fromBase64: decode,
toBase64: encode,
utob: utob,
encode: encode,
encodeURI: encodeURI,
btou: btou,
decode: decode,
noConflict: noConflict,
__buffer__: buffer
};
// if ES5 is available, make Base64.extendString() available
if (typeof Object.defineProperty === 'function') {
var noEnum = function(v){
return {value:v,enumerable:false,writable:true,configurable:true};
};
global.Base64.extendString = function () {
Object.defineProperty(
String.prototype, 'fromBase64', noEnum(function () {
return decode(this)
}));
Object.defineProperty(
String.prototype, 'toBase64', noEnum(function (urisafe) {
return encode(this, urisafe)
}));
Object.defineProperty(
String.prototype, 'toBase64URI', noEnum(function () {
return encode(this, true)
}));
};
}
//
// export Base64 to the namespace
//
if (global['Meteor']) { // Meteor.js
Base64 = global.Base64;
}
// module.exports and AMD are mutually exclusive.
// module.exports has precedence.
if (typeof module !== 'undefined' && module.exports) {
module.exports.Base64 = global.Base64;
}
else if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([], function(){ return global.Base64 });
}
// that's it!
return {Base64: global.Base64}
}));
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],200:[function(require,module,exports){
/*!
* merge-descriptors
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module exports.
* @public
*/
module.exports = merge
/**
* Module variables.
* @private
*/
var hasOwnProperty = Object.prototype.hasOwnProperty
/**
* Merge the property descriptors of `src` into `dest`
*
* @param {object} dest Object to add descriptors to
* @param {object} src Object to clone descriptors from
* @param {boolean} [redefine=true] Redefine `dest` properties with `src` properties
* @returns {object} Reference to dest
* @public
*/
function merge(dest, src, redefine) {
if (!dest) {
throw new TypeError('argument dest is required')
}
if (!src) {
throw new TypeError('argument src is required')
}
if (redefine === undefined) {
// Default to true
redefine = true
}
Object.getOwnPropertyNames(src).forEach(function forEachOwnPropertyName(name) {
if (!redefine && hasOwnProperty.call(dest, name)) {
// Skip desriptor
return
}
// Copy descriptor
var descriptor = Object.getOwnPropertyDescriptor(src, name)
Object.defineProperty(dest, name, descriptor)
})
return dest
}
},{}],201:[function(require,module,exports){
'use strict';
/**
* @param typeMap [Object] Map of MIME type -> Array[extensions]
* @param ...
*/
function Mime() {
this._types = Object.create(null);
this._extensions = Object.create(null);
for (var i = 0; i < arguments.length; i++) {
this.define(arguments[i]);
}
this.define = this.define.bind(this);
this.getType = this.getType.bind(this);
this.getExtension = this.getExtension.bind(this);
}
/**
* Define mimetype -> extension mappings. Each key is a mime-type that maps
* to an array of extensions associated with the type. The first extension is
* used as the default extension for the type.
*
* e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});
*
* If a type declares an extension that has already been defined, an error will
* be thrown. To suppress this error and force the extension to be associated
* with the new type, pass `force`=true. Alternatively, you may prefix the
* extension with "*" to map the type to extension, without mapping the
* extension to the type.
*
* e.g. mime.define({'audio/wav', ['wav']}, {'audio/x-wav', ['*wav']});
*
*
* @param map (Object) type definitions
* @param force (Boolean) if true, force overriding of existing definitions
*/
Mime.prototype.define = function(typeMap, force) {
for (var type in typeMap) {
var extensions = typeMap[type].map(function(t) {return t.toLowerCase()});
type = type.toLowerCase();
for (var i = 0; i < extensions.length; i++) {
var ext = extensions[i];
// '*' prefix = not the preferred type for this extension. So fixup the
// extension, and skip it.
if (ext[0] == '*') {
continue;
}
if (!force && (ext in this._types)) {
throw new Error(
'Attempt to change mapping for "' + ext +
'" extension from "' + this._types[ext] + '" to "' + type +
'". Pass `force=true` to allow this, otherwise remove "' + ext +
'" from the list of extensions for "' + type + '".'
);
}
this._types[ext] = type;
}
// Use first extension as default
if (force || !this._extensions[type]) {
var ext = extensions[0];
this._extensions[type] = (ext[0] != '*') ? ext : ext.substr(1)
}
}
};
/**
* Lookup a mime type based on extension
*/
Mime.prototype.getType = function(path) {
path = String(path);
var last = path.replace(/^.*[/\\]/, '').toLowerCase();
var ext = last.replace(/^.*\./, '').toLowerCase();
var hasPath = last.length < path.length;
var hasDot = ext.length < last.length - 1;
return (hasDot || !hasPath) && this._types[ext] || null;
};
/**
* Return file extension associated with a mime type
*/
Mime.prototype.getExtension = function(type) {
type = /^\s*([^;\s]*)/.test(type) && RegExp.$1;
return type && this._extensions[type.toLowerCase()] || null;
};
module.exports = Mime;
},{}],202:[function(require,module,exports){
'use strict';
var Mime = require('./Mime');
module.exports = new Mime(require('./types/standard'));
},{"./Mime":201,"./types/standard":203}],203:[function(require,module,exports){
module.exports = {"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma","es"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/mrb-consumer+xml":["*xdf"],"application/mrb-publish+xml":["*xdf"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["*xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/ttml+xml":["ttml"],"application/urc-ressheet+xml":["rsheet"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-error+xml":["xer"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/adpcm":["adp"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/stl":["stl"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]};
},{}],204:[function(require,module,exports){
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var w = d * 7;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} [options]
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function(val, options) {
options = options || {};
var type = typeof val;
if (type === 'string' && val.length > 0) {
return parse(val);
} else if (type === 'number' && isFinite(val)) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
'val is not a non-empty string or a valid number. val=' +
JSON.stringify(val)
);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'weeks':
case 'week':
case 'w':
return n * w;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
return undefined;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return Math.round(ms / d) + 'd';
}
if (msAbs >= h) {
return Math.round(ms / h) + 'h';
}
if (msAbs >= m) {
return Math.round(ms / m) + 'm';
}
if (msAbs >= s) {
return Math.round(ms / s) + 's';
}
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return plural(ms, msAbs, d, 'day');
}
if (msAbs >= h) {
return plural(ms, msAbs, h, 'hour');
}
if (msAbs >= m) {
return plural(ms, msAbs, m, 'minute');
}
if (msAbs >= s) {
return plural(ms, msAbs, s, 'second');
}
return ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, msAbs, n, name) {
var isPlural = msAbs >= n * 1.5;
return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
}
},{}],205:[function(require,module,exports){
(function (process){
// .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,
// backported and transplited with Babel, with backwards-compat fixes
// Copyright Joyent, Inc. and other Node 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.
// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = parts.length - 1; i >= 0; i--) {
var last = parts[i];
if (last === '.') {
parts.splice(i, 1);
} else if (last === '..') {
parts.splice(i, 1);
up++;
} else if (up) {
parts.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (allowAboveRoot) {
for (; up--; up) {
parts.unshift('..');
}
}
return parts;
}
// path.resolve([from ...], to)
// posix version
exports.resolve = function() {
var resolvedPath = '',
resolvedAbsolute = false;
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path = (i >= 0) ? arguments[i] : process.cwd();
// Skip empty and invalid entries
if (typeof path !== 'string') {
throw new TypeError('Arguments to path.resolve must be strings');
} else if (!path) {
continue;
}
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path.charAt(0) === '/';
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
return !!p;
}), !resolvedAbsolute).join('/');
return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
};
// path.normalize(path)
// posix version
exports.normalize = function(path) {
var isAbsolute = exports.isAbsolute(path),
trailingSlash = substr(path, -1) === '/';
// Normalize the path
path = normalizeArray(filter(path.split('/'), function(p) {
return !!p;
}), !isAbsolute).join('/');
if (!path && !isAbsolute) {
path = '.';
}
if (path && trailingSlash) {
path += '/';
}
return (isAbsolute ? '/' : '') + path;
};
// posix version
exports.isAbsolute = function(path) {
return path.charAt(0) === '/';
};
// posix version
exports.join = function() {
var paths = Array.prototype.slice.call(arguments, 0);
return exports.normalize(filter(paths, function(p, index) {
if (typeof p !== 'string') {
throw new TypeError('Arguments to path.join must be strings');
}
return p;
}).join('/'));
};
// path.relative(from, to)
// posix version
exports.relative = function(from, to) {
from = exports.resolve(from).substr(1);
to = exports.resolve(to).substr(1);
function trim(arr) {
var start = 0;
for (; start < arr.length; start++) {
if (arr[start] !== '') break;
}
var end = arr.length - 1;
for (; end >= 0; end--) {
if (arr[end] !== '') break;
}
if (start > end) return [];
return arr.slice(start, end - start + 1);
}
var fromParts = trim(from.split('/'));
var toParts = trim(to.split('/'));
var length = Math.min(fromParts.length, toParts.length);
var samePartsLength = length;
for (var i = 0; i < length; i++) {
if (fromParts[i] !== toParts[i]) {
samePartsLength = i;
break;
}
}
var outputParts = [];
for (var i = samePartsLength; i < fromParts.length; i++) {
outputParts.push('..');
}
outputParts = outputParts.concat(toParts.slice(samePartsLength));
return outputParts.join('/');
};
exports.sep = '/';
exports.delimiter = ':';
exports.dirname = function (path) {
if (typeof path !== 'string') path = path + '';
if (path.length === 0) return '.';
var code = path.charCodeAt(0);
var hasRoot = code === 47 /*/*/;
var end = -1;
var matchedSlash = true;
for (var i = path.length - 1; i >= 1; --i) {
code = path.charCodeAt(i);
if (code === 47 /*/*/) {
if (!matchedSlash) {
end = i;
break;
}
} else {
// We saw the first non-path separator
matchedSlash = false;
}
}
if (end === -1) return hasRoot ? '/' : '.';
if (hasRoot && end === 1) {
// return '//';
// Backwards-compat fix:
return '/';
}
return path.slice(0, end);
};
function basename(path) {
if (typeof path !== 'string') path = path + '';
var start = 0;
var end = -1;
var matchedSlash = true;
var i;
for (i = path.length - 1; i >= 0; --i) {
if (path.charCodeAt(i) === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
start = i + 1;
break;
}
} else if (end === -1) {
// We saw the first non-path separator, mark this as the end of our
// path component
matchedSlash = false;
end = i + 1;
}
}
if (end === -1) return '';
return path.slice(start, end);
}
// Uses a mixed approach for backwards-compatibility, as ext behavior changed
// in new Node.js versions, so only basename() above is backported here
exports.basename = function (path, ext) {
var f = basename(path);
if (ext && f.substr(-1 * ext.length) === ext) {
f = f.substr(0, f.length - ext.length);
}
return f;
};
exports.extname = function (path) {
if (typeof path !== 'string') path = path + '';
var startDot = -1;
var startPart = 0;
var end = -1;
var matchedSlash = true;
// Track the state of characters (if any) we see before our first dot and
// after any path separator we find
var preDotState = 0;
for (var i = path.length - 1; i >= 0; --i) {
var code = path.charCodeAt(i);
if (code === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
startPart = i + 1;
break;
}
continue;
}
if (end === -1) {
// We saw the first non-path separator, mark this as the end of our
// extension
matchedSlash = false;
end = i + 1;
}
if (code === 46 /*.*/) {
// If this is our first dot, mark it as the start of our extension
if (startDot === -1)
startDot = i;
else if (preDotState !== 1)
preDotState = 1;
} else if (startDot !== -1) {
// We saw a non-dot and non-path separator before our dot, so we should
// have a good chance at having a non-empty extension
preDotState = -1;
}
}
if (startDot === -1 || end === -1 ||
// We saw a non-dot character immediately before the dot
preDotState === 0 ||
// The (right-most) trimmed path component is exactly '..'
preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
return '';
}
return path.slice(startDot, end);
};
function filter (xs, f) {
if (xs.filter) return xs.filter(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
if (f(xs[i], i, xs)) res.push(xs[i]);
}
return res;
}
// String.prototype.substr - negative index don't work in IE8
var substr = 'ab'.substr(-1) === 'b'
? function (str, start, len) { return str.substr(start, len) }
: function (str, start, len) {
if (start < 0) start = str.length + start;
return str.substr(start, len);
}
;
}).call(this,require('_process'))
},{"_process":208}],206:[function(require,module,exports){
(function (global){
/*!
* Platform.js <https://mths.be/platform>
* Copyright 2014-2018 Benjamin Tan <https://bnjmnt4n.now.sh/>
* Copyright 2011-2013 John-David Dalton <http://allyoucanleet.com/>
* Available under MIT license <https://mths.be/mit>
*/
;(function() {
'use strict';
/** Used to determine if values are of the language type `Object`. */
var objectTypes = {
'function': true,
'object': true
};
/** Used as a reference to the global object. */
var root = (objectTypes[typeof window] && window) || this;
/** Backup possible global object. */
var oldRoot = root;
/** Detect free variable `exports`. */
var freeExports = objectTypes[typeof exports] && exports;
/** Detect free variable `module`. */
var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;
/** Detect free variable `global` from Node.js or Browserified code and use it as `root`. */
var freeGlobal = freeExports && freeModule && typeof global == 'object' && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal)) {
root = freeGlobal;
}
/**
* Used as the maximum length of an array-like object.
* See the [ES6 spec](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength)
* for more details.
*/
var maxSafeInteger = Math.pow(2, 53) - 1;
/** Regular expression to detect Opera. */
var reOpera = /\bOpera/;
/** Possible global object. */
var thisBinding = this;
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check for own properties of an object. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to resolve the internal `[[Class]]` of values. */
var toString = objectProto.toString;
/*--------------------------------------------------------------------------*/
/**
* Capitalizes a string value.
*
* @private
* @param {string} string The string to capitalize.
* @returns {string} The capitalized string.
*/
function capitalize(string) {
string = String(string);
return string.charAt(0).toUpperCase() + string.slice(1);
}
/**
* A utility function to clean up the OS name.
*
* @private
* @param {string} os The OS name to clean up.
* @param {string} [pattern] A `RegExp` pattern matching the OS name.
* @param {string} [label] A label for the OS.
*/
function cleanupOS(os, pattern, label) {
// Platform tokens are defined at:
// http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx
// http://web.archive.org/web/20081122053950/http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx
var data = {
'10.0': '10',
'6.4': '10 Technical Preview',
'6.3': '8.1',
'6.2': '8',
'6.1': 'Server 2008 R2 / 7',
'6.0': 'Server 2008 / Vista',
'5.2': 'Server 2003 / XP 64-bit',
'5.1': 'XP',
'5.01': '2000 SP1',
'5.0': '2000',
'4.0': 'NT',
'4.90': 'ME'
};
// Detect Windows version from platform tokens.
if (pattern && label && /^Win/i.test(os) && !/^Windows Phone /i.test(os) &&
(data = data[/[\d.]+$/.exec(os)])) {
os = 'Windows ' + data;
}
// Correct character case and cleanup string.
os = String(os);
if (pattern && label) {
os = os.replace(RegExp(pattern, 'i'), label);
}
os = format(
os.replace(/ ce$/i, ' CE')
.replace(/\bhpw/i, 'web')
.replace(/\bMacintosh\b/, 'Mac OS')
.replace(/_PowerPC\b/i, ' OS')
.replace(/\b(OS X) [^ \d]+/i, '$1')
.replace(/\bMac (OS X)\b/, '$1')
.replace(/\/(\d)/, ' $1')
.replace(/_/g, '.')
.replace(/(?: BePC|[ .]*fc[ \d.]+)$/i, '')
.replace(/\bx86\.64\b/gi, 'x86_64')
.replace(/\b(Windows Phone) OS\b/, '$1')
.replace(/\b(Chrome OS \w+) [\d.]+\b/, '$1')
.split(' on ')[0]
);
return os;
}
/**
* An iteration utility for arrays and objects.
*
* @private
* @param {Array|Object} object The object to iterate over.
* @param {Function} callback The function called per iteration.
*/
function each(object, callback) {
var index = -1,
length = object ? object.length : 0;
if (typeof length == 'number' && length > -1 && length <= maxSafeInteger) {
while (++index < length) {
callback(object[index], index, object);
}
} else {
forOwn(object, callback);
}
}
/**
* Trim and conditionally capitalize string values.
*
* @private
* @param {string} string The string to format.
* @returns {string} The formatted string.
*/
function format(string) {
string = trim(string);
return /^(?:webOS|i(?:OS|P))/.test(string)
? string
: capitalize(string);
}
/**
* Iterates over an object's own properties, executing the `callback` for each.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} callback The function executed per own property.
*/
function forOwn(object, callback) {
for (var key in object) {
if (hasOwnProperty.call(object, key)) {
callback(object[key], key, object);
}
}
}
/**
* Gets the internal `[[Class]]` of a value.
*
* @private
* @param {*} value The value.
* @returns {string} The `[[Class]]`.
*/
function getClassOf(value) {
return value == null
? capitalize(value)
: toString.call(value).slice(8, -1);
}
/**
* Host objects can return type values that are different from their actual
* data type. The objects we are concerned with usually return non-primitive
* types of "object", "function", or "unknown".
*
* @private
* @param {*} object The owner of the property.
* @param {string} property The property to check.
* @returns {boolean} Returns `true` if the property value is a non-primitive, else `false`.
*/
function isHostType(object, property) {
var type = object != null ? typeof object[property] : 'number';
return !/^(?:boolean|number|string|undefined)$/.test(type) &&
(type == 'object' ? !!object[property] : true);
}
/**
* Prepares a string for use in a `RegExp` by making hyphens and spaces optional.
*
* @private
* @param {string} string The string to qualify.
* @returns {string} The qualified string.
*/
function qualify(string) {
return String(string).replace(/([ -])(?!$)/g, '$1?');
}
/**
* A bare-bones `Array#reduce` like utility function.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function called per iteration.
* @returns {*} The accumulated result.
*/
function reduce(array, callback) {
var accumulator = null;
each(array, function(value, index) {
accumulator = callback(accumulator, value, index, array);
});
return accumulator;
}
/**
* Removes leading and trailing whitespace from a string.
*
* @private
* @param {string} string The string to trim.
* @returns {string} The trimmed string.
*/
function trim(string) {
return String(string).replace(/^ +| +$/g, '');
}
/*--------------------------------------------------------------------------*/
/**
* Creates a new platform object.
*
* @memberOf platform
* @param {Object|string} [ua=navigator.userAgent] The user agent string or
* context object.
* @returns {Object} A platform object.
*/
function parse(ua) {
/** The environment context object. */
var context = root;
/** Used to flag when a custom context is provided. */
var isCustomContext = ua && typeof ua == 'object' && getClassOf(ua) != 'String';
// Juggle arguments.
if (isCustomContext) {
context = ua;
ua = null;
}
/** Browser navigator object. */
var nav = context.navigator || {};
/** Browser user agent string. */
var userAgent = nav.userAgent || '';
ua || (ua = userAgent);
/** Used to flag when `thisBinding` is the [ModuleScope]. */
var isModuleScope = isCustomContext || thisBinding == oldRoot;
/** Used to detect if browser is like Chrome. */
var likeChrome = isCustomContext
? !!nav.likeChrome
: /\bChrome\b/.test(ua) && !/internal|\n/i.test(toString.toString());
/** Internal `[[Class]]` value shortcuts. */
var objectClass = 'Object',
airRuntimeClass = isCustomContext ? objectClass : 'ScriptBridgingProxyObject',
enviroClass = isCustomContext ? objectClass : 'Environment',
javaClass = (isCustomContext && context.java) ? 'JavaPackage' : getClassOf(context.java),
phantomClass = isCustomContext ? objectClass : 'RuntimeObject';
/** Detect Java environments. */
var java = /\bJava/.test(javaClass) && context.java;
/** Detect Rhino. */
var rhino = java && getClassOf(context.environment) == enviroClass;
/** A character to represent alpha. */
var alpha = java ? 'a' : '\u03b1';
/** A character to represent beta. */
var beta = java ? 'b' : '\u03b2';
/** Browser document object. */
var doc = context.document || {};
/**
* Detect Opera browser (Presto-based).
* http://www.howtocreate.co.uk/operaStuff/operaObject.html
* http://dev.opera.com/articles/view/opera-mini-web-content-authoring-guidelines/#operamini
*/
var opera = context.operamini || context.opera;
/** Opera `[[Class]]`. */
var operaClass = reOpera.test(operaClass = (isCustomContext && opera) ? opera['[[Class]]'] : getClassOf(opera))
? operaClass
: (opera = null);
/*------------------------------------------------------------------------*/
/** Temporary variable used over the script's lifetime. */
var data;
/** The CPU architecture. */
var arch = ua;
/** Platform description array. */
var description = [];
/** Platform alpha/beta indicator. */
var prerelease = null;
/** A flag to indicate that environment features should be used to resolve the platform. */
var useFeatures = ua == userAgent;
/** The browser/environment version. */
var version = useFeatures && opera && typeof opera.version == 'function' && opera.version();
/** A flag to indicate if the OS ends with "/ Version" */
var isSpecialCasedOS;
/* Detectable layout engines (order is important). */
var layout = getLayout([
{ 'label': 'EdgeHTML', 'pattern': 'Edge' },
'Trident',
{ 'label': 'WebKit', 'pattern': 'AppleWebKit' },
'iCab',
'Presto',
'NetFront',
'Tasman',
'KHTML',
'Gecko'
]);
/* Detectable browser names (order is important). */
var name = getName([
'Adobe AIR',
'Arora',
'Avant Browser',
'Breach',
'Camino',
'Electron',
'Epiphany',
'Fennec',
'Flock',
'Galeon',
'GreenBrowser',
'iCab',
'Iceweasel',
'K-Meleon',
'Konqueror',
'Lunascape',
'Maxthon',
{ 'label': 'Microsoft Edge', 'pattern': 'Edge' },
'Midori',
'Nook Browser',
'PaleMoon',
'PhantomJS',
'Raven',
'Rekonq',
'RockMelt',
{ 'label': 'Samsung Internet', 'pattern': 'SamsungBrowser' },
'SeaMonkey',
{ 'label': 'Silk', 'pattern': '(?:Cloud9|Silk-Accelerated)' },
'Sleipnir',
'SlimBrowser',
{ 'label': 'SRWare Iron', 'pattern': 'Iron' },
'Sunrise',
'Swiftfox',
'Waterfox',
'WebPositive',
'Opera Mini',
{ 'label': 'Opera Mini', 'pattern': 'OPiOS' },
'Opera',
{ 'label': 'Opera', 'pattern': 'OPR' },
'Chrome',
{ 'label': 'Chrome Mobile', 'pattern': '(?:CriOS|CrMo)' },
{ 'label': 'Firefox', 'pattern': '(?:Firefox|Minefield)' },
{ 'label': 'Firefox for iOS', 'pattern': 'FxiOS' },
{ 'label': 'IE', 'pattern': 'IEMobile' },
{ 'label': 'IE', 'pattern': 'MSIE' },
'Safari'
]);
/* Detectable products (order is important). */
var product = getProduct([
{ 'label': 'BlackBerry', 'pattern': 'BB10' },
'BlackBerry',
{ 'label': 'Galaxy S', 'pattern': 'GT-I9000' },
{ 'label': 'Galaxy S2', 'pattern': 'GT-I9100' },
{ 'label': 'Galaxy S3', 'pattern': 'GT-I9300' },
{ 'label': 'Galaxy S4', 'pattern': 'GT-I9500' },
{ 'label': 'Galaxy S5', 'pattern': 'SM-G900' },
{ 'label': 'Galaxy S6', 'pattern': 'SM-G920' },
{ 'label': 'Galaxy S6 Edge', 'pattern': 'SM-G925' },
{ 'label': 'Galaxy S7', 'pattern': 'SM-G930' },
{ 'label': 'Galaxy S7 Edge', 'pattern': 'SM-G935' },
'Google TV',
'Lumia',
'iPad',
'iPod',
'iPhone',
'Kindle',
{ 'label': 'Kindle Fire', 'pattern': '(?:Cloud9|Silk-Accelerated)' },
'Nexus',
'Nook',
'PlayBook',
'PlayStation Vita',
'PlayStation',
'TouchPad',
'Transformer',
{ 'label': 'Wii U', 'pattern': 'WiiU' },
'Wii',
'Xbox One',
{ 'label': 'Xbox 360', 'pattern': 'Xbox' },
'Xoom'
]);
/* Detectable manufacturers. */
var manufacturer = getManufacturer({
'Apple': { 'iPad': 1, 'iPhone': 1, 'iPod': 1 },
'Archos': {},
'Amazon': { 'Kindle': 1, 'Kindle Fire': 1 },
'Asus': { 'Transformer': 1 },
'Barnes & Noble': { 'Nook': 1 },
'BlackBerry': { 'PlayBook': 1 },
'Google': { 'Google TV': 1, 'Nexus': 1 },
'HP': { 'TouchPad': 1 },
'HTC': {},
'LG': {},
'Microsoft': { 'Xbox': 1, 'Xbox One': 1 },
'Motorola': { 'Xoom': 1 },
'Nintendo': { 'Wii U': 1, 'Wii': 1 },
'Nokia': { 'Lumia': 1 },
'Samsung': { 'Galaxy S': 1, 'Galaxy S2': 1, 'Galaxy S3': 1, 'Galaxy S4': 1 },
'Sony': { 'PlayStation': 1, 'PlayStation Vita': 1 }
});
/* Detectable operating systems (order is important). */
var os = getOS([
'Windows Phone',
'Android',
'CentOS',
{ 'label': 'Chrome OS', 'pattern': 'CrOS' },
'Debian',
'Fedora',
'FreeBSD',
'Gentoo',
'Haiku',
'Kubuntu',
'Linux Mint',
'OpenBSD',
'Red Hat',
'SuSE',
'Ubuntu',
'Xubuntu',
'Cygwin',
'Symbian OS',
'hpwOS',
'webOS ',
'webOS',
'Tablet OS',
'Tizen',
'Linux',
'Mac OS X',
'Macintosh',
'Mac',
'Windows 98;',
'Windows '
]);
/*------------------------------------------------------------------------*/
/**
* Picks the layout engine from an array of guesses.
*
* @private
* @param {Array} guesses An array of guesses.
* @returns {null|string} The detected layout engine.
*/
function getLayout(guesses) {
return reduce(guesses, function(result, guess) {
return result || RegExp('\\b' + (
guess.pattern || qualify(guess)
) + '\\b', 'i').exec(ua) && (guess.label || guess);
});
}
/**
* Picks the manufacturer from an array of guesses.
*
* @private
* @param {Array} guesses An object of guesses.
* @returns {null|string} The detected manufacturer.
*/
function getManufacturer(guesses) {
return reduce(guesses, function(result, value, key) {
// Lookup the manufacturer by product or scan the UA for the manufacturer.
return result || (
value[product] ||
value[/^[a-z]+(?: +[a-z]+\b)*/i.exec(product)] ||
RegExp('\\b' + qualify(key) + '(?:\\b|\\w*\\d)', 'i').exec(ua)
) && key;
});
}
/**
* Picks the browser name from an array of guesses.
*
* @private
* @param {Array} guesses An array of guesses.
* @returns {null|string} The detected browser name.
*/
function getName(guesses) {
return reduce(guesses, function(result, guess) {
return result || RegExp('\\b' + (
guess.pattern || qualify(guess)
) + '\\b', 'i').exec(ua) && (guess.label || guess);
});
}
/**
* Picks the OS name from an array of guesses.
*
* @private
* @param {Array} guesses An array of guesses.
* @returns {null|string} The detected OS name.
*/
function getOS(guesses) {
return reduce(guesses, function(result, guess) {
var pattern = guess.pattern || qualify(guess);
if (!result && (result =
RegExp('\\b' + pattern + '(?:/[\\d.]+|[ \\w.]*)', 'i').exec(ua)
)) {
result = cleanupOS(result, pattern, guess.label || guess);
}
return result;
});
}
/**
* Picks the product name from an array of guesses.
*
* @private
* @param {Array} guesses An array of guesses.
* @returns {null|string} The detected product name.
*/
function getProduct(guesses) {
return reduce(guesses, function(result, guess) {
var pattern = guess.pattern || qualify(guess);
if (!result && (result =
RegExp('\\b' + pattern + ' *\\d+[.\\w_]*', 'i').exec(ua) ||
RegExp('\\b' + pattern + ' *\\w+-[\\w]*', 'i').exec(ua) ||
RegExp('\\b' + pattern + '(?:; *(?:[a-z]+[_-])?[a-z]+\\d+|[^ ();-]*)', 'i').exec(ua)
)) {
// Split by forward slash and append product version if needed.
if ((result = String((guess.label && !RegExp(pattern, 'i').test(guess.label)) ? guess.label : result).split('/'))[1] && !/[\d.]+/.test(result[0])) {
result[0] += ' ' + result[1];
}
// Correct character case and cleanup string.
guess = guess.label || guess;
result = format(result[0]
.replace(RegExp(pattern, 'i'), guess)
.replace(RegExp('; *(?:' + guess + '[_-])?', 'i'), ' ')
.replace(RegExp('(' + guess + ')[-_.]?(\\w)', 'i'), '$1 $2'));
}
return result;
});
}
/**
* Resolves the version using an array of UA patterns.
*
* @private
* @param {Array} patterns An array of UA patterns.
* @returns {null|string} The detected version.
*/
function getVersion(patterns) {
return reduce(patterns, function(result, pattern) {
return result || (RegExp(pattern +
'(?:-[\\d.]+/|(?: for [\\w-]+)?[ /-])([\\d.]+[^ ();/_-]*)', 'i').exec(ua) || 0)[1] || null;
});
}
/**
* Returns `platform.description` when the platform object is coerced to a string.
*
* @name toString
* @memberOf platform
* @returns {string} Returns `platform.description` if available, else an empty string.
*/
function toStringPlatform() {
return this.description || '';
}
/*------------------------------------------------------------------------*/
// Convert layout to an array so we can add extra details.
layout && (layout = [layout]);
// Detect product names that contain their manufacturer's name.
if (manufacturer && !product) {
product = getProduct([manufacturer]);
}
// Clean up Google TV.
if ((data = /\bGoogle TV\b/.exec(product))) {
product = data[0];
}
// Detect simulators.
if (/\bSimulator\b/i.test(ua)) {
product = (product ? product + ' ' : '') + 'Simulator';
}
// Detect Opera Mini 8+ running in Turbo/Uncompressed mode on iOS.
if (name == 'Opera Mini' && /\bOPiOS\b/.test(ua)) {
description.push('running in Turbo/Uncompressed mode');
}
// Detect IE Mobile 11.
if (name == 'IE' && /\blike iPhone OS\b/.test(ua)) {
data = parse(ua.replace(/like iPhone OS/, ''));
manufacturer = data.manufacturer;
product = data.product;
}
// Detect iOS.
else if (/^iP/.test(product)) {
name || (name = 'Safari');
os = 'iOS' + ((data = / OS ([\d_]+)/i.exec(ua))
? ' ' + data[1].replace(/_/g, '.')
: '');
}
// Detect Kubuntu.
else if (name == 'Konqueror' && !/buntu/i.test(os)) {
os = 'Kubuntu';
}
// Detect Android browsers.
else if ((manufacturer && manufacturer != 'Google' &&
((/Chrome/.test(name) && !/\bMobile Safari\b/i.test(ua)) || /\bVita\b/.test(product))) ||
(/\bAndroid\b/.test(os) && /^Chrome/.test(name) && /\bVersion\//i.test(ua))) {
name = 'Android Browser';
os = /\bAndroid\b/.test(os) ? os : 'Android';
}
// Detect Silk desktop/accelerated modes.
else if (name == 'Silk') {
if (!/\bMobi/i.test(ua)) {
os = 'Android';
description.unshift('desktop mode');
}
if (/Accelerated *= *true/i.test(ua)) {
description.unshift('accelerated');
}
}
// Detect PaleMoon identifying as Firefox.
else if (name == 'PaleMoon' && (data = /\bFirefox\/([\d.]+)\b/.exec(ua))) {
description.push('identifying as Firefox ' + data[1]);
}
// Detect Firefox OS and products running Firefox.
else if (name == 'Firefox' && (data = /\b(Mobile|Tablet|TV)\b/i.exec(ua))) {
os || (os = 'Firefox OS');
product || (product = data[1]);
}
// Detect false positives for Firefox/Safari.
else if (!name || (data = !/\bMinefield\b/i.test(ua) && /\b(?:Firefox|Safari)\b/.exec(name))) {
// Escape the `/` for Firefox 1.
if (name && !product && /[\/,]|^[^(]+?\)/.test(ua.slice(ua.indexOf(data + '/') + 8))) {
// Clear name of false positives.
name = null;
}
// Reassign a generic name.
if ((data = product || manufacturer || os) &&
(product || manufacturer || /\b(?:Android|Symbian OS|Tablet OS|webOS)\b/.test(os))) {
name = /[a-z]+(?: Hat)?/i.exec(/\bAndroid\b/.test(os) ? os : data) + ' Browser';
}
}
// Add Chrome version to description for Electron.
else if (name == 'Electron' && (data = (/\bChrome\/([\d.]+)\b/.exec(ua) || 0)[1])) {
description.push('Chromium ' + data);
}
// Detect non-Opera (Presto-based) versions (order is important).
if (!version) {
version = getVersion([
'(?:Cloud9|CriOS|CrMo|Edge|FxiOS|IEMobile|Iron|Opera ?Mini|OPiOS|OPR|Raven|SamsungBrowser|Silk(?!/[\\d.]+$))',
'Version',
qualify(name),
'(?:Firefox|Minefield|NetFront)'
]);
}
// Detect stubborn layout engines.
if ((data =
layout == 'iCab' && parseFloat(version) > 3 && 'WebKit' ||
/\bOpera\b/.test(name) && (/\bOPR\b/.test(ua) ? 'Blink' : 'Presto') ||
/\b(?:Midori|Nook|Safari)\b/i.test(ua) && !/^(?:Trident|EdgeHTML)$/.test(layout) && 'WebKit' ||
!layout && /\bMSIE\b/i.test(ua) && (os == 'Mac OS' ? 'Tasman' : 'Trident') ||
layout == 'WebKit' && /\bPlayStation\b(?! Vita\b)/i.test(name) && 'NetFront'
)) {
layout = [data];
}
// Detect Windows Phone 7 desktop mode.
if (name == 'IE' && (data = (/; *(?:XBLWP|ZuneWP)(\d+)/i.exec(ua) || 0)[1])) {
name += ' Mobile';
os = 'Windows Phone ' + (/\+$/.test(data) ? data : data + '.x');
description.unshift('desktop mode');
}
// Detect Windows Phone 8.x desktop mode.
else if (/\bWPDesktop\b/i.test(ua)) {
name = 'IE Mobile';
os = 'Windows Phone 8.x';
description.unshift('desktop mode');
version || (version = (/\brv:([\d.]+)/.exec(ua) || 0)[1]);
}
// Detect IE 11 identifying as other browsers.
else if (name != 'IE' && layout == 'Trident' && (data = /\brv:([\d.]+)/.exec(ua))) {
if (name) {
description.push('identifying as ' + name + (version ? ' ' + version : ''));
}
name = 'IE';
version = data[1];
}
// Leverage environment features.
if (useFeatures) {
// Detect server-side environments.
// Rhino has a global function while others have a global object.
if (isHostType(context, 'global')) {
if (java) {
data = java.lang.System;
arch = data.getProperty('os.arch');
os = os || data.getProperty('os.name') + ' ' + data.getProperty('os.version');
}
if (rhino) {
try {
version = context.require('ringo/engine').version.join('.');
name = 'RingoJS';
} catch(e) {
if ((data = context.system) && data.global.system == context.system) {
name = 'Narwhal';
os || (os = data[0].os || null);
}
}
if (!name) {
name = 'Rhino';
}
}
else if (
typeof context.process == 'object' && !context.process.browser &&
(data = context.process)
) {
if (typeof data.versions == 'object') {
if (typeof data.versions.electron == 'string') {
description.push('Node ' + data.versions.node);
name = 'Electron';
version = data.versions.electron;
} else if (typeof data.versions.nw == 'string') {
description.push('Chromium ' + version, 'Node ' + data.versions.node);
name = 'NW.js';
version = data.versions.nw;
}
}
if (!name) {
name = 'Node.js';
arch = data.arch;
os = data.platform;
version = /[\d.]+/.exec(data.version);
version = version ? version[0] : null;
}
}
}
// Detect Adobe AIR.
else if (getClassOf((data = context.runtime)) == airRuntimeClass) {
name = 'Adobe AIR';
os = data.flash.system.Capabilities.os;
}
// Detect PhantomJS.
else if (getClassOf((data = context.phantom)) == phantomClass) {
name = 'PhantomJS';
version = (data = data.version || null) && (data.major + '.' + data.minor + '.' + data.patch);
}
// Detect IE compatibility modes.
else if (typeof doc.documentMode == 'number' && (data = /\bTrident\/(\d+)/i.exec(ua))) {
// We're in compatibility mode when the Trident version + 4 doesn't
// equal the document mode.
version = [version, doc.documentMode];
if ((data = +data[1] + 4) != version[1]) {
description.push('IE ' + version[1] + ' mode');
layout && (layout[1] = '');
version[1] = data;
}
version = name == 'IE' ? String(version[1].toFixed(1)) : version[0];
}
// Detect IE 11 masking as other browsers.
else if (typeof doc.documentMode == 'number' && /^(?:Chrome|Firefox)\b/.test(name)) {
description.push('masking as ' + name + ' ' + version);
name = 'IE';
version = '11.0';
layout = ['Trident'];
os = 'Windows';
}
os = os && format(os);
}
// Detect prerelease phases.
if (version && (data =
/(?:[ab]|dp|pre|[ab]\d+pre)(?:\d+\+?)?$/i.exec(version) ||
/(?:alpha|beta)(?: ?\d)?/i.exec(ua + ';' + (useFeatures && nav.appMinorVersion)) ||
/\bMinefield\b/i.test(ua) && 'a'
)) {
prerelease = /b/i.test(data) ? 'beta' : 'alpha';
version = version.replace(RegExp(data + '\\+?$'), '') +
(prerelease == 'beta' ? beta : alpha) + (/\d+\+?/.exec(data) || '');
}
// Detect Firefox Mobile.
if (name == 'Fennec' || name == 'Firefox' && /\b(?:Android|Firefox OS)\b/.test(os)) {
name = 'Firefox Mobile';
}
// Obscure Maxthon's unreliable version.
else if (name == 'Maxthon' && version) {
version = version.replace(/\.[\d.]+/, '.x');
}
// Detect Xbox 360 and Xbox One.
else if (/\bXbox\b/i.test(product)) {
if (product == 'Xbox 360') {
os = null;
}
if (product == 'Xbox 360' && /\bIEMobile\b/.test(ua)) {
description.unshift('mobile mode');
}
}
// Add mobile postfix.
else if ((/^(?:Chrome|IE|Opera)$/.test(name) || name && !product && !/Browser|Mobi/.test(name)) &&
(os == 'Windows CE' || /Mobi/i.test(ua))) {
name += ' Mobile';
}
// Detect IE platform preview.
else if (name == 'IE' && useFeatures) {
try {
if (context.external === null) {
description.unshift('platform preview');
}
} catch(e) {
description.unshift('embedded');
}
}
// Detect BlackBerry OS version.
// http://docs.blackberry.com/en/developers/deliverables/18169/HTTP_headers_sent_by_BB_Browser_1234911_11.jsp
else if ((/\bBlackBerry\b/.test(product) || /\bBB10\b/.test(ua)) && (data =
(RegExp(product.replace(/ +/g, ' *') + '/([.\\d]+)', 'i').exec(ua) || 0)[1] ||
version
)) {
data = [data, /BB10/.test(ua)];
os = (data[1] ? (product = null, manufacturer = 'BlackBerry') : 'Device Software') + ' ' + data[0];
version = null;
}
// Detect Opera identifying/masking itself as another browser.
// http://www.opera.com/support/kb/view/843/
else if (this != forOwn && product != 'Wii' && (
(useFeatures && opera) ||
(/Opera/.test(name) && /\b(?:MSIE|Firefox)\b/i.test(ua)) ||
(name == 'Firefox' && /\bOS X (?:\d+\.){2,}/.test(os)) ||
(name == 'IE' && (
(os && !/^Win/.test(os) && version > 5.5) ||
/\bWindows XP\b/.test(os) && version > 8 ||
version == 8 && !/\bTrident\b/.test(ua)
))
) && !reOpera.test((data = parse.call(forOwn, ua.replace(reOpera, '') + ';'))) && data.name) {
// When "identifying", the UA contains both Opera and the other browser's name.
data = 'ing as ' + data.name + ((data = data.version) ? ' ' + data : '');
if (reOpera.test(name)) {
if (/\bIE\b/.test(data) && os == 'Mac OS') {
os = null;
}
data = 'identify' + data;
}
// When "masking", the UA contains only the other browser's name.
else {
data = 'mask' + data;
if (operaClass) {
name = format(operaClass.replace(/([a-z])([A-Z])/g, '$1 $2'));
} else {
name = 'Opera';
}
if (/\bIE\b/.test(data)) {
os = null;
}
if (!useFeatures) {
version = null;
}
}
layout = ['Presto'];
description.push(data);
}
// Detect WebKit Nightly and approximate Chrome/Safari versions.
if ((data = (/\bAppleWebKit\/([\d.]+\+?)/i.exec(ua) || 0)[1])) {
// Correct build number for numeric comparison.
// (e.g. "532.5" becomes "532.05")
data = [parseFloat(data.replace(/\.(\d)$/, '.0$1')), data];
// Nightly builds are postfixed with a "+".
if (name == 'Safari' && data[1].slice(-1) == '+') {
name = 'WebKit Nightly';
prerelease = 'alpha';
version = data[1].slice(0, -1);
}
// Clear incorrect browser versions.
else if (version == data[1] ||
version == (data[2] = (/\bSafari\/([\d.]+\+?)/i.exec(ua) || 0)[1])) {
version = null;
}
// Use the full Chrome version when available.
data[1] = (/\bChrome\/([\d.]+)/i.exec(ua) || 0)[1];
// Detect Blink layout engine.
if (data[0] == 537.36 && data[2] == 537.36 && parseFloat(data[1]) >= 28 && layout == 'WebKit') {
layout = ['Blink'];
}
// Detect JavaScriptCore.
// http://stackoverflow.com/questions/6768474/how-can-i-detect-which-javascript-engine-v8-or-jsc-is-used-at-runtime-in-androi
if (!useFeatures || (!likeChrome && !data[1])) {
layout && (layout[1] = 'like Safari');
data = (data = data[0], data < 400 ? 1 : data < 500 ? 2 : data < 526 ? 3 : data < 533 ? 4 : data < 534 ? '4+' : data < 535 ? 5 : data < 537 ? 6 : data < 538 ? 7 : data < 601 ? 8 : '8');
} else {
layout && (layout[1] = 'like Chrome');
data = data[1] || (data = data[0], data < 530 ? 1 : data < 532 ? 2 : data < 532.05 ? 3 : data < 533 ? 4 : data < 534.03 ? 5 : data < 534.07 ? 6 : data < 534.10 ? 7 : data < 534.13 ? 8 : data < 534.16 ? 9 : data < 534.24 ? 10 : data < 534.30 ? 11 : data < 535.01 ? 12 : data < 535.02 ? '13+' : data < 535.07 ? 15 : data < 535.11 ? 16 : data < 535.19 ? 17 : data < 536.05 ? 18 : data < 536.10 ? 19 : data < 537.01 ? 20 : data < 537.11 ? '21+' : data < 537.13 ? 23 : data < 537.18 ? 24 : data < 537.24 ? 25 : data < 537.36 ? 26 : layout != 'Blink' ? '27' : '28');
}
// Add the postfix of ".x" or "+" for approximate versions.
layout && (layout[1] += ' ' + (data += typeof data == 'number' ? '.x' : /[.+]/.test(data) ? '' : '+'));
// Obscure version for some Safari 1-2 releases.
if (name == 'Safari' && (!version || parseInt(version) > 45)) {
version = data;
}
}
// Detect Opera desktop modes.
if (name == 'Opera' && (data = /\bzbov|zvav$/.exec(os))) {
name += ' ';
description.unshift('desktop mode');
if (data == 'zvav') {
name += 'Mini';
version = null;
} else {
name += 'Mobile';
}
os = os.replace(RegExp(' *' + data + '$'), '');
}
// Detect Chrome desktop mode.
else if (name == 'Safari' && /\bChrome\b/.exec(layout && layout[1])) {
description.unshift('desktop mode');
name = 'Chrome Mobile';
version = null;
if (/\bOS X\b/.test(os)) {
manufacturer = 'Apple';
os = 'iOS 4.3+';
} else {
os = null;
}
}
// Strip incorrect OS versions.
if (version && version.indexOf((data = /[\d.]+$/.exec(os))) == 0 &&
ua.indexOf('/' + data + '-') > -1) {
os = trim(os.replace(data, ''));
}
// Add layout engine.
if (layout && !/\b(?:Avant|Nook)\b/.test(name) && (
/Browser|Lunascape|Maxthon/.test(name) ||
name != 'Safari' && /^iOS/.test(os) && /\bSafari\b/.test(layout[1]) ||
/^(?:Adobe|Arora|Breach|Midori|Opera|Phantom|Rekonq|Rock|Samsung Internet|Sleipnir|Web)/.test(name) && layout[1])) {
// Don't add layout details to description if they are falsey.
(data = layout[layout.length - 1]) && description.push(data);
}
// Combine contextual information.
if (description.length) {
description = ['(' + description.join('; ') + ')'];
}
// Append manufacturer to description.
if (manufacturer && product && product.indexOf(manufacturer) < 0) {
description.push('on ' + manufacturer);
}
// Append product to description.
if (product) {
description.push((/^on /.test(description[description.length - 1]) ? '' : 'on ') + product);
}
// Parse the OS into an object.
if (os) {
data = / ([\d.+]+)$/.exec(os);
isSpecialCasedOS = data && os.charAt(os.length - data[0].length - 1) == '/';
os = {
'architecture': 32,
'family': (data && !isSpecialCasedOS) ? os.replace(data[0], '') : os,
'version': data ? data[1] : null,
'toString': function() {
var version = this.version;
return this.family + ((version && !isSpecialCasedOS) ? ' ' + version : '') + (this.architecture == 64 ? ' 64-bit' : '');
}
};
}
// Add browser/OS architecture.
if ((data = /\b(?:AMD|IA|Win|WOW|x86_|x)64\b/i.exec(arch)) && !/\bi686\b/i.test(arch)) {
if (os) {
os.architecture = 64;
os.family = os.family.replace(RegExp(' *' + data), '');
}
if (
name && (/\bWOW64\b/i.test(ua) ||
(useFeatures && /\w(?:86|32)$/.test(nav.cpuClass || nav.platform) && !/\bWin64; x64\b/i.test(ua)))
) {
description.unshift('32-bit');
}
}
// Chrome 39 and above on OS X is always 64-bit.
else if (
os && /^OS X/.test(os.family) &&
name == 'Chrome' && parseFloat(version) >= 39
) {
os.architecture = 64;
}
ua || (ua = null);
/*------------------------------------------------------------------------*/
/**
* The platform object.
*
* @name platform
* @type Object
*/
var platform = {};
/**
* The platform description.
*
* @memberOf platform
* @type string|null
*/
platform.description = ua;
/**
* The name of the browser's layout engine.
*
* The list of common layout engines include:
* "Blink", "EdgeHTML", "Gecko", "Trident" and "WebKit"
*
* @memberOf platform
* @type string|null
*/
platform.layout = layout && layout[0];
/**
* The name of the product's manufacturer.
*
* The list of manufacturers include:
* "Apple", "Archos", "Amazon", "Asus", "Barnes & Noble", "BlackBerry",
* "Google", "HP", "HTC", "LG", "Microsoft", "Motorola", "Nintendo",
* "Nokia", "Samsung" and "Sony"
*
* @memberOf platform
* @type string|null
*/
platform.manufacturer = manufacturer;
/**
* The name of the browser/environment.
*
* The list of common browser names include:
* "Chrome", "Electron", "Firefox", "Firefox for iOS", "IE",
* "Microsoft Edge", "PhantomJS", "Safari", "SeaMonkey", "Silk",
* "Opera Mini" and "Opera"
*
* Mobile versions of some browsers have "Mobile" appended to their name:
* eg. "Chrome Mobile", "Firefox Mobile", "IE Mobile" and "Opera Mobile"
*
* @memberOf platform
* @type string|null
*/
platform.name = name;
/**
* The alpha/beta release indicator.
*
* @memberOf platform
* @type string|null
*/
platform.prerelease = prerelease;
/**
* The name of the product hosting the browser.
*
* The list of common products include:
*
* "BlackBerry", "Galaxy S4", "Lumia", "iPad", "iPod", "iPhone", "Kindle",
* "Kindle Fire", "Nexus", "Nook", "PlayBook", "TouchPad" and "Transformer"
*
* @memberOf platform
* @type string|null
*/
platform.product = product;
/**
* The browser's user agent string.
*
* @memberOf platform
* @type string|null
*/
platform.ua = ua;
/**
* The browser/environment version.
*
* @memberOf platform
* @type string|null
*/
platform.version = name && version;
/**
* The name of the operating system.
*
* @memberOf platform
* @type Object
*/
platform.os = os || {
/**
* The CPU architecture the OS is built for.
*
* @memberOf platform.os
* @type number|null
*/
'architecture': null,
/**
* The family of the OS.
*
* Common values include:
* "Windows", "Windows Server 2008 R2 / 7", "Windows Server 2008 / Vista",
* "Windows XP", "OS X", "Ubuntu", "Debian", "Fedora", "Red Hat", "SuSE",
* "Android", "iOS" and "Windows Phone"
*
* @memberOf platform.os
* @type string|null
*/
'family': null,
/**
* The version of the OS.
*
* @memberOf platform.os
* @type string|null
*/
'version': null,
/**
* Returns the OS string.
*
* @memberOf platform.os
* @returns {string} The OS string.
*/
'toString': function() { return 'null'; }
};
platform.parse = parse;
platform.toString = toStringPlatform;
if (platform.version) {
description.unshift(version);
}
if (platform.name) {
description.unshift(name);
}
if (os && name && !(os == String(os).split(' ')[0] && (os == name.split(' ')[0] || product))) {
description.push(product ? '(' + os + ')' : 'on ' + os);
}
if (description.length) {
platform.description = description.join(' ');
}
return platform;
}
/*--------------------------------------------------------------------------*/
// Export platform.
var platform = parse();
// Some AMD build optimizers, like r.js, check for condition patterns like the following:
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
// Expose platform on the global object to prevent errors when platform is
// loaded by a script tag in the presence of an AMD loader.
// See http://requirejs.org/docs/errors.html#mismatch for more details.
root.platform = platform;
// Define as an anonymous module so platform can be aliased through path mapping.
define(function() {
return platform;
});
}
// Check for `exports` after `define` in case a build optimizer adds an `exports` object.
else if (freeExports && freeModule) {
// Export for CommonJS support.
forOwn(platform, function(value, key) {
freeExports[key] = value;
});
}
else {
// Export to the global object.
root.platform = platform;
}
}.call(this));
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],207:[function(require,module,exports){
(function (process){
'use strict';
if (typeof process === 'undefined' ||
!process.version ||
process.version.indexOf('v0.') === 0 ||
process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
module.exports = { nextTick: nextTick };
} else {
module.exports = process
}
function nextTick(fn, arg1, arg2, arg3) {
if (typeof fn !== 'function') {
throw new TypeError('"callback" argument must be a function');
}
var len = arguments.length;
var args, i;
switch (len) {
case 0:
case 1:
return process.nextTick(fn);
case 2:
return process.nextTick(function afterTickOne() {
fn.call(null, arg1);
});
case 3:
return process.nextTick(function afterTickTwo() {
fn.call(null, arg1, arg2);
});
case 4:
return process.nextTick(function afterTickThree() {
fn.call(null, arg1, arg2, arg3);
});
default:
args = new Array(len - 1);
i = 0;
while (i < args.length) {
args[i++] = arguments[i];
}
return process.nextTick(function afterTick() {
fn.apply(null, args);
});
}
}
}).call(this,require('_process'))
},{"_process":208}],208:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],209:[function(require,module,exports){
(function (global){
/*! https://mths.be/punycode v1.4.1 by @mathias */
;(function(root) {
/** Detect free variables */
var freeExports = typeof exports == 'object' && exports &&
!exports.nodeType && exports;
var freeModule = typeof module == 'object' && module &&
!module.nodeType && module;
var freeGlobal = typeof global == 'object' && global;
if (
freeGlobal.global === freeGlobal ||
freeGlobal.window === freeGlobal ||
freeGlobal.self === freeGlobal
) {
root = freeGlobal;
}
/**
* The `punycode` object.
* @name punycode
* @type Object
*/
var punycode,
/** Highest positive signed 32-bit float value */
maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
/** Bootstring parameters */
base = 36,
tMin = 1,
tMax = 26,
skew = 38,
damp = 700,
initialBias = 72,
initialN = 128, // 0x80
delimiter = '-', // '\x2D'
/** Regular expressions */
regexPunycode = /^xn--/,
regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
/** Error messages */
errors = {
'overflow': 'Overflow: input needs wider integers to process',
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
'invalid-input': 'Invalid input'
},
/** Convenience shortcuts */
baseMinusTMin = base - tMin,
floor = Math.floor,
stringFromCharCode = String.fromCharCode,
/** Temporary variable */
key;
/*--------------------------------------------------------------------------*/
/**
* A generic error utility function.
* @private
* @param {String} type The error type.
* @returns {Error} Throws a `RangeError` with the applicable error message.
*/
function error(type) {
throw new RangeError(errors[type]);
}
/**
* A generic `Array#map` utility function.
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function that gets called for every array
* item.
* @returns {Array} A new array of values returned by the callback function.
*/
function map(array, fn) {
var length = array.length;
var result = [];
while (length--) {
result[length] = fn(array[length]);
}
return result;
}
/**
* A simple `Array#map`-like wrapper to work with domain name strings or email
* addresses.
* @private
* @param {String} domain The domain name or email address.
* @param {Function} callback The function that gets called for every
* character.
* @returns {Array} A new string of characters returned by the callback
* function.
*/
function mapDomain(string, fn) {
var parts = string.split('@');
var result = '';
if (parts.length > 1) {
// In email addresses, only the domain name should be punycoded. Leave
// the local part (i.e. everything up to `@`) intact.
result = parts[0] + '@';
string = parts[1];
}
// Avoid `split(regex)` for IE8 compatibility. See #17.
string = string.replace(regexSeparators, '\x2E');
var labels = string.split('.');
var encoded = map(labels, fn).join('.');
return result + encoded;
}
/**
* Creates an array containing the numeric code points of each Unicode
* character in the string. While JavaScript uses UCS-2 internally,
* this function will convert a pair of surrogate halves (each of which
* UCS-2 exposes as separate characters) into a single code point,
* matching UTF-16.
* @see `punycode.ucs2.encode`
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode.ucs2
* @name decode
* @param {String} string The Unicode input string (UCS-2).
* @returns {Array} The new array of code points.
*/
function ucs2decode(string) {
var output = [],
counter = 0,
length = string.length,
value,
extra;
while (counter < length) {
value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// high surrogate, and there is a next character
extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) { // low surrogate
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// unmatched surrogate; only append this code unit, in case the next
// code unit is the high surrogate of a surrogate pair
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
/**
* Creates a string based on an array of numeric code points.
* @see `punycode.ucs2.decode`
* @memberOf punycode.ucs2
* @name encode
* @param {Array} codePoints The array of numeric code points.
* @returns {String} The new Unicode string (UCS-2).
*/
function ucs2encode(array) {
return map(array, function(value) {
var output = '';
if (value > 0xFFFF) {
value -= 0x10000;
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += stringFromCharCode(value);
return output;
}).join('');
}
/**
* Converts a basic code point into a digit/integer.
* @see `digitToBasic()`
* @private
* @param {Number} codePoint The basic numeric code point value.
* @returns {Number} The numeric value of a basic code point (for use in
* representing integers) in the range `0` to `base - 1`, or `base` if
* the code point does not represent a value.
*/
function basicToDigit(codePoint) {
if (codePoint - 48 < 10) {
return codePoint - 22;
}
if (codePoint - 65 < 26) {
return codePoint - 65;
}
if (codePoint - 97 < 26) {
return codePoint - 97;
}
return base;
}
/**
* Converts a digit/integer into a basic code point.
* @see `basicToDigit()`
* @private
* @param {Number} digit The numeric value of a basic code point.
* @returns {Number} The basic code point whose value (when used for
* representing integers) is `digit`, which needs to be in the range
* `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
* used; else, the lowercase form is used. The behavior is undefined
* if `flag` is non-zero and `digit` has no uppercase form.
*/
function digitToBasic(digit, flag) {
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
}
/**
* Bias adaptation function as per section 3.4 of RFC 3492.
* https://tools.ietf.org/html/rfc3492#section-3.4
* @private
*/
function adapt(delta, numPoints, firstTime) {
var k = 0;
delta = firstTime ? floor(delta / damp) : delta >> 1;
delta += floor(delta / numPoints);
for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor(delta / baseMinusTMin);
}
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
}
/**
* Converts a Punycode string of ASCII-only symbols to a string of Unicode
* symbols.
* @memberOf punycode
* @param {String} input The Punycode string of ASCII-only symbols.
* @returns {String} The resulting string of Unicode symbols.
*/
function decode(input) {
// Don't use UCS-2
var output = [],
inputLength = input.length,
out,
i = 0,
n = initialN,
bias = initialBias,
basic,
j,
index,
oldi,
w,
k,
digit,
t,
/** Cached calculation results */
baseMinusT;
// Handle the basic code points: let `basic` be the number of input code
// points before the last delimiter, or `0` if there is none, then copy
// the first basic code points to the output.
basic = input.lastIndexOf(delimiter);
if (basic < 0) {
basic = 0;
}
for (j = 0; j < basic; ++j) {
// if it's not a basic code point
if (input.charCodeAt(j) >= 0x80) {
error('not-basic');
}
output.push(input.charCodeAt(j));
}
// Main decoding loop: start just after the last delimiter if any basic code
// points were copied; start at the beginning otherwise.
for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
// `index` is the index of the next character to be consumed.
// Decode a generalized variable-length integer into `delta`,
// which gets added to `i`. The overflow checking is easier
// if we increase `i` as we go, then subtract off its starting
// value at the end to obtain `delta`.
for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
if (index >= inputLength) {
error('invalid-input');
}
digit = basicToDigit(input.charCodeAt(index++));
if (digit >= base || digit > floor((maxInt - i) / w)) {
error('overflow');
}
i += digit * w;
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (digit < t) {
break;
}
baseMinusT = base - t;
if (w > floor(maxInt / baseMinusT)) {
error('overflow');
}
w *= baseMinusT;
}
out = output.length + 1;
bias = adapt(i - oldi, out, oldi == 0);
// `i` was supposed to wrap around from `out` to `0`,
// incrementing `n` each time, so we'll fix that now:
if (floor(i / out) > maxInt - n) {
error('overflow');
}
n += floor(i / out);
i %= out;
// Insert `n` at position `i` of the output
output.splice(i++, 0, n);
}
return ucs2encode(output);
}
/**
* Converts a string of Unicode symbols (e.g. a domain name label) to a
* Punycode string of ASCII-only symbols.
* @memberOf punycode
* @param {String} input The string of Unicode symbols.
* @returns {String} The resulting Punycode string of ASCII-only symbols.
*/
function encode(input) {
var n,
delta,
handledCPCount,
basicLength,
bias,
j,
m,
q,
k,
t,
currentValue,
output = [],
/** `inputLength` will hold the number of code points in `input`. */
inputLength,
/** Cached calculation results */
handledCPCountPlusOne,
baseMinusT,
qMinusT;
// Convert the input in UCS-2 to Unicode
input = ucs2decode(input);
// Cache the length
inputLength = input.length;
// Initialize the state
n = initialN;
delta = 0;
bias = initialBias;
// Handle the basic code points
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < 0x80) {
output.push(stringFromCharCode(currentValue));
}
}
handledCPCount = basicLength = output.length;
// `handledCPCount` is the number of code points that have been handled;
// `basicLength` is the number of basic code points.
// Finish the basic string - if it is not empty - with a delimiter
if (basicLength) {
output.push(delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next
// larger one:
for (m = maxInt, j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
// but guard against overflow
handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
error('overflow');
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < n && ++delta > maxInt) {
error('overflow');
}
if (currentValue == n) {
// Represent delta as a generalized variable-length integer
for (q = delta, k = base; /* no condition */; k += base) {
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (q < t) {
break;
}
qMinusT = q - t;
baseMinusT = base - t;
output.push(
stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
);
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q, 0)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
++handledCPCount;
}
}
++delta;
++n;
}
return output.join('');
}
/**
* Converts a Punycode string representing a domain name or an email address
* to Unicode. Only the Punycoded parts of the input will be converted, i.e.
* it doesn't matter if you call it on a string that has already been
* converted to Unicode.
* @memberOf punycode
* @param {String} input The Punycoded domain name or email address to
* convert to Unicode.
* @returns {String} The Unicode representation of the given Punycode
* string.
*/
function toUnicode(input) {
return mapDomain(input, function(string) {
return regexPunycode.test(string)
? decode(string.slice(4).toLowerCase())
: string;
});
}
/**
* Converts a Unicode string representing a domain name or an email address to
* Punycode. Only the non-ASCII parts of the domain name will be converted,
* i.e. it doesn't matter if you call it with a domain that's already in
* ASCII.
* @memberOf punycode
* @param {String} input The domain name or email address to convert, as a
* Unicode string.
* @returns {String} The Punycode representation of the given domain name or
* email address.
*/
function toASCII(input) {
return mapDomain(input, function(string) {
return regexNonASCII.test(string)
? 'xn--' + encode(string)
: string;
});
}
/*--------------------------------------------------------------------------*/
/** Define the public API */
punycode = {
/**
* A string representing the current Punycode.js version number.
* @memberOf punycode
* @type String
*/
'version': '1.4.1',
/**
* An object of methods to convert from JavaScript's internal character
* representation (UCS-2) to Unicode code points, and back.
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode
* @type Object
*/
'ucs2': {
'decode': ucs2decode,
'encode': ucs2encode
},
'decode': decode,
'encode': encode,
'toASCII': toASCII,
'toUnicode': toUnicode
};
/** Expose `punycode` */
// Some AMD build optimizers, like r.js, check for specific condition patterns
// like the following:
if (
typeof define == 'function' &&
typeof define.amd == 'object' &&
define.amd
) {
define('punycode', function() {
return punycode;
});
} else if (freeExports && freeModule) {
if (module.exports == freeExports) {
// in Node.js, io.js, or RingoJS v0.8.0+
freeModule.exports = punycode;
} else {
// in Narwhal or RingoJS v0.7.0-
for (key in punycode) {
punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
}
}
} else {
// in Rhino or a web browser
root.punycode = punycode;
}
}(this));
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],210:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node 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.
'use strict';
// If obj.hasOwnProperty has been overridden, then calling
// obj.hasOwnProperty(prop) will break.
// See: https://github.com/joyent/node/issues/1707
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
module.exports = function(qs, sep, eq, options) {
sep = sep || '&';
eq = eq || '=';
var obj = {};
if (typeof qs !== 'string' || qs.length === 0) {
return obj;
}
var regexp = /\+/g;
qs = qs.split(sep);
var maxKeys = 1000;
if (options && typeof options.maxKeys === 'number') {
maxKeys = options.maxKeys;
}
var len = qs.length;
// maxKeys <= 0 means that we should not limit keys count
if (maxKeys > 0 && len > maxKeys) {
len = maxKeys;
}
for (var i = 0; i < len; ++i) {
var x = qs[i].replace(regexp, '%20'),
idx = x.indexOf(eq),
kstr, vstr, k, v;
if (idx >= 0) {
kstr = x.substr(0, idx);
vstr = x.substr(idx + 1);
} else {
kstr = x;
vstr = '';
}
k = decodeURIComponent(kstr);
v = decodeURIComponent(vstr);
if (!hasOwnProperty(obj, k)) {
obj[k] = v;
} else if (isArray(obj[k])) {
obj[k].push(v);
} else {
obj[k] = [obj[k], v];
}
}
return obj;
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
},{}],211:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node 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.
'use strict';
var stringifyPrimitive = function(v) {
switch (typeof v) {
case 'string':
return v;
case 'boolean':
return v ? 'true' : 'false';
case 'number':
return isFinite(v) ? v : '';
default:
return '';
}
};
module.exports = function(obj, sep, eq, name) {
sep = sep || '&';
eq = eq || '=';
if (obj === null) {
obj = undefined;
}
if (typeof obj === 'object') {
return map(objectKeys(obj), function(k) {
var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
if (isArray(obj[k])) {
return map(obj[k], function(v) {
return ks + encodeURIComponent(stringifyPrimitive(v));
}).join(sep);
} else {
return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
}
}).join(sep);
}
if (!name) return '';
return encodeURIComponent(stringifyPrimitive(name)) + eq +
encodeURIComponent(stringifyPrimitive(obj));
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
function map (xs, f) {
if (xs.map) return xs.map(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
res.push(f(xs[i], i));
}
return res;
}
var objectKeys = Object.keys || function (obj) {
var res = [];
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
}
return res;
};
},{}],212:[function(require,module,exports){
'use strict';
exports.decode = exports.parse = require('./decode');
exports.encode = exports.stringify = require('./encode');
},{"./decode":210,"./encode":211}],213:[function(require,module,exports){
module.exports = require('./lib/_stream_duplex.js');
},{"./lib/_stream_duplex.js":214}],214:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node 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.
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
'use strict';
/*<replacement>*/
var _create = require('babel-runtime/core-js/object/create');
var _create2 = _interopRequireDefault(_create);
var _keys = require('babel-runtime/core-js/object/keys');
var _keys2 = _interopRequireDefault(_keys);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var pna = require('process-nextick-args');
/*</replacement>*/
/*<replacement>*/
var objectKeys = _keys2.default || function (obj) {
var keys = [];
for (var key in obj) {
keys.push(key);
}return keys;
};
/*</replacement>*/
module.exports = Duplex;
/*<replacement>*/
var util = (0, _create2.default)(require('core-util-is'));
util.inherits = require('inherits');
/*</replacement>*/
var Readable = require('./_stream_readable');
var Writable = require('./_stream_writable');
util.inherits(Duplex, Readable);
{
// avoid scope creep, the keys array can then be collected
var keys = objectKeys(Writable.prototype);
for (var v = 0; v < keys.length; v++) {
var method = keys[v];
if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
}
}
function Duplex(options) {
if (!(this instanceof Duplex)) return new Duplex(options);
Readable.call(this, options);
Writable.call(this, options);
if (options && options.readable === false) this.readable = false;
if (options && options.writable === false) this.writable = false;
this.allowHalfOpen = true;
if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
this.once('end', onend);
}
Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
return this._writableState.highWaterMark;
}
});
// the no-half-open enforcer
function onend() {
// if we allow half-open state, or if the writable side ended,
// then we're ok.
if (this.allowHalfOpen || this._writableState.ended) return;
// no more data can be written.
// But allow more writes to happen in this tick.
pna.nextTick(onEndNT, this);
}
function onEndNT(self) {
self.end();
}
Object.defineProperty(Duplex.prototype, 'destroyed', {
get: function get() {
if (this._readableState === undefined || this._writableState === undefined) {
return false;
}
return this._readableState.destroyed && this._writableState.destroyed;
},
set: function set(value) {
// we ignore the value if the stream
// has not been initialized yet
if (this._readableState === undefined || this._writableState === undefined) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._readableState.destroyed = value;
this._writableState.destroyed = value;
}
});
Duplex.prototype._destroy = function (err, cb) {
this.push(null);
this.end();
pna.nextTick(cb, err);
};
},{"./_stream_readable":216,"./_stream_writable":218,"babel-runtime/core-js/object/create":55,"babel-runtime/core-js/object/keys":60,"core-util-is":189,"inherits":196,"process-nextick-args":207}],215:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node 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.
// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.
'use strict';
var _create = require('babel-runtime/core-js/object/create');
var _create2 = _interopRequireDefault(_create);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
module.exports = PassThrough;
var Transform = require('./_stream_transform');
/*<replacement>*/
var util = (0, _create2.default)(require('core-util-is'));
util.inherits = require('inherits');
/*</replacement>*/
util.inherits(PassThrough, Transform);
function PassThrough(options) {
if (!(this instanceof PassThrough)) return new PassThrough(options);
Transform.call(this, options);
}
PassThrough.prototype._transform = function (chunk, encoding, cb) {
cb(null, chunk);
};
},{"./_stream_transform":217,"babel-runtime/core-js/object/create":55,"core-util-is":189,"inherits":196}],216:[function(require,module,exports){
(function (process,global){
// Copyright Joyent, Inc. and other Node 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.
'use strict';
/*<replacement>*/
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _create = require('babel-runtime/core-js/object/create');
var _create2 = _interopRequireDefault(_create);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var pna = require('process-nextick-args');
/*</replacement>*/
module.exports = Readable;
/*<replacement>*/
var isArray = require('isarray');
/*</replacement>*/
/*<replacement>*/
var Duplex;
/*</replacement>*/
Readable.ReadableState = ReadableState;
/*<replacement>*/
var EE = require('events').EventEmitter;
var EElistenerCount = function EElistenerCount(emitter, type) {
return emitter.listeners(type).length;
};
/*</replacement>*/
/*<replacement>*/
var Stream = require('./internal/streams/stream');
/*</replacement>*/
/*<replacement>*/
var Buffer = require('safe-buffer').Buffer;
var OurUint8Array = global.Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
return Buffer.from(chunk);
}
function _isUint8Array(obj) {
return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}
/*</replacement>*/
/*<replacement>*/
var util = (0, _create2.default)(require('core-util-is'));
util.inherits = require('inherits');
/*</replacement>*/
/*<replacement>*/
var debugUtil = require('util');
var debug = void 0;
if (debugUtil && debugUtil.debuglog) {
debug = debugUtil.debuglog('stream');
} else {
debug = function debug() {};
}
/*</replacement>*/
var BufferList = require('./internal/streams/BufferList');
var destroyImpl = require('./internal/streams/destroy');
var StringDecoder;
util.inherits(Readable, Stream);
var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
function prependListener(emitter, event, fn) {
// Sadly this is not cacheable as some libraries bundle their own
// event emitter implementation with them.
if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
// This is a hack to make sure that our error handler is attached before any
// userland ones. NEVER DO THIS. This is here only because this code needs
// to continue to work with older versions of Node.js that do not include
// the prependListener() method. The goal is to eventually remove this hack.
if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
}
function ReadableState(options, stream) {
Duplex = Duplex || require('./_stream_duplex');
options = options || {};
// Duplex streams are both readable and writable, but share
// the same options object.
// However, some cases require setting options to different
// values for the readable and the writable sides of the duplex stream.
// These options can be provided separately as readableXXX and writableXXX.
var isDuplex = stream instanceof Duplex;
// object stream flag. Used to make read(n) ignore n and to
// make all the buffer merging and length checks go away
this.objectMode = !!options.objectMode;
if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
// the point at which it stops calling _read() to fill the buffer
// Note: 0 is a valid value, means "don't call _read preemptively ever"
var hwm = options.highWaterMark;
var readableHwm = options.readableHighWaterMark;
var defaultHwm = this.objectMode ? 16 : 16 * 1024;
if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
// cast to ints.
this.highWaterMark = Math.floor(this.highWaterMark);
// A linked list is used to store data chunks instead of an array because the
// linked list can remove elements from the beginning faster than
// array.shift()
this.buffer = new BufferList();
this.length = 0;
this.pipes = null;
this.pipesCount = 0;
this.flowing = null;
this.ended = false;
this.endEmitted = false;
this.reading = false;
// a flag to be able to tell if the event 'readable'/'data' is emitted
// immediately, or on a later tick. We set this to true at first, because
// any actions that shouldn't happen until "later" should generally also
// not happen before the first read call.
this.sync = true;
// whenever we return null, then we set a flag to say
// that we're awaiting a 'readable' event emission.
this.needReadable = false;
this.emittedReadable = false;
this.readableListening = false;
this.resumeScheduled = false;
// has it been destroyed
this.destroyed = false;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// the number of writers that are awaiting a drain event in .pipe()s
this.awaitDrain = 0;
// if true, a maybeReadMore has been scheduled
this.readingMore = false;
this.decoder = null;
this.encoding = null;
if (options.encoding) {
if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
this.decoder = new StringDecoder(options.encoding);
this.encoding = options.encoding;
}
}
function Readable(options) {
Duplex = Duplex || require('./_stream_duplex');
if (!(this instanceof Readable)) return new Readable(options);
this._readableState = new ReadableState(options, this);
// legacy
this.readable = true;
if (options) {
if (typeof options.read === 'function') this._read = options.read;
if (typeof options.destroy === 'function') this._destroy = options.destroy;
}
Stream.call(this);
}
Object.defineProperty(Readable.prototype, 'destroyed', {
get: function get() {
if (this._readableState === undefined) {
return false;
}
return this._readableState.destroyed;
},
set: function set(value) {
// we ignore the value if the stream
// has not been initialized yet
if (!this._readableState) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._readableState.destroyed = value;
}
});
Readable.prototype.destroy = destroyImpl.destroy;
Readable.prototype._undestroy = destroyImpl.undestroy;
Readable.prototype._destroy = function (err, cb) {
this.push(null);
cb(err);
};
// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function (chunk, encoding) {
var state = this._readableState;
var skipChunkCheck;
if (!state.objectMode) {
if (typeof chunk === 'string') {
encoding = encoding || state.defaultEncoding;
if (encoding !== state.encoding) {
chunk = Buffer.from(chunk, encoding);
encoding = '';
}
skipChunkCheck = true;
}
} else {
skipChunkCheck = true;
}
return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
};
// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function (chunk) {
return readableAddChunk(this, chunk, null, true, false);
};
function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
var state = stream._readableState;
if (chunk === null) {
state.reading = false;
onEofChunk(stream, state);
} else {
var er;
if (!skipChunkCheck) er = chunkInvalid(state, chunk);
if (er) {
stream.emit('error', er);
} else if (state.objectMode || chunk && chunk.length > 0) {
if (typeof chunk !== 'string' && !state.objectMode && (0, _getPrototypeOf2.default)(chunk) !== Buffer.prototype) {
chunk = _uint8ArrayToBuffer(chunk);
}
if (addToFront) {
if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
} else if (state.ended) {
stream.emit('error', new Error('stream.push() after EOF'));
} else {
state.reading = false;
if (state.decoder && !encoding) {
chunk = state.decoder.write(chunk);
if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
} else {
addChunk(stream, state, chunk, false);
}
}
} else if (!addToFront) {
state.reading = false;
}
}
return needMoreData(state);
}
function addChunk(stream, state, chunk, addToFront) {
if (state.flowing && state.length === 0 && !state.sync) {
stream.emit('data', chunk);
stream.read(0);
} else {
// update the buffer info.
state.length += state.objectMode ? 1 : chunk.length;
if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
if (state.needReadable) emitReadable(stream);
}
maybeReadMore(stream, state);
}
function chunkInvalid(state, chunk) {
var er;
if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
return er;
}
// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes. This is to work around cases where hwm=0,
// such as the repl. Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
}
Readable.prototype.isPaused = function () {
return this._readableState.flowing === false;
};
// backwards compatibility.
Readable.prototype.setEncoding = function (enc) {
if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
this._readableState.decoder = new StringDecoder(enc);
this._readableState.encoding = enc;
return this;
};
// Don't raise the hwm > 8MB
var MAX_HWM = 0x800000;
function computeNewHighWaterMark(n) {
if (n >= MAX_HWM) {
n = MAX_HWM;
} else {
// Get the next highest power of 2 to prevent increasing hwm excessively in
// tiny amounts
n--;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
n++;
}
return n;
}
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function howMuchToRead(n, state) {
if (n <= 0 || state.length === 0 && state.ended) return 0;
if (state.objectMode) return 1;
if (n !== n) {
// Only flow one buffer at a time
if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
}
// If we're asking for more than the current hwm, then raise the hwm.
if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
if (n <= state.length) return n;
// Don't have enough
if (!state.ended) {
state.needReadable = true;
return 0;
}
return state.length;
}
// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function (n) {
debug('read', n);
n = parseInt(n, 10);
var state = this._readableState;
var nOrig = n;
if (n !== 0) state.emittedReadable = false;
// if we're doing read(0) to trigger a readable event, but we
// already have a bunch of data in the buffer, then just trigger
// the 'readable' event and move on.
if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
debug('read: emitReadable', state.length, state.ended);
if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
return null;
}
n = howMuchToRead(n, state);
// if we've ended, and we're now clear, then finish it up.
if (n === 0 && state.ended) {
if (state.length === 0) endReadable(this);
return null;
}
// All the actual chunk generation logic needs to be
// *below* the call to _read. The reason is that in certain
// synthetic stream cases, such as passthrough streams, _read
// may be a completely synchronous operation which may change
// the state of the read buffer, providing enough data when
// before there was *not* enough.
//
// So, the steps are:
// 1. Figure out what the state of things will be after we do
// a read from the buffer.
//
// 2. If that resulting state will trigger a _read, then call _read.
// Note that this may be asynchronous, or synchronous. Yes, it is
// deeply ugly to write APIs this way, but that still doesn't mean
// that the Readable class should behave improperly, as streams are
// designed to be sync/async agnostic.
// Take note if the _read call is sync or async (ie, if the read call
// has returned yet), so that we know whether or not it's safe to emit
// 'readable' etc.
//
// 3. Actually pull the requested chunks out of the buffer and return.
// if we need a readable event, then we need to do some reading.
var doRead = state.needReadable;
debug('need readable', doRead);
// if we currently have less than the highWaterMark, then also read some
if (state.length === 0 || state.length - n < state.highWaterMark) {
doRead = true;
debug('length less than watermark', doRead);
}
// however, if we've ended, then there's no point, and if we're already
// reading, then it's unnecessary.
if (state.ended || state.reading) {
doRead = false;
debug('reading or ended', doRead);
} else if (doRead) {
debug('do read');
state.reading = true;
state.sync = true;
// if the length is currently zero, then we *need* a readable event.
if (state.length === 0) state.needReadable = true;
// call internal read method
this._read(state.highWaterMark);
state.sync = false;
// If _read pushed data synchronously, then `reading` will be false,
// and we need to re-evaluate how much data we can return to the user.
if (!state.reading) n = howMuchToRead(nOrig, state);
}
var ret;
if (n > 0) ret = fromList(n, state);else ret = null;
if (ret === null) {
state.needReadable = true;
n = 0;
} else {
state.length -= n;
}
if (state.length === 0) {
// If we have nothing in the buffer, then we want to know
// as soon as we *do* get something into the buffer.
if (!state.ended) state.needReadable = true;
// If we tried to read() past the EOF, then emit end on the next tick.
if (nOrig !== n && state.ended) endReadable(this);
}
if (ret !== null) this.emit('data', ret);
return ret;
};
function onEofChunk(stream, state) {
if (state.ended) return;
if (state.decoder) {
var chunk = state.decoder.end();
if (chunk && chunk.length) {
state.buffer.push(chunk);
state.length += state.objectMode ? 1 : chunk.length;
}
}
state.ended = true;
// emit 'readable' now to make sure it gets picked up.
emitReadable(stream);
}
// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow. This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
var state = stream._readableState;
state.needReadable = false;
if (!state.emittedReadable) {
debug('emitReadable', state.flowing);
state.emittedReadable = true;
if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
}
}
function emitReadable_(stream) {
debug('emit readable');
stream.emit('readable');
flow(stream);
}
// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data. that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
if (!state.readingMore) {
state.readingMore = true;
pna.nextTick(maybeReadMore_, stream, state);
}
}
function maybeReadMore_(stream, state) {
var len = state.length;
while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
debug('maybeReadMore read 0');
stream.read(0);
if (len === state.length)
// didn't get any data, stop spinning.
break;else len = state.length;
}
state.readingMore = false;
}
// abstract method. to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function (n) {
this.emit('error', new Error('_read() is not implemented'));
};
Readable.prototype.pipe = function (dest, pipeOpts) {
var src = this;
var state = this._readableState;
switch (state.pipesCount) {
case 0:
state.pipes = dest;
break;
case 1:
state.pipes = [state.pipes, dest];
break;
default:
state.pipes.push(dest);
break;
}
state.pipesCount += 1;
debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
var endFn = doEnd ? onend : unpipe;
if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
dest.on('unpipe', onunpipe);
function onunpipe(readable, unpipeInfo) {
debug('onunpipe');
if (readable === src) {
if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
unpipeInfo.hasUnpiped = true;
cleanup();
}
}
}
function onend() {
debug('onend');
dest.end();
}
// when the dest drains, it reduces the awaitDrain counter
// on the source. This would be more elegant with a .once()
// handler in flow(), but adding and removing repeatedly is
// too slow.
var ondrain = pipeOnDrain(src);
dest.on('drain', ondrain);
var cleanedUp = false;
function cleanup() {
debug('cleanup');
// cleanup event handlers once the pipe is broken
dest.removeListener('close', onclose);
dest.removeListener('finish', onfinish);
dest.removeListener('drain', ondrain);
dest.removeListener('error', onerror);
dest.removeListener('unpipe', onunpipe);
src.removeListener('end', onend);
src.removeListener('end', unpipe);
src.removeListener('data', ondata);
cleanedUp = true;
// if the reader is waiting for a drain event from this
// specific writer, then it would cause it to never start
// flowing again.
// So, if this is awaiting a drain, then we just call it now.
// If we don't know, then assume that we are waiting for one.
if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
}
// If the user pushes more data while we're writing to dest then we'll end up
// in ondata again. However, we only want to increase awaitDrain once because
// dest will only emit one 'drain' event for the multiple writes.
// => Introduce a guard on increasing awaitDrain.
var increasedAwaitDrain = false;
src.on('data', ondata);
function ondata(chunk) {
debug('ondata');
increasedAwaitDrain = false;
var ret = dest.write(chunk);
if (false === ret && !increasedAwaitDrain) {
// If the user unpiped during `dest.write()`, it is possible
// to get stuck in a permanently paused state if that write
// also returned false.
// => Check whether `dest` is still a piping destination.
if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
debug('false write response, pause', src._readableState.awaitDrain);
src._readableState.awaitDrain++;
increasedAwaitDrain = true;
}
src.pause();
}
}
// if the dest has an error, then stop piping into it.
// however, don't suppress the throwing behavior for this.
function onerror(er) {
debug('onerror', er);
unpipe();
dest.removeListener('error', onerror);
if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
}
// Make sure our error handler is attached before userland ones.
prependListener(dest, 'error', onerror);
// Both close and finish should trigger unpipe, but only once.
function onclose() {
dest.removeListener('finish', onfinish);
unpipe();
}
dest.once('close', onclose);
function onfinish() {
debug('onfinish');
dest.removeListener('close', onclose);
unpipe();
}
dest.once('finish', onfinish);
function unpipe() {
debug('unpipe');
src.unpipe(dest);
}
// tell the dest that it's being piped to
dest.emit('pipe', src);
// start the flow if it hasn't been started already.
if (!state.flowing) {
debug('pipe resume');
src.resume();
}
return dest;
};
function pipeOnDrain(src) {
return function () {
var state = src._readableState;
debug('pipeOnDrain', state.awaitDrain);
if (state.awaitDrain) state.awaitDrain--;
if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
state.flowing = true;
flow(src);
}
};
}
Readable.prototype.unpipe = function (dest) {
var state = this._readableState;
var unpipeInfo = { hasUnpiped: false };
// if we're not piping anywhere, then do nothing.
if (state.pipesCount === 0) return this;
// just one destination. most common case.
if (state.pipesCount === 1) {
// passed in one, but it's not the right one.
if (dest && dest !== state.pipes) return this;
if (!dest) dest = state.pipes;
// got a match.
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
if (dest) dest.emit('unpipe', this, unpipeInfo);
return this;
}
// slow case. multiple pipe destinations.
if (!dest) {
// remove all.
var dests = state.pipes;
var len = state.pipesCount;
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
for (var i = 0; i < len; i++) {
dests[i].emit('unpipe', this, unpipeInfo);
}return this;
}
// try to find the right one.
var index = indexOf(state.pipes, dest);
if (index === -1) return this;
state.pipes.splice(index, 1);
state.pipesCount -= 1;
if (state.pipesCount === 1) state.pipes = state.pipes[0];
dest.emit('unpipe', this, unpipeInfo);
return this;
};
// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function (ev, fn) {
var res = Stream.prototype.on.call(this, ev, fn);
if (ev === 'data') {
// Start flowing on next tick if stream isn't explicitly paused
if (this._readableState.flowing !== false) this.resume();
} else if (ev === 'readable') {
var state = this._readableState;
if (!state.endEmitted && !state.readableListening) {
state.readableListening = state.needReadable = true;
state.emittedReadable = false;
if (!state.reading) {
pna.nextTick(nReadingNextTick, this);
} else if (state.length) {
emitReadable(this);
}
}
}
return res;
};
Readable.prototype.addListener = Readable.prototype.on;
function nReadingNextTick(self) {
debug('readable nexttick read 0');
self.read(0);
}
// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function () {
var state = this._readableState;
if (!state.flowing) {
debug('resume');
state.flowing = true;
resume(this, state);
}
return this;
};
function resume(stream, state) {
if (!state.resumeScheduled) {
state.resumeScheduled = true;
pna.nextTick(resume_, stream, state);
}
}
function resume_(stream, state) {
if (!state.reading) {
debug('resume read 0');
stream.read(0);
}
state.resumeScheduled = false;
state.awaitDrain = 0;
stream.emit('resume');
flow(stream);
if (state.flowing && !state.reading) stream.read(0);
}
Readable.prototype.pause = function () {
debug('call pause flowing=%j', this._readableState.flowing);
if (false !== this._readableState.flowing) {
debug('pause');
this._readableState.flowing = false;
this.emit('pause');
}
return this;
};
function flow(stream) {
var state = stream._readableState;
debug('flow', state.flowing);
while (state.flowing && stream.read() !== null) {}
}
// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function (stream) {
var _this = this;
var state = this._readableState;
var paused = false;
stream.on('end', function () {
debug('wrapped end');
if (state.decoder && !state.ended) {
var chunk = state.decoder.end();
if (chunk && chunk.length) _this.push(chunk);
}
_this.push(null);
});
stream.on('data', function (chunk) {
debug('wrapped data');
if (state.decoder) chunk = state.decoder.write(chunk);
// don't skip over falsy values in objectMode
if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
var ret = _this.push(chunk);
if (!ret) {
paused = true;
stream.pause();
}
});
// proxy all the other methods.
// important when wrapping filters and duplexes.
for (var i in stream) {
if (this[i] === undefined && typeof stream[i] === 'function') {
this[i] = function (method) {
return function () {
return stream[method].apply(stream, arguments);
};
}(i);
}
}
// proxy certain important events.
for (var n = 0; n < kProxyEvents.length; n++) {
stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
}
// when we try to consume some more bytes, simply unpause the
// underlying stream.
this._read = function (n) {
debug('wrapped _read', n);
if (paused) {
paused = false;
stream.resume();
}
};
return this;
};
Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
return this._readableState.highWaterMark;
}
});
// exposed for testing purposes only.
Readable._fromList = fromList;
// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromList(n, state) {
// nothing buffered
if (state.length === 0) return null;
var ret;
if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
// read it all, truncate the list
if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
state.buffer.clear();
} else {
// read part of list
ret = fromListPartial(n, state.buffer, state.decoder);
}
return ret;
}
// Extracts only enough buffered data to satisfy the amount requested.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromListPartial(n, list, hasStrings) {
var ret;
if (n < list.head.data.length) {
// slice is the same for buffers and strings
ret = list.head.data.slice(0, n);
list.head.data = list.head.data.slice(n);
} else if (n === list.head.data.length) {
// first chunk is a perfect match
ret = list.shift();
} else {
// result spans more than one buffer
ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
}
return ret;
}
// Copies a specified amount of characters from the list of buffered data
// chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBufferString(n, list) {
var p = list.head;
var c = 1;
var ret = p.data;
n -= ret.length;
while (p = p.next) {
var str = p.data;
var nb = n > str.length ? str.length : n;
if (nb === str.length) ret += str;else ret += str.slice(0, n);
n -= nb;
if (n === 0) {
if (nb === str.length) {
++c;
if (p.next) list.head = p.next;else list.head = list.tail = null;
} else {
list.head = p;
p.data = str.slice(nb);
}
break;
}
++c;
}
list.length -= c;
return ret;
}
// Copies a specified amount of bytes from the list of buffered data chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBuffer(n, list) {
var ret = Buffer.allocUnsafe(n);
var p = list.head;
var c = 1;
p.data.copy(ret);
n -= p.data.length;
while (p = p.next) {
var buf = p.data;
var nb = n > buf.length ? buf.length : n;
buf.copy(ret, ret.length - n, 0, nb);
n -= nb;
if (n === 0) {
if (nb === buf.length) {
++c;
if (p.next) list.head = p.next;else list.head = list.tail = null;
} else {
list.head = p;
p.data = buf.slice(nb);
}
break;
}
++c;
}
list.length -= c;
return ret;
}
function endReadable(stream) {
var state = stream._readableState;
// If we get here before consuming all the bytes, then that is a
// bug in node. Should never happen.
if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
if (!state.endEmitted) {
state.ended = true;
pna.nextTick(endReadableNT, state, stream);
}
}
function endReadableNT(state, stream) {
// Check that we didn't get one last unshift.
if (!state.endEmitted && state.length === 0) {
state.endEmitted = true;
stream.readable = false;
stream.emit('end');
}
}
function indexOf(xs, x) {
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) return i;
}
return -1;
}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./_stream_duplex":214,"./internal/streams/BufferList":219,"./internal/streams/destroy":220,"./internal/streams/stream":221,"_process":208,"babel-runtime/core-js/object/create":55,"babel-runtime/core-js/object/get-prototype-of":59,"core-util-is":189,"events":192,"inherits":196,"isarray":198,"process-nextick-args":207,"safe-buffer":228,"string_decoder/":235,"util":71}],217:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node 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.
// a transform stream is a readable/writable stream where you do
// something with the data. Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored. (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation. For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes. When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up. When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer. When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks. If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk. However,
// a pathological inflate type of transform can cause excessive buffering
// here. For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output. In this case, you could write a very small
// amount of input, and end up with a very large amount of output. In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform. A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.
'use strict';
var _create = require('babel-runtime/core-js/object/create');
var _create2 = _interopRequireDefault(_create);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
module.exports = Transform;
var Duplex = require('./_stream_duplex');
/*<replacement>*/
var util = (0, _create2.default)(require('core-util-is'));
util.inherits = require('inherits');
/*</replacement>*/
util.inherits(Transform, Duplex);
function afterTransform(er, data) {
var ts = this._transformState;
ts.transforming = false;
var cb = ts.writecb;
if (!cb) {
return this.emit('error', new Error('write callback called multiple times'));
}
ts.writechunk = null;
ts.writecb = null;
if (data != null) // single equals check for both `null` and `undefined`
this.push(data);
cb(er);
var rs = this._readableState;
rs.reading = false;
if (rs.needReadable || rs.length < rs.highWaterMark) {
this._read(rs.highWaterMark);
}
}
function Transform(options) {
if (!(this instanceof Transform)) return new Transform(options);
Duplex.call(this, options);
this._transformState = {
afterTransform: afterTransform.bind(this),
needTransform: false,
transforming: false,
writecb: null,
writechunk: null,
writeencoding: null
};
// start out asking for a readable event once data is transformed.
this._readableState.needReadable = true;
// we have implemented the _read method, and done the other things
// that Readable wants before the first _read call, so unset the
// sync guard flag.
this._readableState.sync = false;
if (options) {
if (typeof options.transform === 'function') this._transform = options.transform;
if (typeof options.flush === 'function') this._flush = options.flush;
}
// When the writable side finishes, then flush out anything remaining.
this.on('prefinish', prefinish);
}
function prefinish() {
var _this = this;
if (typeof this._flush === 'function') {
this._flush(function (er, data) {
done(_this, er, data);
});
} else {
done(this, null, null);
}
}
Transform.prototype.push = function (chunk, encoding) {
this._transformState.needTransform = false;
return Duplex.prototype.push.call(this, chunk, encoding);
};
// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side. You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk. If you pass
// an error, then that'll put the hurt on the whole operation. If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function (chunk, encoding, cb) {
throw new Error('_transform() is not implemented');
};
Transform.prototype._write = function (chunk, encoding, cb) {
var ts = this._transformState;
ts.writecb = cb;
ts.writechunk = chunk;
ts.writeencoding = encoding;
if (!ts.transforming) {
var rs = this._readableState;
if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
}
};
// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function (n) {
var ts = this._transformState;
if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
ts.transforming = true;
this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
} else {
// mark that we need a transform, so that any data that comes in
// will get processed, now that we've asked for it.
ts.needTransform = true;
}
};
Transform.prototype._destroy = function (err, cb) {
var _this2 = this;
Duplex.prototype._destroy.call(this, err, function (err2) {
cb(err2);
_this2.emit('close');
});
};
function done(stream, er, data) {
if (er) return stream.emit('error', er);
if (data != null) // single equals check for both `null` and `undefined`
stream.push(data);
// if there's nothing in the write buffer, then that means
// that nothing more will ever be provided
if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
return stream.push(null);
}
},{"./_stream_duplex":214,"babel-runtime/core-js/object/create":55,"core-util-is":189,"inherits":196}],218:[function(require,module,exports){
(function (process,global){
// Copyright Joyent, Inc. and other Node 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.
// A bit simpler than readable streams.
// Implement an async ._write(chunk, encoding, cb), and it'll handle all
// the drain event emission and buffering.
'use strict';
/*<replacement>*/
var _defineProperty = require('babel-runtime/core-js/object/define-property');
var _defineProperty2 = _interopRequireDefault(_defineProperty);
var _hasInstance = require('babel-runtime/core-js/symbol/has-instance');
var _hasInstance2 = _interopRequireDefault(_hasInstance);
var _symbol = require('babel-runtime/core-js/symbol');
var _symbol2 = _interopRequireDefault(_symbol);
var _create = require('babel-runtime/core-js/object/create');
var _create2 = _interopRequireDefault(_create);
var _setImmediate2 = require('babel-runtime/core-js/set-immediate');
var _setImmediate3 = _interopRequireDefault(_setImmediate2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var pna = require('process-nextick-args');
/*</replacement>*/
module.exports = Writable;
/* <replacement> */
function WriteReq(chunk, encoding, cb) {
this.chunk = chunk;
this.encoding = encoding;
this.callback = cb;
this.next = null;
}
// It seems a linked list but it is not
// there will be only 2 of these for each stream
function CorkedRequest(state) {
var _this = this;
this.next = null;
this.entry = null;
this.finish = function () {
onCorkedFinish(_this, state);
};
}
/* </replacement> */
/*<replacement>*/
var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? _setImmediate3.default : pna.nextTick;
/*</replacement>*/
/*<replacement>*/
var Duplex;
/*</replacement>*/
Writable.WritableState = WritableState;
/*<replacement>*/
var util = (0, _create2.default)(require('core-util-is'));
util.inherits = require('inherits');
/*</replacement>*/
/*<replacement>*/
var internalUtil = {
deprecate: require('util-deprecate')
};
/*</replacement>*/
/*<replacement>*/
var Stream = require('./internal/streams/stream');
/*</replacement>*/
/*<replacement>*/
var Buffer = require('safe-buffer').Buffer;
var OurUint8Array = global.Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
return Buffer.from(chunk);
}
function _isUint8Array(obj) {
return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}
/*</replacement>*/
var destroyImpl = require('./internal/streams/destroy');
util.inherits(Writable, Stream);
function nop() {}
function WritableState(options, stream) {
Duplex = Duplex || require('./_stream_duplex');
options = options || {};
// Duplex streams are both readable and writable, but share
// the same options object.
// However, some cases require setting options to different
// values for the readable and the writable sides of the duplex stream.
// These options can be provided separately as readableXXX and writableXXX.
var isDuplex = stream instanceof Duplex;
// object stream flag to indicate whether or not this stream
// contains buffers or objects.
this.objectMode = !!options.objectMode;
if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
// the point at which write() starts returning false
// Note: 0 is a valid value, means that we always return false if
// the entire buffer is not flushed immediately on write()
var hwm = options.highWaterMark;
var writableHwm = options.writableHighWaterMark;
var defaultHwm = this.objectMode ? 16 : 16 * 1024;
if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
// cast to ints.
this.highWaterMark = Math.floor(this.highWaterMark);
// if _final has been called
this.finalCalled = false;
// drain event flag.
this.needDrain = false;
// at the start of calling end()
this.ending = false;
// when end() has been called, and returned
this.ended = false;
// when 'finish' is emitted
this.finished = false;
// has it been destroyed
this.destroyed = false;
// should we decode strings into buffers before passing to _write?
// this is here so that some node-core streams can optimize string
// handling at a lower level.
var noDecode = options.decodeStrings === false;
this.decodeStrings = !noDecode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// not an actual buffer we keep track of, but a measurement
// of how much we're waiting to get pushed to some underlying
// socket or file.
this.length = 0;
// a flag to see when we're in the middle of a write.
this.writing = false;
// when true all writes will be buffered until .uncork() call
this.corked = 0;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// a flag to know if we're processing previously buffered items, which
// may call the _write() callback in the same tick, so that we don't
// end up in an overlapped onwrite situation.
this.bufferProcessing = false;
// the callback that's passed to _write(chunk,cb)
this.onwrite = function (er) {
onwrite(stream, er);
};
// the callback that the user supplies to write(chunk,encoding,cb)
this.writecb = null;
// the amount that is being written when _write is called.
this.writelen = 0;
this.bufferedRequest = null;
this.lastBufferedRequest = null;
// number of pending user-supplied write callbacks
// this must be 0 before 'finish' can be emitted
this.pendingcb = 0;
// emit prefinish if the only thing we're waiting for is _write cbs
// This is relevant for synchronous Transform streams
this.prefinished = false;
// True if the error was already emitted and should not be thrown again
this.errorEmitted = false;
// count buffered requests
this.bufferedRequestCount = 0;
// allocate the first CorkedRequest, there is always
// one allocated and free to use, and we maintain at most two
this.corkedRequestsFree = new CorkedRequest(this);
}
WritableState.prototype.getBuffer = function getBuffer() {
var current = this.bufferedRequest;
var out = [];
while (current) {
out.push(current);
current = current.next;
}
return out;
};
(function () {
try {
Object.defineProperty(WritableState.prototype, 'buffer', {
get: internalUtil.deprecate(function () {
return this.getBuffer();
}, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
});
} catch (_) {}
})();
// Test _writableState for inheritance to account for Duplex streams,
// whose prototype chain only points to Readable.
var realHasInstance;
if (typeof _symbol2.default === 'function' && _hasInstance2.default && typeof Function.prototype[_hasInstance2.default] === 'function') {
realHasInstance = Function.prototype[_hasInstance2.default];
(0, _defineProperty2.default)(Writable, _hasInstance2.default, {
value: function value(object) {
if (realHasInstance.call(this, object)) return true;
if (this !== Writable) return false;
return object && object._writableState instanceof WritableState;
}
});
} else {
realHasInstance = function realHasInstance(object) {
return object instanceof this;
};
}
function Writable(options) {
Duplex = Duplex || require('./_stream_duplex');
// Writable ctor is applied to Duplexes, too.
// `realHasInstance` is necessary because using plain `instanceof`
// would return false, as no `_writableState` property is attached.
// Trying to use the custom `instanceof` for Writable here will also break the
// Node.js LazyTransform implementation, which has a non-trivial getter for
// `_writableState` that would lead to infinite recursion.
if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
return new Writable(options);
}
this._writableState = new WritableState(options, this);
// legacy.
this.writable = true;
if (options) {
if (typeof options.write === 'function') this._write = options.write;
if (typeof options.writev === 'function') this._writev = options.writev;
if (typeof options.destroy === 'function') this._destroy = options.destroy;
if (typeof options.final === 'function') this._final = options.final;
}
Stream.call(this);
}
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function () {
this.emit('error', new Error('Cannot pipe, not readable'));
};
function writeAfterEnd(stream, cb) {
var er = new Error('write after end');
// TODO: defer error events consistently everywhere, not just the cb
stream.emit('error', er);
pna.nextTick(cb, er);
}
// Checks that a user-supplied chunk is valid, especially for the particular
// mode the stream is in. Currently this means that `null` is never accepted
// and undefined/non-string values are only allowed in object mode.
function validChunk(stream, state, chunk, cb) {
var valid = true;
var er = false;
if (chunk === null) {
er = new TypeError('May not write null values to stream');
} else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
if (er) {
stream.emit('error', er);
pna.nextTick(cb, er);
valid = false;
}
return valid;
}
Writable.prototype.write = function (chunk, encoding, cb) {
var state = this._writableState;
var ret = false;
var isBuf = !state.objectMode && _isUint8Array(chunk);
if (isBuf && !Buffer.isBuffer(chunk)) {
chunk = _uint8ArrayToBuffer(chunk);
}
if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
if (typeof cb !== 'function') cb = nop;
if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
state.pendingcb++;
ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
}
return ret;
};
Writable.prototype.cork = function () {
var state = this._writableState;
state.corked++;
};
Writable.prototype.uncork = function () {
var state = this._writableState;
if (state.corked) {
state.corked--;
if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
}
};
Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
// node::ParseEncoding() requires lower case.
if (typeof encoding === 'string') encoding = encoding.toLowerCase();
if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
this._writableState.defaultEncoding = encoding;
return this;
};
function decodeChunk(state, chunk, encoding) {
if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
chunk = Buffer.from(chunk, encoding);
}
return chunk;
}
Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
return this._writableState.highWaterMark;
}
});
// if we're already writing something, then just put this
// in the queue, and wait our turn. Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
if (!isBuf) {
var newChunk = decodeChunk(state, chunk, encoding);
if (chunk !== newChunk) {
isBuf = true;
encoding = 'buffer';
chunk = newChunk;
}
}
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
// we must ensure that previous needDrain will not be reset to false.
if (!ret) state.needDrain = true;
if (state.writing || state.corked) {
var last = state.lastBufferedRequest;
state.lastBufferedRequest = {
chunk: chunk,
encoding: encoding,
isBuf: isBuf,
callback: cb,
next: null
};
if (last) {
last.next = state.lastBufferedRequest;
} else {
state.bufferedRequest = state.lastBufferedRequest;
}
state.bufferedRequestCount += 1;
} else {
doWrite(stream, state, false, len, chunk, encoding, cb);
}
return ret;
}
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
state.writelen = len;
state.writecb = cb;
state.writing = true;
state.sync = true;
if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
--state.pendingcb;
if (sync) {
// defer the callback if we are being called synchronously
// to avoid piling up things on the stack
pna.nextTick(cb, er);
// this can emit finish, and it will always happen
// after error
pna.nextTick(finishMaybe, stream, state);
stream._writableState.errorEmitted = true;
stream.emit('error', er);
} else {
// the caller expect this to happen before if
// it is async
cb(er);
stream._writableState.errorEmitted = true;
stream.emit('error', er);
// this can emit finish, but finish must
// always follow error
finishMaybe(stream, state);
}
}
function onwriteStateUpdate(state) {
state.writing = false;
state.writecb = null;
state.length -= state.writelen;
state.writelen = 0;
}
function onwrite(stream, er) {
var state = stream._writableState;
var sync = state.sync;
var cb = state.writecb;
onwriteStateUpdate(state);
if (er) onwriteError(stream, state, sync, er, cb);else {
// Check if we're actually ready to finish, but don't emit yet
var finished = needFinish(state);
if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
clearBuffer(stream, state);
}
if (sync) {
/*<replacement>*/
asyncWrite(afterWrite, stream, state, finished, cb);
/*</replacement>*/
} else {
afterWrite(stream, state, finished, cb);
}
}
}
function afterWrite(stream, state, finished, cb) {
if (!finished) onwriteDrain(stream, state);
state.pendingcb--;
cb();
finishMaybe(stream, state);
}
// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
if (state.length === 0 && state.needDrain) {
state.needDrain = false;
stream.emit('drain');
}
}
// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
state.bufferProcessing = true;
var entry = state.bufferedRequest;
if (stream._writev && entry && entry.next) {
// Fast case, write everything using _writev()
var l = state.bufferedRequestCount;
var buffer = new Array(l);
var holder = state.corkedRequestsFree;
holder.entry = entry;
var count = 0;
var allBuffers = true;
while (entry) {
buffer[count] = entry;
if (!entry.isBuf) allBuffers = false;
entry = entry.next;
count += 1;
}
buffer.allBuffers = allBuffers;
doWrite(stream, state, true, state.length, buffer, '', holder.finish);
// doWrite is almost always async, defer these to save a bit of time
// as the hot path ends with doWrite
state.pendingcb++;
state.lastBufferedRequest = null;
if (holder.next) {
state.corkedRequestsFree = holder.next;
holder.next = null;
} else {
state.corkedRequestsFree = new CorkedRequest(state);
}
state.bufferedRequestCount = 0;
} else {
// Slow case, write chunks one-by-one
while (entry) {
var chunk = entry.chunk;
var encoding = entry.encoding;
var cb = entry.callback;
var len = state.objectMode ? 1 : chunk.length;
doWrite(stream, state, false, len, chunk, encoding, cb);
entry = entry.next;
state.bufferedRequestCount--;
// if we didn't call the onwrite immediately, then
// it means that we need to wait until it does.
// also, that means that the chunk and cb are currently
// being processed, so move the buffer counter past them.
if (state.writing) {
break;
}
}
if (entry === null) state.lastBufferedRequest = null;
}
state.bufferedRequest = entry;
state.bufferProcessing = false;
}
Writable.prototype._write = function (chunk, encoding, cb) {
cb(new Error('_write() is not implemented'));
};
Writable.prototype._writev = null;
Writable.prototype.end = function (chunk, encoding, cb) {
var state = this._writableState;
if (typeof chunk === 'function') {
cb = chunk;
chunk = null;
encoding = null;
} else if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
// .end() fully uncorks
if (state.corked) {
state.corked = 1;
this.uncork();
}
// ignore unnecessary end() calls.
if (!state.ending && !state.finished) endWritable(this, state, cb);
};
function needFinish(state) {
return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
}
function callFinal(stream, state) {
stream._final(function (err) {
state.pendingcb--;
if (err) {
stream.emit('error', err);
}
state.prefinished = true;
stream.emit('prefinish');
finishMaybe(stream, state);
});
}
function prefinish(stream, state) {
if (!state.prefinished && !state.finalCalled) {
if (typeof stream._final === 'function') {
state.pendingcb++;
state.finalCalled = true;
pna.nextTick(callFinal, stream, state);
} else {
state.prefinished = true;
stream.emit('prefinish');
}
}
}
function finishMaybe(stream, state) {
var need = needFinish(state);
if (need) {
prefinish(stream, state);
if (state.pendingcb === 0) {
state.finished = true;
stream.emit('finish');
}
}
return need;
}
function endWritable(stream, state, cb) {
state.ending = true;
finishMaybe(stream, state);
if (cb) {
if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
}
state.ended = true;
stream.writable = false;
}
function onCorkedFinish(corkReq, state, err) {
var entry = corkReq.entry;
corkReq.entry = null;
while (entry) {
var cb = entry.callback;
state.pendingcb--;
cb(err);
entry = entry.next;
}
if (state.corkedRequestsFree) {
state.corkedRequestsFree.next = corkReq;
} else {
state.corkedRequestsFree = corkReq;
}
}
Object.defineProperty(Writable.prototype, 'destroyed', {
get: function get() {
if (this._writableState === undefined) {
return false;
}
return this._writableState.destroyed;
},
set: function set(value) {
// we ignore the value if the stream
// has not been initialized yet
if (!this._writableState) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._writableState.destroyed = value;
}
});
Writable.prototype.destroy = destroyImpl.destroy;
Writable.prototype._undestroy = destroyImpl.undestroy;
Writable.prototype._destroy = function (err, cb) {
this.end();
cb(err);
};
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./_stream_duplex":214,"./internal/streams/destroy":220,"./internal/streams/stream":221,"_process":208,"babel-runtime/core-js/object/create":55,"babel-runtime/core-js/object/define-property":56,"babel-runtime/core-js/set-immediate":62,"babel-runtime/core-js/symbol":64,"babel-runtime/core-js/symbol/has-instance":65,"core-util-is":189,"inherits":196,"process-nextick-args":207,"safe-buffer":228,"util-deprecate":240}],219:[function(require,module,exports){
'use strict';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var Buffer = require('safe-buffer').Buffer;
var util = require('util');
function copyBuffer(src, target, offset) {
src.copy(target, offset);
}
module.exports = function () {
function BufferList() {
_classCallCheck(this, BufferList);
this.head = null;
this.tail = null;
this.length = 0;
}
BufferList.prototype.push = function push(v) {
var entry = { data: v, next: null };
if (this.length > 0) this.tail.next = entry;else this.head = entry;
this.tail = entry;
++this.length;
};
BufferList.prototype.unshift = function unshift(v) {
var entry = { data: v, next: this.head };
if (this.length === 0) this.tail = entry;
this.head = entry;
++this.length;
};
BufferList.prototype.shift = function shift() {
if (this.length === 0) return;
var ret = this.head.data;
if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
--this.length;
return ret;
};
BufferList.prototype.clear = function clear() {
this.head = this.tail = null;
this.length = 0;
};
BufferList.prototype.join = function join(s) {
if (this.length === 0) return '';
var p = this.head;
var ret = '' + p.data;
while (p = p.next) {
ret += s + p.data;
}return ret;
};
BufferList.prototype.concat = function concat(n) {
if (this.length === 0) return Buffer.alloc(0);
if (this.length === 1) return this.head.data;
var ret = Buffer.allocUnsafe(n >>> 0);
var p = this.head;
var i = 0;
while (p) {
copyBuffer(p.data, ret, i);
i += p.data.length;
p = p.next;
}
return ret;
};
return BufferList;
}();
if (util && util.inspect && util.inspect.custom) {
module.exports.prototype[util.inspect.custom] = function () {
var obj = util.inspect({ length: this.length });
return this.constructor.name + ' ' + obj;
};
}
},{"safe-buffer":228,"util":71}],220:[function(require,module,exports){
'use strict';
/*<replacement>*/
var pna = require('process-nextick-args');
/*</replacement>*/
// undocumented cb() API, needed for core, not for public API
function destroy(err, cb) {
var _this = this;
var readableDestroyed = this._readableState && this._readableState.destroyed;
var writableDestroyed = this._writableState && this._writableState.destroyed;
if (readableDestroyed || writableDestroyed) {
if (cb) {
cb(err);
} else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
pna.nextTick(emitErrorNT, this, err);
}
return this;
}
// we set destroyed to true before firing error callbacks in order
// to make it re-entrance safe in case destroy() is called within callbacks
if (this._readableState) {
this._readableState.destroyed = true;
}
// if this is a duplex stream mark the writable part as destroyed as well
if (this._writableState) {
this._writableState.destroyed = true;
}
this._destroy(err || null, function (err) {
if (!cb && err) {
pna.nextTick(emitErrorNT, _this, err);
if (_this._writableState) {
_this._writableState.errorEmitted = true;
}
} else if (cb) {
cb(err);
}
});
return this;
}
function undestroy() {
if (this._readableState) {
this._readableState.destroyed = false;
this._readableState.reading = false;
this._readableState.ended = false;
this._readableState.endEmitted = false;
}
if (this._writableState) {
this._writableState.destroyed = false;
this._writableState.ended = false;
this._writableState.ending = false;
this._writableState.finished = false;
this._writableState.errorEmitted = false;
}
}
function emitErrorNT(self, err) {
self.emit('error', err);
}
module.exports = {
destroy: destroy,
undestroy: undestroy
};
},{"process-nextick-args":207}],221:[function(require,module,exports){
'use strict';
module.exports = require('events').EventEmitter;
},{"events":192}],222:[function(require,module,exports){
module.exports = require('./readable').PassThrough
},{"./readable":223}],223:[function(require,module,exports){
exports = module.exports = require('./lib/_stream_readable.js');
exports.Stream = exports;
exports.Readable = exports;
exports.Writable = require('./lib/_stream_writable.js');
exports.Duplex = require('./lib/_stream_duplex.js');
exports.Transform = require('./lib/_stream_transform.js');
exports.PassThrough = require('./lib/_stream_passthrough.js');
},{"./lib/_stream_duplex.js":214,"./lib/_stream_passthrough.js":215,"./lib/_stream_readable.js":216,"./lib/_stream_transform.js":217,"./lib/_stream_writable.js":218}],224:[function(require,module,exports){
module.exports = require('./readable').Transform
},{"./readable":223}],225:[function(require,module,exports){
module.exports = require('./lib/_stream_writable.js');
},{"./lib/_stream_writable.js":218}],226:[function(require,module,exports){
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// This method of obtaining a reference to the global object needs to be
// kept identical to the way it is obtained in runtime.js
var g = (function() { return this })() || Function("return this")();
// Use `getOwnPropertyNames` because not all browsers support calling
// `hasOwnProperty` on the global `self` object in a worker. See #183.
var hadRuntime = g.regeneratorRuntime &&
Object.getOwnPropertyNames(g).indexOf("regeneratorRuntime") >= 0;
// Save the old regeneratorRuntime in case it needs to be restored later.
var oldRuntime = hadRuntime && g.regeneratorRuntime;
// Force reevalutation of runtime.js.
g.regeneratorRuntime = undefined;
module.exports = require("./runtime");
if (hadRuntime) {
// Restore the original runtime.
g.regeneratorRuntime = oldRuntime;
} else {
// Remove the global property added by runtime.js.
try {
delete g.regeneratorRuntime;
} catch(e) {
g.regeneratorRuntime = undefined;
}
}
},{"./runtime":227}],227:[function(require,module,exports){
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
!(function(global) {
"use strict";
var Op = Object.prototype;
var hasOwn = Op.hasOwnProperty;
var undefined; // More compressible than void 0.
var $Symbol = typeof Symbol === "function" ? Symbol : {};
var iteratorSymbol = $Symbol.iterator || "@@iterator";
var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
var inModule = typeof module === "object";
var runtime = global.regeneratorRuntime;
if (runtime) {
if (inModule) {
// If regeneratorRuntime is defined globally and we're in a module,
// make the exports object identical to regeneratorRuntime.
module.exports = runtime;
}
// Don't bother evaluating the rest of this file if the runtime was
// already defined globally.
return;
}
// Define the runtime globally (as expected by generated code) as either
// module.exports (if we're in a module) or a new, empty object.
runtime = global.regeneratorRuntime = inModule ? module.exports : {};
function wrap(innerFn, outerFn, self, tryLocsList) {
// If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
var generator = Object.create(protoGenerator.prototype);
var context = new Context(tryLocsList || []);
// The ._invoke method unifies the implementations of the .next,
// .throw, and .return methods.
generator._invoke = makeInvokeMethod(innerFn, self, context);
return generator;
}
runtime.wrap = wrap;
// Try/catch helper to minimize deoptimizations. Returns a completion
// record like context.tryEntries[i].completion. This interface could
// have been (and was previously) designed to take a closure to be
// invoked without arguments, but in all the cases we care about we
// already have an existing method we want to call, so there's no need
// to create a new function object. We can even get away with assuming
// the method takes exactly one argument, since that happens to be true
// in every case, so we don't have to touch the arguments object. The
// only additional allocation required is the completion record, which
// has a stable shape and so hopefully should be cheap to allocate.
function tryCatch(fn, obj, arg) {
try {
return { type: "normal", arg: fn.call(obj, arg) };
} catch (err) {
return { type: "throw", arg: err };
}
}
var GenStateSuspendedStart = "suspendedStart";
var GenStateSuspendedYield = "suspendedYield";
var GenStateExecuting = "executing";
var GenStateCompleted = "completed";
// Returning this object from the innerFn has the same effect as
// breaking out of the dispatch switch statement.
var ContinueSentinel = {};
// Dummy constructor functions that we use as the .constructor and
// .constructor.prototype properties for functions that return Generator
// objects. For full spec compliance, you may wish to configure your
// minifier not to mangle the names of these two functions.
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
// This is a polyfill for %IteratorPrototype% for environments that
// don't natively support it.
var IteratorPrototype = {};
IteratorPrototype[iteratorSymbol] = function () {
return this;
};
var getProto = Object.getPrototypeOf;
var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
if (NativeIteratorPrototype &&
NativeIteratorPrototype !== Op &&
hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
// This environment has a native %IteratorPrototype%; use it instead
// of the polyfill.
IteratorPrototype = NativeIteratorPrototype;
}
var Gp = GeneratorFunctionPrototype.prototype =
Generator.prototype = Object.create(IteratorPrototype);
GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
GeneratorFunctionPrototype.constructor = GeneratorFunction;
GeneratorFunctionPrototype[toStringTagSymbol] =
GeneratorFunction.displayName = "GeneratorFunction";
// Helper for defining the .next, .throw, and .return methods of the
// Iterator interface in terms of a single ._invoke method.
function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function(method) {
prototype[method] = function(arg) {
return this._invoke(method, arg);
};
});
}
runtime.isGeneratorFunction = function(genFun) {
var ctor = typeof genFun === "function" && genFun.constructor;
return ctor
? ctor === GeneratorFunction ||
// For the native GeneratorFunction constructor, the best we can
// do is to check its .name property.
(ctor.displayName || ctor.name) === "GeneratorFunction"
: false;
};
runtime.mark = function(genFun) {
if (Object.setPrototypeOf) {
Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
} else {
genFun.__proto__ = GeneratorFunctionPrototype;
if (!(toStringTagSymbol in genFun)) {
genFun[toStringTagSymbol] = "GeneratorFunction";
}
}
genFun.prototype = Object.create(Gp);
return genFun;
};
// Within the body of any async function, `await x` is transformed to
// `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
// `hasOwn.call(value, "__await")` to determine if the yielded value is
// meant to be awaited.
runtime.awrap = function(arg) {
return { __await: arg };
};
function AsyncIterator(generator) {
function invoke(method, arg, resolve, reject) {
var record = tryCatch(generator[method], generator, arg);
if (record.type === "throw") {
reject(record.arg);
} else {
var result = record.arg;
var value = result.value;
if (value &&
typeof value === "object" &&
hasOwn.call(value, "__await")) {
return Promise.resolve(value.__await).then(function(value) {
invoke("next", value, resolve, reject);
}, function(err) {
invoke("throw", err, resolve, reject);
});
}
return Promise.resolve(value).then(function(unwrapped) {
// When a yielded Promise is resolved, its final value becomes
// the .value of the Promise<{value,done}> result for the
// current iteration. If the Promise is rejected, however, the
// result for this iteration will be rejected with the same
// reason. Note that rejections of yielded Promises are not
// thrown back into the generator function, as is the case
// when an awaited Promise is rejected. This difference in
// behavior between yield and await is important, because it
// allows the consumer to decide what to do with the yielded
// rejection (swallow it and continue, manually .throw it back
// into the generator, abandon iteration, whatever). With
// await, by contrast, there is no opportunity to examine the
// rejection reason outside the generator function, so the
// only option is to throw it from the await expression, and
// let the generator function handle the exception.
result.value = unwrapped;
resolve(result);
}, reject);
}
}
var previousPromise;
function enqueue(method, arg) {
function callInvokeWithMethodAndArg() {
return new Promise(function(resolve, reject) {
invoke(method, arg, resolve, reject);
});
}
return previousPromise =
// If enqueue has been called before, then we want to wait until
// all previous Promises have been resolved before calling invoke,
// so that results are always delivered in the correct order. If
// enqueue has not been called before, then it is important to
// call invoke immediately, without waiting on a callback to fire,
// so that the async generator function has the opportunity to do
// any necessary setup in a predictable way. This predictability
// is why the Promise constructor synchronously invokes its
// executor callback, and why async functions synchronously
// execute code before the first await. Since we implement simple
// async functions in terms of async generators, it is especially
// important to get this right, even though it requires care.
previousPromise ? previousPromise.then(
callInvokeWithMethodAndArg,
// Avoid propagating failures to Promises returned by later
// invocations of the iterator.
callInvokeWithMethodAndArg
) : callInvokeWithMethodAndArg();
}
// Define the unified helper method that is used to implement .next,
// .throw, and .return (see defineIteratorMethods).
this._invoke = enqueue;
}
defineIteratorMethods(AsyncIterator.prototype);
AsyncIterator.prototype[asyncIteratorSymbol] = function () {
return this;
};
runtime.AsyncIterator = AsyncIterator;
// Note that simple async functions are implemented on top of
// AsyncIterator objects; they just return a Promise for the value of
// the final result produced by the iterator.
runtime.async = function(innerFn, outerFn, self, tryLocsList) {
var iter = new AsyncIterator(
wrap(innerFn, outerFn, self, tryLocsList)
);
return runtime.isGeneratorFunction(outerFn)
? iter // If outerFn is a generator, return the full iterator.
: iter.next().then(function(result) {
return result.done ? result.value : iter.next();
});
};
function makeInvokeMethod(innerFn, self, context) {
var state = GenStateSuspendedStart;
return function invoke(method, arg) {
if (state === GenStateExecuting) {
throw new Error("Generator is already running");
}
if (state === GenStateCompleted) {
if (method === "throw") {
throw arg;
}
// Be forgiving, per 25.3.3.3.3 of the spec:
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
return doneResult();
}
context.method = method;
context.arg = arg;
while (true) {
var delegate = context.delegate;
if (delegate) {
var delegateResult = maybeInvokeDelegate(delegate, context);
if (delegateResult) {
if (delegateResult === ContinueSentinel) continue;
return delegateResult;
}
}
if (context.method === "next") {
// Setting context._sent for legacy support of Babel's
// function.sent implementation.
context.sent = context._sent = context.arg;
} else if (context.method === "throw") {
if (state === GenStateSuspendedStart) {
state = GenStateCompleted;
throw context.arg;
}
context.dispatchException(context.arg);
} else if (context.method === "return") {
context.abrupt("return", context.arg);
}
state = GenStateExecuting;
var record = tryCatch(innerFn, self, context);
if (record.type === "normal") {
// If an exception is thrown from innerFn, we leave state ===
// GenStateExecuting and loop back for another invocation.
state = context.done
? GenStateCompleted
: GenStateSuspendedYield;
if (record.arg === ContinueSentinel) {
continue;
}
return {
value: record.arg,
done: context.done
};
} else if (record.type === "throw") {
state = GenStateCompleted;
// Dispatch the exception by looping back around to the
// context.dispatchException(context.arg) call above.
context.method = "throw";
context.arg = record.arg;
}
}
};
}
// Call delegate.iterator[context.method](context.arg) and handle the
// result, either by returning a { value, done } result from the
// delegate iterator, or by modifying context.method and context.arg,
// setting context.delegate to null, and returning the ContinueSentinel.
function maybeInvokeDelegate(delegate, context) {
var method = delegate.iterator[context.method];
if (method === undefined) {
// A .throw or .return when the delegate iterator has no .throw
// method always terminates the yield* loop.
context.delegate = null;
if (context.method === "throw") {
if (delegate.iterator.return) {
// If the delegate iterator has a return method, give it a
// chance to clean up.
context.method = "return";
context.arg = undefined;
maybeInvokeDelegate(delegate, context);
if (context.method === "throw") {
// If maybeInvokeDelegate(context) changed context.method from
// "return" to "throw", let that override the TypeError below.
return ContinueSentinel;
}
}
context.method = "throw";
context.arg = new TypeError(
"The iterator does not provide a 'throw' method");
}
return ContinueSentinel;
}
var record = tryCatch(method, delegate.iterator, context.arg);
if (record.type === "throw") {
context.method = "throw";
context.arg = record.arg;
context.delegate = null;
return ContinueSentinel;
}
var info = record.arg;
if (! info) {
context.method = "throw";
context.arg = new TypeError("iterator result is not an object");
context.delegate = null;
return ContinueSentinel;
}
if (info.done) {
// Assign the result of the finished delegate to the temporary
// variable specified by delegate.resultName (see delegateYield).
context[delegate.resultName] = info.value;
// Resume execution at the desired location (see delegateYield).
context.next = delegate.nextLoc;
// If context.method was "throw" but the delegate handled the
// exception, let the outer generator proceed normally. If
// context.method was "next", forget context.arg since it has been
// "consumed" by the delegate iterator. If context.method was
// "return", allow the original .return call to continue in the
// outer generator.
if (context.method !== "return") {
context.method = "next";
context.arg = undefined;
}
} else {
// Re-yield the result returned by the delegate method.
return info;
}
// The delegate iterator is finished, so forget it and continue with
// the outer generator.
context.delegate = null;
return ContinueSentinel;
}
// Define Generator.prototype.{next,throw,return} in terms of the
// unified ._invoke helper method.
defineIteratorMethods(Gp);
Gp[toStringTagSymbol] = "Generator";
// A Generator should always return itself as the iterator object when the
// @@iterator function is called on it. Some browsers' implementations of the
// iterator prototype chain incorrectly implement this, causing the Generator
// object to not be returned from this call. This ensures that doesn't happen.
// See https://github.com/facebook/regenerator/issues/274 for more details.
Gp[iteratorSymbol] = function() {
return this;
};
Gp.toString = function() {
return "[object Generator]";
};
function pushTryEntry(locs) {
var entry = { tryLoc: locs[0] };
if (1 in locs) {
entry.catchLoc = locs[1];
}
if (2 in locs) {
entry.finallyLoc = locs[2];
entry.afterLoc = locs[3];
}
this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal";
delete record.arg;
entry.completion = record;
}
function Context(tryLocsList) {
// The root entry object (effectively a try statement without a catch
// or a finally block) gives us a place to store values thrown from
// locations where there is no enclosing try statement.
this.tryEntries = [{ tryLoc: "root" }];
tryLocsList.forEach(pushTryEntry, this);
this.reset(true);
}
runtime.keys = function(object) {
var keys = [];
for (var key in object) {
keys.push(key);
}
keys.reverse();
// Rather than returning an object with a next method, we keep
// things simple and return the next function itself.
return function next() {
while (keys.length) {
var key = keys.pop();
if (key in object) {
next.value = key;
next.done = false;
return next;
}
}
// To avoid creating an additional object, we just hang the .value
// and .done properties off the next function object itself. This
// also ensures that the minifier will not anonymize the function.
next.done = true;
return next;
};
};
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) {
return iteratorMethod.call(iterable);
}
if (typeof iterable.next === "function") {
return iterable;
}
if (!isNaN(iterable.length)) {
var i = -1, next = function next() {
while (++i < iterable.length) {
if (hasOwn.call(iterable, i)) {
next.value = iterable[i];
next.done = false;
return next;
}
}
next.value = undefined;
next.done = true;
return next;
};
return next.next = next;
}
}
// Return an iterator with no values.
return { next: doneResult };
}
runtime.values = values;
function doneResult() {
return { value: undefined, done: true };
}
Context.prototype = {
constructor: Context,
reset: function(skipTempReset) {
this.prev = 0;
this.next = 0;
// Resetting context._sent for legacy support of Babel's
// function.sent implementation.
this.sent = this._sent = undefined;
this.done = false;
this.delegate = null;
this.method = "next";
this.arg = undefined;
this.tryEntries.forEach(resetTryEntry);
if (!skipTempReset) {
for (var name in this) {
// Not sure about the optimal order of these conditions:
if (name.charAt(0) === "t" &&
hasOwn.call(this, name) &&
!isNaN(+name.slice(1))) {
this[name] = undefined;
}
}
}
},
stop: function() {
this.done = true;
var rootEntry = this.tryEntries[0];
var rootRecord = rootEntry.completion;
if (rootRecord.type === "throw") {
throw rootRecord.arg;
}
return this.rval;
},
dispatchException: function(exception) {
if (this.done) {
throw exception;
}
var context = this;
function handle(loc, caught) {
record.type = "throw";
record.arg = exception;
context.next = loc;
if (caught) {
// If the dispatched exception was caught by a catch block,
// then let that catch block handle the exception normally.
context.method = "next";
context.arg = undefined;
}
return !! caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
var record = entry.completion;
if (entry.tryLoc === "root") {
// Exception thrown outside of any try block that could handle
// it, so set the completion value of the entire function to
// throw the exception.
return handle("end");
}
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc");
var hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
} else if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else if (hasCatch) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
}
} else if (hasFinally) {
if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else {
throw new Error("try statement without catch or finally");
}
}
}
},
abrupt: function(type, arg) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev &&
hasOwn.call(entry, "finallyLoc") &&
this.prev < entry.finallyLoc) {
var finallyEntry = entry;
break;
}
}
if (finallyEntry &&
(type === "break" ||
type === "continue") &&
finallyEntry.tryLoc <= arg &&
arg <= finallyEntry.finallyLoc) {
// Ignore the finally entry if control is not jumping to a
// location outside the try/catch block.
finallyEntry = null;
}
var record = finallyEntry ? finallyEntry.completion : {};
record.type = type;
record.arg = arg;
if (finallyEntry) {
this.method = "next";
this.next = finallyEntry.finallyLoc;
return ContinueSentinel;
}
return this.complete(record);
},
complete: function(record, afterLoc) {
if (record.type === "throw") {
throw record.arg;
}
if (record.type === "break" ||
record.type === "continue") {
this.next = record.arg;
} else if (record.type === "return") {
this.rval = this.arg = record.arg;
this.method = "return";
this.next = "end";
} else if (record.type === "normal" && afterLoc) {
this.next = afterLoc;
}
return ContinueSentinel;
},
finish: function(finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) {
this.complete(entry.completion, entry.afterLoc);
resetTryEntry(entry);
return ContinueSentinel;
}
}
},
"catch": function(tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if (record.type === "throw") {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
}
// The context.catch method must only be called with a location
// argument that corresponds to a known catch block.
throw new Error("illegal catch attempt");
},
delegateYield: function(iterable, resultName, nextLoc) {
this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc
};
if (this.method === "next") {
// Deliberately forget the last sent value so that we don't
// accidentally pass it on to the delegate.
this.arg = undefined;
}
return ContinueSentinel;
}
};
})(
// In sloppy mode, unbound `this` refers to the global object, fallback to
// Function constructor if we're in global strict mode. That is sadly a form
// of indirect eval which violates Content Security Policy.
(function() { return this })() || Function("return this")()
);
},{}],228:[function(require,module,exports){
/* eslint-disable node/no-deprecated-api */
var buffer = require('buffer')
var Buffer = buffer.Buffer
// alternative to using Object.keys for old browsers
function copyProps (src, dst) {
for (var key in src) {
dst[key] = src[key]
}
}
if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
module.exports = buffer
} else {
// Copy properties from require('buffer')
copyProps(buffer, exports)
exports.Buffer = SafeBuffer
}
function SafeBuffer (arg, encodingOrOffset, length) {
return Buffer(arg, encodingOrOffset, length)
}
// Copy static methods from Buffer
copyProps(Buffer, SafeBuffer)
SafeBuffer.from = function (arg, encodingOrOffset, length) {
if (typeof arg === 'number') {
throw new TypeError('Argument must not be a number')
}
return Buffer(arg, encodingOrOffset, length)
}
SafeBuffer.alloc = function (size, fill, encoding) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
var buf = Buffer(size)
if (fill !== undefined) {
if (typeof encoding === 'string') {
buf.fill(fill, encoding)
} else {
buf.fill(fill)
}
} else {
buf.fill(0)
}
return buf
}
SafeBuffer.allocUnsafe = function (size) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
return Buffer(size)
}
SafeBuffer.allocUnsafeSlow = function (size) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
return buffer.SlowBuffer(size)
}
},{"buffer":73}],229:[function(require,module,exports){
(function (Buffer){
'use strict';
var _fromCodePoint = require('babel-runtime/core-js/string/from-code-point');
var _fromCodePoint2 = _interopRequireDefault(_fromCodePoint);
var _stringify = require('babel-runtime/core-js/json/stringify');
var _stringify2 = _interopRequireDefault(_stringify);
var _typeof2 = require('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
var _defineProperty = require('babel-runtime/core-js/object/define-property');
var _defineProperty2 = _interopRequireDefault(_defineProperty);
var _keys = require('babel-runtime/core-js/object/keys');
var _keys2 = _interopRequireDefault(_keys);
var _create = require('babel-runtime/core-js/object/create');
var _create2 = _interopRequireDefault(_create);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
;(function (sax) {
// wrapper for non-node envs
sax.parser = function (strict, opt) {
return new SAXParser(strict, opt);
};
sax.SAXParser = SAXParser;
sax.SAXStream = SAXStream;
sax.createStream = createStream;
// When we pass the MAX_BUFFER_LENGTH position, start checking for buffer overruns.
// When we check, schedule the next check for MAX_BUFFER_LENGTH - (max(buffer lengths)),
// since that's the earliest that a buffer overrun could occur. This way, checks are
// as rare as required, but as often as necessary to ensure never crossing this bound.
// Furthermore, buffers are only tested at most once per write(), so passing a very
// large string into write() might have undesirable effects, but this is manageable by
// the caller, so it is assumed to be safe. Thus, a call to write() may, in the extreme
// edge case, result in creating at most one complete copy of the string passed in.
// Set to Infinity to have unlimited buffers.
sax.MAX_BUFFER_LENGTH = 64 * 1024;
var buffers = ['comment', 'sgmlDecl', 'textNode', 'tagName', 'doctype', 'procInstName', 'procInstBody', 'entity', 'attribName', 'attribValue', 'cdata', 'script'];
sax.EVENTS = ['text', 'processinginstruction', 'sgmldeclaration', 'doctype', 'comment', 'opentagstart', 'attribute', 'opentag', 'closetag', 'opencdata', 'cdata', 'closecdata', 'error', 'end', 'ready', 'script', 'opennamespace', 'closenamespace'];
function SAXParser(strict, opt) {
if (!(this instanceof SAXParser)) {
return new SAXParser(strict, opt);
}
var parser = this;
clearBuffers(parser);
parser.q = parser.c = '';
parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH;
parser.opt = opt || {};
parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags;
parser.looseCase = parser.opt.lowercase ? 'toLowerCase' : 'toUpperCase';
parser.tags = [];
parser.closed = parser.closedRoot = parser.sawRoot = false;
parser.tag = parser.error = null;
parser.strict = !!strict;
parser.noscript = !!(strict || parser.opt.noscript);
parser.state = S.BEGIN;
parser.strictEntities = parser.opt.strictEntities;
parser.ENTITIES = parser.strictEntities ? (0, _create2.default)(sax.XML_ENTITIES) : (0, _create2.default)(sax.ENTITIES);
parser.attribList = [];
// namespaces form a prototype chain.
// it always points at the current tag,
// which protos to its parent tag.
if (parser.opt.xmlns) {
parser.ns = (0, _create2.default)(rootNS);
}
// mostly just for error reporting
parser.trackPosition = parser.opt.position !== false;
if (parser.trackPosition) {
parser.position = parser.line = parser.column = 0;
}
emit(parser, 'onready');
}
if (!_create2.default) {
Object.create = function (o) {
function F() {}
F.prototype = o;
var newf = new F();
return newf;
};
}
if (!_keys2.default) {
Object.keys = function (o) {
var a = [];
for (var i in o) {
if (o.hasOwnProperty(i)) a.push(i);
}return a;
};
}
function checkBufferLength(parser) {
var maxAllowed = Math.max(sax.MAX_BUFFER_LENGTH, 10);
var maxActual = 0;
for (var i = 0, l = buffers.length; i < l; i++) {
var len = parser[buffers[i]].length;
if (len > maxAllowed) {
// Text/cdata nodes can get big, and since they're buffered,
// we can get here under normal conditions.
// Avoid issues by emitting the text node now,
// so at least it won't get any bigger.
switch (buffers[i]) {
case 'textNode':
closeText(parser);
break;
case 'cdata':
emitNode(parser, 'oncdata', parser.cdata);
parser.cdata = '';
break;
case 'script':
emitNode(parser, 'onscript', parser.script);
parser.script = '';
break;
default:
error(parser, 'Max buffer length exceeded: ' + buffers[i]);
}
}
maxActual = Math.max(maxActual, len);
}
// schedule the next check for the earliest possible buffer overrun.
var m = sax.MAX_BUFFER_LENGTH - maxActual;
parser.bufferCheckPosition = m + parser.position;
}
function clearBuffers(parser) {
for (var i = 0, l = buffers.length; i < l; i++) {
parser[buffers[i]] = '';
}
}
function flushBuffers(parser) {
closeText(parser);
if (parser.cdata !== '') {
emitNode(parser, 'oncdata', parser.cdata);
parser.cdata = '';
}
if (parser.script !== '') {
emitNode(parser, 'onscript', parser.script);
parser.script = '';
}
}
SAXParser.prototype = {
end: function end() {
_end(this);
},
write: write,
resume: function resume() {
this.error = null;return this;
},
close: function close() {
return this.write(null);
},
flush: function flush() {
flushBuffers(this);
}
};
var Stream;
try {
Stream = require('stream').Stream;
} catch (ex) {
Stream = function Stream() {};
}
var streamWraps = sax.EVENTS.filter(function (ev) {
return ev !== 'error' && ev !== 'end';
});
function createStream(strict, opt) {
return new SAXStream(strict, opt);
}
function SAXStream(strict, opt) {
if (!(this instanceof SAXStream)) {
return new SAXStream(strict, opt);
}
Stream.apply(this);
this._parser = new SAXParser(strict, opt);
this.writable = true;
this.readable = true;
var me = this;
this._parser.onend = function () {
me.emit('end');
};
this._parser.onerror = function (er) {
me.emit('error', er);
// if didn't throw, then means error was handled.
// go ahead and clear error, so we can write again.
me._parser.error = null;
};
this._decoder = null;
streamWraps.forEach(function (ev) {
(0, _defineProperty2.default)(me, 'on' + ev, {
get: function get() {
return me._parser['on' + ev];
},
set: function set(h) {
if (!h) {
me.removeAllListeners(ev);
me._parser['on' + ev] = h;
return h;
}
me.on(ev, h);
},
enumerable: true,
configurable: false
});
});
}
SAXStream.prototype = (0, _create2.default)(Stream.prototype, {
constructor: {
value: SAXStream
}
});
SAXStream.prototype.write = function (data) {
if (typeof Buffer === 'function' && typeof Buffer.isBuffer === 'function' && Buffer.isBuffer(data)) {
if (!this._decoder) {
var SD = require('string_decoder').StringDecoder;
this._decoder = new SD('utf8');
}
data = this._decoder.write(data);
}
this._parser.write(data.toString());
this.emit('data', data);
return true;
};
SAXStream.prototype.end = function (chunk) {
if (chunk && chunk.length) {
this.write(chunk);
}
this._parser.end();
return true;
};
SAXStream.prototype.on = function (ev, handler) {
var me = this;
if (!me._parser['on' + ev] && streamWraps.indexOf(ev) !== -1) {
me._parser['on' + ev] = function () {
var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments);
args.splice(0, 0, ev);
me.emit.apply(me, args);
};
}
return Stream.prototype.on.call(me, ev, handler);
};
// this really needs to be replaced with character classes.
// XML allows all manner of ridiculous numbers and digits.
var CDATA = '[CDATA[';
var DOCTYPE = 'DOCTYPE';
var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace';
var XMLNS_NAMESPACE = 'http://www.w3.org/2000/xmlns/';
var rootNS = { xml: XML_NAMESPACE, xmlns: XMLNS_NAMESPACE
// http://www.w3.org/TR/REC-xml/#NT-NameStartChar
// This implementation works on strings, a single character at a time
// as such, it cannot ever support astral-plane characters (10000-EFFFF)
// without a significant breaking change to either this parser, or the
// JavaScript language. Implementation of an emoji-capable xml parser
// is left as an exercise for the reader.
};var nameStart = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/;
var nameBody = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;
var entityStart = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/;
var entityBody = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;
function isWhitespace(c) {
return c === ' ' || c === '\n' || c === '\r' || c === '\t';
}
function isQuote(c) {
return c === '"' || c === '\'';
}
function isAttribEnd(c) {
return c === '>' || isWhitespace(c);
}
function isMatch(regex, c) {
return regex.test(c);
}
function notMatch(regex, c) {
return !isMatch(regex, c);
}
var S = 0;
sax.STATE = {
BEGIN: S++, // leading byte order mark or whitespace
BEGIN_WHITESPACE: S++, // leading whitespace
TEXT: S++, // general stuff
TEXT_ENTITY: S++, // &amp and such.
OPEN_WAKA: S++, // <
SGML_DECL: S++, // <!BLARG
SGML_DECL_QUOTED: S++, // <!BLARG foo "bar
DOCTYPE: S++, // <!DOCTYPE
DOCTYPE_QUOTED: S++, // <!DOCTYPE "//blah
DOCTYPE_DTD: S++, // <!DOCTYPE "//blah" [ ...
DOCTYPE_DTD_QUOTED: S++, // <!DOCTYPE "//blah" [ "foo
COMMENT_STARTING: S++, // <!-
COMMENT: S++, // <!--
COMMENT_ENDING: S++, // <!-- blah -
COMMENT_ENDED: S++, // <!-- blah --
CDATA: S++, // <![CDATA[ something
CDATA_ENDING: S++, // ]
CDATA_ENDING_2: S++, // ]]
PROC_INST: S++, // <?hi
PROC_INST_BODY: S++, // <?hi there
PROC_INST_ENDING: S++, // <?hi "there" ?
OPEN_TAG: S++, // <strong
OPEN_TAG_SLASH: S++, // <strong /
ATTRIB: S++, // <a
ATTRIB_NAME: S++, // <a foo
ATTRIB_NAME_SAW_WHITE: S++, // <a foo _
ATTRIB_VALUE: S++, // <a foo=
ATTRIB_VALUE_QUOTED: S++, // <a foo="bar
ATTRIB_VALUE_CLOSED: S++, // <a foo="bar"
ATTRIB_VALUE_UNQUOTED: S++, // <a foo=bar
ATTRIB_VALUE_ENTITY_Q: S++, // <foo bar="&quot;"
ATTRIB_VALUE_ENTITY_U: S++, // <foo bar=&quot
CLOSE_TAG: S++, // </a
CLOSE_TAG_SAW_WHITE: S++, // </a >
SCRIPT: S++, // <script> ...
SCRIPT_ENDING: S++ // <script> ... <
};
sax.XML_ENTITIES = {
'amp': '&',
'gt': '>',
'lt': '<',
'quot': '"',
'apos': "'"
};
sax.ENTITIES = {
'amp': '&',
'gt': '>',
'lt': '<',
'quot': '"',
'apos': "'",
'AElig': 198,
'Aacute': 193,
'Acirc': 194,
'Agrave': 192,
'Aring': 197,
'Atilde': 195,
'Auml': 196,
'Ccedil': 199,
'ETH': 208,
'Eacute': 201,
'Ecirc': 202,
'Egrave': 200,
'Euml': 203,
'Iacute': 205,
'Icirc': 206,
'Igrave': 204,
'Iuml': 207,
'Ntilde': 209,
'Oacute': 211,
'Ocirc': 212,
'Ograve': 210,
'Oslash': 216,
'Otilde': 213,
'Ouml': 214,
'THORN': 222,
'Uacute': 218,
'Ucirc': 219,
'Ugrave': 217,
'Uuml': 220,
'Yacute': 221,
'aacute': 225,
'acirc': 226,
'aelig': 230,
'agrave': 224,
'aring': 229,
'atilde': 227,
'auml': 228,
'ccedil': 231,
'eacute': 233,
'ecirc': 234,
'egrave': 232,
'eth': 240,
'euml': 235,
'iacute': 237,
'icirc': 238,
'igrave': 236,
'iuml': 239,
'ntilde': 241,
'oacute': 243,
'ocirc': 244,
'ograve': 242,
'oslash': 248,
'otilde': 245,
'ouml': 246,
'szlig': 223,
'thorn': 254,
'uacute': 250,
'ucirc': 251,
'ugrave': 249,
'uuml': 252,
'yacute': 253,
'yuml': 255,
'copy': 169,
'reg': 174,
'nbsp': 160,
'iexcl': 161,
'cent': 162,
'pound': 163,
'curren': 164,
'yen': 165,
'brvbar': 166,
'sect': 167,
'uml': 168,
'ordf': 170,
'laquo': 171,
'not': 172,
'shy': 173,
'macr': 175,
'deg': 176,
'plusmn': 177,
'sup1': 185,
'sup2': 178,
'sup3': 179,
'acute': 180,
'micro': 181,
'para': 182,
'middot': 183,
'cedil': 184,
'ordm': 186,
'raquo': 187,
'frac14': 188,
'frac12': 189,
'frac34': 190,
'iquest': 191,
'times': 215,
'divide': 247,
'OElig': 338,
'oelig': 339,
'Scaron': 352,
'scaron': 353,
'Yuml': 376,
'fnof': 402,
'circ': 710,
'tilde': 732,
'Alpha': 913,
'Beta': 914,
'Gamma': 915,
'Delta': 916,
'Epsilon': 917,
'Zeta': 918,
'Eta': 919,
'Theta': 920,
'Iota': 921,
'Kappa': 922,
'Lambda': 923,
'Mu': 924,
'Nu': 925,
'Xi': 926,
'Omicron': 927,
'Pi': 928,
'Rho': 929,
'Sigma': 931,
'Tau': 932,
'Upsilon': 933,
'Phi': 934,
'Chi': 935,
'Psi': 936,
'Omega': 937,
'alpha': 945,
'beta': 946,
'gamma': 947,
'delta': 948,
'epsilon': 949,
'zeta': 950,
'eta': 951,
'theta': 952,
'iota': 953,
'kappa': 954,
'lambda': 955,
'mu': 956,
'nu': 957,
'xi': 958,
'omicron': 959,
'pi': 960,
'rho': 961,
'sigmaf': 962,
'sigma': 963,
'tau': 964,
'upsilon': 965,
'phi': 966,
'chi': 967,
'psi': 968,
'omega': 969,
'thetasym': 977,
'upsih': 978,
'piv': 982,
'ensp': 8194,
'emsp': 8195,
'thinsp': 8201,
'zwnj': 8204,
'zwj': 8205,
'lrm': 8206,
'rlm': 8207,
'ndash': 8211,
'mdash': 8212,
'lsquo': 8216,
'rsquo': 8217,
'sbquo': 8218,
'ldquo': 8220,
'rdquo': 8221,
'bdquo': 8222,
'dagger': 8224,
'Dagger': 8225,
'bull': 8226,
'hellip': 8230,
'permil': 8240,
'prime': 8242,
'Prime': 8243,
'lsaquo': 8249,
'rsaquo': 8250,
'oline': 8254,
'frasl': 8260,
'euro': 8364,
'image': 8465,
'weierp': 8472,
'real': 8476,
'trade': 8482,
'alefsym': 8501,
'larr': 8592,
'uarr': 8593,
'rarr': 8594,
'darr': 8595,
'harr': 8596,
'crarr': 8629,
'lArr': 8656,
'uArr': 8657,
'rArr': 8658,
'dArr': 8659,
'hArr': 8660,
'forall': 8704,
'part': 8706,
'exist': 8707,
'empty': 8709,
'nabla': 8711,
'isin': 8712,
'notin': 8713,
'ni': 8715,
'prod': 8719,
'sum': 8721,
'minus': 8722,
'lowast': 8727,
'radic': 8730,
'prop': 8733,
'infin': 8734,
'ang': 8736,
'and': 8743,
'or': 8744,
'cap': 8745,
'cup': 8746,
'int': 8747,
'there4': 8756,
'sim': 8764,
'cong': 8773,
'asymp': 8776,
'ne': 8800,
'equiv': 8801,
'le': 8804,
'ge': 8805,
'sub': 8834,
'sup': 8835,
'nsub': 8836,
'sube': 8838,
'supe': 8839,
'oplus': 8853,
'otimes': 8855,
'perp': 8869,
'sdot': 8901,
'lceil': 8968,
'rceil': 8969,
'lfloor': 8970,
'rfloor': 8971,
'lang': 9001,
'rang': 9002,
'loz': 9674,
'spades': 9824,
'clubs': 9827,
'hearts': 9829,
'diams': 9830
};
(0, _keys2.default)(sax.ENTITIES).forEach(function (key) {
var e = sax.ENTITIES[key];
var s = typeof e === 'number' ? String.fromCharCode(e) : e;
sax.ENTITIES[key] = s;
});
for (var s in sax.STATE) {
sax.STATE[sax.STATE[s]] = s;
}
// shorthand
S = sax.STATE;
function emit(parser, event, data) {
parser[event] && parser[event](data);
}
function emitNode(parser, nodeType, data) {
if (parser.textNode) closeText(parser);
emit(parser, nodeType, data);
}
function closeText(parser) {
parser.textNode = textopts(parser.opt, parser.textNode);
if (parser.textNode) emit(parser, 'ontext', parser.textNode);
parser.textNode = '';
}
function textopts(opt, text) {
if (opt.trim) text = text.trim();
if (opt.normalize) text = text.replace(/\s+/g, ' ');
return text;
}
function error(parser, er) {
closeText(parser);
if (parser.trackPosition) {
er += '\nLine: ' + parser.line + '\nColumn: ' + parser.column + '\nChar: ' + parser.c;
}
er = new Error(er);
parser.error = er;
emit(parser, 'onerror', er);
return parser;
}
function _end(parser) {
if (parser.sawRoot && !parser.closedRoot) strictFail(parser, 'Unclosed root tag');
if (parser.state !== S.BEGIN && parser.state !== S.BEGIN_WHITESPACE && parser.state !== S.TEXT) {
error(parser, 'Unexpected end');
}
closeText(parser);
parser.c = '';
parser.closed = true;
emit(parser, 'onend');
SAXParser.call(parser, parser.strict, parser.opt);
return parser;
}
function strictFail(parser, message) {
if ((typeof parser === 'undefined' ? 'undefined' : (0, _typeof3.default)(parser)) !== 'object' || !(parser instanceof SAXParser)) {
throw new Error('bad call to strictFail');
}
if (parser.strict) {
error(parser, message);
}
}
function newTag(parser) {
if (!parser.strict) parser.tagName = parser.tagName[parser.looseCase]();
var parent = parser.tags[parser.tags.length - 1] || parser;
var tag = parser.tag = { name: parser.tagName, attributes: {}
// will be overridden if tag contails an xmlns="foo" or xmlns:foo="bar"
};if (parser.opt.xmlns) {
tag.ns = parent.ns;
}
parser.attribList.length = 0;
emitNode(parser, 'onopentagstart', tag);
}
function qname(name, attribute) {
var i = name.indexOf(':');
var qualName = i < 0 ? ['', name] : name.split(':');
var prefix = qualName[0];
var local = qualName[1];
// <x "xmlns"="http://foo">
if (attribute && name === 'xmlns') {
prefix = 'xmlns';
local = '';
}
return { prefix: prefix, local: local };
}
function attrib(parser) {
if (!parser.strict) {
parser.attribName = parser.attribName[parser.looseCase]();
}
if (parser.attribList.indexOf(parser.attribName) !== -1 || parser.tag.attributes.hasOwnProperty(parser.attribName)) {
parser.attribName = parser.attribValue = '';
return;
}
if (parser.opt.xmlns) {
var qn = qname(parser.attribName, true);
var prefix = qn.prefix;
var local = qn.local;
if (prefix === 'xmlns') {
// namespace binding attribute. push the binding into scope
if (local === 'xml' && parser.attribValue !== XML_NAMESPACE) {
strictFail(parser, 'xml: prefix must be bound to ' + XML_NAMESPACE + '\n' + 'Actual: ' + parser.attribValue);
} else if (local === 'xmlns' && parser.attribValue !== XMLNS_NAMESPACE) {
strictFail(parser, 'xmlns: prefix must be bound to ' + XMLNS_NAMESPACE + '\n' + 'Actual: ' + parser.attribValue);
} else {
var tag = parser.tag;
var parent = parser.tags[parser.tags.length - 1] || parser;
if (tag.ns === parent.ns) {
tag.ns = (0, _create2.default)(parent.ns);
}
tag.ns[local] = parser.attribValue;
}
}
// defer onattribute events until all attributes have been seen
// so any new bindings can take effect. preserve attribute order
// so deferred events can be emitted in document order
parser.attribList.push([parser.attribName, parser.attribValue]);
} else {
// in non-xmlns mode, we can emit the event right away
parser.tag.attributes[parser.attribName] = parser.attribValue;
emitNode(parser, 'onattribute', {
name: parser.attribName,
value: parser.attribValue
});
}
parser.attribName = parser.attribValue = '';
}
function openTag(parser, selfClosing) {
if (parser.opt.xmlns) {
// emit namespace binding events
var tag = parser.tag;
// add namespace info to tag
var qn = qname(parser.tagName);
tag.prefix = qn.prefix;
tag.local = qn.local;
tag.uri = tag.ns[qn.prefix] || '';
if (tag.prefix && !tag.uri) {
strictFail(parser, 'Unbound namespace prefix: ' + (0, _stringify2.default)(parser.tagName));
tag.uri = qn.prefix;
}
var parent = parser.tags[parser.tags.length - 1] || parser;
if (tag.ns && parent.ns !== tag.ns) {
(0, _keys2.default)(tag.ns).forEach(function (p) {
emitNode(parser, 'onopennamespace', {
prefix: p,
uri: tag.ns[p]
});
});
}
// handle deferred onattribute events
// Note: do not apply default ns to attributes:
// http://www.w3.org/TR/REC-xml-names/#defaulting
for (var i = 0, l = parser.attribList.length; i < l; i++) {
var nv = parser.attribList[i];
var name = nv[0];
var value = nv[1];
var qualName = qname(name, true);
var prefix = qualName.prefix;
var local = qualName.local;
var uri = prefix === '' ? '' : tag.ns[prefix] || '';
var a = {
name: name,
value: value,
prefix: prefix,
local: local,
uri: uri
// if there's any attributes with an undefined namespace,
// then fail on them now.
};if (prefix && prefix !== 'xmlns' && !uri) {
strictFail(parser, 'Unbound namespace prefix: ' + (0, _stringify2.default)(prefix));
a.uri = prefix;
}
parser.tag.attributes[name] = a;
emitNode(parser, 'onattribute', a);
}
parser.attribList.length = 0;
}
parser.tag.isSelfClosing = !!selfClosing;
// process the tag
parser.sawRoot = true;
parser.tags.push(parser.tag);
emitNode(parser, 'onopentag', parser.tag);
if (!selfClosing) {
// special case for <script> in non-strict mode.
if (!parser.noscript && parser.tagName.toLowerCase() === 'script') {
parser.state = S.SCRIPT;
} else {
parser.state = S.TEXT;
}
parser.tag = null;
parser.tagName = '';
}
parser.attribName = parser.attribValue = '';
parser.attribList.length = 0;
}
function closeTag(parser) {
if (!parser.tagName) {
strictFail(parser, 'Weird empty close tag.');
parser.textNode += '</>';
parser.state = S.TEXT;
return;
}
if (parser.script) {
if (parser.tagName !== 'script') {
parser.script += '</' + parser.tagName + '>';
parser.tagName = '';
parser.state = S.SCRIPT;
return;
}
emitNode(parser, 'onscript', parser.script);
parser.script = '';
}
// first make sure that the closing tag actually exists.
// <a><b></c></b></a> will close everything, otherwise.
var t = parser.tags.length;
var tagName = parser.tagName;
if (!parser.strict) {
tagName = tagName[parser.looseCase]();
}
var closeTo = tagName;
while (t--) {
var close = parser.tags[t];
if (close.name !== closeTo) {
// fail the first time in strict mode
strictFail(parser, 'Unexpected close tag');
} else {
break;
}
}
// didn't find it. we already failed for strict, so just abort.
if (t < 0) {
strictFail(parser, 'Unmatched closing tag: ' + parser.tagName);
parser.textNode += '</' + parser.tagName + '>';
parser.state = S.TEXT;
return;
}
parser.tagName = tagName;
var s = parser.tags.length;
while (s-- > t) {
var tag = parser.tag = parser.tags.pop();
parser.tagName = parser.tag.name;
emitNode(parser, 'onclosetag', parser.tagName);
var x = {};
for (var i in tag.ns) {
x[i] = tag.ns[i];
}
var parent = parser.tags[parser.tags.length - 1] || parser;
if (parser.opt.xmlns && tag.ns !== parent.ns) {
// remove namespace bindings introduced by tag
(0, _keys2.default)(tag.ns).forEach(function (p) {
var n = tag.ns[p];
emitNode(parser, 'onclosenamespace', { prefix: p, uri: n });
});
}
}
if (t === 0) parser.closedRoot = true;
parser.tagName = parser.attribValue = parser.attribName = '';
parser.attribList.length = 0;
parser.state = S.TEXT;
}
function parseEntity(parser) {
var entity = parser.entity;
var entityLC = entity.toLowerCase();
var num;
var numStr = '';
if (parser.ENTITIES[entity]) {
return parser.ENTITIES[entity];
}
if (parser.ENTITIES[entityLC]) {
return parser.ENTITIES[entityLC];
}
entity = entityLC;
if (entity.charAt(0) === '#') {
if (entity.charAt(1) === 'x') {
entity = entity.slice(2);
num = parseInt(entity, 16);
numStr = num.toString(16);
} else {
entity = entity.slice(1);
num = parseInt(entity, 10);
numStr = num.toString(10);
}
}
entity = entity.replace(/^0+/, '');
if (isNaN(num) || numStr.toLowerCase() !== entity) {
strictFail(parser, 'Invalid character entity');
return '&' + parser.entity + ';';
}
return (0, _fromCodePoint2.default)(num);
}
function beginWhiteSpace(parser, c) {
if (c === '<') {
parser.state = S.OPEN_WAKA;
parser.startTagPosition = parser.position;
} else if (!isWhitespace(c)) {
// have to process this as a text node.
// weird, but happens.
strictFail(parser, 'Non-whitespace before first tag.');
parser.textNode = c;
parser.state = S.TEXT;
}
}
function charAt(chunk, i) {
var result = '';
if (i < chunk.length) {
result = chunk.charAt(i);
}
return result;
}
function write(chunk) {
var parser = this;
if (this.error) {
throw this.error;
}
if (parser.closed) {
return error(parser, 'Cannot write after close. Assign an onready handler.');
}
if (chunk === null) {
return _end(parser);
}
if ((typeof chunk === 'undefined' ? 'undefined' : (0, _typeof3.default)(chunk)) === 'object') {
chunk = chunk.toString();
}
var i = 0;
var c = '';
while (true) {
c = charAt(chunk, i++);
parser.c = c;
if (!c) {
break;
}
if (parser.trackPosition) {
parser.position++;
if (c === '\n') {
parser.line++;
parser.column = 0;
} else {
parser.column++;
}
}
switch (parser.state) {
case S.BEGIN:
parser.state = S.BEGIN_WHITESPACE;
if (c === '\uFEFF') {
continue;
}
beginWhiteSpace(parser, c);
continue;
case S.BEGIN_WHITESPACE:
beginWhiteSpace(parser, c);
continue;
case S.TEXT:
if (parser.sawRoot && !parser.closedRoot) {
var starti = i - 1;
while (c && c !== '<' && c !== '&') {
c = charAt(chunk, i++);
if (c && parser.trackPosition) {
parser.position++;
if (c === '\n') {
parser.line++;
parser.column = 0;
} else {
parser.column++;
}
}
}
parser.textNode += chunk.substring(starti, i - 1);
}
if (c === '<' && !(parser.sawRoot && parser.closedRoot && !parser.strict)) {
parser.state = S.OPEN_WAKA;
parser.startTagPosition = parser.position;
} else {
if (!isWhitespace(c) && (!parser.sawRoot || parser.closedRoot)) {
strictFail(parser, 'Text data outside of root node.');
}
if (c === '&') {
parser.state = S.TEXT_ENTITY;
} else {
parser.textNode += c;
}
}
continue;
case S.SCRIPT:
// only non-strict
if (c === '<') {
parser.state = S.SCRIPT_ENDING;
} else {
parser.script += c;
}
continue;
case S.SCRIPT_ENDING:
if (c === '/') {
parser.state = S.CLOSE_TAG;
} else {
parser.script += '<' + c;
parser.state = S.SCRIPT;
}
continue;
case S.OPEN_WAKA:
// either a /, ?, !, or text is coming next.
if (c === '!') {
parser.state = S.SGML_DECL;
parser.sgmlDecl = '';
} else if (isWhitespace(c)) {
// wait for it...
} else if (isMatch(nameStart, c)) {
parser.state = S.OPEN_TAG;
parser.tagName = c;
} else if (c === '/') {
parser.state = S.CLOSE_TAG;
parser.tagName = '';
} else if (c === '?') {
parser.state = S.PROC_INST;
parser.procInstName = parser.procInstBody = '';
} else {
strictFail(parser, 'Unencoded <');
// if there was some whitespace, then add that in.
if (parser.startTagPosition + 1 < parser.position) {
var pad = parser.position - parser.startTagPosition;
c = new Array(pad).join(' ') + c;
}
parser.textNode += '<' + c;
parser.state = S.TEXT;
}
continue;
case S.SGML_DECL:
if ((parser.sgmlDecl + c).toUpperCase() === CDATA) {
emitNode(parser, 'onopencdata');
parser.state = S.CDATA;
parser.sgmlDecl = '';
parser.cdata = '';
} else if (parser.sgmlDecl + c === '--') {
parser.state = S.COMMENT;
parser.comment = '';
parser.sgmlDecl = '';
} else if ((parser.sgmlDecl + c).toUpperCase() === DOCTYPE) {
parser.state = S.DOCTYPE;
if (parser.doctype || parser.sawRoot) {
strictFail(parser, 'Inappropriately located doctype declaration');
}
parser.doctype = '';
parser.sgmlDecl = '';
} else if (c === '>') {
emitNode(parser, 'onsgmldeclaration', parser.sgmlDecl);
parser.sgmlDecl = '';
parser.state = S.TEXT;
} else if (isQuote(c)) {
parser.state = S.SGML_DECL_QUOTED;
parser.sgmlDecl += c;
} else {
parser.sgmlDecl += c;
}
continue;
case S.SGML_DECL_QUOTED:
if (c === parser.q) {
parser.state = S.SGML_DECL;
parser.q = '';
}
parser.sgmlDecl += c;
continue;
case S.DOCTYPE:
if (c === '>') {
parser.state = S.TEXT;
emitNode(parser, 'ondoctype', parser.doctype);
parser.doctype = true; // just remember that we saw it.
} else {
parser.doctype += c;
if (c === '[') {
parser.state = S.DOCTYPE_DTD;
} else if (isQuote(c)) {
parser.state = S.DOCTYPE_QUOTED;
parser.q = c;
}
}
continue;
case S.DOCTYPE_QUOTED:
parser.doctype += c;
if (c === parser.q) {
parser.q = '';
parser.state = S.DOCTYPE;
}
continue;
case S.DOCTYPE_DTD:
parser.doctype += c;
if (c === ']') {
parser.state = S.DOCTYPE;
} else if (isQuote(c)) {
parser.state = S.DOCTYPE_DTD_QUOTED;
parser.q = c;
}
continue;
case S.DOCTYPE_DTD_QUOTED:
parser.doctype += c;
if (c === parser.q) {
parser.state = S.DOCTYPE_DTD;
parser.q = '';
}
continue;
case S.COMMENT:
if (c === '-') {
parser.state = S.COMMENT_ENDING;
} else {
parser.comment += c;
}
continue;
case S.COMMENT_ENDING:
if (c === '-') {
parser.state = S.COMMENT_ENDED;
parser.comment = textopts(parser.opt, parser.comment);
if (parser.comment) {
emitNode(parser, 'oncomment', parser.comment);
}
parser.comment = '';
} else {
parser.comment += '-' + c;
parser.state = S.COMMENT;
}
continue;
case S.COMMENT_ENDED:
if (c !== '>') {
strictFail(parser, 'Malformed comment');
// allow <!-- blah -- bloo --> in non-strict mode,
// which is a comment of " blah -- bloo "
parser.comment += '--' + c;
parser.state = S.COMMENT;
} else {
parser.state = S.TEXT;
}
continue;
case S.CDATA:
if (c === ']') {
parser.state = S.CDATA_ENDING;
} else {
parser.cdata += c;
}
continue;
case S.CDATA_ENDING:
if (c === ']') {
parser.state = S.CDATA_ENDING_2;
} else {
parser.cdata += ']' + c;
parser.state = S.CDATA;
}
continue;
case S.CDATA_ENDING_2:
if (c === '>') {
if (parser.cdata) {
emitNode(parser, 'oncdata', parser.cdata);
}
emitNode(parser, 'onclosecdata');
parser.cdata = '';
parser.state = S.TEXT;
} else if (c === ']') {
parser.cdata += ']';
} else {
parser.cdata += ']]' + c;
parser.state = S.CDATA;
}
continue;
case S.PROC_INST:
if (c === '?') {
parser.state = S.PROC_INST_ENDING;
} else if (isWhitespace(c)) {
parser.state = S.PROC_INST_BODY;
} else {
parser.procInstName += c;
}
continue;
case S.PROC_INST_BODY:
if (!parser.procInstBody && isWhitespace(c)) {
continue;
} else if (c === '?') {
parser.state = S.PROC_INST_ENDING;
} else {
parser.procInstBody += c;
}
continue;
case S.PROC_INST_ENDING:
if (c === '>') {
emitNode(parser, 'onprocessinginstruction', {
name: parser.procInstName,
body: parser.procInstBody
});
parser.procInstName = parser.procInstBody = '';
parser.state = S.TEXT;
} else {
parser.procInstBody += '?' + c;
parser.state = S.PROC_INST_BODY;
}
continue;
case S.OPEN_TAG:
if (isMatch(nameBody, c)) {
parser.tagName += c;
} else {
newTag(parser);
if (c === '>') {
openTag(parser);
} else if (c === '/') {
parser.state = S.OPEN_TAG_SLASH;
} else {
if (!isWhitespace(c)) {
strictFail(parser, 'Invalid character in tag name');
}
parser.state = S.ATTRIB;
}
}
continue;
case S.OPEN_TAG_SLASH:
if (c === '>') {
openTag(parser, true);
closeTag(parser);
} else {
strictFail(parser, 'Forward-slash in opening tag not followed by >');
parser.state = S.ATTRIB;
}
continue;
case S.ATTRIB:
// haven't read the attribute name yet.
if (isWhitespace(c)) {
continue;
} else if (c === '>') {
openTag(parser);
} else if (c === '/') {
parser.state = S.OPEN_TAG_SLASH;
} else if (isMatch(nameStart, c)) {
parser.attribName = c;
parser.attribValue = '';
parser.state = S.ATTRIB_NAME;
} else {
strictFail(parser, 'Invalid attribute name');
}
continue;
case S.ATTRIB_NAME:
if (c === '=') {
parser.state = S.ATTRIB_VALUE;
} else if (c === '>') {
strictFail(parser, 'Attribute without value');
parser.attribValue = parser.attribName;
attrib(parser);
openTag(parser);
} else if (isWhitespace(c)) {
parser.state = S.ATTRIB_NAME_SAW_WHITE;
} else if (isMatch(nameBody, c)) {
parser.attribName += c;
} else {
strictFail(parser, 'Invalid attribute name');
}
continue;
case S.ATTRIB_NAME_SAW_WHITE:
if (c === '=') {
parser.state = S.ATTRIB_VALUE;
} else if (isWhitespace(c)) {
continue;
} else {
strictFail(parser, 'Attribute without value');
parser.tag.attributes[parser.attribName] = '';
parser.attribValue = '';
emitNode(parser, 'onattribute', {
name: parser.attribName,
value: ''
});
parser.attribName = '';
if (c === '>') {
openTag(parser);
} else if (isMatch(nameStart, c)) {
parser.attribName = c;
parser.state = S.ATTRIB_NAME;
} else {
strictFail(parser, 'Invalid attribute name');
parser.state = S.ATTRIB;
}
}
continue;
case S.ATTRIB_VALUE:
if (isWhitespace(c)) {
continue;
} else if (isQuote(c)) {
parser.q = c;
parser.state = S.ATTRIB_VALUE_QUOTED;
} else {
strictFail(parser, 'Unquoted attribute value');
parser.state = S.ATTRIB_VALUE_UNQUOTED;
parser.attribValue = c;
}
continue;
case S.ATTRIB_VALUE_QUOTED:
if (c !== parser.q) {
if (c === '&') {
parser.state = S.ATTRIB_VALUE_ENTITY_Q;
} else {
parser.attribValue += c;
}
continue;
}
attrib(parser);
parser.q = '';
parser.state = S.ATTRIB_VALUE_CLOSED;
continue;
case S.ATTRIB_VALUE_CLOSED:
if (isWhitespace(c)) {
parser.state = S.ATTRIB;
} else if (c === '>') {
openTag(parser);
} else if (c === '/') {
parser.state = S.OPEN_TAG_SLASH;
} else if (isMatch(nameStart, c)) {
strictFail(parser, 'No whitespace between attributes');
parser.attribName = c;
parser.attribValue = '';
parser.state = S.ATTRIB_NAME;
} else {
strictFail(parser, 'Invalid attribute name');
}
continue;
case S.ATTRIB_VALUE_UNQUOTED:
if (!isAttribEnd(c)) {
if (c === '&') {
parser.state = S.ATTRIB_VALUE_ENTITY_U;
} else {
parser.attribValue += c;
}
continue;
}
attrib(parser);
if (c === '>') {
openTag(parser);
} else {
parser.state = S.ATTRIB;
}
continue;
case S.CLOSE_TAG:
if (!parser.tagName) {
if (isWhitespace(c)) {
continue;
} else if (notMatch(nameStart, c)) {
if (parser.script) {
parser.script += '</' + c;
parser.state = S.SCRIPT;
} else {
strictFail(parser, 'Invalid tagname in closing tag.');
}
} else {
parser.tagName = c;
}
} else if (c === '>') {
closeTag(parser);
} else if (isMatch(nameBody, c)) {
parser.tagName += c;
} else if (parser.script) {
parser.script += '</' + parser.tagName;
parser.tagName = '';
parser.state = S.SCRIPT;
} else {
if (!isWhitespace(c)) {
strictFail(parser, 'Invalid tagname in closing tag');
}
parser.state = S.CLOSE_TAG_SAW_WHITE;
}
continue;
case S.CLOSE_TAG_SAW_WHITE:
if (isWhitespace(c)) {
continue;
}
if (c === '>') {
closeTag(parser);
} else {
strictFail(parser, 'Invalid characters in closing tag');
}
continue;
case S.TEXT_ENTITY:
case S.ATTRIB_VALUE_ENTITY_Q:
case S.ATTRIB_VALUE_ENTITY_U:
var returnState;
var buffer;
switch (parser.state) {
case S.TEXT_ENTITY:
returnState = S.TEXT;
buffer = 'textNode';
break;
case S.ATTRIB_VALUE_ENTITY_Q:
returnState = S.ATTRIB_VALUE_QUOTED;
buffer = 'attribValue';
break;
case S.ATTRIB_VALUE_ENTITY_U:
returnState = S.ATTRIB_VALUE_UNQUOTED;
buffer = 'attribValue';
break;
}
if (c === ';') {
parser[buffer] += parseEntity(parser);
parser.entity = '';
parser.state = returnState;
} else if (isMatch(parser.entity.length ? entityBody : entityStart, c)) {
parser.entity += c;
} else {
strictFail(parser, 'Invalid character in entity name');
parser[buffer] += '&' + parser.entity + c;
parser.entity = '';
parser.state = returnState;
}
continue;
default:
throw new Error(parser, 'Unknown state: ' + parser.state);
}
} // while
if (parser.position >= parser.bufferCheckPosition) {
checkBufferLength(parser);
}
return parser;
}
/*! http://mths.be/fromcodepoint v0.1.0 by @mathias */
/* istanbul ignore next */
if (!_fromCodePoint2.default) {
(function () {
var stringFromCharCode = String.fromCharCode;
var floor = Math.floor;
var fromCodePoint = function fromCodePoint() {
var MAX_SIZE = 0x4000;
var codeUnits = [];
var highSurrogate;
var lowSurrogate;
var index = -1;
var length = arguments.length;
if (!length) {
return '';
}
var result = '';
while (++index < length) {
var codePoint = Number(arguments[index]);
if (!isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`
codePoint < 0 || // not a valid Unicode code point
codePoint > 0x10FFFF || // not a valid Unicode code point
floor(codePoint) !== codePoint // not an integer
) {
throw RangeError('Invalid code point: ' + codePoint);
}
if (codePoint <= 0xFFFF) {
// BMP code point
codeUnits.push(codePoint);
} else {
// Astral code point; split in surrogate halves
// http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
codePoint -= 0x10000;
highSurrogate = (codePoint >> 10) + 0xD800;
lowSurrogate = codePoint % 0x400 + 0xDC00;
codeUnits.push(highSurrogate, lowSurrogate);
}
if (index + 1 === length || codeUnits.length > MAX_SIZE) {
result += stringFromCharCode.apply(null, codeUnits);
codeUnits.length = 0;
}
}
return result;
};
/* istanbul ignore next */
if (_defineProperty2.default) {
Object.defineProperty(String, 'fromCodePoint', {
value: fromCodePoint,
configurable: true,
writable: true
});
} else {
String.fromCodePoint = fromCodePoint;
}
})();
}
})(typeof exports === 'undefined' ? undefined.sax = {} : exports);
}).call(this,require("buffer").Buffer)
},{"babel-runtime/core-js/json/stringify":53,"babel-runtime/core-js/object/create":55,"babel-runtime/core-js/object/define-property":56,"babel-runtime/core-js/object/keys":60,"babel-runtime/core-js/string/from-code-point":63,"babel-runtime/helpers/typeof":67,"buffer":73,"stream":230,"string_decoder":72}],230:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node 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.
module.exports = Stream;
var EE = require('events').EventEmitter;
var inherits = require('inherits');
inherits(Stream, EE);
Stream.Readable = require('readable-stream/readable.js');
Stream.Writable = require('readable-stream/writable.js');
Stream.Duplex = require('readable-stream/duplex.js');
Stream.Transform = require('readable-stream/transform.js');
Stream.PassThrough = require('readable-stream/passthrough.js');
// Backwards-compat with node 0.4.x
Stream.Stream = Stream;
// old-style streams. Note that the pipe method (the only relevant
// part of this class) is overridden in the Readable class.
function Stream() {
EE.call(this);
}
Stream.prototype.pipe = function(dest, options) {
var source = this;
function ondata(chunk) {
if (dest.writable) {
if (false === dest.write(chunk) && source.pause) {
source.pause();
}
}
}
source.on('data', ondata);
function ondrain() {
if (source.readable && source.resume) {
source.resume();
}
}
dest.on('drain', ondrain);
// If the 'end' option is not supplied, dest.end() will be called when
// source gets the 'end' or 'close' events. Only dest.end() once.
if (!dest._isStdio && (!options || options.end !== false)) {
source.on('end', onend);
source.on('close', onclose);
}
var didOnEnd = false;
function onend() {
if (didOnEnd) return;
didOnEnd = true;
dest.end();
}
function onclose() {
if (didOnEnd) return;
didOnEnd = true;
if (typeof dest.destroy === 'function') dest.destroy();
}
// don't leave dangling pipes when there are errors.
function onerror(er) {
cleanup();
if (EE.listenerCount(this, 'error') === 0) {
throw er; // Unhandled stream error in pipe.
}
}
source.on('error', onerror);
dest.on('error', onerror);
// remove all the event listeners that were added.
function cleanup() {
source.removeListener('data', ondata);
dest.removeListener('drain', ondrain);
source.removeListener('end', onend);
source.removeListener('close', onclose);
source.removeListener('error', onerror);
dest.removeListener('error', onerror);
source.removeListener('end', cleanup);
source.removeListener('close', cleanup);
dest.removeListener('close', cleanup);
}
source.on('end', cleanup);
source.on('close', cleanup);
dest.on('close', cleanup);
dest.emit('pipe', source);
// Allow for unix-like usage: A.pipe(B).pipe(C)
return dest;
};
},{"events":192,"inherits":196,"readable-stream/duplex.js":213,"readable-stream/passthrough.js":222,"readable-stream/readable.js":223,"readable-stream/transform.js":224,"readable-stream/writable.js":225}],231:[function(require,module,exports){
(function (global){
var ClientRequest = require('./lib/request')
var response = require('./lib/response')
var extend = require('xtend')
var statusCodes = require('builtin-status-codes')
var url = require('url')
var http = exports
http.request = function (opts, cb) {
if (typeof opts === 'string')
opts = url.parse(opts)
else
opts = extend(opts)
// Normally, the page is loaded from http or https, so not specifying a protocol
// will result in a (valid) protocol-relative url. However, this won't work if
// the protocol is something else, like 'file:'
var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : ''
var protocol = opts.protocol || defaultProtocol
var host = opts.hostname || opts.host
var port = opts.port
var path = opts.path || '/'
// Necessary for IPv6 addresses
if (host && host.indexOf(':') !== -1)
host = '[' + host + ']'
// This may be a relative url. The browser should always be able to interpret it correctly.
opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path
opts.method = (opts.method || 'GET').toUpperCase()
opts.headers = opts.headers || {}
// Also valid opts.auth, opts.mode
var req = new ClientRequest(opts)
if (cb)
req.on('response', cb)
return req
}
http.get = function get (opts, cb) {
var req = http.request(opts, cb)
req.end()
return req
}
http.ClientRequest = ClientRequest
http.IncomingMessage = response.IncomingMessage
http.Agent = function () {}
http.Agent.defaultMaxSockets = 4
http.globalAgent = new http.Agent()
http.STATUS_CODES = statusCodes
http.METHODS = [
'CHECKOUT',
'CONNECT',
'COPY',
'DELETE',
'GET',
'HEAD',
'LOCK',
'M-SEARCH',
'MERGE',
'MKACTIVITY',
'MKCOL',
'MOVE',
'NOTIFY',
'OPTIONS',
'PATCH',
'POST',
'PROPFIND',
'PROPPATCH',
'PURGE',
'PUT',
'REPORT',
'SEARCH',
'SUBSCRIBE',
'TRACE',
'UNLOCK',
'UNSUBSCRIBE'
]
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./lib/request":233,"./lib/response":234,"builtin-status-codes":74,"url":238,"xtend":283}],232:[function(require,module,exports){
(function (global){
'use strict';
exports.fetch = isFunction(global.fetch) && isFunction(global.ReadableStream);
exports.writableStream = isFunction(global.WritableStream);
exports.abortController = isFunction(global.AbortController);
exports.blobConstructor = false;
try {
new Blob([new ArrayBuffer(1)]);
exports.blobConstructor = true;
} catch (e) {}
// The xhr request to example.com may violate some restrictive CSP configurations,
// so if we're running in a browser that supports `fetch`, avoid calling getXHR()
// and assume support for certain features below.
var xhr;
function getXHR() {
// Cache the xhr value
if (xhr !== undefined) return xhr;
if (global.XMLHttpRequest) {
xhr = new global.XMLHttpRequest();
// If XDomainRequest is available (ie only, where xhr might not work
// cross domain), use the page location. Otherwise use example.com
// Note: this doesn't actually make an http request.
try {
xhr.open('GET', global.XDomainRequest ? '/' : 'https://example.com');
} catch (e) {
xhr = null;
}
} else {
// Service workers don't have XHR
xhr = null;
}
return xhr;
}
function checkTypeSupport(type) {
var xhr = getXHR();
if (!xhr) return false;
try {
xhr.responseType = type;
return xhr.responseType === type;
} catch (e) {}
return false;
}
// For some strange reason, Safari 7.0 reports typeof global.ArrayBuffer === 'object'.
// Safari 7.1 appears to have fixed this bug.
var haveArrayBuffer = typeof global.ArrayBuffer !== 'undefined';
var haveSlice = haveArrayBuffer && isFunction(global.ArrayBuffer.prototype.slice);
// If fetch is supported, then arraybuffer will be supported too. Skip calling
// checkTypeSupport(), since that calls getXHR().
exports.arraybuffer = exports.fetch || haveArrayBuffer && checkTypeSupport('arraybuffer');
// These next two tests unavoidably show warnings in Chrome. Since fetch will always
// be used if it's available, just return false for these to avoid the warnings.
exports.msstream = !exports.fetch && haveSlice && checkTypeSupport('ms-stream');
exports.mozchunkedarraybuffer = !exports.fetch && haveArrayBuffer && checkTypeSupport('moz-chunked-arraybuffer');
// If fetch is supported, then overrideMimeType will be supported too. Skip calling
// getXHR().
exports.overrideMimeType = exports.fetch || (getXHR() ? isFunction(getXHR().overrideMimeType) : false);
exports.vbArray = isFunction(global.VBArray);
function isFunction(value) {
return typeof value === 'function';
}
xhr = null; // Help gc
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],233:[function(require,module,exports){
(function (process,global,Buffer){
'use strict';
var _keys = require('babel-runtime/core-js/object/keys');
var _keys2 = _interopRequireDefault(_keys);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var capability = require('./capability');
var inherits = require('inherits');
var response = require('./response');
var stream = require('readable-stream');
var toArrayBuffer = require('to-arraybuffer');
var IncomingMessage = response.IncomingMessage;
var rStates = response.readyStates;
function decideMode(preferBinary, useFetch) {
if (capability.fetch && useFetch) {
return 'fetch';
} else if (capability.mozchunkedarraybuffer) {
return 'moz-chunked-arraybuffer';
} else if (capability.msstream) {
return 'ms-stream';
} else if (capability.arraybuffer && preferBinary) {
return 'arraybuffer';
} else if (capability.vbArray && preferBinary) {
return 'text:vbarray';
} else {
return 'text';
}
}
var ClientRequest = module.exports = function (opts) {
var self = this;
stream.Writable.call(self);
self._opts = opts;
self._body = [];
self._headers = {};
if (opts.auth) self.setHeader('Authorization', 'Basic ' + new Buffer(opts.auth).toString('base64'));
(0, _keys2.default)(opts.headers).forEach(function (name) {
self.setHeader(name, opts.headers[name]);
});
var preferBinary;
var useFetch = true;
if (opts.mode === 'disable-fetch' || 'requestTimeout' in opts && !capability.abortController) {
// If the use of XHR should be preferred. Not typically needed.
useFetch = false;
preferBinary = true;
} else if (opts.mode === 'prefer-streaming') {
// If streaming is a high priority but binary compatibility and
// the accuracy of the 'content-type' header aren't
preferBinary = false;
} else if (opts.mode === 'allow-wrong-content-type') {
// If streaming is more important than preserving the 'content-type' header
preferBinary = !capability.overrideMimeType;
} else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') {
// Use binary if text streaming may corrupt data or the content-type header, or for speed
preferBinary = true;
} else {
throw new Error('Invalid value for opts.mode');
}
self._mode = decideMode(preferBinary, useFetch);
self._fetchTimer = null;
self.on('finish', function () {
self._onFinish();
});
};
inherits(ClientRequest, stream.Writable);
ClientRequest.prototype.setHeader = function (name, value) {
var self = this;
var lowerName = name.toLowerCase();
// This check is not necessary, but it prevents warnings from browsers about setting unsafe
// headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but
// http-browserify did it, so I will too.
if (unsafeHeaders.indexOf(lowerName) !== -1) return;
self._headers[lowerName] = {
name: name,
value: value
};
};
ClientRequest.prototype.getHeader = function (name) {
var header = this._headers[name.toLowerCase()];
if (header) return header.value;
return null;
};
ClientRequest.prototype.removeHeader = function (name) {
var self = this;
delete self._headers[name.toLowerCase()];
};
ClientRequest.prototype._onFinish = function () {
var self = this;
if (self._destroyed) return;
var opts = self._opts;
var headersObj = self._headers;
var body = null;
if (opts.method !== 'GET' && opts.method !== 'HEAD') {
if (capability.arraybuffer) {
body = toArrayBuffer(Buffer.concat(self._body));
} else if (capability.blobConstructor) {
body = new global.Blob(self._body.map(function (buffer) {
return toArrayBuffer(buffer);
}), {
type: (headersObj['content-type'] || {}).value || ''
});
} else {
// get utf8 string
body = Buffer.concat(self._body).toString();
}
}
// create flattened list of headers
var headersList = [];
(0, _keys2.default)(headersObj).forEach(function (keyName) {
var name = headersObj[keyName].name;
var value = headersObj[keyName].value;
if (Array.isArray(value)) {
value.forEach(function (v) {
headersList.push([name, v]);
});
} else {
headersList.push([name, value]);
}
});
if (self._mode === 'fetch') {
var signal = null;
var fetchTimer = null;
if (capability.abortController) {
var controller = new AbortController();
signal = controller.signal;
self._fetchAbortController = controller;
if ('requestTimeout' in opts && opts.requestTimeout !== 0) {
self._fetchTimer = global.setTimeout(function () {
self.emit('requestTimeout');
if (self._fetchAbortController) self._fetchAbortController.abort();
}, opts.requestTimeout);
}
}
global.fetch(self._opts.url, {
method: self._opts.method,
headers: headersList,
body: body || undefined,
mode: 'cors',
credentials: opts.withCredentials ? 'include' : 'same-origin',
signal: signal
}).then(function (response) {
self._fetchResponse = response;
self._connect();
}, function (reason) {
global.clearTimeout(self._fetchTimer);
if (!self._destroyed) self.emit('error', reason);
});
} else {
var xhr = self._xhr = new global.XMLHttpRequest();
try {
xhr.open(self._opts.method, self._opts.url, true);
} catch (err) {
process.nextTick(function () {
self.emit('error', err);
});
return;
}
// Can't set responseType on really old browsers
if ('responseType' in xhr) xhr.responseType = self._mode.split(':')[0];
if ('withCredentials' in xhr) xhr.withCredentials = !!opts.withCredentials;
if (self._mode === 'text' && 'overrideMimeType' in xhr) xhr.overrideMimeType('text/plain; charset=x-user-defined');
if ('requestTimeout' in opts) {
xhr.timeout = opts.requestTimeout;
xhr.ontimeout = function () {
self.emit('requestTimeout');
};
}
headersList.forEach(function (header) {
xhr.setRequestHeader(header[0], header[1]);
});
self._response = null;
xhr.onreadystatechange = function () {
switch (xhr.readyState) {
case rStates.LOADING:
case rStates.DONE:
self._onXHRProgress();
break;
}
};
// Necessary for streaming in Firefox, since xhr.response is ONLY defined
// in onprogress, not in onreadystatechange with xhr.readyState = 3
if (self._mode === 'moz-chunked-arraybuffer') {
xhr.onprogress = function () {
self._onXHRProgress();
};
}
xhr.onerror = function () {
if (self._destroyed) return;
self.emit('error', new Error('XHR error'));
};
try {
xhr.send(body);
} catch (err) {
process.nextTick(function () {
self.emit('error', err);
});
return;
}
}
};
/**
* Checks if xhr.status is readable and non-zero, indicating no error.
* Even though the spec says it should be available in readyState 3,
* accessing it throws an exception in IE8
*/
function statusValid(xhr) {
try {
var status = xhr.status;
return status !== null && status !== 0;
} catch (e) {
return false;
}
}
ClientRequest.prototype._onXHRProgress = function () {
var self = this;
if (!statusValid(self._xhr) || self._destroyed) return;
if (!self._response) self._connect();
self._response._onXHRProgress();
};
ClientRequest.prototype._connect = function () {
var self = this;
if (self._destroyed) return;
self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode, self._fetchTimer);
self._response.on('error', function (err) {
self.emit('error', err);
});
self.emit('response', self._response);
};
ClientRequest.prototype._write = function (chunk, encoding, cb) {
var self = this;
self._body.push(chunk);
cb();
};
ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () {
var self = this;
self._destroyed = true;
global.clearTimeout(self._fetchTimer);
if (self._response) self._response._destroyed = true;
if (self._xhr) self._xhr.abort();else if (self._fetchAbortController) self._fetchAbortController.abort();
};
ClientRequest.prototype.end = function (data, encoding, cb) {
var self = this;
if (typeof data === 'function') {
cb = data;
data = undefined;
}
stream.Writable.prototype.end.call(self, data, encoding, cb);
};
ClientRequest.prototype.flushHeaders = function () {};
ClientRequest.prototype.setTimeout = function () {};
ClientRequest.prototype.setNoDelay = function () {};
ClientRequest.prototype.setSocketKeepAlive = function () {};
// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method
var unsafeHeaders = ['accept-charset', 'accept-encoding', 'access-control-request-headers', 'access-control-request-method', 'connection', 'content-length', 'cookie', 'cookie2', 'date', 'dnt', 'expect', 'host', 'keep-alive', 'origin', 'referer', 'te', 'trailer', 'transfer-encoding', 'upgrade', 'user-agent', 'via'];
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
},{"./capability":232,"./response":234,"_process":208,"babel-runtime/core-js/object/keys":60,"buffer":73,"inherits":196,"readable-stream":223,"to-arraybuffer":237}],234:[function(require,module,exports){
(function (process,global,Buffer){
'use strict';
var _promise = require('babel-runtime/core-js/promise');
var _promise2 = _interopRequireDefault(_promise);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var capability = require('./capability');
var inherits = require('inherits');
var stream = require('readable-stream');
var rStates = exports.readyStates = {
UNSENT: 0,
OPENED: 1,
HEADERS_RECEIVED: 2,
LOADING: 3,
DONE: 4
};
var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode, fetchTimer) {
var self = this;
stream.Readable.call(self);
self._mode = mode;
self.headers = {};
self.rawHeaders = [];
self.trailers = {};
self.rawTrailers = [];
// Fake the 'close' event, but only once 'end' fires
self.on('end', function () {
// The nextTick is necessary to prevent the 'request' module from causing an infinite loop
process.nextTick(function () {
self.emit('close');
});
});
if (mode === 'fetch') {
var read = function read() {
reader.read().then(function (result) {
if (self._destroyed) return;
if (result.done) {
global.clearTimeout(fetchTimer);
self.push(null);
return;
}
self.push(new Buffer(result.value));
read();
}).catch(function (err) {
global.clearTimeout(fetchTimer);
if (!self._destroyed) self.emit('error', err);
});
};
self._fetchResponse = response;
self.url = response.url;
self.statusCode = response.status;
self.statusMessage = response.statusText;
response.headers.forEach(function (header, key) {
self.headers[key.toLowerCase()] = header;
self.rawHeaders.push(key, header);
});
if (capability.writableStream) {
var writable = new WritableStream({
write: function write(chunk) {
return new _promise2.default(function (resolve, reject) {
if (self._destroyed) {
reject();
} else if (self.push(new Buffer(chunk))) {
resolve();
} else {
self._resumeFetch = resolve;
}
});
},
close: function close() {
global.clearTimeout(fetchTimer);
if (!self._destroyed) self.push(null);
},
abort: function abort(err) {
if (!self._destroyed) self.emit('error', err);
}
});
try {
response.body.pipeTo(writable).catch(function (err) {
global.clearTimeout(fetchTimer);
if (!self._destroyed) self.emit('error', err);
});
return;
} catch (e) {} // pipeTo method isn't defined. Can't find a better way to feature test this
}
// fallback for when writableStream or pipeTo aren't available
var reader = response.body.getReader();
read();
} else {
self._xhr = xhr;
self._pos = 0;
self.url = xhr.responseURL;
self.statusCode = xhr.status;
self.statusMessage = xhr.statusText;
var headers = xhr.getAllResponseHeaders().split(/\r?\n/);
headers.forEach(function (header) {
var matches = header.match(/^([^:]+):\s*(.*)/);
if (matches) {
var key = matches[1].toLowerCase();
if (key === 'set-cookie') {
if (self.headers[key] === undefined) {
self.headers[key] = [];
}
self.headers[key].push(matches[2]);
} else if (self.headers[key] !== undefined) {
self.headers[key] += ', ' + matches[2];
} else {
self.headers[key] = matches[2];
}
self.rawHeaders.push(matches[1], matches[2]);
}
});
self._charset = 'x-user-defined';
if (!capability.overrideMimeType) {
var mimeType = self.rawHeaders['mime-type'];
if (mimeType) {
var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/);
if (charsetMatch) {
self._charset = charsetMatch[1].toLowerCase();
}
}
if (!self._charset) self._charset = 'utf-8'; // best guess
}
}
};
inherits(IncomingMessage, stream.Readable);
IncomingMessage.prototype._read = function () {
var self = this;
var resolve = self._resumeFetch;
if (resolve) {
self._resumeFetch = null;
resolve();
}
};
IncomingMessage.prototype._onXHRProgress = function () {
var self = this;
var xhr = self._xhr;
var response = null;
switch (self._mode) {
case 'text:vbarray':
// For IE9
if (xhr.readyState !== rStates.DONE) break;
try {
// This fails in IE8
response = new global.VBArray(xhr.responseBody).toArray();
} catch (e) {}
if (response !== null) {
self.push(new Buffer(response));
break;
}
// Falls through in IE8
case 'text':
try {
// This will fail when readyState = 3 in IE9. Switch mode and wait for readyState = 4
response = xhr.responseText;
} catch (e) {
self._mode = 'text:vbarray';
break;
}
if (response.length > self._pos) {
var newData = response.substr(self._pos);
if (self._charset === 'x-user-defined') {
var buffer = new Buffer(newData.length);
for (var i = 0; i < newData.length; i++) {
buffer[i] = newData.charCodeAt(i) & 0xff;
}self.push(buffer);
} else {
self.push(newData, self._charset);
}
self._pos = response.length;
}
break;
case 'arraybuffer':
if (xhr.readyState !== rStates.DONE || !xhr.response) break;
response = xhr.response;
self.push(new Buffer(new Uint8Array(response)));
break;
case 'moz-chunked-arraybuffer':
// take whole
response = xhr.response;
if (xhr.readyState !== rStates.LOADING || !response) break;
self.push(new Buffer(new Uint8Array(response)));
break;
case 'ms-stream':
response = xhr.response;
if (xhr.readyState !== rStates.LOADING) break;
var reader = new global.MSStreamReader();
reader.onprogress = function () {
if (reader.result.byteLength > self._pos) {
self.push(new Buffer(new Uint8Array(reader.result.slice(self._pos))));
self._pos = reader.result.byteLength;
}
};
reader.onload = function () {
self.push(null);
};
// reader.onerror = ??? // TODO: this
reader.readAsArrayBuffer(response);
break;
}
// The ms-stream case handles end separately in reader.onload()
if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') {
self.push(null);
}
};
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
},{"./capability":232,"_process":208,"babel-runtime/core-js/promise":61,"buffer":73,"inherits":196,"readable-stream":223}],235:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node 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.
'use strict';
/*<replacement>*/
var Buffer = require('safe-buffer').Buffer;
/*</replacement>*/
var isEncoding = Buffer.isEncoding || function (encoding) {
encoding = '' + encoding;
switch (encoding && encoding.toLowerCase()) {
case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
return true;
default:
return false;
}
};
function _normalizeEncoding(enc) {
if (!enc) return 'utf8';
var retried;
while (true) {
switch (enc) {
case 'utf8':
case 'utf-8':
return 'utf8';
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return 'utf16le';
case 'latin1':
case 'binary':
return 'latin1';
case 'base64':
case 'ascii':
case 'hex':
return enc;
default:
if (retried) return; // undefined
enc = ('' + enc).toLowerCase();
retried = true;
}
}
};
// Do not cache `Buffer.isEncoding` when checking encoding names as some
// modules monkey-patch it to support additional encodings
function normalizeEncoding(enc) {
var nenc = _normalizeEncoding(enc);
if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
return nenc || enc;
}
// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters.
exports.StringDecoder = StringDecoder;
function StringDecoder(encoding) {
this.encoding = normalizeEncoding(encoding);
var nb;
switch (this.encoding) {
case 'utf16le':
this.text = utf16Text;
this.end = utf16End;
nb = 4;
break;
case 'utf8':
this.fillLast = utf8FillLast;
nb = 4;
break;
case 'base64':
this.text = base64Text;
this.end = base64End;
nb = 3;
break;
default:
this.write = simpleWrite;
this.end = simpleEnd;
return;
}
this.lastNeed = 0;
this.lastTotal = 0;
this.lastChar = Buffer.allocUnsafe(nb);
}
StringDecoder.prototype.write = function (buf) {
if (buf.length === 0) return '';
var r;
var i;
if (this.lastNeed) {
r = this.fillLast(buf);
if (r === undefined) return '';
i = this.lastNeed;
this.lastNeed = 0;
} else {
i = 0;
}
if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
return r || '';
};
StringDecoder.prototype.end = utf8End;
// Returns only complete characters in a Buffer
StringDecoder.prototype.text = utf8Text;
// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
StringDecoder.prototype.fillLast = function (buf) {
if (this.lastNeed <= buf.length) {
buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
return this.lastChar.toString(this.encoding, 0, this.lastTotal);
}
buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
this.lastNeed -= buf.length;
};
// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
// continuation byte. If an invalid byte is detected, -2 is returned.
function utf8CheckByte(byte) {
if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
return byte >> 6 === 0x02 ? -1 : -2;
}
// Checks at most 3 bytes at the end of a Buffer in order to detect an
// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
// needed to complete the UTF-8 character (if applicable) are returned.
function utf8CheckIncomplete(self, buf, i) {
var j = buf.length - 1;
if (j < i) return 0;
var nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) self.lastNeed = nb - 1;
return nb;
}
if (--j < i || nb === -2) return 0;
nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) self.lastNeed = nb - 2;
return nb;
}
if (--j < i || nb === -2) return 0;
nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) {
if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
}
return nb;
}
return 0;
}
// Validates as many continuation bytes for a multi-byte UTF-8 character as
// needed or are available. If we see a non-continuation byte where we expect
// one, we "replace" the validated continuation bytes we've seen so far with
// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
// behavior. The continuation byte check is included three times in the case
// where all of the continuation bytes for a character exist in the same buffer.
// It is also done this way as a slight performance increase instead of using a
// loop.
function utf8CheckExtraBytes(self, buf, p) {
if ((buf[0] & 0xC0) !== 0x80) {
self.lastNeed = 0;
return '\uFFFD';
}
if (self.lastNeed > 1 && buf.length > 1) {
if ((buf[1] & 0xC0) !== 0x80) {
self.lastNeed = 1;
return '\uFFFD';
}
if (self.lastNeed > 2 && buf.length > 2) {
if ((buf[2] & 0xC0) !== 0x80) {
self.lastNeed = 2;
return '\uFFFD';
}
}
}
}
// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
function utf8FillLast(buf) {
var p = this.lastTotal - this.lastNeed;
var r = utf8CheckExtraBytes(this, buf, p);
if (r !== undefined) return r;
if (this.lastNeed <= buf.length) {
buf.copy(this.lastChar, p, 0, this.lastNeed);
return this.lastChar.toString(this.encoding, 0, this.lastTotal);
}
buf.copy(this.lastChar, p, 0, buf.length);
this.lastNeed -= buf.length;
}
// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
// partial character, the character's bytes are buffered until the required
// number of bytes are available.
function utf8Text(buf, i) {
var total = utf8CheckIncomplete(this, buf, i);
if (!this.lastNeed) return buf.toString('utf8', i);
this.lastTotal = total;
var end = buf.length - (total - this.lastNeed);
buf.copy(this.lastChar, 0, end);
return buf.toString('utf8', i, end);
}
// For UTF-8, a replacement character is added when ending on a partial
// character.
function utf8End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) return r + '\uFFFD';
return r;
}
// UTF-16LE typically needs two bytes per character, but even if we have an even
// number of bytes available, we need to check if we end on a leading/high
// surrogate. In that case, we need to wait for the next two bytes in order to
// decode the last character properly.
function utf16Text(buf, i) {
if ((buf.length - i) % 2 === 0) {
var r = buf.toString('utf16le', i);
if (r) {
var c = r.charCodeAt(r.length - 1);
if (c >= 0xD800 && c <= 0xDBFF) {
this.lastNeed = 2;
this.lastTotal = 4;
this.lastChar[0] = buf[buf.length - 2];
this.lastChar[1] = buf[buf.length - 1];
return r.slice(0, -1);
}
}
return r;
}
this.lastNeed = 1;
this.lastTotal = 2;
this.lastChar[0] = buf[buf.length - 1];
return buf.toString('utf16le', i, buf.length - 1);
}
// For UTF-16LE we do not explicitly append special replacement characters if we
// end on a partial character, we simply let v8 handle that.
function utf16End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) {
var end = this.lastTotal - this.lastNeed;
return r + this.lastChar.toString('utf16le', 0, end);
}
return r;
}
function base64Text(buf, i) {
var n = (buf.length - i) % 3;
if (n === 0) return buf.toString('base64', i);
this.lastNeed = 3 - n;
this.lastTotal = 3;
if (n === 1) {
this.lastChar[0] = buf[buf.length - 1];
} else {
this.lastChar[0] = buf[buf.length - 2];
this.lastChar[1] = buf[buf.length - 1];
}
return buf.toString('base64', i, buf.length - n);
}
function base64End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
return r;
}
// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
function simpleWrite(buf) {
return buf.toString(this.encoding);
}
function simpleEnd(buf) {
return buf && buf.length ? this.write(buf) : '';
}
},{"safe-buffer":228}],236:[function(require,module,exports){
(function (setImmediate,clearImmediate){
var nextTick = require('process/browser.js').nextTick;
var apply = Function.prototype.apply;
var slice = Array.prototype.slice;
var immediateIds = {};
var nextImmediateId = 0;
// DOM APIs, for completeness
exports.setTimeout = function() {
return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
};
exports.setInterval = function() {
return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
};
exports.clearTimeout =
exports.clearInterval = function(timeout) { timeout.close(); };
function Timeout(id, clearFn) {
this._id = id;
this._clearFn = clearFn;
}
Timeout.prototype.unref = Timeout.prototype.ref = function() {};
Timeout.prototype.close = function() {
this._clearFn.call(window, this._id);
};
// Does not start the time, just sets up the members needed.
exports.enroll = function(item, msecs) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = msecs;
};
exports.unenroll = function(item) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = -1;
};
exports._unrefActive = exports.active = function(item) {
clearTimeout(item._idleTimeoutId);
var msecs = item._idleTimeout;
if (msecs >= 0) {
item._idleTimeoutId = setTimeout(function onTimeout() {
if (item._onTimeout)
item._onTimeout();
}, msecs);
}
};
// That's not how node.js implements it but the exposed api is the same.
exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
var id = nextImmediateId++;
var args = arguments.length < 2 ? false : slice.call(arguments, 1);
immediateIds[id] = true;
nextTick(function onNextTick() {
if (immediateIds[id]) {
// fn.call() is faster so we optimize for the common use-case
// @see http://jsperf.com/call-apply-segu
if (args) {
fn.apply(null, args);
} else {
fn.call(null);
}
// Prevent ids from leaking
exports.clearImmediate(id);
}
});
return id;
};
exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
delete immediateIds[id];
};
}).call(this,require("timers").setImmediate,require("timers").clearImmediate)
},{"process/browser.js":208,"timers":236}],237:[function(require,module,exports){
var Buffer = require('buffer').Buffer
module.exports = function (buf) {
// If the buffer is backed by a Uint8Array, a faster version will work
if (buf instanceof Uint8Array) {
// If the buffer isn't a subarray, return the underlying ArrayBuffer
if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) {
return buf.buffer
} else if (typeof buf.buffer.slice === 'function') {
// Otherwise we need to get a proper copy
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
}
}
if (Buffer.isBuffer(buf)) {
// This is the slow version that will work with any Buffer
// implementation (even in old browsers)
var arrayCopy = new Uint8Array(buf.length)
var len = buf.length
for (var i = 0; i < len; i++) {
arrayCopy[i] = buf[i]
}
return arrayCopy.buffer
} else {
throw new Error('Argument must be a Buffer')
}
}
},{"buffer":73}],238:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node 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.
'use strict';
var punycode = require('punycode');
var util = require('./util');
exports.parse = urlParse;
exports.resolve = urlResolve;
exports.resolveObject = urlResolveObject;
exports.format = urlFormat;
exports.Url = Url;
function Url() {
this.protocol = null;
this.slashes = null;
this.auth = null;
this.host = null;
this.port = null;
this.hostname = null;
this.hash = null;
this.search = null;
this.query = null;
this.pathname = null;
this.path = null;
this.href = null;
}
// Reference: RFC 3986, RFC 1808, RFC 2396
// define these here so at least they only have to be
// compiled once on the first module load.
var protocolPattern = /^([a-z0-9.+-]+:)/i,
portPattern = /:[0-9]*$/,
// Special case for a simple path URL
simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
// RFC 2396: characters reserved for delimiting URLs.
// We actually just auto-escape these.
delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
// RFC 2396: characters not allowed for various reasons.
unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
// Allowed by RFCs, but cause of XSS attacks. Always escape these.
autoEscape = ['\''].concat(unwise),
// Characters that are never ever allowed in a hostname.
// Note that any invalid chars are also handled, but these
// are the ones that are *expected* to be seen, so we fast-path
// them.
nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
hostEndingChars = ['/', '?', '#'],
hostnameMaxLen = 255,
hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
// protocols that can allow "unsafe" and "unwise" chars.
unsafeProtocol = {
'javascript': true,
'javascript:': true
},
// protocols that never have a hostname.
hostlessProtocol = {
'javascript': true,
'javascript:': true
},
// protocols that always contain a // bit.
slashedProtocol = {
'http': true,
'https': true,
'ftp': true,
'gopher': true,
'file': true,
'http:': true,
'https:': true,
'ftp:': true,
'gopher:': true,
'file:': true
},
querystring = require('querystring');
function urlParse(url, parseQueryString, slashesDenoteHost) {
if (url && util.isObject(url) && url instanceof Url) return url;
var u = new Url;
u.parse(url, parseQueryString, slashesDenoteHost);
return u;
}
Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
if (!util.isString(url)) {
throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
}
// Copy chrome, IE, opera backslash-handling behavior.
// Back slashes before the query string get converted to forward slashes
// See: https://code.google.com/p/chromium/issues/detail?id=25916
var queryIndex = url.indexOf('?'),
splitter =
(queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
uSplit = url.split(splitter),
slashRegex = /\\/g;
uSplit[0] = uSplit[0].replace(slashRegex, '/');
url = uSplit.join(splitter);
var rest = url;
// trim before proceeding.
// This is to support parse stuff like " http://foo.com \n"
rest = rest.trim();
if (!slashesDenoteHost && url.split('#').length === 1) {
// Try fast path regexp
var simplePath = simplePathPattern.exec(rest);
if (simplePath) {
this.path = rest;
this.href = rest;
this.pathname = simplePath[1];
if (simplePath[2]) {
this.search = simplePath[2];
if (parseQueryString) {
this.query = querystring.parse(this.search.substr(1));
} else {
this.query = this.search.substr(1);
}
} else if (parseQueryString) {
this.search = '';
this.query = {};
}
return this;
}
}
var proto = protocolPattern.exec(rest);
if (proto) {
proto = proto[0];
var lowerProto = proto.toLowerCase();
this.protocol = lowerProto;
rest = rest.substr(proto.length);
}
// figure out if it's got a host
// user@server is *always* interpreted as a hostname, and url
// resolution will treat //foo/bar as host=foo,path=bar because that's
// how the browser resolves relative URLs.
if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
var slashes = rest.substr(0, 2) === '//';
if (slashes && !(proto && hostlessProtocol[proto])) {
rest = rest.substr(2);
this.slashes = true;
}
}
if (!hostlessProtocol[proto] &&
(slashes || (proto && !slashedProtocol[proto]))) {
// there's a hostname.
// the first instance of /, ?, ;, or # ends the host.
//
// If there is an @ in the hostname, then non-host chars *are* allowed
// to the left of the last @ sign, unless some host-ending character
// comes *before* the @-sign.
// URLs are obnoxious.
//
// ex:
// http://a@b@c/ => user:a@b host:c
// http://a@b?@c => user:a host:c path:/?@c
// v0.12 TODO(isaacs): This is not quite how Chrome does things.
// Review our test case against browsers more comprehensively.
// find the first instance of any hostEndingChars
var hostEnd = -1;
for (var i = 0; i < hostEndingChars.length; i++) {
var hec = rest.indexOf(hostEndingChars[i]);
if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
hostEnd = hec;
}
// at this point, either we have an explicit point where the
// auth portion cannot go past, or the last @ char is the decider.
var auth, atSign;
if (hostEnd === -1) {
// atSign can be anywhere.
atSign = rest.lastIndexOf('@');
} else {
// atSign must be in auth portion.
// http://a@b/c@d => host:b auth:a path:/c@d
atSign = rest.lastIndexOf('@', hostEnd);
}
// Now we have a portion which is definitely the auth.
// Pull that off.
if (atSign !== -1) {
auth = rest.slice(0, atSign);
rest = rest.slice(atSign + 1);
this.auth = decodeURIComponent(auth);
}
// the host is the remaining to the left of the first non-host char
hostEnd = -1;
for (var i = 0; i < nonHostChars.length; i++) {
var hec = rest.indexOf(nonHostChars[i]);
if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
hostEnd = hec;
}
// if we still have not hit it, then the entire thing is a host.
if (hostEnd === -1)
hostEnd = rest.length;
this.host = rest.slice(0, hostEnd);
rest = rest.slice(hostEnd);
// pull out port.
this.parseHost();
// we've indicated that there is a hostname,
// so even if it's empty, it has to be present.
this.hostname = this.hostname || '';
// if hostname begins with [ and ends with ]
// assume that it's an IPv6 address.
var ipv6Hostname = this.hostname[0] === '[' &&
this.hostname[this.hostname.length - 1] === ']';
// validate a little.
if (!ipv6Hostname) {
var hostparts = this.hostname.split(/\./);
for (var i = 0, l = hostparts.length; i < l; i++) {
var part = hostparts[i];
if (!part) continue;
if (!part.match(hostnamePartPattern)) {
var newpart = '';
for (var j = 0, k = part.length; j < k; j++) {
if (part.charCodeAt(j) > 127) {
// we replace non-ASCII char with a temporary placeholder
// we need this to make sure size of hostname is not
// broken by replacing non-ASCII by nothing
newpart += 'x';
} else {
newpart += part[j];
}
}
// we test again with ASCII char only
if (!newpart.match(hostnamePartPattern)) {
var validParts = hostparts.slice(0, i);
var notHost = hostparts.slice(i + 1);
var bit = part.match(hostnamePartStart);
if (bit) {
validParts.push(bit[1]);
notHost.unshift(bit[2]);
}
if (notHost.length) {
rest = '/' + notHost.join('.') + rest;
}
this.hostname = validParts.join('.');
break;
}
}
}
}
if (this.hostname.length > hostnameMaxLen) {
this.hostname = '';
} else {
// hostnames are always lower case.
this.hostname = this.hostname.toLowerCase();
}
if (!ipv6Hostname) {
// IDNA Support: Returns a punycoded representation of "domain".
// It only converts parts of the domain name that
// have non-ASCII characters, i.e. it doesn't matter if
// you call it with a domain that already is ASCII-only.
this.hostname = punycode.toASCII(this.hostname);
}
var p = this.port ? ':' + this.port : '';
var h = this.hostname || '';
this.host = h + p;
this.href += this.host;
// strip [ and ] from the hostname
// the host field still retains them, though
if (ipv6Hostname) {
this.hostname = this.hostname.substr(1, this.hostname.length - 2);
if (rest[0] !== '/') {
rest = '/' + rest;
}
}
}
// now rest is set to the post-host stuff.
// chop off any delim chars.
if (!unsafeProtocol[lowerProto]) {
// First, make 100% sure that any "autoEscape" chars get
// escaped, even if encodeURIComponent doesn't think they
// need to be.
for (var i = 0, l = autoEscape.length; i < l; i++) {
var ae = autoEscape[i];
if (rest.indexOf(ae) === -1)
continue;
var esc = encodeURIComponent(ae);
if (esc === ae) {
esc = escape(ae);
}
rest = rest.split(ae).join(esc);
}
}
// chop off from the tail first.
var hash = rest.indexOf('#');
if (hash !== -1) {
// got a fragment string.
this.hash = rest.substr(hash);
rest = rest.slice(0, hash);
}
var qm = rest.indexOf('?');
if (qm !== -1) {
this.search = rest.substr(qm);
this.query = rest.substr(qm + 1);
if (parseQueryString) {
this.query = querystring.parse(this.query);
}
rest = rest.slice(0, qm);
} else if (parseQueryString) {
// no query string, but parseQueryString still requested
this.search = '';
this.query = {};
}
if (rest) this.pathname = rest;
if (slashedProtocol[lowerProto] &&
this.hostname && !this.pathname) {
this.pathname = '/';
}
//to support http.request
if (this.pathname || this.search) {
var p = this.pathname || '';
var s = this.search || '';
this.path = p + s;
}
// finally, reconstruct the href based on what has been validated.
this.href = this.format();
return this;
};
// format a parsed object into a url string
function urlFormat(obj) {
// ensure it's an object, and not a string url.
// If it's an obj, this is a no-op.
// this way, you can call url_format() on strings
// to clean up potentially wonky urls.
if (util.isString(obj)) obj = urlParse(obj);
if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
return obj.format();
}
Url.prototype.format = function() {
var auth = this.auth || '';
if (auth) {
auth = encodeURIComponent(auth);
auth = auth.replace(/%3A/i, ':');
auth += '@';
}
var protocol = this.protocol || '',
pathname = this.pathname || '',
hash = this.hash || '',
host = false,
query = '';
if (this.host) {
host = auth + this.host;
} else if (this.hostname) {
host = auth + (this.hostname.indexOf(':') === -1 ?
this.hostname :
'[' + this.hostname + ']');
if (this.port) {
host += ':' + this.port;
}
}
if (this.query &&
util.isObject(this.query) &&
Object.keys(this.query).length) {
query = querystring.stringify(this.query);
}
var search = this.search || (query && ('?' + query)) || '';
if (protocol && protocol.substr(-1) !== ':') protocol += ':';
// only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
// unless they had them to begin with.
if (this.slashes ||
(!protocol || slashedProtocol[protocol]) && host !== false) {
host = '//' + (host || '');
if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
} else if (!host) {
host = '';
}
if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
if (search && search.charAt(0) !== '?') search = '?' + search;
pathname = pathname.replace(/[?#]/g, function(match) {
return encodeURIComponent(match);
});
search = search.replace('#', '%23');
return protocol + host + pathname + search + hash;
};
function urlResolve(source, relative) {
return urlParse(source, false, true).resolve(relative);
}
Url.prototype.resolve = function(relative) {
return this.resolveObject(urlParse(relative, false, true)).format();
};
function urlResolveObject(source, relative) {
if (!source) return relative;
return urlParse(source, false, true).resolveObject(relative);
}
Url.prototype.resolveObject = function(relative) {
if (util.isString(relative)) {
var rel = new Url();
rel.parse(relative, false, true);
relative = rel;
}
var result = new Url();
var tkeys = Object.keys(this);
for (var tk = 0; tk < tkeys.length; tk++) {
var tkey = tkeys[tk];
result[tkey] = this[tkey];
}
// hash is always overridden, no matter what.
// even href="" will remove it.
result.hash = relative.hash;
// if the relative url is empty, then there's nothing left to do here.
if (relative.href === '') {
result.href = result.format();
return result;
}
// hrefs like //foo/bar always cut to the protocol.
if (relative.slashes && !relative.protocol) {
// take everything except the protocol from relative
var rkeys = Object.keys(relative);
for (var rk = 0; rk < rkeys.length; rk++) {
var rkey = rkeys[rk];
if (rkey !== 'protocol')
result[rkey] = relative[rkey];
}
//urlParse appends trailing / to urls like http://www.example.com
if (slashedProtocol[result.protocol] &&
result.hostname && !result.pathname) {
result.path = result.pathname = '/';
}
result.href = result.format();
return result;
}
if (relative.protocol && relative.protocol !== result.protocol) {
// if it's a known url protocol, then changing
// the protocol does weird things
// first, if it's not file:, then we MUST have a host,
// and if there was a path
// to begin with, then we MUST have a path.
// if it is file:, then the host is dropped,
// because that's known to be hostless.
// anything else is assumed to be absolute.
if (!slashedProtocol[relative.protocol]) {
var keys = Object.keys(relative);
for (var v = 0; v < keys.length; v++) {
var k = keys[v];
result[k] = relative[k];
}
result.href = result.format();
return result;
}
result.protocol = relative.protocol;
if (!relative.host && !hostlessProtocol[relative.protocol]) {
var relPath = (relative.pathname || '').split('/');
while (relPath.length && !(relative.host = relPath.shift()));
if (!relative.host) relative.host = '';
if (!relative.hostname) relative.hostname = '';
if (relPath[0] !== '') relPath.unshift('');
if (relPath.length < 2) relPath.unshift('');
result.pathname = relPath.join('/');
} else {
result.pathname = relative.pathname;
}
result.search = relative.search;
result.query = relative.query;
result.host = relative.host || '';
result.auth = relative.auth;
result.hostname = relative.hostname || relative.host;
result.port = relative.port;
// to support http.request
if (result.pathname || result.search) {
var p = result.pathname || '';
var s = result.search || '';
result.path = p + s;
}
result.slashes = result.slashes || relative.slashes;
result.href = result.format();
return result;
}
var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
isRelAbs = (
relative.host ||
relative.pathname && relative.pathname.charAt(0) === '/'
),
mustEndAbs = (isRelAbs || isSourceAbs ||
(result.host && relative.pathname)),
removeAllDots = mustEndAbs,
srcPath = result.pathname && result.pathname.split('/') || [],
relPath = relative.pathname && relative.pathname.split('/') || [],
psychotic = result.protocol && !slashedProtocol[result.protocol];
// if the url is a non-slashed url, then relative
// links like ../.. should be able
// to crawl up to the hostname, as well. This is strange.
// result.protocol has already been set by now.
// Later on, put the first path part into the host field.
if (psychotic) {
result.hostname = '';
result.port = null;
if (result.host) {
if (srcPath[0] === '') srcPath[0] = result.host;
else srcPath.unshift(result.host);
}
result.host = '';
if (relative.protocol) {
relative.hostname = null;
relative.port = null;
if (relative.host) {
if (relPath[0] === '') relPath[0] = relative.host;
else relPath.unshift(relative.host);
}
relative.host = null;
}
mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
}
if (isRelAbs) {
// it's absolute.
result.host = (relative.host || relative.host === '') ?
relative.host : result.host;
result.hostname = (relative.hostname || relative.hostname === '') ?
relative.hostname : result.hostname;
result.search = relative.search;
result.query = relative.query;
srcPath = relPath;
// fall through to the dot-handling below.
} else if (relPath.length) {
// it's relative
// throw away the existing file, and take the new path instead.
if (!srcPath) srcPath = [];
srcPath.pop();
srcPath = srcPath.concat(relPath);
result.search = relative.search;
result.query = relative.query;
} else if (!util.isNullOrUndefined(relative.search)) {
// just pull out the search.
// like href='?foo'.
// Put this after the other two cases because it simplifies the booleans
if (psychotic) {
result.hostname = result.host = srcPath.shift();
//occationaly the auth can get stuck only in host
//this especially happens in cases like
//url.resolveObject('mailto:local1@domain1', 'local2@domain2')
var authInHost = result.host && result.host.indexOf('@') > 0 ?
result.host.split('@') : false;
if (authInHost) {
result.auth = authInHost.shift();
result.host = result.hostname = authInHost.shift();
}
}
result.search = relative.search;
result.query = relative.query;
//to support http.request
if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
result.path = (result.pathname ? result.pathname : '') +
(result.search ? result.search : '');
}
result.href = result.format();
return result;
}
if (!srcPath.length) {
// no path at all. easy.
// we've already handled the other stuff above.
result.pathname = null;
//to support http.request
if (result.search) {
result.path = '/' + result.search;
} else {
result.path = null;
}
result.href = result.format();
return result;
}
// if a url ENDs in . or .., then it must get a trailing slash.
// however, if it ends in anything else non-slashy,
// then it must NOT get a trailing slash.
var last = srcPath.slice(-1)[0];
var hasTrailingSlash = (
(result.host || relative.host || srcPath.length > 1) &&
(last === '.' || last === '..') || last === '');
// strip single dots, resolve double dots to parent dir
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = srcPath.length; i >= 0; i--) {
last = srcPath[i];
if (last === '.') {
srcPath.splice(i, 1);
} else if (last === '..') {
srcPath.splice(i, 1);
up++;
} else if (up) {
srcPath.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (!mustEndAbs && !removeAllDots) {
for (; up--; up) {
srcPath.unshift('..');
}
}
if (mustEndAbs && srcPath[0] !== '' &&
(!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
srcPath.unshift('');
}
if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
srcPath.push('');
}
var isAbsolute = srcPath[0] === '' ||
(srcPath[0] && srcPath[0].charAt(0) === '/');
// put the host back
if (psychotic) {
result.hostname = result.host = isAbsolute ? '' :
srcPath.length ? srcPath.shift() : '';
//occationaly the auth can get stuck only in host
//this especially happens in cases like
//url.resolveObject('mailto:local1@domain1', 'local2@domain2')
var authInHost = result.host && result.host.indexOf('@') > 0 ?
result.host.split('@') : false;
if (authInHost) {
result.auth = authInHost.shift();
result.host = result.hostname = authInHost.shift();
}
}
mustEndAbs = mustEndAbs || (result.host && srcPath.length);
if (mustEndAbs && !isAbsolute) {
srcPath.unshift('');
}
if (!srcPath.length) {
result.pathname = null;
result.path = null;
} else {
result.pathname = srcPath.join('/');
}
//to support request.http
if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
result.path = (result.pathname ? result.pathname : '') +
(result.search ? result.search : '');
}
result.auth = relative.auth || result.auth;
result.slashes = result.slashes || relative.slashes;
result.href = result.format();
return result;
};
Url.prototype.parseHost = function() {
var host = this.host;
var port = portPattern.exec(host);
if (port) {
port = port[0];
if (port !== ':') {
this.port = port.substr(1);
}
host = host.substr(0, host.length - port.length);
}
if (host) this.hostname = host;
};
},{"./util":239,"punycode":209,"querystring":212}],239:[function(require,module,exports){
'use strict';
module.exports = {
isString: function(arg) {
return typeof(arg) === 'string';
},
isObject: function(arg) {
return typeof(arg) === 'object' && arg !== null;
},
isNull: function(arg) {
return arg === null;
},
isNullOrUndefined: function(arg) {
return arg == null;
}
};
},{}],240:[function(require,module,exports){
(function (global){
/**
* Module exports.
*/
module.exports = deprecate;
/**
* Mark that a method should not be used.
* Returns a modified function which warns once by default.
*
* If `localStorage.noDeprecation = true` is set, then it is a no-op.
*
* If `localStorage.throwDeprecation = true` is set, then deprecated functions
* will throw an Error when invoked.
*
* If `localStorage.traceDeprecation = true` is set, then deprecated functions
* will invoke `console.trace()` instead of `console.error()`.
*
* @param {Function} fn - the function to deprecate
* @param {String} msg - the string to print to the console when `fn` is invoked
* @returns {Function} a new "deprecated" version of `fn`
* @api public
*/
function deprecate (fn, msg) {
if (config('noDeprecation')) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (config('throwDeprecation')) {
throw new Error(msg);
} else if (config('traceDeprecation')) {
console.trace(msg);
} else {
console.warn(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
}
/**
* Checks `localStorage` for boolean values for the given `name`.
*
* @param {String} name
* @returns {Boolean}
* @api private
*/
function config (name) {
// accessing global.localStorage can trigger a DOMException in sandboxed iframes
try {
if (!global.localStorage) return false;
} catch (_) {
return false;
}
var val = global.localStorage[name];
if (null == val) return false;
return String(val).toLowerCase() === 'true';
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],241:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],242:[function(require,module,exports){
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
},{}],243:[function(require,module,exports){
(function (process,global){
// Copyright Joyent, Inc. and other Node 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 formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = require('./support/isBuffer');
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = require('inherits');
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./support/isBuffer":242,"_process":208,"inherits":241}],244:[function(require,module,exports){
"use strict";
// Generated by CoffeeScript 1.12.7
(function () {
"use strict";
exports.stripBOM = function (str) {
if (str[0] === "\uFEFF") {
return str.substring(1);
} else {
return str;
}
};
}).call(undefined);
},{}],245:[function(require,module,exports){
'use strict';
var _typeof2 = require('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
var _keys = require('babel-runtime/core-js/object/keys');
var _keys2 = _interopRequireDefault(_keys);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by CoffeeScript 1.12.7
(function () {
"use strict";
var builder,
defaults,
escapeCDATA,
requiresCDATA,
wrapCDATA,
hasProp = {}.hasOwnProperty;
builder = require('xmlbuilder');
defaults = require('./defaults').defaults;
requiresCDATA = function requiresCDATA(entry) {
return typeof entry === "string" && (entry.indexOf('&') >= 0 || entry.indexOf('>') >= 0 || entry.indexOf('<') >= 0);
};
wrapCDATA = function wrapCDATA(entry) {
return "<![CDATA[" + escapeCDATA(entry) + "]]>";
};
escapeCDATA = function escapeCDATA(entry) {
return entry.replace(']]>', ']]]]><![CDATA[>');
};
exports.Builder = function () {
function Builder(opts) {
var key, ref, value;
this.options = {};
ref = defaults["0.2"];
for (key in ref) {
if (!hasProp.call(ref, key)) continue;
value = ref[key];
this.options[key] = value;
}
for (key in opts) {
if (!hasProp.call(opts, key)) continue;
value = opts[key];
this.options[key] = value;
}
}
Builder.prototype.buildObject = function (rootObj) {
var attrkey, charkey, render, rootElement, rootName;
attrkey = this.options.attrkey;
charkey = this.options.charkey;
if ((0, _keys2.default)(rootObj).length === 1 && this.options.rootName === defaults['0.2'].rootName) {
rootName = (0, _keys2.default)(rootObj)[0];
rootObj = rootObj[rootName];
} else {
rootName = this.options.rootName;
}
render = function (_this) {
return function (element, obj) {
var attr, child, entry, index, key, value;
if ((typeof obj === 'undefined' ? 'undefined' : (0, _typeof3.default)(obj)) !== 'object') {
if (_this.options.cdata && requiresCDATA(obj)) {
element.raw(wrapCDATA(obj));
} else {
element.txt(obj);
}
} else if (Array.isArray(obj)) {
for (index in obj) {
if (!hasProp.call(obj, index)) continue;
child = obj[index];
for (key in child) {
entry = child[key];
element = render(element.ele(key), entry).up();
}
}
} else {
for (key in obj) {
if (!hasProp.call(obj, key)) continue;
child = obj[key];
if (key === attrkey) {
if ((typeof child === 'undefined' ? 'undefined' : (0, _typeof3.default)(child)) === "object") {
for (attr in child) {
value = child[attr];
element = element.att(attr, value);
}
}
} else if (key === charkey) {
if (_this.options.cdata && requiresCDATA(child)) {
element = element.raw(wrapCDATA(child));
} else {
element = element.txt(child);
}
} else if (Array.isArray(child)) {
for (index in child) {
if (!hasProp.call(child, index)) continue;
entry = child[index];
if (typeof entry === 'string') {
if (_this.options.cdata && requiresCDATA(entry)) {
element = element.ele(key).raw(wrapCDATA(entry)).up();
} else {
element = element.ele(key, entry).up();
}
} else {
element = render(element.ele(key), entry).up();
}
}
} else if ((typeof child === 'undefined' ? 'undefined' : (0, _typeof3.default)(child)) === "object") {
element = render(element.ele(key), child).up();
} else {
if (typeof child === 'string' && _this.options.cdata && requiresCDATA(child)) {
element = element.ele(key).raw(wrapCDATA(child)).up();
} else {
if (child == null) {
child = '';
}
element = element.ele(key, child.toString()).up();
}
}
}
}
return element;
};
}(this);
rootElement = builder.create(rootName, this.options.xmldec, this.options.doctype, {
headless: this.options.headless,
allowSurrogateChars: this.options.allowSurrogateChars
});
return render(rootElement, rootObj).end(this.options.renderOpts);
};
return Builder;
}();
}).call(undefined);
},{"./defaults":246,"babel-runtime/core-js/object/keys":60,"babel-runtime/helpers/typeof":67,"xmlbuilder":282}],246:[function(require,module,exports){
"use strict";
// Generated by CoffeeScript 1.12.7
(function () {
exports.defaults = {
"0.1": {
explicitCharkey: false,
trim: true,
normalize: true,
normalizeTags: false,
attrkey: "@",
charkey: "#",
explicitArray: false,
ignoreAttrs: false,
mergeAttrs: false,
explicitRoot: false,
validator: null,
xmlns: false,
explicitChildren: false,
childkey: '@@',
charsAsChildren: false,
includeWhiteChars: false,
async: false,
strict: true,
attrNameProcessors: null,
attrValueProcessors: null,
tagNameProcessors: null,
valueProcessors: null,
emptyTag: ''
},
"0.2": {
explicitCharkey: false,
trim: false,
normalize: false,
normalizeTags: false,
attrkey: "$",
charkey: "_",
explicitArray: true,
ignoreAttrs: false,
mergeAttrs: false,
explicitRoot: true,
validator: null,
xmlns: false,
explicitChildren: false,
preserveChildrenOrder: false,
childkey: '$$',
charsAsChildren: false,
includeWhiteChars: false,
async: false,
strict: true,
attrNameProcessors: null,
attrValueProcessors: null,
tagNameProcessors: null,
valueProcessors: null,
rootName: 'root',
xmldec: {
'version': '1.0',
'encoding': 'UTF-8',
'standalone': true
},
doctype: null,
renderOpts: {
'pretty': true,
'indent': ' ',
'newline': '\n'
},
headless: false,
chunkSize: 10000,
emptyTag: '',
cdata: false
}
};
}).call(undefined);
},{}],247:[function(require,module,exports){
'use strict';
var _promise = require('babel-runtime/core-js/promise');
var _promise2 = _interopRequireDefault(_promise);
var _getOwnPropertyNames = require('babel-runtime/core-js/object/get-own-property-names');
var _getOwnPropertyNames2 = _interopRequireDefault(_getOwnPropertyNames);
var _keys = require('babel-runtime/core-js/object/keys');
var _keys2 = _interopRequireDefault(_keys);
var _typeof2 = require('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by CoffeeScript 1.12.7
(function () {
"use strict";
var bom,
defaults,
events,
isEmpty,
processItem,
processors,
sax,
setImmediate,
bind = function bind(fn, me) {
return function () {
return fn.apply(me, arguments);
};
},
extend = function extend(child, parent) {
for (var key in parent) {
if (hasProp.call(parent, key)) child[key] = parent[key];
}function ctor() {
this.constructor = child;
}ctor.prototype = parent.prototype;child.prototype = new ctor();child.__super__ = parent.prototype;return child;
},
hasProp = {}.hasOwnProperty;
sax = require('sax');
events = require('events');
bom = require('./bom');
processors = require('./processors');
setImmediate = require('timers').setImmediate;
defaults = require('./defaults').defaults;
isEmpty = function isEmpty(thing) {
return (typeof thing === 'undefined' ? 'undefined' : (0, _typeof3.default)(thing)) === "object" && thing != null && (0, _keys2.default)(thing).length === 0;
};
processItem = function processItem(processors, item, key) {
var i, len, process;
for (i = 0, len = processors.length; i < len; i++) {
process = processors[i];
item = process(item, key);
}
return item;
};
exports.Parser = function (superClass) {
extend(Parser, superClass);
function Parser(opts) {
this.parseStringPromise = bind(this.parseStringPromise, this);
this.parseString = bind(this.parseString, this);
this.reset = bind(this.reset, this);
this.assignOrPush = bind(this.assignOrPush, this);
this.processAsync = bind(this.processAsync, this);
var key, ref, value;
if (!(this instanceof exports.Parser)) {
return new exports.Parser(opts);
}
this.options = {};
ref = defaults["0.2"];
for (key in ref) {
if (!hasProp.call(ref, key)) continue;
value = ref[key];
this.options[key] = value;
}
for (key in opts) {
if (!hasProp.call(opts, key)) continue;
value = opts[key];
this.options[key] = value;
}
if (this.options.xmlns) {
this.options.xmlnskey = this.options.attrkey + "ns";
}
if (this.options.normalizeTags) {
if (!this.options.tagNameProcessors) {
this.options.tagNameProcessors = [];
}
this.options.tagNameProcessors.unshift(processors.normalize);
}
this.reset();
}
Parser.prototype.processAsync = function () {
var chunk, err;
try {
if (this.remaining.length <= this.options.chunkSize) {
chunk = this.remaining;
this.remaining = '';
this.saxParser = this.saxParser.write(chunk);
return this.saxParser.close();
} else {
chunk = this.remaining.substr(0, this.options.chunkSize);
this.remaining = this.remaining.substr(this.options.chunkSize, this.remaining.length);
this.saxParser = this.saxParser.write(chunk);
return setImmediate(this.processAsync);
}
} catch (error1) {
err = error1;
if (!this.saxParser.errThrown) {
this.saxParser.errThrown = true;
return this.emit(err);
}
}
};
Parser.prototype.assignOrPush = function (obj, key, newValue) {
if (!(key in obj)) {
if (!this.options.explicitArray) {
return obj[key] = newValue;
} else {
return obj[key] = [newValue];
}
} else {
if (!(obj[key] instanceof Array)) {
obj[key] = [obj[key]];
}
return obj[key].push(newValue);
}
};
Parser.prototype.reset = function () {
var attrkey, charkey, ontext, stack;
this.removeAllListeners();
this.saxParser = sax.parser(this.options.strict, {
trim: false,
normalize: false,
xmlns: this.options.xmlns
});
this.saxParser.errThrown = false;
this.saxParser.onerror = function (_this) {
return function (error) {
_this.saxParser.resume();
if (!_this.saxParser.errThrown) {
_this.saxParser.errThrown = true;
return _this.emit("error", error);
}
};
}(this);
this.saxParser.onend = function (_this) {
return function () {
if (!_this.saxParser.ended) {
_this.saxParser.ended = true;
return _this.emit("end", _this.resultObject);
}
};
}(this);
this.saxParser.ended = false;
this.EXPLICIT_CHARKEY = this.options.explicitCharkey;
this.resultObject = null;
stack = [];
attrkey = this.options.attrkey;
charkey = this.options.charkey;
this.saxParser.onopentag = function (_this) {
return function (node) {
var key, newValue, obj, processedKey, ref;
obj = {};
obj[charkey] = "";
if (!_this.options.ignoreAttrs) {
ref = node.attributes;
for (key in ref) {
if (!hasProp.call(ref, key)) continue;
if (!(attrkey in obj) && !_this.options.mergeAttrs) {
obj[attrkey] = {};
}
newValue = _this.options.attrValueProcessors ? processItem(_this.options.attrValueProcessors, node.attributes[key], key) : node.attributes[key];
processedKey = _this.options.attrNameProcessors ? processItem(_this.options.attrNameProcessors, key) : key;
if (_this.options.mergeAttrs) {
_this.assignOrPush(obj, processedKey, newValue);
} else {
obj[attrkey][processedKey] = newValue;
}
}
}
obj["#name"] = _this.options.tagNameProcessors ? processItem(_this.options.tagNameProcessors, node.name) : node.name;
if (_this.options.xmlns) {
obj[_this.options.xmlnskey] = {
uri: node.uri,
local: node.local
};
}
return stack.push(obj);
};
}(this);
this.saxParser.onclosetag = function (_this) {
return function () {
var cdata, emptyStr, key, node, nodeName, obj, objClone, old, s, xpath;
obj = stack.pop();
nodeName = obj["#name"];
if (!_this.options.explicitChildren || !_this.options.preserveChildrenOrder) {
delete obj["#name"];
}
if (obj.cdata === true) {
cdata = obj.cdata;
delete obj.cdata;
}
s = stack[stack.length - 1];
if (obj[charkey].match(/^\s*$/) && !cdata) {
emptyStr = obj[charkey];
delete obj[charkey];
} else {
if (_this.options.trim) {
obj[charkey] = obj[charkey].trim();
}
if (_this.options.normalize) {
obj[charkey] = obj[charkey].replace(/\s{2,}/g, " ").trim();
}
obj[charkey] = _this.options.valueProcessors ? processItem(_this.options.valueProcessors, obj[charkey], nodeName) : obj[charkey];
if ((0, _keys2.default)(obj).length === 1 && charkey in obj && !_this.EXPLICIT_CHARKEY) {
obj = obj[charkey];
}
}
if (isEmpty(obj)) {
obj = _this.options.emptyTag !== '' ? _this.options.emptyTag : emptyStr;
}
if (_this.options.validator != null) {
xpath = "/" + function () {
var i, len, results;
results = [];
for (i = 0, len = stack.length; i < len; i++) {
node = stack[i];
results.push(node["#name"]);
}
return results;
}().concat(nodeName).join("/");
(function () {
var err;
try {
return obj = _this.options.validator(xpath, s && s[nodeName], obj);
} catch (error1) {
err = error1;
return _this.emit("error", err);
}
})();
}
if (_this.options.explicitChildren && !_this.options.mergeAttrs && (typeof obj === 'undefined' ? 'undefined' : (0, _typeof3.default)(obj)) === 'object') {
if (!_this.options.preserveChildrenOrder) {
node = {};
if (_this.options.attrkey in obj) {
node[_this.options.attrkey] = obj[_this.options.attrkey];
delete obj[_this.options.attrkey];
}
if (!_this.options.charsAsChildren && _this.options.charkey in obj) {
node[_this.options.charkey] = obj[_this.options.charkey];
delete obj[_this.options.charkey];
}
if ((0, _getOwnPropertyNames2.default)(obj).length > 0) {
node[_this.options.childkey] = obj;
}
obj = node;
} else if (s) {
s[_this.options.childkey] = s[_this.options.childkey] || [];
objClone = {};
for (key in obj) {
if (!hasProp.call(obj, key)) continue;
objClone[key] = obj[key];
}
s[_this.options.childkey].push(objClone);
delete obj["#name"];
if ((0, _keys2.default)(obj).length === 1 && charkey in obj && !_this.EXPLICIT_CHARKEY) {
obj = obj[charkey];
}
}
}
if (stack.length > 0) {
return _this.assignOrPush(s, nodeName, obj);
} else {
if (_this.options.explicitRoot) {
old = obj;
obj = {};
obj[nodeName] = old;
}
_this.resultObject = obj;
_this.saxParser.ended = true;
return _this.emit("end", _this.resultObject);
}
};
}(this);
ontext = function (_this) {
return function (text) {
var charChild, s;
s = stack[stack.length - 1];
if (s) {
s[charkey] += text;
if (_this.options.explicitChildren && _this.options.preserveChildrenOrder && _this.options.charsAsChildren && (_this.options.includeWhiteChars || text.replace(/\\n/g, '').trim() !== '')) {
s[_this.options.childkey] = s[_this.options.childkey] || [];
charChild = {
'#name': '__text__'
};
charChild[charkey] = text;
if (_this.options.normalize) {
charChild[charkey] = charChild[charkey].replace(/\s{2,}/g, " ").trim();
}
s[_this.options.childkey].push(charChild);
}
return s;
}
};
}(this);
this.saxParser.ontext = ontext;
return this.saxParser.oncdata = function (_this) {
return function (text) {
var s;
s = ontext(text);
if (s) {
return s.cdata = true;
}
};
}(this);
};
Parser.prototype.parseString = function (str, cb) {
var err;
if (cb != null && typeof cb === "function") {
this.on("end", function (result) {
this.reset();
return cb(null, result);
});
this.on("error", function (err) {
this.reset();
return cb(err);
});
}
try {
str = str.toString();
if (str.trim() === '') {
this.emit("end", null);
return true;
}
str = bom.stripBOM(str);
if (this.options.async) {
this.remaining = str;
setImmediate(this.processAsync);
return this.saxParser;
}
return this.saxParser.write(str).close();
} catch (error1) {
err = error1;
if (!(this.saxParser.errThrown || this.saxParser.ended)) {
this.emit('error', err);
return this.saxParser.errThrown = true;
} else if (this.saxParser.ended) {
throw err;
}
}
};
Parser.prototype.parseStringPromise = function (str) {
return new _promise2.default(function (_this) {
return function (resolve, reject) {
return _this.parseString(str, function (err, value) {
if (err) {
return reject(err);
} else {
return resolve(value);
}
});
};
}(this));
};
return Parser;
}(events);
exports.parseString = function (str, a, b) {
var cb, options, parser;
if (b != null) {
if (typeof b === 'function') {
cb = b;
}
if ((typeof a === 'undefined' ? 'undefined' : (0, _typeof3.default)(a)) === 'object') {
options = a;
}
} else {
if (typeof a === 'function') {
cb = a;
}
options = {};
}
parser = new exports.Parser(options);
return parser.parseString(str, cb);
};
exports.parseStringPromise = function (str, a) {
var options, parser;
if ((typeof a === 'undefined' ? 'undefined' : (0, _typeof3.default)(a)) === 'object') {
options = a;
}
parser = new exports.Parser(options);
return parser.parseStringPromise(str);
};
}).call(undefined);
},{"./bom":244,"./defaults":246,"./processors":248,"babel-runtime/core-js/object/get-own-property-names":58,"babel-runtime/core-js/object/keys":60,"babel-runtime/core-js/promise":61,"babel-runtime/helpers/typeof":67,"events":192,"sax":229,"timers":236}],248:[function(require,module,exports){
'use strict';
// Generated by CoffeeScript 1.12.7
(function () {
"use strict";
var prefixMatch;
prefixMatch = new RegExp(/(?!xmlns)^.*:/);
exports.normalize = function (str) {
return str.toLowerCase();
};
exports.firstCharLowerCase = function (str) {
return str.charAt(0).toLowerCase() + str.slice(1);
};
exports.stripPrefix = function (str) {
return str.replace(prefixMatch, '');
};
exports.parseNumbers = function (str) {
if (!isNaN(str)) {
str = str % 1 === 0 ? parseInt(str, 10) : parseFloat(str);
}
return str;
};
exports.parseBooleans = function (str) {
if (/^(?:true|false)$/i.test(str)) {
str = str.toLowerCase() === 'true';
}
return str;
};
}).call(undefined);
},{}],249:[function(require,module,exports){
'use strict';
// Generated by CoffeeScript 1.12.7
(function () {
"use strict";
var builder,
defaults,
parser,
processors,
extend = function extend(child, parent) {
for (var key in parent) {
if (hasProp.call(parent, key)) child[key] = parent[key];
}function ctor() {
this.constructor = child;
}ctor.prototype = parent.prototype;child.prototype = new ctor();child.__super__ = parent.prototype;return child;
},
hasProp = {}.hasOwnProperty;
defaults = require('./defaults');
builder = require('./builder');
parser = require('./parser');
processors = require('./processors');
exports.defaults = defaults.defaults;
exports.processors = processors;
exports.ValidationError = function (superClass) {
extend(ValidationError, superClass);
function ValidationError(message) {
this.message = message;
}
return ValidationError;
}(Error);
exports.Builder = builder.Builder;
exports.Parser = parser.Parser;
exports.parseString = parser.parseString;
exports.parseStringPromise = parser.parseStringPromise;
}).call(undefined);
},{"./builder":245,"./defaults":246,"./parser":247,"./processors":248}],250:[function(require,module,exports){
"use strict";
// Generated by CoffeeScript 1.12.7
(function () {
module.exports = {
Disconnected: 1,
Preceding: 2,
Following: 4,
Contains: 8,
ContainedBy: 16,
ImplementationSpecific: 32
};
}).call(undefined);
},{}],251:[function(require,module,exports){
"use strict";
// Generated by CoffeeScript 1.12.7
(function () {
module.exports = {
Element: 1,
Attribute: 2,
Text: 3,
CData: 4,
EntityReference: 5,
EntityDeclaration: 6,
ProcessingInstruction: 7,
Comment: 8,
Document: 9,
DocType: 10,
DocumentFragment: 11,
NotationDeclaration: 12,
Declaration: 201,
Raw: 202,
AttributeDeclaration: 203,
ElementDeclaration: 204,
Dummy: 205
};
}).call(undefined);
},{}],252:[function(require,module,exports){
'use strict';
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _typeof2 = require('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
var _assign = require('babel-runtime/core-js/object/assign');
var _assign2 = _interopRequireDefault(_assign);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by CoffeeScript 1.12.7
(function () {
var assign,
getValue,
isArray,
isEmpty,
isFunction,
isObject,
isPlainObject,
slice = [].slice,
hasProp = {}.hasOwnProperty;
assign = function assign() {
var i, key, len, source, sources, target;
target = arguments[0], sources = 2 <= arguments.length ? slice.call(arguments, 1) : [];
if (isFunction(_assign2.default)) {
_assign2.default.apply(null, arguments);
} else {
for (i = 0, len = sources.length; i < len; i++) {
source = sources[i];
if (source != null) {
for (key in source) {
if (!hasProp.call(source, key)) continue;
target[key] = source[key];
}
}
}
}
return target;
};
isFunction = function isFunction(val) {
return !!val && Object.prototype.toString.call(val) === '[object Function]';
};
isObject = function isObject(val) {
var ref;
return !!val && ((ref = typeof val === 'undefined' ? 'undefined' : (0, _typeof3.default)(val)) === 'function' || ref === 'object');
};
isArray = function isArray(val) {
if (isFunction(Array.isArray)) {
return Array.isArray(val);
} else {
return Object.prototype.toString.call(val) === '[object Array]';
}
};
isEmpty = function isEmpty(val) {
var key;
if (isArray(val)) {
return !val.length;
} else {
for (key in val) {
if (!hasProp.call(val, key)) continue;
return false;
}
return true;
}
};
isPlainObject = function isPlainObject(val) {
var ctor, proto;
return isObject(val) && (proto = (0, _getPrototypeOf2.default)(val)) && (ctor = proto.constructor) && typeof ctor === 'function' && ctor instanceof ctor && Function.prototype.toString.call(ctor) === Function.prototype.toString.call(Object);
};
getValue = function getValue(obj) {
if (isFunction(obj.valueOf)) {
return obj.valueOf();
} else {
return obj;
}
};
module.exports.assign = assign;
module.exports.isFunction = isFunction;
module.exports.isObject = isObject;
module.exports.isArray = isArray;
module.exports.isEmpty = isEmpty;
module.exports.isPlainObject = isPlainObject;
module.exports.getValue = getValue;
}).call(undefined);
},{"babel-runtime/core-js/object/assign":54,"babel-runtime/core-js/object/get-prototype-of":59,"babel-runtime/helpers/typeof":67}],253:[function(require,module,exports){
"use strict";
// Generated by CoffeeScript 1.12.7
(function () {
module.exports = {
None: 0,
OpenTag: 1,
InsideTag: 2,
CloseTag: 3
};
}).call(undefined);
},{}],254:[function(require,module,exports){
'use strict';
var _create = require('babel-runtime/core-js/object/create');
var _create2 = _interopRequireDefault(_create);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by CoffeeScript 1.12.7
(function () {
var NodeType, XMLAttribute, XMLNode;
NodeType = require('./NodeType');
XMLNode = require('./XMLNode');
module.exports = XMLAttribute = function () {
function XMLAttribute(parent, name, value) {
this.parent = parent;
if (this.parent) {
this.options = this.parent.options;
this.stringify = this.parent.stringify;
}
if (name == null) {
throw new Error("Missing attribute name. " + this.debugInfo(name));
}
this.name = this.stringify.name(name);
this.value = this.stringify.attValue(value);
this.type = NodeType.Attribute;
this.isId = false;
this.schemaTypeInfo = null;
}
Object.defineProperty(XMLAttribute.prototype, 'nodeType', {
get: function get() {
return this.type;
}
});
Object.defineProperty(XMLAttribute.prototype, 'ownerElement', {
get: function get() {
return this.parent;
}
});
Object.defineProperty(XMLAttribute.prototype, 'textContent', {
get: function get() {
return this.value;
},
set: function set(value) {
return this.value = value || '';
}
});
Object.defineProperty(XMLAttribute.prototype, 'namespaceURI', {
get: function get() {
return '';
}
});
Object.defineProperty(XMLAttribute.prototype, 'prefix', {
get: function get() {
return '';
}
});
Object.defineProperty(XMLAttribute.prototype, 'localName', {
get: function get() {
return this.name;
}
});
Object.defineProperty(XMLAttribute.prototype, 'specified', {
get: function get() {
return true;
}
});
XMLAttribute.prototype.clone = function () {
return (0, _create2.default)(this);
};
XMLAttribute.prototype.toString = function (options) {
return this.options.writer.attribute(this, this.options.writer.filterOptions(options));
};
XMLAttribute.prototype.debugInfo = function (name) {
name = name || this.name;
if (name == null) {
return "parent: <" + this.parent.name + ">";
} else {
return "attribute: {" + name + "}, parent: <" + this.parent.name + ">";
}
};
XMLAttribute.prototype.isEqualNode = function (node) {
if (node.namespaceURI !== this.namespaceURI) {
return false;
}
if (node.prefix !== this.prefix) {
return false;
}
if (node.localName !== this.localName) {
return false;
}
if (node.value !== this.value) {
return false;
}
return true;
};
return XMLAttribute;
}();
}).call(undefined);
},{"./NodeType":251,"./XMLNode":273,"babel-runtime/core-js/object/create":55}],255:[function(require,module,exports){
'use strict';
var _create = require('babel-runtime/core-js/object/create');
var _create2 = _interopRequireDefault(_create);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by CoffeeScript 1.12.7
(function () {
var NodeType,
XMLCData,
XMLCharacterData,
extend = function extend(child, parent) {
for (var key in parent) {
if (hasProp.call(parent, key)) child[key] = parent[key];
}function ctor() {
this.constructor = child;
}ctor.prototype = parent.prototype;child.prototype = new ctor();child.__super__ = parent.prototype;return child;
},
hasProp = {}.hasOwnProperty;
NodeType = require('./NodeType');
XMLCharacterData = require('./XMLCharacterData');
module.exports = XMLCData = function (superClass) {
extend(XMLCData, superClass);
function XMLCData(parent, text) {
XMLCData.__super__.constructor.call(this, parent);
if (text == null) {
throw new Error("Missing CDATA text. " + this.debugInfo());
}
this.name = "#cdata-section";
this.type = NodeType.CData;
this.value = this.stringify.cdata(text);
}
XMLCData.prototype.clone = function () {
return (0, _create2.default)(this);
};
XMLCData.prototype.toString = function (options) {
return this.options.writer.cdata(this, this.options.writer.filterOptions(options));
};
return XMLCData;
}(XMLCharacterData);
}).call(undefined);
},{"./NodeType":251,"./XMLCharacterData":256,"babel-runtime/core-js/object/create":55}],256:[function(require,module,exports){
'use strict';
var _create = require('babel-runtime/core-js/object/create');
var _create2 = _interopRequireDefault(_create);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by CoffeeScript 1.12.7
(function () {
var XMLCharacterData,
XMLNode,
extend = function extend(child, parent) {
for (var key in parent) {
if (hasProp.call(parent, key)) child[key] = parent[key];
}function ctor() {
this.constructor = child;
}ctor.prototype = parent.prototype;child.prototype = new ctor();child.__super__ = parent.prototype;return child;
},
hasProp = {}.hasOwnProperty;
XMLNode = require('./XMLNode');
module.exports = XMLCharacterData = function (superClass) {
extend(XMLCharacterData, superClass);
function XMLCharacterData(parent) {
XMLCharacterData.__super__.constructor.call(this, parent);
this.value = '';
}
Object.defineProperty(XMLCharacterData.prototype, 'data', {
get: function get() {
return this.value;
},
set: function set(value) {
return this.value = value || '';
}
});
Object.defineProperty(XMLCharacterData.prototype, 'length', {
get: function get() {
return this.value.length;
}
});
Object.defineProperty(XMLCharacterData.prototype, 'textContent', {
get: function get() {
return this.value;
},
set: function set(value) {
return this.value = value || '';
}
});
XMLCharacterData.prototype.clone = function () {
return (0, _create2.default)(this);
};
XMLCharacterData.prototype.substringData = function (offset, count) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLCharacterData.prototype.appendData = function (arg) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLCharacterData.prototype.insertData = function (offset, arg) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLCharacterData.prototype.deleteData = function (offset, count) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLCharacterData.prototype.replaceData = function (offset, count, arg) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLCharacterData.prototype.isEqualNode = function (node) {
if (!XMLCharacterData.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) {
return false;
}
if (node.data !== this.data) {
return false;
}
return true;
};
return XMLCharacterData;
}(XMLNode);
}).call(undefined);
},{"./XMLNode":273,"babel-runtime/core-js/object/create":55}],257:[function(require,module,exports){
'use strict';
var _create = require('babel-runtime/core-js/object/create');
var _create2 = _interopRequireDefault(_create);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by CoffeeScript 1.12.7
(function () {
var NodeType,
XMLCharacterData,
XMLComment,
extend = function extend(child, parent) {
for (var key in parent) {
if (hasProp.call(parent, key)) child[key] = parent[key];
}function ctor() {
this.constructor = child;
}ctor.prototype = parent.prototype;child.prototype = new ctor();child.__super__ = parent.prototype;return child;
},
hasProp = {}.hasOwnProperty;
NodeType = require('./NodeType');
XMLCharacterData = require('./XMLCharacterData');
module.exports = XMLComment = function (superClass) {
extend(XMLComment, superClass);
function XMLComment(parent, text) {
XMLComment.__super__.constructor.call(this, parent);
if (text == null) {
throw new Error("Missing comment text. " + this.debugInfo());
}
this.name = "#comment";
this.type = NodeType.Comment;
this.value = this.stringify.comment(text);
}
XMLComment.prototype.clone = function () {
return (0, _create2.default)(this);
};
XMLComment.prototype.toString = function (options) {
return this.options.writer.comment(this, this.options.writer.filterOptions(options));
};
return XMLComment;
}(XMLCharacterData);
}).call(undefined);
},{"./NodeType":251,"./XMLCharacterData":256,"babel-runtime/core-js/object/create":55}],258:[function(require,module,exports){
'use strict';
var _keys = require('babel-runtime/core-js/object/keys');
var _keys2 = _interopRequireDefault(_keys);
var _create = require('babel-runtime/core-js/object/create');
var _create2 = _interopRequireDefault(_create);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by CoffeeScript 1.12.7
(function () {
var XMLDOMConfiguration, XMLDOMErrorHandler, XMLDOMStringList;
XMLDOMErrorHandler = require('./XMLDOMErrorHandler');
XMLDOMStringList = require('./XMLDOMStringList');
module.exports = XMLDOMConfiguration = function () {
function XMLDOMConfiguration() {
var clonedSelf;
this.defaultParams = {
"canonical-form": false,
"cdata-sections": false,
"comments": false,
"datatype-normalization": false,
"element-content-whitespace": true,
"entities": true,
"error-handler": new XMLDOMErrorHandler(),
"infoset": true,
"validate-if-schema": false,
"namespaces": true,
"namespace-declarations": true,
"normalize-characters": false,
"schema-location": '',
"schema-type": '',
"split-cdata-sections": true,
"validate": false,
"well-formed": true
};
this.params = clonedSelf = (0, _create2.default)(this.defaultParams);
}
Object.defineProperty(XMLDOMConfiguration.prototype, 'parameterNames', {
get: function get() {
return new XMLDOMStringList((0, _keys2.default)(this.defaultParams));
}
});
XMLDOMConfiguration.prototype.getParameter = function (name) {
if (this.params.hasOwnProperty(name)) {
return this.params[name];
} else {
return null;
}
};
XMLDOMConfiguration.prototype.canSetParameter = function (name, value) {
return true;
};
XMLDOMConfiguration.prototype.setParameter = function (name, value) {
if (value != null) {
return this.params[name] = value;
} else {
return delete this.params[name];
}
};
return XMLDOMConfiguration;
}();
}).call(undefined);
},{"./XMLDOMErrorHandler":259,"./XMLDOMStringList":261,"babel-runtime/core-js/object/create":55,"babel-runtime/core-js/object/keys":60}],259:[function(require,module,exports){
"use strict";
// Generated by CoffeeScript 1.12.7
(function () {
var XMLDOMErrorHandler;
module.exports = XMLDOMErrorHandler = function () {
function XMLDOMErrorHandler() {}
XMLDOMErrorHandler.prototype.handleError = function (error) {
throw new Error(error);
};
return XMLDOMErrorHandler;
}();
}).call(undefined);
},{}],260:[function(require,module,exports){
"use strict";
// Generated by CoffeeScript 1.12.7
(function () {
var XMLDOMImplementation;
module.exports = XMLDOMImplementation = function () {
function XMLDOMImplementation() {}
XMLDOMImplementation.prototype.hasFeature = function (feature, version) {
return true;
};
XMLDOMImplementation.prototype.createDocumentType = function (qualifiedName, publicId, systemId) {
throw new Error("This DOM method is not implemented.");
};
XMLDOMImplementation.prototype.createDocument = function (namespaceURI, qualifiedName, doctype) {
throw new Error("This DOM method is not implemented.");
};
XMLDOMImplementation.prototype.createHTMLDocument = function (title) {
throw new Error("This DOM method is not implemented.");
};
XMLDOMImplementation.prototype.getFeature = function (feature, version) {
throw new Error("This DOM method is not implemented.");
};
return XMLDOMImplementation;
}();
}).call(undefined);
},{}],261:[function(require,module,exports){
'use strict';
// Generated by CoffeeScript 1.12.7
(function () {
var XMLDOMStringList;
module.exports = XMLDOMStringList = function () {
function XMLDOMStringList(arr) {
this.arr = arr || [];
}
Object.defineProperty(XMLDOMStringList.prototype, 'length', {
get: function get() {
return this.arr.length;
}
});
XMLDOMStringList.prototype.item = function (index) {
return this.arr[index] || null;
};
XMLDOMStringList.prototype.contains = function (str) {
return this.arr.indexOf(str) !== -1;
};
return XMLDOMStringList;
}();
}).call(undefined);
},{}],262:[function(require,module,exports){
'use strict';
// Generated by CoffeeScript 1.12.7
(function () {
var NodeType,
XMLDTDAttList,
XMLNode,
extend = function extend(child, parent) {
for (var key in parent) {
if (hasProp.call(parent, key)) child[key] = parent[key];
}function ctor() {
this.constructor = child;
}ctor.prototype = parent.prototype;child.prototype = new ctor();child.__super__ = parent.prototype;return child;
},
hasProp = {}.hasOwnProperty;
XMLNode = require('./XMLNode');
NodeType = require('./NodeType');
module.exports = XMLDTDAttList = function (superClass) {
extend(XMLDTDAttList, superClass);
function XMLDTDAttList(parent, elementName, attributeName, attributeType, defaultValueType, defaultValue) {
XMLDTDAttList.__super__.constructor.call(this, parent);
if (elementName == null) {
throw new Error("Missing DTD element name. " + this.debugInfo());
}
if (attributeName == null) {
throw new Error("Missing DTD attribute name. " + this.debugInfo(elementName));
}
if (!attributeType) {
throw new Error("Missing DTD attribute type. " + this.debugInfo(elementName));
}
if (!defaultValueType) {
throw new Error("Missing DTD attribute default. " + this.debugInfo(elementName));
}
if (defaultValueType.indexOf('#') !== 0) {
defaultValueType = '#' + defaultValueType;
}
if (!defaultValueType.match(/^(#REQUIRED|#IMPLIED|#FIXED|#DEFAULT)$/)) {
throw new Error("Invalid default value type; expected: #REQUIRED, #IMPLIED, #FIXED or #DEFAULT. " + this.debugInfo(elementName));
}
if (defaultValue && !defaultValueType.match(/^(#FIXED|#DEFAULT)$/)) {
throw new Error("Default value only applies to #FIXED or #DEFAULT. " + this.debugInfo(elementName));
}
this.elementName = this.stringify.name(elementName);
this.type = NodeType.AttributeDeclaration;
this.attributeName = this.stringify.name(attributeName);
this.attributeType = this.stringify.dtdAttType(attributeType);
if (defaultValue) {
this.defaultValue = this.stringify.dtdAttDefault(defaultValue);
}
this.defaultValueType = defaultValueType;
}
XMLDTDAttList.prototype.toString = function (options) {
return this.options.writer.dtdAttList(this, this.options.writer.filterOptions(options));
};
return XMLDTDAttList;
}(XMLNode);
}).call(undefined);
},{"./NodeType":251,"./XMLNode":273}],263:[function(require,module,exports){
'use strict';
// Generated by CoffeeScript 1.12.7
(function () {
var NodeType,
XMLDTDElement,
XMLNode,
extend = function extend(child, parent) {
for (var key in parent) {
if (hasProp.call(parent, key)) child[key] = parent[key];
}function ctor() {
this.constructor = child;
}ctor.prototype = parent.prototype;child.prototype = new ctor();child.__super__ = parent.prototype;return child;
},
hasProp = {}.hasOwnProperty;
XMLNode = require('./XMLNode');
NodeType = require('./NodeType');
module.exports = XMLDTDElement = function (superClass) {
extend(XMLDTDElement, superClass);
function XMLDTDElement(parent, name, value) {
XMLDTDElement.__super__.constructor.call(this, parent);
if (name == null) {
throw new Error("Missing DTD element name. " + this.debugInfo());
}
if (!value) {
value = '(#PCDATA)';
}
if (Array.isArray(value)) {
value = '(' + value.join(',') + ')';
}
this.name = this.stringify.name(name);
this.type = NodeType.ElementDeclaration;
this.value = this.stringify.dtdElementValue(value);
}
XMLDTDElement.prototype.toString = function (options) {
return this.options.writer.dtdElement(this, this.options.writer.filterOptions(options));
};
return XMLDTDElement;
}(XMLNode);
}).call(undefined);
},{"./NodeType":251,"./XMLNode":273}],264:[function(require,module,exports){
'use strict';
// Generated by CoffeeScript 1.12.7
(function () {
var NodeType,
XMLDTDEntity,
XMLNode,
isObject,
extend = function extend(child, parent) {
for (var key in parent) {
if (hasProp.call(parent, key)) child[key] = parent[key];
}function ctor() {
this.constructor = child;
}ctor.prototype = parent.prototype;child.prototype = new ctor();child.__super__ = parent.prototype;return child;
},
hasProp = {}.hasOwnProperty;
isObject = require('./Utility').isObject;
XMLNode = require('./XMLNode');
NodeType = require('./NodeType');
module.exports = XMLDTDEntity = function (superClass) {
extend(XMLDTDEntity, superClass);
function XMLDTDEntity(parent, pe, name, value) {
XMLDTDEntity.__super__.constructor.call(this, parent);
if (name == null) {
throw new Error("Missing DTD entity name. " + this.debugInfo(name));
}
if (value == null) {
throw new Error("Missing DTD entity value. " + this.debugInfo(name));
}
this.pe = !!pe;
this.name = this.stringify.name(name);
this.type = NodeType.EntityDeclaration;
if (!isObject(value)) {
this.value = this.stringify.dtdEntityValue(value);
this.internal = true;
} else {
if (!value.pubID && !value.sysID) {
throw new Error("Public and/or system identifiers are required for an external entity. " + this.debugInfo(name));
}
if (value.pubID && !value.sysID) {
throw new Error("System identifier is required for a public external entity. " + this.debugInfo(name));
}
this.internal = false;
if (value.pubID != null) {
this.pubID = this.stringify.dtdPubID(value.pubID);
}
if (value.sysID != null) {
this.sysID = this.stringify.dtdSysID(value.sysID);
}
if (value.nData != null) {
this.nData = this.stringify.dtdNData(value.nData);
}
if (this.pe && this.nData) {
throw new Error("Notation declaration is not allowed in a parameter entity. " + this.debugInfo(name));
}
}
}
Object.defineProperty(XMLDTDEntity.prototype, 'publicId', {
get: function get() {
return this.pubID;
}
});
Object.defineProperty(XMLDTDEntity.prototype, 'systemId', {
get: function get() {
return this.sysID;
}
});
Object.defineProperty(XMLDTDEntity.prototype, 'notationName', {
get: function get() {
return this.nData || null;
}
});
Object.defineProperty(XMLDTDEntity.prototype, 'inputEncoding', {
get: function get() {
return null;
}
});
Object.defineProperty(XMLDTDEntity.prototype, 'xmlEncoding', {
get: function get() {
return null;
}
});
Object.defineProperty(XMLDTDEntity.prototype, 'xmlVersion', {
get: function get() {
return null;
}
});
XMLDTDEntity.prototype.toString = function (options) {
return this.options.writer.dtdEntity(this, this.options.writer.filterOptions(options));
};
return XMLDTDEntity;
}(XMLNode);
}).call(undefined);
},{"./NodeType":251,"./Utility":252,"./XMLNode":273}],265:[function(require,module,exports){
'use strict';
// Generated by CoffeeScript 1.12.7
(function () {
var NodeType,
XMLDTDNotation,
XMLNode,
extend = function extend(child, parent) {
for (var key in parent) {
if (hasProp.call(parent, key)) child[key] = parent[key];
}function ctor() {
this.constructor = child;
}ctor.prototype = parent.prototype;child.prototype = new ctor();child.__super__ = parent.prototype;return child;
},
hasProp = {}.hasOwnProperty;
XMLNode = require('./XMLNode');
NodeType = require('./NodeType');
module.exports = XMLDTDNotation = function (superClass) {
extend(XMLDTDNotation, superClass);
function XMLDTDNotation(parent, name, value) {
XMLDTDNotation.__super__.constructor.call(this, parent);
if (name == null) {
throw new Error("Missing DTD notation name. " + this.debugInfo(name));
}
if (!value.pubID && !value.sysID) {
throw new Error("Public or system identifiers are required for an external entity. " + this.debugInfo(name));
}
this.name = this.stringify.name(name);
this.type = NodeType.NotationDeclaration;
if (value.pubID != null) {
this.pubID = this.stringify.dtdPubID(value.pubID);
}
if (value.sysID != null) {
this.sysID = this.stringify.dtdSysID(value.sysID);
}
}
Object.defineProperty(XMLDTDNotation.prototype, 'publicId', {
get: function get() {
return this.pubID;
}
});
Object.defineProperty(XMLDTDNotation.prototype, 'systemId', {
get: function get() {
return this.sysID;
}
});
XMLDTDNotation.prototype.toString = function (options) {
return this.options.writer.dtdNotation(this, this.options.writer.filterOptions(options));
};
return XMLDTDNotation;
}(XMLNode);
}).call(undefined);
},{"./NodeType":251,"./XMLNode":273}],266:[function(require,module,exports){
'use strict';
// Generated by CoffeeScript 1.12.7
(function () {
var NodeType,
XMLDeclaration,
XMLNode,
isObject,
extend = function extend(child, parent) {
for (var key in parent) {
if (hasProp.call(parent, key)) child[key] = parent[key];
}function ctor() {
this.constructor = child;
}ctor.prototype = parent.prototype;child.prototype = new ctor();child.__super__ = parent.prototype;return child;
},
hasProp = {}.hasOwnProperty;
isObject = require('./Utility').isObject;
XMLNode = require('./XMLNode');
NodeType = require('./NodeType');
module.exports = XMLDeclaration = function (superClass) {
extend(XMLDeclaration, superClass);
function XMLDeclaration(parent, version, encoding, standalone) {
var ref;
XMLDeclaration.__super__.constructor.call(this, parent);
if (isObject(version)) {
ref = version, version = ref.version, encoding = ref.encoding, standalone = ref.standalone;
}
if (!version) {
version = '1.0';
}
this.type = NodeType.Declaration;
this.version = this.stringify.xmlVersion(version);
if (encoding != null) {
this.encoding = this.stringify.xmlEncoding(encoding);
}
if (standalone != null) {
this.standalone = this.stringify.xmlStandalone(standalone);
}
}
XMLDeclaration.prototype.toString = function (options) {
return this.options.writer.declaration(this, this.options.writer.filterOptions(options));
};
return XMLDeclaration;
}(XMLNode);
}).call(undefined);
},{"./NodeType":251,"./Utility":252,"./XMLNode":273}],267:[function(require,module,exports){
'use strict';
// Generated by CoffeeScript 1.12.7
(function () {
var NodeType,
XMLDTDAttList,
XMLDTDElement,
XMLDTDEntity,
XMLDTDNotation,
XMLDocType,
XMLNamedNodeMap,
XMLNode,
isObject,
extend = function extend(child, parent) {
for (var key in parent) {
if (hasProp.call(parent, key)) child[key] = parent[key];
}function ctor() {
this.constructor = child;
}ctor.prototype = parent.prototype;child.prototype = new ctor();child.__super__ = parent.prototype;return child;
},
hasProp = {}.hasOwnProperty;
isObject = require('./Utility').isObject;
XMLNode = require('./XMLNode');
NodeType = require('./NodeType');
XMLDTDAttList = require('./XMLDTDAttList');
XMLDTDEntity = require('./XMLDTDEntity');
XMLDTDElement = require('./XMLDTDElement');
XMLDTDNotation = require('./XMLDTDNotation');
XMLNamedNodeMap = require('./XMLNamedNodeMap');
module.exports = XMLDocType = function (superClass) {
extend(XMLDocType, superClass);
function XMLDocType(parent, pubID, sysID) {
var child, i, len, ref, ref1, ref2;
XMLDocType.__super__.constructor.call(this, parent);
this.type = NodeType.DocType;
if (parent.children) {
ref = parent.children;
for (i = 0, len = ref.length; i < len; i++) {
child = ref[i];
if (child.type === NodeType.Element) {
this.name = child.name;
break;
}
}
}
this.documentObject = parent;
if (isObject(pubID)) {
ref1 = pubID, pubID = ref1.pubID, sysID = ref1.sysID;
}
if (sysID == null) {
ref2 = [pubID, sysID], sysID = ref2[0], pubID = ref2[1];
}
if (pubID != null) {
this.pubID = this.stringify.dtdPubID(pubID);
}
if (sysID != null) {
this.sysID = this.stringify.dtdSysID(sysID);
}
}
Object.defineProperty(XMLDocType.prototype, 'entities', {
get: function get() {
var child, i, len, nodes, ref;
nodes = {};
ref = this.children;
for (i = 0, len = ref.length; i < len; i++) {
child = ref[i];
if (child.type === NodeType.EntityDeclaration && !child.pe) {
nodes[child.name] = child;
}
}
return new XMLNamedNodeMap(nodes);
}
});
Object.defineProperty(XMLDocType.prototype, 'notations', {
get: function get() {
var child, i, len, nodes, ref;
nodes = {};
ref = this.children;
for (i = 0, len = ref.length; i < len; i++) {
child = ref[i];
if (child.type === NodeType.NotationDeclaration) {
nodes[child.name] = child;
}
}
return new XMLNamedNodeMap(nodes);
}
});
Object.defineProperty(XMLDocType.prototype, 'publicId', {
get: function get() {
return this.pubID;
}
});
Object.defineProperty(XMLDocType.prototype, 'systemId', {
get: function get() {
return this.sysID;
}
});
Object.defineProperty(XMLDocType.prototype, 'internalSubset', {
get: function get() {
throw new Error("This DOM method is not implemented." + this.debugInfo());
}
});
XMLDocType.prototype.element = function (name, value) {
var child;
child = new XMLDTDElement(this, name, value);
this.children.push(child);
return this;
};
XMLDocType.prototype.attList = function (elementName, attributeName, attributeType, defaultValueType, defaultValue) {
var child;
child = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue);
this.children.push(child);
return this;
};
XMLDocType.prototype.entity = function (name, value) {
var child;
child = new XMLDTDEntity(this, false, name, value);
this.children.push(child);
return this;
};
XMLDocType.prototype.pEntity = function (name, value) {
var child;
child = new XMLDTDEntity(this, true, name, value);
this.children.push(child);
return this;
};
XMLDocType.prototype.notation = function (name, value) {
var child;
child = new XMLDTDNotation(this, name, value);
this.children.push(child);
return this;
};
XMLDocType.prototype.toString = function (options) {
return this.options.writer.docType(this, this.options.writer.filterOptions(options));
};
XMLDocType.prototype.ele = function (name, value) {
return this.element(name, value);
};
XMLDocType.prototype.att = function (elementName, attributeName, attributeType, defaultValueType, defaultValue) {
return this.attList(elementName, attributeName, attributeType, defaultValueType, defaultValue);
};
XMLDocType.prototype.ent = function (name, value) {
return this.entity(name, value);
};
XMLDocType.prototype.pent = function (name, value) {
return this.pEntity(name, value);
};
XMLDocType.prototype.not = function (name, value) {
return this.notation(name, value);
};
XMLDocType.prototype.up = function () {
return this.root() || this.documentObject;
};
XMLDocType.prototype.isEqualNode = function (node) {
if (!XMLDocType.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) {
return false;
}
if (node.name !== this.name) {
return false;
}
if (node.publicId !== this.publicId) {
return false;
}
if (node.systemId !== this.systemId) {
return false;
}
return true;
};
return XMLDocType;
}(XMLNode);
}).call(undefined);
},{"./NodeType":251,"./Utility":252,"./XMLDTDAttList":262,"./XMLDTDElement":263,"./XMLDTDEntity":264,"./XMLDTDNotation":265,"./XMLNamedNodeMap":272,"./XMLNode":273}],268:[function(require,module,exports){
'use strict';
// Generated by CoffeeScript 1.12.7
(function () {
var NodeType,
XMLDOMConfiguration,
XMLDOMImplementation,
XMLDocument,
XMLNode,
XMLStringWriter,
XMLStringifier,
isPlainObject,
extend = function extend(child, parent) {
for (var key in parent) {
if (hasProp.call(parent, key)) child[key] = parent[key];
}function ctor() {
this.constructor = child;
}ctor.prototype = parent.prototype;child.prototype = new ctor();child.__super__ = parent.prototype;return child;
},
hasProp = {}.hasOwnProperty;
isPlainObject = require('./Utility').isPlainObject;
XMLDOMImplementation = require('./XMLDOMImplementation');
XMLDOMConfiguration = require('./XMLDOMConfiguration');
XMLNode = require('./XMLNode');
NodeType = require('./NodeType');
XMLStringifier = require('./XMLStringifier');
XMLStringWriter = require('./XMLStringWriter');
module.exports = XMLDocument = function (superClass) {
extend(XMLDocument, superClass);
function XMLDocument(options) {
XMLDocument.__super__.constructor.call(this, null);
this.name = "#document";
this.type = NodeType.Document;
this.documentURI = null;
this.domConfig = new XMLDOMConfiguration();
options || (options = {});
if (!options.writer) {
options.writer = new XMLStringWriter();
}
this.options = options;
this.stringify = new XMLStringifier(options);
}
Object.defineProperty(XMLDocument.prototype, 'implementation', {
value: new XMLDOMImplementation()
});
Object.defineProperty(XMLDocument.prototype, 'doctype', {
get: function get() {
var child, i, len, ref;
ref = this.children;
for (i = 0, len = ref.length; i < len; i++) {
child = ref[i];
if (child.type === NodeType.DocType) {
return child;
}
}
return null;
}
});
Object.defineProperty(XMLDocument.prototype, 'documentElement', {
get: function get() {
return this.rootObject || null;
}
});
Object.defineProperty(XMLDocument.prototype, 'inputEncoding', {
get: function get() {
return null;
}
});
Object.defineProperty(XMLDocument.prototype, 'strictErrorChecking', {
get: function get() {
return false;
}
});
Object.defineProperty(XMLDocument.prototype, 'xmlEncoding', {
get: function get() {
if (this.children.length !== 0 && this.children[0].type === NodeType.Declaration) {
return this.children[0].encoding;
} else {
return null;
}
}
});
Object.defineProperty(XMLDocument.prototype, 'xmlStandalone', {
get: function get() {
if (this.children.length !== 0 && this.children[0].type === NodeType.Declaration) {
return this.children[0].standalone === 'yes';
} else {
return false;
}
}
});
Object.defineProperty(XMLDocument.prototype, 'xmlVersion', {
get: function get() {
if (this.children.length !== 0 && this.children[0].type === NodeType.Declaration) {
return this.children[0].version;
} else {
return "1.0";
}
}
});
Object.defineProperty(XMLDocument.prototype, 'URL', {
get: function get() {
return this.documentURI;
}
});
Object.defineProperty(XMLDocument.prototype, 'origin', {
get: function get() {
return null;
}
});
Object.defineProperty(XMLDocument.prototype, 'compatMode', {
get: function get() {
return null;
}
});
Object.defineProperty(XMLDocument.prototype, 'characterSet', {
get: function get() {
return null;
}
});
Object.defineProperty(XMLDocument.prototype, 'contentType', {
get: function get() {
return null;
}
});
XMLDocument.prototype.end = function (writer) {
var writerOptions;
writerOptions = {};
if (!writer) {
writer = this.options.writer;
} else if (isPlainObject(writer)) {
writerOptions = writer;
writer = this.options.writer;
}
return writer.document(this, writer.filterOptions(writerOptions));
};
XMLDocument.prototype.toString = function (options) {
return this.options.writer.document(this, this.options.writer.filterOptions(options));
};
XMLDocument.prototype.createElement = function (tagName) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLDocument.prototype.createDocumentFragment = function () {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLDocument.prototype.createTextNode = function (data) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLDocument.prototype.createComment = function (data) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLDocument.prototype.createCDATASection = function (data) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLDocument.prototype.createProcessingInstruction = function (target, data) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLDocument.prototype.createAttribute = function (name) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLDocument.prototype.createEntityReference = function (name) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLDocument.prototype.getElementsByTagName = function (tagname) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLDocument.prototype.importNode = function (importedNode, deep) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLDocument.prototype.createElementNS = function (namespaceURI, qualifiedName) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLDocument.prototype.createAttributeNS = function (namespaceURI, qualifiedName) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLDocument.prototype.getElementsByTagNameNS = function (namespaceURI, localName) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLDocument.prototype.getElementById = function (elementId) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLDocument.prototype.adoptNode = function (source) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLDocument.prototype.normalizeDocument = function () {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLDocument.prototype.renameNode = function (node, namespaceURI, qualifiedName) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLDocument.prototype.getElementsByClassName = function (classNames) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLDocument.prototype.createEvent = function (eventInterface) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLDocument.prototype.createRange = function () {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLDocument.prototype.createNodeIterator = function (root, whatToShow, filter) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLDocument.prototype.createTreeWalker = function (root, whatToShow, filter) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
return XMLDocument;
}(XMLNode);
}).call(undefined);
},{"./NodeType":251,"./Utility":252,"./XMLDOMConfiguration":258,"./XMLDOMImplementation":260,"./XMLNode":273,"./XMLStringWriter":278,"./XMLStringifier":279}],269:[function(require,module,exports){
'use strict';
// Generated by CoffeeScript 1.12.7
(function () {
var NodeType,
WriterState,
XMLAttribute,
XMLCData,
XMLComment,
XMLDTDAttList,
XMLDTDElement,
XMLDTDEntity,
XMLDTDNotation,
XMLDeclaration,
XMLDocType,
XMLDocument,
XMLDocumentCB,
XMLElement,
XMLProcessingInstruction,
XMLRaw,
XMLStringWriter,
XMLStringifier,
XMLText,
getValue,
isFunction,
isObject,
isPlainObject,
ref,
hasProp = {}.hasOwnProperty;
ref = require('./Utility'), isObject = ref.isObject, isFunction = ref.isFunction, isPlainObject = ref.isPlainObject, getValue = ref.getValue;
NodeType = require('./NodeType');
XMLDocument = require('./XMLDocument');
XMLElement = require('./XMLElement');
XMLCData = require('./XMLCData');
XMLComment = require('./XMLComment');
XMLRaw = require('./XMLRaw');
XMLText = require('./XMLText');
XMLProcessingInstruction = require('./XMLProcessingInstruction');
XMLDeclaration = require('./XMLDeclaration');
XMLDocType = require('./XMLDocType');
XMLDTDAttList = require('./XMLDTDAttList');
XMLDTDEntity = require('./XMLDTDEntity');
XMLDTDElement = require('./XMLDTDElement');
XMLDTDNotation = require('./XMLDTDNotation');
XMLAttribute = require('./XMLAttribute');
XMLStringifier = require('./XMLStringifier');
XMLStringWriter = require('./XMLStringWriter');
WriterState = require('./WriterState');
module.exports = XMLDocumentCB = function () {
function XMLDocumentCB(options, onData, onEnd) {
var writerOptions;
this.name = "?xml";
this.type = NodeType.Document;
options || (options = {});
writerOptions = {};
if (!options.writer) {
options.writer = new XMLStringWriter();
} else if (isPlainObject(options.writer)) {
writerOptions = options.writer;
options.writer = new XMLStringWriter();
}
this.options = options;
this.writer = options.writer;
this.writerOptions = this.writer.filterOptions(writerOptions);
this.stringify = new XMLStringifier(options);
this.onDataCallback = onData || function () {};
this.onEndCallback = onEnd || function () {};
this.currentNode = null;
this.currentLevel = -1;
this.openTags = {};
this.documentStarted = false;
this.documentCompleted = false;
this.root = null;
}
XMLDocumentCB.prototype.createChildNode = function (node) {
var att, attName, attributes, child, i, len, ref1, ref2;
switch (node.type) {
case NodeType.CData:
this.cdata(node.value);
break;
case NodeType.Comment:
this.comment(node.value);
break;
case NodeType.Element:
attributes = {};
ref1 = node.attribs;
for (attName in ref1) {
if (!hasProp.call(ref1, attName)) continue;
att = ref1[attName];
attributes[attName] = att.value;
}
this.node(node.name, attributes);
break;
case NodeType.Dummy:
this.dummy();
break;
case NodeType.Raw:
this.raw(node.value);
break;
case NodeType.Text:
this.text(node.value);
break;
case NodeType.ProcessingInstruction:
this.instruction(node.target, node.value);
break;
default:
throw new Error("This XML node type is not supported in a JS object: " + node.constructor.name);
}
ref2 = node.children;
for (i = 0, len = ref2.length; i < len; i++) {
child = ref2[i];
this.createChildNode(child);
if (child.type === NodeType.Element) {
this.up();
}
}
return this;
};
XMLDocumentCB.prototype.dummy = function () {
return this;
};
XMLDocumentCB.prototype.node = function (name, attributes, text) {
var ref1;
if (name == null) {
throw new Error("Missing node name.");
}
if (this.root && this.currentLevel === -1) {
throw new Error("Document can only have one root node. " + this.debugInfo(name));
}
this.openCurrent();
name = getValue(name);
if (attributes == null) {
attributes = {};
}
attributes = getValue(attributes);
if (!isObject(attributes)) {
ref1 = [attributes, text], text = ref1[0], attributes = ref1[1];
}
this.currentNode = new XMLElement(this, name, attributes);
this.currentNode.children = false;
this.currentLevel++;
this.openTags[this.currentLevel] = this.currentNode;
if (text != null) {
this.text(text);
}
return this;
};
XMLDocumentCB.prototype.element = function (name, attributes, text) {
var child, i, len, oldValidationFlag, ref1, root;
if (this.currentNode && this.currentNode.type === NodeType.DocType) {
this.dtdElement.apply(this, arguments);
} else {
if (Array.isArray(name) || isObject(name) || isFunction(name)) {
oldValidationFlag = this.options.noValidation;
this.options.noValidation = true;
root = new XMLDocument(this.options).element('TEMP_ROOT');
root.element(name);
this.options.noValidation = oldValidationFlag;
ref1 = root.children;
for (i = 0, len = ref1.length; i < len; i++) {
child = ref1[i];
this.createChildNode(child);
if (child.type === NodeType.Element) {
this.up();
}
}
} else {
this.node(name, attributes, text);
}
}
return this;
};
XMLDocumentCB.prototype.attribute = function (name, value) {
var attName, attValue;
if (!this.currentNode || this.currentNode.children) {
throw new Error("att() can only be used immediately after an ele() call in callback mode. " + this.debugInfo(name));
}
if (name != null) {
name = getValue(name);
}
if (isObject(name)) {
for (attName in name) {
if (!hasProp.call(name, attName)) continue;
attValue = name[attName];
this.attribute(attName, attValue);
}
} else {
if (isFunction(value)) {
value = value.apply();
}
if (this.options.keepNullAttributes && value == null) {
this.currentNode.attribs[name] = new XMLAttribute(this, name, "");
} else if (value != null) {
this.currentNode.attribs[name] = new XMLAttribute(this, name, value);
}
}
return this;
};
XMLDocumentCB.prototype.text = function (value) {
var node;
this.openCurrent();
node = new XMLText(this, value);
this.onData(this.writer.text(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
return this;
};
XMLDocumentCB.prototype.cdata = function (value) {
var node;
this.openCurrent();
node = new XMLCData(this, value);
this.onData(this.writer.cdata(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
return this;
};
XMLDocumentCB.prototype.comment = function (value) {
var node;
this.openCurrent();
node = new XMLComment(this, value);
this.onData(this.writer.comment(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
return this;
};
XMLDocumentCB.prototype.raw = function (value) {
var node;
this.openCurrent();
node = new XMLRaw(this, value);
this.onData(this.writer.raw(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
return this;
};
XMLDocumentCB.prototype.instruction = function (target, value) {
var i, insTarget, insValue, len, node;
this.openCurrent();
if (target != null) {
target = getValue(target);
}
if (value != null) {
value = getValue(value);
}
if (Array.isArray(target)) {
for (i = 0, len = target.length; i < len; i++) {
insTarget = target[i];
this.instruction(insTarget);
}
} else if (isObject(target)) {
for (insTarget in target) {
if (!hasProp.call(target, insTarget)) continue;
insValue = target[insTarget];
this.instruction(insTarget, insValue);
}
} else {
if (isFunction(value)) {
value = value.apply();
}
node = new XMLProcessingInstruction(this, target, value);
this.onData(this.writer.processingInstruction(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
}
return this;
};
XMLDocumentCB.prototype.declaration = function (version, encoding, standalone) {
var node;
this.openCurrent();
if (this.documentStarted) {
throw new Error("declaration() must be the first node.");
}
node = new XMLDeclaration(this, version, encoding, standalone);
this.onData(this.writer.declaration(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
return this;
};
XMLDocumentCB.prototype.doctype = function (root, pubID, sysID) {
this.openCurrent();
if (root == null) {
throw new Error("Missing root node name.");
}
if (this.root) {
throw new Error("dtd() must come before the root node.");
}
this.currentNode = new XMLDocType(this, pubID, sysID);
this.currentNode.rootNodeName = root;
this.currentNode.children = false;
this.currentLevel++;
this.openTags[this.currentLevel] = this.currentNode;
return this;
};
XMLDocumentCB.prototype.dtdElement = function (name, value) {
var node;
this.openCurrent();
node = new XMLDTDElement(this, name, value);
this.onData(this.writer.dtdElement(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
return this;
};
XMLDocumentCB.prototype.attList = function (elementName, attributeName, attributeType, defaultValueType, defaultValue) {
var node;
this.openCurrent();
node = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue);
this.onData(this.writer.dtdAttList(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
return this;
};
XMLDocumentCB.prototype.entity = function (name, value) {
var node;
this.openCurrent();
node = new XMLDTDEntity(this, false, name, value);
this.onData(this.writer.dtdEntity(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
return this;
};
XMLDocumentCB.prototype.pEntity = function (name, value) {
var node;
this.openCurrent();
node = new XMLDTDEntity(this, true, name, value);
this.onData(this.writer.dtdEntity(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
return this;
};
XMLDocumentCB.prototype.notation = function (name, value) {
var node;
this.openCurrent();
node = new XMLDTDNotation(this, name, value);
this.onData(this.writer.dtdNotation(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);
return this;
};
XMLDocumentCB.prototype.up = function () {
if (this.currentLevel < 0) {
throw new Error("The document node has no parent.");
}
if (this.currentNode) {
if (this.currentNode.children) {
this.closeNode(this.currentNode);
} else {
this.openNode(this.currentNode);
}
this.currentNode = null;
} else {
this.closeNode(this.openTags[this.currentLevel]);
}
delete this.openTags[this.currentLevel];
this.currentLevel--;
return this;
};
XMLDocumentCB.prototype.end = function () {
while (this.currentLevel >= 0) {
this.up();
}
return this.onEnd();
};
XMLDocumentCB.prototype.openCurrent = function () {
if (this.currentNode) {
this.currentNode.children = true;
return this.openNode(this.currentNode);
}
};
XMLDocumentCB.prototype.openNode = function (node) {
var att, chunk, name, ref1;
if (!node.isOpen) {
if (!this.root && this.currentLevel === 0 && node.type === NodeType.Element) {
this.root = node;
}
chunk = '';
if (node.type === NodeType.Element) {
this.writerOptions.state = WriterState.OpenTag;
chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + '<' + node.name;
ref1 = node.attribs;
for (name in ref1) {
if (!hasProp.call(ref1, name)) continue;
att = ref1[name];
chunk += this.writer.attribute(att, this.writerOptions, this.currentLevel);
}
chunk += (node.children ? '>' : '/>') + this.writer.endline(node, this.writerOptions, this.currentLevel);
this.writerOptions.state = WriterState.InsideTag;
} else {
this.writerOptions.state = WriterState.OpenTag;
chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + '<!DOCTYPE ' + node.rootNodeName;
if (node.pubID && node.sysID) {
chunk += ' PUBLIC "' + node.pubID + '" "' + node.sysID + '"';
} else if (node.sysID) {
chunk += ' SYSTEM "' + node.sysID + '"';
}
if (node.children) {
chunk += ' [';
this.writerOptions.state = WriterState.InsideTag;
} else {
this.writerOptions.state = WriterState.CloseTag;
chunk += '>';
}
chunk += this.writer.endline(node, this.writerOptions, this.currentLevel);
}
this.onData(chunk, this.currentLevel);
return node.isOpen = true;
}
};
XMLDocumentCB.prototype.closeNode = function (node) {
var chunk;
if (!node.isClosed) {
chunk = '';
this.writerOptions.state = WriterState.CloseTag;
if (node.type === NodeType.Element) {
chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + '</' + node.name + '>' + this.writer.endline(node, this.writerOptions, this.currentLevel);
} else {
chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + ']>' + this.writer.endline(node, this.writerOptions, this.currentLevel);
}
this.writerOptions.state = WriterState.None;
this.onData(chunk, this.currentLevel);
return node.isClosed = true;
}
};
XMLDocumentCB.prototype.onData = function (chunk, level) {
this.documentStarted = true;
return this.onDataCallback(chunk, level + 1);
};
XMLDocumentCB.prototype.onEnd = function () {
this.documentCompleted = true;
return this.onEndCallback();
};
XMLDocumentCB.prototype.debugInfo = function (name) {
if (name == null) {
return "";
} else {
return "node: <" + name + ">";
}
};
XMLDocumentCB.prototype.ele = function () {
return this.element.apply(this, arguments);
};
XMLDocumentCB.prototype.nod = function (name, attributes, text) {
return this.node(name, attributes, text);
};
XMLDocumentCB.prototype.txt = function (value) {
return this.text(value);
};
XMLDocumentCB.prototype.dat = function (value) {
return this.cdata(value);
};
XMLDocumentCB.prototype.com = function (value) {
return this.comment(value);
};
XMLDocumentCB.prototype.ins = function (target, value) {
return this.instruction(target, value);
};
XMLDocumentCB.prototype.dec = function (version, encoding, standalone) {
return this.declaration(version, encoding, standalone);
};
XMLDocumentCB.prototype.dtd = function (root, pubID, sysID) {
return this.doctype(root, pubID, sysID);
};
XMLDocumentCB.prototype.e = function (name, attributes, text) {
return this.element(name, attributes, text);
};
XMLDocumentCB.prototype.n = function (name, attributes, text) {
return this.node(name, attributes, text);
};
XMLDocumentCB.prototype.t = function (value) {
return this.text(value);
};
XMLDocumentCB.prototype.d = function (value) {
return this.cdata(value);
};
XMLDocumentCB.prototype.c = function (value) {
return this.comment(value);
};
XMLDocumentCB.prototype.r = function (value) {
return this.raw(value);
};
XMLDocumentCB.prototype.i = function (target, value) {
return this.instruction(target, value);
};
XMLDocumentCB.prototype.att = function () {
if (this.currentNode && this.currentNode.type === NodeType.DocType) {
return this.attList.apply(this, arguments);
} else {
return this.attribute.apply(this, arguments);
}
};
XMLDocumentCB.prototype.a = function () {
if (this.currentNode && this.currentNode.type === NodeType.DocType) {
return this.attList.apply(this, arguments);
} else {
return this.attribute.apply(this, arguments);
}
};
XMLDocumentCB.prototype.ent = function (name, value) {
return this.entity(name, value);
};
XMLDocumentCB.prototype.pent = function (name, value) {
return this.pEntity(name, value);
};
XMLDocumentCB.prototype.not = function (name, value) {
return this.notation(name, value);
};
return XMLDocumentCB;
}();
}).call(undefined);
},{"./NodeType":251,"./Utility":252,"./WriterState":253,"./XMLAttribute":254,"./XMLCData":255,"./XMLComment":257,"./XMLDTDAttList":262,"./XMLDTDElement":263,"./XMLDTDEntity":264,"./XMLDTDNotation":265,"./XMLDeclaration":266,"./XMLDocType":267,"./XMLDocument":268,"./XMLElement":271,"./XMLProcessingInstruction":275,"./XMLRaw":276,"./XMLStringWriter":278,"./XMLStringifier":279,"./XMLText":280}],270:[function(require,module,exports){
'use strict';
var _create = require('babel-runtime/core-js/object/create');
var _create2 = _interopRequireDefault(_create);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by CoffeeScript 1.12.7
(function () {
var NodeType,
XMLDummy,
XMLNode,
extend = function extend(child, parent) {
for (var key in parent) {
if (hasProp.call(parent, key)) child[key] = parent[key];
}function ctor() {
this.constructor = child;
}ctor.prototype = parent.prototype;child.prototype = new ctor();child.__super__ = parent.prototype;return child;
},
hasProp = {}.hasOwnProperty;
XMLNode = require('./XMLNode');
NodeType = require('./NodeType');
module.exports = XMLDummy = function (superClass) {
extend(XMLDummy, superClass);
function XMLDummy(parent) {
XMLDummy.__super__.constructor.call(this, parent);
this.type = NodeType.Dummy;
}
XMLDummy.prototype.clone = function () {
return (0, _create2.default)(this);
};
XMLDummy.prototype.toString = function (options) {
return '';
};
return XMLDummy;
}(XMLNode);
}).call(undefined);
},{"./NodeType":251,"./XMLNode":273,"babel-runtime/core-js/object/create":55}],271:[function(require,module,exports){
'use strict';
var _create = require('babel-runtime/core-js/object/create');
var _create2 = _interopRequireDefault(_create);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by CoffeeScript 1.12.7
(function () {
var NodeType,
XMLAttribute,
XMLElement,
XMLNamedNodeMap,
XMLNode,
getValue,
isFunction,
isObject,
ref,
extend = function extend(child, parent) {
for (var key in parent) {
if (hasProp.call(parent, key)) child[key] = parent[key];
}function ctor() {
this.constructor = child;
}ctor.prototype = parent.prototype;child.prototype = new ctor();child.__super__ = parent.prototype;return child;
},
hasProp = {}.hasOwnProperty;
ref = require('./Utility'), isObject = ref.isObject, isFunction = ref.isFunction, getValue = ref.getValue;
XMLNode = require('./XMLNode');
NodeType = require('./NodeType');
XMLAttribute = require('./XMLAttribute');
XMLNamedNodeMap = require('./XMLNamedNodeMap');
module.exports = XMLElement = function (superClass) {
extend(XMLElement, superClass);
function XMLElement(parent, name, attributes) {
var child, j, len, ref1;
XMLElement.__super__.constructor.call(this, parent);
if (name == null) {
throw new Error("Missing element name. " + this.debugInfo());
}
this.name = this.stringify.name(name);
this.type = NodeType.Element;
this.attribs = {};
this.schemaTypeInfo = null;
if (attributes != null) {
this.attribute(attributes);
}
if (parent.type === NodeType.Document) {
this.isRoot = true;
this.documentObject = parent;
parent.rootObject = this;
if (parent.children) {
ref1 = parent.children;
for (j = 0, len = ref1.length; j < len; j++) {
child = ref1[j];
if (child.type === NodeType.DocType) {
child.name = this.name;
break;
}
}
}
}
}
Object.defineProperty(XMLElement.prototype, 'tagName', {
get: function get() {
return this.name;
}
});
Object.defineProperty(XMLElement.prototype, 'namespaceURI', {
get: function get() {
return '';
}
});
Object.defineProperty(XMLElement.prototype, 'prefix', {
get: function get() {
return '';
}
});
Object.defineProperty(XMLElement.prototype, 'localName', {
get: function get() {
return this.name;
}
});
Object.defineProperty(XMLElement.prototype, 'id', {
get: function get() {
throw new Error("This DOM method is not implemented." + this.debugInfo());
}
});
Object.defineProperty(XMLElement.prototype, 'className', {
get: function get() {
throw new Error("This DOM method is not implemented." + this.debugInfo());
}
});
Object.defineProperty(XMLElement.prototype, 'classList', {
get: function get() {
throw new Error("This DOM method is not implemented." + this.debugInfo());
}
});
Object.defineProperty(XMLElement.prototype, 'attributes', {
get: function get() {
if (!this.attributeMap || !this.attributeMap.nodes) {
this.attributeMap = new XMLNamedNodeMap(this.attribs);
}
return this.attributeMap;
}
});
XMLElement.prototype.clone = function () {
var att, attName, clonedSelf, ref1;
clonedSelf = (0, _create2.default)(this);
if (clonedSelf.isRoot) {
clonedSelf.documentObject = null;
}
clonedSelf.attribs = {};
ref1 = this.attribs;
for (attName in ref1) {
if (!hasProp.call(ref1, attName)) continue;
att = ref1[attName];
clonedSelf.attribs[attName] = att.clone();
}
clonedSelf.children = [];
this.children.forEach(function (child) {
var clonedChild;
clonedChild = child.clone();
clonedChild.parent = clonedSelf;
return clonedSelf.children.push(clonedChild);
});
return clonedSelf;
};
XMLElement.prototype.attribute = function (name, value) {
var attName, attValue;
if (name != null) {
name = getValue(name);
}
if (isObject(name)) {
for (attName in name) {
if (!hasProp.call(name, attName)) continue;
attValue = name[attName];
this.attribute(attName, attValue);
}
} else {
if (isFunction(value)) {
value = value.apply();
}
if (this.options.keepNullAttributes && value == null) {
this.attribs[name] = new XMLAttribute(this, name, "");
} else if (value != null) {
this.attribs[name] = new XMLAttribute(this, name, value);
}
}
return this;
};
XMLElement.prototype.removeAttribute = function (name) {
var attName, j, len;
if (name == null) {
throw new Error("Missing attribute name. " + this.debugInfo());
}
name = getValue(name);
if (Array.isArray(name)) {
for (j = 0, len = name.length; j < len; j++) {
attName = name[j];
delete this.attribs[attName];
}
} else {
delete this.attribs[name];
}
return this;
};
XMLElement.prototype.toString = function (options) {
return this.options.writer.element(this, this.options.writer.filterOptions(options));
};
XMLElement.prototype.att = function (name, value) {
return this.attribute(name, value);
};
XMLElement.prototype.a = function (name, value) {
return this.attribute(name, value);
};
XMLElement.prototype.getAttribute = function (name) {
if (this.attribs.hasOwnProperty(name)) {
return this.attribs[name].value;
} else {
return null;
}
};
XMLElement.prototype.setAttribute = function (name, value) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLElement.prototype.getAttributeNode = function (name) {
if (this.attribs.hasOwnProperty(name)) {
return this.attribs[name];
} else {
return null;
}
};
XMLElement.prototype.setAttributeNode = function (newAttr) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLElement.prototype.removeAttributeNode = function (oldAttr) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLElement.prototype.getElementsByTagName = function (name) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLElement.prototype.getAttributeNS = function (namespaceURI, localName) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLElement.prototype.setAttributeNS = function (namespaceURI, qualifiedName, value) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLElement.prototype.removeAttributeNS = function (namespaceURI, localName) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLElement.prototype.getAttributeNodeNS = function (namespaceURI, localName) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLElement.prototype.setAttributeNodeNS = function (newAttr) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLElement.prototype.getElementsByTagNameNS = function (namespaceURI, localName) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLElement.prototype.hasAttribute = function (name) {
return this.attribs.hasOwnProperty(name);
};
XMLElement.prototype.hasAttributeNS = function (namespaceURI, localName) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLElement.prototype.setIdAttribute = function (name, isId) {
if (this.attribs.hasOwnProperty(name)) {
return this.attribs[name].isId;
} else {
return isId;
}
};
XMLElement.prototype.setIdAttributeNS = function (namespaceURI, localName, isId) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLElement.prototype.setIdAttributeNode = function (idAttr, isId) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLElement.prototype.getElementsByTagName = function (tagname) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLElement.prototype.getElementsByTagNameNS = function (namespaceURI, localName) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLElement.prototype.getElementsByClassName = function (classNames) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLElement.prototype.isEqualNode = function (node) {
var i, j, ref1;
if (!XMLElement.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) {
return false;
}
if (node.namespaceURI !== this.namespaceURI) {
return false;
}
if (node.prefix !== this.prefix) {
return false;
}
if (node.localName !== this.localName) {
return false;
}
if (node.attribs.length !== this.attribs.length) {
return false;
}
for (i = j = 0, ref1 = this.attribs.length - 1; 0 <= ref1 ? j <= ref1 : j >= ref1; i = 0 <= ref1 ? ++j : --j) {
if (!this.attribs[i].isEqualNode(node.attribs[i])) {
return false;
}
}
return true;
};
return XMLElement;
}(XMLNode);
}).call(undefined);
},{"./NodeType":251,"./Utility":252,"./XMLAttribute":254,"./XMLNamedNodeMap":272,"./XMLNode":273,"babel-runtime/core-js/object/create":55}],272:[function(require,module,exports){
"use strict";
var _keys = require("babel-runtime/core-js/object/keys");
var _keys2 = _interopRequireDefault(_keys);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by CoffeeScript 1.12.7
(function () {
var XMLNamedNodeMap;
module.exports = XMLNamedNodeMap = function () {
function XMLNamedNodeMap(nodes) {
this.nodes = nodes;
}
Object.defineProperty(XMLNamedNodeMap.prototype, 'length', {
get: function get() {
return (0, _keys2.default)(this.nodes).length || 0;
}
});
XMLNamedNodeMap.prototype.clone = function () {
return this.nodes = null;
};
XMLNamedNodeMap.prototype.getNamedItem = function (name) {
return this.nodes[name];
};
XMLNamedNodeMap.prototype.setNamedItem = function (node) {
var oldNode;
oldNode = this.nodes[node.nodeName];
this.nodes[node.nodeName] = node;
return oldNode || null;
};
XMLNamedNodeMap.prototype.removeNamedItem = function (name) {
var oldNode;
oldNode = this.nodes[name];
delete this.nodes[name];
return oldNode || null;
};
XMLNamedNodeMap.prototype.item = function (index) {
return this.nodes[(0, _keys2.default)(this.nodes)[index]] || null;
};
XMLNamedNodeMap.prototype.getNamedItemNS = function (namespaceURI, localName) {
throw new Error("This DOM method is not implemented.");
};
XMLNamedNodeMap.prototype.setNamedItemNS = function (node) {
throw new Error("This DOM method is not implemented.");
};
XMLNamedNodeMap.prototype.removeNamedItemNS = function (namespaceURI, localName) {
throw new Error("This DOM method is not implemented.");
};
return XMLNamedNodeMap;
}();
}).call(undefined);
},{"babel-runtime/core-js/object/keys":60}],273:[function(require,module,exports){
'use strict';
// Generated by CoffeeScript 1.12.7
(function () {
var DocumentPosition,
NodeType,
XMLCData,
XMLComment,
XMLDeclaration,
XMLDocType,
XMLDummy,
XMLElement,
XMLNamedNodeMap,
XMLNode,
XMLNodeList,
XMLProcessingInstruction,
XMLRaw,
XMLText,
getValue,
isEmpty,
isFunction,
isObject,
ref1,
hasProp = {}.hasOwnProperty;
ref1 = require('./Utility'), isObject = ref1.isObject, isFunction = ref1.isFunction, isEmpty = ref1.isEmpty, getValue = ref1.getValue;
XMLElement = null;
XMLCData = null;
XMLComment = null;
XMLDeclaration = null;
XMLDocType = null;
XMLRaw = null;
XMLText = null;
XMLProcessingInstruction = null;
XMLDummy = null;
NodeType = null;
XMLNodeList = null;
XMLNamedNodeMap = null;
DocumentPosition = null;
module.exports = XMLNode = function () {
function XMLNode(parent1) {
this.parent = parent1;
if (this.parent) {
this.options = this.parent.options;
this.stringify = this.parent.stringify;
}
this.value = null;
this.children = [];
this.baseURI = null;
if (!XMLElement) {
XMLElement = require('./XMLElement');
XMLCData = require('./XMLCData');
XMLComment = require('./XMLComment');
XMLDeclaration = require('./XMLDeclaration');
XMLDocType = require('./XMLDocType');
XMLRaw = require('./XMLRaw');
XMLText = require('./XMLText');
XMLProcessingInstruction = require('./XMLProcessingInstruction');
XMLDummy = require('./XMLDummy');
NodeType = require('./NodeType');
XMLNodeList = require('./XMLNodeList');
XMLNamedNodeMap = require('./XMLNamedNodeMap');
DocumentPosition = require('./DocumentPosition');
}
}
Object.defineProperty(XMLNode.prototype, 'nodeName', {
get: function get() {
return this.name;
}
});
Object.defineProperty(XMLNode.prototype, 'nodeType', {
get: function get() {
return this.type;
}
});
Object.defineProperty(XMLNode.prototype, 'nodeValue', {
get: function get() {
return this.value;
}
});
Object.defineProperty(XMLNode.prototype, 'parentNode', {
get: function get() {
return this.parent;
}
});
Object.defineProperty(XMLNode.prototype, 'childNodes', {
get: function get() {
if (!this.childNodeList || !this.childNodeList.nodes) {
this.childNodeList = new XMLNodeList(this.children);
}
return this.childNodeList;
}
});
Object.defineProperty(XMLNode.prototype, 'firstChild', {
get: function get() {
return this.children[0] || null;
}
});
Object.defineProperty(XMLNode.prototype, 'lastChild', {
get: function get() {
return this.children[this.children.length - 1] || null;
}
});
Object.defineProperty(XMLNode.prototype, 'previousSibling', {
get: function get() {
var i;
i = this.parent.children.indexOf(this);
return this.parent.children[i - 1] || null;
}
});
Object.defineProperty(XMLNode.prototype, 'nextSibling', {
get: function get() {
var i;
i = this.parent.children.indexOf(this);
return this.parent.children[i + 1] || null;
}
});
Object.defineProperty(XMLNode.prototype, 'ownerDocument', {
get: function get() {
return this.document() || null;
}
});
Object.defineProperty(XMLNode.prototype, 'textContent', {
get: function get() {
var child, j, len, ref2, str;
if (this.nodeType === NodeType.Element || this.nodeType === NodeType.DocumentFragment) {
str = '';
ref2 = this.children;
for (j = 0, len = ref2.length; j < len; j++) {
child = ref2[j];
if (child.textContent) {
str += child.textContent;
}
}
return str;
} else {
return null;
}
},
set: function set(value) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
}
});
XMLNode.prototype.setParent = function (parent) {
var child, j, len, ref2, results;
this.parent = parent;
if (parent) {
this.options = parent.options;
this.stringify = parent.stringify;
}
ref2 = this.children;
results = [];
for (j = 0, len = ref2.length; j < len; j++) {
child = ref2[j];
results.push(child.setParent(this));
}
return results;
};
XMLNode.prototype.element = function (name, attributes, text) {
var childNode, item, j, k, key, lastChild, len, len1, ref2, ref3, val;
lastChild = null;
if (attributes === null && text == null) {
ref2 = [{}, null], attributes = ref2[0], text = ref2[1];
}
if (attributes == null) {
attributes = {};
}
attributes = getValue(attributes);
if (!isObject(attributes)) {
ref3 = [attributes, text], text = ref3[0], attributes = ref3[1];
}
if (name != null) {
name = getValue(name);
}
if (Array.isArray(name)) {
for (j = 0, len = name.length; j < len; j++) {
item = name[j];
lastChild = this.element(item);
}
} else if (isFunction(name)) {
lastChild = this.element(name.apply());
} else if (isObject(name)) {
for (key in name) {
if (!hasProp.call(name, key)) continue;
val = name[key];
if (isFunction(val)) {
val = val.apply();
}
if (!this.options.ignoreDecorators && this.stringify.convertAttKey && key.indexOf(this.stringify.convertAttKey) === 0) {
lastChild = this.attribute(key.substr(this.stringify.convertAttKey.length), val);
} else if (!this.options.separateArrayItems && Array.isArray(val) && isEmpty(val)) {
lastChild = this.dummy();
} else if (isObject(val) && isEmpty(val)) {
lastChild = this.element(key);
} else if (!this.options.keepNullNodes && val == null) {
lastChild = this.dummy();
} else if (!this.options.separateArrayItems && Array.isArray(val)) {
for (k = 0, len1 = val.length; k < len1; k++) {
item = val[k];
childNode = {};
childNode[key] = item;
lastChild = this.element(childNode);
}
} else if (isObject(val)) {
if (!this.options.ignoreDecorators && this.stringify.convertTextKey && key.indexOf(this.stringify.convertTextKey) === 0) {
lastChild = this.element(val);
} else {
lastChild = this.element(key);
lastChild.element(val);
}
} else {
lastChild = this.element(key, val);
}
}
} else if (!this.options.keepNullNodes && text === null) {
lastChild = this.dummy();
} else {
if (!this.options.ignoreDecorators && this.stringify.convertTextKey && name.indexOf(this.stringify.convertTextKey) === 0) {
lastChild = this.text(text);
} else if (!this.options.ignoreDecorators && this.stringify.convertCDataKey && name.indexOf(this.stringify.convertCDataKey) === 0) {
lastChild = this.cdata(text);
} else if (!this.options.ignoreDecorators && this.stringify.convertCommentKey && name.indexOf(this.stringify.convertCommentKey) === 0) {
lastChild = this.comment(text);
} else if (!this.options.ignoreDecorators && this.stringify.convertRawKey && name.indexOf(this.stringify.convertRawKey) === 0) {
lastChild = this.raw(text);
} else if (!this.options.ignoreDecorators && this.stringify.convertPIKey && name.indexOf(this.stringify.convertPIKey) === 0) {
lastChild = this.instruction(name.substr(this.stringify.convertPIKey.length), text);
} else {
lastChild = this.node(name, attributes, text);
}
}
if (lastChild == null) {
throw new Error("Could not create any elements with: " + name + ". " + this.debugInfo());
}
return lastChild;
};
XMLNode.prototype.insertBefore = function (name, attributes, text) {
var child, i, newChild, refChild, removed;
if (name != null ? name.type : void 0) {
newChild = name;
refChild = attributes;
newChild.setParent(this);
if (refChild) {
i = children.indexOf(refChild);
removed = children.splice(i);
children.push(newChild);
Array.prototype.push.apply(children, removed);
} else {
children.push(newChild);
}
return newChild;
} else {
if (this.isRoot) {
throw new Error("Cannot insert elements at root level. " + this.debugInfo(name));
}
i = this.parent.children.indexOf(this);
removed = this.parent.children.splice(i);
child = this.parent.element(name, attributes, text);
Array.prototype.push.apply(this.parent.children, removed);
return child;
}
};
XMLNode.prototype.insertAfter = function (name, attributes, text) {
var child, i, removed;
if (this.isRoot) {
throw new Error("Cannot insert elements at root level. " + this.debugInfo(name));
}
i = this.parent.children.indexOf(this);
removed = this.parent.children.splice(i + 1);
child = this.parent.element(name, attributes, text);
Array.prototype.push.apply(this.parent.children, removed);
return child;
};
XMLNode.prototype.remove = function () {
var i, ref2;
if (this.isRoot) {
throw new Error("Cannot remove the root element. " + this.debugInfo());
}
i = this.parent.children.indexOf(this);
[].splice.apply(this.parent.children, [i, i - i + 1].concat(ref2 = [])), ref2;
return this.parent;
};
XMLNode.prototype.node = function (name, attributes, text) {
var child, ref2;
if (name != null) {
name = getValue(name);
}
attributes || (attributes = {});
attributes = getValue(attributes);
if (!isObject(attributes)) {
ref2 = [attributes, text], text = ref2[0], attributes = ref2[1];
}
child = new XMLElement(this, name, attributes);
if (text != null) {
child.text(text);
}
this.children.push(child);
return child;
};
XMLNode.prototype.text = function (value) {
var child;
if (isObject(value)) {
this.element(value);
}
child = new XMLText(this, value);
this.children.push(child);
return this;
};
XMLNode.prototype.cdata = function (value) {
var child;
child = new XMLCData(this, value);
this.children.push(child);
return this;
};
XMLNode.prototype.comment = function (value) {
var child;
child = new XMLComment(this, value);
this.children.push(child);
return this;
};
XMLNode.prototype.commentBefore = function (value) {
var child, i, removed;
i = this.parent.children.indexOf(this);
removed = this.parent.children.splice(i);
child = this.parent.comment(value);
Array.prototype.push.apply(this.parent.children, removed);
return this;
};
XMLNode.prototype.commentAfter = function (value) {
var child, i, removed;
i = this.parent.children.indexOf(this);
removed = this.parent.children.splice(i + 1);
child = this.parent.comment(value);
Array.prototype.push.apply(this.parent.children, removed);
return this;
};
XMLNode.prototype.raw = function (value) {
var child;
child = new XMLRaw(this, value);
this.children.push(child);
return this;
};
XMLNode.prototype.dummy = function () {
var child;
child = new XMLDummy(this);
return child;
};
XMLNode.prototype.instruction = function (target, value) {
var insTarget, insValue, instruction, j, len;
if (target != null) {
target = getValue(target);
}
if (value != null) {
value = getValue(value);
}
if (Array.isArray(target)) {
for (j = 0, len = target.length; j < len; j++) {
insTarget = target[j];
this.instruction(insTarget);
}
} else if (isObject(target)) {
for (insTarget in target) {
if (!hasProp.call(target, insTarget)) continue;
insValue = target[insTarget];
this.instruction(insTarget, insValue);
}
} else {
if (isFunction(value)) {
value = value.apply();
}
instruction = new XMLProcessingInstruction(this, target, value);
this.children.push(instruction);
}
return this;
};
XMLNode.prototype.instructionBefore = function (target, value) {
var child, i, removed;
i = this.parent.children.indexOf(this);
removed = this.parent.children.splice(i);
child = this.parent.instruction(target, value);
Array.prototype.push.apply(this.parent.children, removed);
return this;
};
XMLNode.prototype.instructionAfter = function (target, value) {
var child, i, removed;
i = this.parent.children.indexOf(this);
removed = this.parent.children.splice(i + 1);
child = this.parent.instruction(target, value);
Array.prototype.push.apply(this.parent.children, removed);
return this;
};
XMLNode.prototype.declaration = function (version, encoding, standalone) {
var doc, xmldec;
doc = this.document();
xmldec = new XMLDeclaration(doc, version, encoding, standalone);
if (doc.children.length === 0) {
doc.children.unshift(xmldec);
} else if (doc.children[0].type === NodeType.Declaration) {
doc.children[0] = xmldec;
} else {
doc.children.unshift(xmldec);
}
return doc.root() || doc;
};
XMLNode.prototype.dtd = function (pubID, sysID) {
var child, doc, doctype, i, j, k, len, len1, ref2, ref3;
doc = this.document();
doctype = new XMLDocType(doc, pubID, sysID);
ref2 = doc.children;
for (i = j = 0, len = ref2.length; j < len; i = ++j) {
child = ref2[i];
if (child.type === NodeType.DocType) {
doc.children[i] = doctype;
return doctype;
}
}
ref3 = doc.children;
for (i = k = 0, len1 = ref3.length; k < len1; i = ++k) {
child = ref3[i];
if (child.isRoot) {
doc.children.splice(i, 0, doctype);
return doctype;
}
}
doc.children.push(doctype);
return doctype;
};
XMLNode.prototype.up = function () {
if (this.isRoot) {
throw new Error("The root node has no parent. Use doc() if you need to get the document object.");
}
return this.parent;
};
XMLNode.prototype.root = function () {
var node;
node = this;
while (node) {
if (node.type === NodeType.Document) {
return node.rootObject;
} else if (node.isRoot) {
return node;
} else {
node = node.parent;
}
}
};
XMLNode.prototype.document = function () {
var node;
node = this;
while (node) {
if (node.type === NodeType.Document) {
return node;
} else {
node = node.parent;
}
}
};
XMLNode.prototype.end = function (options) {
return this.document().end(options);
};
XMLNode.prototype.prev = function () {
var i;
i = this.parent.children.indexOf(this);
if (i < 1) {
throw new Error("Already at the first node. " + this.debugInfo());
}
return this.parent.children[i - 1];
};
XMLNode.prototype.next = function () {
var i;
i = this.parent.children.indexOf(this);
if (i === -1 || i === this.parent.children.length - 1) {
throw new Error("Already at the last node. " + this.debugInfo());
}
return this.parent.children[i + 1];
};
XMLNode.prototype.importDocument = function (doc) {
var clonedRoot;
clonedRoot = doc.root().clone();
clonedRoot.parent = this;
clonedRoot.isRoot = false;
this.children.push(clonedRoot);
return this;
};
XMLNode.prototype.debugInfo = function (name) {
var ref2, ref3;
name = name || this.name;
if (name == null && !((ref2 = this.parent) != null ? ref2.name : void 0)) {
return "";
} else if (name == null) {
return "parent: <" + this.parent.name + ">";
} else if (!((ref3 = this.parent) != null ? ref3.name : void 0)) {
return "node: <" + name + ">";
} else {
return "node: <" + name + ">, parent: <" + this.parent.name + ">";
}
};
XMLNode.prototype.ele = function (name, attributes, text) {
return this.element(name, attributes, text);
};
XMLNode.prototype.nod = function (name, attributes, text) {
return this.node(name, attributes, text);
};
XMLNode.prototype.txt = function (value) {
return this.text(value);
};
XMLNode.prototype.dat = function (value) {
return this.cdata(value);
};
XMLNode.prototype.com = function (value) {
return this.comment(value);
};
XMLNode.prototype.ins = function (target, value) {
return this.instruction(target, value);
};
XMLNode.prototype.doc = function () {
return this.document();
};
XMLNode.prototype.dec = function (version, encoding, standalone) {
return this.declaration(version, encoding, standalone);
};
XMLNode.prototype.e = function (name, attributes, text) {
return this.element(name, attributes, text);
};
XMLNode.prototype.n = function (name, attributes, text) {
return this.node(name, attributes, text);
};
XMLNode.prototype.t = function (value) {
return this.text(value);
};
XMLNode.prototype.d = function (value) {
return this.cdata(value);
};
XMLNode.prototype.c = function (value) {
return this.comment(value);
};
XMLNode.prototype.r = function (value) {
return this.raw(value);
};
XMLNode.prototype.i = function (target, value) {
return this.instruction(target, value);
};
XMLNode.prototype.u = function () {
return this.up();
};
XMLNode.prototype.importXMLBuilder = function (doc) {
return this.importDocument(doc);
};
XMLNode.prototype.replaceChild = function (newChild, oldChild) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLNode.prototype.removeChild = function (oldChild) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLNode.prototype.appendChild = function (newChild) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLNode.prototype.hasChildNodes = function () {
return this.children.length !== 0;
};
XMLNode.prototype.cloneNode = function (deep) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLNode.prototype.normalize = function () {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLNode.prototype.isSupported = function (feature, version) {
return true;
};
XMLNode.prototype.hasAttributes = function () {
return this.attribs.length !== 0;
};
XMLNode.prototype.compareDocumentPosition = function (other) {
var ref, res;
ref = this;
if (ref === other) {
return 0;
} else if (this.document() !== other.document()) {
res = DocumentPosition.Disconnected | DocumentPosition.ImplementationSpecific;
if (Math.random() < 0.5) {
res |= DocumentPosition.Preceding;
} else {
res |= DocumentPosition.Following;
}
return res;
} else if (ref.isAncestor(other)) {
return DocumentPosition.Contains | DocumentPosition.Preceding;
} else if (ref.isDescendant(other)) {
return DocumentPosition.Contains | DocumentPosition.Following;
} else if (ref.isPreceding(other)) {
return DocumentPosition.Preceding;
} else {
return DocumentPosition.Following;
}
};
XMLNode.prototype.isSameNode = function (other) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLNode.prototype.lookupPrefix = function (namespaceURI) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLNode.prototype.isDefaultNamespace = function (namespaceURI) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLNode.prototype.lookupNamespaceURI = function (prefix) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLNode.prototype.isEqualNode = function (node) {
var i, j, ref2;
if (node.nodeType !== this.nodeType) {
return false;
}
if (node.children.length !== this.children.length) {
return false;
}
for (i = j = 0, ref2 = this.children.length - 1; 0 <= ref2 ? j <= ref2 : j >= ref2; i = 0 <= ref2 ? ++j : --j) {
if (!this.children[i].isEqualNode(node.children[i])) {
return false;
}
}
return true;
};
XMLNode.prototype.getFeature = function (feature, version) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLNode.prototype.setUserData = function (key, data, handler) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLNode.prototype.getUserData = function (key) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLNode.prototype.contains = function (other) {
if (!other) {
return false;
}
return other === this || this.isDescendant(other);
};
XMLNode.prototype.isDescendant = function (node) {
var child, isDescendantChild, j, len, ref2;
ref2 = this.children;
for (j = 0, len = ref2.length; j < len; j++) {
child = ref2[j];
if (node === child) {
return true;
}
isDescendantChild = child.isDescendant(node);
if (isDescendantChild) {
return true;
}
}
return false;
};
XMLNode.prototype.isAncestor = function (node) {
return node.isDescendant(this);
};
XMLNode.prototype.isPreceding = function (node) {
var nodePos, thisPos;
nodePos = this.treePosition(node);
thisPos = this.treePosition(this);
if (nodePos === -1 || thisPos === -1) {
return false;
} else {
return nodePos < thisPos;
}
};
XMLNode.prototype.isFollowing = function (node) {
var nodePos, thisPos;
nodePos = this.treePosition(node);
thisPos = this.treePosition(this);
if (nodePos === -1 || thisPos === -1) {
return false;
} else {
return nodePos > thisPos;
}
};
XMLNode.prototype.treePosition = function (node) {
var found, pos;
pos = 0;
found = false;
this.foreachTreeNode(this.document(), function (childNode) {
pos++;
if (!found && childNode === node) {
return found = true;
}
});
if (found) {
return pos;
} else {
return -1;
}
};
XMLNode.prototype.foreachTreeNode = function (node, func) {
var child, j, len, ref2, res;
node || (node = this.document());
ref2 = node.children;
for (j = 0, len = ref2.length; j < len; j++) {
child = ref2[j];
if (res = func(child)) {
return res;
} else {
res = this.foreachTreeNode(child, func);
if (res) {
return res;
}
}
}
};
return XMLNode;
}();
}).call(undefined);
},{"./DocumentPosition":250,"./NodeType":251,"./Utility":252,"./XMLCData":255,"./XMLComment":257,"./XMLDeclaration":266,"./XMLDocType":267,"./XMLDummy":270,"./XMLElement":271,"./XMLNamedNodeMap":272,"./XMLNodeList":274,"./XMLProcessingInstruction":275,"./XMLRaw":276,"./XMLText":280}],274:[function(require,module,exports){
'use strict';
// Generated by CoffeeScript 1.12.7
(function () {
var XMLNodeList;
module.exports = XMLNodeList = function () {
function XMLNodeList(nodes) {
this.nodes = nodes;
}
Object.defineProperty(XMLNodeList.prototype, 'length', {
get: function get() {
return this.nodes.length || 0;
}
});
XMLNodeList.prototype.clone = function () {
return this.nodes = null;
};
XMLNodeList.prototype.item = function (index) {
return this.nodes[index] || null;
};
return XMLNodeList;
}();
}).call(undefined);
},{}],275:[function(require,module,exports){
'use strict';
var _create = require('babel-runtime/core-js/object/create');
var _create2 = _interopRequireDefault(_create);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by CoffeeScript 1.12.7
(function () {
var NodeType,
XMLCharacterData,
XMLProcessingInstruction,
extend = function extend(child, parent) {
for (var key in parent) {
if (hasProp.call(parent, key)) child[key] = parent[key];
}function ctor() {
this.constructor = child;
}ctor.prototype = parent.prototype;child.prototype = new ctor();child.__super__ = parent.prototype;return child;
},
hasProp = {}.hasOwnProperty;
NodeType = require('./NodeType');
XMLCharacterData = require('./XMLCharacterData');
module.exports = XMLProcessingInstruction = function (superClass) {
extend(XMLProcessingInstruction, superClass);
function XMLProcessingInstruction(parent, target, value) {
XMLProcessingInstruction.__super__.constructor.call(this, parent);
if (target == null) {
throw new Error("Missing instruction target. " + this.debugInfo());
}
this.type = NodeType.ProcessingInstruction;
this.target = this.stringify.insTarget(target);
this.name = this.target;
if (value) {
this.value = this.stringify.insValue(value);
}
}
XMLProcessingInstruction.prototype.clone = function () {
return (0, _create2.default)(this);
};
XMLProcessingInstruction.prototype.toString = function (options) {
return this.options.writer.processingInstruction(this, this.options.writer.filterOptions(options));
};
XMLProcessingInstruction.prototype.isEqualNode = function (node) {
if (!XMLProcessingInstruction.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) {
return false;
}
if (node.target !== this.target) {
return false;
}
return true;
};
return XMLProcessingInstruction;
}(XMLCharacterData);
}).call(undefined);
},{"./NodeType":251,"./XMLCharacterData":256,"babel-runtime/core-js/object/create":55}],276:[function(require,module,exports){
'use strict';
var _create = require('babel-runtime/core-js/object/create');
var _create2 = _interopRequireDefault(_create);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by CoffeeScript 1.12.7
(function () {
var NodeType,
XMLNode,
XMLRaw,
extend = function extend(child, parent) {
for (var key in parent) {
if (hasProp.call(parent, key)) child[key] = parent[key];
}function ctor() {
this.constructor = child;
}ctor.prototype = parent.prototype;child.prototype = new ctor();child.__super__ = parent.prototype;return child;
},
hasProp = {}.hasOwnProperty;
NodeType = require('./NodeType');
XMLNode = require('./XMLNode');
module.exports = XMLRaw = function (superClass) {
extend(XMLRaw, superClass);
function XMLRaw(parent, text) {
XMLRaw.__super__.constructor.call(this, parent);
if (text == null) {
throw new Error("Missing raw text. " + this.debugInfo());
}
this.type = NodeType.Raw;
this.value = this.stringify.raw(text);
}
XMLRaw.prototype.clone = function () {
return (0, _create2.default)(this);
};
XMLRaw.prototype.toString = function (options) {
return this.options.writer.raw(this, this.options.writer.filterOptions(options));
};
return XMLRaw;
}(XMLNode);
}).call(undefined);
},{"./NodeType":251,"./XMLNode":273,"babel-runtime/core-js/object/create":55}],277:[function(require,module,exports){
'use strict';
// Generated by CoffeeScript 1.12.7
(function () {
var NodeType,
WriterState,
XMLStreamWriter,
XMLWriterBase,
extend = function extend(child, parent) {
for (var key in parent) {
if (hasProp.call(parent, key)) child[key] = parent[key];
}function ctor() {
this.constructor = child;
}ctor.prototype = parent.prototype;child.prototype = new ctor();child.__super__ = parent.prototype;return child;
},
hasProp = {}.hasOwnProperty;
NodeType = require('./NodeType');
XMLWriterBase = require('./XMLWriterBase');
WriterState = require('./WriterState');
module.exports = XMLStreamWriter = function (superClass) {
extend(XMLStreamWriter, superClass);
function XMLStreamWriter(stream, options) {
this.stream = stream;
XMLStreamWriter.__super__.constructor.call(this, options);
}
XMLStreamWriter.prototype.endline = function (node, options, level) {
if (node.isLastRootNode && options.state === WriterState.CloseTag) {
return '';
} else {
return XMLStreamWriter.__super__.endline.call(this, node, options, level);
}
};
XMLStreamWriter.prototype.document = function (doc, options) {
var child, i, j, k, len, len1, ref, ref1, results;
ref = doc.children;
for (i = j = 0, len = ref.length; j < len; i = ++j) {
child = ref[i];
child.isLastRootNode = i === doc.children.length - 1;
}
options = this.filterOptions(options);
ref1 = doc.children;
results = [];
for (k = 0, len1 = ref1.length; k < len1; k++) {
child = ref1[k];
results.push(this.writeChildNode(child, options, 0));
}
return results;
};
XMLStreamWriter.prototype.attribute = function (att, options, level) {
return this.stream.write(XMLStreamWriter.__super__.attribute.call(this, att, options, level));
};
XMLStreamWriter.prototype.cdata = function (node, options, level) {
return this.stream.write(XMLStreamWriter.__super__.cdata.call(this, node, options, level));
};
XMLStreamWriter.prototype.comment = function (node, options, level) {
return this.stream.write(XMLStreamWriter.__super__.comment.call(this, node, options, level));
};
XMLStreamWriter.prototype.declaration = function (node, options, level) {
return this.stream.write(XMLStreamWriter.__super__.declaration.call(this, node, options, level));
};
XMLStreamWriter.prototype.docType = function (node, options, level) {
var child, j, len, ref;
level || (level = 0);
this.openNode(node, options, level);
options.state = WriterState.OpenTag;
this.stream.write(this.indent(node, options, level));
this.stream.write('<!DOCTYPE ' + node.root().name);
if (node.pubID && node.sysID) {
this.stream.write(' PUBLIC "' + node.pubID + '" "' + node.sysID + '"');
} else if (node.sysID) {
this.stream.write(' SYSTEM "' + node.sysID + '"');
}
if (node.children.length > 0) {
this.stream.write(' [');
this.stream.write(this.endline(node, options, level));
options.state = WriterState.InsideTag;
ref = node.children;
for (j = 0, len = ref.length; j < len; j++) {
child = ref[j];
this.writeChildNode(child, options, level + 1);
}
options.state = WriterState.CloseTag;
this.stream.write(']');
}
options.state = WriterState.CloseTag;
this.stream.write(options.spaceBeforeSlash + '>');
this.stream.write(this.endline(node, options, level));
options.state = WriterState.None;
return this.closeNode(node, options, level);
};
XMLStreamWriter.prototype.element = function (node, options, level) {
var att, child, childNodeCount, firstChildNode, j, len, name, prettySuppressed, ref, ref1;
level || (level = 0);
this.openNode(node, options, level);
options.state = WriterState.OpenTag;
this.stream.write(this.indent(node, options, level) + '<' + node.name);
ref = node.attribs;
for (name in ref) {
if (!hasProp.call(ref, name)) continue;
att = ref[name];
this.attribute(att, options, level);
}
childNodeCount = node.children.length;
firstChildNode = childNodeCount === 0 ? null : node.children[0];
if (childNodeCount === 0 || node.children.every(function (e) {
return (e.type === NodeType.Text || e.type === NodeType.Raw) && e.value === '';
})) {
if (options.allowEmpty) {
this.stream.write('>');
options.state = WriterState.CloseTag;
this.stream.write('</' + node.name + '>');
} else {
options.state = WriterState.CloseTag;
this.stream.write(options.spaceBeforeSlash + '/>');
}
} else if (options.pretty && childNodeCount === 1 && (firstChildNode.type === NodeType.Text || firstChildNode.type === NodeType.Raw) && firstChildNode.value != null) {
this.stream.write('>');
options.state = WriterState.InsideTag;
options.suppressPrettyCount++;
prettySuppressed = true;
this.writeChildNode(firstChildNode, options, level + 1);
options.suppressPrettyCount--;
prettySuppressed = false;
options.state = WriterState.CloseTag;
this.stream.write('</' + node.name + '>');
} else {
this.stream.write('>' + this.endline(node, options, level));
options.state = WriterState.InsideTag;
ref1 = node.children;
for (j = 0, len = ref1.length; j < len; j++) {
child = ref1[j];
this.writeChildNode(child, options, level + 1);
}
options.state = WriterState.CloseTag;
this.stream.write(this.indent(node, options, level) + '</' + node.name + '>');
}
this.stream.write(this.endline(node, options, level));
options.state = WriterState.None;
return this.closeNode(node, options, level);
};
XMLStreamWriter.prototype.processingInstruction = function (node, options, level) {
return this.stream.write(XMLStreamWriter.__super__.processingInstruction.call(this, node, options, level));
};
XMLStreamWriter.prototype.raw = function (node, options, level) {
return this.stream.write(XMLStreamWriter.__super__.raw.call(this, node, options, level));
};
XMLStreamWriter.prototype.text = function (node, options, level) {
return this.stream.write(XMLStreamWriter.__super__.text.call(this, node, options, level));
};
XMLStreamWriter.prototype.dtdAttList = function (node, options, level) {
return this.stream.write(XMLStreamWriter.__super__.dtdAttList.call(this, node, options, level));
};
XMLStreamWriter.prototype.dtdElement = function (node, options, level) {
return this.stream.write(XMLStreamWriter.__super__.dtdElement.call(this, node, options, level));
};
XMLStreamWriter.prototype.dtdEntity = function (node, options, level) {
return this.stream.write(XMLStreamWriter.__super__.dtdEntity.call(this, node, options, level));
};
XMLStreamWriter.prototype.dtdNotation = function (node, options, level) {
return this.stream.write(XMLStreamWriter.__super__.dtdNotation.call(this, node, options, level));
};
return XMLStreamWriter;
}(XMLWriterBase);
}).call(undefined);
},{"./NodeType":251,"./WriterState":253,"./XMLWriterBase":281}],278:[function(require,module,exports){
'use strict';
// Generated by CoffeeScript 1.12.7
(function () {
var XMLStringWriter,
XMLWriterBase,
extend = function extend(child, parent) {
for (var key in parent) {
if (hasProp.call(parent, key)) child[key] = parent[key];
}function ctor() {
this.constructor = child;
}ctor.prototype = parent.prototype;child.prototype = new ctor();child.__super__ = parent.prototype;return child;
},
hasProp = {}.hasOwnProperty;
XMLWriterBase = require('./XMLWriterBase');
module.exports = XMLStringWriter = function (superClass) {
extend(XMLStringWriter, superClass);
function XMLStringWriter(options) {
XMLStringWriter.__super__.constructor.call(this, options);
}
XMLStringWriter.prototype.document = function (doc, options) {
var child, i, len, r, ref;
options = this.filterOptions(options);
r = '';
ref = doc.children;
for (i = 0, len = ref.length; i < len; i++) {
child = ref[i];
r += this.writeChildNode(child, options, 0);
}
if (options.pretty && r.slice(-options.newline.length) === options.newline) {
r = r.slice(0, -options.newline.length);
}
return r;
};
return XMLStringWriter;
}(XMLWriterBase);
}).call(undefined);
},{"./XMLWriterBase":281}],279:[function(require,module,exports){
'use strict';
// Generated by CoffeeScript 1.12.7
(function () {
var XMLStringifier,
bind = function bind(fn, me) {
return function () {
return fn.apply(me, arguments);
};
},
hasProp = {}.hasOwnProperty;
module.exports = XMLStringifier = function () {
function XMLStringifier(options) {
this.assertLegalName = bind(this.assertLegalName, this);
this.assertLegalChar = bind(this.assertLegalChar, this);
var key, ref, value;
options || (options = {});
this.options = options;
if (!this.options.version) {
this.options.version = '1.0';
}
ref = options.stringify || {};
for (key in ref) {
if (!hasProp.call(ref, key)) continue;
value = ref[key];
this[key] = value;
}
}
XMLStringifier.prototype.name = function (val) {
if (this.options.noValidation) {
return val;
}
return this.assertLegalName('' + val || '');
};
XMLStringifier.prototype.text = function (val) {
if (this.options.noValidation) {
return val;
}
return this.assertLegalChar(this.textEscape('' + val || ''));
};
XMLStringifier.prototype.cdata = function (val) {
if (this.options.noValidation) {
return val;
}
val = '' + val || '';
val = val.replace(']]>', ']]]]><![CDATA[>');
return this.assertLegalChar(val);
};
XMLStringifier.prototype.comment = function (val) {
if (this.options.noValidation) {
return val;
}
val = '' + val || '';
if (val.match(/--/)) {
throw new Error("Comment text cannot contain double-hypen: " + val);
}
return this.assertLegalChar(val);
};
XMLStringifier.prototype.raw = function (val) {
if (this.options.noValidation) {
return val;
}
return '' + val || '';
};
XMLStringifier.prototype.attValue = function (val) {
if (this.options.noValidation) {
return val;
}
return this.assertLegalChar(this.attEscape(val = '' + val || ''));
};
XMLStringifier.prototype.insTarget = function (val) {
if (this.options.noValidation) {
return val;
}
return this.assertLegalChar('' + val || '');
};
XMLStringifier.prototype.insValue = function (val) {
if (this.options.noValidation) {
return val;
}
val = '' + val || '';
if (val.match(/\?>/)) {
throw new Error("Invalid processing instruction value: " + val);
}
return this.assertLegalChar(val);
};
XMLStringifier.prototype.xmlVersion = function (val) {
if (this.options.noValidation) {
return val;
}
val = '' + val || '';
if (!val.match(/1\.[0-9]+/)) {
throw new Error("Invalid version number: " + val);
}
return val;
};
XMLStringifier.prototype.xmlEncoding = function (val) {
if (this.options.noValidation) {
return val;
}
val = '' + val || '';
if (!val.match(/^[A-Za-z](?:[A-Za-z0-9._-])*$/)) {
throw new Error("Invalid encoding: " + val);
}
return this.assertLegalChar(val);
};
XMLStringifier.prototype.xmlStandalone = function (val) {
if (this.options.noValidation) {
return val;
}
if (val) {
return "yes";
} else {
return "no";
}
};
XMLStringifier.prototype.dtdPubID = function (val) {
if (this.options.noValidation) {
return val;
}
return this.assertLegalChar('' + val || '');
};
XMLStringifier.prototype.dtdSysID = function (val) {
if (this.options.noValidation) {
return val;
}
return this.assertLegalChar('' + val || '');
};
XMLStringifier.prototype.dtdElementValue = function (val) {
if (this.options.noValidation) {
return val;
}
return this.assertLegalChar('' + val || '');
};
XMLStringifier.prototype.dtdAttType = function (val) {
if (this.options.noValidation) {
return val;
}
return this.assertLegalChar('' + val || '');
};
XMLStringifier.prototype.dtdAttDefault = function (val) {
if (this.options.noValidation) {
return val;
}
return this.assertLegalChar('' + val || '');
};
XMLStringifier.prototype.dtdEntityValue = function (val) {
if (this.options.noValidation) {
return val;
}
return this.assertLegalChar('' + val || '');
};
XMLStringifier.prototype.dtdNData = function (val) {
if (this.options.noValidation) {
return val;
}
return this.assertLegalChar('' + val || '');
};
XMLStringifier.prototype.convertAttKey = '@';
XMLStringifier.prototype.convertPIKey = '?';
XMLStringifier.prototype.convertTextKey = '#text';
XMLStringifier.prototype.convertCDataKey = '#cdata';
XMLStringifier.prototype.convertCommentKey = '#comment';
XMLStringifier.prototype.convertRawKey = '#raw';
XMLStringifier.prototype.assertLegalChar = function (str) {
var regex, res;
if (this.options.noValidation) {
return str;
}
regex = '';
if (this.options.version === '1.0') {
regex = /[\0-\x08\x0B\f\x0E-\x1F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
if (res = str.match(regex)) {
throw new Error("Invalid character in string: " + str + " at index " + res.index);
}
} else if (this.options.version === '1.1') {
regex = /[\0\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
if (res = str.match(regex)) {
throw new Error("Invalid character in string: " + str + " at index " + res.index);
}
}
return str;
};
XMLStringifier.prototype.assertLegalName = function (str) {
var regex;
if (this.options.noValidation) {
return str;
}
this.assertLegalChar(str);
regex = /^([:A-Z_a-z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])([\x2D\.0-:A-Z_a-z\xB7\xC0-\xD6\xD8-\xF6\xF8-\u037D\u037F-\u1FFF\u200C\u200D\u203F\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]|[\uD800-\uDB7F][\uDC00-\uDFFF])*$/;
if (!str.match(regex)) {
throw new Error("Invalid character in name");
}
return str;
};
XMLStringifier.prototype.textEscape = function (str) {
var ampregex;
if (this.options.noValidation) {
return str;
}
ampregex = this.options.noDoubleEncoding ? /(?!&\S+;)&/g : /&/g;
return str.replace(ampregex, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\r/g, '&#xD;');
};
XMLStringifier.prototype.attEscape = function (str) {
var ampregex;
if (this.options.noValidation) {
return str;
}
ampregex = this.options.noDoubleEncoding ? /(?!&\S+;)&/g : /&/g;
return str.replace(ampregex, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;').replace(/\t/g, '&#x9;').replace(/\n/g, '&#xA;').replace(/\r/g, '&#xD;');
};
return XMLStringifier;
}();
}).call(undefined);
},{}],280:[function(require,module,exports){
'use strict';
var _create = require('babel-runtime/core-js/object/create');
var _create2 = _interopRequireDefault(_create);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by CoffeeScript 1.12.7
(function () {
var NodeType,
XMLCharacterData,
XMLText,
extend = function extend(child, parent) {
for (var key in parent) {
if (hasProp.call(parent, key)) child[key] = parent[key];
}function ctor() {
this.constructor = child;
}ctor.prototype = parent.prototype;child.prototype = new ctor();child.__super__ = parent.prototype;return child;
},
hasProp = {}.hasOwnProperty;
NodeType = require('./NodeType');
XMLCharacterData = require('./XMLCharacterData');
module.exports = XMLText = function (superClass) {
extend(XMLText, superClass);
function XMLText(parent, text) {
XMLText.__super__.constructor.call(this, parent);
if (text == null) {
throw new Error("Missing element text. " + this.debugInfo());
}
this.name = "#text";
this.type = NodeType.Text;
this.value = this.stringify.text(text);
}
Object.defineProperty(XMLText.prototype, 'isElementContentWhitespace', {
get: function get() {
throw new Error("This DOM method is not implemented." + this.debugInfo());
}
});
Object.defineProperty(XMLText.prototype, 'wholeText', {
get: function get() {
var next, prev, str;
str = '';
prev = this.previousSibling;
while (prev) {
str = prev.data + str;
prev = prev.previousSibling;
}
str += this.data;
next = this.nextSibling;
while (next) {
str = str + next.data;
next = next.nextSibling;
}
return str;
}
});
XMLText.prototype.clone = function () {
return (0, _create2.default)(this);
};
XMLText.prototype.toString = function (options) {
return this.options.writer.text(this, this.options.writer.filterOptions(options));
};
XMLText.prototype.splitText = function (offset) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
XMLText.prototype.replaceWholeText = function (content) {
throw new Error("This DOM method is not implemented." + this.debugInfo());
};
return XMLText;
}(XMLCharacterData);
}).call(undefined);
},{"./NodeType":251,"./XMLCharacterData":256,"babel-runtime/core-js/object/create":55}],281:[function(require,module,exports){
'use strict';
// Generated by CoffeeScript 1.12.7
(function () {
var NodeType,
WriterState,
XMLCData,
XMLComment,
XMLDTDAttList,
XMLDTDElement,
XMLDTDEntity,
XMLDTDNotation,
XMLDeclaration,
XMLDocType,
XMLDummy,
XMLElement,
XMLProcessingInstruction,
XMLRaw,
XMLText,
XMLWriterBase,
assign,
hasProp = {}.hasOwnProperty;
assign = require('./Utility').assign;
NodeType = require('./NodeType');
XMLDeclaration = require('./XMLDeclaration');
XMLDocType = require('./XMLDocType');
XMLCData = require('./XMLCData');
XMLComment = require('./XMLComment');
XMLElement = require('./XMLElement');
XMLRaw = require('./XMLRaw');
XMLText = require('./XMLText');
XMLProcessingInstruction = require('./XMLProcessingInstruction');
XMLDummy = require('./XMLDummy');
XMLDTDAttList = require('./XMLDTDAttList');
XMLDTDElement = require('./XMLDTDElement');
XMLDTDEntity = require('./XMLDTDEntity');
XMLDTDNotation = require('./XMLDTDNotation');
WriterState = require('./WriterState');
module.exports = XMLWriterBase = function () {
function XMLWriterBase(options) {
var key, ref, value;
options || (options = {});
this.options = options;
ref = options.writer || {};
for (key in ref) {
if (!hasProp.call(ref, key)) continue;
value = ref[key];
this["_" + key] = this[key];
this[key] = value;
}
}
XMLWriterBase.prototype.filterOptions = function (options) {
var filteredOptions, ref, ref1, ref2, ref3, ref4, ref5, ref6;
options || (options = {});
options = assign({}, this.options, options);
filteredOptions = {
writer: this
};
filteredOptions.pretty = options.pretty || false;
filteredOptions.allowEmpty = options.allowEmpty || false;
filteredOptions.indent = (ref = options.indent) != null ? ref : ' ';
filteredOptions.newline = (ref1 = options.newline) != null ? ref1 : '\n';
filteredOptions.offset = (ref2 = options.offset) != null ? ref2 : 0;
filteredOptions.dontPrettyTextNodes = (ref3 = (ref4 = options.dontPrettyTextNodes) != null ? ref4 : options.dontprettytextnodes) != null ? ref3 : 0;
filteredOptions.spaceBeforeSlash = (ref5 = (ref6 = options.spaceBeforeSlash) != null ? ref6 : options.spacebeforeslash) != null ? ref5 : '';
if (filteredOptions.spaceBeforeSlash === true) {
filteredOptions.spaceBeforeSlash = ' ';
}
filteredOptions.suppressPrettyCount = 0;
filteredOptions.user = {};
filteredOptions.state = WriterState.None;
return filteredOptions;
};
XMLWriterBase.prototype.indent = function (node, options, level) {
var indentLevel;
if (!options.pretty || options.suppressPrettyCount) {
return '';
} else if (options.pretty) {
indentLevel = (level || 0) + options.offset + 1;
if (indentLevel > 0) {
return new Array(indentLevel).join(options.indent);
}
}
return '';
};
XMLWriterBase.prototype.endline = function (node, options, level) {
if (!options.pretty || options.suppressPrettyCount) {
return '';
} else {
return options.newline;
}
};
XMLWriterBase.prototype.attribute = function (att, options, level) {
var r;
this.openAttribute(att, options, level);
r = ' ' + att.name + '="' + att.value + '"';
this.closeAttribute(att, options, level);
return r;
};
XMLWriterBase.prototype.cdata = function (node, options, level) {
var r;
this.openNode(node, options, level);
options.state = WriterState.OpenTag;
r = this.indent(node, options, level) + '<![CDATA[';
options.state = WriterState.InsideTag;
r += node.value;
options.state = WriterState.CloseTag;
r += ']]>' + this.endline(node, options, level);
options.state = WriterState.None;
this.closeNode(node, options, level);
return r;
};
XMLWriterBase.prototype.comment = function (node, options, level) {
var r;
this.openNode(node, options, level);
options.state = WriterState.OpenTag;
r = this.indent(node, options, level) + '<!-- ';
options.state = WriterState.InsideTag;
r += node.value;
options.state = WriterState.CloseTag;
r += ' -->' + this.endline(node, options, level);
options.state = WriterState.None;
this.closeNode(node, options, level);
return r;
};
XMLWriterBase.prototype.declaration = function (node, options, level) {
var r;
this.openNode(node, options, level);
options.state = WriterState.OpenTag;
r = this.indent(node, options, level) + '<?xml';
options.state = WriterState.InsideTag;
r += ' version="' + node.version + '"';
if (node.encoding != null) {
r += ' encoding="' + node.encoding + '"';
}
if (node.standalone != null) {
r += ' standalone="' + node.standalone + '"';
}
options.state = WriterState.CloseTag;
r += options.spaceBeforeSlash + '?>';
r += this.endline(node, options, level);
options.state = WriterState.None;
this.closeNode(node, options, level);
return r;
};
XMLWriterBase.prototype.docType = function (node, options, level) {
var child, i, len, r, ref;
level || (level = 0);
this.openNode(node, options, level);
options.state = WriterState.OpenTag;
r = this.indent(node, options, level);
r += '<!DOCTYPE ' + node.root().name;
if (node.pubID && node.sysID) {
r += ' PUBLIC "' + node.pubID + '" "' + node.sysID + '"';
} else if (node.sysID) {
r += ' SYSTEM "' + node.sysID + '"';
}
if (node.children.length > 0) {
r += ' [';
r += this.endline(node, options, level);
options.state = WriterState.InsideTag;
ref = node.children;
for (i = 0, len = ref.length; i < len; i++) {
child = ref[i];
r += this.writeChildNode(child, options, level + 1);
}
options.state = WriterState.CloseTag;
r += ']';
}
options.state = WriterState.CloseTag;
r += options.spaceBeforeSlash + '>';
r += this.endline(node, options, level);
options.state = WriterState.None;
this.closeNode(node, options, level);
return r;
};
XMLWriterBase.prototype.element = function (node, options, level) {
var att, child, childNodeCount, firstChildNode, i, j, len, len1, name, prettySuppressed, r, ref, ref1, ref2;
level || (level = 0);
prettySuppressed = false;
r = '';
this.openNode(node, options, level);
options.state = WriterState.OpenTag;
r += this.indent(node, options, level) + '<' + node.name;
ref = node.attribs;
for (name in ref) {
if (!hasProp.call(ref, name)) continue;
att = ref[name];
r += this.attribute(att, options, level);
}
childNodeCount = node.children.length;
firstChildNode = childNodeCount === 0 ? null : node.children[0];
if (childNodeCount === 0 || node.children.every(function (e) {
return (e.type === NodeType.Text || e.type === NodeType.Raw) && e.value === '';
})) {
if (options.allowEmpty) {
r += '>';
options.state = WriterState.CloseTag;
r += '</' + node.name + '>' + this.endline(node, options, level);
} else {
options.state = WriterState.CloseTag;
r += options.spaceBeforeSlash + '/>' + this.endline(node, options, level);
}
} else if (options.pretty && childNodeCount === 1 && (firstChildNode.type === NodeType.Text || firstChildNode.type === NodeType.Raw) && firstChildNode.value != null) {
r += '>';
options.state = WriterState.InsideTag;
options.suppressPrettyCount++;
prettySuppressed = true;
r += this.writeChildNode(firstChildNode, options, level + 1);
options.suppressPrettyCount--;
prettySuppressed = false;
options.state = WriterState.CloseTag;
r += '</' + node.name + '>' + this.endline(node, options, level);
} else {
if (options.dontPrettyTextNodes) {
ref1 = node.children;
for (i = 0, len = ref1.length; i < len; i++) {
child = ref1[i];
if ((child.type === NodeType.Text || child.type === NodeType.Raw) && child.value != null) {
options.suppressPrettyCount++;
prettySuppressed = true;
break;
}
}
}
r += '>' + this.endline(node, options, level);
options.state = WriterState.InsideTag;
ref2 = node.children;
for (j = 0, len1 = ref2.length; j < len1; j++) {
child = ref2[j];
r += this.writeChildNode(child, options, level + 1);
}
options.state = WriterState.CloseTag;
r += this.indent(node, options, level) + '</' + node.name + '>';
if (prettySuppressed) {
options.suppressPrettyCount--;
}
r += this.endline(node, options, level);
options.state = WriterState.None;
}
this.closeNode(node, options, level);
return r;
};
XMLWriterBase.prototype.writeChildNode = function (node, options, level) {
switch (node.type) {
case NodeType.CData:
return this.cdata(node, options, level);
case NodeType.Comment:
return this.comment(node, options, level);
case NodeType.Element:
return this.element(node, options, level);
case NodeType.Raw:
return this.raw(node, options, level);
case NodeType.Text:
return this.text(node, options, level);
case NodeType.ProcessingInstruction:
return this.processingInstruction(node, options, level);
case NodeType.Dummy:
return '';
case NodeType.Declaration:
return this.declaration(node, options, level);
case NodeType.DocType:
return this.docType(node, options, level);
case NodeType.AttributeDeclaration:
return this.dtdAttList(node, options, level);
case NodeType.ElementDeclaration:
return this.dtdElement(node, options, level);
case NodeType.EntityDeclaration:
return this.dtdEntity(node, options, level);
case NodeType.NotationDeclaration:
return this.dtdNotation(node, options, level);
default:
throw new Error("Unknown XML node type: " + node.constructor.name);
}
};
XMLWriterBase.prototype.processingInstruction = function (node, options, level) {
var r;
this.openNode(node, options, level);
options.state = WriterState.OpenTag;
r = this.indent(node, options, level) + '<?';
options.state = WriterState.InsideTag;
r += node.target;
if (node.value) {
r += ' ' + node.value;
}
options.state = WriterState.CloseTag;
r += options.spaceBeforeSlash + '?>';
r += this.endline(node, options, level);
options.state = WriterState.None;
this.closeNode(node, options, level);
return r;
};
XMLWriterBase.prototype.raw = function (node, options, level) {
var r;
this.openNode(node, options, level);
options.state = WriterState.OpenTag;
r = this.indent(node, options, level);
options.state = WriterState.InsideTag;
r += node.value;
options.state = WriterState.CloseTag;
r += this.endline(node, options, level);
options.state = WriterState.None;
this.closeNode(node, options, level);
return r;
};
XMLWriterBase.prototype.text = function (node, options, level) {
var r;
this.openNode(node, options, level);
options.state = WriterState.OpenTag;
r = this.indent(node, options, level);
options.state = WriterState.InsideTag;
r += node.value;
options.state = WriterState.CloseTag;
r += this.endline(node, options, level);
options.state = WriterState.None;
this.closeNode(node, options, level);
return r;
};
XMLWriterBase.prototype.dtdAttList = function (node, options, level) {
var r;
this.openNode(node, options, level);
options.state = WriterState.OpenTag;
r = this.indent(node, options, level) + '<!ATTLIST';
options.state = WriterState.InsideTag;
r += ' ' + node.elementName + ' ' + node.attributeName + ' ' + node.attributeType;
if (node.defaultValueType !== '#DEFAULT') {
r += ' ' + node.defaultValueType;
}
if (node.defaultValue) {
r += ' "' + node.defaultValue + '"';
}
options.state = WriterState.CloseTag;
r += options.spaceBeforeSlash + '>' + this.endline(node, options, level);
options.state = WriterState.None;
this.closeNode(node, options, level);
return r;
};
XMLWriterBase.prototype.dtdElement = function (node, options, level) {
var r;
this.openNode(node, options, level);
options.state = WriterState.OpenTag;
r = this.indent(node, options, level) + '<!ELEMENT';
options.state = WriterState.InsideTag;
r += ' ' + node.name + ' ' + node.value;
options.state = WriterState.CloseTag;
r += options.spaceBeforeSlash + '>' + this.endline(node, options, level);
options.state = WriterState.None;
this.closeNode(node, options, level);
return r;
};
XMLWriterBase.prototype.dtdEntity = function (node, options, level) {
var r;
this.openNode(node, options, level);
options.state = WriterState.OpenTag;
r = this.indent(node, options, level) + '<!ENTITY';
options.state = WriterState.InsideTag;
if (node.pe) {
r += ' %';
}
r += ' ' + node.name;
if (node.value) {
r += ' "' + node.value + '"';
} else {
if (node.pubID && node.sysID) {
r += ' PUBLIC "' + node.pubID + '" "' + node.sysID + '"';
} else if (node.sysID) {
r += ' SYSTEM "' + node.sysID + '"';
}
if (node.nData) {
r += ' NDATA ' + node.nData;
}
}
options.state = WriterState.CloseTag;
r += options.spaceBeforeSlash + '>' + this.endline(node, options, level);
options.state = WriterState.None;
this.closeNode(node, options, level);
return r;
};
XMLWriterBase.prototype.dtdNotation = function (node, options, level) {
var r;
this.openNode(node, options, level);
options.state = WriterState.OpenTag;
r = this.indent(node, options, level) + '<!NOTATION';
options.state = WriterState.InsideTag;
r += ' ' + node.name;
if (node.pubID && node.sysID) {
r += ' PUBLIC "' + node.pubID + '" "' + node.sysID + '"';
} else if (node.pubID) {
r += ' PUBLIC "' + node.pubID + '"';
} else if (node.sysID) {
r += ' SYSTEM "' + node.sysID + '"';
}
options.state = WriterState.CloseTag;
r += options.spaceBeforeSlash + '>' + this.endline(node, options, level);
options.state = WriterState.None;
this.closeNode(node, options, level);
return r;
};
XMLWriterBase.prototype.openNode = function (node, options, level) {};
XMLWriterBase.prototype.closeNode = function (node, options, level) {};
XMLWriterBase.prototype.openAttribute = function (att, options, level) {};
XMLWriterBase.prototype.closeAttribute = function (att, options, level) {};
return XMLWriterBase;
}();
}).call(undefined);
},{"./NodeType":251,"./Utility":252,"./WriterState":253,"./XMLCData":255,"./XMLComment":257,"./XMLDTDAttList":262,"./XMLDTDElement":263,"./XMLDTDEntity":264,"./XMLDTDNotation":265,"./XMLDeclaration":266,"./XMLDocType":267,"./XMLDummy":270,"./XMLElement":271,"./XMLProcessingInstruction":275,"./XMLRaw":276,"./XMLText":280}],282:[function(require,module,exports){
'use strict';
// Generated by CoffeeScript 1.12.7
(function () {
var NodeType, WriterState, XMLDOMImplementation, XMLDocument, XMLDocumentCB, XMLStreamWriter, XMLStringWriter, assign, isFunction, ref;
ref = require('./Utility'), assign = ref.assign, isFunction = ref.isFunction;
XMLDOMImplementation = require('./XMLDOMImplementation');
XMLDocument = require('./XMLDocument');
XMLDocumentCB = require('./XMLDocumentCB');
XMLStringWriter = require('./XMLStringWriter');
XMLStreamWriter = require('./XMLStreamWriter');
NodeType = require('./NodeType');
WriterState = require('./WriterState');
module.exports.create = function (name, xmldec, doctype, options) {
var doc, root;
if (name == null) {
throw new Error("Root element needs a name.");
}
options = assign({}, xmldec, doctype, options);
doc = new XMLDocument(options);
root = doc.element(name);
if (!options.headless) {
doc.declaration(options);
if (options.pubID != null || options.sysID != null) {
doc.dtd(options);
}
}
return root;
};
module.exports.begin = function (options, onData, onEnd) {
var ref1;
if (isFunction(options)) {
ref1 = [options, onData], onData = ref1[0], onEnd = ref1[1];
options = {};
}
if (onData) {
return new XMLDocumentCB(options, onData, onEnd);
} else {
return new XMLDocument(options);
}
};
module.exports.stringWriter = function (options) {
return new XMLStringWriter(options);
};
module.exports.streamWriter = function (stream, options) {
return new XMLStreamWriter(stream, options);
};
module.exports.implementation = new XMLDOMImplementation();
module.exports.nodeType = NodeType;
module.exports.writerState = WriterState;
}).call(undefined);
},{"./NodeType":251,"./Utility":252,"./WriterState":253,"./XMLDOMImplementation":260,"./XMLDocument":268,"./XMLDocumentCB":269,"./XMLStreamWriter":277,"./XMLStringWriter":278}],283:[function(require,module,exports){
module.exports = extend
var hasOwnProperty = Object.prototype.hasOwnProperty;
function extend() {
var target = {}
for (var i = 0; i < arguments.length; i++) {
var source = arguments[i]
for (var key in source) {
if (hasOwnProperty.call(source, key)) {
target[key] = source[key]
}
}
}
return target
}
},{}],284:[function(require,module,exports){
'use strict';
var Buffer = require('buffer').Buffer;
var sha = require('./sha');
var md5 = require('./md5');
var algorithms = {
sha1: sha,
md5: md5
};
var blocksize = 64;
var zeroBuffer = Buffer.alloc(blocksize);
zeroBuffer.fill(0);
function hmac(fn, key, data) {
if (!Buffer.isBuffer(key)) key = Buffer.from(key);
if (!Buffer.isBuffer(data)) data = Buffer.from(data);
if (key.length > blocksize) {
key = fn(key);
} else if (key.length < blocksize) {
key = Buffer.concat([key, zeroBuffer], blocksize);
}
var ipad = Buffer.alloc(blocksize),
opad = Buffer.alloc(blocksize);
for (var i = 0; i < blocksize; i++) {
ipad[i] = key[i] ^ 0x36;
opad[i] = key[i] ^ 0x5C;
}
var hash = fn(Buffer.concat([ipad, data]));
return fn(Buffer.concat([opad, hash]));
}
function hash(alg, key) {
alg = alg || 'sha1';
var fn = algorithms[alg];
var bufs = [];
var length = 0;
if (!fn) error('algorithm:', alg, 'is not yet supported');
return {
update: function update(data) {
if (!Buffer.isBuffer(data)) data = Buffer.from(data);
bufs.push(data);
length += data.length;
return this;
},
digest: function digest(enc) {
var buf = Buffer.concat(bufs);
var r = key ? hmac(fn, key, buf) : fn(buf);
bufs = null;
return enc ? r.toString(enc) : r;
}
};
}
function error() {
var m = [].slice.call(arguments).join(' ');
throw new Error([m, 'we accept pull requests', 'http://github.com/dominictarr/crypto-browserify'].join('\n'));
}
exports.createHash = function (alg) {
return hash(alg);
};
exports.createHmac = function (alg, key) {
return hash(alg, key);
};
exports.createCredentials = function () {
error('sorry,createCredentials is not implemented yet');
};
exports.createCipher = function () {
error('sorry,createCipher is not implemented yet');
};
exports.createCipheriv = function () {
error('sorry,createCipheriv is not implemented yet');
};
exports.createDecipher = function () {
error('sorry,createDecipher is not implemented yet');
};
exports.createDecipheriv = function () {
error('sorry,createDecipheriv is not implemented yet');
};
exports.createSign = function () {
error('sorry,createSign is not implemented yet');
};
exports.createVerify = function () {
error('sorry,createVerify is not implemented yet');
};
exports.createDiffieHellman = function () {
error('sorry,createDiffieHellman is not implemented yet');
};
exports.pbkdf2 = function () {
error('sorry,pbkdf2 is not implemented yet');
};
},{"./md5":286,"./sha":287,"buffer":73}],285:[function(require,module,exports){
'use strict';
var Buffer = require('buffer').Buffer;
var intSize = 4;
var zeroBuffer = Buffer.alloc(intSize);zeroBuffer.fill(0);
var chrsz = 8;
function toArray(buf, bigEndian) {
if (buf.length % intSize !== 0) {
var len = buf.length + (intSize - buf.length % intSize);
buf = Buffer.concat([buf, zeroBuffer], len);
}
var arr = [];
var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE;
for (var i = 0; i < buf.length; i += intSize) {
arr.push(fn.call(buf, i));
}
return arr;
}
function toBuffer(arr, size, bigEndian) {
var buf = Buffer.alloc(size);
var fn = bigEndian ? buf.writeInt32BE : buf.writeInt32LE;
for (var i = 0; i < arr.length; i++) {
fn.call(buf, arr[i], i * 4, true);
}
return buf;
}
function hash(buf, fn, hashSize, bigEndian) {
if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf);
var arr = fn(toArray(buf, bigEndian), buf.length * chrsz);
return toBuffer(arr, hashSize, bigEndian);
}
module.exports = { hash: hash };
},{"buffer":73}],286:[function(require,module,exports){
"use strict";
/*
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
var helpers = require('./helpers');
/*
* Perform a simple self-test to see if the VM is working
*/
function md5_vm_test() {
return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}
/*
* Calculate the MD5 of an array of little-endian words, and a bit length
*/
function core_md5(x, len) {
/* append padding */
x[len >> 5] |= 0x80 << len % 32;
x[(len + 64 >>> 9 << 4) + 14] = len;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for (var i = 0; i < x.length; i += 16) {
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936);
d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586);
c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819);
b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);
a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897);
d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);
c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);
b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983);
a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);
d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);
c = md5_ff(c, d, a, b, x[i + 10], 17, -42063);
b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);
a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);
d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101);
c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);
b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);
a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510);
d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);
c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713);
b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302);
a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691);
d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083);
c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335);
b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848);
a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438);
d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);
c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961);
b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);
a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);
d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784);
c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);
b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);
a = md5_hh(a, b, c, d, x[i + 5], 4, -378558);
d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);
c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);
b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556);
a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);
d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);
c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632);
b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);
a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174);
d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222);
c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979);
b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189);
a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487);
d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835);
c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520);
b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651);
a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844);
d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);
c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);
b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055);
a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);
d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);
c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523);
b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);
a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);
d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744);
c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);
b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);
a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070);
d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);
c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259);
b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551);
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
return Array(a, b, c, d);
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
function md5_cmn(q, a, b, x, s, t) {
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b);
}
function md5_ff(a, b, c, d, x, s, t) {
return md5_cmn(b & c | ~b & d, a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t) {
return md5_cmn(b & d | c & ~d, a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t) {
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t) {
return md5_cmn(c ^ (b | ~d), a, b, x, s, t);
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return msw << 16 | lsw & 0xFFFF;
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function bit_rol(num, cnt) {
return num << cnt | num >>> 32 - cnt;
}
module.exports = function md5(buf) {
return helpers.hash(buf, core_md5, 16);
};
},{"./helpers":285}],287:[function(require,module,exports){
'use strict';
/*
* A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
* in FIPS PUB 180-1
* Version 2.1a Copyright Paul Johnston 2000 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for details.
*/
var helpers = require('./helpers');
/*
* Calculate the SHA-1 of an array of big-endian words, and a bit length
*/
function core_sha1(x, len) {
/* append padding */
x[len >> 5] |= 0x80 << 24 - len % 32;
x[(len + 64 >> 9 << 4) + 15] = len;
var w = Array(80);
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
var e = -1009589776;
for (var i = 0; i < x.length; i += 16) {
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
var olde = e;
for (var j = 0; j < 80; j++) {
if (j < 16) w[j] = x[i + j];else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j)));
e = d;
d = c;
c = rol(b, 30);
b = a;
a = t;
}
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
e = safe_add(e, olde);
}
return Array(a, b, c, d, e);
}
/*
* Perform the appropriate triplet combination function for the current
* iteration
*/
function sha1_ft(t, b, c, d) {
if (t < 20) return b & c | ~b & d;
if (t < 40) return b ^ c ^ d;
if (t < 60) return b & c | b & d | c & d;
return b ^ c ^ d;
}
/*
* Determine the appropriate additive constant for the current iteration
*/
function sha1_kt(t) {
return t < 20 ? 1518500249 : t < 40 ? 1859775393 : t < 60 ? -1894007588 : -899497514;
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return msw << 16 | lsw & 0xFFFF;
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function rol(num, cnt) {
return num << cnt | num >>> 32 - cnt;
}
module.exports = function sha1(buf) {
return helpers.hash(buf, core_sha1, 20, true);
};
},{"./helpers":285}],288:[function(require,module,exports){
"use strict";
module.exports = function () {
return function () {};
};
},{}],289:[function(require,module,exports){
(function (Buffer){
'use strict';
var _typeof2 = require('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _require = require('stream'),
Stream = _require.Stream;
var _require2 = require('../lib/common/utils/isArray'),
isArray = _require2.isArray;
module.exports.string = function isString(obj) {
return typeof obj === 'string';
};
module.exports.array = isArray;
module.exports.buffer = Buffer.isBuffer;
function isStream(obj) {
return obj instanceof Stream;
}
module.exports.writableStream = function isWritableStream(obj) {
return isStream(obj) && typeof obj._write === 'function' && (0, _typeof3.default)(obj._writableState) === 'object';
};
}).call(this,{"isBuffer":require("../node_modules/is-buffer/index.js")})
},{"../lib/common/utils/isArray":42,"../node_modules/is-buffer/index.js":197,"babel-runtime/helpers/typeof":67,"stream":230}],290:[function(require,module,exports){
'use strict';
// copy from https://github.com/node-modules/utility for browser
exports.encodeURIComponent = function (text) {
try {
return encodeURIComponent(text);
} catch (e) {
return text;
}
};
exports.escape = require('escape-html');
exports.timestamp = function timestamp(t) {
if (t) {
var v = t;
if (typeof v === 'string') {
v = Number(v);
}
if (String(t).length === 10) {
v *= 1000;
}
return new Date(v);
}
return Math.round(Date.now() / 1000);
};
},{"escape-html":191}],291:[function(require,module,exports){
(function (process,Buffer){
'use strict';
var _stringify = require('babel-runtime/core-js/json/stringify');
var _stringify2 = _interopRequireDefault(_stringify);
var _typeof2 = require('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var util = require('util');
var urlutil = require('url');
var http = require('http');
var https = require('https');
var debug = require('debug')('urllib');
var ms = require('humanize-ms');
var _Promise;
var REQUEST_ID = 0;
var MAX_VALUE = Math.pow(2, 31) - 10;
var PROTO_RE = /^https?:\/\//i;
function getAgent(agent, defaultAgent) {
return agent === undefined ? defaultAgent : agent;
}
function makeCallback(resolve, reject) {
return function (err, data, res) {
if (err) {
return reject(err);
}
resolve({
data: data,
status: res.statusCode,
headers: res.headers,
res: res
});
};
}
// exports.TIMEOUT = ms('5s');
exports.TIMEOUTS = [ms('300s'), ms('300s')];
var TEXT_DATA_TYPES = ['json', 'text'];
exports.request = function request(url, args, callback) {
// request(url, callback)
if (arguments.length === 2 && typeof args === 'function') {
callback = args;
args = null;
}
if (typeof callback === 'function') {
return exports.requestWithCallback(url, args, callback);
}
// Promise
if (!_Promise) {
_Promise = require('any-promise');
}
return new _Promise(function (resolve, reject) {
exports.requestWithCallback(url, args, makeCallback(resolve, reject));
});
};
exports.requestWithCallback = function requestWithCallback(url, args, callback) {
// requestWithCallback(url, callback)
if (!url || typeof url !== 'string' && (typeof url === 'undefined' ? 'undefined' : (0, _typeof3.default)(url)) !== 'object') {
var msg = util.format('expect request url to be a string or a http request options, but got %j', url);
throw new Error(msg);
}
if (arguments.length === 2 && typeof args === 'function') {
callback = args;
args = null;
}
args = args || {};
if (REQUEST_ID >= MAX_VALUE) {
REQUEST_ID = 0;
}
var reqId = ++REQUEST_ID;
args.requestUrls = args.requestUrls || [];
var reqMeta = {
requestId: reqId,
url: url,
args: args,
ctx: args.ctx
};
if (args.emitter) {
args.emitter.emit('request', reqMeta);
}
args.timeout = args.timeout || exports.TIMEOUTS;
args.maxRedirects = args.maxRedirects || 10;
args.streaming = args.streaming || args.customResponse;
var requestStartTime = Date.now();
var parsedUrl;
if (typeof url === 'string') {
if (!PROTO_RE.test(url)) {
// Support `request('www.server.com')`
url = 'http://' + url;
}
parsedUrl = urlutil.parse(url);
} else {
parsedUrl = url;
}
var method = (args.type || args.method || parsedUrl.method || 'GET').toUpperCase();
var port = parsedUrl.port || 80;
var httplib = http;
var agent = getAgent(args.agent, exports.agent);
var fixJSONCtlChars = args.fixJSONCtlChars;
if (parsedUrl.protocol === 'https:') {
httplib = https;
agent = getAgent(args.httpsAgent, exports.httpsAgent);
if (!parsedUrl.port) {
port = 443;
}
}
// request through proxy tunnel
// var proxyTunnelAgent = detectProxyAgent(parsedUrl, args);
// if (proxyTunnelAgent) {
// agent = proxyTunnelAgent;
// }
var options = {
host: parsedUrl.hostname || parsedUrl.host || 'localhost',
path: parsedUrl.path || '/',
method: method,
port: port,
agent: agent,
headers: args.headers || {},
// default is dns.lookup
// https://github.com/nodejs/node/blob/master/lib/net.js#L986
// custom dnslookup require node >= 4.0.0
// https://github.com/nodejs/node/blob/archived-io.js-v0.12/lib/net.js#L952
lookup: args.lookup
};
if (Array.isArray(args.timeout)) {
options.requestTimeout = args.timeout[args.timeout.length - 1];
} else if (typeof args.timeout !== 'undefined') {
options.requestTimeout = args.timeout;
}
var sslNames = ['pfx', 'key', 'passphrase', 'cert', 'ca', 'ciphers', 'rejectUnauthorized', 'secureProtocol', 'secureOptions'];
for (var i = 0; i < sslNames.length; i++) {
var name = sslNames[i];
if (args.hasOwnProperty(name)) {
options[name] = args[name];
}
}
// don't check ssl
if (options.rejectUnauthorized === false && !options.hasOwnProperty('secureOptions')) {
options.secureOptions = require('constants').SSL_OP_NO_TLSv1_2;
}
var auth = args.auth || parsedUrl.auth;
if (auth) {
options.auth = auth;
}
var body = args.content || args.data;
var dataAsQueryString = method === 'GET' || method === 'HEAD' || args.dataAsQueryString;
if (!args.content) {
if (body && !(typeof body === 'string' || Buffer.isBuffer(body))) {
if (dataAsQueryString) {
// read: GET, HEAD, use query string
body = args.nestedQuerystring ? qs.stringify(body) : querystring.stringify(body);
} else {
var contentType = options.headers['Content-Type'] || options.headers['content-type'];
// auto add application/x-www-form-urlencoded when using urlencode form request
if (!contentType) {
if (args.contentType === 'json') {
contentType = 'application/json';
} else {
contentType = 'application/x-www-form-urlencoded';
}
options.headers['Content-Type'] = contentType;
}
if (parseContentType(contentType).type === 'application/json') {
body = (0, _stringify2.default)(body);
} else {
// 'application/x-www-form-urlencoded'
body = args.nestedQuerystring ? qs.stringify(body) : querystring.stringify(body);
}
}
}
}
// if it's a GET or HEAD request, data should be sent as query string
if (dataAsQueryString && body) {
options.path += (parsedUrl.query ? '&' : '?') + body;
body = null;
}
var requestSize = 0;
if (body) {
var length = body.length;
if (!Buffer.isBuffer(body)) {
length = Buffer.byteLength(body);
}
requestSize = options.headers['Content-Length'] = length;
}
if (args.dataType === 'json') {
options.headers.Accept = 'application/json';
}
if (typeof args.beforeRequest === 'function') {
// you can use this hook to change every thing.
args.beforeRequest(options);
}
var connectTimer = null;
var responseTimer = null;
var __err = null;
var connected = false; // socket connected or not
var keepAliveSocket = false; // request with keepalive socket
var responseSize = 0;
var statusCode = -1;
var responseAborted = false;
var remoteAddress = '';
var remotePort = '';
var timing = null;
if (args.timing) {
timing = {
// socket assigned
queuing: 0,
// dns lookup time
dnslookup: 0,
// socket connected
connected: 0,
// request sent
requestSent: 0,
// Time to first byte (TTFB)
waiting: 0,
contentDownload: 0
};
}
function cancelConnectTimer() {
if (connectTimer) {
clearTimeout(connectTimer);
connectTimer = null;
}
}
function cancelResponseTimer() {
if (responseTimer) {
clearTimeout(responseTimer);
responseTimer = null;
}
}
function done(err, data, res) {
cancelResponseTimer();
if (!callback) {
console.warn('[urllib:warn] [%s] [%s] [worker:%s] %s %s callback twice!!!', Date(), reqId, process.pid, options.method, url);
// https://github.com/node-modules/urllib/pull/30
if (err) {
console.warn('[urllib:warn] [%s] [%s] [worker:%s] %s: %s\nstack: %s', Date(), reqId, process.pid, err.name, err.message, err.stack);
}
return;
}
var cb = callback;
callback = null;
var headers = {};
if (res) {
statusCode = res.statusCode;
headers = res.headers;
}
// handle digest auth
if (statusCode === 401 && headers['www-authenticate'] && (!args.headers || !args.headers.Authorization) && args.digestAuth) {
var authenticate = headers['www-authenticate'];
if (authenticate.indexOf('Digest ') >= 0) {
debug('Request#%d %s: got digest auth header WWW-Authenticate: %s', reqId, url, authenticate);
args.headers = args.headers || {};
args.headers.Authorization = digestAuthHeader(options.method, options.path, authenticate, args.digestAuth);
debug('Request#%d %s: auth with digest header: %s', reqId, url, args.headers.Authorization);
if (res.headers['set-cookie']) {
args.headers.Cookie = res.headers['set-cookie'].join(';');
}
return exports.requestWithCallback(url, args, cb);
}
}
var requestUseTime = Date.now() - requestStartTime;
if (timing) {
timing.contentDownload = requestUseTime;
}
debug('[%sms] done, %s bytes HTTP %s %s %s %s, keepAliveSocket: %s, timing: %j', requestUseTime, responseSize, statusCode, options.method, options.host, options.path, keepAliveSocket, timing);
var response = {
status: statusCode,
statusCode: statusCode,
headers: headers,
size: responseSize,
aborted: responseAborted,
rt: requestUseTime,
keepAliveSocket: keepAliveSocket,
data: data,
requestUrls: args.requestUrls,
timing: timing,
remoteAddress: remoteAddress,
remotePort: remotePort
};
if (err) {
var agentStatus = '';
if (agent && typeof agent.getCurrentStatus === 'function') {
// add current agent status to error message for logging and debug
agentStatus = ', agent status: ' + (0, _stringify2.default)(agent.getCurrentStatus());
}
err.message += ', ' + options.method + ' ' + url + ' ' + statusCode + ' (connected: ' + connected + ', keepalive socket: ' + keepAliveSocket + agentStatus + ')' + '\nheaders: ' + (0, _stringify2.default)(headers);
err.data = data;
err.path = options.path;
err.status = statusCode;
err.headers = headers;
err.res = response;
}
cb(err, data, args.streaming ? res : response);
if (args.emitter) {
// keep to use the same reqMeta object on request event before
reqMeta.url = url;
reqMeta.socket = req && req.connection;
reqMeta.options = options;
reqMeta.size = requestSize;
args.emitter.emit('response', {
requestId: reqId,
error: err,
ctx: args.ctx,
req: reqMeta,
res: response
});
}
}
function handleRedirect(res) {
var err = null;
if (args.followRedirect && statuses.redirect[res.statusCode]) {
// handle redirect
args._followRedirectCount = (args._followRedirectCount || 0) + 1;
var location = res.headers.location;
if (!location) {
err = new Error('Got statusCode ' + res.statusCode + ' but cannot resolve next location from headers');
err.name = 'FollowRedirectError';
} else if (args._followRedirectCount > args.maxRedirects) {
err = new Error('Exceeded maxRedirects. Probably stuck in a redirect loop ' + url);
err.name = 'MaxRedirectError';
} else {
var newUrl = args.formatRedirectUrl ? args.formatRedirectUrl(url, location) : urlutil.resolve(url, location);
debug('Request#%d %s: `redirected` from %s to %s', reqId, options.path, url, newUrl);
// make sure timer stop
cancelResponseTimer();
// should clean up headers.Host on `location: http://other-domain/url`
if (args.headers && args.headers.Host && PROTO_RE.test(location)) {
args.headers.Host = null;
}
// avoid done will be execute in the future change.
var cb = callback;
callback = null;
exports.requestWithCallback(newUrl, args, cb);
return {
redirect: true,
error: null
};
}
}
return {
redirect: false,
error: err
};
}
// set user-agent
if (!options.headers['User-Agent'] && !options.headers['user-agent']) {
options.headers['User-Agent'] = navigator.userAgent;
}
if (args.gzip) {
if (!options.headers['Accept-Encoding'] && !options.headers['accept-encoding']) {
options.headers['Accept-Encoding'] = 'gzip';
}
}
function decodeContent(res, body, cb) {
var encoding = res.headers['content-encoding'];
// if (body.length === 0) {
// return cb(null, body, encoding);
// }
// if (!encoding || encoding.toLowerCase() !== 'gzip') {
return cb(null, body, encoding);
// }
// debug('gunzip %d length body', body.length);
// zlib.gunzip(body, cb);
}
var writeStream = args.writeStream;
debug('Request#%d %s %s with headers %j, options.path: %s', reqId, method, url, options.headers, options.path);
args.requestUrls.push(url);
function onResponse(res) {
if (timing) {
timing.waiting = Date.now() - requestStartTime;
}
debug('Request#%d %s `req response` event emit: status %d, headers: %j', reqId, url, res.statusCode, res.headers);
if (args.streaming) {
var result = handleRedirect(res);
if (result.redirect) {
res.resume();
return;
}
if (result.error) {
res.resume();
return done(result.error, null, res);
}
return done(null, null, res);
}
res.on('close', function () {
debug('Request#%d %s: `res close` event emit, total size %d', reqId, url, responseSize);
});
res.on('error', function () {
debug('Request#%d %s: `res error` event emit, total size %d', reqId, url, responseSize);
});
res.on('aborted', function () {
responseAborted = true;
debug('Request#%d %s: `res aborted` event emit, total size %d', reqId, url, responseSize);
});
if (writeStream) {
// If there's a writable stream to recieve the response data, just pipe the
// response stream to that writable stream and call the callback when it has
// finished writing.
//
// NOTE that when the response stream `res` emits an 'end' event it just
// means that it has finished piping data to another stream. In the
// meanwhile that writable stream may still writing data to the disk until
// it emits a 'close' event.
//
// That means that we should not apply callback until the 'close' of the
// writable stream is emited.
//
// See also:
// - https://github.com/TBEDP/urllib/commit/959ac3365821e0e028c231a5e8efca6af410eabb
// - http://nodejs.org/api/stream.html#stream_event_end
// - http://nodejs.org/api/stream.html#stream_event_close_1
var result = handleRedirect(res);
if (result.redirect) {
res.resume();
return;
}
if (result.error) {
res.resume();
// end ths stream first
writeStream.end();
return done(result.error, null, res);
}
// you can set consumeWriteStream false that only wait response end
if (args.consumeWriteStream === false) {
res.on('end', done.bind(null, null, null, res));
} else {
// node 0.10, 0.12: only emit res aborted, writeStream close not fired
if (isNode010 || isNode012) {
first([[writeStream, 'close'], [res, 'aborted']], function (_, stream, event) {
debug('Request#%d %s: writeStream or res %s event emitted', reqId, url, event);
done(__err || null, null, res);
});
} else {
writeStream.on('close', function () {
debug('Request#%d %s: writeStream close event emitted', reqId, url);
done(__err || null, null, res);
});
}
}
return res.pipe(writeStream);
}
// Otherwise, just concat those buffers.
//
// NOTE that the `chunk` is not a String but a Buffer. It means that if
// you simply concat two chunk with `+` you're actually converting both
// Buffers into Strings before concating them. It'll cause problems when
// dealing with multi-byte characters.
//
// The solution is to store each chunk in an array and concat them with
// 'buffer-concat' when all chunks is recieved.
//
// See also:
// http://cnodejs.org/topic/4faf65852e8fb5bc65113403
var chunks = [];
res.on('data', function (chunk) {
debug('Request#%d %s: `res data` event emit, size %d', reqId, url, chunk.length);
responseSize += chunk.length;
chunks.push(chunk);
});
res.on('end', function () {
var body = Buffer.concat(chunks, responseSize);
debug('Request#%d %s: `res end` event emit, total size %d, _dumped: %s', reqId, url, responseSize, res._dumped);
if (__err) {
// req.abort() after `res data` event emit.
return done(__err, body, res);
}
var result = handleRedirect(res);
if (result.error) {
return done(result.error, body, res);
}
if (result.redirect) {
return;
}
decodeContent(res, body, function (err, data, encoding) {
if (err) {
return done(err, body, res);
}
// if body not decode, dont touch it
if (!encoding && TEXT_DATA_TYPES.indexOf(args.dataType) >= 0) {
// try to decode charset
try {
data = decodeBodyByCharset(data, res);
} catch (e) {
debug('decodeBodyByCharset error: %s', e);
// if error, dont touch it
return done(null, data, res);
}
if (args.dataType === 'json') {
if (responseSize === 0) {
data = null;
} else {
var r = parseJSON(data, fixJSONCtlChars);
if (r.error) {
err = r.error;
} else {
data = r.data;
}
}
}
}
if (responseAborted) {
// err = new Error('Remote socket was terminated before `response.end()` was called');
// err.name = 'RemoteSocketClosedError';
debug('Request#%d %s: Remote socket was terminated before `response.end()` was called', reqId, url);
}
done(err, data, res);
});
});
}
var connectTimeout, responseTimeout;
if (Array.isArray(args.timeout)) {
connectTimeout = ms(args.timeout[0]);
responseTimeout = ms(args.timeout[1]);
} else {
// set both timeout equal
connectTimeout = responseTimeout = ms(args.timeout);
}
debug('ConnectTimeout: %d, ResponseTimeout: %d', connectTimeout, responseTimeout);
function startConnectTimer() {
debug('Connect timer ticking, timeout: %d', connectTimeout);
connectTimer = setTimeout(function () {
connectTimer = null;
if (statusCode === -1) {
statusCode = -2;
}
var msg = 'Connect timeout for ' + connectTimeout + 'ms';
var errorName = 'ConnectionTimeoutError';
if (!req.socket) {
errorName = 'SocketAssignTimeoutError';
msg += ', working sockets is full';
}
__err = new Error(msg);
__err.name = errorName;
__err.requestId = reqId;
debug('ConnectTimeout: Request#%d %s %s: %s, connected: %s', reqId, url, __err.name, msg, connected);
abortRequest();
}, connectTimeout);
}
function startResposneTimer() {
debug('Response timer ticking, timeout: %d', responseTimeout);
responseTimer = setTimeout(function () {
responseTimer = null;
var msg = 'Response timeout for ' + responseTimeout + 'ms';
var errorName = 'ResponseTimeoutError';
__err = new Error(msg);
__err.name = errorName;
__err.requestId = reqId;
debug('ResponseTimeout: Request#%d %s %s: %s, connected: %s', reqId, url, __err.name, msg, connected);
abortRequest();
}, responseTimeout);
}
var req;
// request headers checker will throw error
options.mode = args.mode ? args.mode : '';
try {
req = httplib.request(options, onResponse);
} catch (err) {
return done(err);
}
// environment detection: browser or nodejs
if (typeof window === 'undefined') {
// start connect timer just after `request` return, and just in nodejs environment
startConnectTimer();
} else {
req.on('requestTimeout', function () {
if (statusCode === -1) {
statusCode = -2;
}
var msg = 'Connect timeout for ' + connectTimeout + 'ms';
var errorName = 'ConnectionTimeoutError';
__err = new Error(msg);
__err.name = errorName;
__err.requestId = reqId;
abortRequest();
});
}
function abortRequest() {
debug('Request#%d %s abort, connected: %s', reqId, url, connected);
// it wont case error event when req haven't been assigned a socket yet.
if (!req.socket) {
__err.noSocket = true;
done(__err);
}
req.abort();
}
if (timing) {
// request sent
req.on('finish', function () {
timing.requestSent = Date.now() - requestStartTime;
});
}
req.once('socket', function (socket) {
if (timing) {
// socket queuing time
timing.queuing = Date.now() - requestStartTime;
}
// https://github.com/nodejs/node/blob/master/lib/net.js#L377
// https://github.com/nodejs/node/blob/v0.10.40-release/lib/net.js#L352
// should use socket.socket on 0.10.x
if (isNode010 && socket.socket) {
socket = socket.socket;
}
var readyState = socket.readyState;
if (readyState === 'opening') {
socket.once('lookup', function (err, ip, addressType) {
debug('Request#%d %s lookup: %s, %s, %s', reqId, url, err, ip, addressType);
if (timing) {
timing.dnslookup = Date.now() - requestStartTime;
}
if (ip) {
remoteAddress = ip;
}
});
socket.once('connect', function () {
if (timing) {
// socket connected
timing.connected = Date.now() - requestStartTime;
}
// cancel socket timer at first and start tick for TTFB
cancelConnectTimer();
startResposneTimer();
debug('Request#%d %s new socket connected', reqId, url);
connected = true;
if (!remoteAddress) {
remoteAddress = socket.remoteAddress;
}
remotePort = socket.remotePort;
});
return;
}
debug('Request#%d %s reuse socket connected, readyState: %s', reqId, url, readyState);
connected = true;
keepAliveSocket = true;
if (!remoteAddress) {
remoteAddress = socket.remoteAddress;
}
remotePort = socket.remotePort;
// reuse socket, timer should be canceled.
cancelConnectTimer();
startResposneTimer();
});
req.on('error', function (err) {
//TypeError for browser fetch api, Error for browser xmlhttprequest api
if (err.name === 'Error' || err.name === 'TypeError') {
err.name = connected ? 'ResponseError' : 'RequestError';
}
err.message += ' (req "error")';
debug('Request#%d %s `req error` event emit, %s: %s', reqId, url, err.name, err.message);
done(__err || err);
});
if (writeStream) {
writeStream.once('error', function (err) {
err.message += ' (writeStream "error")';
__err = err;
debug('Request#%d %s `writeStream error` event emit, %s: %s', reqId, url, err.name, err.message);
abortRequest();
});
}
if (args.stream) {
args.stream.pipe(req);
args.stream.once('error', function (err) {
err.message += ' (stream "error")';
__err = err;
debug('Request#%d %s `readStream error` event emit, %s: %s', reqId, url, err.name, err.message);
abortRequest();
});
} else {
req.end(body);
}
req.requestId = reqId;
return req;
};
}).call(this,require('_process'),require("buffer").Buffer)
},{"_process":208,"any-promise":49,"babel-runtime/core-js/json/stringify":53,"babel-runtime/helpers/typeof":67,"buffer":73,"constants":75,"debug":288,"http":231,"https":193,"humanize-ms":194,"url":238,"util":243}]},{},[1])(1)
});
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/global.js */ "yLpj")))
/***/ }),
/***/ "nKGa":
/*!*******************************************************************!*\
!*** ./src/assets/images/classrooms/export_exercise-template.png ***!
\*******************************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__.p + "static/export_exercise-template.f7655c19.png";
/***/ }),
/***/ "nukY":
/*!*********************************************!*\
!*** ./src/assets/images/icons/groups1.png ***!
\*********************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports) {
module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAALoAAABSCAYAAADjGc4eAAAMkklEQVR4Xu2dWWwcSRnHv7Yd577v+74vkgWEQCAEy6IVWuCB62GVICFIYkcsvMC+LW8LL7BIiTiEhCweInjgPrRCC2KBJTBVYzm24yRO4ty3kziJj9ie+tC/d9oaT2b67ume7irJsjdbVf19X/266quvjjaEEG8w8yukk7ZAii1gMHODEOK3RPRSivXUqmXcAgb07+jomDk2NvYPZn4u4/bQ6qfUAiboSEKI5cz8XyJanVJdtVoZtsAE6EXYdzPzv4hoToZtolVPoQUmgV6E/QVm/hMRNaVQX61SRi3wDOiwg5Tya0qpn2TUJlrtFFqgIujFnv27zPztFOqsVcqgBaqCzsyGlPJXzPy5DNpFq5wyC1QFHXr29fVN6+/v/zszfyBlemt1MmYBW9Bhi3w+v7hQKJwkog0Zs41WN0UWcAS96K9vI6J3mHl+inTXqmTIAq5Ahz1yudxHDcN4k5mbM2QfrWpKLOAa9CLsB4ioLSW6azUyZAFPoBdh/w4RvZYhG2lVU2ABz6AXYf8FEb2cAv21ChmxgC/Qu7q6moeHh/9KRB/JiJ20mnVuAV+gQ+fu7u4FQ0ND/yGiLXVuAy1+BizgG/Ri2HEjEZ1k5kUZsJVWsY4tEAh06N3e3v7B8fHxt4hoWh3bIRbRm5qaaHx83NOzDcMg/DCz+RNlamhoMKtXSkX5mJrUHRh0SCml/CIzn8D+mJpInYKHNDY20p49e2hoaIguX75MIyMjrrRatWoVLVu2jJ48eUJnzpxxVcZPpunTp9POnTvNot3d3TQ8POynmsSUCQ1MIcSrzPx6YjSrIMiSJUvM3jCK9PTpU3r48KHrqhcvXkxr166lQqFAp06dMn+7SRp0N1Z6Nk+orS6E+Bkzf8WfKNGX2rdvH6EnjSINDAxQb2+v66p37NhBM2bMoNu3b9PVq1ddl9OguzbVpIyhgs7MTUKIvxDR8/7EibbU1q1byfI7w3pSc3MzTZkyhbyADsABOnzsrq4uwmhgJYw406ZVn+4sXbqUFi1aZLo8fX19VdUYHR2dNEqsWbOG5sxxf0ISckydOtWsH/J5mQ88ePCArl+/HpaJQ6knVNAhkRBiLjP/m4jedfBSntatW2eC5wV0QAc3CkBcuHBhkoWslyCo2S5dukT37t2bqGbTpk00b968oNW6Ko/n4vlJSqGDDuXy+fza4tbeZUlSNgpZvIKOSMvu3btNF+rs2bP0+PHjmoA+e/Zsc+RxmzBSwU1CunbtGmGEcJswAgwODrrNXpN8kYBehP29SincFTOjJprE9BCvoK9evZrgfgBwgG4lRDkA4/37923dhJUrV5qjAUA6d+5cVa0REvTibpRXpKMuHoDK5XKfMQzj17gNzEOxSLMi2oFGBCj9/f2Bn+UFdPSSu3btMiM/PT09pp9tpS1btpg+NEC/ePFiVbn0ZNRfk0XWo1viSCm/oZT6gT/xwi+1ceNGmj9/vum/huFHegHdylv+bPTkmCijF8bk1M5NCAo63Be87E4JLhZGDqQ7d+64WtiCXl5cHCcZwvz/kYMOYXO53DEiag1TcL91xQU6IilYgLFgHhsbM1VA775t2zaaOXMm3bp1y/SH7VJQ0MOa7FaSsdKcw287hV2uJqAzc6OU8nfM/KmwFfBaXxygoxcFzAjXwWXCD/4G/HBnADu2AnR2dpohQfw33KtKCf79woULzZXKauFF9KrVthaUgo4Frmp+PCbLVjjy0aNHtgtaGCGRMg86jNDV1TVreHj4bSLa5xXOMPPHBfrevXtt1cA2gLt375p58BIgMuM3YVTA6FAplYLe0dFB1shSntftZBTrEvv379eglxown8+vKBQKuMj03bhVDMkCHT1ntUb2IhZ6a/R+TnF0PBe9J0Jv2NeC3wsWLJiIoGByaiUNupcWcJe3Jq5LGex7C4XCP4lotjsRw81lgR5ureQIeqUec/v27aabgs1Z5XHnICu4drsNdY8edsvb1CelfEkp9fsaPnLiURboiGNbrkIYcmB0KF/8sasXkGMC6nWvS1BZNehBLeihvJTy+0qpb3ooElrWsH10P4JhQomFI7gwp0+frul+71LQ8aJX6/0RXsSkFwnrDXb75qEPkp6MltAgpXxZKYXD1bGkuEFHL46YOVwWgIF95aUJ/jn8d4AGWb0mLDjZjVQ6vOjVoj7ySymfU0rhQwOxnUaKE3RMXOGyIKRoRUbwN8J41g8gx8QU/46DGV6TUyweMlg9cKW6EfLE5i+EKCEDkvU3wpF2B0TwgpXuxPQqe5T5azYZ7ejoWDI6Oiri/nRMXKADGjwbPTr8eUADuK2tsFYj49/Pnz8/CfQbN244Roiw2one2gl0O5gwiuBFxG/E6LHjEQn77NevX2/G0vESej3+FyXAbuuuCehCCGybe4uZP+xWsKjyRQ06lvkBK8KNpYsxGzZsMMOJ5Qk+MtwX5Ec5q0cs7dGxkOTUU1rbcP2CDlcK+22wHQFbIxAFKj1Kh7g6dMCEG5vJgmwYi6pt7eqtFeg/YubDcShY/swoQUc8HaeYkDDJLN20hYkdXgIAi3/HyiZ+A5xKE8Jago5QJiCGy2KNKJUWjHD0DyMHZMao4/b4XxLaPXLQpZRfVUr9NAnKQoYoQS9d6ClfdbRO77s9UV8r0OGmbN682XSpADDcFMhYbWUULgxeWvjqyOs00iSl3SMFHVdhFAoFfEggMTfwRgn63LlzTWgwrEspfbWxdXgbk0ZrMhqV6zJr1izT98YLCvcJLon1ItptAbBsCF/9ypUr5tbipKfIQC8u96O1E3XKKErQcQ0FdhfCLcEVEW4TelW8JHAdMEHFSincgqhAh4sFOXEEEC9WJVfEDnSUwXFAa7sv3B3s1QljS4Vbm3nNFwnovb29UwcGBt5m5vd7FSjq/NbQiyEXPWWYCfFxTOawwGJ3cBm9NVwFREkANv4uvYYDL0kUoOMZmBDjlJIVOqw2eXWzqQsvCoCHj4/e/ebNm+be9SROVCMBXQjxc2b+cpgQhVXX8uXLzYZGQiMDyqCHBQCFtUEL9QLy0tNL6EFxiAFA46fS2U1MTHFYGr0jRoRSHx2ugdPEzwpVVgIXgANKjDhWOBNgIrpS7S4aN6BDV7ysGCWtemFLAI9DGEkCPnTQhRBfZ+YfhgVm2PWgQRA2C7Jpyk4mDN84JVQKJsAu36aLfPCL4TYAtvKXLcwFoxUrVhB+kAAfXhwsWNm5Gm5BR52wJerHQpQ1MiH2j5+kpFBBx+dfiAjXSSf6q9PwhzHkli/WBGkUAARocRlRpevbcPDCOnQBwJ1GkVLQnfaaQG7499CnUo8OEPFyA2zI5+aEvhfQLbuhDEKQSNjekMoeHVdcKKVEPd2sC5cCvW3Qa+qsfeZhNmzY4UXo6WWy6Ad0C3jY1cnVCtKp+CkbSo8uhJhRvLToPX6E0GUqW8Dy5d0ACrjQcwMwt7F6O7sHuakrie0ZCui5XO4EEX0piQpqmbQFYIHAoOdyuW8R0fe0ObUFkmyBQKBLKT/JzH9O0gVFSTa2li0+C/gGXUq5iZn/p78mHV/j6Se7t4Av0ItXV5zMyo257s2pcybVAp5Bx+dbpJS4T/GzSVVKy6UtUG4Bz6BLKV9TSuHr0TppC9SNBTyBXrwd9zf6o1x1075a0KIFXIMupdyulMItW7FcPKRbTFsgiAVcgd7e3j6vUCggwrI5yMN0WW2BuCzgCDpi5EKIPxLRi3EJqZ+rLRDUAo6gCyFeZ+ZXgz5Il9cWiNMCtqBLKb+glPplnALqZ2sLhGGBqqDn8/m9Sql30v6xrTCMqOtIvgUqgt7T07NwcHAQe8vXJV8FLaG2gLMFngEdX3+WUr7JzB9zLq5zaAvUhwWeAV0I8QYzv1If4msptQXcWWAS6Llc7gARtbkrqnNpC9SPBSZAb29vf9/4+Dg+phXblc71YzYtab1ZwAS9s7Nz6cjICK50ju0jWvVmOC1vfVnAKF7pjPsRP1RfomtptQXcWwB7y3+slDrkvojOqS1QfxZw3AJQfyppibNkgWPHjrGDvsowjMMa9CxRkUJdHUAfNwzjQGtr6wkNegobP0sq2YD+1DCMz7e2tv4B9tCgZ4mKFOpaBfTBxsbGTx85cuRvlsoa9BQ2fpZUqgD6w4aGhhdbWlpwS8VE0qBniYoU6loKumEYdxobG184fPhwR7mqGvQUNn6WVCoB/VpDQ8PzLS0tZyvpr0HPEhUp1LUI+gUi+vjRo0cvV1NRg57Cxs+SSsePH+9qamr6xKFDh27a6a1BzxIVKdS1ra1t4cGDB/udVPs/YIoD4AHLutsAAAAASUVORK5CYII="
/***/ }),
/***/ "oRuE":
/*!************************************************!*\
!*** ./node_modules/crypto-js/pad-iso10126.js ***!
\************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory, undef) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"), __webpack_require__(/*! ./cipher-core */ "OLod"));
}
else {}
}(this, function (CryptoJS) {
/**
* ISO 10126 padding strategy.
*/
CryptoJS.pad.Iso10126 = {
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
// Pad
data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)).
concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1));
},
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
return CryptoJS.pad.Iso10126;
}));
/***/ }),
/***/ "onxn":
/*!*********************************************!*\
!*** ./src/assets/images/icons/firefox.png ***!
\*********************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports) {
module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADQAAAA0CAYAAADFeBvrAAAQFElEQVRoQ71aCXRUVZr+7ttqr6yVPSRASCBIVFBUWgUURZFW7FYa9Xhc2lHWGdM9bYszaqa1tcUFV9RRu3V6etw4DQJqY4MDLUJQEQIYEsieqspW2Wp/9ZY7570ia1VIRXH+cyo59e6/3O/+//3vf/9XBGeR8sr/lipS6QpKyMUApoOiGISmgBIbJZSAwkdA+ihQB0JqCPAVy3K7Op5Z3Hm2pkF+qKKiik/sfV7lF5SSOwF6MSiYiekklBAcIqDvmAzkLy1/WNo7MfmR3N8bUF75fpOInnIK+iClsP2QSQzIEiAIBk8L9uwN7ooLgt9H54QBUUqJo3zHrZTgSVDkfx+jY8lcaqgDJ0awl5S6KGXWezYu+W9CCJ2IjQkByvzXnZNlRXoPlM4dywghBJRhwBACkNPRp1nRpqX/p6CqJq2Cqqr+XSdFgVGg2DRlG85FE7Y6i/Bs6NqvZdZwc9uz1zUnCiouIPrBzaxr9+Eb816v2zygKONXO+apKrZSUEeMcg0AwwAMB8JMaI2iABUFqihC7e0HMQr43YwDuGvqd/B2yni0bn7/X6W5i47J5aUC1K1pL9V5zwQurnXXqmnrKMX8vNdO3aQJp//641ug0D9RUMOgMs0BLBf9aN44C0RlGbKrHVSW8OCsY1hXVg0qq6issStfdOQ+ssrw+VKVKtfnPHvSM2aEjB6gFQuMzjaXi4AazclJOcWR391LqbphiI+AcGwMkDsNO7DCvBNFllYc8J6L273/8b0gamEot7WDhsJ4+JxDWHleva6ntQl0c2PRK/fYv1zESOwjjicPb463v2KW1rWyeIVK1Xc1JSeZ3E+XG35zDUB1PsKwYHgeGOaROVw13nI8jmxr9Chp6MvHPM9boDTB7K1SqH4/wLIgRgMIy4JTJZCudgR8Et77yW5cNrlb193WotLaOn7TvOn9a8KuwIbs3x/77ehViwHkXDntY0rpEo1RDPF0m3AB+b11OViOxSS2B4WcGy7GgXopH4u5SryVXwGek3W9vrAVs5zvIUSNCXtH6eiE4vNH+QkBa7fBEvRg2/kfoaOHxfrm+dh67R6k2RWdpaNeUpSWnu0ZZUk3BI93Xpy98eRXw43FAGpdWdQDihRR5CAGObCciu6kZGSrPeAhg+EU8FYRooVBRnonBENkUN8jrlV4PfjzhMFojHJ7Z9RDo6jQ7MOuqz8GI0r4pCEHN14Y9ZJGx48xvpIMP1V8kj91UuEksvzDKNrTiXSQsW3l9EKZyo2yxCDoF8ALCkxmKZpu4xBhVKQVt8FoD8EXtmCac0vioTagT8twEUlP21pSoOEwVH9AH51u7cFn132mlx5UoWCMrP5cSxQNDcQ9dQrNDhxsvzvj6eq34wNaVTRfVrEn4DOA52UIxkHgY656xsxWCBYR3zpn4drQxgl5ZyxmLQw1kMQg4IXCHfhZWUcMq9QnUc7MyqLb70m7/6ucuIDcq4uuFsPMTm2Q4/XT78zEqMid06DnCNfRPDyl3In3rQvGk5rQON/pxndXvQPeFCdMFJVSFaR/f9tVuRtP7IoJuTdWL69YLH/7aKLHCmeKIGtWiz7BhsqpCPeb4DVYEGSMCDEGeIkZzX6CPRkLcdhaOiEgA8xUkvGY5V3cPts1pnyoumdn+kPfXhMD6G+rrvDOVFsSLjQNSUE4Sty6obovihEJCjFGWwMEp4QcPFbym9gJaftGkvVUDZ4bO6z7G3Fw8fsjxhm5DyqXrD+TOoL9yfft178M+nHL6ut+eYFS++ZEltGYHEB6cZsu0vR1IYI91hhxr92B59hF2Jty0YgxqlJIzS16MtCJZSEUThpxxg0IqIEgjs99EbZhS82Fm6EIGaCMCUpARvCLnsys1452DgL6ZtUFTZlqX8FEAAmWMDJmOnWR9upcBKRS8JmZYA0GRDo7YJ5RisaICTc0XhajVnK69Yw2nBizGVx2ZiwoSvGu4xVcXDSU3tlIGxjZC8lcohe+3kr3kuynqj/VAblWlZSoqlIzETAaLyPIyDmvSRfz+yZDmXH/CBWHGv24o+VCRNSRVYMWZrp34hCbngY2OWlohFJI7jaszjqIh35SO/ickXog+I4jnKotFkH4uKc87d+PPK8DqrnvnA0WhOME+fgQM85pgWCOQFUIvBkPg5jSIPZ78W8n87HNnxdXgVavqZ5uqMEgqBx7NLBJdrCOdF02V2xFyN2LkqR+/M+SL4cB6oPR+w3CyXOhsnaEjvc+rnSJL+uAjq46vzZF9RWPP/1YDrPDi9TJ0TouJBbgSPhnuKlrCeRo+TcuKX1eKJ7Y4pmxmEFMZsy2tOH53C245dvFOHCTfqLoxEQ8MPqOIGKeAtk0Be3HfO8a3L07CS2/xNQa9PgIaPQYTpQIhS27V/8wbPSSpv3NOvX30QVIjEbZ5dYvd2xaKrR9IzW3gkpSDB9jEFCcKWP35e/huf8twK8WDt3zWLEdBv9xyIIDEdu5qK0UD2T2dewl7lXT57QR2xcZSq8pUSysICFtWrteIYym0rrN6KbRdBqPNCBSQ3TfaZlNSwKyM5r6RxPhOORmCTi44G30dipISWcx0IJhRRcM/hNQWTPCyfPwx12Oqhulb+qJc/W08/YyZQcul6oSKpEZXkZGqROsQUbEZ0QkJKCLSQHHS8g2dyGv6dMzrou2Z6SmxG7UhGFgNhOcXKbfZoau8QD4QA34sFO/2ASs83Hb3690bmL+XKUH+r7VlyoFSntCF5i0Ei1cAPexPB2MxHBYWvAHRAiHEtKMWnrmzK8VoFJT/AwXbyVYQtFy24cxQ8a+A2CUaBHbTS/BVftWeLcbX9pD+stnpvqCooeOWVMP6RKsISQVeNBwYCqoEsVfaSvFese9iUarvsqRxkZApYB2WYyzd4YrM3MyTq34a/SRKgKMAVAjMPf+Y5DtSM9CPHBsofQn05+3E+fKaUsppdsTmVFSvgc+jxV97uge0arxzcnzsdGstx4SJqXfCzAMWLMJES38ztCoKrL3Y+/1OwFVAhvphGLMBRd2QggMHZsvVK8A2yurNwpVbxDXyuInVao+mMhsUqe1oeXbfKgyp4MxmiRECI8Pci7BxuAt42a3eDbktg6ogWjoxKOrspx4e9F+ECUAPliPiPUcGPv2g1GjVYa2Fk/sW4E7hEOUIeSfNQ99Fqb8IgMi4x4cyYWdaDk8CRyvwGwdSrPZcxrwlW8WVnieQHhYY2hgggKVcD5biwuEE+hV7NitXIgONTUaRYEANFDxaEnqCUxNjuDBebVgpG4I/mrI5skQ/EPeURQWbYcmR8UJt5A4VxY9U8vm/0ux3Dp2uXvamjW7D+01mbDYIiDMUJzY87phz+lFQDThma478Mfg9RBIBD/lvsQ91q0oSWkAyw1VBIrCYFPHL/B44Jd6X05u17wUBGuzQfH5BrEdvHQjZJKEwgIruHArhEAtVNYIRhmqASNBAzqP50MFQ+0mcyrpXD2zaC+Zcvhi+URsqTxq2QzJAfg67BAMCiglGN6ltWT0w57bA5ZXoltCyzKnfa7IDJQID6oS/TkryPrnmuZXcEQqiXrqdJNRckWrd42ci9dDMJoh2UrAB2rBh1tjHBnw2NDbkIlDaqG47I1dRt3kf629uW6hdHjqePtIO4PkCA+GUIRD2gQBg0kGM8xbnEkEZ5T0LKh95AgHVeJ0MLLM6DIKyyJgMeAJ2y3Yq84eMkspIvWN+neWKOi6dh1UzgbRPgeC5yA4MuS9AaGexgwEu+x4UVlU8/Sbr83QAf1l3c+3XB6pWjYeoBHjFAj4DVBkogPSukMsR4e8RgFF1QAQKArRi1eNGq3ZeCr5VtQKsX1+rfzRyiCN1k/ZhQdKPoDC2NDdkA9HQfXwduDgVNqqChAOG7EC5U9/9Z8rH9CtfLL2p8tmSSe2TAiQ3ncnCAd5SJHxz2TKMnjVcQM+NM8f04zS3QOlt08fPzr/CeSbmxAJGOBzp+il1miSRQ7tVYXYJp5DH7Xeled5+Qa3Dkhrztd+XiNaaGhiBeppC5LEIBLmdW+NJonlsN86E8+lrICXGbtcVMPhwZou19iDo/PXQxF5hPvM0K762hVlNPW7UuF1pWFdeEXfR+88lqKND85g59orj5RKzedO1EvD+ZtIJt4WFiNV9qGdS8XXxhL0MPaEVMqdXVC90T2yvWwj5mXVwHMqG9aMfphTY88pLfG0VxVgu68MIc5Sef8b710yAtDna69cPU1qfiUh62dgOspNwUOWe9DGRM+ZRGmKtw62Xieuzq5Ceckn6D6ZCXNaAAZ7CLwp1jthrwnHvpuBfXIRvcZY+3Tpa1V6n3vQQ7RiAXe409/nUPosiU5iLL4QMaCeycFxbjK+4Gehkp8xpkoGKubKNdjgfwP9ioA8iweqyMKW1acDMaX64yaDzpocrHbdhg227YqBKMvyXju1YwQg7cvuNVfcXyy3nJ32J4AAMeFz4Tzs4mejgclBO5sCCoJ0tR9TVTeWipXIUz2YLrfoffMBsmb1InlSNwLdVljSYvveWqJ49OtbYGZlepehMpyXnZdKKvbop+2IXUwrKpjDHR93OdTeicVLgi6VwUJ7t89ijK4sQ2HP6dGrDm2PhLotetiNpgPVZXi741I8aN0t80R9Pv/VU4P9kJi0VLnm8iU5cvsOAu1Y//8jLZMlF3SBN0ZrRNFnBG8RRxza2utYf3syDjWVoIjV30Z8kzc7aR6579BgYRl30tvXLH7rPLn+7h8bjlZ5mFP9MDt8EMxD13lt4lpb2ZQc0qegnTeyyKOv2QE5FO3OSgzvFjjporyX6qKNwdMU/6UxpWTfmsuOFCrtZT8WKMKqyJkdbfSPpn5nql4XamMamN5GB0TvUK4KE6HbTqS5ma+eahgtO2ZY9fx2TlKtVziZp3Zl/FigUiZ3wOIYWZ/52pLR35oOU6oPtuw+dNdl6QfsAHmYlMZcEpiXsak6tnQY70bWubrUepjkNJTKTbGv8s8SSlOaD5Z0LwhL4XWmQvSa42rWrgf7+Fn7byVVV5KX6mLbTWcKueEa6etz+M+OphwqlZtmnSUME1bjJyb6vOmm8tc3PvrCeMIJZTLt5zBb1i59tUxuvDeRm+14RscbD1IB9Uo6ZnHRfp2XsX4489Ujy8eT08YTAjSg6Plf333p9HDLpzPlpnEvg4kYH83TrZrxcugy7IkU4SnrdszlW6AS5iOzndzu2FAbexmKY2RCgDR5zVsfrFm2YSrc92cqveNe2xMF9pk4HZvFMmQwflxrqMZFXKub49R1+ZtOne5hJaZpwoAG1GpXjhf/YXuxTK37pyLFPZSGErM7JleYCPVGRN7kreaXsp45OnY7aAwN3xvQcH1b1y65VabMwzMU5zQ79bMKmLHLm2GCEXC0jUkVRSLUF6hdW62c8n7WyzXHfsianBVAg16rqGCOerYt+E4tuOIbviR3suK+cBp1Zdpp0GRVRfZl4/XHD7AzTpnYSFWB0vHlzS2TDiz/cPn4vx2YAML/AxiD3K8wfl5pAAAAAElFTkSuQmCC"
/***/ }),
/***/ "osHv":
/*!********************************************************!*\
!*** ./node_modules/codemirror/addon/fold/xml-fold.js ***!
\********************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
if (true) // CommonJS
mod(__webpack_require__(/*! ../../lib/codemirror */ "VrN/"));
else {}
})(function(CodeMirror) {
"use strict";
var Pos = CodeMirror.Pos;
function cmp(a, b) { return a.line - b.line || a.ch - b.ch; }
var nameStartChar = "A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
var nameChar = nameStartChar + "\-\:\.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
var xmlTagStart = new RegExp("<(/?)([" + nameStartChar + "][" + nameChar + "]*)", "g");
function Iter(cm, line, ch, range) {
this.line = line; this.ch = ch;
this.cm = cm; this.text = cm.getLine(line);
this.min = range ? Math.max(range.from, cm.firstLine()) : cm.firstLine();
this.max = range ? Math.min(range.to - 1, cm.lastLine()) : cm.lastLine();
}
function tagAt(iter, ch) {
var type = iter.cm.getTokenTypeAt(Pos(iter.line, ch));
return type && /\btag\b/.test(type);
}
function nextLine(iter) {
if (iter.line >= iter.max) return;
iter.ch = 0;
iter.text = iter.cm.getLine(++iter.line);
return true;
}
function prevLine(iter) {
if (iter.line <= iter.min) return;
iter.text = iter.cm.getLine(--iter.line);
iter.ch = iter.text.length;
return true;
}
function toTagEnd(iter) {
for (;;) {
var gt = iter.text.indexOf(">", iter.ch);
if (gt == -1) { if (nextLine(iter)) continue; else return; }
if (!tagAt(iter, gt + 1)) { iter.ch = gt + 1; continue; }
var lastSlash = iter.text.lastIndexOf("/", gt);
var selfClose = lastSlash > -1 && !/\S/.test(iter.text.slice(lastSlash + 1, gt));
iter.ch = gt + 1;
return selfClose ? "selfClose" : "regular";
}
}
function toTagStart(iter) {
for (;;) {
var lt = iter.ch ? iter.text.lastIndexOf("<", iter.ch - 1) : -1;
if (lt == -1) { if (prevLine(iter)) continue; else return; }
if (!tagAt(iter, lt + 1)) { iter.ch = lt; continue; }
xmlTagStart.lastIndex = lt;
iter.ch = lt;
var match = xmlTagStart.exec(iter.text);
if (match && match.index == lt) return match;
}
}
function toNextTag(iter) {
for (;;) {
xmlTagStart.lastIndex = iter.ch;
var found = xmlTagStart.exec(iter.text);
if (!found) { if (nextLine(iter)) continue; else return; }
if (!tagAt(iter, found.index + 1)) { iter.ch = found.index + 1; continue; }
iter.ch = found.index + found[0].length;
return found;
}
}
function toPrevTag(iter) {
for (;;) {
var gt = iter.ch ? iter.text.lastIndexOf(">", iter.ch - 1) : -1;
if (gt == -1) { if (prevLine(iter)) continue; else return; }
if (!tagAt(iter, gt + 1)) { iter.ch = gt; continue; }
var lastSlash = iter.text.lastIndexOf("/", gt);
var selfClose = lastSlash > -1 && !/\S/.test(iter.text.slice(lastSlash + 1, gt));
iter.ch = gt + 1;
return selfClose ? "selfClose" : "regular";
}
}
function findMatchingClose(iter, tag) {
var stack = [];
for (;;) {
var next = toNextTag(iter), end, startLine = iter.line, startCh = iter.ch - (next ? next[0].length : 0);
if (!next || !(end = toTagEnd(iter))) return;
if (end == "selfClose") continue;
if (next[1]) { // closing tag
for (var i = stack.length - 1; i >= 0; --i) if (stack[i] == next[2]) {
stack.length = i;
break;
}
if (i < 0 && (!tag || tag == next[2])) return {
tag: next[2],
from: Pos(startLine, startCh),
to: Pos(iter.line, iter.ch)
};
} else { // opening tag
stack.push(next[2]);
}
}
}
function findMatchingOpen(iter, tag) {
var stack = [];
for (;;) {
var prev = toPrevTag(iter);
if (!prev) return;
if (prev == "selfClose") { toTagStart(iter); continue; }
var endLine = iter.line, endCh = iter.ch;
var start = toTagStart(iter);
if (!start) return;
if (start[1]) { // closing tag
stack.push(start[2]);
} else { // opening tag
for (var i = stack.length - 1; i >= 0; --i) if (stack[i] == start[2]) {
stack.length = i;
break;
}
if (i < 0 && (!tag || tag == start[2])) return {
tag: start[2],
from: Pos(iter.line, iter.ch),
to: Pos(endLine, endCh)
};
}
}
}
CodeMirror.registerHelper("fold", "xml", function(cm, start) {
var iter = new Iter(cm, start.line, 0);
for (;;) {
var openTag = toNextTag(iter)
if (!openTag || iter.line != start.line) return
var end = toTagEnd(iter)
if (!end) return
if (!openTag[1] && end != "selfClose") {
var startPos = Pos(iter.line, iter.ch);
var endPos = findMatchingClose(iter, openTag[2]);
return endPos && cmp(endPos.from, startPos) > 0 ? {from: startPos, to: endPos.from} : null
}
}
});
CodeMirror.findMatchingTag = function(cm, pos, range) {
var iter = new Iter(cm, pos.line, pos.ch, range);
if (iter.text.indexOf(">") == -1 && iter.text.indexOf("<") == -1) return;
var end = toTagEnd(iter), to = end && Pos(iter.line, iter.ch);
var start = end && toTagStart(iter);
if (!end || !start || cmp(iter, pos) > 0) return;
var here = {from: Pos(iter.line, iter.ch), to: to, tag: start[2]};
if (end == "selfClose") return {open: here, close: null, at: "open"};
if (start[1]) { // closing tag
return {open: findMatchingOpen(iter, start[2]), close: here, at: "close"};
} else { // opening tag
iter = new Iter(cm, to.line, to.ch, range);
return {open: here, close: findMatchingClose(iter, start[2]), at: "open"};
}
};
CodeMirror.findEnclosingTag = function(cm, pos, range, tag) {
var iter = new Iter(cm, pos.line, pos.ch, range);
for (;;) {
var open = findMatchingOpen(iter, tag);
if (!open) break;
var forward = new Iter(cm, pos.line, pos.ch, range);
var close = findMatchingClose(forward, open.tag);
if (close) return {open: open, close: close};
}
};
// Used by addon/edit/closetag.js
CodeMirror.scanForClosingTag = function(cm, pos, name, end) {
var iter = new Iter(cm, pos.line, pos.ch, end ? {from: 0, to: end} : null);
return findMatchingClose(iter, name);
};
});
/***/ }),
/***/ "p77/":
/*!****************************************************!*\
!*** ./node_modules/codemirror/lib/codemirror.css ***!
\****************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/***/ "pA7S":
/*!*********************************************!*\
!*** ./node_modules/crypto-js/tripledes.js ***!
\*********************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory, undef) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"), __webpack_require__(/*! ./enc-base64 */ "ETIr"), __webpack_require__(/*! ./md5 */ "cv67"), __webpack_require__(/*! ./evpkdf */ "K3mO"), __webpack_require__(/*! ./cipher-core */ "OLod"));
}
else {}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Permuted Choice 1 constants
var PC1 = [
57, 49, 41, 33, 25, 17, 9, 1,
58, 50, 42, 34, 26, 18, 10, 2,
59, 51, 43, 35, 27, 19, 11, 3,
60, 52, 44, 36, 63, 55, 47, 39,
31, 23, 15, 7, 62, 54, 46, 38,
30, 22, 14, 6, 61, 53, 45, 37,
29, 21, 13, 5, 28, 20, 12, 4
];
// Permuted Choice 2 constants
var PC2 = [
14, 17, 11, 24, 1, 5,
3, 28, 15, 6, 21, 10,
23, 19, 12, 4, 26, 8,
16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55,
30, 40, 51, 45, 33, 48,
44, 49, 39, 56, 34, 53,
46, 42, 50, 36, 29, 32
];
// Cumulative bit shift constants
var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28];
// SBOXes and round permutation constants
var SBOX_P = [
{
0x0: 0x808200,
0x10000000: 0x8000,
0x20000000: 0x808002,
0x30000000: 0x2,
0x40000000: 0x200,
0x50000000: 0x808202,
0x60000000: 0x800202,
0x70000000: 0x800000,
0x80000000: 0x202,
0x90000000: 0x800200,
0xa0000000: 0x8200,
0xb0000000: 0x808000,
0xc0000000: 0x8002,
0xd0000000: 0x800002,
0xe0000000: 0x0,
0xf0000000: 0x8202,
0x8000000: 0x0,
0x18000000: 0x808202,
0x28000000: 0x8202,
0x38000000: 0x8000,
0x48000000: 0x808200,
0x58000000: 0x200,
0x68000000: 0x808002,
0x78000000: 0x2,
0x88000000: 0x800200,
0x98000000: 0x8200,
0xa8000000: 0x808000,
0xb8000000: 0x800202,
0xc8000000: 0x800002,
0xd8000000: 0x8002,
0xe8000000: 0x202,
0xf8000000: 0x800000,
0x1: 0x8000,
0x10000001: 0x2,
0x20000001: 0x808200,
0x30000001: 0x800000,
0x40000001: 0x808002,
0x50000001: 0x8200,
0x60000001: 0x200,
0x70000001: 0x800202,
0x80000001: 0x808202,
0x90000001: 0x808000,
0xa0000001: 0x800002,
0xb0000001: 0x8202,
0xc0000001: 0x202,
0xd0000001: 0x800200,
0xe0000001: 0x8002,
0xf0000001: 0x0,
0x8000001: 0x808202,
0x18000001: 0x808000,
0x28000001: 0x800000,
0x38000001: 0x200,
0x48000001: 0x8000,
0x58000001: 0x800002,
0x68000001: 0x2,
0x78000001: 0x8202,
0x88000001: 0x8002,
0x98000001: 0x800202,
0xa8000001: 0x202,
0xb8000001: 0x808200,
0xc8000001: 0x800200,
0xd8000001: 0x0,
0xe8000001: 0x8200,
0xf8000001: 0x808002
},
{
0x0: 0x40084010,
0x1000000: 0x4000,
0x2000000: 0x80000,
0x3000000: 0x40080010,
0x4000000: 0x40000010,
0x5000000: 0x40084000,
0x6000000: 0x40004000,
0x7000000: 0x10,
0x8000000: 0x84000,
0x9000000: 0x40004010,
0xa000000: 0x40000000,
0xb000000: 0x84010,
0xc000000: 0x80010,
0xd000000: 0x0,
0xe000000: 0x4010,
0xf000000: 0x40080000,
0x800000: 0x40004000,
0x1800000: 0x84010,
0x2800000: 0x10,
0x3800000: 0x40004010,
0x4800000: 0x40084010,
0x5800000: 0x40000000,
0x6800000: 0x80000,
0x7800000: 0x40080010,
0x8800000: 0x80010,
0x9800000: 0x0,
0xa800000: 0x4000,
0xb800000: 0x40080000,
0xc800000: 0x40000010,
0xd800000: 0x84000,
0xe800000: 0x40084000,
0xf800000: 0x4010,
0x10000000: 0x0,
0x11000000: 0x40080010,
0x12000000: 0x40004010,
0x13000000: 0x40084000,
0x14000000: 0x40080000,
0x15000000: 0x10,
0x16000000: 0x84010,
0x17000000: 0x4000,
0x18000000: 0x4010,
0x19000000: 0x80000,
0x1a000000: 0x80010,
0x1b000000: 0x40000010,
0x1c000000: 0x84000,
0x1d000000: 0x40004000,
0x1e000000: 0x40000000,
0x1f000000: 0x40084010,
0x10800000: 0x84010,
0x11800000: 0x80000,
0x12800000: 0x40080000,
0x13800000: 0x4000,
0x14800000: 0x40004000,
0x15800000: 0x40084010,
0x16800000: 0x10,
0x17800000: 0x40000000,
0x18800000: 0x40084000,
0x19800000: 0x40000010,
0x1a800000: 0x40004010,
0x1b800000: 0x80010,
0x1c800000: 0x0,
0x1d800000: 0x4010,
0x1e800000: 0x40080010,
0x1f800000: 0x84000
},
{
0x0: 0x104,
0x100000: 0x0,
0x200000: 0x4000100,
0x300000: 0x10104,
0x400000: 0x10004,
0x500000: 0x4000004,
0x600000: 0x4010104,
0x700000: 0x4010000,
0x800000: 0x4000000,
0x900000: 0x4010100,
0xa00000: 0x10100,
0xb00000: 0x4010004,
0xc00000: 0x4000104,
0xd00000: 0x10000,
0xe00000: 0x4,
0xf00000: 0x100,
0x80000: 0x4010100,
0x180000: 0x4010004,
0x280000: 0x0,
0x380000: 0x4000100,
0x480000: 0x4000004,
0x580000: 0x10000,
0x680000: 0x10004,
0x780000: 0x104,
0x880000: 0x4,
0x980000: 0x100,
0xa80000: 0x4010000,
0xb80000: 0x10104,
0xc80000: 0x10100,
0xd80000: 0x4000104,
0xe80000: 0x4010104,
0xf80000: 0x4000000,
0x1000000: 0x4010100,
0x1100000: 0x10004,
0x1200000: 0x10000,
0x1300000: 0x4000100,
0x1400000: 0x100,
0x1500000: 0x4010104,
0x1600000: 0x4000004,
0x1700000: 0x0,
0x1800000: 0x4000104,
0x1900000: 0x4000000,
0x1a00000: 0x4,
0x1b00000: 0x10100,
0x1c00000: 0x4010000,
0x1d00000: 0x104,
0x1e00000: 0x10104,
0x1f00000: 0x4010004,
0x1080000: 0x4000000,
0x1180000: 0x104,
0x1280000: 0x4010100,
0x1380000: 0x0,
0x1480000: 0x10004,
0x1580000: 0x4000100,
0x1680000: 0x100,
0x1780000: 0x4010004,
0x1880000: 0x10000,
0x1980000: 0x4010104,
0x1a80000: 0x10104,
0x1b80000: 0x4000004,
0x1c80000: 0x4000104,
0x1d80000: 0x4010000,
0x1e80000: 0x4,
0x1f80000: 0x10100
},
{
0x0: 0x80401000,
0x10000: 0x80001040,
0x20000: 0x401040,
0x30000: 0x80400000,
0x40000: 0x0,
0x50000: 0x401000,
0x60000: 0x80000040,
0x70000: 0x400040,
0x80000: 0x80000000,
0x90000: 0x400000,
0xa0000: 0x40,
0xb0000: 0x80001000,
0xc0000: 0x80400040,
0xd0000: 0x1040,
0xe0000: 0x1000,
0xf0000: 0x80401040,
0x8000: 0x80001040,
0x18000: 0x40,
0x28000: 0x80400040,
0x38000: 0x80001000,
0x48000: 0x401000,
0x58000: 0x80401040,
0x68000: 0x0,
0x78000: 0x80400000,
0x88000: 0x1000,
0x98000: 0x80401000,
0xa8000: 0x400000,
0xb8000: 0x1040,
0xc8000: 0x80000000,
0xd8000: 0x400040,
0xe8000: 0x401040,
0xf8000: 0x80000040,
0x100000: 0x400040,
0x110000: 0x401000,
0x120000: 0x80000040,
0x130000: 0x0,
0x140000: 0x1040,
0x150000: 0x80400040,
0x160000: 0x80401000,
0x170000: 0x80001040,
0x180000: 0x80401040,
0x190000: 0x80000000,
0x1a0000: 0x80400000,
0x1b0000: 0x401040,
0x1c0000: 0x80001000,
0x1d0000: 0x400000,
0x1e0000: 0x40,
0x1f0000: 0x1000,
0x108000: 0x80400000,
0x118000: 0x80401040,
0x128000: 0x0,
0x138000: 0x401000,
0x148000: 0x400040,
0x158000: 0x80000000,
0x168000: 0x80001040,
0x178000: 0x40,
0x188000: 0x80000040,
0x198000: 0x1000,
0x1a8000: 0x80001000,
0x1b8000: 0x80400040,
0x1c8000: 0x1040,
0x1d8000: 0x80401000,
0x1e8000: 0x400000,
0x1f8000: 0x401040
},
{
0x0: 0x80,
0x1000: 0x1040000,
0x2000: 0x40000,
0x3000: 0x20000000,
0x4000: 0x20040080,
0x5000: 0x1000080,
0x6000: 0x21000080,
0x7000: 0x40080,
0x8000: 0x1000000,
0x9000: 0x20040000,
0xa000: 0x20000080,
0xb000: 0x21040080,
0xc000: 0x21040000,
0xd000: 0x0,
0xe000: 0x1040080,
0xf000: 0x21000000,
0x800: 0x1040080,
0x1800: 0x21000080,
0x2800: 0x80,
0x3800: 0x1040000,
0x4800: 0x40000,
0x5800: 0x20040080,
0x6800: 0x21040000,
0x7800: 0x20000000,
0x8800: 0x20040000,
0x9800: 0x0,
0xa800: 0x21040080,
0xb800: 0x1000080,
0xc800: 0x20000080,
0xd800: 0x21000000,
0xe800: 0x1000000,
0xf800: 0x40080,
0x10000: 0x40000,
0x11000: 0x80,
0x12000: 0x20000000,
0x13000: 0x21000080,
0x14000: 0x1000080,
0x15000: 0x21040000,
0x16000: 0x20040080,
0x17000: 0x1000000,
0x18000: 0x21040080,
0x19000: 0x21000000,
0x1a000: 0x1040000,
0x1b000: 0x20040000,
0x1c000: 0x40080,
0x1d000: 0x20000080,
0x1e000: 0x0,
0x1f000: 0x1040080,
0x10800: 0x21000080,
0x11800: 0x1000000,
0x12800: 0x1040000,
0x13800: 0x20040080,
0x14800: 0x20000000,
0x15800: 0x1040080,
0x16800: 0x80,
0x17800: 0x21040000,
0x18800: 0x40080,
0x19800: 0x21040080,
0x1a800: 0x0,
0x1b800: 0x21000000,
0x1c800: 0x1000080,
0x1d800: 0x40000,
0x1e800: 0x20040000,
0x1f800: 0x20000080
},
{
0x0: 0x10000008,
0x100: 0x2000,
0x200: 0x10200000,
0x300: 0x10202008,
0x400: 0x10002000,
0x500: 0x200000,
0x600: 0x200008,
0x700: 0x10000000,
0x800: 0x0,
0x900: 0x10002008,
0xa00: 0x202000,
0xb00: 0x8,
0xc00: 0x10200008,
0xd00: 0x202008,
0xe00: 0x2008,
0xf00: 0x10202000,
0x80: 0x10200000,
0x180: 0x10202008,
0x280: 0x8,
0x380: 0x200000,
0x480: 0x202008,
0x580: 0x10000008,
0x680: 0x10002000,
0x780: 0x2008,
0x880: 0x200008,
0x980: 0x2000,
0xa80: 0x10002008,
0xb80: 0x10200008,
0xc80: 0x0,
0xd80: 0x10202000,
0xe80: 0x202000,
0xf80: 0x10000000,
0x1000: 0x10002000,
0x1100: 0x10200008,
0x1200: 0x10202008,
0x1300: 0x2008,
0x1400: 0x200000,
0x1500: 0x10000000,
0x1600: 0x10000008,
0x1700: 0x202000,
0x1800: 0x202008,
0x1900: 0x0,
0x1a00: 0x8,
0x1b00: 0x10200000,
0x1c00: 0x2000,
0x1d00: 0x10002008,
0x1e00: 0x10202000,
0x1f00: 0x200008,
0x1080: 0x8,
0x1180: 0x202000,
0x1280: 0x200000,
0x1380: 0x10000008,
0x1480: 0x10002000,
0x1580: 0x2008,
0x1680: 0x10202008,
0x1780: 0x10200000,
0x1880: 0x10202000,
0x1980: 0x10200008,
0x1a80: 0x2000,
0x1b80: 0x202008,
0x1c80: 0x200008,
0x1d80: 0x0,
0x1e80: 0x10000000,
0x1f80: 0x10002008
},
{
0x0: 0x100000,
0x10: 0x2000401,
0x20: 0x400,
0x30: 0x100401,
0x40: 0x2100401,
0x50: 0x0,
0x60: 0x1,
0x70: 0x2100001,
0x80: 0x2000400,
0x90: 0x100001,
0xa0: 0x2000001,
0xb0: 0x2100400,
0xc0: 0x2100000,
0xd0: 0x401,
0xe0: 0x100400,
0xf0: 0x2000000,
0x8: 0x2100001,
0x18: 0x0,
0x28: 0x2000401,
0x38: 0x2100400,
0x48: 0x100000,
0x58: 0x2000001,
0x68: 0x2000000,
0x78: 0x401,
0x88: 0x100401,
0x98: 0x2000400,
0xa8: 0x2100000,
0xb8: 0x100001,
0xc8: 0x400,
0xd8: 0x2100401,
0xe8: 0x1,
0xf8: 0x100400,
0x100: 0x2000000,
0x110: 0x100000,
0x120: 0x2000401,
0x130: 0x2100001,
0x140: 0x100001,
0x150: 0x2000400,
0x160: 0x2100400,
0x170: 0x100401,
0x180: 0x401,
0x190: 0x2100401,
0x1a0: 0x100400,
0x1b0: 0x1,
0x1c0: 0x0,
0x1d0: 0x2100000,
0x1e0: 0x2000001,
0x1f0: 0x400,
0x108: 0x100400,
0x118: 0x2000401,
0x128: 0x2100001,
0x138: 0x1,
0x148: 0x2000000,
0x158: 0x100000,
0x168: 0x401,
0x178: 0x2100400,
0x188: 0x2000001,
0x198: 0x2100000,
0x1a8: 0x0,
0x1b8: 0x2100401,
0x1c8: 0x100401,
0x1d8: 0x400,
0x1e8: 0x2000400,
0x1f8: 0x100001
},
{
0x0: 0x8000820,
0x1: 0x20000,
0x2: 0x8000000,
0x3: 0x20,
0x4: 0x20020,
0x5: 0x8020820,
0x6: 0x8020800,
0x7: 0x800,
0x8: 0x8020000,
0x9: 0x8000800,
0xa: 0x20800,
0xb: 0x8020020,
0xc: 0x820,
0xd: 0x0,
0xe: 0x8000020,
0xf: 0x20820,
0x80000000: 0x800,
0x80000001: 0x8020820,
0x80000002: 0x8000820,
0x80000003: 0x8000000,
0x80000004: 0x8020000,
0x80000005: 0x20800,
0x80000006: 0x20820,
0x80000007: 0x20,
0x80000008: 0x8000020,
0x80000009: 0x820,
0x8000000a: 0x20020,
0x8000000b: 0x8020800,
0x8000000c: 0x0,
0x8000000d: 0x8020020,
0x8000000e: 0x8000800,
0x8000000f: 0x20000,
0x10: 0x20820,
0x11: 0x8020800,
0x12: 0x20,
0x13: 0x800,
0x14: 0x8000800,
0x15: 0x8000020,
0x16: 0x8020020,
0x17: 0x20000,
0x18: 0x0,
0x19: 0x20020,
0x1a: 0x8020000,
0x1b: 0x8000820,
0x1c: 0x8020820,
0x1d: 0x20800,
0x1e: 0x820,
0x1f: 0x8000000,
0x80000010: 0x20000,
0x80000011: 0x800,
0x80000012: 0x8020020,
0x80000013: 0x20820,
0x80000014: 0x20,
0x80000015: 0x8020000,
0x80000016: 0x8000000,
0x80000017: 0x8000820,
0x80000018: 0x8020820,
0x80000019: 0x8000020,
0x8000001a: 0x8000800,
0x8000001b: 0x0,
0x8000001c: 0x20800,
0x8000001d: 0x820,
0x8000001e: 0x20020,
0x8000001f: 0x8020800
}
];
// Masks that select the SBOX input
var SBOX_MASK = [
0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000,
0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f
];
/**
* DES block cipher algorithm.
*/
var DES = C_algo.DES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
// Select 56 bits according to PC1
var keyBits = [];
for (var i = 0; i < 56; i++) {
var keyBitPos = PC1[i] - 1;
keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1;
}
// Assemble 16 subkeys
var subKeys = this._subKeys = [];
for (var nSubKey = 0; nSubKey < 16; nSubKey++) {
// Create subkey
var subKey = subKeys[nSubKey] = [];
// Shortcut
var bitShift = BIT_SHIFTS[nSubKey];
// Select 48 bits according to PC2
for (var i = 0; i < 24; i++) {
// Select from the left 28 key bits
subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6);
// Select from the right 28 key bits
subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6);
}
// Since each subkey is applied to an expanded 32-bit input,
// the subkey can be broken into 8 values scaled to 32-bits,
// which allows the key to be used without expansion
subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31);
for (var i = 1; i < 7; i++) {
subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3);
}
subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27);
}
// Compute inverse subkeys
var invSubKeys = this._invSubKeys = [];
for (var i = 0; i < 16; i++) {
invSubKeys[i] = subKeys[15 - i];
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._subKeys);
},
decryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._invSubKeys);
},
_doCryptBlock: function (M, offset, subKeys) {
// Get input
this._lBlock = M[offset];
this._rBlock = M[offset + 1];
// Initial permutation
exchangeLR.call(this, 4, 0x0f0f0f0f);
exchangeLR.call(this, 16, 0x0000ffff);
exchangeRL.call(this, 2, 0x33333333);
exchangeRL.call(this, 8, 0x00ff00ff);
exchangeLR.call(this, 1, 0x55555555);
// Rounds
for (var round = 0; round < 16; round++) {
// Shortcuts
var subKey = subKeys[round];
var lBlock = this._lBlock;
var rBlock = this._rBlock;
// Feistel function
var f = 0;
for (var i = 0; i < 8; i++) {
f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0];
}
this._lBlock = rBlock;
this._rBlock = lBlock ^ f;
}
// Undo swap from last round
var t = this._lBlock;
this._lBlock = this._rBlock;
this._rBlock = t;
// Final permutation
exchangeLR.call(this, 1, 0x55555555);
exchangeRL.call(this, 8, 0x00ff00ff);
exchangeRL.call(this, 2, 0x33333333);
exchangeLR.call(this, 16, 0x0000ffff);
exchangeLR.call(this, 4, 0x0f0f0f0f);
// Set output
M[offset] = this._lBlock;
M[offset + 1] = this._rBlock;
},
keySize: 64/32,
ivSize: 64/32,
blockSize: 64/32
});
// Swap bits across the left and right words
function exchangeLR(offset, mask) {
var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask;
this._rBlock ^= t;
this._lBlock ^= t << offset;
}
function exchangeRL(offset, mask) {
var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask;
this._lBlock ^= t;
this._rBlock ^= t << offset;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.DES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg);
*/
C.DES = BlockCipher._createHelper(DES);
/**
* Triple-DES block cipher algorithm.
*/
var TripleDES = C_algo.TripleDES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
// Make sure the key length is valid (64, 128 or >= 192 bit)
if (keyWords.length !== 2 && keyWords.length !== 4 && keyWords.length < 6) {
throw new Error('Invalid key length - 3DES requires the key length to be 64, 128, 192 or >192.');
}
// Extend the key according to the keying options defined in 3DES standard
var key1 = keyWords.slice(0, 2);
var key2 = keyWords.length < 4 ? keyWords.slice(0, 2) : keyWords.slice(2, 4);
var key3 = keyWords.length < 6 ? keyWords.slice(0, 2) : keyWords.slice(4, 6);
// Create DES instances
this._des1 = DES.createEncryptor(WordArray.create(key1));
this._des2 = DES.createEncryptor(WordArray.create(key2));
this._des3 = DES.createEncryptor(WordArray.create(key3));
},
encryptBlock: function (M, offset) {
this._des1.encryptBlock(M, offset);
this._des2.decryptBlock(M, offset);
this._des3.encryptBlock(M, offset);
},
decryptBlock: function (M, offset) {
this._des3.decryptBlock(M, offset);
this._des2.encryptBlock(M, offset);
this._des1.decryptBlock(M, offset);
},
keySize: 192/32,
ivSize: 64/32,
blockSize: 64/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg);
*/
C.TripleDES = BlockCipher._createHelper(TripleDES);
}());
return CryptoJS.TripleDES;
}));
/***/ }),
/***/ "pED+":
/*!*****************************************************!*\
!*** ./node_modules/antd/es/table/style/index.less ***!
\*****************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/***/ "pIsd":
/*!***************************************!*\
!*** ./node_modules/json2mq/index.js ***!
\***************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
var camel2hyphen = __webpack_require__(/*! string-convert/camel2hyphen */ "BJfS");
var isDimension = function (feature) {
var re = /[height|width]$/;
return re.test(feature);
};
var obj2mq = function (obj) {
var mq = '';
var features = Object.keys(obj);
features.forEach(function (feature, index) {
var value = obj[feature];
feature = camel2hyphen(feature);
// Add px to dimension features
if (isDimension(feature) && typeof value === 'number') {
value = value + 'px';
}
if (value === true) {
mq += feature;
} else if (value === false) {
mq += 'not ' + feature;
} else {
mq += '(' + feature + ': ' + value + ')';
}
if (index < features.length-1) {
mq += ' and '
}
});
return mq;
};
var json2mq = function (query) {
var mq = '';
if (typeof query === 'string') {
return query;
}
// Handling array of media queries
if (query instanceof Array) {
query.forEach(function (q, index) {
mq += obj2mq(q);
if (index < query.length-1) {
mq += ', '
}
});
return mq;
}
// Handling single media query
return obj2mq(query);
};
module.exports = json2mq;
/***/ }),
/***/ "qBft":
/*!************************************************!*\
!*** ./node_modules/crypto-js/pad-ansix923.js ***!
\************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory, undef) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"), __webpack_require__(/*! ./cipher-core */ "OLod"));
}
else {}
}(this, function (CryptoJS) {
/**
* ANSI X.923 padding strategy.
*/
CryptoJS.pad.AnsiX923 = {
pad: function (data, blockSize) {
// Shortcuts
var dataSigBytes = data.sigBytes;
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes;
// Compute last byte position
var lastBytePos = dataSigBytes + nPaddingBytes - 1;
// Pad
data.clamp();
data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8);
data.sigBytes += nPaddingBytes;
},
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
return CryptoJS.pad.Ansix923;
}));
/***/ }),
/***/ "qHvr":
/*!******************************************************************!*\
!*** ./src/pages/Competitions/Entered/Enteredmodel/Addteams.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 _Users_xxq_node_forgeplus_react_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/slicedToArray */ "tJVT");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! react */ "q1tI");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _ant_design_icons__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @ant-design/icons */ "4i/N");
//创建战队弹窗
function Addteans(_ref) {
var isAddmodle = _ref.isAddmodle,
setIsAdd = _ref.setIsAdd,
createTeam = _ref.createTeam;
var _useState = Object(react__WEBPACK_IMPORTED_MODULE_7__["useState"])(""),
_useState2 = Object(_Users_xxq_node_forgeplus_react_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_slicedToArray__WEBPACK_IMPORTED_MODULE_6__[/* default */ "a"])(_useState, 2),
personname = _useState2[0],
setpersonname = _useState2[1];
return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement(antd_es_modal__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"], {
centered: true,
title: /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("div", {
style: {
alignItems: 'center',
display: 'flex'
}
}, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("div", {
style: {
textAlign: 'left',
flex: '1'
}
}, "\u521B\u5EFA\u6218\u961F"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement(_ant_design_icons__WEBPACK_IMPORTED_MODULE_8__[/* default */ "a"], {
onClick: function onClick() {
return setIsAdd(false);
},
style: {
cursor: 'porint'
}
})),
visible: isAddmodle,
closable: false,
destroyOnClose: true,
onOk: function onOk() {
if (!personname) {
antd_es_message__WEBPACK_IMPORTED_MODULE_5__[/* default */ "b"].info('战队名不能为空');
return;
}
createTeam(personname);
},
onCancel: function onCancel() {
return setIsAdd(false);
}
}, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("div", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("span", {
style: {
fontSize: '14px',
color: '#F73737'
}
}, "*"), "\u961F\u540D\uFF1A", /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("p", {
style: {
marginTop: '15px',
marginLeft: '15px'
}
}, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement(antd_es_input__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"], {
placeholder: "请输入队名",
value: personname,
maxLength: 60,
addonAfter: String(personname && personname.length || 0) + "/60",
onChange: function onChange(e) {
return setpersonname(e.target.value);
}
}))));
}
/* harmony default export */ __webpack_exports__["a"] = (Addteans);
/***/ }),
/***/ "qM6L":
/*!*********************************************!*\
!*** ./node_modules/crypto-js/enc-utf16.js ***!
\*********************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"));
}
else {}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* UTF-16 BE encoding strategy.
*/
var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = {
/**
* Converts a word array to a UTF-16 BE string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-16 BE string.
*
* @static
*
* @example
*
* var utf16String = CryptoJS.enc.Utf16.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var utf16Chars = [];
for (var i = 0; i < sigBytes; i += 2) {
var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff;
utf16Chars.push(String.fromCharCode(codePoint));
}
return utf16Chars.join('');
},
/**
* Converts a UTF-16 BE string to a word array.
*
* @param {string} utf16Str The UTF-16 BE string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf16.parse(utf16String);
*/
parse: function (utf16Str) {
// Shortcut
var utf16StrLength = utf16Str.length;
// Convert
var words = [];
for (var i = 0; i < utf16StrLength; i++) {
words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16);
}
return WordArray.create(words, utf16StrLength * 2);
}
};
/**
* UTF-16 LE encoding strategy.
*/
C_enc.Utf16LE = {
/**
* Converts a word array to a UTF-16 LE string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-16 LE string.
*
* @static
*
* @example
*
* var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var utf16Chars = [];
for (var i = 0; i < sigBytes; i += 2) {
var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff);
utf16Chars.push(String.fromCharCode(codePoint));
}
return utf16Chars.join('');
},
/**
* Converts a UTF-16 LE string to a word array.
*
* @param {string} utf16Str The UTF-16 LE string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str);
*/
parse: function (utf16Str) {
// Shortcut
var utf16StrLength = utf16Str.length;
// Convert
var words = [];
for (var i = 0; i < utf16StrLength; i++) {
words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16));
}
return WordArray.create(words, utf16StrLength * 2);
}
};
function swapEndian(word) {
return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff);
}
}());
return CryptoJS.enc.Utf16;
}));
/***/ }),
/***/ "qWUW":
/*!***********************************************************************!*\
!*** ./node_modules/@ant-design/icons/lib/icons/CaretDownOutlined.js ***!
\***********************************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireWildcard = __webpack_require__(/*! @babel/runtime/helpers/interopRequireWildcard */ "284h");
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "TqRt");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/objectSpread2 */ "3tO9"));
var React = _interopRequireWildcard(__webpack_require__(/*! react */ "q1tI"));
var _CaretDownOutlined = _interopRequireDefault(__webpack_require__(/*! @ant-design/icons-svg/lib/asn/CaretDownOutlined */ "DL4k"));
var _AntdIcon = _interopRequireDefault(__webpack_require__(/*! ../components/AntdIcon */ "KQxl"));
// GENERATE BY ./scripts/generate.ts
// DON NOT EDIT IT MANUALLY
var CaretDownOutlined = function CaretDownOutlined(props, ref) {
return /*#__PURE__*/React.createElement(_AntdIcon.default, (0, _objectSpread2.default)((0, _objectSpread2.default)({}, props), {}, {
ref: ref,
icon: _CaretDownOutlined.default
}));
};
CaretDownOutlined.displayName = 'CaretDownOutlined';
var _default = /*#__PURE__*/React.forwardRef(CaretDownOutlined);
exports.default = _default;
/***/ }),
/***/ "qgvg":
/*!**************************************!*\
!*** ./src/assets/images/notice.gif ***!
\**************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports) {
module.exports = "data:image/gif;base64,R0lGODlhFAAQAOZVAD6Q33p6ezZto2VnaW5vcDuCxiYvNysvM1tdXzNij5eXlyg0QTA0OExOUWZnaS8zN19hYzFYf0Oi/Sg1QoeHh2JjZWZoaTdzrTRmljl5tzFZgDBWez6P3Tl4tjl8uzdxqWBiYys/VCUqL39/gHV2dy4yNScyPDJeiEpNTzk8P0CX6jc7PiYuNWlqaywwNDZtojAzNytDWScrLitAVUGb8Xl6eoWFhTp+wDNgjWRmZ4+QkFdZWzo9QIODgyo/Uzh3syg0QCczPmprbTRllW9wcSotMVJUVjZupDuEylBSVUGb8kxPUZGRkTd0rUGc82JkZUKe9j2M1zg7P4iIiEOj/yUpLQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh/wtYTVAgRGF0YVhNUDw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMTQ1IDc5LjE2MzQ5OSwgMjAxOC8wOC8xMy0xNjo0MDoyMiAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTkgKE1hY2ludG9zaCkiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6N0U3Nzk1NkY5QkRGMTFFQUIzQzFDQjY5MEVFODZDMDciIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6N0U3Nzk1NzA5QkRGMTFFQUIzQzFDQjY5MEVFODZDMDciPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDo3RTc3OTU2RDlCREYxMUVBQjNDMUNCNjkwRUU4NkMwNyIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDo3RTc3OTU2RTlCREYxMUVBQjNDMUNCNjkwRUU4NkMwNyIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PgH//v38+/r5+Pf29fTz8vHw7+7t7Ovq6ejn5uXk4+Lh4N/e3dzb2tnY19bV1NPS0dDPzs3My8rJyMfGxcTDwsHAv769vLu6ubi3trW0s7KxsK+urayrqqmop6alpKOioaCfnp2cm5qZmJeWlZSTkpGQj46NjIuKiYiHhoWEg4KBgH9+fXx7enl4d3Z1dHNycXBvbm1sa2ppaGdmZWRjYmFgX15dXFtaWVhXVlVUU1JRUE9OTUxLSklIR0ZFRENCQUA/Pj08Ozo5ODc2NTQzMjEwLy4tLCsqKSgnJiUkIyIhIB8eHRwbGhkYFxYVFBMSERAPDg0MCwoJCAcGBQQDAgEAACH5BAUyAFUALAAAAAAUABAAAAd5gFWCg4RSLoSIiVUPFlNEhAwDCIoyST1TUwGCBwM6AweJPCSYmJpVCAMMgykgFRUtFKSlilVCsreZtAS4sqaJu7yzisDBvhAKyBDEvL6Iy7jNhA7BwoklKA0NRiO30bRFOzakpqiqtItPsTWbA0wWoOcrOUuEMA6TgQAh+QQFMgBVACwAAAAAFAAQAAAHeIBVgoOEISaEiIlVExlUSIQLAgmKIidOVFQAggYCNAIGiTFRmJiaVQkCC4MzHxcXHhKkpYpVN7K3mbQFuLKmibu8s4rAwb4YpBjEvL6IyrjMhB3BwolBGxEROCq30LQsQ1CkpqiqtItNsRybAkpHoOY+PxqEQC+TgQA7"
/***/ }),
/***/ "qtz/":
/*!***********************************************!*\
!*** ./src/assets/images/competition/cla.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,iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAABHNCSVQICAgIfAhkiAAAAYNJREFUOE/tlE9OwlAQxr9p/LPUG8gR8ARiIsSd3ACWwAZuoJ7AukGX5QTWnUET6g08At4AlqLp+E21pDYFecREF77kpe+9zvzezLyZEXyOo5ZWxMONALvpmdNXMZ5tYz/yZWJ65HyMWkfP+Dl1guWE4xiHD9cS/Q5YFY8KhJ7gwtYiSCzJDv5v0uW99Gwli6kUaIyB52Fkayhnfgh8gstO4HVivZrFC9z/kVAUup8l/61QAM+0ePxNrMvMlh3Xxzsf9sWKZuGotjUi+MAV7JwYhVlR7WiTrvtZ11zILKIpG0Tlvi9PSUmzR4QsgNHrFgZ2sPHCahL0shW17AKrSgIDAoPjlpZiQZf7qYHJBY2FdaWQ89JurbW1ToEm9yd5sFnHi0Nlus1lgQbl6wnLaiAFf0l8RUTFYHglA7PijQrc1+nJxPoHvTMDsDlDQxQ9Aks5/WJwKmReEOh77Bl315KkHt/CekOX0y4r7N0LLXZ5tCLZf/A8KkkoWJaTdYtiyVvcvgOWneig6wGwigAAAABJRU5ErkJggg=="
/***/ }),
/***/ "qu8F":
/*!****************************************************!*\
!*** ./node_modules/crypto-js/mode-ctr-gladman.js ***!
\****************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory, undef) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"), __webpack_require__(/*! ./cipher-core */ "OLod"));
}
else {}
}(this, function (CryptoJS) {
/** @preserve
* Counter block mode compatible with Dr Brian Gladman fileenc.c
* derived from CryptoJS.mode.CTR
* Jan Hruby jhruby.web@gmail.com
*/
CryptoJS.mode.CTRGladman = (function () {
var CTRGladman = CryptoJS.lib.BlockCipherMode.extend();
function incWord(word)
{
if (((word >> 24) & 0xff) === 0xff) { //overflow
var b1 = (word >> 16)&0xff;
var b2 = (word >> 8)&0xff;
var b3 = word & 0xff;
if (b1 === 0xff) // overflow b1
{
b1 = 0;
if (b2 === 0xff)
{
b2 = 0;
if (b3 === 0xff)
{
b3 = 0;
}
else
{
++b3;
}
}
else
{
++b2;
}
}
else
{
++b1;
}
word = 0;
word += (b1 << 16);
word += (b2 << 8);
word += b3;
}
else
{
word += (0x01 << 24);
}
return word;
}
function incCounter(counter)
{
if ((counter[0] = incWord(counter[0])) === 0)
{
// encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8
counter[1] = incWord(counter[1]);
}
return counter;
}
var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var counter = this._counter;
// Generate keystream
if (iv) {
counter = this._counter = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
incCounter(counter);
var keystream = counter.slice(0);
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
CTRGladman.Decryptor = Encryptor;
return CTRGladman;
}());
return CryptoJS.mode.CTRGladman;
}));
/***/ }),
/***/ "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 _unsupportedIterableToArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./unsupportedIterableToArray */ "Qw5x");
function _createForOfIteratorHelper(o, allowArrayLike) {
var it;
if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
if (Array.isArray(o) || (it = Object(_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
};
/***/ }),
/***/ "ruvs":
/*!*****************************************************!*\
!*** ./src/components/Header/index.tsx + 8 modules ***!
\*****************************************************/
/*! exports provided: getCourseParam, default */
/*! exports used: default, getCourseParam */
/*! 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/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/regenerator/index.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./src/.umi-production/core/umiExports.ts */
/*! ModuleConcatenation bailout: Cannot concat with ./src/components/ImagesIcon/index.ts */
/*! ModuleConcatenation bailout: Cannot concat with ./src/service/home.ts */
/*! ModuleConcatenation bailout: Cannot concat with ./src/service/user.ts */
/*! ModuleConcatenation bailout: Cannot concat with ./src/utils/authority.ts */
/*! ModuleConcatenation bailout: Cannot concat with ./src/utils/env.ts */
/*! ModuleConcatenation bailout: Cannot concat with ./src/utils/util.tsx */
/*! ModuleConcatenation bailout: Cannot concat with ./src/utils/verifyLogin.tsx */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/button/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/button/style/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/checkbox/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/checkbox/style/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/dropdown/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/dropdown/style/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/input/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/input/style/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/layout/Sider.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/layout/layout.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/menu/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/menu/style/index.js */
/*! 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/antd/es/modal/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/modal/style/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/radio/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/radio/style/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./src/components/AuthModal/index.less?modules (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./src/components/Header/components/Join/index.less?modules (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./src/components/Header/components/User/index.less?modules (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./src/components/Header/index.less?modules (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/react-router-dom/esm/react-router-dom.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/react-router/esm/react-router.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/react/index.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./src/assets/images/cert/shimingrenzheng.png (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./src/assets/images/cert/zhiyerenzheng.png (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./src/components/HomeModal/jqr.png (<- Module is not an ECMAScript module) */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// EXPORTS
__webpack_require__.d(__webpack_exports__, "b", function() { return /* binding */ getCourseParam; });
// EXTERNAL MODULE: ./node_modules/antd/es/modal/style/index.js
var style = __webpack_require__("2qtc");
// EXTERNAL MODULE: ./node_modules/antd/es/modal/index.js + 19 modules
var modal = __webpack_require__("kLXV");
// 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);
// 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/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: ./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/input/style/index.js
var input_style = __webpack_require__("5NDa");
// EXTERNAL MODULE: ./node_modules/antd/es/input/index.js + 14 modules
var input = __webpack_require__("5rEg");
// EXTERNAL MODULE: ./node_modules/antd/es/style/index.less
var es_style = __webpack_require__("cIOH");
// EXTERNAL MODULE: ./node_modules/antd/es/layout/style/index.less
var layout_style = __webpack_require__("0XgM");
// CONCATENATED MODULE: ./node_modules/antd/es/layout/style/index.js
// EXTERNAL MODULE: ./node_modules/antd/es/layout/layout.js
var layout = __webpack_require__("PKem");
// EXTERNAL MODULE: ./node_modules/antd/es/layout/Sider.js + 1 modules
var Sider = __webpack_require__("ZX9x");
// CONCATENATED MODULE: ./node_modules/antd/es/layout/index.js
layout["b" /* default */].Sider = Sider["b" /* default */];
/* harmony default export */ var es_layout = (layout["b" /* default */]);
// EXTERNAL MODULE: ./node_modules/react/index.js
var react = __webpack_require__("q1tI");
var react_default = /*#__PURE__*/__webpack_require__.n(react);
// EXTERNAL MODULE: ./node_modules/react-router/esm/react-router.js
var react_router = __webpack_require__("Ty5D");
// EXTERNAL MODULE: ./node_modules/react-router-dom/esm/react-router-dom.js
var react_router_dom = __webpack_require__("55Ip");
// EXTERNAL MODULE: ./src/.umi-production/core/umiExports.ts + 19 modules
var umiExports = __webpack_require__("9kvl");
// EXTERNAL MODULE: ./src/components/ImagesIcon/index.ts
var ImagesIcon = __webpack_require__("lzim");
// EXTERNAL MODULE: ./src/components/Header/index.less?modules
var Headermodules = __webpack_require__("xrsn");
var Headermodules_default = /*#__PURE__*/__webpack_require__.n(Headermodules);
// EXTERNAL MODULE: ./src/components/Header/search-input.less
var search_input = __webpack_require__("1Sn+");
// EXTERNAL MODULE: ./node_modules/antd/es/dropdown/style/index.js
var dropdown_style = __webpack_require__("qVdP");
// EXTERNAL MODULE: ./node_modules/antd/es/dropdown/index.js
var dropdown = __webpack_require__("jsC+");
// EXTERNAL MODULE: ./node_modules/antd/es/menu/style/index.js
var menu_style = __webpack_require__("lUTK");
// EXTERNAL MODULE: ./node_modules/antd/es/menu/index.js + 16 modules
var menu = __webpack_require__("BvKs");
// 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 es_message = __webpack_require__("tsqr");
// EXTERNAL MODULE: ./node_modules/antd/es/radio/style/index.js
var radio_style = __webpack_require__("7Kak");
// EXTERNAL MODULE: ./node_modules/antd/es/radio/index.js + 5 modules
var es_radio = __webpack_require__("9yH6");
// EXTERNAL MODULE: ./src/service/home.ts
var home = __webpack_require__("6CvP");
// EXTERNAL MODULE: ./src/components/Header/components/Join/index.less?modules
var Joinmodules = __webpack_require__("6Fuo");
var Joinmodules_default = /*#__PURE__*/__webpack_require__.n(Joinmodules);
// CONCATENATED MODULE: ./src/components/Header/components/Join/JoinProjectModal.tsx
var Type;
(function (Type) {
Type["Manager"] = "manager";
Type["Developer"] = "developer";
Type["Reporter"] = "reporter";
})(Type || (Type = {}));
var JoinProjectModal_JoinProjectModal = function JoinProjectModal(_ref) {
var visible = _ref.visible,
_ref$onCancel = _ref.onCancel,
onCancel = _ref$onCancel === void 0 ? function () {} : _ref$onCancel;
var _useState = Object(react["useState"])(),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
inputValue = _useState2[0],
setInputValue = _useState2[1];
var _useState3 = Object(react["useState"])("developer"),
_useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
radioValue = _useState4[0],
setRadioValue = _useState4[1];
var _useState5 = Object(react["useState"])(false),
_useState6 = Object(slicedToArray["a" /* default */])(_useState5, 2),
isLoading = _useState6[0],
setIsLoading = _useState6[1];
var handleOk = /*#__PURE__*/function () {
var _ref2 = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee() {
var res;
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (inputValue) {
_context.next = 3;
break;
}
es_message["b" /* default */].info('请输入开发项目邀请码!');
return _context.abrupt("return");
case 3:
if (!(inputValue.length !== 6)) {
_context.next = 6;
break;
}
es_message["b" /* default */].info('请输入6位项目邀请码');
return _context.abrupt("return");
case 6:
if (radioValue) {
_context.next = 9;
break;
}
es_message["b" /* default */].info('请选择一个身份!');
return _context.abrupt("return");
case 9:
setIsLoading(true);
_context.next = 12;
return Object(home["e" /* projectApplies */])({
applied_project: {
code: inputValue,
role: radioValue
}
});
case 12:
res = _context.sent;
setIsLoading(false);
handleCancel(); // const mapping: any = {
// 1: "您输入的邀请码错误",
// 2: "您已经是该项目成员",
// 3: "请选择一个角色",
// 4: "您的申请已提交,请等待项目管理员审批",
// 5: "您已经申请加入该项目了,请耐心等待",
// 6: "您已成功加入项目",
// }
// if (res.status !== 0 ) {
// message.info(res.message);
// return;
// }
// if (res.status === 0) {
// if (radioValue === "reporter") {
// message.success('您加入项目成功!');
// trackEvent(['开发项目', '加入项目成功'])
// history.push(`/projects/${res?.project_id}`);
// } else {
// trackEvent(['开发项目', '加入项目等待审批'])
// message.success('您的申请已提交,请等待项目管理员审批!');
// }
// return;
// }
es_message["b" /* default */].info(res.message);
return _context.abrupt("return");
case 17:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function handleOk() {
return _ref2.apply(this, arguments);
};
}();
var handleCancel = /*#__PURE__*/function () {
var _ref3 = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee2() {
return regenerator_default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
onCancel();
case 1:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
return function handleCancel() {
return _ref3.apply(this, arguments);
};
}();
return /*#__PURE__*/react_default.a.createElement(react_default.a.Fragment, null, /*#__PURE__*/react_default.a.createElement(modal["a" /* default */], {
centered: true,
keyboard: false,
closable: true,
title: "\u52A0\u5165\u9879\u76EE",
visible: visible,
confirmLoading: isLoading,
onOk: handleOk,
onCancel: handleCancel,
wrapClassName: Joinmodules_default.a.joinModal
}, /*#__PURE__*/react_default.a.createElement("div", {
className: "tc"
}, /*#__PURE__*/react_default.a.createElement("div", null, /*#__PURE__*/react_default.a.createElement("span", null, "\u9879\u76EE\u9080\u8BF7\u7801\uFF1A"), /*#__PURE__*/react_default.a.createElement(input["a" /* default */], {
placeholder: "\u8BF7\u8F93\u51656\u4F4D\u5F00\u53D1\u9879\u76EE\u9080\u8BF7\u7801",
style: {
width: 270
},
value: inputValue,
onChange: function onChange(e) {
if (e.target.value.length >= 7) {
es_message["b" /* default */].info('请输入6位开发项目邀请码');
return;
}
setInputValue(e.target.value);
}
})), /*#__PURE__*/react_default.a.createElement("div", {
className: "mt30 font14"
}, /*#__PURE__*/react_default.a.createElement("span", {
className: "mr5"
}, "\u9009\u62E9\u89D2\u8272\uFF1A"), /*#__PURE__*/react_default.a.createElement(es_radio["a" /* default */].Group, {
value: radioValue,
onChange: function onChange(e) {
return setRadioValue(e.target.value);
}
}, /*#__PURE__*/react_default.a.createElement(es_radio["a" /* default */], {
value: Type.Manager
}, "\u7BA1\u7406\u8005"), /*#__PURE__*/react_default.a.createElement(es_radio["a" /* default */], {
value: Type.Developer
}, "\u5F00\u53D1\u8005"), /*#__PURE__*/react_default.a.createElement(es_radio["a" /* default */], {
value: Type.Reporter
}, "\u62A5\u544A\u8005"))))));
};
/* harmony default export */ var Join_JoinProjectModal = (JoinProjectModal_JoinProjectModal);
// EXTERNAL MODULE: ./node_modules/antd/es/checkbox/style/index.js
var checkbox_style = __webpack_require__("sRBo");
// EXTERNAL MODULE: ./node_modules/antd/es/checkbox/index.js + 2 modules
var es_checkbox = __webpack_require__("kaz8");
// EXTERNAL MODULE: ./src/assets/images/cert/shimingrenzheng.png
var shimingrenzheng = __webpack_require__("3wET");
var shimingrenzheng_default = /*#__PURE__*/__webpack_require__.n(shimingrenzheng);
// EXTERNAL MODULE: ./src/assets/images/cert/zhiyerenzheng.png
var zhiyerenzheng = __webpack_require__("bUJZ");
var zhiyerenzheng_default = /*#__PURE__*/__webpack_require__.n(zhiyerenzheng);
// EXTERNAL MODULE: ./src/components/AuthModal/index.less?modules
var AuthModalmodules = __webpack_require__("Ct/S");
var AuthModalmodules_default = /*#__PURE__*/__webpack_require__.n(AuthModalmodules);
// CONCATENATED MODULE: ./src/components/AuthModal/index.tsx
var AuthModal_AuthModal = function AuthModal(_ref) {
var visible = _ref.visible,
occupationValue = _ref.occupationValue,
_ref$onCancel = _ref.onCancel,
_onCancel = _ref$onCancel === void 0 ? function () {} : _ref$onCancel;
var renderOccupationAuth = function renderOccupationAuth() {
return /*#__PURE__*/react_default.a.createElement("div", {
className: AuthModalmodules_default.a.flexColumn
}, /*#__PURE__*/react_default.a.createElement("img", {
className: AuthModalmodules_default.a.img,
src: zhiyerenzheng_default.a
}), /*#__PURE__*/react_default.a.createElement("span", {
className: AuthModalmodules_default.a.content
}, "\u672A\u804C\u4E1A\u8BA4\u8BC1"));
};
var renderAutonymAuth = function renderAutonymAuth() {
return /*#__PURE__*/react_default.a.createElement("div", {
className: AuthModalmodules_default.a.flexColumn
}, /*#__PURE__*/react_default.a.createElement("img", {
className: AuthModalmodules_default.a.img,
src: shimingrenzheng_default.a
}), /*#__PURE__*/react_default.a.createElement("span", {
className: AuthModalmodules_default.a.content
}, "\u672A\u5B9E\u540D\u8BA4\u8BC1"));
};
var renderContent = function renderContent() {
if (occupationValue === 3) {
return /*#__PURE__*/react_default.a.createElement(react_default.a.Fragment, null, renderAutonymAuth(), renderOccupationAuth());
}
if (occupationValue === 2) {
return renderOccupationAuth();
}
return renderAutonymAuth();
};
return /*#__PURE__*/react_default.a.createElement(modal["a" /* default */], {
centered: true,
keyboard: false,
closable: false,
destroyOnClose: true,
visible: visible,
title: "\u56E0\u4E3A\u4EE5\u4E0B\u539F\u56E0\uFF0C\u60A8\u6682\u65F6\u4E0D\u80FD\u8FDB\u884C\u64CD\u4F5C",
okText: "\u7ACB\u5373\u8BA4\u8BC1",
cancelText: "\u53D6\u6D88",
width: "600px",
onOk: function onOk() {
_onCancel();
umiExports["c" /* history */].push("/account/certification");
},
onCancel: function onCancel() {
_onCancel();
}
}, /*#__PURE__*/react_default.a.createElement("div", {
className: AuthModalmodules_default.a.tilte
}, "\u8BF7\u5728\u5B8C\u6210\u6761\u4EF6\u540E\u91CD\u8BD5"), /*#__PURE__*/react_default.a.createElement("div", {
className: AuthModalmodules_default.a.flexRow
}, renderContent()));
};
/* harmony default export */ var components_AuthModal = (Object(umiExports["a" /* connect */])(function (_ref2) {
var paperlibrary = _ref2.paperlibrary,
loading = _ref2.loading,
globalSetting = _ref2.globalSetting;
return {
paperlibrary: paperlibrary,
globalSetting: globalSetting,
loading: loading.effects
};
})(AuthModal_AuthModal));
// EXTERNAL MODULE: ./src/utils/util.tsx + 6 modules
var util = __webpack_require__("1vsH");
// CONCATENATED MODULE: ./src/components/Header/components/Join/JoinClassroomModal.tsx
var JoinClassroomModal_Type;
(function (Type) {
Type[Type["Professor"] = 1] = "Professor";
Type[Type["AssistantProfessor"] = 2] = "AssistantProfessor";
Type[Type["Student"] = 3] = "Student";
})(JoinClassroomModal_Type || (JoinClassroomModal_Type = {}));
var JoinClassroomModal_JoinClassroomModal = function JoinClassroomModal(_ref) {
var visible = _ref.visible,
user = _ref.user,
_ref$onCancel = _ref.onCancel,
onCancel = _ref$onCancel === void 0 ? function () {} : _ref$onCancel;
var _useState = Object(react["useState"])(),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
inputValue = _useState2[0],
setInputValue = _useState2[1];
var _useState3 = Object(react["useState"])([]),
_useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
checkedList = _useState4[0],
setCheckedList = _useState4[1];
var _useState5 = Object(react["useState"])(false),
_useState6 = Object(slicedToArray["a" /* default */])(_useState5, 2),
isLoading = _useState6[0],
setIsLoading = _useState6[1];
var _useState7 = Object(react["useState"])(false),
_useState8 = Object(slicedToArray["a" /* default */])(_useState7, 2),
visibleAuth = _useState8[0],
setVisibleAuth = _useState8[1];
var _useState9 = Object(react["useState"])(),
_useState10 = Object(slicedToArray["a" /* default */])(_useState9, 2),
occupationValue = _useState10[0],
setOccupationValue = _useState10[1];
Object(react["useEffect"])(function () {
var _user$userInfo;
if (user === null || user === void 0 ? void 0 : (_user$userInfo = user.userInfo) === null || _user$userInfo === void 0 ? void 0 : _user$userInfo.identity) {
var _user$userInfo2;
setCheckedList([(user === null || user === void 0 ? void 0 : (_user$userInfo2 = user.userInfo) === null || _user$userInfo2 === void 0 ? void 0 : _user$userInfo2.identity) === 'student' ? 3 : 1]);
}
}, [user]);
var handlePrompt = function handlePrompt(course_id, message) {
if (checkedList.includes(JoinClassroomModal_Type.Professor)) {
modal["a" /* default */].confirm({
centered: true,
okText: '确定',
cancelText: '取消',
title: '提示',
content: /*#__PURE__*/react_default.a.createElement("div", {
className: "tc"
}, message || "申请已提交,请等待审核"),
onOk: function onOk() {
umiExports["c" /* history */].push("/classrooms/".concat(course_id, "/students"));
}
});
return;
}
umiExports["c" /* history */].push("/classrooms/".concat(course_id, "/students"));
};
var handleOk = /*#__PURE__*/function () {
var _ref2 = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee() {
var res;
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (inputValue) {
_context.next = 3;
break;
}
es_message["b" /* default */].info('邀请码不能为空');
return _context.abrupt("return");
case 3:
setIsLoading(true);
_context.next = 6;
return Object(home["c" /* applyToJoinCourse */])({
invite_code: inputValue,
professor: checkedList.includes(JoinClassroomModal_Type.Professor) ? 1 : null,
assistant_professor: checkedList.includes(JoinClassroomModal_Type.AssistantProfessor) ? 1 : null,
student: checkedList.includes(JoinClassroomModal_Type.Student) ? 1 : null
});
case 6:
res = _context.sent;
setIsLoading(false);
if (!((res === null || res === void 0 ? void 0 : res.status) === -2)) {
_context.next = 22;
break;
}
handleCancel();
if (!(res.message === "该课堂要求成员完成实名认证")) {
_context.next = 14;
break;
}
setVisibleAuth(true);
setOccupationValue(1);
return _context.abrupt("return");
case 14:
if (!(res.message === "该课堂要求成员完成职业认证")) {
_context.next = 18;
break;
}
setVisibleAuth(true);
setOccupationValue(2);
return _context.abrupt("return");
case 18:
if (!(res.message === "该课堂要求成员完成实名和职业认证")) {
_context.next = 22;
break;
}
setVisibleAuth(true);
setOccupationValue(3);
return _context.abrupt("return");
case 22:
if (!((res === null || res === void 0 ? void 0 : res.status) === 0)) {
_context.next = 27;
break;
}
Object(util["s" /* trackEvent */])(['教学课堂', '首页', '加入课堂']);
handleCancel(); // message.info(res.message);
(res === null || res === void 0 ? void 0 : res.course_id) && handlePrompt(res.course_id, res.message);
return _context.abrupt("return");
case 27:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function handleOk() {
return _ref2.apply(this, arguments);
};
}();
var handleCancel = /*#__PURE__*/function () {
var _ref3 = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee2() {
return regenerator_default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
onCancel();
case 1:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
return function handleCancel() {
return _ref3.apply(this, arguments);
};
}();
return /*#__PURE__*/react_default.a.createElement(react_default.a.Fragment, null, /*#__PURE__*/react_default.a.createElement(modal["a" /* default */], {
centered: true,
keyboard: false,
closable: false,
title: "\u52A0\u5165\u8BFE\u5802",
visible: visible,
confirmLoading: isLoading,
onOk: handleOk,
onCancel: handleCancel
}, /*#__PURE__*/react_default.a.createElement("div", {
className: "tc"
}, /*#__PURE__*/react_default.a.createElement("div", null, /*#__PURE__*/react_default.a.createElement("span", null, "\u8BFE\u5802\u9080\u8BF7\u7801\uFF1A"), /*#__PURE__*/react_default.a.createElement(input["a" /* default */], {
placeholder: "\u8BF7\u8F93\u51655\u4F4D\u8BFE\u5802\u9080\u8BF7\u7801\u62166\u4F4D\u5206\u73ED\u9080\u8BF7\u7801",
style: {
width: 270
},
value: inputValue,
onChange: function onChange(e) {
if (e.target.value.length >= 7) {
es_message["b" /* default */].info('请输入5位课堂邀请码或6位分班邀请码');
return;
}
setInputValue(e.target.value);
}
})), /*#__PURE__*/react_default.a.createElement("div", {
className: "mt10 font14"
}, /*#__PURE__*/react_default.a.createElement("span", null, "\u8EAB\u4EFD\uFF1A"), /*#__PURE__*/react_default.a.createElement(es_checkbox["a" /* default */].Group, {
value: checkedList,
onChange: function onChange(value) {
return setCheckedList(value);
}
}, /*#__PURE__*/react_default.a.createElement(es_checkbox["a" /* default */], {
value: JoinClassroomModal_Type.Professor,
disabled: checkedList.includes(2)
}, "\u6559\u5E08"), /*#__PURE__*/react_default.a.createElement(es_checkbox["a" /* default */], {
value: JoinClassroomModal_Type.AssistantProfessor,
disabled: checkedList.includes(1)
}, "\u52A9\u6559"), /*#__PURE__*/react_default.a.createElement(es_checkbox["a" /* default */], {
value: JoinClassroomModal_Type.Student
}, "\u5B66\u751F/\u53C2\u8D5B\u8005"))))), /*#__PURE__*/react_default.a.createElement(components_AuthModal, {
visible: visibleAuth,
onCancel: function onCancel() {
return setVisibleAuth(false);
},
occupationValue: occupationValue
}));
};
/* harmony default export */ var Join_JoinClassroomModal = (Object(umiExports["a" /* connect */])(function (_ref4) {
var user = _ref4.user;
return {
user: user
};
})(JoinClassroomModal_JoinClassroomModal));
// EXTERNAL MODULE: ./src/utils/verifyLogin.tsx
var verifyLogin = __webpack_require__("NLgs");
// CONCATENATED MODULE: ./src/components/Header/components/Join/index.tsx
var VerifyType;
(function (VerifyType) {
VerifyType["Projects"] = "projects";
VerifyType["Shixuns"] = "shixuns";
VerifyType["Classrooms"] = "classrooms";
})(VerifyType || (VerifyType = {}));
var NavType;
(function (NavType) {
NavType["Classrooms"] = "classrooms";
NavType["Shixuns"] = "shixuns";
NavType["Paths"] = "paths";
NavType["Projects"] = "projects";
NavType["Videos"] = "videos";
NavType["Topics"] = "topics";
})(NavType || (NavType = {}));
var Join_Join = function Join(_ref) {
var _find, _globalSetting$settin, _find2, _globalSetting$settin2, _find3, _globalSetting$settin3, _globalSetting$settin4;
var homePage = _ref.homePage,
user = _ref.user,
globalSetting = _ref.globalSetting,
loading = _ref.loading,
dispatch = _ref.dispatch,
location = _ref.location,
props = Object(objectWithoutProperties["a" /* default */])(_ref, ["homePage", "user", "globalSetting", "loading", "dispatch", "location"]);
var _useState = Object(react["useState"])(),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
visibleJoinClassroom = _useState2[0],
setVisibleJoinClassroom = _useState2[1];
var _useState3 = Object(react["useState"])(),
_useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
visibleJoinProject = _useState4[0],
setVisibleJoinProject = _useState4[1];
var handleJoinVerify = function handleJoinVerify(type) {
// if (!handleVerify(dispatch)) {
// return;
// }
// if (type === VerifyType.Projects && !user.userInfo?.email) {
// message.info('请先绑定邮箱,谢谢');
// return;
// }
// if (type === VerifyType.Classrooms) {
// setVisibleJoinClassroom(true);
// } else if (type === VerifyType.Projects) {
// setVisibleJoinProject(true);
// }
setVisibleJoinProject(true);
};
var handleAddVerify = function handleAddVerify(url, type) {
var _user$userInfo;
if (!Object(verifyLogin["b" /* handleVerify */])(dispatch)) {
return;
}
if (type === VerifyType.Projects && !((_user$userInfo = user.userInfo) === null || _user$userInfo === void 0 ? void 0 : _user$userInfo.email)) {
es_message["b" /* default */].info('请先绑定邮箱,谢谢');
return;
}
if (type === VerifyType.Shixuns && !Object(verifyLogin["a" /* handleCanShixunAddModal */])()) {
return;
}
url && (window.location.href = url);
};
var isClassroomsHidden = (_find = (((_globalSetting$settin = globalSetting.setting) === null || _globalSetting$settin === void 0 ? void 0 : _globalSetting$settin.navbar) || []).find(function (item) {
return item.link === "/".concat(NavType.Classrooms);
})) === null || _find === void 0 ? void 0 : _find.hidden;
var isShixunsHidden = (_find2 = (((_globalSetting$settin2 = globalSetting.setting) === null || _globalSetting$settin2 === void 0 ? void 0 : _globalSetting$settin2.navbar) || []).find(function (item) {
return item.link === "/".concat(NavType.Shixuns);
})) === null || _find2 === void 0 ? void 0 : _find2.hidden;
var isPathsHidden = (_find3 = (((_globalSetting$settin3 = globalSetting.setting) === null || _globalSetting$settin3 === void 0 ? void 0 : _globalSetting$settin3.navbar) || []).find(function (item) {
return item.link === "/".concat(NavType.Paths);
})) === null || _find3 === void 0 ? void 0 : _find3.hidden;
if (globalSetting === null || globalSetting === void 0 ? void 0 : (_globalSetting$settin4 = globalSetting.setting) === null || _globalSetting$settin4 === void 0 ? void 0 : _globalSetting$settin4.is_local) {
var _user$userInfo2;
if (!(user === null || user === void 0 ? void 0 : (_user$userInfo2 = user.userInfo) === null || _user$userInfo2 === void 0 ? void 0 : _user$userInfo2.is_shixun_marker)) isShixunsHidden = true;
} // const JoinOverlay = (joinProps: any) => {
// return <>
// <Row justify="space-around" className="pt5 pb5">
// <Col className={styles.joinCol}>
// {
// user.userInfo?.user_identity !== '学生' &&
// !isClassroomsHidden &&
// <Menu.Item {...joinProps}>
// <a onClick={() => handleAddVerify('/classrooms/new')}>
// {
// user.userInfo?.main_site ?
// '新建教学课堂' :
// '新建课堂'
// }
// </a>
// </Menu.Item>
// }
// {
// !isShixunsHidden &&
// <Menu.Item {...joinProps}>
// <a onClick={() => handleAddVerify('/shixuns/new', VerifyType.Shixuns)}>
// 新建实践项目
// </a>
// </Menu.Item>
// }
// {
// (
// user.userInfo?.main_site && user.navigationInfo?.top ||
// (
// !user.userInfo?.main_site && user.navigationInfo?.top && !isPathsHidden &&
// (user.userInfo?.admin || user.userInfo?.is_teacher || user.userInfo?.business)
// )
// ) &&
// <Menu.Item {...joinProps}>
// <a onClick={() => handleAddVerify('/paths/new')}>新建实践课程</a>
// </Menu.Item>
// }
// {
// !globalSetting?.setting?.is_local &&
// user.userInfo?.main_site &&
// <Menu.Item {...joinProps}>
// <a onClick={() => handleAddVerify(`${user.navigationInfo?.top?.old_url}/projects/new`, VerifyType.Projects)}>新建开发项目</a>
// </Menu.Item>
// }
// </Col>
// <Col>
// <div className={styles.joinBoard}></div>
// </Col>
// <Col className={styles.joinCol}>
// {
// !isClassroomsHidden &&
// // user.userInfo?.main_site &&
// <Menu.Item {...joinProps}>
// <a onClick={() => handleJoinVerify(VerifyType.Classrooms)}>
// {
// user.userInfo?.main_site ?
// '加入教学课堂' :
// '加入课堂'
// }
// </a>
// </Menu.Item>
// }
// {
// user.userInfo?.main_site &&
// !globalSetting?.setting?.is_local &&
// <Menu.Item {...joinProps}>
// <a onClick={() => handleJoinVerify(VerifyType.Projects)}>
// 加入开发项目
// </a>
// </Menu.Item>
// }
// </Col>
// </Row>
// </>
// }
var JoinOverlay = function JoinOverlay(list) {
return /*#__PURE__*/react_default.a.createElement(react_default.a.Fragment, null, /*#__PURE__*/react_default.a.createElement("div", {
className: Joinmodules_default.a.dropdownFlex
}, /*#__PURE__*/react_default.a.createElement(menu["a" /* default */], null, list.map(function (item, key) {
return item.name !== "加入课堂" && item.name !== "加入开发项目" && /*#__PURE__*/react_default.a.createElement(menu["a" /* default */].Item, {
key: item.name + key
}, /*#__PURE__*/react_default.a.createElement("a", {
onClick: function onClick() {
window.location.href = item.url;
}
}, item.name));
}), /*#__PURE__*/react_default.a.createElement(menu["a" /* default */].Item, null, /*#__PURE__*/react_default.a.createElement("a", {
onClick: function onClick() {
return handleJoinVerify(VerifyType.Projects);
}
}, "\u52A0\u5165\u9879\u76EE")))));
};
return /*#__PURE__*/react_default.a.createElement("section", null, /*#__PURE__*/react_default.a.createElement(dropdown["a" /* default */], {
overlay: function overlay() {
var _globalSetting$settin5;
return JoinOverlay(globalSetting === null || globalSetting === void 0 ? void 0 : (_globalSetting$settin5 = globalSetting.setting) === null || _globalSetting$settin5 === void 0 ? void 0 : _globalSetting$settin5.add);
},
placement: "bottomRight"
}, /*#__PURE__*/react_default.a.createElement("span", {
style: {
lineHeight: 'inherit'
},
className: "iconfont icon-tianjiafangda c-white font18 current ml15 mr15"
})), /*#__PURE__*/react_default.a.createElement(Join_JoinClassroomModal, {
visible: visibleJoinClassroom,
onCancel: function onCancel() {
return setVisibleJoinClassroom(false);
}
}), /*#__PURE__*/react_default.a.createElement(Join_JoinProjectModal, {
visible: visibleJoinProject,
onCancel: function onCancel() {
return setVisibleJoinProject(false);
}
}));
};
/* harmony default export */ var components_Join = (Object(umiExports["a" /* connect */])(function (_ref2) {
var homePage = _ref2.homePage,
loading = _ref2.loading,
user = _ref2.user,
globalSetting = _ref2.globalSetting;
return {
homePage: homePage,
user: user,
globalSetting: globalSetting,
loading: loading.models.index
};
})(Join_Join));
// EXTERNAL MODULE: ./src/components/Header/components/User/index.less?modules
var Usermodules = __webpack_require__("vToQ");
var Usermodules_default = /*#__PURE__*/__webpack_require__.n(Usermodules);
// EXTERNAL MODULE: ./src/utils/authority.ts
var authority = __webpack_require__("xKgJ");
// EXTERNAL MODULE: ./src/service/user.ts
var service_user = __webpack_require__("jb+D");
// EXTERNAL MODULE: ./src/utils/env.ts + 1 modules
var env = __webpack_require__("m3rI");
// CONCATENATED MODULE: ./src/components/Header/components/User/index.tsx
var getCookie = function getCookie(key) {
var arr,
reg = RegExp('(^| )' + key + '=([^;]+)(;|$)');
if (arr = document.cookie.match(reg)) //["username=liuwei;", "", "liuwei", ";"]
return decodeURIComponent(arr[2]);else return null;
};
var delCookie = function delCookie(name) {
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval = getCookie(name);
if (cval != null) {
document.cookie = name + '=' + cval + ';expires=' + exp.toGMTString();
}
};
var User_NavType;
(function (NavType) {
NavType["Classrooms"] = "classrooms";
NavType["Shixuns"] = "shixuns";
NavType["Paths"] = "paths";
NavType["Projects"] = "projects";
NavType["Videos"] = "videos";
NavType["Topics"] = "topics";
})(User_NavType || (User_NavType = {}));
var User_User = function User(_ref) {
var _find, _globalSetting$settin, _find2, _globalSetting$settin2, _find3, _globalSetting$settin3, _user$userInfo, _user$userInfo2, _user$userInfo3, _user$userInfo4, _user$userInfo5;
var homePage = _ref.homePage,
user = _ref.user,
globalSetting = _ref.globalSetting,
loading = _ref.loading,
dispatch = _ref.dispatch,
shixunHomeworks = _ref.shixunHomeworks,
location = _ref.location,
_ref$payload = _ref.payload,
payload = _ref$payload === void 0 ? {} : _ref$payload,
props = Object(objectWithoutProperties["a" /* default */])(_ref, ["homePage", "user", "globalSetting", "loading", "dispatch", "shixunHomeworks", "location", "payload"]);
var isClassroomsHidden = (_find = (((_globalSetting$settin = globalSetting.setting) === null || _globalSetting$settin === void 0 ? void 0 : _globalSetting$settin.navbar) || []).find(function (item) {
return item.link === "/".concat(User_NavType.Classrooms);
})) === null || _find === void 0 ? void 0 : _find.hidden;
var isShixunsHidden = (_find2 = (((_globalSetting$settin2 = globalSetting.setting) === null || _globalSetting$settin2 === void 0 ? void 0 : _globalSetting$settin2.navbar) || []).find(function (item) {
return item.link === "/".concat(User_NavType.Shixuns);
})) === null || _find2 === void 0 ? void 0 : _find2.hidden;
var isPathsHidden = (_find3 = (((_globalSetting$settin3 = globalSetting.setting) === null || _globalSetting$settin3 === void 0 ? void 0 : _globalSetting$settin3.navbar) || []).find(function (item) {
return item.link === "/".concat(User_NavType.Paths);
})) === null || _find3 === void 0 ? void 0 : _find3.hidden;
var isPaperlibraryShow = ((_user$userInfo = user.userInfo) === null || _user$userInfo === void 0 ? void 0 : _user$userInfo.admin) || ((_user$userInfo2 = user.userInfo) === null || _user$userInfo2 === void 0 ? void 0 : _user$userInfo2.business) || ((_user$userInfo3 = user.userInfo) === null || _user$userInfo3 === void 0 ? void 0 : _user$userInfo3.is_shixun_marker) || ((_user$userInfo4 = user.userInfo) === null || _user$userInfo4 === void 0 ? void 0 : _user$userInfo4.is_teacher) || ((_user$userInfo5 = user.userInfo) === null || _user$userInfo5 === void 0 ? void 0 : _user$userInfo5.user_identity) !== '学生';
var DropdownMenu = function DropdownMenu() {
if (Object(util["b" /* checkIsClientExam */])()) {
return /*#__PURE__*/react_default.a.createElement(menu["a" /* default */], {
className: "".concat(Usermodules_default.a.rightMenu, " ").concat(Usermodules_default.a.menuWrap)
}, /*#__PURE__*/react_default.a.createElement(menu["a" /* default */].Item, null, /*#__PURE__*/react_default.a.createElement(react_router_dom["a" /* Link */], {
to: "/account/profile"
}, "\u8D26\u53F7\u7BA1\u7406")));
} else {
var _user$userInfo6, _user$userInfo7, _user$userInfo8, _user$userInfo9, _user$userInfo10, _user$userInfo11, _user$userInfo12, _globalSetting$settin4, _user$userInfo13, _user$userInfo14, _user$navigationInfo, _user$navigationInfo$, _user$navigationInfo2, _user$navigationInfo3, _user$navigationInfo4, _user$navigationInfo5, _user$navigationInfo6, _user$navigationInfo7, _user$navigationInfo8, _user$navigationInfo9, _user$navigationInfo10, _user$navigationInfo11;
return /*#__PURE__*/react_default.a.createElement(menu["a" /* default */], {
className: "".concat(Usermodules_default.a.rightMenu, " ").concat(Usermodules_default.a.menuWrap)
}, /*#__PURE__*/react_default.a.createElement(menu["a" /* default */].Item, null, /*#__PURE__*/react_default.a.createElement(react_router_dom["a" /* Link */], {
to: "/users/".concat((_user$userInfo6 = user.userInfo) === null || _user$userInfo6 === void 0 ? void 0 : _user$userInfo6.login, "/classrooms")
}, "\u6211\u7684\u4E2A\u4EBA\u4E3B\u9875")), !isClassroomsHidden && /*#__PURE__*/react_default.a.createElement(menu["a" /* default */].Item, null, /*#__PURE__*/react_default.a.createElement(react_router_dom["a" /* Link */], {
to: "/users/".concat((_user$userInfo7 = user.userInfo) === null || _user$userInfo7 === void 0 ? void 0 : _user$userInfo7.login, "/classrooms")
}, ((_user$userInfo8 = user.userInfo) === null || _user$userInfo8 === void 0 ? void 0 : _user$userInfo8.main_site) ? '我的教学课堂' : '我的课堂')), !isShixunsHidden && /*#__PURE__*/react_default.a.createElement(menu["a" /* default */].Item, null, /*#__PURE__*/react_default.a.createElement(react_router_dom["a" /* Link */], {
to: "/users/".concat((_user$userInfo9 = user.userInfo) === null || _user$userInfo9 === void 0 ? void 0 : _user$userInfo9.login, "/shixuns")
}, "\u6211\u7684\u5B9E\u8DF5\u9879\u76EE")), !isPathsHidden && /*#__PURE__*/react_default.a.createElement(menu["a" /* default */].Item, null, /*#__PURE__*/react_default.a.createElement(react_router_dom["a" /* Link */], {
to: "/users/".concat((_user$userInfo10 = user.userInfo) === null || _user$userInfo10 === void 0 ? void 0 : _user$userInfo10.login, "/paths")
}, ((_user$userInfo11 = user.userInfo) === null || _user$userInfo11 === void 0 ? void 0 : _user$userInfo11.main_site) ? '我的实践课程' : '我的课程')), ((_user$userInfo12 = user.userInfo) === null || _user$userInfo12 === void 0 ? void 0 : _user$userInfo12.main_site) && !((_globalSetting$settin4 = globalSetting.setting) === null || _globalSetting$settin4 === void 0 ? void 0 : _globalSetting$settin4.is_local) && /*#__PURE__*/react_default.a.createElement(menu["a" /* default */].Item, null, /*#__PURE__*/react_default.a.createElement(react_router_dom["a" /* Link */], {
to: "/users/".concat((_user$userInfo13 = user.userInfo) === null || _user$userInfo13 === void 0 ? void 0 : _user$userInfo13.login, "/projects")
}, "\u6211\u7684\u5F00\u53D1\u9879\u76EE")), /*#__PURE__*/react_default.a.createElement(menu["a" /* default */].Item, null, /*#__PURE__*/react_default.a.createElement(react_router_dom["a" /* Link */], {
to: "/users/".concat((_user$userInfo14 = user.userInfo) === null || _user$userInfo14 === void 0 ? void 0 : _user$userInfo14.login, "/teach-group")
}, "\u6211\u7684\u6559\u7814\u56E2\u961F")), /*#__PURE__*/react_default.a.createElement(menu["a" /* default */].Item, null, /*#__PURE__*/react_default.a.createElement("a", {
onClick: function onClick() {
if (!Object(verifyLogin["b" /* handleVerify */])(dispatch)) {
return;
}
umiExports["c" /* history */].push("/problemset");
}
}, "\u8BD5\u9898\u5E93")), isPaperlibraryShow && /*#__PURE__*/react_default.a.createElement(menu["a" /* default */].Item, null, /*#__PURE__*/react_default.a.createElement("a", {
onClick: function onClick() {
if (!Object(verifyLogin["b" /* handleVerify */])(dispatch)) {
return;
}
umiExports["c" /* history */].push("/paperlibrary");
}
}, "\u8BD5\u5377\u5E93")), ((_user$navigationInfo = user.navigationInfo) === null || _user$navigationInfo === void 0 ? void 0 : (_user$navigationInfo$ = _user$navigationInfo.top) === null || _user$navigationInfo$ === void 0 ? void 0 : _user$navigationInfo$.customer_management_url) && /*#__PURE__*/react_default.a.createElement(menu["a" /* default */].Item, null, /*#__PURE__*/react_default.a.createElement("a", {
href: (_user$navigationInfo2 = user.navigationInfo) === null || _user$navigationInfo2 === void 0 ? void 0 : (_user$navigationInfo3 = _user$navigationInfo2.top) === null || _user$navigationInfo3 === void 0 ? void 0 : _user$navigationInfo3.customer_management_url
}, "\u5BA2\u6237\u7BA1\u7406")), ((_user$navigationInfo4 = user.navigationInfo) === null || _user$navigationInfo4 === void 0 ? void 0 : (_user$navigationInfo5 = _user$navigationInfo4.top) === null || _user$navigationInfo5 === void 0 ? void 0 : _user$navigationInfo5.college_identifier) && /*#__PURE__*/react_default.a.createElement(menu["a" /* default */].Item, null, /*#__PURE__*/react_default.a.createElement(react_router_dom["a" /* Link */], {
to: "/colleges/".concat((_user$navigationInfo6 = user.navigationInfo) === null || _user$navigationInfo6 === void 0 ? void 0 : (_user$navigationInfo7 = _user$navigationInfo6.top) === null || _user$navigationInfo7 === void 0 ? void 0 : _user$navigationInfo7.college_identifier, "/statistics")
}, "\u5B66\u9662\u7EDF\u8BA1")), ((_user$navigationInfo8 = user.navigationInfo) === null || _user$navigationInfo8 === void 0 ? void 0 : (_user$navigationInfo9 = _user$navigationInfo8.top) === null || _user$navigationInfo9 === void 0 ? void 0 : _user$navigationInfo9.laboratory_admin_url) && /*#__PURE__*/react_default.a.createElement(menu["a" /* default */].Item, null, /*#__PURE__*/react_default.a.createElement("a", {
href: (_user$navigationInfo10 = user.navigationInfo) === null || _user$navigationInfo10 === void 0 ? void 0 : (_user$navigationInfo11 = _user$navigationInfo10.top) === null || _user$navigationInfo11 === void 0 ? void 0 : _user$navigationInfo11.laboratory_admin_url
}, "\u540E\u53F0\u7BA1\u7406")), /*#__PURE__*/react_default.a.createElement(menu["a" /* default */].Item, null, /*#__PURE__*/react_default.a.createElement(react_router_dom["a" /* Link */], {
onClick: function onClick() {
if (localStorage.getItem('Noviceguide') === '0') {} else {
dispatch({
type: 'shixunHomeworks/setActionTabs',
payload: {
key: '底部弹窗',
type: 2,
href: '/classrooms',
text: /*#__PURE__*/react_default.a.createElement("div", null, "OK\uFF0C\u63A5\u4E0B\u6765\uFF0C\u8BA9\u6211\u4EEC\u5F00\u59CB\u65B0\u5EFA\u3010\u6559\u5B66\u8BFE\u5802\u3011\uFF0C\u8BF7\u60A8\u627E\u5230\u95EA\u5149\u6846\u5E76\u70B9\u51FB \u201C\u6559\u5B66\u8BFE\u5802\u201D\u3002")
}
});
}
},
to: "/account/profile"
}, "\u8D26\u53F7\u7BA1\u7406")), /*#__PURE__*/react_default.a.createElement(menu["a" /* default */].Item, null, /*#__PURE__*/react_default.a.createElement(react_router_dom["a" /* Link */], {
to: "/order"
}, "\u6211\u7684\u8BA2\u5355")), /*#__PURE__*/react_default.a.createElement(menu["a" /* default */].Item, {
className: Usermodules_default.a.exit
}, /*#__PURE__*/react_default.a.createElement("a", {
onClick: /*#__PURE__*/Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee() {
var res;
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return Object(service_user["h" /* LoginOut */])({});
case 2:
res = _context.sent;
if ((res === null || res === void 0 ? void 0 : res.status) === 1) {
dispatch({
type: 'user/getUserInfo',
payload: Object(objectSpread2["a" /* default */])({}, payload)
});
dispatch({
type: 'user/getNavigationInfo',
payload: Object(objectSpread2["a" /* default */])({}, payload)
});
delCookie('logintrustie');
delCookie('_educoder_session');
localStorage.removeItem('isfirst');
localStorage.removeItem('SystemUpdateadvtime');
localStorage.removeItem('item');
localStorage.removeItem('iscreate'); // localStorage.removeItem('CCshow')
es_message["b" /* default */].success(res === null || res === void 0 ? void 0 : res.message);
umiExports["c" /* history */].replace('/');
}
case 4:
case "end":
return _context.stop();
}
}
}, _callee);
}))
}, "\u9000\u51FA")));
}
};
var OwnerDownMenu = function OwnerDownMenu() {
var _user$userInfo15, _user$userInfo16, _globalSetting$settin5, _globalSetting$settin6;
return /*#__PURE__*/react_default.a.createElement(menu["a" /* default */], {
className: Usermodules_default.a.currentMenu
}, /*#__PURE__*/react_default.a.createElement(menu["a" /* default */].Item, null, /*#__PURE__*/react_default.a.createElement("span", {
className: Usermodules_default.a.currentName,
title: (_user$userInfo15 = user.userInfo) === null || _user$userInfo15 === void 0 ? void 0 : _user$userInfo15.username
}, (_user$userInfo16 = user.userInfo) === null || _user$userInfo16 === void 0 ? void 0 : _user$userInfo16.username)), (globalSetting === null || globalSetting === void 0 ? void 0 : (_globalSetting$settin5 = globalSetting.setting) === null || _globalSetting$settin5 === void 0 ? void 0 : _globalSetting$settin5.personal) && (globalSetting === null || globalSetting === void 0 ? void 0 : (_globalSetting$settin6 = globalSetting.setting) === null || _globalSetting$settin6 === void 0 ? void 0 : _globalSetting$settin6.personal.map(function (item, key) {
return /*#__PURE__*/react_default.a.createElement("li", {
key: key
}, /*#__PURE__*/react_default.a.createElement("a", {
href: item.url,
target: "_blank"
}, item.name));
})), /*#__PURE__*/react_default.a.createElement(menu["a" /* default */].Item, null, /*#__PURE__*/react_default.a.createElement("a", {
onClick: /*#__PURE__*/Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee2() {
var _history$location;
var res;
return regenerator_default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return Object(service_user["d" /* ForgeLoginOut */])({});
case 2:
res = _context2.sent;
dispatch({
type: 'user/getUserInfo',
payload: Object(objectSpread2["a" /* default */])({}, payload)
});
umiExports["c" /* history */].push({
pathname: umiExports["c" /* history */] === null || umiExports["c" /* history */] === void 0 ? void 0 : (_history$location = umiExports["c" /* history */].location) === null || _history$location === void 0 ? void 0 : _history$location.pathname,
search: ""
});
window.location.reload();
delCookie('autologin');
delCookie('logintrustie');
case 8:
case "end":
return _context2.stop();
}
}
}, _callee2);
}))
}, "\u9000\u51FA")));
};
var educoderloginysl = function educoderloginysl() {
//退出账号时清除登录页面的下次自动登录(用户再次打开登录页面时下次自动登录框不勾选)
// cookie.remove("autologin");
delCookie("autologin"); //退出账号
// var url = `/accounts/logout.json`;
// axios.get((url)).then((result) => {
// if (result !== undefined) {
// window.location.href = "/";
// }
// }).catch((error) => {
// console.log(error);
// })
};
if (Object(authority["b" /* isLogin */])()) {
var _globalSetting$settin7, _globalSetting$settin8, _user$userInfo17, _user$userInfo18;
return /*#__PURE__*/react_default.a.createElement(dropdown["a" /* default */], {
className: "".concat(Usermodules_default.a.height67, " mr25"),
overlay: OwnerDownMenu,
placement: "bottomLeft"
}, /*#__PURE__*/react_default.a.createElement("section", null, /*#__PURE__*/react_default.a.createElement("aside", null, /*#__PURE__*/react_default.a.createElement("div", {
className: shixunHomeworks.actionTabs.type === 1 ? Usermodules_default.a.classromediv : ''
}, /*#__PURE__*/react_default.a.createElement("a", {
href: "".concat(globalSetting === null || globalSetting === void 0 ? void 0 : (_globalSetting$settin7 = globalSetting.setting) === null || _globalSetting$settin7 === void 0 ? void 0 : (_globalSetting$settin8 = _globalSetting$settin7.common) === null || _globalSetting$settin8 === void 0 ? void 0 : _globalSetting$settin8.main_site_url, "/").concat((_user$userInfo17 = user.userInfo) === null || _user$userInfo17 === void 0 ? void 0 : _user$userInfo17.login)
}, /*#__PURE__*/react_default.a.createElement("img", {
className: "".concat(Usermodules_default.a.userPic, " current ml15"),
src: "".concat(env["a" /* default */] === null || env["a" /* default */] === void 0 ? void 0 : env["a" /* default */].FORGE_SERVER, "/").concat((_user$userInfo18 = user.userInfo) === null || _user$userInfo18 === void 0 ? void 0 : _user$userInfo18.image_url),
alt: ""
}))))));
} else {
var _globalSetting$settin9, _globalSetting$settin10;
return /*#__PURE__*/react_default.a.createElement("div", {
className: "font15"
}, /*#__PURE__*/react_default.a.createElement("span", {
className: "ml10 mr5 current c-white",
onClick: function onClick() {
dispatch({
type: 'user/showPopLogin',
payload: {
showPopLogin: true,
showClosable: true
}
});
}
}, "\u767B\u5F55"), /*#__PURE__*/react_default.a.createElement("span", {
className: "ml5 mr5"
}, "|"), /*#__PURE__*/react_default.a.createElement("a", {
href: "".concat(globalSetting === null || globalSetting === void 0 ? void 0 : (_globalSetting$settin9 = globalSetting.setting) === null || _globalSetting$settin9 === void 0 ? void 0 : (_globalSetting$settin10 = _globalSetting$settin9.common) === null || _globalSetting$settin10 === void 0 ? void 0 : _globalSetting$settin10.register),
className: "ml5 current c-white pr30"
}, "\u6CE8\u518C"));
}
};
/* harmony default export */ var components_User = (Object(umiExports["a" /* connect */])(function (_ref4) {
var homePage = _ref4.homePage,
loading = _ref4.loading,
user = _ref4.user,
globalSetting = _ref4.globalSetting,
shixunHomeworks = _ref4.shixunHomeworks;
return {
homePage: homePage,
user: user,
globalSetting: globalSetting,
shixunHomeworks: shixunHomeworks,
loading: loading.models.index
};
})(User_User));
// EXTERNAL MODULE: ./node_modules/antd/es/button/style/index.js
var button_style = __webpack_require__("+L6B");
// EXTERNAL MODULE: ./node_modules/antd/es/button/index.js
var es_button = __webpack_require__("2/Rp");
// EXTERNAL MODULE: ./src/components/HomeModal/jqr.png
var jqr = __webpack_require__("Cs+z");
var jqr_default = /*#__PURE__*/__webpack_require__.n(jqr);
// CONCATENATED MODULE: ./src/components/HomeModal/Beginnerbottom.tsx
var showLinks = ['/', '/classrooms', '/account/profile', '/account/profile/edit', '/classrooms/new'];
var Beginnerbottom_User = function User(_ref) {
var homePage = _ref.homePage,
user = _ref.user,
globalSetting = _ref.globalSetting,
loading = _ref.loading,
dispatch = _ref.dispatch,
location = _ref.location,
text = _ref.text,
shixunHomeworks = _ref.shixunHomeworks,
_ref$payload = _ref.payload,
payload = _ref$payload === void 0 ? {} : _ref$payload,
props = Object(objectWithoutProperties["a" /* default */])(_ref, ["homePage", "user", "globalSetting", "loading", "dispatch", "location", "text", "shixunHomeworks", "payload"]);
var _useState = Object(react["useState"])('none'),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
showbottom = _useState2[0],
setshowbottom = _useState2[1];
Object(react["useEffect"])(function () {
if (shixunHomeworks.actionTabs.key === '底部弹窗') {
setshowbottom('flex');
}
}, [shixunHomeworks.actionTabs.key]);
Object(react["useEffect"])(function () {
if (shixunHomeworks.actionTabs.key === '隐藏') {
setshowbottom('none');
localStorage.setItem('Noviceguide', '0');
}
}, [shixunHomeworks.actionTabs.key]);
return /*#__PURE__*/react_default.a.createElement("div", {
style: {
display: showbottom,
background: '#fff',
width: '100%',
height: '200px',
position: "fixed",
bottom: '0px',
boxShadow: '0px -4px 6px 0px rgba(204, 204, 204, 0.2)',
zIndex: '999'
}
}, /*#__PURE__*/react_default.a.createElement("div", {
style: {
margin: '0 auto',
width: '1200px'
}
}, /*#__PURE__*/react_default.a.createElement("img", {
src: jqr_default.a,
style: {
position: 'absolute',
top: '-32px'
}
}), /*#__PURE__*/react_default.a.createElement("div", {
style: {
marginLeft: "151px",
marginTop: '40px',
fontSize: '18px',
color: "#333333"
}
}, shixunHomeworks.actionTabs.text), shixunHomeworks.actionTabs.type === 9 ? /*#__PURE__*/react_default.a.createElement("div", {
style: {
display: 'flex',
justifyContent: 'flex-end'
}
}, /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
type: "primary",
onClick: function onClick() {
localStorage.setItem('Noviceguide', '0');
setshowbottom('none');
dispatch({
type: 'shixunHomeworks/setActionTabs',
payload: {
key: ''
}
});
},
ghost: true,
style: {
marginTop: "30px",
width: '138px',
height: '40px',
position: 'absolute',
top: '124px'
}
}, "\u5446\u4F1A\u89C1\uFF0C\u6709\u4E8B\u547C\u6211")) : /*#__PURE__*/react_default.a.createElement("div", {
style: {
display: 'flex',
justifyContent: 'flex-end'
}
}, /*#__PURE__*/react_default.a.createElement(es_button["a" /* default */], {
type: "primary",
onClick: function onClick() {
localStorage.setItem('Noviceguide', '0');
dispatch({
type: 'shixunHomeworks/setActionTabs',
payload: {
key: ''
}
});
setshowbottom('none');
},
ghost: true,
style: {
marginTop: "30px",
width: '138px',
height: '40px',
position: 'absolute',
top: '124px'
}
}, "\u8DF3\u8FC7\uFF0C\u6211\u81EA\u5DF1\u6765"))));
};
/* harmony default export */ var Beginnerbottom = (Object(umiExports["a" /* connect */])(function (_ref2) {
var homePage = _ref2.homePage,
loading = _ref2.loading,
user = _ref2.user,
globalSetting = _ref2.globalSetting,
shixunHomeworks = _ref2.shixunHomeworks;
return {
homePage: homePage,
user: user,
globalSetting: globalSetting,
loading: loading.models.index,
shixunHomeworks: shixunHomeworks
};
})(Beginnerbottom_User));
// CONCATENATED MODULE: ./src/components/Header/index.tsx
var Header = es_layout.Header;
var Search = input["a" /* default */].Search;
function getCourseParam() {
var _type$, _type$2;
var query = window.location.pathname;
var type = query.split('/');
var params = {};
if (type[1] == 'classrooms' && type.length > 3 && !((_type$ = type[4]) === null || _type$ === void 0 ? void 0 : _type$.includes('newgold')) && !((_type$2 = type[5]) === null || _type$2 === void 0 ? void 0 : _type$2.includes('newgold')) && type[2] !== 'coursesId') {
params.course_id = type[2];
}
if (type[1] === 'shixuns' && type.length > 3) {
params.objective_type = 'shixun';
params.objective_id = type[2];
}
if (type[1] === 'paths' && type.length > 3) {
params.objective_type = 'path';
params.objective_id = type[2];
}
return Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, params), {
school: 1
});
}
var routerLinks = {
首页: "/",
'/paths': {
link: "/paths",
key: 1
},
'/shixuns': {
link: "/shixuns",
key: 2
},
'/classrooms': {
link: "/classrooms",
key: 3
},
'/competitions': {
link: "/competitions",
key: 4
},
'/moop_cases': {
link: "/moop_cases",
key: 5
},
'/forums': {
link: "/forums",
key: 6
},
'/recruitment': {
link: "/competitions/index",
key: 7
},
'/three': {
link: "/three",
key: 7
}
};
var Header_showLinks = ['/', '/classrooms', '/account/profile', '/account/profile/edit', '/classrooms/new'];
var Header_HeaderComponents = function HeaderComponents(_ref) {
var _globalSetting$settin6;
var homePage = _ref.homePage,
user = _ref.user,
globalSetting = _ref.globalSetting,
loading = _ref.loading,
dispatch = _ref.dispatch,
location = _ref.location,
_ref$isLogin = _ref.isLogin,
isLogin = _ref$isLogin === void 0 ? false : _ref$isLogin,
shixunHomeworks = _ref.shixunHomeworks,
props = Object(objectWithoutProperties["a" /* default */])(_ref, ["homePage", "user", "globalSetting", "loading", "dispatch", "location", "isLogin", "shixunHomeworks"]);
var history = Object(react_router["j" /* useHistory */])();
var _useState = Object(react["useState"])(false),
_useState2 = Object(slicedToArray["a" /* default */])(_useState, 2),
openSearch = _useState2[0],
setOpenSearch = _useState2[1];
var _useState3 = Object(react["useState"])(-1),
_useState4 = Object(slicedToArray["a" /* default */])(_useState3, 2),
activeKey = _useState4[0],
setActiveKey = _useState4[1];
var _useState5 = Object(react["useState"])(false),
_useState6 = Object(slicedToArray["a" /* default */])(_useState5, 2),
QQVisible = _useState6[0],
setQQVisible = _useState6[1];
var payload = getCourseParam();
var pathname = location.pathname;
Object(react["useEffect"])(function () {
dispatch({
type: 'user/getNavigationInfo',
payload: Object(objectSpread2["a" /* default */])({}, payload)
});
}, [globalSetting.name]); // console.log('-----------',location.pathname==='/classrooms'?'1':'2');
Object(react["useEffect"])(function () {
// if(parseInt(localStorage.getItem('Noviceguide'))===1){
// if(location.pathname.indexOf('/account/profile')===0){
// }else if(location.pathname.indexOf('/classrooms')!=0){
// dispatch({
// type: 'shixunHomeworks/setActionTabs',
// payload: {
// key: '隐藏',
// },
// })
// }
// }
if (shixunHomeworks.actionTabs.key === '底部弹窗') {
if ((Header_showLinks === null || Header_showLinks === void 0 ? void 0 : Header_showLinks.includes(location === null || location === void 0 ? void 0 : location.pathname)) || (location === null || location === void 0 ? void 0 : location.pathname.indexOf('/classrooms')) === 0) {} else {
dispatch({
type: 'shixunHomeworks/setActionTabs',
payload: {
key: '隐藏'
}
});
}
} // const key: string = Object.keys(routerLinks).filter(item => location.pathname.indexOf(item) > -1)[0]
// setActiveKey(routerLinks?.[key]?.['key'])
}, [location.pathname]);
Object(react["useEffect"])(function () {
//判断 如果刷新了 直接吧状态赋空 防止点击埋点出现问题
if (shixunHomeworks.actionTabs.key === '底部弹窗') {} else if (shixunHomeworks.actionTabs.key) {} else {
localStorage.setItem('Noviceguide', '0');
}
}, [shixunHomeworks.actionTabs.key]);
Object(react["useEffect"])(function () {
if (globalSetting === null || globalSetting === void 0 ? void 0 : globalSetting.setting) {
var _globalSetting$settin, _globalSetting$settin2;
globalSetting === null || globalSetting === void 0 ? void 0 : (_globalSetting$settin = globalSetting.setting) === null || _globalSetting$settin === void 0 ? void 0 : (_globalSetting$settin2 = _globalSetting$settin.navbar) === null || _globalSetting$settin2 === void 0 ? void 0 : _globalSetting$settin2.map(function (val, key) {
if (location.pathname.indexOf(val.link) > -1) {
setActiveKey(key);
}
});
if (activeKey === -1) {
Object(util["p" /* setDocumentTitle */])(globalSetting.setting.name);
} else {
var _globalSetting$settin3;
Object(util["p" /* setDocumentTitle */])(((_globalSetting$settin3 = globalSetting.setting.navbar[activeKey]) === null || _globalSetting$settin3 === void 0 ? void 0 : _globalSetting$settin3.name) || globalSetting.setting.name);
}
}
}, [globalSetting === null || globalSetting === void 0 ? void 0 : globalSetting.setting]);
var logoUrl = Object(react["useMemo"])(function () {
var _globalSetting$settin4;
if (!!(globalSetting === null || globalSetting === void 0 ? void 0 : (_globalSetting$settin4 = globalSetting.setting) === null || _globalSetting$settin4 === void 0 ? void 0 : _globalSetting$settin4.nav_logo_url)) {
var _globalSetting$settin5;
return "".concat(env["a" /* default */].IMG_SERVER, "/").concat(globalSetting === null || globalSetting === void 0 ? void 0 : (_globalSetting$settin5 = globalSetting.setting) === null || _globalSetting$settin5 === void 0 ? void 0 : _globalSetting$settin5.nav_logo_url);
} else {
return "".concat(env["a" /* default */].IMG_SERVER, "/images/avatars/LaboratorySetting/1nav?t=").concat(new Date().getTime());
}
}, [globalSetting === null || globalSetting === void 0 ? void 0 : (_globalSetting$settin6 = globalSetting.setting) === null || _globalSetting$settin6 === void 0 ? void 0 : _globalSetting$settin6.nav_logo_url]);
function onGlobalSearch(value) {
history.push('/search?value=' + value);
}
var SearchInput = function SearchInput() {
if (openSearch) {
return /*#__PURE__*/react_default.a.createElement("div", {
onBlur: function onBlur() {
setTimeout(function () {
setOpenSearch(false);
}, 300);
}
}, /*#__PURE__*/react_default.a.createElement(Search, {
placeholder: "\u8BF7\u8F93\u5165\u641C\u7D22\u5173\u952E\u5B57",
className: "search-input mr20",
onSearch: onGlobalSearch,
autoFocus: true
}));
} else {
return /*#__PURE__*/react_default.a.createElement("span", {
className: "iconfont icon-sousuo font18 current ml15 mr15",
onClick: function onClick() {
setOpenSearch(true); // history.push('/search?value=')
}
});
}
};
var handleCert = /*#__PURE__*/function () {
var _ref2 = Object(asyncToGenerator["a" /* default */])( /*#__PURE__*/regenerator_default.a.mark(function _callee(e) {
var _res$data;
var res, _res$data2;
return regenerator_default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
e.preventDefault();
_context.next = 3;
return Object(service_user["m" /* getEngineerUrl */])();
case 3:
res = _context.sent;
if (res === null || res === void 0 ? void 0 : (_res$data = res.data) === null || _res$data === void 0 ? void 0 : _res$data.engineer_url) {
document.location.href = res === null || res === void 0 ? void 0 : (_res$data2 = res.data) === null || _res$data2 === void 0 ? void 0 : _res$data2.engineer_url;
} else if ((res === null || res === void 0 ? void 0 : res.status) != 401) {
setQQVisible(true);
}
case 5:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function handleCert(_x) {
return _ref2.apply(this, arguments);
};
}();
if (globalSetting.showHeader && globalSetting.showHeaderFooter) {
var _globalSetting$settin7, _globalSetting$settin8, _globalSetting$settin9, _globalSetting$settin10, _user$userInfo, _user$userInfo2, _user$userInfo3;
return /*#__PURE__*/react_default.a.createElement(es_layout, {
className: "".concat(Headermodules_default.a.header, " ").concat(Headermodules_default.a.headerFixed)
}, /*#__PURE__*/react_default.a.createElement(Header, {
className: "header"
}, /*#__PURE__*/react_default.a.createElement("section", {
className: Headermodules_default.a['edu-menu']
}, /*#__PURE__*/react_default.a.createElement("ul", {
className: "".concat(Headermodules_default.a.menu, " ").concat(Object(util["b" /* checkIsClientExam */])() && "ml0")
}, Object(util["b" /* checkIsClientExam */])() && /*#__PURE__*/react_default.a.createElement("li", null, /*#__PURE__*/react_default.a.createElement("a", {
href: "/"
}, "\u8003\u8BD5\u7CFB\u7EDF")), ((_globalSetting$settin7 = globalSetting.setting) === null || _globalSetting$settin7 === void 0 ? void 0 : _globalSetting$settin7.nav_logo_url) && /*#__PURE__*/react_default.a.createElement("a", {
style: {
marginLeft: "78px"
},
href: (_globalSetting$settin8 = globalSetting.setting) === null || _globalSetting$settin8 === void 0 ? void 0 : (_globalSetting$settin9 = _globalSetting$settin8.common) === null || _globalSetting$settin9 === void 0 ? void 0 : _globalSetting$settin9.main_site_url
}, /*#__PURE__*/react_default.a.createElement("img", {
width: "155px",
src: env["a" /* default */].FORGE_SERVER + '/' + ((_globalSetting$settin10 = globalSetting.setting) === null || _globalSetting$settin10 === void 0 ? void 0 : _globalSetting$settin10.nav_logo_url),
className: "mr50"
})), !Object(util["b" /* checkIsClientExam */])() && globalSetting.setting && globalSetting.setting.navbar.map(function (v, k) {
if (!v.hidden) {
return /*#__PURE__*/react_default.a.createElement("li", {
key: k,
className: v.link === "".concat(env["a" /* default */].FORGE_SERVER, "/competitions") ? Headermodules_default.a.actived : ''
}, (v === null || v === void 0 ? void 0 : v.name) === '教学课堂' && /*#__PURE__*/react_default.a.createElement(react_router_dom["a" /* Link */], {
onClick: function onClick() {
if (localStorage.getItem('Noviceguide') === '0') {} else {
dispatch({
type: 'shixunHomeworks/setActionTabs',
payload: {
key: '底部弹窗',
type: 5,
text: /*#__PURE__*/react_default.a.createElement("div", null, "\u975E\u5E38\u68D2\uFF0C\u54B1\u4EEC\u5DF2\u7ECF\u5230\u8FBE\u3010\u6559\u5B66\u8BFE\u5802\u3011\uFF0C\u5E73\u53F0\u4E0A\u5DF2\u7ECF\u6709\u51E0\u5343\u4F4D\u8001\u5E08\u521B\u5EFA\u4E86\u81EA\u5DF1\u7684\u6559\u5B66\u8BFE\u5802\uFF0C\u4F60\u4E5F\u53EF\u4EE5\u8F7B\u677E\u5B8C\u6210\u54DF\uFF01\u73B0\u5728\u8BF7\u60A8\u70B9\u51FB\u9875\u9762\u4E0A \u201C\u65B0\u5EFA\u8BFE\u5802\u201D\u6309\u94AE\u5F00\u59CB\u65B0\u5EFA\u81EA\u5DF1\u7684\u8BFE\u5802~")
}
});
}
},
className: shixunHomeworks.actionTabs.type === 4 ? Headermodules_default.a.classromediv : '',
dangerouslySetInnerHTML: {
__html: v.name
},
to: v.link
}), (v === null || v === void 0 ? void 0 : v.name) != '教学课堂' && v.link.indexOf("http") < 0 && /*#__PURE__*/react_default.a.createElement(react_router_dom["a" /* Link */], {
onClick: function onClick() {
dispatch({
type: 'shixunHomeworks/setActionTabs',
payload: {
key: ''
}
});
},
dangerouslySetInnerHTML: {
__html: v.name
},
to: v.link
}), (v === null || v === void 0 ? void 0 : v.name) != '教学课堂' && v.link.indexOf("http") > -1 && /*#__PURE__*/react_default.a.createElement("a", {
dangerouslySetInnerHTML: {
__html: v.name
},
href: v.link
}));
}
})), /*#__PURE__*/react_default.a.createElement("div", {
className: "search-bar"
}, !Object(util["b" /* checkIsClientExam */])() && /*#__PURE__*/react_default.a.createElement(react_default.a.Fragment, null, /*#__PURE__*/react_default.a.createElement(SearchInput, null), !isLogin && !!(user === null || user === void 0 ? void 0 : (_user$userInfo = user.userInfo) === null || _user$userInfo === void 0 ? void 0 : _user$userInfo.login) && /*#__PURE__*/react_default.a.createElement(components_Join, null), !!(user === null || user === void 0 ? void 0 : (_user$userInfo2 = user.userInfo) === null || _user$userInfo2 === void 0 ? void 0 : _user$userInfo2.login) && /*#__PURE__*/react_default.a.createElement("a", {
className: "iconfont icon-xiaoxilingdang c-white ml15 mr15 font18 relative",
href: "".concat(env["a" /* default */].FORGE_SERVER, "/settings/notice")
}, (user === null || user === void 0 ? void 0 : (_user$userInfo3 = user.userInfo) === null || _user$userInfo3 === void 0 ? void 0 : _user$userInfo3.message_unread_total) > 0 ? /*#__PURE__*/react_default.a.createElement("span", {
className: Headermodules_default.a.newslight
}) : "")), !isLogin && /*#__PURE__*/react_default.a.createElement(components_User, {
payload: payload
}))), /*#__PURE__*/react_default.a.createElement(modal["a" /* default */], {
centered: true,
destroyOnClose: true,
visible: QQVisible,
title: "\u63D0\u793A",
width: "500px" // footer={null}
,
okText: "\u7ACB\u5373\u8054\u7CFB",
cancelText: "\u53D6\u6D88",
onOk: function onOk() {
Object(util["n" /* openNewWindow */])("https://qm.qq.com/cgi-bin/qm/qr?k=DWdqQHAbbfw7_rqm0d-Q_vDn5H6bMp91&jump_from=webapi");
},
onCancel: function onCancel() {
return setQQVisible(false);
}
}, /*#__PURE__*/react_default.a.createElement("div", {
style: {
display: 'flex',
flexDirection: 'column',
alignItems: 'center'
}
}, /*#__PURE__*/react_default.a.createElement("p", null, "\u60A8\u53EF\u4EE5\u5728QQ\u670D\u52A1\u7FA4\u5411\u7BA1\u7406\u5458\u7533\u8BF7\uFF0C\u83B7\u5F97\u7EE7\u7EED\u64CD\u4F5C\u7684\u6743\u9650"), /*#__PURE__*/react_default.a.createElement("img", {
src: ImagesIcon["c" /* teacherQQIcon */],
width: 200,
height: 200
}), /*#__PURE__*/react_default.a.createElement("p", null, "\u7FA4\u53F7\uFF1A693542422 ")))), /*#__PURE__*/react_default.a.createElement(Beginnerbottom, null));
} else {
return /*#__PURE__*/react_default.a.createElement(react_default.a.Fragment, null);
}
};
/* harmony default export */ var components_Header = __webpack_exports__["a"] = (Object(umiExports["a" /* connect */])(function (_ref3) {
var homePage = _ref3.homePage,
loading = _ref3.loading,
user = _ref3.user,
globalSetting = _ref3.globalSetting,
shixunHomeworks = _ref3.shixunHomeworks;
return {
homePage: homePage,
user: user,
globalSetting: globalSetting,
loading: loading.models.index,
shixunHomeworks: shixunHomeworks
};
})(Header_HeaderComponents));
/***/ }),
/***/ "sPJy":
/*!********************************************************!*\
!*** ./node_modules/antd/es/breadcrumb/style/index.js ***!
\********************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _style_index_less__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../style/index.less */ "cIOH");
/* harmony import */ var _style_index_less__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_style_index_less__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _index_less__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./index.less */ "AOa7");
/* harmony import */ var _index_less__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_index_less__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _menu_style__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../menu/style */ "lUTK");
/* harmony import */ var _dropdown_style__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../dropdown/style */ "qVdP");
/***/ }),
/***/ "sPtV":
/*!**********************************************************!*\
!*** ./node_modules/antd/es/_util/hooks/useSyncState.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 useSyncState; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "q1tI");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _useForceUpdate__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./useForceUpdate */ "hkKa");
function useSyncState(initialValue) {
var ref = react__WEBPACK_IMPORTED_MODULE_0__["useRef"](initialValue);
var forceUpdate = Object(_useForceUpdate__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"])();
return [function () {
return ref.current;
}, function (newValue) {
ref.current = newValue; // re-render
forceUpdate();
}];
}
/***/ }),
/***/ "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 */ "q1tI");
/* 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);
/***/ }),
/***/ "tSko":
/*!******************************************************************!*\
!*** ./node_modules/@ant-design/icons/lib/icons/PlusOutlined.js ***!
\******************************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireWildcard = __webpack_require__(/*! @babel/runtime/helpers/interopRequireWildcard */ "284h");
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "TqRt");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/objectSpread2 */ "3tO9"));
var React = _interopRequireWildcard(__webpack_require__(/*! react */ "q1tI"));
var _PlusOutlined = _interopRequireDefault(__webpack_require__(/*! @ant-design/icons-svg/lib/asn/PlusOutlined */ "SRve"));
var _AntdIcon = _interopRequireDefault(__webpack_require__(/*! ../components/AntdIcon */ "KQxl"));
// GENERATE BY ./scripts/generate.ts
// DON NOT EDIT IT MANUALLY
var PlusOutlined = function PlusOutlined(props, ref) {
return /*#__PURE__*/React.createElement(_AntdIcon.default, (0, _objectSpread2.default)((0, _objectSpread2.default)({}, props), {}, {
ref: ref,
icon: _PlusOutlined.default
}));
};
PlusOutlined.displayName = 'PlusOutlined';
var _default = /*#__PURE__*/React.forwardRef(PlusOutlined);
exports.default = _default;
/***/ }),
/***/ "tWlo":
/*!*******************************************!*\
!*** ./src/assets/images/icons/anony.png ***!
\*******************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports) {
module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMTQ1IDc5LjE2MzQ5OSwgMjAxOC8wOC8xMy0xNjo0MDoyMiAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTkgKFdpbmRvd3MpIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOkVCNENBMTM0OENGMTExRTk4NzNCRkMxMzdBMjc5MEY5IiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOkVCNENBMTM1OENGMTExRTk4NzNCRkMxMzdBMjc5MEY5Ij4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6RUI0Q0ExMzI4Q0YxMTFFOTg3M0JGQzEzN0EyNzkwRjkiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6RUI0Q0ExMzM4Q0YxMTFFOTg3M0JGQzEzN0EyNzkwRjkiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz7p3KzkAAAFvElEQVR42sRae0ybVRQ/peVRaFce8pwgj1Je5TFsEHGbMAkzmqiJyba4hYh/LJlxiRr9Z0aNGv8xvhKTGckM2zKWmGEgU7MsPnCZIrKBjMcKY9BCBMqjjEcLtFDwHPZVC12h934f8yS/P6Dfud/5nXvvueec+8neOPEuSCAxiDJEMSITkYKIRoQJv9sREwgTogfRjGhEjIt9sUKEbhSiEvEC4mGEbJNngxGRiAzEk8L/VhGtiPOIswgrjxEBHDrxiE8Qg4hPEYYtjPclMkGXxhhCfIFI2E4CNFtvIm4hXvdYHlJIKOIVRK/wjkCpCaQjWhAfIVSwfaIS3kHvypaKwLOI64hdcP+kAPEn4jmxBI4ivkXsgPsvNBt1gg1cBI4hvkLI4f8TuWDDMdYw+owQFdh3Y6gSCnL1oNOmQnxcHAQHB8HCwiLMzM7C8KgFjD23oN9khtXVVZZhyZZhxEV/CGQhalk9r1AoYO9jxfBokQGCgoK8SBHi42LBsCsfJq1TcOnHn+F2v4llJsimIoRx3Q8le0o9/6bwdRmRxGJ8ZEQ4vHjkEORkZYBcLvdrlvL0OeBwOuDv4RF/X0Ne2Y34GrHiaw+8ishnMT4tNRmOVlVCTPQDzKfY/vJ9kJWpY1Ej217ztYnpFHyH6UjGJXH4wPOgVIZw7VAi8XRFOSjkTKv1bc8T25PACdZDan95mV9LZjNRq1Wg02lZw+tbGwnQ/L/EMooyJASSkxIliZUp7ONUCTb/S+AI2cTqOZlMJgmBcI2GVUUp2LyOAJMwxvHN04EAnqQYDrsJUDFSyKrtdC5JRmDR4eBRoxokgQjs48nn5+fnJSNgt3ONRTaXEYFHeLSXlpd5Peclk1Yrr6ohQKhhuWR6ekYSAiOWMV7VDCKg5Z0/uwTLaNnlAssYd22fTgRieTRz9dmQlpIsmgCdwuWle3nVY4mAmkczLCxUsk0cEaHhVVUH8GqOT0xKRmB6ZpZX1UkE5ng0zeYhsNntkhBgqAs2yhwR4AoBrpUVaO/oEm38nelp6B/gJnCHCNzm1f79jxaWgsRLbDY7XKj/Dlb405I+ItDDqz2/sACnTp9DEqNc+qfO1MLwyKiYCewNEPov3EK+G59k39BOp3Nt+YiUViLQKNjBH8sV7EXNivhslgb4xb2J28SMtMSRmbrwBBYpZPOI+xw4J2aka23tzB4VETrdct6zoCECC7wjjWIy1tbewZT//9R4RYzxZOtZTwK0C2vEjHjT2Ov3sx2d3TA7ZxPzuhrB5nVdiQ8pNPPvKP+XkEjjbYKtXm0VOpHe5x01KDDI72dFtmI+EGz1IkDyOeIvnlETH/T/digqKoLXeLLts3UNgY0REXGQZpmpqtCmrjV1/ZWcrEzIzEhnTtwQhwQb/5vNDc1dkinak4gDsMUFSEhwMJQ9vhueqihnWhYBMhnokYRGowGLZRwcW9fWLsGxTV6HqA8F6sMfR5z0qiDUKsjQpoEuPQ1SsSILVPDd1FJTrDA/Fwry9NDX1w9dxh7MSs2+ytTjcI+7gc0IkHwpMD+JnpbnZGdCXk4WPJSUKFlHzj0bGTrtGqhZNjJqgQHzIHRjWMbzhd7/MqLaZxqzxfjVFU+UjhcZCs+gp7f9nowcszMhfg17SoptSKDyym9N9cbePt8O2GrQ5pbrDRMTkwbe6MQpN6hfFRUVWa+Qb+7je23ideLAtPdGZ/cUZpw1iTsTFtFLJcBwEc2RIryHqELvW2q/qQPT4JA4AmupL5aP/Saza8A0eDU2Jvr0DrWaNkEe3L32kULmhXV+cHHR8cOvV5tcDd9f8qvm9ouAW2Zm5yhpm5uwWi9HRoRXq1UqC9zt08cDe391VUiJPyaPo+F1zddaZy80XFyLRv52v2ViPrehiJSvz6Z7rthQpZI+t6E+K91yuj+3UXnkL+7PbYxCFdiIKfgYdTcohHZ23QTnEntd8Y8AAwCTubpzlq2wWAAAAABJRU5ErkJggg=="
/***/ }),
/***/ "uGsb":
/*!******************************************!*\
!*** ./node_modules/crypto-js/sha384.js ***!
\******************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory, undef) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"), __webpack_require__(/*! ./x64-core */ "MlIO"), __webpack_require__(/*! ./sha512 */ "1uat"));
}
else {}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var X64WordArray = C_x64.WordArray;
var C_algo = C.algo;
var SHA512 = C_algo.SHA512;
/**
* SHA-384 hash algorithm.
*/
var SHA384 = C_algo.SHA384 = SHA512.extend({
_doReset: function () {
this._hash = new X64WordArray.init([
new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507),
new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939),
new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511),
new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4)
]);
},
_doFinalize: function () {
var hash = SHA512._doFinalize.call(this);
hash.sigBytes -= 16;
return hash;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA384('message');
* var hash = CryptoJS.SHA384(wordArray);
*/
C.SHA384 = SHA512._createHelper(SHA384);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA384(message, key);
*/
C.HmacSHA384 = SHA512._createHmacHelper(SHA384);
}());
return CryptoJS.SHA384;
}));
/***/ }),
/***/ "uGxW":
/*!*************************************************!*\
!*** ./node_modules/crypto-js/pad-nopadding.js ***!
\*************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory, undef) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"), __webpack_require__(/*! ./cipher-core */ "OLod"));
}
else {}
}(this, function (CryptoJS) {
/**
* A noop padding strategy.
*/
CryptoJS.pad.NoPadding = {
pad: function () {
},
unpad: function () {
}
};
return CryptoJS.pad.NoPadding;
}));
/***/ }),
/***/ "uK0f":
/*!*****************************************************!*\
!*** ./node_modules/array-tree-filter/lib/index.js ***!
\*****************************************************/
/*! no static exports found */
/*! exports used: default */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
(function (global, factory) {
true ? module.exports = factory() :
undefined;
}(this, (function () { 'use strict';
function arrayTreeFilter(data, filterFn, options) {
options = options || {};
options.childrenKeyName = options.childrenKeyName || "children";
var children = data || [];
var result = [];
var level = 0;
do {
var foundItem = children.filter(function (item) {
return filterFn(item, level);
})[0];
if (!foundItem) {
break;
}
result.push(foundItem);
children = foundItem[options.childrenKeyName] || [];
level += 1;
} while (children.length > 0);
return result;
}
return arrayTreeFilter;
})));
/***/ }),
/***/ "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) {
var _currentInitSegment;
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;
} else if (!newFrag.initSegment || newFrag.initSegment.relurl == ((_currentInitSegment = currentInitSegment) === null || _currentInitSegment === void 0 ? void 0 : _currentInitSegment.relurl)) {
newFrag.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;
this.setInterval(TICK_INTERVAL);
} else {
this.mediaBuffer = null;
}
} // 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.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.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;
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 sn = data.frag.sn;
if (sn !== lastSn + 1) {
cea608Parser1.reset();
cea608Parser2.reset();
}
this.lastSn = sn;
}
};
_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: 0,
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: 0,
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: 0,
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;
}
}
} // 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.1";
}
}, {
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
/***/ }),
/***/ "v56E":
/*!********************************************************!*\
!*** ./node_modules/antd/es/cascader/style/index.less ***!
\********************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/***/ "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","monaco":"monaco___1ypjT","darkBlue":"darkBlue___2ViJc","close":"close___3q-z4"};
/***/ }),
/***/ "vToQ":
/*!******************************************************************!*\
!*** ./src/components/Header/components/User/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___3UWMh","flex_space_between":"flex_space_between___2nh9S","flex_box_vertical_center":"flex_box_vertical_center___2Neiq","flex_box_center_end":"flex_box_center_end___2_1FS","flex_box_column":"flex_box_column___2E-v7","userPic":"userPic___3Pu9t","currentMenu":"currentMenu___zT3IA","rightMenu":"rightMenu___1qaVl","menuWrap":"menuWrap___3r9jm","exit":"exit___38Urs","classromediv":"classromediv___2R8_g","glow":"glow___323IR","height67":"height67___1DFRI"};
/***/ }),
/***/ "vg9a":
/*!***********************************************!*\
!*** ./node_modules/katex/dist/katex.min.css ***!
\***********************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/***/ "w7YG":
/*!***************************************!*\
!*** ./node_modules/crypto-js/rc4.js ***!
\***************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory, undef) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"), __webpack_require__(/*! ./enc-base64 */ "ETIr"), __webpack_require__(/*! ./md5 */ "cv67"), __webpack_require__(/*! ./evpkdf */ "K3mO"), __webpack_require__(/*! ./cipher-core */ "OLod"));
}
else {}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
/**
* RC4 stream cipher algorithm.
*/
var RC4 = C_algo.RC4 = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
var keySigBytes = key.sigBytes;
// Init sbox
var S = this._S = [];
for (var i = 0; i < 256; i++) {
S[i] = i;
}
// Key setup
for (var i = 0, j = 0; i < 256; i++) {
var keyByteIndex = i % keySigBytes;
var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff;
j = (j + S[i] + keyByte) % 256;
// Swap
var t = S[i];
S[i] = S[j];
S[j] = t;
}
// Counters
this._i = this._j = 0;
},
_doProcessBlock: function (M, offset) {
M[offset] ^= generateKeystreamWord.call(this);
},
keySize: 256/32,
ivSize: 0
});
function generateKeystreamWord() {
// Shortcuts
var S = this._S;
var i = this._i;
var j = this._j;
// Generate keystream word
var keystreamWord = 0;
for (var n = 0; n < 4; n++) {
i = (i + 1) % 256;
j = (j + S[i]) % 256;
// Swap
var t = S[i];
S[i] = S[j];
S[j] = t;
keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8);
}
// Update counters
this._i = i;
this._j = j;
return keystreamWord;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg);
*/
C.RC4 = StreamCipher._createHelper(RC4);
/**
* Modified RC4 stream cipher algorithm.
*/
var RC4Drop = C_algo.RC4Drop = RC4.extend({
/**
* Configuration options.
*
* @property {number} drop The number of keystream words to drop. Default 192
*/
cfg: RC4.cfg.extend({
drop: 192
}),
_doReset: function () {
RC4._doReset.call(this);
// Drop
for (var i = this.cfg.drop; i > 0; i--) {
generateKeystreamWord.call(this);
}
}
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg);
*/
C.RC4Drop = StreamCipher._createHelper(RC4Drop);
}());
return CryptoJS.RC4;
}));
/***/ }),
/***/ "wCAj":
/*!**********************************************************!*\
!*** ./node_modules/antd/es/table/index.js + 53 modules ***!
\**********************************************************/
/*! exports provided: default */
/*! exports used: default */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/CaretDownOutlined.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/CaretUpOutlined.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/DownOutlined.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@ant-design/icons/FilterFilled.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/defineProperty.js (<- Module is not an ECMAScript module) */
/*! 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/@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/helpers/extends.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/slicedToArray.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/toArray.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/toConsumableArray.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/@babel/runtime/helpers/typeof.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/_util/devWarning.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/_util/hooks/useSyncState.js because of ./node_modules/antd/es/upload/Upload.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/button/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/checkbox/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/config-provider/SizeContext.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/config-provider/context.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/dropdown/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/empty/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/grid/hooks/useBreakpoint.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/locale/default.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/menu/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/pagination/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/radio/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/spin/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/antd/es/tooltip/index.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/classnames/index.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/lodash/isEqual.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/omit.js/es/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-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/getScrollBarSize.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/rc-util/es/hooks/useMergedState.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/react/index.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/shallowequal/index.js (<- Module is not an ECMAScript module) */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/typeof.js
var helpers_typeof = __webpack_require__("cDf5");
var typeof_default = /*#__PURE__*/__webpack_require__.n(helpers_typeof);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/defineProperty.js
var defineProperty = __webpack_require__("lSNA");
var defineProperty_default = /*#__PURE__*/__webpack_require__.n(defineProperty);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/slicedToArray.js
var slicedToArray = __webpack_require__("J4zp");
var slicedToArray_default = /*#__PURE__*/__webpack_require__.n(slicedToArray);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/extends.js
var helpers_extends = __webpack_require__("pVnL");
var extends_default = /*#__PURE__*/__webpack_require__.n(helpers_extends);
// EXTERNAL MODULE: ./node_modules/react/index.js
var react = __webpack_require__("q1tI");
var react_default = /*#__PURE__*/__webpack_require__.n(react);
// EXTERNAL MODULE: ./node_modules/classnames/index.js
var classnames = __webpack_require__("TSYQ");
var classnames_default = /*#__PURE__*/__webpack_require__.n(classnames);
// EXTERNAL MODULE: ./node_modules/omit.js/es/index.js
var es = __webpack_require__("BGR+");
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/defineProperty.js
var esm_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/typeof.js
var esm_typeof = __webpack_require__("U8pU");
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/slicedToArray.js + 1 modules
var esm_slicedToArray = __webpack_require__("ODXe");
// EXTERNAL MODULE: ./node_modules/shallowequal/index.js
var shallowequal = __webpack_require__("Gytx");
var shallowequal_default = /*#__PURE__*/__webpack_require__.n(shallowequal);
// EXTERNAL MODULE: ./node_modules/rc-util/es/warning.js
var warning = __webpack_require__("Kwbf");
// EXTERNAL MODULE: ./node_modules/rc-resize-observer/es/index.js
var rc_resize_observer_es = __webpack_require__("t23M");
// EXTERNAL MODULE: ./node_modules/rc-util/es/getScrollBarSize.js
var getScrollBarSize = __webpack_require__("qx4F");
// CONCATENATED MODULE: ./node_modules/rc-table/es/sugar/ColumnGroup.js
/* istanbul ignore next */
/**
* This is a syntactic sugar for `columns` prop.
* So HOC will not work on this.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function ColumnGroup(_) {
return null;
}
/* harmony default export */ var sugar_ColumnGroup = (ColumnGroup);
// CONCATENATED MODULE: ./node_modules/rc-table/es/sugar/Column.js
/* istanbul ignore next */
/**
* This is a syntactic sugar for `columns` prop.
* So HOC will not work on this.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function Column(_) {
return null;
}
/* harmony default export */ var sugar_Column = (Column);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js
var objectWithoutProperties = __webpack_require__("Ff2n");
// EXTERNAL MODULE: ./node_modules/rc-util/es/ref.js
var es_ref = __webpack_require__("c+Xe");
// CONCATENATED MODULE: ./node_modules/rc-table/es/utils/valueUtil.js
var INTERNAL_KEY_PREFIX = 'RC_TABLE_KEY';
function toArray(arr) {
if (arr === undefined || arr === null) {
return [];
}
return Array.isArray(arr) ? arr : [arr];
}
function getPathValue(record, path) {
// Skip if path is empty
if (!path && typeof path !== 'number') {
return record;
}
var pathList = toArray(path);
var current = record;
for (var i = 0; i < pathList.length; i += 1) {
if (!current) {
return null;
}
var prop = pathList[i];
current = current[prop];
}
return current;
}
function getColumnsKey(columns) {
var columnKeys = [];
var keys = {};
columns.forEach(function (column) {
var _ref = column || {},
key = _ref.key,
dataIndex = _ref.dataIndex;
var mergedKey = key || toArray(dataIndex).join('-') || INTERNAL_KEY_PREFIX;
while (keys[mergedKey]) {
mergedKey = "".concat(mergedKey, "_next");
}
keys[mergedKey] = true;
columnKeys.push(mergedKey);
});
return columnKeys;
}
function mergeObject() {
var merged = {};
/* eslint-disable no-param-reassign */
function fillProps(obj, clone) {
if (clone) {
Object.keys(clone).forEach(function (key) {
var value = clone[key];
if (value && Object(esm_typeof["a" /* default */])(value) === 'object') {
obj[key] = obj[key] || {};
fillProps(obj[key], value);
} else {
obj[key] = value;
}
});
}
}
/* eslint-enable */
for (var _len = arguments.length, objects = new Array(_len), _key = 0; _key < _len; _key++) {
objects[_key] = arguments[_key];
}
objects.forEach(function (clone) {
fillProps(merged, clone);
});
return merged;
}
function validateValue(val) {
return val !== null && val !== undefined;
}
// CONCATENATED MODULE: ./node_modules/rc-table/es/Cell/index.js
function isRenderCell(data) {
return data && Object(esm_typeof["a" /* default */])(data) === 'object' && !Array.isArray(data) && !react["isValidElement"](data);
}
function isRefComponent(component) {
// String tag component also support ref
if (typeof component === 'string') {
return true;
}
return Object(es_ref["c" /* supportRef */])(component);
}
function Cell(_ref, ref) {
var _classNames;
var prefixCls = _ref.prefixCls,
className = _ref.className,
record = _ref.record,
index = _ref.index,
dataIndex = _ref.dataIndex,
render = _ref.render,
children = _ref.children,
_ref$component = _ref.component,
Component = _ref$component === void 0 ? 'td' : _ref$component,
colSpan = _ref.colSpan,
rowSpan = _ref.rowSpan,
fixLeft = _ref.fixLeft,
fixRight = _ref.fixRight,
firstFixLeft = _ref.firstFixLeft,
lastFixLeft = _ref.lastFixLeft,
firstFixRight = _ref.firstFixRight,
lastFixRight = _ref.lastFixRight,
appendNode = _ref.appendNode,
_ref$additionalProps = _ref.additionalProps,
additionalProps = _ref$additionalProps === void 0 ? {} : _ref$additionalProps,
ellipsis = _ref.ellipsis,
align = _ref.align,
rowType = _ref.rowType,
isSticky = _ref.isSticky;
var cellPrefixCls = "".concat(prefixCls, "-cell"); // ==================== Child Node ====================
var cellProps;
var childNode;
if (children) {
childNode = children;
} else {
var value = getPathValue(record, dataIndex); // Customize render node
childNode = value;
if (render) {
var renderData = render(value, record, index);
if (isRenderCell(renderData)) {
childNode = renderData.children;
cellProps = renderData.props;
} else {
childNode = renderData;
}
}
} // Not crash if final `childNode` is not validate ReactNode
if (Object(esm_typeof["a" /* default */])(childNode) === 'object' && !Array.isArray(childNode) && !react["isValidElement"](childNode)) {
childNode = null;
}
if (ellipsis && (lastFixLeft || firstFixRight)) {
childNode = react["createElement"]("span", {
className: "".concat(cellPrefixCls, "-content")
}, childNode);
}
var _ref2 = cellProps || {},
cellColSpan = _ref2.colSpan,
cellRowSpan = _ref2.rowSpan,
cellStyle = _ref2.style,
cellClassName = _ref2.className,
restCellProps = Object(objectWithoutProperties["a" /* default */])(_ref2, ["colSpan", "rowSpan", "style", "className"]);
var mergedColSpan = cellColSpan !== undefined ? cellColSpan : colSpan;
var mergedRowSpan = cellRowSpan !== undefined ? cellRowSpan : rowSpan;
if (mergedColSpan === 0 || mergedRowSpan === 0) {
return null;
} // ====================== Fixed =======================
var fixedStyle = {};
var isFixLeft = typeof fixLeft === 'number';
var isFixRight = typeof fixRight === 'number';
if (isFixLeft) {
fixedStyle.position = 'sticky';
fixedStyle.left = fixLeft;
}
if (isFixRight) {
fixedStyle.position = 'sticky';
fixedStyle.right = fixRight;
} // ====================== Align =======================
var alignStyle = {};
if (align) {
alignStyle.textAlign = align;
} // ====================== Render ======================
var title;
var ellipsisConfig = ellipsis === true ? {
showTitle: true
} : ellipsis;
if (ellipsisConfig && (ellipsisConfig.showTitle || rowType === 'header')) {
if (typeof childNode === 'string' || typeof childNode === 'number') {
title = childNode.toString();
} else if (react["isValidElement"](childNode) && typeof childNode.props.children === 'string') {
title = childNode.props.children;
}
}
var componentProps = Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({
title: title
}, restCellProps), additionalProps), {}, {
colSpan: mergedColSpan && mergedColSpan !== 1 ? mergedColSpan : null,
rowSpan: mergedRowSpan && mergedRowSpan !== 1 ? mergedRowSpan : null,
className: classnames_default()(cellPrefixCls, className, (_classNames = {}, Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(cellPrefixCls, "-fix-left"), isFixLeft), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(cellPrefixCls, "-fix-left-first"), firstFixLeft), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(cellPrefixCls, "-fix-left-last"), lastFixLeft), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(cellPrefixCls, "-fix-right"), isFixRight), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(cellPrefixCls, "-fix-right-first"), firstFixRight), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(cellPrefixCls, "-fix-right-last"), lastFixRight), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(cellPrefixCls, "-ellipsis"), ellipsis), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(cellPrefixCls, "-with-append"), appendNode), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(cellPrefixCls, "-fix-sticky"), (isFixLeft || isFixRight) && isSticky), _classNames), additionalProps.className, cellClassName),
style: Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, additionalProps.style), alignStyle), fixedStyle), cellStyle),
ref: isRefComponent(Component) ? ref : null
});
return react["createElement"](Component, Object.assign({}, componentProps), appendNode, childNode);
}
var RefCell = react["forwardRef"](Cell);
RefCell.displayName = 'Cell';
var MemoCell = react["memo"](RefCell, function (prev, next) {
if (next.shouldCellUpdate) {
return !next.shouldCellUpdate(next.record, prev.record);
}
return false;
});
/* harmony default export */ var es_Cell = (MemoCell);
// CONCATENATED MODULE: ./node_modules/rc-table/es/context/TableContext.js
var TableContext = react["createContext"](null);
/* harmony default export */ var context_TableContext = (TableContext);
// CONCATENATED MODULE: ./node_modules/rc-table/es/utils/fixUtil.js
function getCellFixedInfo(colStart, colEnd, columns, stickyOffsets, direction) {
var startColumn = columns[colStart] || {};
var endColumn = columns[colEnd] || {};
var fixLeft;
var fixRight;
if (startColumn.fixed === 'left') {
fixLeft = stickyOffsets.left[colStart];
} else if (endColumn.fixed === 'right') {
fixRight = stickyOffsets.right[colEnd];
}
var lastFixLeft = false;
var firstFixRight = false;
var lastFixRight = false;
var firstFixLeft = false;
var nextColumn = columns[colEnd + 1];
var prevColumn = columns[colStart - 1];
if (direction === 'rtl') {
if (fixLeft !== undefined) {
var prevFixLeft = prevColumn && prevColumn.fixed === 'left';
firstFixLeft = !prevFixLeft;
} else if (fixRight !== undefined) {
var nextFixRight = nextColumn && nextColumn.fixed === 'right';
lastFixRight = !nextFixRight;
}
} else if (fixLeft !== undefined) {
var nextFixLeft = nextColumn && nextColumn.fixed === 'left';
lastFixLeft = !nextFixLeft;
} else if (fixRight !== undefined) {
var prevFixRight = prevColumn && prevColumn.fixed === 'right';
firstFixRight = !prevFixRight;
}
return {
fixLeft: fixLeft,
fixRight: fixRight,
lastFixLeft: lastFixLeft,
firstFixRight: firstFixRight,
lastFixRight: lastFixRight,
firstFixLeft: firstFixLeft,
isSticky: stickyOffsets.isSticky
};
}
// CONCATENATED MODULE: ./node_modules/rc-table/es/Header/HeaderRow.js
function HeaderRow(_ref) {
var cells = _ref.cells,
stickyOffsets = _ref.stickyOffsets,
flattenColumns = _ref.flattenColumns,
RowComponent = _ref.rowComponent,
CellComponent = _ref.cellComponent,
onHeaderRow = _ref.onHeaderRow,
index = _ref.index;
var _React$useContext = react["useContext"](context_TableContext),
prefixCls = _React$useContext.prefixCls,
direction = _React$useContext.direction;
var rowProps;
if (onHeaderRow) {
rowProps = onHeaderRow(cells.map(function (cell) {
return cell.column;
}), index);
}
var columnsKey = getColumnsKey(cells.map(function (cell) {
return cell.column;
}));
return react["createElement"](RowComponent, Object.assign({}, rowProps), cells.map(function (cell, cellIndex) {
var column = cell.column;
var fixedInfo = getCellFixedInfo(cell.colStart, cell.colEnd, flattenColumns, stickyOffsets, direction);
var additionalProps;
if (column && column.onHeaderCell) {
additionalProps = cell.column.onHeaderCell(column);
}
return react["createElement"](es_Cell, Object.assign({}, cell, {
ellipsis: column.ellipsis,
align: column.align,
component: CellComponent,
prefixCls: prefixCls,
key: columnsKey[cellIndex]
}, fixedInfo, {
additionalProps: additionalProps,
rowType: "header"
}));
}));
}
HeaderRow.displayName = 'HeaderRow';
/* harmony default export */ var Header_HeaderRow = (HeaderRow);
// CONCATENATED MODULE: ./node_modules/rc-table/es/Header/Header.js
function parseHeaderRows(rootColumns) {
var rows = [];
function fillRowCells(columns, colIndex) {
var rowIndex = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
// Init rows
rows[rowIndex] = rows[rowIndex] || [];
var currentColIndex = colIndex;
var colSpans = columns.filter(Boolean).map(function (column) {
var cell = {
key: column.key,
className: column.className || '',
children: column.title,
column: column,
colStart: currentColIndex
};
var colSpan = 1;
var subColumns = column.children;
if (subColumns && subColumns.length > 0) {
colSpan = fillRowCells(subColumns, currentColIndex, rowIndex + 1).reduce(function (total, count) {
return total + count;
}, 0);
cell.hasSubColumns = true;
}
if ('colSpan' in column) {
colSpan = column.colSpan;
}
if ('rowSpan' in column) {
cell.rowSpan = column.rowSpan;
}
cell.colSpan = colSpan;
cell.colEnd = cell.colStart + colSpan - 1;
rows[rowIndex].push(cell);
currentColIndex += colSpan;
return colSpan;
});
return colSpans;
} // Generate `rows` cell data
fillRowCells(rootColumns, 0); // Handle `rowSpan`
var rowCount = rows.length;
var _loop = function _loop(rowIndex) {
rows[rowIndex].forEach(function (cell) {
if (!('rowSpan' in cell) && !cell.hasSubColumns) {
// eslint-disable-next-line no-param-reassign
cell.rowSpan = rowCount - rowIndex;
}
});
};
for (var rowIndex = 0; rowIndex < rowCount; rowIndex += 1) {
_loop(rowIndex);
}
return rows;
}
function Header(_ref) {
var stickyOffsets = _ref.stickyOffsets,
columns = _ref.columns,
flattenColumns = _ref.flattenColumns,
onHeaderRow = _ref.onHeaderRow;
var _React$useContext = react["useContext"](context_TableContext),
prefixCls = _React$useContext.prefixCls,
getComponent = _React$useContext.getComponent;
var rows = react["useMemo"](function () {
return parseHeaderRows(columns);
}, [columns]);
var WrapperComponent = getComponent(['header', 'wrapper'], 'thead');
var trComponent = getComponent(['header', 'row'], 'tr');
var thComponent = getComponent(['header', 'cell'], 'th');
return react["createElement"](WrapperComponent, {
className: "".concat(prefixCls, "-thead")
}, rows.map(function (row, rowIndex) {
var rowNode = react["createElement"](Header_HeaderRow, {
key: rowIndex,
flattenColumns: flattenColumns,
cells: row,
stickyOffsets: stickyOffsets,
rowComponent: trComponent,
cellComponent: thComponent,
onHeaderRow: onHeaderRow,
index: rowIndex
});
return rowNode;
}));
}
/* harmony default export */ var Header_Header = (Header);
// CONCATENATED MODULE: ./node_modules/rc-table/es/utils/legacyUtil.js
var INTERNAL_COL_DEFINE = 'RC_TABLE_INTERNAL_COL_DEFINE';
function getExpandableProps(props) {
var expandable = props.expandable,
legacyExpandableConfig = Object(objectWithoutProperties["a" /* default */])(props, ["expandable"]);
if ('expandable' in props) {
return Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, legacyExpandableConfig), expandable);
}
if (false) {}
return legacyExpandableConfig;
}
/**
* Returns only data- and aria- key/value pairs
* @param {object} props
*/
function getDataAndAriaProps(props) {
/* eslint-disable no-param-reassign */
return Object.keys(props).reduce(function (memo, key) {
if (key.substr(0, 5) === 'data-' || key.substr(0, 5) === 'aria-') {
memo[key] = props[key];
}
return memo;
}, {});
/* eslint-enable */
}
// CONCATENATED MODULE: ./node_modules/rc-table/es/ColGroup.js
function ColGroup(_ref) {
var colWidths = _ref.colWidths,
columns = _ref.columns,
columCount = _ref.columCount;
var cols = [];
var len = columCount || columns.length; // Only insert col with width & additional props
// Skip if rest col do not have any useful info
var mustInsert = false;
for (var i = len - 1; i >= 0; i -= 1) {
var width = colWidths[i];
var column = columns && columns[i];
var additionalProps = column && column[INTERNAL_COL_DEFINE];
if (width || additionalProps || mustInsert) {
cols.unshift(react["createElement"]("col", Object.assign({
key: i,
style: {
width: width,
minWidth: width
}
}, additionalProps)));
mustInsert = true;
}
}
return react["createElement"]("colgroup", null, cols);
}
/* harmony default export */ var es_ColGroup = (ColGroup);
// CONCATENATED MODULE: ./node_modules/rc-table/es/Header/FixedHeader.js
function useColumnWidth(colWidths, columCount) {
return Object(react["useMemo"])(function () {
var cloneColumns = [];
for (var i = 0; i < columCount; i += 1) {
var val = colWidths[i];
if (val !== undefined) {
cloneColumns[i] = val;
} else {
return null;
}
}
return cloneColumns;
}, [colWidths.join('_'), columCount]);
}
var FixedHeader = react["forwardRef"](function (_ref, ref) {
var noData = _ref.noData,
columns = _ref.columns,
flattenColumns = _ref.flattenColumns,
colWidths = _ref.colWidths,
columCount = _ref.columCount,
stickyOffsets = _ref.stickyOffsets,
direction = _ref.direction,
fixHeader = _ref.fixHeader,
offsetHeader = _ref.offsetHeader,
stickyClassName = _ref.stickyClassName,
onScroll = _ref.onScroll,
props = Object(objectWithoutProperties["a" /* default */])(_ref, ["noData", "columns", "flattenColumns", "colWidths", "columCount", "stickyOffsets", "direction", "fixHeader", "offsetHeader", "stickyClassName", "onScroll"]);
var _React$useContext = react["useContext"](context_TableContext),
prefixCls = _React$useContext.prefixCls,
scrollbarSize = _React$useContext.scrollbarSize,
isSticky = _React$useContext.isSticky;
var combinationScrollBarSize = isSticky && !fixHeader ? 0 : scrollbarSize; // Pass wheel to scroll event
var scrollRef = react["useRef"](null);
var setScrollRef = react["useCallback"](function (element) {
Object(es_ref["b" /* fillRef */])(ref, element);
Object(es_ref["b" /* fillRef */])(scrollRef, element);
}, []);
react["useEffect"](function () {
var _scrollRef$current;
function onWheel(e) {
var currentTarget = e.currentTarget,
deltaX = e.deltaX;
if (deltaX) {
onScroll({
currentTarget: currentTarget,
scrollLeft: currentTarget.scrollLeft + deltaX
});
e.preventDefault();
}
}
(_scrollRef$current = scrollRef.current) === null || _scrollRef$current === void 0 ? void 0 : _scrollRef$current.addEventListener('wheel', onWheel);
return function () {
var _scrollRef$current2;
(_scrollRef$current2 = scrollRef.current) === null || _scrollRef$current2 === void 0 ? void 0 : _scrollRef$current2.removeEventListener('wheel', onWheel);
};
}, []); // Add scrollbar column
var lastColumn = flattenColumns[flattenColumns.length - 1];
var ScrollBarColumn = {
fixed: lastColumn ? lastColumn.fixed : null,
onHeaderCell: function onHeaderCell() {
return {
className: "".concat(prefixCls, "-cell-scrollbar")
};
}
};
var columnsWithScrollbar = Object(react["useMemo"])(function () {
return combinationScrollBarSize ? [].concat(Object(toConsumableArray["a" /* default */])(columns), [ScrollBarColumn]) : columns;
}, [combinationScrollBarSize, columns]);
var flattenColumnsWithScrollbar = Object(react["useMemo"])(function () {
return combinationScrollBarSize ? [].concat(Object(toConsumableArray["a" /* default */])(flattenColumns), [ScrollBarColumn]) : flattenColumns;
}, [combinationScrollBarSize, flattenColumns]); // Calculate the sticky offsets
var headerStickyOffsets = Object(react["useMemo"])(function () {
var right = stickyOffsets.right,
left = stickyOffsets.left;
return Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, stickyOffsets), {}, {
left: direction === 'rtl' ? [].concat(Object(toConsumableArray["a" /* default */])(left.map(function (width) {
return width + combinationScrollBarSize;
})), [0]) : left,
right: direction === 'rtl' ? right : [].concat(Object(toConsumableArray["a" /* default */])(right.map(function (width) {
return width + combinationScrollBarSize;
})), [0]),
isSticky: isSticky
});
}, [combinationScrollBarSize, stickyOffsets, isSticky]);
var mergedColumnWidth = useColumnWidth(colWidths, columCount);
return react["createElement"]("div", {
style: Object(objectSpread2["a" /* default */])({
overflow: 'hidden'
}, isSticky ? {
top: offsetHeader
} : {}),
ref: setScrollRef,
className: classnames_default()("".concat(prefixCls, "-header"), Object(esm_defineProperty["a" /* default */])({}, stickyClassName, !!stickyClassName))
}, react["createElement"]("table", {
style: {
tableLayout: 'fixed',
visibility: noData || mergedColumnWidth ? null : 'hidden'
}
}, react["createElement"](es_ColGroup, {
colWidths: mergedColumnWidth ? [].concat(Object(toConsumableArray["a" /* default */])(mergedColumnWidth), [combinationScrollBarSize]) : [],
columCount: columCount + 1,
columns: flattenColumnsWithScrollbar
}), react["createElement"](Header_Header, Object.assign({}, props, {
stickyOffsets: headerStickyOffsets,
columns: columnsWithScrollbar,
flattenColumns: flattenColumnsWithScrollbar
}))));
});
FixedHeader.displayName = 'FixedHeader';
/* harmony default export */ var Header_FixedHeader = (FixedHeader);
// CONCATENATED MODULE: ./node_modules/rc-table/es/context/BodyContext.js
var BodyContext = react["createContext"](null);
/* harmony default export */ var context_BodyContext = (BodyContext);
// CONCATENATED MODULE: ./node_modules/rc-table/es/Body/ExpandedRow.js
function ExpandedRow(_ref) {
var prefixCls = _ref.prefixCls,
children = _ref.children,
Component = _ref.component,
cellComponent = _ref.cellComponent,
fixHeader = _ref.fixHeader,
fixColumn = _ref.fixColumn,
horizonScroll = _ref.horizonScroll,
className = _ref.className,
expanded = _ref.expanded,
componentWidth = _ref.componentWidth,
colSpan = _ref.colSpan;
var _React$useContext = react["useContext"](context_TableContext),
scrollbarSize = _React$useContext.scrollbarSize; // Cache render node
return react["useMemo"](function () {
var contentNode = children;
if (fixColumn) {
contentNode = react["createElement"]("div", {
style: {
width: componentWidth - (fixHeader ? scrollbarSize : 0),
position: 'sticky',
left: 0,
overflow: 'hidden'
},
className: "".concat(prefixCls, "-expanded-row-fixed")
}, contentNode);
}
return react["createElement"](Component, {
className: className,
style: {
display: expanded ? null : 'none'
}
}, react["createElement"](es_Cell, {
component: cellComponent,
prefixCls: prefixCls,
colSpan: colSpan
}, contentNode));
}, [children, Component, fixHeader, horizonScroll, className, expanded, componentWidth, colSpan, scrollbarSize]);
}
/* harmony default export */ var Body_ExpandedRow = (ExpandedRow);
// CONCATENATED MODULE: ./node_modules/rc-table/es/Body/BodyRow.js
function BodyRow(props) {
var className = props.className,
style = props.style,
record = props.record,
index = props.index,
rowKey = props.rowKey,
getRowKey = props.getRowKey,
rowExpandable = props.rowExpandable,
expandedKeys = props.expandedKeys,
onRow = props.onRow,
_props$indent = props.indent,
indent = _props$indent === void 0 ? 0 : _props$indent,
RowComponent = props.rowComponent,
cellComponent = props.cellComponent,
childrenColumnName = props.childrenColumnName;
var _React$useContext = react["useContext"](context_TableContext),
prefixCls = _React$useContext.prefixCls,
fixedInfoList = _React$useContext.fixedInfoList;
var _React$useContext2 = react["useContext"](context_BodyContext),
fixHeader = _React$useContext2.fixHeader,
fixColumn = _React$useContext2.fixColumn,
horizonScroll = _React$useContext2.horizonScroll,
componentWidth = _React$useContext2.componentWidth,
flattenColumns = _React$useContext2.flattenColumns,
expandableType = _React$useContext2.expandableType,
expandRowByClick = _React$useContext2.expandRowByClick,
onTriggerExpand = _React$useContext2.onTriggerExpand,
rowClassName = _React$useContext2.rowClassName,
expandedRowClassName = _React$useContext2.expandedRowClassName,
indentSize = _React$useContext2.indentSize,
expandIcon = _React$useContext2.expandIcon,
expandedRowRender = _React$useContext2.expandedRowRender,
expandIconColumnIndex = _React$useContext2.expandIconColumnIndex;
var _React$useState = react["useState"](false),
_React$useState2 = Object(esm_slicedToArray["a" /* default */])(_React$useState, 2),
expandRended = _React$useState2[0],
setExpandRended = _React$useState2[1];
var expanded = expandedKeys && expandedKeys.has(props.recordKey);
react["useEffect"](function () {
if (expanded) {
setExpandRended(true);
}
}, [expanded]);
var rowSupportExpand = expandableType === 'row' && (!rowExpandable || rowExpandable(record)); // Only when row is not expandable and `children` exist in record
var nestExpandable = expandableType === 'nest';
var hasNestChildren = childrenColumnName && record && record[childrenColumnName];
var mergedExpandable = rowSupportExpand || nestExpandable; // =========================== onRow ===========================
var additionalProps;
if (onRow) {
additionalProps = onRow(record, index);
}
var onClick = function onClick(event) {
if (expandRowByClick && mergedExpandable) {
onTriggerExpand(record, event);
}
if (additionalProps && additionalProps.onClick) {
var _additionalProps;
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
(_additionalProps = additionalProps).onClick.apply(_additionalProps, [event].concat(args));
}
}; // ======================== Base tr row ========================
var computeRowClassName;
if (typeof rowClassName === 'string') {
computeRowClassName = rowClassName;
} else if (typeof rowClassName === 'function') {
computeRowClassName = rowClassName(record, index, indent);
}
var columnsKey = getColumnsKey(flattenColumns);
var baseRowNode = react["createElement"](RowComponent, Object.assign({}, additionalProps, {
"data-row-key": rowKey,
className: classnames_default()(className, "".concat(prefixCls, "-row"), "".concat(prefixCls, "-row-level-").concat(indent), computeRowClassName, additionalProps && additionalProps.className),
style: Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, style), additionalProps ? additionalProps.style : null),
onClick: onClick
}), flattenColumns.map(function (column, colIndex) {
var render = column.render,
dataIndex = column.dataIndex,
columnClassName = column.className;
var key = columnsKey[colIndex];
var fixedInfo = fixedInfoList[colIndex]; // ============= Used for nest expandable =============
var appendCellNode;
if (colIndex === (expandIconColumnIndex || 0) && nestExpandable) {
appendCellNode = react["createElement"](react["Fragment"], null, react["createElement"]("span", {
style: {
paddingLeft: "".concat(indentSize * indent, "px")
},
className: "".concat(prefixCls, "-row-indent indent-level-").concat(indent)
}), expandIcon({
prefixCls: prefixCls,
expanded: expanded,
expandable: hasNestChildren,
record: record,
onExpand: onTriggerExpand
}));
}
var additionalCellProps;
if (column.onCell) {
additionalCellProps = column.onCell(record, index);
}
return react["createElement"](es_Cell, Object.assign({
className: columnClassName,
ellipsis: column.ellipsis,
align: column.align,
component: cellComponent,
prefixCls: prefixCls,
key: key,
record: record,
index: index,
dataIndex: dataIndex,
render: render,
shouldCellUpdate: column.shouldCellUpdate
}, fixedInfo, {
appendNode: appendCellNode,
additionalProps: additionalCellProps
}));
})); // ======================== Expand Row =========================
var expandRowNode;
if (rowSupportExpand && (expandRended || expanded)) {
var expandContent = expandedRowRender(record, index, indent + 1, expanded);
var computedExpandedRowClassName = expandedRowClassName && expandedRowClassName(record, index, indent);
expandRowNode = react["createElement"](Body_ExpandedRow, {
expanded: expanded,
className: classnames_default()("".concat(prefixCls, "-expanded-row"), "".concat(prefixCls, "-expanded-row-level-").concat(indent + 1), computedExpandedRowClassName),
prefixCls: prefixCls,
fixHeader: fixHeader,
fixColumn: fixColumn,
horizonScroll: horizonScroll,
component: RowComponent,
componentWidth: componentWidth,
cellComponent: cellComponent,
colSpan: flattenColumns.length
}, expandContent);
} // ========================= Nest Row ==========================
var nestRowNode;
if (hasNestChildren && expanded) {
nestRowNode = (record[childrenColumnName] || []).map(function (subRecord, subIndex) {
var subKey = getRowKey(subRecord, subIndex);
return react["createElement"](BodyRow, Object.assign({}, props, {
key: subKey,
rowKey: subKey,
record: subRecord,
recordKey: subKey,
index: subIndex,
indent: indent + 1
}));
});
}
return react["createElement"](react["Fragment"], null, baseRowNode, expandRowNode, nestRowNode);
}
BodyRow.displayName = 'BodyRow';
/* harmony default export */ var Body_BodyRow = (BodyRow);
// CONCATENATED MODULE: ./node_modules/rc-table/es/context/ResizeContext.js
var ResizeContext = react["createContext"](null);
/* harmony default export */ var context_ResizeContext = (ResizeContext);
// CONCATENATED MODULE: ./node_modules/rc-table/es/Body/MeasureCell.js
function MeasureCell(_ref) {
var columnKey = _ref.columnKey,
onColumnResize = _ref.onColumnResize;
var cellRef = react["useRef"]();
react["useEffect"](function () {
if (cellRef.current) {
onColumnResize(columnKey, cellRef.current.offsetWidth);
}
}, []);
return react["createElement"](rc_resize_observer_es["a" /* default */], {
onResize: function onResize(_ref2) {
var offsetWidth = _ref2.offsetWidth;
onColumnResize(columnKey, offsetWidth);
}
}, react["createElement"]("td", {
ref: cellRef,
style: {
padding: 0,
border: 0,
height: 0
}
}, react["createElement"]("div", {
style: {
height: 0,
overflow: 'hidden'
}
}, "\xA0")));
}
// CONCATENATED MODULE: ./node_modules/rc-table/es/Body/index.js
function Body(_ref) {
var data = _ref.data,
getRowKey = _ref.getRowKey,
measureColumnWidth = _ref.measureColumnWidth,
expandedKeys = _ref.expandedKeys,
onRow = _ref.onRow,
rowExpandable = _ref.rowExpandable,
emptyNode = _ref.emptyNode,
childrenColumnName = _ref.childrenColumnName;
var _React$useContext = react["useContext"](context_ResizeContext),
onColumnResize = _React$useContext.onColumnResize;
var _React$useContext2 = react["useContext"](context_TableContext),
prefixCls = _React$useContext2.prefixCls,
getComponent = _React$useContext2.getComponent;
var _React$useContext3 = react["useContext"](context_BodyContext),
fixHeader = _React$useContext3.fixHeader,
horizonScroll = _React$useContext3.horizonScroll,
flattenColumns = _React$useContext3.flattenColumns,
componentWidth = _React$useContext3.componentWidth;
return react["useMemo"](function () {
var WrapperComponent = getComponent(['body', 'wrapper'], 'tbody');
var trComponent = getComponent(['body', 'row'], 'tr');
var tdComponent = getComponent(['body', 'cell'], 'td');
var rows;
if (data.length) {
rows = data.map(function (record, index) {
var key = getRowKey(record, index);
return react["createElement"](Body_BodyRow, {
key: key,
rowKey: key,
record: record,
recordKey: key,
index: index,
rowComponent: trComponent,
cellComponent: tdComponent,
expandedKeys: expandedKeys,
onRow: onRow,
getRowKey: getRowKey,
rowExpandable: rowExpandable,
childrenColumnName: childrenColumnName
});
});
} else {
rows = react["createElement"](Body_ExpandedRow, {
expanded: true,
className: "".concat(prefixCls, "-placeholder"),
prefixCls: prefixCls,
fixHeader: fixHeader,
fixColumn: horizonScroll,
horizonScroll: horizonScroll,
component: trComponent,
componentWidth: componentWidth,
cellComponent: tdComponent,
colSpan: flattenColumns.length
}, emptyNode);
}
var columnsKey = getColumnsKey(flattenColumns);
return react["createElement"](WrapperComponent, {
className: "".concat(prefixCls, "-tbody")
}, measureColumnWidth && react["createElement"]("tr", {
"aria-hidden": "true",
className: "".concat(prefixCls, "-measure-row"),
style: {
height: 0
}
}, columnsKey.map(function (columnKey) {
return react["createElement"](MeasureCell, {
key: columnKey,
columnKey: columnKey,
onColumnResize: onColumnResize
});
})), rows);
}, [data, prefixCls, onRow, measureColumnWidth, expandedKeys, getRowKey, getComponent, componentWidth, emptyNode, flattenColumns]);
}
var MemoBody = react["memo"](Body);
MemoBody.displayName = 'Body';
/* harmony default export */ var es_Body = (MemoBody);
// EXTERNAL MODULE: ./node_modules/rc-util/es/Children/toArray.js
var Children_toArray = __webpack_require__("Zm9Q");
// CONCATENATED MODULE: ./node_modules/rc-table/es/hooks/useColumns.js
function convertChildrenToColumns(children) {
return Object(Children_toArray["a" /* default */])(children).filter(function (node) {
return react["isValidElement"](node);
}).map(function (_ref) {
var key = _ref.key,
props = _ref.props;
var nodeChildren = props.children,
restProps = Object(objectWithoutProperties["a" /* default */])(props, ["children"]);
var column = Object(objectSpread2["a" /* default */])({
key: key
}, restProps);
if (nodeChildren) {
column.children = convertChildrenToColumns(nodeChildren);
}
return column;
});
}
function flatColumns(columns) {
return columns.reduce(function (list, column) {
var fixed = column.fixed; // Convert `fixed='true'` to `fixed='left'` instead
var parsedFixed = fixed === true ? 'left' : fixed;
var subColumns = column.children;
if (subColumns && subColumns.length > 0) {
return [].concat(Object(toConsumableArray["a" /* default */])(list), Object(toConsumableArray["a" /* default */])(flatColumns(subColumns).map(function (subColum) {
return Object(objectSpread2["a" /* default */])({
fixed: parsedFixed
}, subColum);
})));
}
return [].concat(Object(toConsumableArray["a" /* default */])(list), [Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, column), {}, {
fixed: parsedFixed
})]);
}, []);
}
function warningFixed(flattenColumns) {
var allFixLeft = true;
for (var i = 0; i < flattenColumns.length; i += 1) {
var col = flattenColumns[i];
if (allFixLeft && col.fixed !== 'left') {
allFixLeft = false;
} else if (!allFixLeft && col.fixed === 'left') {
Object(warning["a" /* default */])(false, "Index ".concat(i - 1, " of `columns` missing `fixed='left'` prop."));
break;
}
}
var allFixRight = true;
for (var _i = flattenColumns.length - 1; _i >= 0; _i -= 1) {
var _col = flattenColumns[_i];
if (allFixRight && _col.fixed !== 'right') {
allFixRight = false;
} else if (!allFixRight && _col.fixed === 'right') {
Object(warning["a" /* default */])(false, "Index ".concat(_i + 1, " of `columns` missing `fixed='right'` prop."));
break;
}
}
}
function revertForRtl(columns) {
return columns.map(function (column) {
var fixed = column.fixed,
restProps = Object(objectWithoutProperties["a" /* default */])(column, ["fixed"]); // Convert `fixed='left'` to `fixed='right'` instead
var parsedFixed = fixed;
if (fixed === 'left') {
parsedFixed = 'right';
} else if (fixed === 'right') {
parsedFixed = 'left';
}
return Object(objectSpread2["a" /* default */])({
fixed: parsedFixed
}, restProps);
});
}
/**
* Parse `columns` & `children` into `columns`.
*/
function useColumns(_ref2, transformColumns) {
var prefixCls = _ref2.prefixCls,
columns = _ref2.columns,
children = _ref2.children,
expandable = _ref2.expandable,
expandedKeys = _ref2.expandedKeys,
getRowKey = _ref2.getRowKey,
onTriggerExpand = _ref2.onTriggerExpand,
expandIcon = _ref2.expandIcon,
rowExpandable = _ref2.rowExpandable,
expandIconColumnIndex = _ref2.expandIconColumnIndex,
direction = _ref2.direction,
expandRowByClick = _ref2.expandRowByClick;
var baseColumns = react["useMemo"](function () {
return columns || convertChildrenToColumns(children);
}, [columns, children]); // Add expand column
var withExpandColumns = react["useMemo"](function () {
if (expandable) {
var _expandColumn;
var expandColIndex = expandIconColumnIndex || 0;
var prevColumn = baseColumns[expandColIndex];
var expandColumn = (_expandColumn = {}, Object(esm_defineProperty["a" /* default */])(_expandColumn, INTERNAL_COL_DEFINE, {
className: "".concat(prefixCls, "-expand-icon-col")
}), Object(esm_defineProperty["a" /* default */])(_expandColumn, "title", ''), Object(esm_defineProperty["a" /* default */])(_expandColumn, "fixed", prevColumn ? prevColumn.fixed : null), Object(esm_defineProperty["a" /* default */])(_expandColumn, "className", "".concat(prefixCls, "-row-expand-icon-cell")), Object(esm_defineProperty["a" /* default */])(_expandColumn, "render", function render(_, record, index) {
var rowKey = getRowKey(record, index);
var expanded = expandedKeys.has(rowKey);
var recordExpandable = rowExpandable ? rowExpandable(record) : true;
var icon = expandIcon({
prefixCls: prefixCls,
expanded: expanded,
expandable: recordExpandable,
record: record,
onExpand: onTriggerExpand
});
if (expandRowByClick) {
return react["createElement"]("span", {
onClick: function onClick(e) {
return e.stopPropagation();
}
}, icon);
}
return icon;
}), _expandColumn); // Insert expand column in the target position
var cloneColumns = baseColumns.slice();
if (expandColIndex >= 0) {
cloneColumns.splice(expandColIndex, 0, expandColumn);
}
return cloneColumns;
}
return baseColumns;
}, [expandable, baseColumns, getRowKey, expandedKeys, expandIcon, direction]);
var mergedColumns = react["useMemo"](function () {
var finalColumns = withExpandColumns;
if (transformColumns) {
finalColumns = transformColumns(finalColumns);
} // Always provides at least one column for table display
if (!finalColumns.length) {
finalColumns = [{
render: function render() {
return null;
}
}];
}
return finalColumns;
}, [transformColumns, withExpandColumns, direction]);
var flattenColumns = react["useMemo"](function () {
if (direction === 'rtl') {
return revertForRtl(flatColumns(mergedColumns));
}
return flatColumns(mergedColumns);
}, [mergedColumns, direction]); // Only check out of production since it's waste for each render
if (false) {}
return [mergedColumns, flattenColumns];
}
/* harmony default export */ var hooks_useColumns = (useColumns);
// EXTERNAL MODULE: ./node_modules/raf/index.js
var raf = __webpack_require__("xEkU");
var raf_default = /*#__PURE__*/__webpack_require__.n(raf);
// CONCATENATED MODULE: ./node_modules/rc-table/es/hooks/useFrame.js
function useFrameState(defaultState) {
var stateRef = Object(react["useRef"])(defaultState);
var _useState = Object(react["useState"])({}),
_useState2 = Object(esm_slicedToArray["a" /* default */])(_useState, 2),
forceUpdate = _useState2[1];
var timeoutRef = Object(react["useRef"])(null);
var updateBatchRef = Object(react["useRef"])([]);
function setFrameState(updater) {
if (timeoutRef.current === null) {
updateBatchRef.current = [];
timeoutRef.current = raf_default()(function () {
updateBatchRef.current.forEach(function (batchUpdater) {
stateRef.current = batchUpdater(stateRef.current);
});
timeoutRef.current = null;
forceUpdate({});
});
}
updateBatchRef.current.push(updater);
}
Object(react["useEffect"])(function () {
return function () {
raf_default.a.cancel(timeoutRef.current);
};
}, []);
return [stateRef.current, setFrameState];
}
/** Lock frame, when frame pass reset the lock. */
function useTimeoutLock(defaultState) {
var frameRef = Object(react["useRef"])(defaultState);
var timeoutRef = Object(react["useRef"])(null);
function cleanUp() {
window.clearTimeout(timeoutRef.current);
}
function setState(newState) {
frameRef.current = newState;
cleanUp();
timeoutRef.current = window.setTimeout(function () {
frameRef.current = null;
timeoutRef.current = null;
}, 100);
}
function getState() {
return frameRef.current;
}
Object(react["useEffect"])(function () {
return cleanUp;
}, []);
return [setState, getState];
}
// CONCATENATED MODULE: ./node_modules/rc-table/es/hooks/useStickyOffsets.js
/**
* Get sticky column offset width
*/
function useStickyOffsets(colWidths, columCount, direction) {
var stickyOffsets = Object(react["useMemo"])(function () {
var leftOffsets = [];
var rightOffsets = [];
var left = 0;
var right = 0;
for (var start = 0; start < columCount; start += 1) {
if (direction === 'rtl') {
// Left offset
rightOffsets[start] = right;
right += colWidths[start] || 0; // Right offset
var end = columCount - start - 1;
leftOffsets[end] = left;
left += colWidths[end] || 0;
} else {
// Left offset
leftOffsets[start] = left;
left += colWidths[start] || 0; // Right offset
var _end = columCount - start - 1;
rightOffsets[_end] = right;
right += colWidths[_end] || 0;
}
}
return {
left: leftOffsets,
right: rightOffsets
};
}, [colWidths, columCount, direction]);
return stickyOffsets;
}
/* harmony default export */ var hooks_useStickyOffsets = (useStickyOffsets);
// CONCATENATED MODULE: ./node_modules/rc-table/es/Panel/index.js
function Panel(_ref) {
var className = _ref.className,
children = _ref.children;
return react["createElement"]("div", {
className: className
}, children);
}
/* harmony default export */ var es_Panel = (Panel);
// CONCATENATED MODULE: ./node_modules/rc-table/es/Footer/Cell.js
function SummaryCell(_ref) {
var className = _ref.className,
index = _ref.index,
children = _ref.children,
colSpan = _ref.colSpan,
rowSpan = _ref.rowSpan;
var _React$useContext = react["useContext"](context_TableContext),
prefixCls = _React$useContext.prefixCls,
fixedInfoList = _React$useContext.fixedInfoList;
var fixedInfo = fixedInfoList[index];
return react["createElement"](es_Cell, Object.assign({
className: className,
index: index,
component: "td",
prefixCls: prefixCls,
record: null,
dataIndex: null,
render: function render() {
return {
children: children,
props: {
colSpan: colSpan,
rowSpan: rowSpan
}
};
}
}, fixedInfo));
}
// CONCATENATED MODULE: ./node_modules/rc-table/es/Footer/Row.js
function FooterRow(props) {
return react["createElement"]("tr", Object.assign({}, props));
}
// CONCATENATED MODULE: ./node_modules/rc-table/es/Footer/index.js
function Footer(_ref) {
var children = _ref.children;
var _React$useContext = react["useContext"](context_TableContext),
prefixCls = _React$useContext.prefixCls;
return react["createElement"]("tfoot", {
className: "".concat(prefixCls, "-summary")
}, children);
}
/* harmony default export */ var es_Footer = (Footer);
var FooterComponents = {
Cell: SummaryCell,
Row: FooterRow
};
// CONCATENATED MODULE: ./node_modules/rc-table/es/utils/expandUtil.js
function renderExpandIcon(_ref) {
var _classNames;
var prefixCls = _ref.prefixCls,
record = _ref.record,
onExpand = _ref.onExpand,
expanded = _ref.expanded,
expandable = _ref.expandable;
var expandClassName = "".concat(prefixCls, "-row-expand-icon");
if (!expandable) {
return react["createElement"]("span", {
className: classnames_default()(expandClassName, "".concat(prefixCls, "-row-spaced"))
});
}
var onClick = function onClick(event) {
onExpand(record, event);
event.stopPropagation();
};
return react["createElement"]("span", {
className: classnames_default()(expandClassName, (_classNames = {}, Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-row-expanded"), expanded), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-row-collapsed"), !expanded), _classNames)),
onClick: onClick
});
}
function findAllChildrenKeys(data, getRowKey, childrenColumnName) {
var keys = [];
function dig(list) {
(list || []).forEach(function (item, index) {
keys.push(getRowKey(item, index));
dig(item[childrenColumnName]);
});
}
dig(data);
return keys;
}
// EXTERNAL MODULE: ./node_modules/rc-util/es/Dom/addEventListener.js
var addEventListener = __webpack_require__("zT1h");
// CONCATENATED MODULE: ./node_modules/rc-util/es/Dom/css.js
/* eslint-disable no-nested-ternary */
var PIXEL_PATTERN = /margin|padding|width|height|max|min|offset/;
var removePixel = {
left: true,
top: true
};
var floatMap = {
cssFloat: 1,
styleFloat: 1,
float: 1
};
function getComputedStyle(node) {
return node.nodeType === 1 ? node.ownerDocument.defaultView.getComputedStyle(node, null) : {};
}
function getStyleValue(node, type, value) {
type = type.toLowerCase();
if (value === 'auto') {
if (type === 'height') {
return node.offsetHeight;
}
if (type === 'width') {
return node.offsetWidth;
}
}
if (!(type in removePixel)) {
removePixel[type] = PIXEL_PATTERN.test(type);
}
return removePixel[type] ? parseFloat(value) || 0 : value;
}
function css_get(node, name) {
var length = arguments.length;
var style = getComputedStyle(node);
name = floatMap[name] ? 'cssFloat' in node.style ? 'cssFloat' : 'styleFloat' : name;
return length === 1 ? style : getStyleValue(node, name, style[name] || node.style[name]);
}
function set(node, name, value) {
var length = arguments.length;
name = floatMap[name] ? 'cssFloat' in node.style ? 'cssFloat' : 'styleFloat' : name;
if (length === 3) {
if (typeof value === 'number' && PIXEL_PATTERN.test(name)) {
value = "".concat(value, "px");
}
node.style[name] = value; // Number
return value;
}
for (var x in name) {
if (name.hasOwnProperty(x)) {
set(node, x, name[x]);
}
}
return getComputedStyle(node);
}
function getOuterWidth(el) {
if (el === document.body) {
return document.documentElement.clientWidth;
}
return el.offsetWidth;
}
function getOuterHeight(el) {
if (el === document.body) {
return window.innerHeight || document.documentElement.clientHeight;
}
return el.offsetHeight;
}
function getDocSize() {
var width = Math.max(document.documentElement.scrollWidth, document.body.scrollWidth);
var height = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
return {
width: width,
height: height
};
}
function getClientSize() {
var width = document.documentElement.clientWidth;
var height = window.innerHeight || document.documentElement.clientHeight;
return {
width: width,
height: height
};
}
function getScroll() {
return {
scrollLeft: Math.max(document.documentElement.scrollLeft, document.body.scrollLeft),
scrollTop: Math.max(document.documentElement.scrollTop, document.body.scrollTop)
};
}
function getOffset(node) {
var box = node.getBoundingClientRect();
var docElem = document.documentElement; // < ie8 不支持 win.pageXOffset, 则使用 docElem.scrollLeft
return {
left: box.left + (window.pageXOffset || docElem.scrollLeft) - (docElem.clientLeft || document.body.clientLeft || 0),
top: box.top + (window.pageYOffset || docElem.scrollTop) - (docElem.clientTop || document.body.clientTop || 0)
};
}
// CONCATENATED MODULE: ./node_modules/rc-table/es/stickyScrollBar.js
var stickyScrollBar_StickyScrollBar = function StickyScrollBar(_ref, ref) {
var _scrollBodyRef$curren, _scrollBodyRef$curren2;
var scrollBodyRef = _ref.scrollBodyRef,
onScroll = _ref.onScroll,
offsetScroll = _ref.offsetScroll;
var _React$useContext = react["useContext"](context_TableContext),
prefixCls = _React$useContext.prefixCls;
var bodyScrollWidth = ((_scrollBodyRef$curren = scrollBodyRef.current) === null || _scrollBodyRef$curren === void 0 ? void 0 : _scrollBodyRef$curren.scrollWidth) || 0;
var bodyWidth = ((_scrollBodyRef$curren2 = scrollBodyRef.current) === null || _scrollBodyRef$curren2 === void 0 ? void 0 : _scrollBodyRef$curren2.clientWidth) || 0;
var scrollBarWidth = bodyScrollWidth && bodyWidth * (bodyWidth / bodyScrollWidth);
var scrollBarRef = react["useRef"]();
var _useFrameState = useFrameState({
scrollLeft: 0,
isHiddenScrollBar: false
}),
_useFrameState2 = Object(esm_slicedToArray["a" /* default */])(_useFrameState, 2),
frameState = _useFrameState2[0],
setFrameState = _useFrameState2[1];
var refState = react["useRef"]({
delta: 0,
x: 0
});
var _React$useState = react["useState"](false),
_React$useState2 = Object(esm_slicedToArray["a" /* default */])(_React$useState, 2),
isActive = _React$useState2[0],
setActive = _React$useState2[1];
var onMouseUp = function onMouseUp() {
setActive(false);
};
var onMouseDown = function onMouseDown(event) {
event.persist();
refState.current.delta = event.pageX - frameState.scrollLeft;
refState.current.x = 0;
setActive(true);
event.preventDefault();
};
var onMouseMove = function onMouseMove(event) {
var _window;
// https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons
var _ref2 = event || ((_window = window) === null || _window === void 0 ? void 0 : _window.event),
buttons = _ref2.buttons;
if (!isActive || buttons === 0) {
// If out body mouse up, we can set isActive false when mouse move
if (isActive) {
setActive(false);
}
return;
}
var left = refState.current.x + event.pageX - refState.current.x - refState.current.delta;
if (left <= 0) {
left = 0;
}
if (left + scrollBarWidth >= bodyWidth) {
left = bodyWidth - scrollBarWidth;
}
onScroll({
scrollLeft: left / bodyWidth * (bodyScrollWidth + 2)
});
refState.current.x = event.pageX;
};
var onContainerScroll = function onContainerScroll() {
var tableOffsetTop = getOffset(scrollBodyRef.current).top;
var tableBottomOffset = tableOffsetTop + scrollBodyRef.current.offsetHeight;
var currentClientOffset = document.documentElement.scrollTop + window.innerHeight;
if (tableBottomOffset - Object(getScrollBarSize["a" /* default */])() <= currentClientOffset || tableOffsetTop >= currentClientOffset - offsetScroll) {
setFrameState(function (state) {
return Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, state), {}, {
isHiddenScrollBar: true
});
});
} else {
setFrameState(function (state) {
return Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, state), {}, {
isHiddenScrollBar: false
});
});
}
};
var setScrollLeft = function setScrollLeft(left) {
setFrameState(function (state) {
return Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, state), {}, {
scrollLeft: left / bodyScrollWidth * bodyWidth || 0
});
});
};
react["useImperativeHandle"](ref, function () {
return {
setScrollLeft: setScrollLeft
};
});
react["useEffect"](function () {
var onMouseUpListener = Object(addEventListener["a" /* default */])(document.body, 'mouseup', onMouseUp, false);
var onMouseMoveListener = Object(addEventListener["a" /* default */])(document.body, 'mousemove', onMouseMove, false);
onContainerScroll();
return function () {
onMouseUpListener.remove();
onMouseMoveListener.remove();
};
}, [scrollBarWidth, isActive]);
react["useEffect"](function () {
var onScrollListener = Object(addEventListener["a" /* default */])(window, 'scroll', onContainerScroll, false);
var onResizeListener = Object(addEventListener["a" /* default */])(window, 'resize', onContainerScroll, false);
return function () {
onScrollListener.remove();
onResizeListener.remove();
};
}, []);
react["useEffect"](function () {
if (!frameState.isHiddenScrollBar) {
setFrameState(function (state) {
var _scrollBodyRef$curren3, _scrollBodyRef$curren4;
return Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, state), {}, {
scrollLeft: scrollBodyRef.current.scrollLeft / ((_scrollBodyRef$curren3 = scrollBodyRef.current) === null || _scrollBodyRef$curren3 === void 0 ? void 0 : _scrollBodyRef$curren3.scrollWidth) * ((_scrollBodyRef$curren4 = scrollBodyRef.current) === null || _scrollBodyRef$curren4 === void 0 ? void 0 : _scrollBodyRef$curren4.clientWidth)
});
});
}
}, [frameState.isHiddenScrollBar]);
if (bodyScrollWidth <= bodyWidth || !scrollBarWidth || frameState.isHiddenScrollBar) {
return null;
}
return react["createElement"]("div", {
style: {
height: Object(getScrollBarSize["a" /* default */])(),
width: bodyWidth,
bottom: offsetScroll
},
className: "".concat(prefixCls, "-sticky-scroll")
}, react["createElement"]("div", {
onMouseDown: onMouseDown,
ref: scrollBarRef,
className: classnames_default()("".concat(prefixCls, "-sticky-scroll-bar"), Object(esm_defineProperty["a" /* default */])({}, "".concat(prefixCls, "-sticky-scroll-bar-active"), isActive)),
style: {
width: "".concat(scrollBarWidth, "px"),
transform: "translate3d(".concat(frameState.scrollLeft, "px, 0, 0)")
}
}));
};
/* harmony default export */ var stickyScrollBar = (react["forwardRef"](stickyScrollBar_StickyScrollBar));
// CONCATENATED MODULE: ./node_modules/rc-table/es/hooks/useSticky.js
/** Sticky header hooks */
function useSticky(sticky, prefixCls) {
return react["useMemo"](function () {
var isSticky = !!sticky;
return {
isSticky: isSticky,
stickyClassName: isSticky ? "".concat(prefixCls, "-sticky-header") : '',
offsetHeader: Object(esm_typeof["a" /* default */])(sticky) === 'object' ? sticky.offsetHeader || 0 : 0,
offsetScroll: Object(esm_typeof["a" /* default */])(sticky) === 'object' ? sticky.offsetScroll || 0 : 0
};
}, [sticky, prefixCls]);
}
// CONCATENATED MODULE: ./node_modules/rc-table/es/Table.js
/**
* Feature:
* - fixed not need to set width
* - support `rowExpandable` to config row expand logic
* - add `summary` to support `() => ReactNode`
*
* Update:
* - `dataIndex` is `array[]` now
* - `expandable` wrap all the expand related props
*
* Removed:
* - expandIconAsCell
* - useFixedHeader
* - rowRef
* - columns[number].onCellClick
* - onRowClick
* - onRowDoubleClick
* - onRowMouseEnter
* - onRowMouseLeave
* - getBodyWrapper
* - bodyStyle
*
* Deprecated:
* - All expanded props, move into expandable
*/
// Used for conditions cache
var EMPTY_DATA = []; // Used for customize scroll
var EMPTY_SCROLL_TARGET = {};
var INTERNAL_HOOKS = 'rc-table-internal-hook';
var MemoTableContent = react["memo"](function (_ref) {
var children = _ref.children;
return children;
}, function (prev, next) {
if (!shallowequal_default()(prev.props, next.props)) {
return false;
} // No additional render when pinged status change.
// This is not a bug.
return prev.pingLeft !== next.pingLeft || prev.pingRight !== next.pingRight;
});
function Table(props) {
var _classNames;
var prefixCls = props.prefixCls,
className = props.className,
rowClassName = props.rowClassName,
style = props.style,
data = props.data,
rowKey = props.rowKey,
scroll = props.scroll,
tableLayout = props.tableLayout,
direction = props.direction,
title = props.title,
footer = props.footer,
summary = props.summary,
id = props.id,
showHeader = props.showHeader,
components = props.components,
emptyText = props.emptyText,
onRow = props.onRow,
onHeaderRow = props.onHeaderRow,
internalHooks = props.internalHooks,
transformColumns = props.transformColumns,
internalRefs = props.internalRefs,
sticky = props.sticky;
var mergedData = data || EMPTY_DATA;
var hasData = !!mergedData.length; // ===================== Effects ======================
var _React$useState = react["useState"](0),
_React$useState2 = Object(esm_slicedToArray["a" /* default */])(_React$useState, 2),
scrollbarSize = _React$useState2[0],
setScrollbarSize = _React$useState2[1];
react["useEffect"](function () {
setScrollbarSize(Object(getScrollBarSize["a" /* default */])());
}); // ===================== Warning ======================
if (false) {} // ==================== Customize =====================
var mergedComponents = react["useMemo"](function () {
return mergeObject(components, {});
}, [components]);
var getComponent = react["useCallback"](function (path, defaultComponent) {
return getPathValue(mergedComponents, path) || defaultComponent;
}, [mergedComponents]);
var getRowKey = react["useMemo"](function () {
if (typeof rowKey === 'function') {
return rowKey;
}
return function (record) {
var key = record && record[rowKey];
if (false) {}
return key;
};
}, [rowKey]); // ====================== Expand ======================
var expandableConfig = getExpandableProps(props);
var expandIcon = expandableConfig.expandIcon,
expandedRowKeys = expandableConfig.expandedRowKeys,
defaultExpandedRowKeys = expandableConfig.defaultExpandedRowKeys,
defaultExpandAllRows = expandableConfig.defaultExpandAllRows,
expandedRowRender = expandableConfig.expandedRowRender,
onExpand = expandableConfig.onExpand,
onExpandedRowsChange = expandableConfig.onExpandedRowsChange,
expandRowByClick = expandableConfig.expandRowByClick,
rowExpandable = expandableConfig.rowExpandable,
expandIconColumnIndex = expandableConfig.expandIconColumnIndex,
expandedRowClassName = expandableConfig.expandedRowClassName,
childrenColumnName = expandableConfig.childrenColumnName,
indentSize = expandableConfig.indentSize;
var mergedExpandIcon = expandIcon || renderExpandIcon;
var mergedChildrenColumnName = childrenColumnName || 'children';
var expandableType = react["useMemo"](function () {
if (expandedRowRender) {
return 'row';
}
/* eslint-disable no-underscore-dangle */
/**
* Fix https://github.com/ant-design/ant-design/issues/21154
* This is a workaround to not to break current behavior.
* We can remove follow code after final release.
*
* To other developer:
* Do not use `__PARENT_RENDER_ICON__` in prod since we will remove this when refactor
*/
if (props.expandable && internalHooks === INTERNAL_HOOKS && props.expandable.__PARENT_RENDER_ICON__ || mergedData.some(function (record) {
return record && Object(esm_typeof["a" /* default */])(record) === 'object' && record[mergedChildrenColumnName];
})) {
return 'nest';
}
/* eslint-enable */
return false;
}, [!!expandedRowRender, mergedData]);
var _React$useState3 = react["useState"](function () {
if (defaultExpandedRowKeys) {
return defaultExpandedRowKeys;
}
if (defaultExpandAllRows) {
return findAllChildrenKeys(mergedData, getRowKey, mergedChildrenColumnName);
}
return [];
}),
_React$useState4 = Object(esm_slicedToArray["a" /* default */])(_React$useState3, 2),
innerExpandedKeys = _React$useState4[0],
setInnerExpandedKeys = _React$useState4[1];
var mergedExpandedKeys = react["useMemo"](function () {
return new Set(expandedRowKeys || innerExpandedKeys || []);
}, [expandedRowKeys, innerExpandedKeys]);
var onTriggerExpand = react["useCallback"](function (record) {
var key = getRowKey(record, mergedData.indexOf(record));
var newExpandedKeys;
var hasKey = mergedExpandedKeys.has(key);
if (hasKey) {
mergedExpandedKeys.delete(key);
newExpandedKeys = Object(toConsumableArray["a" /* default */])(mergedExpandedKeys);
} else {
newExpandedKeys = [].concat(Object(toConsumableArray["a" /* default */])(mergedExpandedKeys), [key]);
}
setInnerExpandedKeys(newExpandedKeys);
if (onExpand) {
onExpand(!hasKey, record);
}
if (onExpandedRowsChange) {
onExpandedRowsChange(newExpandedKeys);
}
}, [getRowKey, mergedExpandedKeys, mergedData, onExpand, onExpandedRowsChange]); // ====================== Column ======================
var _React$useState5 = react["useState"](0),
_React$useState6 = Object(esm_slicedToArray["a" /* default */])(_React$useState5, 2),
componentWidth = _React$useState6[0],
setComponentWidth = _React$useState6[1];
var _useColumns = hooks_useColumns(Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, props), expandableConfig), {}, {
expandable: !!expandedRowRender,
expandedKeys: mergedExpandedKeys,
getRowKey: getRowKey,
// https://github.com/ant-design/ant-design/issues/23894
onTriggerExpand: onTriggerExpand,
expandIcon: mergedExpandIcon,
expandIconColumnIndex: expandIconColumnIndex,
direction: direction
}), internalHooks === INTERNAL_HOOKS ? transformColumns : null),
_useColumns2 = Object(esm_slicedToArray["a" /* default */])(_useColumns, 2),
columns = _useColumns2[0],
flattenColumns = _useColumns2[1];
var columnContext = react["useMemo"](function () {
return {
columns: columns,
flattenColumns: flattenColumns
};
}, [columns, flattenColumns]); // ====================== Scroll ======================
var fullTableRef = react["useRef"]();
var scrollHeaderRef = react["useRef"]();
var scrollBodyRef = react["useRef"]();
var _React$useState7 = react["useState"](false),
_React$useState8 = Object(esm_slicedToArray["a" /* default */])(_React$useState7, 2),
pingedLeft = _React$useState8[0],
setPingedLeft = _React$useState8[1];
var _React$useState9 = react["useState"](false),
_React$useState10 = Object(esm_slicedToArray["a" /* default */])(_React$useState9, 2),
pingedRight = _React$useState10[0],
setPingedRight = _React$useState10[1];
var _useFrameState = useFrameState(new Map()),
_useFrameState2 = Object(esm_slicedToArray["a" /* default */])(_useFrameState, 2),
colsWidths = _useFrameState2[0],
updateColsWidths = _useFrameState2[1]; // Convert map to number width
var colsKeys = getColumnsKey(flattenColumns);
var pureColWidths = colsKeys.map(function (columnKey) {
return colsWidths.get(columnKey);
});
var colWidths = react["useMemo"](function () {
return pureColWidths;
}, [pureColWidths.join('_')]);
var stickyOffsets = hooks_useStickyOffsets(colWidths, flattenColumns.length, direction);
var fixHeader = scroll && validateValue(scroll.y);
var horizonScroll = scroll && validateValue(scroll.x);
var fixColumn = horizonScroll && flattenColumns.some(function (_ref2) {
var fixed = _ref2.fixed;
return fixed;
}); // Sticky
var stickyRef = react["useRef"]();
var _useSticky = useSticky(sticky, prefixCls),
isSticky = _useSticky.isSticky,
offsetHeader = _useSticky.offsetHeader,
offsetScroll = _useSticky.offsetScroll,
stickyClassName = _useSticky.stickyClassName;
var scrollXStyle;
var scrollYStyle;
var scrollTableStyle;
if (fixHeader) {
scrollYStyle = {
overflowY: 'scroll',
maxHeight: scroll.y
};
}
if (horizonScroll) {
scrollXStyle = {
overflowX: 'auto'
}; // When no vertical scrollbar, should hide it
// https://github.com/ant-design/ant-design/pull/20705
// https://github.com/ant-design/ant-design/issues/21879
if (!fixHeader) {
scrollYStyle = {
overflowY: 'hidden'
};
}
scrollTableStyle = {
width: scroll.x === true ? 'auto' : scroll.x,
minWidth: '100%'
};
}
var onColumnResize = react["useCallback"](function (columnKey, width) {
updateColsWidths(function (widths) {
var newWidths = new Map(widths);
newWidths.set(columnKey, width);
return newWidths;
});
}, []);
var _useTimeoutLock = useTimeoutLock(null),
_useTimeoutLock2 = Object(esm_slicedToArray["a" /* default */])(_useTimeoutLock, 2),
setScrollTarget = _useTimeoutLock2[0],
getScrollTarget = _useTimeoutLock2[1];
function forceScroll(scrollLeft, target) {
if (!target) {
return;
}
if (typeof target === 'function') {
target(scrollLeft);
} else if (target.scrollLeft !== scrollLeft) {
// eslint-disable-next-line no-param-reassign
target.scrollLeft = scrollLeft;
}
}
var onScroll = function onScroll(_ref3) {
var currentTarget = _ref3.currentTarget,
scrollLeft = _ref3.scrollLeft;
var mergedScrollLeft = typeof scrollLeft === 'number' ? scrollLeft : currentTarget.scrollLeft;
var compareTarget = currentTarget || EMPTY_SCROLL_TARGET;
if (!getScrollTarget() || getScrollTarget() === compareTarget) {
var _stickyRef$current;
setScrollTarget(compareTarget);
forceScroll(mergedScrollLeft, scrollHeaderRef.current);
forceScroll(mergedScrollLeft, scrollBodyRef.current);
forceScroll(mergedScrollLeft, (_stickyRef$current = stickyRef.current) === null || _stickyRef$current === void 0 ? void 0 : _stickyRef$current.setScrollLeft);
}
if (currentTarget) {
var scrollWidth = currentTarget.scrollWidth,
clientWidth = currentTarget.clientWidth;
setPingedLeft(mergedScrollLeft > 0);
setPingedRight(mergedScrollLeft < scrollWidth - clientWidth);
}
};
var triggerOnScroll = function triggerOnScroll() {
if (scrollBodyRef.current) {
onScroll({
currentTarget: scrollBodyRef.current
});
}
};
var onFullTableResize = function onFullTableResize(_ref4) {
var width = _ref4.width;
triggerOnScroll();
setComponentWidth(fullTableRef.current ? fullTableRef.current.offsetWidth : width);
}; // Sync scroll bar when init or `horizonScroll` changed
react["useEffect"](function () {
return triggerOnScroll;
}, []);
react["useEffect"](function () {
if (horizonScroll) {
triggerOnScroll();
}
}, [horizonScroll]); // ================== INTERNAL HOOKS ==================
react["useEffect"](function () {
if (internalHooks === INTERNAL_HOOKS && internalRefs) {
internalRefs.body.current = scrollBodyRef.current;
}
}); // ====================== Render ======================
var TableComponent = getComponent(['table'], 'table'); // Table layout
var mergedTableLayout = react["useMemo"](function () {
if (tableLayout) {
return tableLayout;
} // https://github.com/ant-design/ant-design/issues/25227
// When scroll.x is max-content, no need to fix table layout
// it's width should stretch out to fit content
if (fixColumn) {
return scroll.x === 'max-content' ? 'auto' : 'fixed';
}
if (fixHeader || flattenColumns.some(function (_ref5) {
var ellipsis = _ref5.ellipsis;
return ellipsis;
})) {
return 'fixed';
}
return 'auto';
}, [fixHeader, fixColumn, flattenColumns, tableLayout]);
var groupTableNode; // Header props
var headerProps = {
colWidths: colWidths,
columCount: flattenColumns.length,
stickyOffsets: stickyOffsets,
onHeaderRow: onHeaderRow,
fixHeader: fixHeader
}; // Empty
var emptyNode = react["useMemo"](function () {
if (hasData) {
return null;
}
if (typeof emptyText === 'function') {
return emptyText();
}
return emptyText;
}, [hasData, emptyText]); // Body
var bodyTable = react["createElement"](es_Body, {
data: mergedData,
measureColumnWidth: fixHeader || horizonScroll || isSticky,
expandedKeys: mergedExpandedKeys,
rowExpandable: rowExpandable,
getRowKey: getRowKey,
onRow: onRow,
emptyNode: emptyNode,
childrenColumnName: mergedChildrenColumnName
});
var bodyColGroup = react["createElement"](es_ColGroup, {
colWidths: flattenColumns.map(function (_ref6) {
var width = _ref6.width;
return width;
}),
columns: flattenColumns
});
var footerTable = summary && react["createElement"](es_Footer, null, summary(mergedData));
var customizeScrollBody = getComponent(['body']);
if (false) {}
if (fixHeader || isSticky) {
var bodyContent;
if (typeof customizeScrollBody === 'function') {
bodyContent = customizeScrollBody(mergedData, {
scrollbarSize: scrollbarSize,
ref: scrollBodyRef,
onScroll: onScroll
});
headerProps.colWidths = flattenColumns.map(function (_ref7, index) {
var width = _ref7.width;
var colWidth = index === columns.length - 1 ? width - scrollbarSize : width;
if (typeof colWidth === 'number' && !Number.isNaN(colWidth)) {
return colWidth;
}
Object(warning["a" /* default */])(false, 'When use `components.body` with render props. Each column should have a fixed value.');
return 0;
});
} else {
bodyContent = react["createElement"]("div", {
style: Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, scrollXStyle), scrollYStyle),
onScroll: onScroll,
ref: scrollBodyRef,
className: classnames_default()("".concat(prefixCls, "-body"))
}, react["createElement"](TableComponent, {
style: Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, scrollTableStyle), {}, {
tableLayout: mergedTableLayout
})
}, bodyColGroup, bodyTable, footerTable), isSticky && react["createElement"](stickyScrollBar, {
ref: stickyRef,
offsetScroll: offsetScroll,
scrollBodyRef: scrollBodyRef,
onScroll: onScroll
}));
}
groupTableNode = react["createElement"](react["Fragment"], null, showHeader !== false && react["createElement"](Header_FixedHeader, Object.assign({
noData: !mergedData.length
}, headerProps, columnContext, {
direction: direction,
// Fixed Props
offsetHeader: offsetHeader,
stickyClassName: stickyClassName,
ref: scrollHeaderRef,
onScroll: onScroll
})), bodyContent);
} else {
groupTableNode = react["createElement"]("div", {
style: Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, scrollXStyle), scrollYStyle),
className: classnames_default()("".concat(prefixCls, "-content")),
onScroll: onScroll,
ref: scrollBodyRef
}, react["createElement"](TableComponent, {
style: Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, scrollTableStyle), {}, {
tableLayout: mergedTableLayout
})
}, bodyColGroup, showHeader !== false && react["createElement"](Header_Header, Object.assign({}, headerProps, columnContext)), bodyTable, footerTable));
}
var ariaProps = getDataAndAriaProps(props);
var fullTable = react["createElement"]("div", Object.assign({
className: classnames_default()(prefixCls, className, (_classNames = {}, Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-rtl"), direction === 'rtl'), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-ping-left"), pingedLeft), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-ping-right"), pingedRight), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-layout-fixed"), tableLayout === 'fixed'), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-fixed-header"), fixHeader), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-fixed-column"), fixColumn), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-scroll-horizontal"), horizonScroll), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-has-fix-left"), flattenColumns[0] && flattenColumns[0].fixed), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-has-fix-right"), flattenColumns[flattenColumns.length - 1] && flattenColumns[flattenColumns.length - 1].fixed === 'right'), _classNames)),
style: style,
id: id,
ref: fullTableRef
}, ariaProps), react["createElement"](MemoTableContent, {
pingLeft: pingedLeft,
pingRight: pingedRight,
props: Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, props), {}, {
stickyOffsets: stickyOffsets,
mergedExpandedKeys: mergedExpandedKeys
})
}, title && react["createElement"](es_Panel, {
className: "".concat(prefixCls, "-title")
}, title(mergedData)), react["createElement"]("div", {
className: "".concat(prefixCls, "-container")
}, groupTableNode), footer && react["createElement"](es_Panel, {
className: "".concat(prefixCls, "-footer")
}, footer(mergedData))));
if (horizonScroll) {
fullTable = react["createElement"](rc_resize_observer_es["a" /* default */], {
onResize: onFullTableResize
}, fullTable);
}
var TableContextValue = react["useMemo"](function () {
return {
prefixCls: prefixCls,
getComponent: getComponent,
scrollbarSize: scrollbarSize,
direction: direction,
fixedInfoList: flattenColumns.map(function (_, colIndex) {
return getCellFixedInfo(colIndex, colIndex, flattenColumns, stickyOffsets, direction);
}),
isSticky: isSticky
};
}, [prefixCls, getComponent, scrollbarSize, direction, flattenColumns, stickyOffsets, direction, isSticky]);
var BodyContextValue = react["useMemo"](function () {
return Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, columnContext), {}, {
tableLayout: mergedTableLayout,
rowClassName: rowClassName,
expandedRowClassName: expandedRowClassName,
componentWidth: componentWidth,
fixHeader: fixHeader,
fixColumn: fixColumn,
horizonScroll: horizonScroll,
expandIcon: mergedExpandIcon,
expandableType: expandableType,
expandRowByClick: expandRowByClick,
expandedRowRender: expandedRowRender,
onTriggerExpand: onTriggerExpand,
expandIconColumnIndex: expandIconColumnIndex,
indentSize: indentSize
});
}, [columnContext, mergedTableLayout, rowClassName, expandedRowClassName, componentWidth, fixHeader, fixColumn, horizonScroll, mergedExpandIcon, expandableType, expandRowByClick, expandedRowRender, onTriggerExpand, expandIconColumnIndex, indentSize]);
var ResizeContextValue = react["useMemo"](function () {
return {
onColumnResize: onColumnResize
};
}, [onColumnResize]);
return react["createElement"](context_TableContext.Provider, {
value: TableContextValue
}, react["createElement"](context_BodyContext.Provider, {
value: BodyContextValue
}, react["createElement"](context_ResizeContext.Provider, {
value: ResizeContextValue
}, fullTable)));
}
Table.Column = sugar_Column;
Table.ColumnGroup = sugar_ColumnGroup;
Table.Summary = FooterComponents;
Table.defaultProps = {
rowKey: 'key',
prefixCls: 'rc-table',
emptyText: function emptyText() {
return 'No Data';
}
};
/* harmony default export */ var es_Table = (Table);
// CONCATENATED MODULE: ./node_modules/rc-table/es/index.js
/* harmony default export */ var rc_table_es = (es_Table);
// EXTERNAL MODULE: ./node_modules/antd/es/spin/index.js
var spin = __webpack_require__("W9HT");
// EXTERNAL MODULE: ./node_modules/antd/es/pagination/index.js + 7 modules
var es_pagination = __webpack_require__("NUBc");
// EXTERNAL MODULE: ./node_modules/antd/es/config-provider/context.js + 1 modules
var config_provider_context = __webpack_require__("H84U");
// CONCATENATED MODULE: ./node_modules/antd/es/table/hooks/usePagination.js
var __rest = undefined && undefined.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
var DEFAULT_PAGE_SIZE = 10;
function getPaginationParam(pagination, mergedPagination) {
var param = {
current: mergedPagination.current,
pageSize: mergedPagination.pageSize
};
var paginationObj = pagination && typeof_default()(pagination) === 'object' ? pagination : {};
Object.keys(paginationObj).forEach(function (pageProp) {
var value = mergedPagination[pageProp];
if (typeof value !== 'function') {
param[pageProp] = value;
}
});
return param;
}
function extendsObject() {
var result = {};
for (var _len = arguments.length, list = new Array(_len), _key = 0; _key < _len; _key++) {
list[_key] = arguments[_key];
}
list.forEach(function (obj) {
if (obj) {
Object.keys(obj).forEach(function (key) {
var val = obj[key];
if (val !== undefined) {
result[key] = val;
}
});
}
});
return result;
}
function usePagination(total, pagination, onChange) {
var _a = pagination && typeof_default()(pagination) === 'object' ? pagination : {},
_a$total = _a.total,
paginationTotal = _a$total === void 0 ? 0 : _a$total,
paginationObj = __rest(_a, ["total"]);
var _useState = Object(react["useState"])(function () {
return {
current: 'defaultCurrent' in paginationObj ? paginationObj.defaultCurrent : 1,
pageSize: 'defaultPageSize' in paginationObj ? paginationObj.defaultPageSize : DEFAULT_PAGE_SIZE
};
}),
_useState2 = slicedToArray_default()(_useState, 2),
innerPagination = _useState2[0],
setInnerPagination = _useState2[1]; // ============ Basic Pagination Config ============
var mergedPagination = extendsObject(innerPagination, paginationObj, {
total: paginationTotal > 0 ? paginationTotal : total
});
if (!paginationTotal) {
// Reset `current` if data length changed. Only reset when paginationObj do not have total
var maxPage = Math.ceil(total / mergedPagination.pageSize);
if (maxPage < mergedPagination.current) {
mergedPagination.current = 1;
}
}
var refreshPagination = function refreshPagination() {
var current = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
var pageSize = arguments.length > 1 ? arguments[1] : undefined;
setInnerPagination(extends_default()(extends_default()({}, mergedPagination), {
current: current,
pageSize: pageSize || mergedPagination.pageSize
}));
};
var onInternalChange = function onInternalChange(current, pageSize) {
var paginationPageSize = mergedPagination === null || mergedPagination === void 0 ? void 0 : mergedPagination.pageSize;
if (pageSize && pageSize !== paginationPageSize) {
current = 1;
if (pagination && pagination.onShowSizeChange) pagination.onShowSizeChange(current, pageSize);
}
if (pagination && pagination.onChange) pagination.onChange(current, pageSize);
refreshPagination(current, pageSize);
onChange(current, pageSize || paginationPageSize);
};
if (pagination === false) {
return [{}, function () {}];
}
return [extends_default()(extends_default()({}, mergedPagination), {
onChange: onInternalChange
}), refreshPagination];
}
// CONCATENATED MODULE: ./node_modules/antd/es/table/hooks/useLazyKVMap.js
function useLazyKVMap(data, childrenColumnName, getRowKey) {
var mapCacheRef = react["useRef"]({});
function getRecordByKey(key) {
if (!mapCacheRef.current || mapCacheRef.current.data !== data || mapCacheRef.current.childrenColumnName !== childrenColumnName || mapCacheRef.current.getRowKey !== getRowKey) {
/* eslint-disable no-inner-declarations */
var dig = function dig(records) {
records.forEach(function (record, index) {
var rowKey = getRowKey(record, index);
kvMap.set(rowKey, record);
if (record && typeof_default()(record) === 'object' && childrenColumnName in record) {
dig(record[childrenColumnName] || []);
}
});
};
/* eslint-enable */
var kvMap = new Map();
dig(data);
mapCacheRef.current = {
data: data,
childrenColumnName: childrenColumnName,
kvMap: kvMap,
getRowKey: getRowKey
};
}
return mapCacheRef.current.kvMap.get(key);
}
return [getRecordByKey];
}
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/toArray.js
var helpers_toArray = __webpack_require__("SA+Z");
var toArray_default = /*#__PURE__*/__webpack_require__.n(helpers_toArray);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/toConsumableArray.js
var helpers_toConsumableArray = __webpack_require__("RIqP");
var toConsumableArray_default = /*#__PURE__*/__webpack_require__.n(helpers_toConsumableArray);
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/DownOutlined.js
var DownOutlined = __webpack_require__("HQEm");
var DownOutlined_default = /*#__PURE__*/__webpack_require__.n(DownOutlined);
// 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");
// CONCATENATED MODULE: ./node_modules/rc-tree/es/contextTypes.js
/**
* 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["createContext"](null);
// 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(react["createElement"]("span", {
key: i,
className: classnames_default()(baseClassName, (_classNames = {}, Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(baseClassName, "-start"), isStart[i + 1]), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(baseClassName, "-end"), isEnd[i + 1]), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(baseClassName, "-end-first-level"), !i && isEnd[0]), _classNames))
}));
}
return react["createElement"]("span", {
"aria-hidden": "true",
className: "".concat(prefixCls, "-indent")
}, list);
};
/* harmony default export */ var es_Indent = (Indent_Indent);
// 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, 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, convertNodePropsToEventData(_this.props));
};
_this.onSelect = function (e) {
if (_this.isDisabled()) return;
var onNodeSelect = _this.props.context.onNodeSelect;
e.preventDefault();
onNodeSelect(e, 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, convertNodePropsToEventData(_this.props), targetChecked);
};
_this.onMouseEnter = function (e) {
var onNodeMouseEnter = _this.props.context.onNodeMouseEnter;
onNodeMouseEnter(e, convertNodePropsToEventData(_this.props));
};
_this.onMouseLeave = function (e) {
var onNodeMouseLeave = _this.props.context.onNodeMouseLeave;
onNodeMouseLeave(e, convertNodePropsToEventData(_this.props));
};
_this.onContextMenu = function (e) {
var onNodeContextMenu = _this.props.context.onNodeContextMenu;
onNodeContextMenu(e, 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, 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(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 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 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 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 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 ? 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 = react["createElement"]("span", {
className: "".concat(prefixCls, "-title")
}, titleNode);
return 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 = getDataAndAria(otherProps);
var _ref2 = keyEntities[eventKey] || {},
level = _ref2.level;
var isEndNode = isEnd[isEnd.length - 1];
return react["createElement"]("div", Object.assign({
ref: domRef,
className: classnames_default()(className, "".concat(prefixCls, "-treenode"), (_classNames = {}, Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-treenode-disabled"), disabled), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-treenode-switcher-").concat(expanded ? 'open' : 'close'), !isLeaf), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-treenode-checkbox-checked"), checked), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-treenode-checkbox-indeterminate"), halfChecked), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-treenode-selected"), selected), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-treenode-loading"), loading), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-treenode-active"), active), Object(esm_defineProperty["a" /* default */])(_classNames, "".concat(prefixCls, "-treenode-leaf-last"), isEndNode), Object(esm_defineProperty["a" /* default */])(_classNames, 'drag-over', !disabled && dragOver), Object(esm_defineProperty["a" /* default */])(_classNames, 'drag-over-gap-top', !disabled && dragOverGapTop), Object(esm_defineProperty["a" /* default */])(_classNames, 'drag-over-gap-bottom', !disabled && dragOverGapBottom), Object(esm_defineProperty["a" /* default */])(_classNames, 'filter-node', filterTreeNode && filterTreeNode(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), react["createElement"](es_Indent, {
prefixCls: prefixCls,
level: level,
isStart: isStart,
isEnd: isEnd
}), this.renderSwitcher(), this.renderCheckbox(), this.renderSelector());
}
}]);
return InternalTreeNode;
}(react["Component"]);
var TreeNode_ContextTreeNode = function ContextTreeNode(props) {
return react["createElement"](TreeContext.Consumer, null, function (context) {
return 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 = (TreeNode_ContextTreeNode);
// CONCATENATED MODULE: ./node_modules/rc-tree/es/util.js
/**
* 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(objectWithoutProperties["a" /* default */])(_ref3, ["children"]);
var childrenNodes = convertDataToTree(children, processor);
return react_default.a.createElement(TreeNode, 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(esm_typeof["a" /* default */])(keys) === 'object') {
keyProps = {
checkedKeys: keys.checked || undefined,
halfCheckedKeys: keys.halfChecked || undefined
};
} else {
Object(warning["a" /* default */])(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(toConsumableArray["a" /* default */])(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;
}
// CONCATENATED MODULE: ./node_modules/rc-tree/es/utils/treeUtil.js
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(warning["a" /* default */])(key !== null && key !== undefined, "Tree node must have a certain key: [".concat(path).concat(key, "]"));
var recordKey = String(key);
Object(warning["a" /* default */])(!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(Children_toArray["a" /* default */])(node);
return treeNodes.map(function (treeNode) {
// Filter invalidate node
if (!isTreeNode(treeNode)) {
Object(warning["a" /* default */])(!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(objectWithoutProperties["a" /* default */])(_treeNode$props, ["children"]);
var dataNode = Object(objectSpread2["a" /* default */])({
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 = getPosition(parent ? parent.pos : '0', index);
var mergedKey = getKey(treeNode.key, pos); // Add FlattenDataNode into list
var flattenNode = Object(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, treeNode), {}, {
parent: parent,
pos: pos,
children: null,
data: treeNode,
isStart: [].concat(Object(toConsumableArray["a" /* default */])(parent ? parent.isStart : []), [index === 0]),
isEnd: [].concat(Object(toConsumableArray["a" /* default */])(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 ? getPosition(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(objectSpread2["a" /* default */])(Object(objectSpread2["a" /* default */])({}, 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(warning["a" /* default */])(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;
}
// CONCATENATED MODULE: ./node_modules/rc-tree/es/utils/conductUtil.js
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(warning["a" /* default */])(!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;
}
// EXTERNAL MODULE: ./node_modules/rc-util/es/hooks/useMergedState.js
var useMergedState = __webpack_require__("6cGi");
// EXTERNAL MODULE: ./node_modules/antd/es/checkbox/index.js + 2 modules
var es_checkbox = __webpack_require__("kaz8");
// EXTERNAL MODULE: ./node_modules/antd/es/dropdown/index.js
var dropdown = __webpack_require__("jsC+");
// EXTERNAL MODULE: ./node_modules/antd/es/menu/index.js + 16 modules
var es_menu = __webpack_require__("BvKs");
// EXTERNAL MODULE: ./node_modules/antd/es/radio/index.js + 5 modules
var es_radio = __webpack_require__("9yH6");
// EXTERNAL MODULE: ./node_modules/antd/es/_util/devWarning.js
var devWarning = __webpack_require__("uaoM");
// CONCATENATED MODULE: ./node_modules/antd/es/table/hooks/useSelection.js
// TODO: warning if use ajax!!!
var SELECTION_ALL = 'SELECT_ALL';
var SELECTION_INVERT = 'SELECT_INVERT';
function getFixedType(column) {
return column && column.fixed;
}
function flattenData(data, childrenColumnName) {
var list = [];
(data || []).forEach(function (record) {
list.push(record);
if (record && typeof_default()(record) === 'object' && childrenColumnName in record) {
list = [].concat(toConsumableArray_default()(list), toConsumableArray_default()(flattenData(record[childrenColumnName], childrenColumnName)));
}
});
return list;
}
function useSelection(rowSelection, config) {
var _ref = rowSelection || {},
preserveSelectedRowKeys = _ref.preserveSelectedRowKeys,
selectedRowKeys = _ref.selectedRowKeys,
getCheckboxProps = _ref.getCheckboxProps,
onSelectionChange = _ref.onChange,
onSelect = _ref.onSelect,
onSelectAll = _ref.onSelectAll,
onSelectInvert = _ref.onSelectInvert,
onSelectMultiple = _ref.onSelectMultiple,
selectionColWidth = _ref.columnWidth,
selectionType = _ref.type,
selections = _ref.selections,
fixed = _ref.fixed,
customizeRenderCell = _ref.renderCell,
hideSelectAll = _ref.hideSelectAll,
_ref$checkStrictly = _ref.checkStrictly,
checkStrictly = _ref$checkStrictly === void 0 ? true : _ref$checkStrictly;
var prefixCls = config.prefixCls,
data = config.data,
pageData = config.pageData,
getRecordByKey = config.getRecordByKey,
getRowKey = config.getRowKey,
expandType = config.expandType,
childrenColumnName = config.childrenColumnName,
tableLocale = config.locale,
expandIconColumnIndex = config.expandIconColumnIndex,
getPopupContainer = config.getPopupContainer; // ======================== Caches ========================
var preserveRecordsRef = react["useRef"](new Map()); // ========================= Keys =========================
var _useMergedState = Object(useMergedState["a" /* default */])(selectedRowKeys || [], {
value: selectedRowKeys
}),
_useMergedState2 = slicedToArray_default()(_useMergedState, 2),
mergedSelectedKeys = _useMergedState2[0],
setMergedSelectedKeys = _useMergedState2[1];
var _useMemo = Object(react["useMemo"])(function () {
return checkStrictly ? {
keyEntities: null
} : convertDataToEntities(data, undefined, getRowKey);
}, [data, getRowKey, checkStrictly]),
keyEntities = _useMemo.keyEntities; // Get flatten data
var flattedData = Object(react["useMemo"])(function () {
return flattenData(pageData, childrenColumnName);
}, [pageData, childrenColumnName]); // Get all checkbox props
var checkboxPropsMap = Object(react["useMemo"])(function () {
var map = new Map();
flattedData.forEach(function (record, index) {
var key = getRowKey(record, index);
var checkboxProps = (getCheckboxProps ? getCheckboxProps(record) : null) || {};
map.set(key, checkboxProps);
if (false) {}
});
return map;
}, [flattedData, getRowKey, getCheckboxProps]);
var isCheckboxDisabled = Object(react["useCallback"])(function (r) {
var _a;
return !!((_a = checkboxPropsMap.get(getRowKey(r))) === null || _a === void 0 ? void 0 : _a.disabled);
}, [checkboxPropsMap, getRowKey]);
var _useMemo2 = Object(react["useMemo"])(function () {
if (checkStrictly) {
return [mergedSelectedKeys, []];
}
var _conductCheck = conductCheck(mergedSelectedKeys, true, keyEntities, isCheckboxDisabled),
checkedKeys = _conductCheck.checkedKeys,
halfCheckedKeys = _conductCheck.halfCheckedKeys;
return [checkedKeys, halfCheckedKeys];
}, [mergedSelectedKeys, checkStrictly, keyEntities, isCheckboxDisabled]),
_useMemo3 = slicedToArray_default()(_useMemo2, 2),
derivedSelectedKeys = _useMemo3[0],
derivedHalfSelectedKeys = _useMemo3[1];
var derivedSelectedKeySet = Object(react["useMemo"])(function () {
var keys = selectionType === 'radio' ? derivedSelectedKeys.slice(0, 1) : derivedSelectedKeys;
return new Set(keys);
}, [derivedSelectedKeys, selectionType]);
var derivedHalfSelectedKeySet = Object(react["useMemo"])(function () {
return selectionType === 'radio' ? new Set() : new Set(derivedHalfSelectedKeys);
}, [derivedHalfSelectedKeys, selectionType]); // Save last selected key to enable range selection
var _useState = Object(react["useState"])(null),
_useState2 = slicedToArray_default()(_useState, 2),
lastSelectedKey = _useState2[0],
setLastSelectedKey = _useState2[1]; // Reset if rowSelection reset
react["useEffect"](function () {
if (!rowSelection) {
setMergedSelectedKeys([]);
}
}, [!!rowSelection]);
var setSelectedKeys = Object(react["useCallback"])(function (keys) {
var availableKeys;
var records;
if (preserveSelectedRowKeys) {
// Keep key if mark as preserveSelectedRowKeys
var newCache = new Map();
availableKeys = keys;
records = keys.map(function (key) {
var record = getRecordByKey(key);
if (!record && preserveRecordsRef.current.has(key)) {
record = preserveRecordsRef.current.get(key);
}
newCache.set(key, record);
return record;
}); // Refresh to new cache
preserveRecordsRef.current = newCache;
} else {
// Filter key which not exist in the `dataSource`
availableKeys = [];
records = [];
keys.forEach(function (key) {
var record = getRecordByKey(key);
if (record !== undefined) {
availableKeys.push(key);
records.push(record);
}
});
}
setMergedSelectedKeys(availableKeys);
if (onSelectionChange) {
onSelectionChange(availableKeys, records);
}
}, [setMergedSelectedKeys, getRecordByKey, onSelectionChange, preserveSelectedRowKeys]); // ====================== Selections ======================
// Trigger single `onSelect` event
var triggerSingleSelection = Object(react["useCallback"])(function (key, selected, keys, event) {
if (onSelect) {
var rows = keys.map(function (k) {
return getRecordByKey(k);
});
onSelect(getRecordByKey(key), selected, rows, event);
}
setSelectedKeys(keys);
}, [onSelect, getRecordByKey, setSelectedKeys]);
var mergedSelections = Object(react["useMemo"])(function () {
if (!selections || hideSelectAll) {
return null;
}
var selectionList = selections === true ? [SELECTION_ALL, SELECTION_INVERT] : selections;
return selectionList.map(function (selection) {
if (selection === SELECTION_ALL) {
return {
key: 'all',
text: tableLocale.selectionAll,
onSelect: function onSelect() {
setSelectedKeys(data.map(function (record, index) {
return getRowKey(record, index);
}));
}
};
}
if (selection === SELECTION_INVERT) {
return {
key: 'invert',
text: tableLocale.selectInvert,
onSelect: function onSelect() {
var keySet = new Set(derivedSelectedKeySet);
pageData.forEach(function (record, index) {
var key = getRowKey(record, index);
if (keySet.has(key)) {
keySet["delete"](key);
} else {
keySet.add(key);
}
});
var keys = Array.from(keySet);
setSelectedKeys(keys);
if (onSelectInvert) {
Object(devWarning["a" /* default */])(false, 'Table', '`onSelectInvert` will be removed in future. Please use `onChange` instead.');
onSelectInvert(keys);
}
}
};
}
return selection;
});
}, [selections, derivedSelectedKeySet, pageData, getRowKey, onSelectInvert, setSelectedKeys]); // ======================= Columns ========================
var transformColumns = Object(react["useCallback"])(function (columns) {
if (!rowSelection) {
return columns;
} // Support selection
var keySet = new Set(derivedSelectedKeySet); // Record key only need check with enabled
var recordKeys = flattedData.map(getRowKey).filter(function (key) {
return !checkboxPropsMap.get(key).disabled;
});
var checkedCurrentAll = recordKeys.every(function (key) {
return keySet.has(key);
});
var checkedCurrentSome = recordKeys.some(function (key) {
return keySet.has(key);
});
var onSelectAllChange = function onSelectAllChange() {
var changeKeys = [];
if (checkedCurrentAll) {
recordKeys.forEach(function (key) {
keySet["delete"](key);
changeKeys.push(key);
});
} else {
recordKeys.forEach(function (key) {
if (!keySet.has(key)) {
keySet.add(key);
changeKeys.push(key);
}
});
}
var keys = Array.from(keySet);
setSelectedKeys(keys);
if (onSelectAll) {
onSelectAll(!checkedCurrentAll, keys.map(function (k) {
return getRecordByKey(k);
}), changeKeys.map(function (k) {
return getRecordByKey(k);
}));
}
}; // ===================== Render =====================
// Title Cell
var title;
if (selectionType !== 'radio') {
var customizeSelections;
if (mergedSelections) {
var menu = /*#__PURE__*/react["createElement"](es_menu["a" /* default */], {
getPopupContainer: getPopupContainer
}, mergedSelections.map(function (selection, index) {
var key = selection.key,
text = selection.text,
onSelectionClick = selection.onSelect;
return /*#__PURE__*/react["createElement"](es_menu["a" /* default */].Item, {
key: key || index,
onClick: function onClick() {
if (onSelectionClick) {
onSelectionClick(recordKeys);
}
}
}, text);
}));
customizeSelections = /*#__PURE__*/react["createElement"]("div", {
className: "".concat(prefixCls, "-selection-extra")
}, /*#__PURE__*/react["createElement"](dropdown["a" /* default */], {
overlay: menu,
getPopupContainer: getPopupContainer
}, /*#__PURE__*/react["createElement"]("span", null, /*#__PURE__*/react["createElement"](DownOutlined_default.a, null))));
}
var allDisabled = flattedData.every(function (record, index) {
var key = getRowKey(record, index);
var checkboxProps = checkboxPropsMap.get(key) || {};
return checkboxProps.disabled;
});
title = !hideSelectAll && /*#__PURE__*/react["createElement"]("div", {
className: "".concat(prefixCls, "-selection")
}, /*#__PURE__*/react["createElement"](es_checkbox["a" /* default */], {
checked: !allDisabled && !!flattedData.length && checkedCurrentAll,
indeterminate: !checkedCurrentAll && checkedCurrentSome,
onChange: onSelectAllChange,
disabled: flattedData.length === 0 || allDisabled
}), customizeSelections);
} // Body Cell
var renderCell;
if (selectionType === 'radio') {
renderCell = function renderCell(_, record, index) {
var key = getRowKey(record, index);
var checked = keySet.has(key);
return {
node: /*#__PURE__*/react["createElement"](es_radio["a" /* default */], extends_default()({}, checkboxPropsMap.get(key), {
checked: checked,
onClick: function onClick(e) {
return e.stopPropagation();
},
onChange: function onChange(event) {
if (!keySet.has(key)) {
triggerSingleSelection(key, true, [key], event.nativeEvent);
}
}
})),
checked: checked
};
};
} else {
renderCell = function renderCell(_, record, index) {
var _a;
var key = getRowKey(record, index);
var checked = keySet.has(key);
var indeterminate = derivedHalfSelectedKeySet.has(key);
var checkboxProps = checkboxPropsMap.get(key);
var mergedIndeterminate;
if (expandType === 'nest') {
mergedIndeterminate = indeterminate;
Object(devWarning["a" /* default */])(!(typeof (checkboxProps === null || checkboxProps === void 0 ? void 0 : checkboxProps.indeterminate) === 'boolean'), 'Table', 'set `indeterminate` using `rowSelection.getCheckboxProps` is not allowed with tree structured dataSource.');
} else {
mergedIndeterminate = (_a = checkboxProps === null || checkboxProps === void 0 ? void 0 : checkboxProps.indeterminate) !== null && _a !== void 0 ? _a : indeterminate;
} // Record checked
return {
node: /*#__PURE__*/react["createElement"](es_checkbox["a" /* default */], extends_default()({}, checkboxProps, {
indeterminate: mergedIndeterminate,
checked: checked,
onClick: function onClick(e) {
return e.stopPropagation();
},
onChange: function onChange(_ref2) {
var nativeEvent = _ref2.nativeEvent;
var shiftKey = nativeEvent.shiftKey;
var startIndex = -1;
var endIndex = -1; // Get range of this
if (shiftKey && checkStrictly) {
var pointKeys = new Set([lastSelectedKey, key]);
recordKeys.some(function (recordKey, recordIndex) {
if (pointKeys.has(recordKey)) {
if (startIndex === -1) {
startIndex = recordIndex;
} else {
endIndex = recordIndex;
return true;
}
}
return false;
});
}
if (endIndex !== -1 && startIndex !== endIndex && checkStrictly) {
// Batch update selections
var rangeKeys = recordKeys.slice(startIndex, endIndex + 1);
var changedKeys = [];
if (checked) {
rangeKeys.forEach(function (recordKey) {
if (keySet.has(recordKey)) {
changedKeys.push(recordKey);
keySet["delete"](recordKey);
}
});
} else {
rangeKeys.forEach(function (recordKey) {
if (!keySet.has(recordKey)) {
changedKeys.push(recordKey);
keySet.add(recordKey);
}
});
}
var keys = Array.from(keySet);
setSelectedKeys(keys);
if (onSelectMultiple) {
onSelectMultiple(!checked, keys.map(function (recordKey) {
return getRecordByKey(recordKey);
}), changedKeys.map(function (recordKey) {
return getRecordByKey(recordKey);
}));
}
} else {
// Single record selected
var originCheckedKeys = derivedSelectedKeys;
if (checkStrictly) {
var checkedKeys = checked ? arrDel(originCheckedKeys, key) : arrAdd(originCheckedKeys, key);
triggerSingleSelection(key, !checked, checkedKeys, nativeEvent);
} else {
// Always fill first
var result = conductCheck([].concat(toConsumableArray_default()(originCheckedKeys), [key]), true, keyEntities, isCheckboxDisabled);
var _checkedKeys = result.checkedKeys,
halfCheckedKeys = result.halfCheckedKeys;
var nextCheckedKeys = _checkedKeys; // If remove, we do it again to correction
if (checked) {
var tempKeySet = new Set(_checkedKeys);
tempKeySet["delete"](key);
nextCheckedKeys = conductCheck(Array.from(tempKeySet), {
checked: false,
halfCheckedKeys: halfCheckedKeys
}, keyEntities, isCheckboxDisabled).checkedKeys;
}
triggerSingleSelection(key, !checked, nextCheckedKeys, nativeEvent);
}
}
setLastSelectedKey(key);
}
})),
checked: checked
};
};
}
var renderSelectionCell = function renderSelectionCell(_, record, index) {
var _renderCell = renderCell(_, record, index),
node = _renderCell.node,
checked = _renderCell.checked;
if (customizeRenderCell) {
return customizeRenderCell(checked, record, index, node);
}
return node;
}; // Columns
var selectionColumn = defineProperty_default()({
width: selectionColWidth,
className: "".concat(prefixCls, "-selection-column"),
title: rowSelection.columnTitle || title,
render: renderSelectionCell
}, INTERNAL_COL_DEFINE, {
className: "".concat(prefixCls, "-selection-col")
});
if (expandType === 'row' && columns.length && !expandIconColumnIndex) {
var _columns = toArray_default()(columns),
expandColumn = _columns[0],
restColumns = _columns.slice(1);
var selectionFixed = fixed || getFixedType(restColumns[0]);
if (selectionFixed) {
expandColumn.fixed = selectionFixed;
}
return [expandColumn, extends_default()(extends_default()({}, selectionColumn), {
fixed: selectionFixed
})].concat(toConsumableArray_default()(restColumns));
}
return [extends_default()(extends_default()({}, selectionColumn), {
fixed: fixed || getFixedType(columns[0])
})].concat(toConsumableArray_default()(columns));
}, [getRowKey, flattedData, rowSelection, derivedSelectedKeys, derivedSelectedKeySet, derivedHalfSelectedKeySet, selectionColWidth, mergedSelections, expandType, lastSelectedKey, checkboxPropsMap, onSelectMultiple, triggerSingleSelection, isCheckboxDisabled]);
return [transformColumns, derivedSelectedKeySet];
}
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/CaretDownOutlined.js
var CaretDownOutlined = __webpack_require__("6SEX");
var CaretDownOutlined_default = /*#__PURE__*/__webpack_require__.n(CaretDownOutlined);
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/CaretUpOutlined.js
var CaretUpOutlined = __webpack_require__("i8CU");
var CaretUpOutlined_default = /*#__PURE__*/__webpack_require__.n(CaretUpOutlined);
// EXTERNAL MODULE: ./node_modules/antd/es/tooltip/index.js + 5 modules
var tooltip = __webpack_require__("3S7+");
// CONCATENATED MODULE: ./node_modules/antd/es/table/util.js
function getColumnKey(column, defaultKey) {
if ('key' in column && column.key !== undefined && column.key !== null) {
return column.key;
}
if (column.dataIndex) {
return Array.isArray(column.dataIndex) ? column.dataIndex.join('.') : column.dataIndex;
}
return defaultKey;
}
function getColumnPos(index, pos) {
return pos ? "".concat(pos, "-").concat(index) : "".concat(index);
}
function renderColumnTitle(title, props) {
if (typeof title === 'function') {
return title(props);
}
return title;
}
// CONCATENATED MODULE: ./node_modules/antd/es/table/hooks/useSorter.js
var ASCEND = 'ascend';
var DESCEND = 'descend';
function getMultiplePriority(column) {
if (typeof_default()(column.sorter) === 'object' && typeof column.sorter.multiple === 'number') {
return column.sorter.multiple;
}
return false;
}
function getSortFunction(sorter) {
if (typeof sorter === 'function') {
return sorter;
}
if (sorter && typeof_default()(sorter) === 'object' && sorter.compare) {
return sorter.compare;
}
return false;
}
function nextSortDirection(sortDirections, current) {
if (!current) {
return sortDirections[0];
}
return sortDirections[sortDirections.indexOf(current) + 1];
}
function collectSortStates(columns, init, pos) {
var sortStates = [];
function pushState(column, columnPos) {
sortStates.push({
column: column,
key: getColumnKey(column, columnPos),
multiplePriority: getMultiplePriority(column),
sortOrder: column.sortOrder
});
}
(columns || []).forEach(function (column, index) {
var columnPos = getColumnPos(index, pos);
if (column.children) {
if ('sortOrder' in column) {
// Controlled
pushState(column, columnPos);
}
sortStates = [].concat(toConsumableArray_default()(sortStates), toConsumableArray_default()(collectSortStates(column.children, init, columnPos)));
} else if (column.sorter) {
if ('sortOrder' in column) {
// Controlled
pushState(column, columnPos);
} else if (init && column.defaultSortOrder) {
// Default sorter
sortStates.push({
column: column,
key: getColumnKey(column, columnPos),
multiplePriority: getMultiplePriority(column),
sortOrder: column.defaultSortOrder
});
}
}
});
return sortStates;
}
function injectSorter(prefixCls, columns, sorterSates, triggerSorter, defaultSortDirections, tableLocale, tableShowSorterTooltip, pos) {
return (columns || []).map(function (column, index) {
var columnPos = getColumnPos(index, pos);
var newColumn = column;
if (newColumn.sorter) {
var sortDirections = newColumn.sortDirections || defaultSortDirections;
var showSorterTooltip = newColumn.showSorterTooltip === undefined ? tableShowSorterTooltip : newColumn.showSorterTooltip;
var columnKey = getColumnKey(newColumn, columnPos);
var sorterState = sorterSates.find(function (_ref) {
var key = _ref.key;
return key === columnKey;
});
var sorterOrder = sorterState ? sorterState.sortOrder : null;
var nextSortOrder = nextSortDirection(sortDirections, sorterOrder);
var upNode = sortDirections.includes(ASCEND) && /*#__PURE__*/react["createElement"](CaretUpOutlined_default.a, {
className: classnames_default()("".concat(prefixCls, "-column-sorter-up"), {
active: sorterOrder === ASCEND
})
});
var downNode = sortDirections.includes(DESCEND) && /*#__PURE__*/react["createElement"](CaretDownOutlined_default.a, {
className: classnames_default()("".concat(prefixCls, "-column-sorter-down"), {
active: sorterOrder === DESCEND
})
});
var _ref2 = tableLocale || {},
cancelSort = _ref2.cancelSort,
triggerAsc = _ref2.triggerAsc,
triggerDesc = _ref2.triggerDesc;
var sortTip = cancelSort;
if (nextSortOrder === DESCEND) {
sortTip = triggerDesc;
} else if (nextSortOrder === ASCEND) {
sortTip = triggerAsc;
}
newColumn = extends_default()(extends_default()({}, newColumn), {
className: classnames_default()(newColumn.className, defineProperty_default()({}, "".concat(prefixCls, "-column-sort"), sorterOrder)),
title: function title(renderProps) {
var renderSortTitle = /*#__PURE__*/react["createElement"]("div", {
className: "".concat(prefixCls, "-column-sorters")
}, /*#__PURE__*/react["createElement"]("span", null, renderColumnTitle(column.title, renderProps)), /*#__PURE__*/react["createElement"]("span", {
className: classnames_default()("".concat(prefixCls, "-column-sorter"), defineProperty_default()({}, "".concat(prefixCls, "-column-sorter-full"), upNode && downNode))
}, /*#__PURE__*/react["createElement"]("span", {
className: "".concat(prefixCls, "-column-sorter-inner")
}, upNode, downNode)));
return showSorterTooltip ? /*#__PURE__*/react["createElement"](tooltip["a" /* default */], {
title: sortTip
}, /*#__PURE__*/react["createElement"]("div", {
className: "".concat(prefixCls, "-column-sorters-with-tooltip")
}, renderSortTitle)) : renderSortTitle;
},
onHeaderCell: function onHeaderCell(col) {
var cell = column.onHeaderCell && column.onHeaderCell(col) || {};
var originOnClick = cell.onClick;
cell.onClick = function (event) {
triggerSorter({
column: column,
key: columnKey,
sortOrder: nextSortOrder,
multiplePriority: getMultiplePriority(column)
});
if (originOnClick) {
originOnClick(event);
}
};
cell.className = classnames_default()(cell.className, "".concat(prefixCls, "-column-has-sorters"));
return cell;
}
});
}
if ('children' in newColumn) {
newColumn = extends_default()(extends_default()({}, newColumn), {
children: injectSorter(prefixCls, newColumn.children, sorterSates, triggerSorter, defaultSortDirections, tableLocale, tableShowSorterTooltip, columnPos)
});
}
return newColumn;
});
}
function stateToInfo(sorterStates) {
var column = sorterStates.column,
sortOrder = sorterStates.sortOrder;
return {
column: column,
order: sortOrder,
field: column.dataIndex,
columnKey: column.key
};
}
function generateSorterInfo(sorterStates) {
var list = sorterStates.filter(function (_ref3) {
var sortOrder = _ref3.sortOrder;
return sortOrder;
}).map(stateToInfo); // =========== Legacy compatible support ===========
// https://github.com/ant-design/ant-design/pull/19226
if (list.length === 0 && sorterStates.length) {
return extends_default()(extends_default()({}, stateToInfo(sorterStates[sorterStates.length - 1])), {
column: undefined
});
}
if (list.length <= 1) {
return list[0] || {};
}
return list;
}
function getSortData(data, sortStates, childrenColumnName) {
var innerSorterStates = sortStates.slice().sort(function (a, b) {
return b.multiplePriority - a.multiplePriority;
});
var cloneData = data.slice();
var runningSorters = innerSorterStates.filter(function (_ref4) {
var sorter = _ref4.column.sorter,
sortOrder = _ref4.sortOrder;
return getSortFunction(sorter) && sortOrder;
}); // Skip if no sorter needed
if (!runningSorters.length) {
return cloneData;
}
return cloneData.sort(function (record1, record2) {
for (var i = 0; i < runningSorters.length; i += 1) {
var sorterState = runningSorters[i];
var sorter = sorterState.column.sorter,
sortOrder = sorterState.sortOrder;
var compareFn = getSortFunction(sorter);
if (compareFn && sortOrder) {
var compareResult = compareFn(record1, record2, sortOrder);
if (compareResult !== 0) {
return sortOrder === ASCEND ? compareResult : -compareResult;
}
}
}
return 0;
}).map(function (record) {
var subRecords = record[childrenColumnName];
if (subRecords) {
return extends_default()(extends_default()({}, record), defineProperty_default()({}, childrenColumnName, getSortData(subRecords, sortStates, childrenColumnName)));
}
return record;
});
}
function useFilterSorter(_ref5) {
var prefixCls = _ref5.prefixCls,
mergedColumns = _ref5.mergedColumns,
onSorterChange = _ref5.onSorterChange,
sortDirections = _ref5.sortDirections,
tableLocale = _ref5.tableLocale,
showSorterTooltip = _ref5.showSorterTooltip;
var _React$useState = react["useState"](collectSortStates(mergedColumns, true)),
_React$useState2 = slicedToArray_default()(_React$useState, 2),
sortStates = _React$useState2[0],
setSortStates = _React$useState2[1];
var mergedSorterStates = react["useMemo"](function () {
var validate = true;
var collectedStates = collectSortStates(mergedColumns, false); // Return if not controlled
if (!collectedStates.length) {
return sortStates;
}
var validateStates = [];
function patchStates(state) {
if (validate) {
validateStates.push(state);
} else {
validateStates.push(extends_default()(extends_default()({}, state), {
sortOrder: null
}));
}
}
var multipleMode = null;
collectedStates.forEach(function (state) {
if (multipleMode === null) {
patchStates(state);
if (state.sortOrder) {
if (state.multiplePriority === false) {
validate = false;
} else {
multipleMode = true;
}
}
} else if (multipleMode && state.multiplePriority !== false) {
patchStates(state);
} else {
validate = false;
patchStates(state);
}
});
return validateStates;
}, [mergedColumns, sortStates]); // Get render columns title required props
var columnTitleSorterProps = react["useMemo"](function () {
var sortColumns = mergedSorterStates.map(function (_ref6) {
var column = _ref6.column,
sortOrder = _ref6.sortOrder;
return {
column: column,
order: sortOrder
};
});
return {
sortColumns: sortColumns,
// Legacy
sortColumn: sortColumns[0] && sortColumns[0].column,
sortOrder: sortColumns[0] && sortColumns[0].order
};
}, [mergedSorterStates]);
function triggerSorter(sortState) {
var newSorterStates;
if (sortState.multiplePriority === false || !mergedSorterStates.length || mergedSorterStates[0].multiplePriority === false) {
newSorterStates = [sortState];
} else {
newSorterStates = [].concat(toConsumableArray_default()(mergedSorterStates.filter(function (_ref7) {
var key = _ref7.key;
return key !== sortState.key;
})), [sortState]);
}
setSortStates(newSorterStates);
onSorterChange(generateSorterInfo(newSorterStates), newSorterStates);
}
var transformColumns = function transformColumns(innerColumns) {
return injectSorter(prefixCls, innerColumns, mergedSorterStates, triggerSorter, sortDirections, tableLocale, showSorterTooltip);
};
var getSorters = function getSorters() {
return generateSorterInfo(mergedSorterStates);
};
return [transformColumns, mergedSorterStates, columnTitleSorterProps, getSorters];
}
// EXTERNAL MODULE: ./node_modules/lodash/isEqual.js
var isEqual = __webpack_require__("Y+p1");
var isEqual_default = /*#__PURE__*/__webpack_require__.n(isEqual);
// EXTERNAL MODULE: ./node_modules/@ant-design/icons/FilterFilled.js
var FilterFilled = __webpack_require__("5Uyt");
var FilterFilled_default = /*#__PURE__*/__webpack_require__.n(FilterFilled);
// EXTERNAL MODULE: ./node_modules/antd/es/button/index.js
var es_button = __webpack_require__("2/Rp");
// EXTERNAL MODULE: ./node_modules/antd/es/empty/index.js + 2 modules
var empty = __webpack_require__("ECub");
// CONCATENATED MODULE: ./node_modules/antd/es/table/hooks/useFilter/FilterWrapper.js
var FilterWrapper_FilterDropdownMenuWrapper = function FilterDropdownMenuWrapper(props) {
return /*#__PURE__*/react["createElement"]("div", {
className: props.className,
onClick: function onClick(e) {
return e.stopPropagation();
}
}, props.children);
};
/* harmony default export */ var FilterWrapper = (FilterWrapper_FilterDropdownMenuWrapper);
// EXTERNAL MODULE: ./node_modules/antd/es/_util/hooks/useSyncState.js
var useSyncState = __webpack_require__("sPtV");
// CONCATENATED MODULE: ./node_modules/antd/es/table/hooks/useFilter/FilterDropdown.js
var SubMenu = es_menu["a" /* default */].SubMenu,
MenuItem = es_menu["a" /* default */].Item;
function hasSubMenu(filters) {
return filters.some(function (_ref) {
var children = _ref.children;
return children;
});
}
function renderFilterItems(_ref2) {
var filters = _ref2.filters,
prefixCls = _ref2.prefixCls,
filteredKeys = _ref2.filteredKeys,
filterMultiple = _ref2.filterMultiple,
locale = _ref2.locale;
if (filters.length === 0) {
// wrapped with <></> to avoid react warning
// https://github.com/ant-design/ant-design/issues/25979
return /*#__PURE__*/react["createElement"](react["Fragment"], null, /*#__PURE__*/react["createElement"](empty["a" /* default */], {
image: empty["a" /* default */].PRESENTED_IMAGE_SIMPLE,
description: locale.filterEmptyText,
style: {
margin: '16px 0'
},
imageStyle: {
height: 24
}
}));
}
return filters.map(function (filter, index) {
var key = String(filter.value);
if (filter.children) {
return /*#__PURE__*/react["createElement"](SubMenu, {
key: key || index,
title: filter.text,
popupClassName: "".concat(prefixCls, "-dropdown-submenu")
}, renderFilterItems({
filters: filter.children,
prefixCls: prefixCls,
filteredKeys: filteredKeys,
filterMultiple: filterMultiple,
locale: locale
}));
}
var Component = filterMultiple ? es_checkbox["a" /* default */] : es_radio["a" /* default */];
return /*#__PURE__*/react["createElement"](MenuItem, {
key: filter.value !== undefined ? key : index
}, /*#__PURE__*/react["createElement"](Component, {
checked: filteredKeys.includes(key)
}), /*#__PURE__*/react["createElement"]("span", null, filter.text));
});
}
function FilterDropdown(props) {
var _a;
var prefixCls = props.prefixCls,
column = props.column,
dropdownPrefixCls = props.dropdownPrefixCls,
columnKey = props.columnKey,
filterMultiple = props.filterMultiple,
filterState = props.filterState,
triggerFilter = props.triggerFilter,
locale = props.locale,
children = props.children,
getPopupContainer = props.getPopupContainer;
var filterDropdownVisible = column.filterDropdownVisible,
onFilterDropdownVisibleChange = column.onFilterDropdownVisibleChange;
var _React$useState = react["useState"](false),
_React$useState2 = slicedToArray_default()(_React$useState, 2),
visible = _React$useState2[0],
setVisible = _React$useState2[1];
var filtered = !!(filterState && (((_a = filterState.filteredKeys) === null || _a === void 0 ? void 0 : _a.length) || filterState.forceFiltered));
var triggerVisible = function triggerVisible(newVisible) {
setVisible(newVisible);
if (onFilterDropdownVisibleChange) {
onFilterDropdownVisibleChange(newVisible);
}
};
var mergedVisible = typeof filterDropdownVisible === 'boolean' ? filterDropdownVisible : visible; // ===================== Select Keys =====================
var propFilteredKeys = filterState && filterState.filteredKeys;
var _useSyncState = Object(useSyncState["a" /* default */])(propFilteredKeys || []),
_useSyncState2 = slicedToArray_default()(_useSyncState, 2),
getFilteredKeysSync = _useSyncState2[0],
setFilteredKeysSync = _useSyncState2[1];
var onSelectKeys = function onSelectKeys(_ref3) {
var selectedKeys = _ref3.selectedKeys;
setFilteredKeysSync(selectedKeys);
};
react["useEffect"](function () {
onSelectKeys({
selectedKeys: propFilteredKeys || []
});
}, [propFilteredKeys]); // ====================== Open Keys ======================
var _React$useState3 = react["useState"]([]),
_React$useState4 = slicedToArray_default()(_React$useState3, 2),
openKeys = _React$useState4[0],
setOpenKeys = _React$useState4[1];
var openRef = react["useRef"]();
var onOpenChange = function onOpenChange(keys) {
openRef.current = window.setTimeout(function () {
setOpenKeys(keys);
});
};
var onMenuClick = function onMenuClick() {
window.clearTimeout(openRef.current);
};
react["useEffect"](function () {
return function () {
window.clearTimeout(openRef.current);
};
}, []); // ======================= Submit ========================
var internalTriggerFilter = function internalTriggerFilter(keys) {
triggerVisible(false);
var mergedKeys = keys && keys.length ? keys : null;
if (mergedKeys === null && (!filterState || !filterState.filteredKeys)) {
return null;
}
if (isEqual_default()(mergedKeys, filterState === null || filterState === void 0 ? void 0 : filterState.filteredKeys)) {
return null;
}
triggerFilter({
column: column,
key: columnKey,
filteredKeys: mergedKeys
});
};
var onConfirm = function onConfirm() {
internalTriggerFilter(getFilteredKeysSync());
};
var onReset = function onReset() {
setFilteredKeysSync([]);
internalTriggerFilter([]);
};
var onVisibleChange = function onVisibleChange(newVisible) {
if (newVisible && propFilteredKeys !== undefined) {
// Sync filteredKeys on appear in controlled mode (propFilteredKeys !== undefiend)
setFilteredKeysSync(propFilteredKeys || []);
}
triggerVisible(newVisible); // Default will filter when closed
if (!newVisible && !column.filterDropdown) {
onConfirm();
}
}; // ======================== Style ========================
var dropdownMenuClass = classnames_default()(defineProperty_default()({}, "".concat(dropdownPrefixCls, "-menu-without-submenu"), !hasSubMenu(column.filters || [])));
var dropdownContent;
if (typeof column.filterDropdown === 'function') {
dropdownContent = column.filterDropdown({
prefixCls: "".concat(dropdownPrefixCls, "-custom"),
setSelectedKeys: function setSelectedKeys(selectedKeys) {
return onSelectKeys({
selectedKeys: selectedKeys
});
},
selectedKeys: getFilteredKeysSync(),
confirm: onConfirm,
clearFilters: onReset,
filters: column.filters,
visible: mergedVisible
});
} else if (column.filterDropdown) {
dropdownContent = column.filterDropdown;
} else {
var selectedKeys = getFilteredKeysSync() || [];
dropdownContent = /*#__PURE__*/react["createElement"](react["Fragment"], null, /*#__PURE__*/react["createElement"](es_menu["a" /* default */], {
multiple: filterMultiple,
prefixCls: "".concat(dropdownPrefixCls, "-menu"),
className: dropdownMenuClass,
onClick: onMenuClick,
onSelect: onSelectKeys,
onDeselect: onSelectKeys,
selectedKeys: selectedKeys,
getPopupContainer: getPopupContainer,
openKeys: openKeys,
onOpenChange: onOpenChange
}, renderFilterItems({
filters: column.filters || [],
prefixCls: prefixCls,
filteredKeys: getFilteredKeysSync(),
filterMultiple: filterMultiple,
locale: locale
})), /*#__PURE__*/react["createElement"]("div", {
className: "".concat(prefixCls, "-dropdown-btns")
}, /*#__PURE__*/react["createElement"](es_button["a" /* default */], {
type: "link",
size: "small",
disabled: selectedKeys.length === 0,
onClick: onReset
}, locale.filterReset), /*#__PURE__*/react["createElement"](es_button["a" /* default */], {
type: "primary",
size: "small",
onClick: onConfirm
}, locale.filterConfirm)));
}
var menu = /*#__PURE__*/react["createElement"](FilterWrapper, {
className: "".concat(prefixCls, "-dropdown")
}, dropdownContent);
var filterIcon;
if (typeof column.filterIcon === 'function') {
filterIcon = column.filterIcon(filtered);
} else if (column.filterIcon) {
filterIcon = column.filterIcon;
} else {
filterIcon = /*#__PURE__*/react["createElement"](FilterFilled_default.a, null);
}
var _React$useContext = react["useContext"](config_provider_context["b" /* ConfigContext */]),
direction = _React$useContext.direction;
return /*#__PURE__*/react["createElement"]("div", {
className: classnames_default()("".concat(prefixCls, "-column"))
}, /*#__PURE__*/react["createElement"]("span", {
className: "".concat(prefixCls, "-column-title")
}, children), /*#__PURE__*/react["createElement"]("span", {
className: classnames_default()("".concat(prefixCls, "-trigger-container"), defineProperty_default()({}, "".concat(prefixCls, "-trigger-container-open"), mergedVisible)),
onClick: function onClick(e) {
e.stopPropagation();
}
}, /*#__PURE__*/react["createElement"](dropdown["a" /* default */], {
overlay: menu,
trigger: ['click'],
visible: mergedVisible,
onVisibleChange: onVisibleChange,
getPopupContainer: getPopupContainer,
placement: direction === 'rtl' ? 'bottomLeft' : 'bottomRight'
}, /*#__PURE__*/react["createElement"]("span", {
role: "button",
tabIndex: -1,
className: classnames_default()("".concat(prefixCls, "-trigger"), {
active: filtered
})
}, filterIcon))));
}
/* harmony default export */ var useFilter_FilterDropdown = (FilterDropdown);
// CONCATENATED MODULE: ./node_modules/antd/es/table/hooks/useFilter/index.js
function collectFilterStates(columns, init, pos) {
var filterStates = [];
(columns || []).forEach(function (column, index) {
var columnPos = getColumnPos(index, pos);
if ('children' in column) {
filterStates = [].concat(toConsumableArray_default()(filterStates), toConsumableArray_default()(collectFilterStates(column.children, init, columnPos)));
} else if (column.filters || 'filterDropdown' in column || 'onFilter' in column) {
if ('filteredValue' in column) {
// Controlled
filterStates.push({
column: column,
key: getColumnKey(column, columnPos),
filteredKeys: column.filteredValue,
forceFiltered: column.filtered
});
} else {
// Uncontrolled
filterStates.push({
column: column,
key: getColumnKey(column, columnPos),
filteredKeys: init && column.defaultFilteredValue ? column.defaultFilteredValue : undefined,
forceFiltered: column.filtered
});
}
}
});
return filterStates;
}
function injectFilter(prefixCls, dropdownPrefixCls, columns, filterStates, triggerFilter, getPopupContainer, locale, pos) {
return columns.map(function (column, index) {
var columnPos = getColumnPos(index, pos);
var _column$filterMultipl = column.filterMultiple,
filterMultiple = _column$filterMultipl === void 0 ? true : _column$filterMultipl;
if (column.filters || 'filterDropdown' in column) {
var columnKey = getColumnKey(column, columnPos);
var filterState = filterStates.find(function (_ref) {
var key = _ref.key;
return columnKey === key;
});
return extends_default()(extends_default()({}, column), {
title: function title(renderProps) {
return /*#__PURE__*/react["createElement"](useFilter_FilterDropdown, {
prefixCls: "".concat(prefixCls, "-filter"),
dropdownPrefixCls: dropdownPrefixCls,
column: column,
columnKey: columnKey,
filterState: filterState,
filterMultiple: filterMultiple,
triggerFilter: triggerFilter,
locale: locale,
getPopupContainer: getPopupContainer
}, renderColumnTitle(column.title, renderProps));
}
});
}
if ('children' in column) {
return extends_default()(extends_default()({}, column), {
children: injectFilter(prefixCls, dropdownPrefixCls, column.children, filterStates, triggerFilter, getPopupContainer, locale, columnPos)
});
}
return column;
});
}
function generateFilterInfo(filterStates) {
var currentFilters = {};
filterStates.forEach(function (_ref2) {
var key = _ref2.key,
filteredKeys = _ref2.filteredKeys;
currentFilters[key] = filteredKeys || null;
});
return currentFilters;
}
function flattenKeys(filters) {
var keys = [];
(filters || []).forEach(function (_ref3) {
var value = _ref3.value,
children = _ref3.children;
keys.push(value);
if (children) {
keys = [].concat(toConsumableArray_default()(keys), toConsumableArray_default()(flattenKeys(children)));
}
});
return keys;
}
function getFilterData(data, filterStates) {
return filterStates.reduce(function (currentData, filterState) {
var _filterState$column = filterState.column,
onFilter = _filterState$column.onFilter,
filters = _filterState$column.filters,
filteredKeys = filterState.filteredKeys;
if (onFilter && filteredKeys && filteredKeys.length) {
return currentData.filter(function (record) {
return filteredKeys.some(function (key) {
var keys = flattenKeys(filters);
var keyIndex = keys.findIndex(function (k) {
return String(k) === String(key);
});
var realKey = keyIndex !== -1 ? keys[keyIndex] : key;
return onFilter(realKey, record);
});
});
}
return currentData;
}, data);
}
function useFilter(_ref4) {
var prefixCls = _ref4.prefixCls,
dropdownPrefixCls = _ref4.dropdownPrefixCls,
mergedColumns = _ref4.mergedColumns,
onFilterChange = _ref4.onFilterChange,
getPopupContainer = _ref4.getPopupContainer,
tableLocale = _ref4.locale;
var _React$useState = react["useState"](collectFilterStates(mergedColumns, true)),
_React$useState2 = slicedToArray_default()(_React$useState, 2),
filterStates = _React$useState2[0],
setFilterStates = _React$useState2[1];
var mergedFilterStates = react["useMemo"](function () {
var collectedStates = collectFilterStates(mergedColumns, false); // Return if not controlled
if (collectedStates.every(function (_ref5) {
var filteredKeys = _ref5.filteredKeys;
return filteredKeys === undefined;
})) {
return filterStates;
}
return collectedStates;
}, [mergedColumns, filterStates]);
var getFilters = react["useCallback"](function () {
return generateFilterInfo(mergedFilterStates);
}, [mergedFilterStates]);
var triggerFilter = function triggerFilter(filterState) {
var newFilterStates = mergedFilterStates.filter(function (_ref6) {
var key = _ref6.key;
return key !== filterState.key;
});
newFilterStates.push(filterState);
setFilterStates(newFilterStates);
onFilterChange(generateFilterInfo(newFilterStates), newFilterStates);
};
var transformColumns = function transformColumns(innerColumns) {
return injectFilter(prefixCls, dropdownPrefixCls, innerColumns, mergedFilterStates, triggerFilter, getPopupContainer, tableLocale);
};
return [transformColumns, mergedFilterStates, getFilters];
}
/* harmony default export */ var hooks_useFilter = (useFilter);
// CONCATENATED MODULE: ./node_modules/antd/es/table/hooks/useTitleColumns.js
function fillTitle(columns, columnTitleProps) {
return columns.map(function (column) {
var cloneColumn = extends_default()({}, column);
cloneColumn.title = renderColumnTitle(column.title, columnTitleProps);
if ('children' in cloneColumn) {
cloneColumn.children = fillTitle(cloneColumn.children, columnTitleProps);
}
return cloneColumn;
});
}
function useTitleColumns(columnTitleProps) {
var filledColumns = react["useCallback"](function (columns) {
return fillTitle(columns, columnTitleProps);
}, [columnTitleProps]);
return [filledColumns];
}
// CONCATENATED MODULE: ./node_modules/antd/es/table/ExpandIcon.js
function ExpandIcon_renderExpandIcon(locale) {
return function expandIcon(_ref) {
var _classNames;
var prefixCls = _ref.prefixCls,
onExpand = _ref.onExpand,
record = _ref.record,
expanded = _ref.expanded,
expandable = _ref.expandable;
var iconPrefix = "".concat(prefixCls, "-row-expand-icon");
return /*#__PURE__*/react["createElement"]("button", {
type: "button",
onClick: function onClick(e) {
onExpand(record, e);
e.stopPropagation();
},
className: classnames_default()(iconPrefix, (_classNames = {}, defineProperty_default()(_classNames, "".concat(iconPrefix, "-spaced"), !expandable), defineProperty_default()(_classNames, "".concat(iconPrefix, "-expanded"), expandable && expanded), defineProperty_default()(_classNames, "".concat(iconPrefix, "-collapsed"), expandable && !expanded), _classNames)),
"aria-label": expanded ? locale.collapse : locale.expand
});
};
}
/* harmony default export */ var ExpandIcon = (ExpandIcon_renderExpandIcon);
// CONCATENATED MODULE: ./node_modules/antd/es/_util/getScroll.js
function isWindow(obj) {
return obj !== null && obj !== undefined && obj === obj.window;
}
function getScroll_getScroll(target, top) {
if (typeof window === 'undefined') {
return 0;
}
var method = top ? 'scrollTop' : 'scrollLeft';
var result = 0;
if (isWindow(target)) {
result = target[top ? 'pageYOffset' : 'pageXOffset'];
} else if (target instanceof Document) {
result = target.documentElement[method];
} else if (target) {
result = target[method];
}
if (target && !isWindow(target) && typeof result !== 'number') {
result = (target.ownerDocument || target).documentElement[method];
}
return result;
}
// CONCATENATED MODULE: ./node_modules/antd/es/_util/easings.js
// eslint-disable-next-line import/prefer-default-export
function easeInOutCubic(t, b, c, d) {
var cc = c - b;
t /= d / 2;
if (t < 1) {
return cc / 2 * t * t * t + b;
} // eslint-disable-next-line no-return-assign
return cc / 2 * ((t -= 2) * t * t + 2) + b;
}
// CONCATENATED MODULE: ./node_modules/antd/es/_util/scrollTo.js
function scrollTo(y) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var _options$getContainer = options.getContainer,
getContainer = _options$getContainer === void 0 ? function () {
return window;
} : _options$getContainer,
callback = options.callback,
_options$duration = options.duration,
duration = _options$duration === void 0 ? 450 : _options$duration;
var container = getContainer();
var scrollTop = getScroll_getScroll(container, true);
var startTime = Date.now();
var frameFunc = function frameFunc() {
var timestamp = Date.now();
var time = timestamp - startTime;
var nextScrollTop = easeInOutCubic(time > duration ? duration : time, scrollTop, y, duration);
if (isWindow(container)) {
container.scrollTo(window.pageXOffset, nextScrollTop);
} else if (container instanceof HTMLDocument || container.constructor.name === 'HTMLDocument') {
container.documentElement.scrollTop = nextScrollTop;
} else {
container.scrollTop = nextScrollTop;
}
if (time < duration) {
raf_default()(frameFunc);
} else if (typeof callback === 'function') {
callback();
}
};
raf_default()(frameFunc);
}
// EXTERNAL MODULE: ./node_modules/antd/es/locale/default.js + 4 modules
var locale_default = __webpack_require__("ZvpZ");
// CONCATENATED MODULE: ./node_modules/antd/es/locale/en_US.js
/* harmony default export */ var en_US = (locale_default["a" /* default */]);
// EXTERNAL MODULE: ./node_modules/antd/es/config-provider/SizeContext.js
var SizeContext = __webpack_require__("3Nzz");
// CONCATENATED MODULE: ./node_modules/antd/es/table/Column.js
/* istanbul ignore next */
/**
* This is a syntactic sugar for `columns` prop.
* So HOC will not work on this.
*/
// eslint-disable-next-line no-unused-vars
function Column_Column(_) {
return null;
}
/* harmony default export */ var table_Column = (Column_Column);
// CONCATENATED MODULE: ./node_modules/antd/es/table/ColumnGroup.js
/* istanbul ignore next */
/**
* This is a syntactic sugar for `columns` prop.
* So HOC will not work on this.
*/
// eslint-disable-next-line no-unused-vars
function ColumnGroup_ColumnGroup(_) {
return null;
}
/* harmony default export */ var table_ColumnGroup = (ColumnGroup_ColumnGroup);
// EXTERNAL MODULE: ./node_modules/antd/es/grid/hooks/useBreakpoint.js
var useBreakpoint = __webpack_require__("5OYt");
// CONCATENATED MODULE: ./node_modules/antd/es/table/Table.js
var EMPTY_LIST = [];
function Table_Table(props) {
var _classNames3;
var customizePrefixCls = props.prefixCls,
className = props.className,
style = props.style,
customizeSize = props.size,
bordered = props.bordered,
customizeDropdownPrefixCls = props.dropdownPrefixCls,
dataSource = props.dataSource,
pagination = props.pagination,
rowSelection = props.rowSelection,
rowKey = props.rowKey,
rowClassName = props.rowClassName,
columns = props.columns,
children = props.children,
legacyChildrenColumnName = props.childrenColumnName,
onChange = props.onChange,
getPopupContainer = props.getPopupContainer,
loading = props.loading,
expandIcon = props.expandIcon,
expandable = props.expandable,
expandedRowRender = props.expandedRowRender,
expandIconColumnIndex = props.expandIconColumnIndex,
indentSize = props.indentSize,
scroll = props.scroll,
sortDirections = props.sortDirections,
locale = props.locale,
_props$showSorterTool = props.showSorterTooltip,
showSorterTooltip = _props$showSorterTool === void 0 ? true : _props$showSorterTool;
Object(devWarning["a" /* default */])(!(typeof rowKey === 'function' && rowKey.length > 1), 'Table', '`index` parameter of `rowKey` function is deprecated. There is no guarantee that it will work as expected.');
var screens = Object(useBreakpoint["a" /* default */])();
var mergedColumns = react["useMemo"](function () {
var matched = new Set(Object.keys(screens).filter(function (m) {
return screens[m];
}));
return (columns || convertChildrenToColumns(children)).filter(function (c) {
return !c.responsive || c.responsive.some(function (r) {
return matched.has(r);
});
});
}, [children, columns, screens]);
var tableProps = Object(es["a" /* default */])(props, ['className', 'style', 'columns']);
var size = react["useContext"](SizeContext["b" /* default */]);
var _React$useContext = react["useContext"](config_provider_context["b" /* ConfigContext */]),
_React$useContext$loc = _React$useContext.locale,
contextLocale = _React$useContext$loc === void 0 ? en_US : _React$useContext$loc,
renderEmpty = _React$useContext.renderEmpty,
direction = _React$useContext.direction;
var mergedSize = customizeSize || size;
var tableLocale = extends_default()(extends_default()({}, contextLocale.Table), locale);
var rawData = dataSource || EMPTY_LIST;
var _React$useContext2 = react["useContext"](config_provider_context["b" /* ConfigContext */]),
getPrefixCls = _React$useContext2.getPrefixCls;
var prefixCls = getPrefixCls('table', customizePrefixCls);
var dropdownPrefixCls = getPrefixCls('dropdown', customizeDropdownPrefixCls);
var mergedExpandable = extends_default()({
childrenColumnName: legacyChildrenColumnName,
expandIconColumnIndex: expandIconColumnIndex
}, expandable);
var _mergedExpandable$chi = mergedExpandable.childrenColumnName,
childrenColumnName = _mergedExpandable$chi === void 0 ? 'children' : _mergedExpandable$chi;
var expandType = react["useMemo"](function () {
if (rawData.some(function (item) {
var _a;
return (_a = item) === null || _a === void 0 ? void 0 : _a[childrenColumnName];
})) {
return 'nest';
}
if (expandedRowRender || expandable && expandable.expandedRowRender) {
return 'row';
}
return null;
}, [rawData]);
var internalRefs = {
body: react["useRef"]()
}; // ============================ RowKey ============================
var getRowKey = react["useMemo"](function () {
if (typeof rowKey === 'function') {
return rowKey;
}
return function (record) {
var _a;
return (_a = record) === null || _a === void 0 ? void 0 : _a[rowKey];
};
}, [rowKey]);
var _useLazyKVMap = useLazyKVMap(rawData, childrenColumnName, getRowKey),
_useLazyKVMap2 = slicedToArray_default()(_useLazyKVMap, 1),
getRecordByKey = _useLazyKVMap2[0]; // ============================ Events =============================
var changeEventInfo = {};
var triggerOnChange = function triggerOnChange(info, action) {
var reset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var changeInfo = extends_default()(extends_default()({}, changeEventInfo), info);
if (reset) {
changeEventInfo.resetPagination(); // Reset event param
if (changeInfo.pagination.current) {
changeInfo.pagination.current = 1;
} // Trigger pagination events
if (pagination && pagination.onChange) {
pagination.onChange(1, changeInfo.pagination.pageSize);
}
}
if (scroll && scroll.scrollToFirstRowOnChange !== false && internalRefs.body.current) {
scrollTo(0, {
getContainer: function getContainer() {
return internalRefs.body.current;
}
});
}
if (onChange) {
onChange(changeInfo.pagination, changeInfo.filters, changeInfo.sorter, {
currentDataSource: getFilterData(getSortData(rawData, changeInfo.sorterStates, childrenColumnName), changeInfo.filterStates),
action: action
});
}
};
/**
* Controlled state in `columns` is not a good idea that makes too many code (1000+ line?)
* to read state out and then put it back to title render.
* Move these code into `hooks` but still too complex.
* We should provides Table props like `sorter` & `filter` to handle control in next big version.
*/
// ============================ Sorter =============================
var onSorterChange = function onSorterChange(sorter, sorterStates) {
triggerOnChange({
sorter: sorter,
sorterStates: sorterStates
}, 'sort', false);
};
var _useSorter = useFilterSorter({
prefixCls: prefixCls,
mergedColumns: mergedColumns,
onSorterChange: onSorterChange,
sortDirections: sortDirections || ['ascend', 'descend'],
tableLocale: tableLocale,
showSorterTooltip: showSorterTooltip
}),
_useSorter2 = slicedToArray_default()(_useSorter, 4),
transformSorterColumns = _useSorter2[0],
sortStates = _useSorter2[1],
sorterTitleProps = _useSorter2[2],
getSorters = _useSorter2[3];
var sortedData = react["useMemo"](function () {
return getSortData(rawData, sortStates, childrenColumnName);
}, [rawData, sortStates]);
changeEventInfo.sorter = getSorters();
changeEventInfo.sorterStates = sortStates; // ============================ Filter ============================
var onFilterChange = function onFilterChange(filters, filterStates) {
triggerOnChange({
filters: filters,
filterStates: filterStates
}, 'filter', true);
};
var _useFilter = hooks_useFilter({
prefixCls: prefixCls,
locale: tableLocale,
dropdownPrefixCls: dropdownPrefixCls,
mergedColumns: mergedColumns,
onFilterChange: onFilterChange,
getPopupContainer: getPopupContainer
}),
_useFilter2 = slicedToArray_default()(_useFilter, 3),
transformFilterColumns = _useFilter2[0],
filterStates = _useFilter2[1],
getFilters = _useFilter2[2];
var mergedData = getFilterData(sortedData, filterStates);
changeEventInfo.filters = getFilters();
changeEventInfo.filterStates = filterStates; // ============================ Column ============================
var columnTitleProps = react["useMemo"](function () {
return extends_default()({}, sorterTitleProps);
}, [sorterTitleProps]);
var _useTitleColumns = useTitleColumns(columnTitleProps),
_useTitleColumns2 = slicedToArray_default()(_useTitleColumns, 1),
transformTitleColumns = _useTitleColumns2[0]; // ========================== Pagination ==========================
var onPaginationChange = function onPaginationChange(current, pageSize) {
triggerOnChange({
pagination: extends_default()(extends_default()({}, changeEventInfo.pagination), {
current: current,
pageSize: pageSize
})
}, 'paginate');
};
var _usePagination = usePagination(mergedData.length, pagination, onPaginationChange),
_usePagination2 = slicedToArray_default()(_usePagination, 2),
mergedPagination = _usePagination2[0],
resetPagination = _usePagination2[1];
changeEventInfo.pagination = pagination === false ? {} : getPaginationParam(pagination, mergedPagination);
changeEventInfo.resetPagination = resetPagination; // ============================= Data =============================
var pageData = react["useMemo"](function () {
if (pagination === false || !mergedPagination.pageSize) {
return mergedData;
}
var _mergedPagination$cur = mergedPagination.current,
current = _mergedPagination$cur === void 0 ? 1 : _mergedPagination$cur,
total = mergedPagination.total,
_mergedPagination$pag = mergedPagination.pageSize,
pageSize = _mergedPagination$pag === void 0 ? DEFAULT_PAGE_SIZE : _mergedPagination$pag; // Dynamic table data
if (mergedData.length < total) {
if (mergedData.length > pageSize) {
Object(devWarning["a" /* default */])(false, 'Table', '`dataSource` length is less than `pagination.total` but large than `pagination.pageSize`. Please make sure your config correct data with async mode.');
return mergedData.slice((current - 1) * pageSize, current * pageSize);
}
return mergedData;
}
return mergedData.slice((current - 1) * pageSize, current * pageSize);
}, [!!pagination, mergedData, mergedPagination && mergedPagination.current, mergedPagination && mergedPagination.pageSize, mergedPagination && mergedPagination.total]); // ========================== Selections ==========================
var _useSelection = useSelection(rowSelection, {
prefixCls: prefixCls,
data: mergedData,
pageData: pageData,
getRowKey: getRowKey,
getRecordByKey: getRecordByKey,
expandType: expandType,
childrenColumnName: childrenColumnName,
locale: tableLocale,
expandIconColumnIndex: mergedExpandable.expandIconColumnIndex,
getPopupContainer: getPopupContainer
}),
_useSelection2 = slicedToArray_default()(_useSelection, 2),
transformSelectionColumns = _useSelection2[0],
selectedKeySet = _useSelection2[1];
var internalRowClassName = function internalRowClassName(record, index, indent) {
var mergedRowClassName;
if (typeof rowClassName === 'function') {
mergedRowClassName = classnames_default()(rowClassName(record, index, indent));
} else {
mergedRowClassName = classnames_default()(rowClassName);
}
return classnames_default()(defineProperty_default()({}, "".concat(prefixCls, "-row-selected"), selectedKeySet.has(getRowKey(record, index))), mergedRowClassName);
}; // ========================== Expandable ==========================
// Pass origin render status into `rc-table`, this can be removed when refactor with `rc-table`
mergedExpandable.__PARENT_RENDER_ICON__ = mergedExpandable.expandIcon; // Customize expandable icon
mergedExpandable.expandIcon = mergedExpandable.expandIcon || expandIcon || ExpandIcon(tableLocale); // Adjust expand icon index, no overwrite expandIconColumnIndex if set.
if (expandType === 'nest' && mergedExpandable.expandIconColumnIndex === undefined) {
mergedExpandable.expandIconColumnIndex = rowSelection ? 1 : 0;
} else if (mergedExpandable.expandIconColumnIndex > 0 && rowSelection) {
mergedExpandable.expandIconColumnIndex -= 1;
} // Indent size
if (typeof mergedExpandable.indentSize !== 'number') {
mergedExpandable.indentSize = typeof indentSize === 'number' ? indentSize : 15;
} // ============================ Render ============================
var transformColumns = react["useCallback"](function (innerColumns) {
return transformTitleColumns(transformSelectionColumns(transformFilterColumns(transformSorterColumns(innerColumns))));
}, [transformSorterColumns, transformFilterColumns, transformSelectionColumns]);
var topPaginationNode;
var bottomPaginationNode;
if (pagination !== false) {
var paginationSize;
if (mergedPagination.size) {
paginationSize = mergedPagination.size;
} else {
paginationSize = mergedSize === 'small' || mergedSize === 'middle' ? 'small' : undefined;
}
var renderPagination = function renderPagination(position) {
return /*#__PURE__*/react["createElement"](es_pagination["a" /* default */], extends_default()({
className: "".concat(prefixCls, "-pagination ").concat(prefixCls, "-pagination-").concat(position)
}, mergedPagination, {
size: paginationSize
}));
};
var defaultPosition = direction === 'rtl' ? 'left' : 'right';
if (mergedPagination.position !== null && Array.isArray(mergedPagination.position)) {
var topPos = mergedPagination.position.find(function (p) {
return p.indexOf('top') !== -1;
});
var bottomPos = mergedPagination.position.find(function (p) {
return p.indexOf('bottom') !== -1;
});
if (!topPos && !bottomPos) {
bottomPaginationNode = renderPagination(defaultPosition);
} else {
if (topPos) {
topPaginationNode = renderPagination(topPos.toLowerCase().replace('top', ''));
}
if (bottomPos) {
bottomPaginationNode = renderPagination(bottomPos.toLowerCase().replace('bottom', ''));
}
}
} else {
bottomPaginationNode = renderPagination(defaultPosition);
}
} // >>>>>>>>> Spinning
var spinProps;
if (typeof loading === 'boolean') {
spinProps = {
spinning: loading
};
} else if (typeof_default()(loading) === 'object') {
spinProps = extends_default()({
spinning: true
}, loading);
}
var wrapperClassNames = classnames_default()("".concat(prefixCls, "-wrapper"), className, defineProperty_default()({}, "".concat(prefixCls, "-wrapper-rtl"), direction === 'rtl'));
return /*#__PURE__*/react["createElement"]("div", {
className: wrapperClassNames,
style: style
}, /*#__PURE__*/react["createElement"](spin["a" /* default */], extends_default()({
spinning: false
}, spinProps), topPaginationNode, /*#__PURE__*/react["createElement"](rc_table_es, extends_default()({}, tableProps, {
columns: mergedColumns,
direction: direction,
expandable: mergedExpandable,
prefixCls: prefixCls,
className: classnames_default()((_classNames3 = {}, defineProperty_default()(_classNames3, "".concat(prefixCls, "-middle"), mergedSize === 'middle'), defineProperty_default()(_classNames3, "".concat(prefixCls, "-small"), mergedSize === 'small'), defineProperty_default()(_classNames3, "".concat(prefixCls, "-bordered"), bordered), defineProperty_default()(_classNames3, "".concat(prefixCls, "-empty"), rawData.length === 0), _classNames3)),
data: pageData,
rowKey: getRowKey,
rowClassName: internalRowClassName,
emptyText: locale && locale.emptyText || renderEmpty('Table') // Internal
,
internalHooks: INTERNAL_HOOKS,
internalRefs: internalRefs,
transformColumns: transformColumns
})), mergedData && mergedData.length > 0 && bottomPaginationNode));
}
Table_Table.defaultProps = {
rowKey: 'key'
};
Table_Table.SELECTION_ALL = SELECTION_ALL;
Table_Table.SELECTION_INVERT = SELECTION_INVERT;
Table_Table.Column = table_Column;
Table_Table.ColumnGroup = table_ColumnGroup;
Table_Table.Summary = FooterComponents;
/* harmony default export */ var table_Table = (Table_Table);
// CONCATENATED MODULE: ./node_modules/antd/es/table/index.js
/* harmony default export */ var table = __webpack_exports__["a"] = (table_Table);
/***/ }),
/***/ "wZgz":
/*!***************************************!*\
!*** ./node_modules/crypto-js/aes.js ***!
\***************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory, undef) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"), __webpack_require__(/*! ./enc-base64 */ "ETIr"), __webpack_require__(/*! ./md5 */ "cv67"), __webpack_require__(/*! ./evpkdf */ "K3mO"), __webpack_require__(/*! ./cipher-core */ "OLod"));
}
else {}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Lookup tables
var SBOX = [];
var INV_SBOX = [];
var SUB_MIX_0 = [];
var SUB_MIX_1 = [];
var SUB_MIX_2 = [];
var SUB_MIX_3 = [];
var INV_SUB_MIX_0 = [];
var INV_SUB_MIX_1 = [];
var INV_SUB_MIX_2 = [];
var INV_SUB_MIX_3 = [];
// Compute lookup tables
(function () {
// Compute double table
var d = [];
for (var i = 0; i < 256; i++) {
if (i < 128) {
d[i] = i << 1;
} else {
d[i] = (i << 1) ^ 0x11b;
}
}
// Walk GF(2^8)
var x = 0;
var xi = 0;
for (var i = 0; i < 256; i++) {
// Compute sbox
var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);
sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;
SBOX[x] = sx;
INV_SBOX[sx] = x;
// Compute multiplication
var x2 = d[x];
var x4 = d[x2];
var x8 = d[x4];
// Compute sub bytes, mix columns tables
var t = (d[sx] * 0x101) ^ (sx * 0x1010100);
SUB_MIX_0[x] = (t << 24) | (t >>> 8);
SUB_MIX_1[x] = (t << 16) | (t >>> 16);
SUB_MIX_2[x] = (t << 8) | (t >>> 24);
SUB_MIX_3[x] = t;
// Compute inv sub bytes, inv mix columns tables
var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);
INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8);
INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16);
INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24);
INV_SUB_MIX_3[sx] = t;
// Compute next counter
if (!x) {
x = xi = 1;
} else {
x = x2 ^ d[d[d[x8 ^ x2]]];
xi ^= d[d[xi]];
}
}
}());
// Precomputed Rcon lookup
var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
/**
* AES block cipher algorithm.
*/
var AES = C_algo.AES = BlockCipher.extend({
_doReset: function () {
var t;
// Skip reset of nRounds has been set before and key did not change
if (this._nRounds && this._keyPriorReset === this._key) {
return;
}
// Shortcuts
var key = this._keyPriorReset = this._key;
var keyWords = key.words;
var keySize = key.sigBytes / 4;
// Compute number of rounds
var nRounds = this._nRounds = keySize + 6;
// Compute number of key schedule rows
var ksRows = (nRounds + 1) * 4;
// Compute key schedule
var keySchedule = this._keySchedule = [];
for (var ksRow = 0; ksRow < ksRows; ksRow++) {
if (ksRow < keySize) {
keySchedule[ksRow] = keyWords[ksRow];
} else {
t = keySchedule[ksRow - 1];
if (!(ksRow % keySize)) {
// 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] = keySchedule[ksRow - keySize] ^ t;
}
}
// Compute inv key schedule
var invKeySchedule = this._invKeySchedule = [];
for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) {
var ksRow = ksRows - invKsRow;
if (invKsRow % 4) {
var t = keySchedule[ksRow];
} else {
var t = keySchedule[ksRow - 4];
}
if (invKsRow < 4 || ksRow <= 4) {
invKeySchedule[invKsRow] = t;
} else {
invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^
INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]];
}
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX);
},
decryptBlock: function (M, offset) {
// Swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX);
// Inv swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
},
_doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) {
// Shortcut
var nRounds = this._nRounds;
// Get input, add round key
var s0 = M[offset] ^ keySchedule[0];
var s1 = M[offset + 1] ^ keySchedule[1];
var s2 = M[offset + 2] ^ keySchedule[2];
var s3 = M[offset + 3] ^ keySchedule[3];
// Key schedule row counter
var ksRow = 4;
// Rounds
for (var round = 1; round < nRounds; round++) {
// Shift rows, sub bytes, mix columns, add round key
var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++];
var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++];
var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++];
var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++];
// Update state
s0 = t0;
s1 = t1;
s2 = t2;
s3 = t3;
}
// Shift rows, sub bytes, add round key
var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++];
var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++];
var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++];
var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++];
// Set output
M[offset] = t0;
M[offset + 1] = t1;
M[offset + 2] = t2;
M[offset + 3] = t3;
},
keySize: 256/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.AES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg);
*/
C.AES = BlockCipher._createHelper(AES);
}());
return CryptoJS.AES;
}));
/***/ }),
/***/ "wbyO":
/*!*************************************************!*\
!*** ./node_modules/crypto-js/enc-base64url.js ***!
\*************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
;(function (root, factory) {
if (true) {
// CommonJS
module.exports = exports = factory(__webpack_require__(/*! ./core */ "Ib8C"));
}
else {}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* Base64url encoding strategy.
*/
var Base64url = C_enc.Base64url = {
/**
* Converts a word array to a Base64url string.
*
* @param {WordArray} wordArray The word array.
*
* @param {boolean} urlSafe Whether to use url safe
*
* @return {string} The Base64url string.
*
* @static
*
* @example
*
* var base64String = CryptoJS.enc.Base64url.stringify(wordArray);
*/
stringify: function (wordArray, urlSafe=true) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
var map = urlSafe ? this._safe_map : this._map;
// Clamp excess bits
wordArray.clamp();
// Convert
var base64Chars = [];
for (var i = 0; i < sigBytes; i += 3) {
var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;
var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;
var triplet = (byte1 << 16) | (byte2 << 8) | byte3;
for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {
base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));
}
}
// Add padding
var paddingChar = map.charAt(64);
if (paddingChar) {
while (base64Chars.length % 4) {
base64Chars.push(paddingChar);
}
}
return base64Chars.join('');
},
/**
* Converts a Base64url string to a word array.
*
* @param {string} base64Str The Base64url string.
*
* @param {boolean} urlSafe Whether to use url safe
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Base64url.parse(base64String);
*/
parse: function (base64Str, urlSafe=true) {
// Shortcuts
var base64StrLength = base64Str.length;
var map = urlSafe ? this._safe_map : this._map;
var reverseMap = this._reverseMap;
if (!reverseMap) {
reverseMap = this._reverseMap = [];
for (var j = 0; j < map.length; j++) {
reverseMap[map.charCodeAt(j)] = j;
}
}
// Ignore padding
var paddingChar = map.charAt(64);
if (paddingChar) {
var paddingIndex = base64Str.indexOf(paddingChar);
if (paddingIndex !== -1) {
base64StrLength = paddingIndex;
}
}
// Convert
return parseLoop(base64Str, base64StrLength, reverseMap);
},
_map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
_safe_map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
};
function parseLoop(base64Str, base64StrLength, reverseMap) {
var words = [];
var nBytes = 0;
for (var i = 0; i < base64StrLength; i++) {
if (i % 4) {
var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2);
var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2);
var bitsCombined = bits1 | bits2;
words[nBytes >>> 2] |= bitsCombined << (24 - (nBytes % 4) * 8);
nBytes++;
}
}
return WordArray.create(words, nBytes);
}
}());
return CryptoJS.enc.Base64url;
}));
/***/ }),
/***/ "xb2K":
/*!******************************************************************!*\
!*** ./node_modules/@ant-design/icons/lib/icons/RedoOutlined.js ***!
\******************************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireWildcard = __webpack_require__(/*! @babel/runtime/helpers/interopRequireWildcard */ "284h");
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "TqRt");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/objectSpread2 */ "3tO9"));
var React = _interopRequireWildcard(__webpack_require__(/*! react */ "q1tI"));
var _RedoOutlined = _interopRequireDefault(__webpack_require__(/*! @ant-design/icons-svg/lib/asn/RedoOutlined */ "5yev"));
var _AntdIcon = _interopRequireDefault(__webpack_require__(/*! ../components/AntdIcon */ "KQxl"));
// GENERATE BY ./scripts/generate.ts
// DON NOT EDIT IT MANUALLY
var RedoOutlined = function RedoOutlined(props, ref) {
return /*#__PURE__*/React.createElement(_AntdIcon.default, (0, _objectSpread2.default)((0, _objectSpread2.default)({}, props), {}, {
ref: ref,
icon: _RedoOutlined.default
}));
};
RedoOutlined.displayName = 'RedoOutlined';
var _default = /*#__PURE__*/React.forwardRef(RedoOutlined);
exports.default = _default;
/***/ }),
/***/ "xrsn":
/*!**************************************************!*\
!*** ./src/components/Header/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___2cC1r","flex_space_between":"flex_space_between___9TeDx","flex_box_vertical_center":"flex_box_vertical_center___3EIYv","flex_box_center_end":"flex_box_center_end___1Uph0","flex_box_column":"flex_box_column___17_5w","header":"header___1E4MV","logo":"logo___R8PNJ","headerFixed":"headerFixed___1V7d4","menu":"menu___Km2Uo","actived":"actived___12Ff0","edu-menu":"edu-menu___2hxbr","newslight":"newslight___jwZR3","classromediv":"classromediv___Cjpgf","glow":"glow___3Nuu5","spandiv":"spandiv___3YPu8"};
/***/ }),
/***/ "y3Yb":
/*!***********************************************************************!*\
!*** ./node_modules/@ant-design/icons/lib/icons/PaperClipOutlined.js ***!
\***********************************************************************/
/*! no static exports found */
/*! all exports used */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _interopRequireWildcard = __webpack_require__(/*! @babel/runtime/helpers/interopRequireWildcard */ "284h");
var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "TqRt");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _objectSpread2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/objectSpread2 */ "3tO9"));
var React = _interopRequireWildcard(__webpack_require__(/*! react */ "q1tI"));
var _PaperClipOutlined = _interopRequireDefault(__webpack_require__(/*! @ant-design/icons-svg/lib/asn/PaperClipOutlined */ "HBhm"));
var _AntdIcon = _interopRequireDefault(__webpack_require__(/*! ../components/AntdIcon */ "KQxl"));
// GENERATE BY ./scripts/generate.ts
// DON NOT EDIT IT MANUALLY
var PaperClipOutlined = function PaperClipOutlined(props, ref) {
return /*#__PURE__*/React.createElement(_AntdIcon.default, (0, _objectSpread2.default)((0, _objectSpread2.default)({}, props), {}, {
ref: ref,
icon: _PaperClipOutlined.default
}));
};
PaperClipOutlined.displayName = 'PaperClipOutlined';
var _default = /*#__PURE__*/React.forwardRef(PaperClipOutlined);
exports.default = _default;
/***/ }),
/***/ "y8nQ":
/*!**************************************************!*\
!*** ./node_modules/antd/es/form/style/index.js ***!
\**************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _style_index_less__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../style/index.less */ "cIOH");
/* harmony import */ var _style_index_less__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_style_index_less__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _index_less__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./index.less */ "gwTy");
/* harmony import */ var _index_less__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_index_less__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _grid_style__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../grid/style */ "1GLa");
// style dependencies
/***/ }),
/***/ "yslc":
/*!*********************************************!*\
!*** ./src/assets/images/icons/groups3.png ***!
\*********************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports) {
module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAALoAAABSCAYAAADjGc4eAAAOHklEQVR4Xu1dCXQURRr+emZyTO6D3BCEgKCInCKeK3IoiyIqlxLyQBRBV8DNhCCrS3Z9Cq66KOoi68ECKocCcutTLhUERM1MEpBLEuQmQMKEnDNd+6onEzKTuXqmJ5l0V/EeL+mp+qu+r77UVP1V9TcHffZbIJgOlhgDMmaAA8lTwVDxJQh5UMY4GTSFM8AJ+PW6cIDsBEEfhfPB4MuUAYvQaTowOwV1NXtB0E6mWBksBTNwTeiUBENud/CmHwBEKZgTBl2GDNgKnQIsyBkCM9kEEI0M8TJICmWgqdCFkT17MngsUignDLYMGXAsdAo0XzcPILkyxMwgKZAB50InhIMhZxUIGalAXhhkmTHgXOgU6PG8UFwxbgdBf5nhZnAUxoBroVMyjryQgMraPSDoqDBuGFwZMeBe6MLi9IWuIHW7QUisjLAzKApiwDOhC25H3T3g8TUICVYQPwyqTBjwXOgUsD4nC4RfIhPsDIaCGBAndEHsujwQMkdBHDGoMmBAvNAtPvZlAMmUAX4GQSEMeCf0wrxgmCu+ASF3K4QnBrOVM+Cd0Cnoorw4mIw/guD6Vs4Ba74CGPBe6IInJicDZn4PgDYK4IpBbMUM+CZ0Qey5t4M3bwUhoa2YB4dNT1CHIzkoEkZzDYrrLtvkCeU0aBsULTw7WntRbtARoQrGbWHtBVw/Vpaggq9t1Rh9F7qwOM0ZA45fDgJp7PmJ0i4hCegU3AabjAc9qmF24r14JeXP+MZ4GEN+/69NmVvD0rGn8zThWYghF7XE7JFN+0wL0x5BQfVZLL60D1XE5JUNfxTqEZqC/C7Zgumeh96EvvqMP6ppNpvSCTM/ZxbAz222lousqGtIAnZkPIMETThmndmM1y/scGvB30KfFNcPH7YbLbRjwokVWHJ5v/CzltMgWq112z5HGXgQnDdVeFW2cSEmdFcU6nUfgpBJPrPsBwPhqmCsSM/EA9E3CtaXXPoJk09+4XIk9qfQrwuKhaFLNiLVodh7tQS3HX0HpB735Lj+WNTOu0Ojl0yViC/6u88MMqG7opDkaWCo2AJCBvnMtB8MqMFhQdoIPNPmDsH6+vIijCxegjrwDmvzl9BV4LAtYwr+FJEBEzHj1iML8EvVqYY2MKFL3/nSTV2sbTuWGw2jaReAbtI3VxqLuQkDMC91mGBsXXkhRhUvFcQeBBViNWENlcxocxdeSBqInRXHMLpkmU3lfbRtsbnjk8KzdgdetvlmKDVdBZ1COEuvJA/F7KSBwsfPnVyLdy9Suq6lOLUWafULXbGITYTHwZrzYos1yc9GdE8oPJDdHnXcHhCS7En2lsgzJ2kw8pLvA094YaG5teIoBoRnYFunqT43J6koz+E8mX6jLGz7KJ6KtxzvpwvQJ/5Y5XN9nhp4NLo7empTPcqepIlsaOcHF/fgnMnoUbmi6nNYUZbvUd7mzCT9iG5tfcHMvjDzOwFybYhsTmQe1PVGygPClOGzsl+F3P4UOl0jrGyfiWFRljXCBjptKlnqtbfGA3hNsixLfwyZsf4N3bO6zCDgCrTkP6FTpAbdQyBYA0JUgQbcUXvoiEsFaU26hHvwUvJgbK84ihHHF9sU6RvWDlszpgjPEgr/biNYI19jM3FJ0kRgY4dJoGVo+rxMj3ElnzasDai/flBkZ3xeZoDJyXpBCv6sQj9XZ4TBjbswUhWC/uEWP/qeqyWgmFylm0KTkRIUBWUKnTKj180AIfOl6KjmtiHVYnRB6gg8l3Cn0Pz/lO7CtFNfwtzoT2HtdRMwIvom6KtOo8/h+TafSYnZKnT6h2a/5rCvR+wcfUm7sciK66tgoVMG87PfBfCslJ3WHLZeTByEl1Pux8byA3iw+GObKsVsGD0U1Q2fpj8uuDOt0ySrsYmxt+Dj9DHCrxNPrMD/6n3p/sDHhO4PVhvbJKvU0O9bBxCLq6MFUhgX5LBWOlVwtqv5r5RhyEkcgE8v/4LME595LXQ6HUoPimniDWnsS6dz9uHFi4V1gtWb4wtNtL2rywtsTDCh+8Kop2UL8yJgNn4Hgl6eFpEqHz23Yez+qkNzruaUH7QdhSfjbxWmG8+eWuu10B1VTH3p2zOm4O6IDFw0XUW3Q6/jnKkCAyM64dv6ub8v+McUL8Oqcj0Tej0D/l2M2vfUbzNTUcPvBSFtfelEsWW9FfoX7bPwaMzNmHtuK2af3SKp0F9NHir46GkaXbwUn5cbhJ/bqMNwW/h1biF2CI7D22kjhHxTT67GqbpymzI/V57EadMVJvQWETqttDC3B8zm70FIpNvelDAD3YRpnGa0uVvwqFhHdDrnzoztbZNneFQ3pAfHClv0P1X9YfMZ9TOPiukhPFtYuhtmO2/JS2e+Qhlf3QSBBirBl06/KWj61ngYg+0OjHkCu/Fisctv83C4ptRtMTZ1cUuRxBn0ugdByHqJrYoyNytxAOamDGsQ+oTYvlicPlaUDVeZ6W7pSbtRlrrsVrUfj/ujujYU/eTyzxh/YrnoehsLvetvr+FQzQW3NpjQ3VIkcYb8nH8D/PMSWxVlzl7o9Oz1hLhbGmwkayIxPLobCCH4+NK+Ji6/RE2E4BKk6aOLe5t8PuvMJlw2VzXYS9VEYVPHSeipTROemQkPNacCE7qobvM6c/PO0WkzC3SZMBPbgyNeN9/7gvZCt7f0z6T7hKkNPedyz7GFTSoS4168MSQJX3V8Cu2CYwQ7b5zfgdSgKDwe21sSoYudurANI+9141lJQ3YfEO6HQLiN5ErodIe05MYXhYNVT5xYicWXf/JJ6COiumFth4m4aq7BpJOrsLJMD+sGixQjulihe9ZZ3uVS7s6olS+9LhEg+wPl1TGuhP5A1A3Y0GESKvla0ANajq6RiRnRqddnb+dpGFvyiXCbiKaWFPrB6nNYXe/lcSZnsYe6Hoq6Cd21KQrfGSWLgmA4Qu+V3uXdOCF9KWdCp/7tbzOexoCITlh2aT+y/ljhsHIxQqcGgjm1zcZUSwqdHQGQXk8Wi/qchSC85QRUgCRnQl/UdiQmx/cXFqF3HX0PuyqLJRG6vZGWEPro6B7opU2Dofo0lrs5Siv2rMuo6JvRW9sWBdVnmhxzCIQu9/9i1KB7CjyxvVkcAMgdCb3xhYi/nlqP+aXfOW2p2BE9EIQuhnaxQhdjuyXy+lfollAY2wMxAq/14oV18RSvDsPxG2YLdzgXXPge00+vc9kfTOgtIVfv6/Sf0C3b/T8H4i2jJ+P64d20RxCi0qCGN2FMyTKsu1KEx2J6CrudI4uXurwKR+lmQvdedC1R0j9CP7IgBFdL6Pd+v5YA5arO+anDMSPBEjKyzFyFGLVWuE73t7NbMO/8dtAtek8uP3QLScJH9aEq7jz6nkdlGrerJeboYvqCTV08YSs/m17HmeBJ1ubMMy6mFz5pP06ocvaZzZh3fhueib8d76Q9DI7jsPzyr5hz9mscqXV/bsTXdvsqdHo5e//1M4RmeOpHF9NmJnR3bOl100DI2+6yNffnnYPb4Jfrn0eEOgTvl+7G1FNrGppA/wDoOZcgTi08O1pTiiM1F3DWZASNk0JHeHq7nm7b09v99H4//Z+O/nQbX8OpoIZKKB/CqaFVBWFdeRHWXil0CtNTodPIBF1DE1HF16GSr0MVqQM9M5OXPAQT4/oJ4TKSi/6Bi+ZKSSllQndFJ339ixnfBOJbp3dkTBXiqNDNkt6H56PaLvxbL20q5iQNAT2xSEd3X9PQ3z/AV8ZDkgj9SvdXEKpyfHHEemHD1/bal2dCd8YoDXFRCxpTLSAj6/YMTRVu7tAYLs584xRatCoUPbSp6BqSiFi1FtHqUISpgqHmOGHUpiM4PSKg4jjQf87S9FNf4oqLC8WejujU/u5Of2lyRp1e1th85SDevLDTL3ERmdAd9ezpvDCcr9gFkJ5SjyxS2qMiLndwRlzKOjy1Ra/RxWvChdtF9pF67W3QIwR0Z7VxKjdX++0SNa2HXgAZG2O5DLai7FeUSjw18pQnqfL5/h1NW6LXLQch0h3mlgods8MYqGfAd6EbcmaC519jjDIGApkB34Sen3sfOPPm1hKgKJA7grXNvwx4L/SiWZ1gMu1jb5P2bwcx69Iw4J3QaegKk5G+uyhgI+ZKQw+zIhcGxAudEA56Hd1tscRaYIkx0AoYEC90vW4OCMlrBdhYExkDDQyIE7oQHZesDfSXcrH+ZQzYM+C50Atm3gBeiLLVrIGHWJcxBqRgwDOhH8+LQXnFPoB0lqJSZoMx0NwMuBc6yVPBULERhAxt7sax+hgDUjHgXuiG7LngMUuqCpkdxkBLMOBa6AW60TCTlS3RMFYnY0BKBpwLnUa9NZl3B/LLtqQkgtmSNwOOhX7whXjU1NKz5e4DdcubH4ZOJgw0Fbrl7c9fg5B7ZYKRwWAMOLgio89+CwTTGTeMATkxYDui63OyQPglcgLIsDAGKAPXhF6YfQvM3HeBENKZdQ1jQGoGLEIvmJ0EvnZ/c79ES2owzB5jwBkDHGhIZ/2R7QC5g9HEGJArAxzyde8D5Gm5AmS4GAO2c3TGB2OgFTLALR1KA6e5SByvUpEp7s+6tELwrMnKYcCl0DmYVOCyzOM3L2dCV44mZInUhdBrVFCPMmdt3MCmLrLsemWBcih0DlfVBMNNWVu2WdlgI7qydCE7tE2FzpVpVOqhdZkbaJSKhsSELruuVxYgG6FzOK+Bekjd+I16exaY0JWlC9mhbRA6h5PBCBpUM369w1jdTOiy63plAaoX+rEQNTewetzmEmfomdCVpQvZoeWWDi3UctrBlePXnHHpTZcdcgZIUQxErnk43vjI2ovuQP8faDGikjbF4FsAAAAASUVORK5CYII="
/***/ }),
/***/ "zrhs":
/*!******************************************************!*\
!*** ./src/components/AuthenticationModel/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 _Users_xxq_node_forgeplus_react_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./node_modules/@umijs/babel-preset-umi/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties */ "PpiC");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! react */ "q1tI");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var umi__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! umi */ "9kvl");
var AuthModal = function AuthModal(_ref) {
var shixunsDetail = _ref.shixunsDetail,
globalSetting = _ref.globalSetting,
loading = _ref.loading,
dispatch = _ref.dispatch,
props = Object(_Users_xxq_node_forgeplus_react_node_modules_umijs_babel_preset_umi_node_modules_babel_runtime_helpers_esm_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"])(_ref, ["shixunsDetail", "globalSetting", "loading", "dispatch"]);
return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(antd_es_modal__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"], {
centered: true,
keyboard: false,
closable: false,
zIndex: 6666,
title: "\u63D0\u793A",
visible: shixunsDetail.actionTabs.key === 'Banner-Auth',
okText: "\u786E\u5B9A",
cancelText: "\u53D6\u6D88",
onOk: function onOk() {
dispatch({
type: 'shixunsDetail/setActionTabs',
payload: {}
});
window.location.href = '/account/certification';
},
onCancel: function onCancel() {
dispatch({
type: 'shixunsDetail/setActionTabs',
payload: {}
});
}
}, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("p", {
className: "tc font16"
}, "\u5F53\u524D\u7ADE\u8D5B\u9700\u8981\u5B9E\u540D\u8BA4\u8BC1\uFF0C\u8BF7\u5148\u5B8C\u6210\u5B9E\u540D\u8BA4\u8BC1\u540E\u518D\u62A5\u540D\u53C2\u8D5B", /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("br", null), "\u8BF7\u95EE\u662F\u5426\u524D\u5F80\u8FDB\u884C\u8BA4\u8BC1\uFF1F"));
};
/* harmony default export */ __webpack_exports__["a"] = (Object(umi__WEBPACK_IMPORTED_MODULE_4__[/* connect */ "a"])(function (_ref2) {
var shixunsDetail = _ref2.shixunsDetail,
loading = _ref2.loading,
globalSetting = _ref2.globalSetting;
return {
shixunsDetail: shixunsDetail,
globalSetting: globalSetting,
loading: loading.models.index
};
})(AuthModal));
/***/ })
}]);