(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 c(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 // {this.props.num} // {this.props.status} // {this.props.log} // // } //}); // //module.exports = LogBlock; exports["default"] = _default; },{"react":417,"react-dom":413}],3:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = _interopRequireWildcard(require("react")); var _reactDom = _interopRequireDefault(require("react-dom")); var _queryString = _interopRequireDefault(require("query-string")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } function _typeof(obj) { 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 _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 _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _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 _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _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); } var SearchBox = /*#__PURE__*/ function (_Component) { _inherits(SearchBox, _Component); function SearchBox(props) { var _this; _classCallCheck(this, SearchBox); _this = _possibleConstructorReturn(this, _getPrototypeOf(SearchBox).call(this, props)); var searchTitle = !!props.searchTitle ? props.searchTitle : 'Search'; _this.state = { searchTitle: searchTitle, search: '', filtered: false, count: jQuery('.google_tags li:not(.d-none)').length }; return _this; } _createClass(SearchBox, [{ key: "componentDidMount", value: function componentDidMount() { var value = _queryString["default"].parse(window.location.search); if (!!value.search) this.doSearchUpdate(value.search); } }, { key: "componentWillUnmount", value: function componentWillUnmount() {} }, { key: "reset", value: function reset(e) { this.doSearchUpdate(''); } }, { key: "handleChange", value: function handleChange(e) { this.doSearchUpdate(e.target.value); } }, { key: "doSearchUpdate", value: function doSearchUpdate(search) { // If the search bar isn't empty if (search !== "") { jQuery('.google_tags li').each(function (i, item) { var display = !jQuery(item).text().toLowerCase().includes(search.toLowerCase()); jQuery(item).toggleClass('d-none', display); }); this.setState({ filtered: true }); } else { jQuery('.google_tags li').toggleClass('d-none', false); this.setState({ filtered: false }); } // Set the filtered state based on what our rules added to newList this.setState({ search: search, count: jQuery('.google_tags li:not(.d-none)').length }); } }, { key: "render", value: function render() { return _react["default"].createElement("form", null, _react["default"].createElement("div", { className: "form-group row align-items-center" }, _react["default"].createElement("label", { htmlFor: "inputSearchLocal", className: "col-sm-6 col-form-label font-weight-bold text-right" }, this.state.searchTitle, ":"), _react["default"].createElement("div", { className: "col-sm-6" }, _react["default"].createElement("div", { className: "input-group mb-2" }, _react["default"].createElement("div", { className: "input-group-prepend" }, this.state.filtered ? _react["default"].createElement("div", { className: "input-group-text bg-danger text-white py-0", onClick: this.reset.bind(this) }, " x ") : _react["default"].createElement("div", { className: "input-group-text py-0" }, " > ")), _react["default"].createElement("input", { id: "inputSearchLocal", type: "text", className: "form-control", value: this.state.search, onChange: this.handleChange.bind(this), placeholder: "shop ..." }))), this.state.count === 0 && _react["default"].createElement("div", { className: "alert alert-warning col-10 offset-2" }, " no results "))); } }]); return SearchBox; }(_react.Component); var _default = SearchBox; exports["default"] = _default; },{"query-string":408,"react":417,"react-dom":413}],4:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _react = _interopRequireWildcard(require("react")); var _reactDom = _interopRequireDefault(require("react-dom")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } function _typeof(obj) { 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 _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 _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _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 _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _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); } var VersionBlock = /*#__PURE__*/ function (_Component) { _inherits(VersionBlock, _Component); function VersionBlock() { _classCallCheck(this, VersionBlock); return _possibleConstructorReturn(this, _getPrototypeOf(VersionBlock).apply(this, arguments)); } _createClass(VersionBlock, [{ key: "render", value: function render() { var created = this.props.created ? this.props.created.format('YYYY/MM/DD H:mm') : null; var updated = this.props.updated ? this.props.updated.format('YYYY/MM/DD H:mm') : null; return _react["default"].createElement("div", { className: "version" }, created != null && _react["default"].createElement("div", null, "Created:", created), updated != null && _react["default"].createElement("div", null, "Updated:", updated), this.props.lastVersion != null && _react["default"].createElement("div", null, "Version:", this.props.lastVersion.version, this.props.lastVersion.username != null && _react["default"].createElement("span", null, ", by", this.props.lastVersion.username))); } }]); return VersionBlock; }(_react.Component); var _default = VersionBlock; //var React = require('react'); //var createReactClass = require('create-react-class'); // //var VersionBlock = createReactClass({ // render:function(){ // var created = this.props.created? // this.props.created.format('YYYY/MM/DD H:mm') : null; // var updated = this.props.updated? // this.props.updated.format('YYYY/MM/DD H:mm') : null; // // return
// {created != null && //
Created: {created}
// } // {updated != null && //
Updated: {updated}
// } // {this.props.lastVersion != null && //
// Version: {this.props.lastVersion.version} // {this.props.lastVersion.username != null && // , by {this.props.lastVersion.username} // } //
// } //
// } //}); //module.exports = VersionBlock; exports["default"] = _default; },{"react":417,"react-dom":413}],5:[function(require,module,exports){ "use strict"; var _react = _interopRequireWildcard(require("react")); var _reactDom = _interopRequireDefault(require("react-dom")); var _EventSystem = _interopRequireDefault(require("../libs/EventSystem")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } function _typeof(obj) { 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 _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 _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _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); } var ProfileController = /*#__PURE__*/ function (_React$Component) { _inherits(ProfileController, _React$Component); function ProfileController(props) { var _this; _classCallCheck(this, ProfileController); _this = _possibleConstructorReturn(this, _getPrototypeOf(ProfileController).call(this, props)); _this.state = { companies: [], hovered: false }; _this.loadStateData = _this.loadStateData.bind(_assertThisInitialized(_this)); _this.addToList = _this.addToList.bind(_assertThisInitialized(_this)); _this.removeCompany = _this.removeCompany.bind(_assertThisInitialized(_this)); return _this; } _createClass(ProfileController, [{ key: "componentDidMount", value: function componentDidMount() { this.state.subscriber = _EventSystem["default"].subscribe('profile.add.company', this.addToList); this.state.subscriber = _EventSystem["default"].subscribe('profile.remove.company', this.removeCompany); this.loadStateData(); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { _EventSystem["default"].unsubscribe('profile.add.company', this.addToList); _EventSystem["default"].unsubscribe('profile.remove.company', this.removeCompany); } }, { key: "loadStateData", value: function loadStateData() { var _this2 = this; fetch(Routing.generate('front_profile_selected_list', {})).then(function (res) { return res.json(); }).then(function (result) { _this2.setState({ companies: result }); }, function (error) { _EventSystem["default"].publish('error.ajax', error + ' profile_controller'); }); } }, { key: "addToList", value: function addToList() { var _this3 = this; var companyId = arguments[0]; fetch(Routing.generate('front_profile_selected_add', { company: companyId })).then(function (res) { return res.json(); }).then(function (result) { _this3.state.companies[companyId] = result; _this3.setState({ companies: _this3.state.companies }); _EventSystem["default"].publish('profile.status.changed.company.' + companyId, 'added'); }, function (error) { _EventSystem["default"].publish('error.ajax', error + ' profile_controller'); }); } }, { key: "removeCompany", value: function removeCompany() { var _this4 = this; var companyId = arguments[0]; fetch(Routing.generate('front_profile_selected_remove', { company: companyId })).then(function (res) { return res.json(); }).then(function (result) { delete _this4.state.companies[companyId]; _this4.setState({ companies: _this4.state.companies }); _EventSystem["default"].publish('profile.status.changed.company.' + companyId, ''); }, function (error) { _EventSystem["default"].publish('error.ajax', error + ' profile_controller'); }); } }, { key: "render", value: function render() { var _this5 = this; var listItems = Object.keys(this.state.companies).map(function (companyId) { return (// Wrong! The key should have been specified here: _react["default"].createElement("li", { key: companyId }, _this5.state.companies[companyId].name, _react["default"].createElement("span", { onClick: function onClick() { _EventSystem["default"].publish('profile.remove.company', companyId); } }, "x")) ); }); var listClass = "companies list border-0 bg-danger position-absolute " + (this.state.hovered ? '' : 'd-none'); return _react["default"].createElement("a", { href: "/profile/selected", className: "profileContainer", onMouseOver: function onMouseOver() { _this5.setState({ hovered: true }); }, onMouseOut: function onMouseOut() { _this5.setState({ hovered: false }); } }, _react["default"].createElement("div", { className: "companies count" }, Object.keys(this.state.companies).length), _react["default"].createElement("div", { className: listClass }, _react["default"].createElement("ul", null, listItems))); } }]); return ProfileController; }(_react["default"].Component); module.exports = ProfileController; },{"../libs/EventSystem":6,"react":417,"react-dom":413}],6:[function(require,module,exports){ "use strict"; function _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 _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var EventSystem = /*#__PURE__*/ function () { function EventSystem() { _classCallCheck(this, EventSystem); this.queue = {}; this.maxNamespaceSize = 50; } _createClass(EventSystem, [{ key: "publish", value: function publish() /** namespace **/ /** arguments **/ { if (arguments.length < 1) { throw "Invalid namespace to publish"; } var namespace = arguments[0]; var queue = this.queue[namespace]; if (typeof queue === 'undefined' || queue.length < 1) { console.log('did not find queue for %s', namespace); return false; } var valueArgs = Array.prototype.slice.call(arguments); valueArgs.shift(); // remove namespace value from value args queue.forEach(function (callback) { callback.apply(null, valueArgs); }); return true; } }, { key: "subscribe", value: function subscribe() /** namespace **/ /** callback **/ { var namespace = arguments[0]; if (!namespace) throw "Invalid namespace"; var callback = arguments[arguments.length - 1]; if (typeof callback !== 'function') throw "Invalid callback method"; if (typeof this.queue[namespace] === 'undefined') { this.queue[namespace] = []; } var queue = this.queue[namespace]; if (queue.length === this.maxNamespaceSize) { console.warn('Shifting first element in queue: `%s` since it reached max namespace queue count : %d', namespace, this.maxNamespaceSize); queue.shift(); } // Check if this callback already exists for this namespace for (var i = 0; i < queue.length; i++) { if (queue[i] === callback) { throw "The exact same callback exists on this namespace: " + namespace; } } this.queue[namespace].push(callback); return [namespace, callback]; } }, { key: "unsubscribe", value: function unsubscribe() /** array or topic, method **/ { var namespace; var callback; if (arguments.length === 1) { var arg = arguments[0]; if (!arg || !Array.isArray(arg)) throw "Unsubscribe argument must be an array"; namespace = arg[0]; callback = arg[1]; } else if (arguments.length === 2) { namespace = arguments[0]; callback = arguments[1]; } if (!namespace || typeof callback !== 'function') throw "Namespace must exist or callback must be a function"; var queue = this.queue[namespace]; if (queue) { for (var i = 0; i < queue.length; i++) { if (queue[i] === callback) { queue.splice(i, 1); // only unique callbacks can be pushed to same namespace queue return; } } } } }, { key: "setNamespaceSize", value: function setNamespaceSize(size) { if (!this.isNumber(size)) throw "Queue size must be a number"; this.maxNamespaceSize = size; return true; } }, { key: "isNumber", value: function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } }]); return EventSystem; }(); module.exports = new EventSystem(); },{}],7:[function(require,module,exports){ (function (global){ "use strict"; var _search_box = _interopRequireDefault(require("./components/search_box")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var React = require('react'); var ReactDOM = require('react-dom'); var ReactDOMServer = require('react-dom/server'); var babelify = require('babelify'); var VersionBlock = require('./components/version_block'); var LogBlock = require('./components/log_block'); var ProfileController = require('./controllers/profile_controller'); var CompanyCartButton = require('./components/company_cart_button'); global.renderSearchBox = function (htmlDom, searchTitle) { return ReactDOM.render(React.createElement(_search_box["default"], { searchTitle: searchTitle }), htmlDom); }; // we should not render it right away - but place it in render block that will render it in the place global.getCompanyCartButton = function (companyId, status) { return ReactDOMServer.renderToStaticMarkup(React.createElement(CompanyCartButton, { companyId: companyId, status: status })); }; global.renderCompanyCartButton = function (data, htmlDom) { return ReactDOM.render(React.createElement(CompanyCartButton, { companyId: data.companyId, status: data.status }), htmlDom); }; global.getVersionBlock = function (data) { return ReactDOMServer.renderToStaticMarkup(React.createElement(VersionBlock, { created: data.createdAt, updated: data.updatedAt, lastVersion: data.version })); }; global.getLogBlock = function (data) { return ReactDOMServer.renderToStaticMarkup(React.createElement(LogBlock, { status: data.status, log: data.text, num: data.num })); }; global.renderVersionBlock = function (data, objectId) { return ReactDOM.render(React.createElement(VersionBlock, { created: moment(data.createdAt), updated: moment(data.updatedAt), lastVersion: data.version }), document.getElementById(objectId)); }; global.render_grid_version_block = function (data, type, row, meta, colData, colIndex) { var createdAt = row.createdAt && row.createdAt.timestamp ? moment.unix(row.createdAt.timestamp) : null; var updatedAt = row.updatedAt && row.updatedAt.timestamp && row.updatedAt && row.updatedAt.timestamp != row.updatedAt.timestamp ? moment.unix(row.updated.timestamp) : null; updatedAt = updatedAt != createdAt ? updatedAt : null; return getVersionBlock({ createdAt: createdAt, updatedAt: updatedAt, version: row.version }); }; global.render_grid_file_block = function (data, type, row, meta, colData, colIndex) { var url = Routing.generate('api_stream_file_content', { file_id: row.source.id }); var sourceName = ''; //row.source.name; return ReactDOMServer.renderToStaticMarkup(React.createElement("a", { className: "btn btn-info", target: "_blank", href: url }, sourceName)); }; global.render_grid_array_block = function (data, type, row, meta, colData, colIndex) { return JSON.stringify(row.log); }; jQuery('.searchBox').each(function (e, i) { renderSearchBox(i, jQuery('.searchBox').data('search-title')); }); global.babelify = babelify; global.React = React; global.ReactDOM = ReactDOM; global.ReactDOMServer = ReactDOMServer; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./components/company_cart_button":1,"./components/log_block":2,"./components/search_box":3,"./components/version_block":4,"./controllers/profile_controller":5,"babelify":178,"react":417,"react-dom":413,"react-dom/server":414}],8:[function(require,module,exports){ (function (process){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.codeFrameColumns = codeFrameColumns; exports.default = _default; function _highlight() { const data = _interopRequireWildcard(require("@babel/highlight")); _highlight = function () { return data; }; return data; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } let deprecationWarningShown = false; function getDefs(chalk) { return { gutter: chalk.grey, marker: chalk.red.bold, message: chalk.red.bold }; } const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; function getMarkerLines(loc, source, opts) { const startLoc = Object.assign({ column: 0, line: -1 }, loc.start); const endLoc = Object.assign({}, startLoc, loc.end); const { linesAbove = 2, linesBelow = 3 } = opts || {}; const startLine = startLoc.line; const startColumn = startLoc.column; const endLine = endLoc.line; const endColumn = endLoc.column; let start = Math.max(startLine - (linesAbove + 1), 0); let end = Math.min(source.length, endLine + linesBelow); if (startLine === -1) { start = 0; } if (endLine === -1) { end = source.length; } const lineDiff = endLine - startLine; const markerLines = {}; if (lineDiff) { for (let i = 0; i <= lineDiff; i++) { const lineNumber = i + startLine; if (!startColumn) { markerLines[lineNumber] = true; } else if (i === 0) { const sourceLength = source[lineNumber - 1].length; markerLines[lineNumber] = [startColumn, sourceLength - startColumn]; } else if (i === lineDiff) { markerLines[lineNumber] = [0, endColumn]; } else { const sourceLength = source[lineNumber - i].length; markerLines[lineNumber] = [0, sourceLength]; } } } else { if (startColumn === endColumn) { if (startColumn) { markerLines[startLine] = [startColumn, 0]; } else { markerLines[startLine] = true; } } else { markerLines[startLine] = [startColumn, endColumn - startColumn]; } } return { start, end, markerLines }; } function codeFrameColumns(rawLines, loc, opts = {}) { const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight().shouldHighlight)(opts); const chalk = (0, _highlight().getChalk)(opts); const defs = getDefs(chalk); const maybeHighlight = (chalkFn, string) => { return highlighted ? chalkFn(string) : string; }; if (highlighted) rawLines = (0, _highlight().default)(rawLines, opts); const lines = rawLines.split(NEWLINE); const { start, end, markerLines } = getMarkerLines(loc, lines, opts); const hasColumns = loc.start && typeof loc.start.column === "number"; const numberMaxWidth = String(end).length; let frame = lines.slice(start, end).map((line, index) => { const number = start + 1 + index; const paddedNumber = ` ${number}`.slice(-numberMaxWidth); const gutter = ` ${paddedNumber} | `; const hasMarker = markerLines[number]; const lastMarkerLine = !markerLines[number + 1]; if (hasMarker) { let markerLine = ""; if (Array.isArray(hasMarker)) { const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "); const numberOfMarkers = hasMarker[1] || 1; markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join(""); if (lastMarkerLine && opts.message) { markerLine += " " + maybeHighlight(defs.message, opts.message); } } return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join(""); } else { return ` ${maybeHighlight(defs.gutter, gutter)}${line}`; } }).join("\n"); if (opts.message && !hasColumns) { frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`; } if (highlighted) { return chalk.reset(frame); } else { return frame; } } function _default(rawLines, lineNumber, colNumber, opts = {}) { if (!deprecationWarningShown) { deprecationWarningShown = true; const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`."; if (process.emitWarning) { process.emitWarning(message, "DeprecationWarning"); } else { const deprecationError = new Error(message); deprecationError.name = "DeprecationWarning"; console.warn(new Error(message)); } } colNumber = Math.max(colNumber, 0); const location = { start: { column: colNumber, line: lineNumber } }; return codeFrameColumns(rawLines, location, opts); } }).call(this,require('_process')) },{"@babel/highlight":66,"_process":405}],9:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.makeStrongCache = makeStrongCache; exports.makeWeakCache = makeWeakCache; exports.assertSimpleType = assertSimpleType; function makeStrongCache(handler) { return makeCachedFunction(new Map(), handler); } function makeWeakCache(handler) { return makeCachedFunction(new WeakMap(), handler); } function makeCachedFunction(callCache, handler) { return function cachedFunction(arg, data) { let cachedValue = callCache.get(arg); if (cachedValue) { for (const _ref of cachedValue) { const { value, valid } = _ref; if (valid(data)) return value; } } const cache = new CacheConfigurator(data); const value = handler(arg, cache); if (!cache.configured()) cache.forever(); cache.deactivate(); switch (cache.mode()) { case "forever": cachedValue = [{ value, valid: () => true }]; callCache.set(arg, cachedValue); break; case "invalidate": cachedValue = [{ value, valid: cache.validator() }]; callCache.set(arg, cachedValue); break; case "valid": if (cachedValue) { cachedValue.push({ value, valid: cache.validator() }); } else { cachedValue = [{ value, valid: cache.validator() }]; callCache.set(arg, cachedValue); } } return value; }; } class CacheConfigurator { constructor(data) { this._active = true; this._never = false; this._forever = false; this._invalidate = false; this._configured = false; this._pairs = []; this._data = data; } simple() { return makeSimpleConfigurator(this); } mode() { if (this._never) return "never"; if (this._forever) return "forever"; if (this._invalidate) return "invalidate"; return "valid"; } forever() { if (!this._active) { throw new Error("Cannot change caching after evaluation has completed."); } if (this._never) { throw new Error("Caching has already been configured with .never()"); } this._forever = true; this._configured = true; } never() { if (!this._active) { throw new Error("Cannot change caching after evaluation has completed."); } if (this._forever) { throw new Error("Caching has already been configured with .forever()"); } this._never = true; this._configured = true; } using(handler) { if (!this._active) { throw new Error("Cannot change caching after evaluation has completed."); } if (this._never || this._forever) { throw new Error("Caching has already been configured with .never or .forever()"); } this._configured = true; const key = handler(this._data); this._pairs.push([key, handler]); return key; } invalidate(handler) { if (!this._active) { throw new Error("Cannot change caching after evaluation has completed."); } if (this._never || this._forever) { throw new Error("Caching has already been configured with .never or .forever()"); } this._invalidate = true; this._configured = true; const key = handler(this._data); this._pairs.push([key, handler]); return key; } validator() { const pairs = this._pairs; return data => pairs.every(([key, fn]) => key === fn(data)); } deactivate() { this._active = false; } configured() { return this._configured; } } function makeSimpleConfigurator(cache) { function cacheFn(val) { if (typeof val === "boolean") { if (val) cache.forever();else cache.never(); return; } return cache.using(() => assertSimpleType(val())); } cacheFn.forever = () => cache.forever(); cacheFn.never = () => cache.never(); cacheFn.using = cb => cache.using(() => assertSimpleType(cb())); cacheFn.invalidate = cb => cache.invalidate(() => assertSimpleType(cb())); return cacheFn; } function assertSimpleType(value) { if (value != null && typeof value !== "string" && typeof value !== "boolean" && typeof value !== "number") { throw new Error("Cache keys must be either string, boolean, number, null, or undefined."); } return value; } },{}],10:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.buildPresetChain = buildPresetChain; exports.buildRootChain = buildRootChain; exports.buildPresetChainWalker = void 0; function _path() { const data = _interopRequireDefault(require("path")); _path = function () { return data; }; return data; } function _debug() { const data = _interopRequireDefault(require("debug")); _debug = function () { return data; }; return data; } var _options = require("./validation/options"); var _patternToRegex = _interopRequireDefault(require("./pattern-to-regex")); var _files = require("./files"); var _caching = require("./caching"); var _configDescriptors = require("./config-descriptors"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug().default)("babel:config:config-chain"); function buildPresetChain(arg, context) { const chain = buildPresetChainWalker(arg, context); if (!chain) return null; return { plugins: dedupDescriptors(chain.plugins), presets: dedupDescriptors(chain.presets), options: chain.options.map(o => normalizeOptions(o)) }; } const buildPresetChainWalker = makeChainWalker({ init: arg => arg, root: preset => loadPresetDescriptors(preset), env: (preset, envName) => loadPresetEnvDescriptors(preset)(envName), overrides: (preset, index) => loadPresetOverridesDescriptors(preset)(index), overridesEnv: (preset, index, envName) => loadPresetOverridesEnvDescriptors(preset)(index)(envName) }); exports.buildPresetChainWalker = buildPresetChainWalker; const loadPresetDescriptors = (0, _caching.makeWeakCache)(preset => buildRootDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors)); const loadPresetEnvDescriptors = (0, _caching.makeWeakCache)(preset => (0, _caching.makeStrongCache)(envName => buildEnvDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, envName))); const loadPresetOverridesDescriptors = (0, _caching.makeWeakCache)(preset => (0, _caching.makeStrongCache)(index => buildOverrideDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, index))); const loadPresetOverridesEnvDescriptors = (0, _caching.makeWeakCache)(preset => (0, _caching.makeStrongCache)(index => (0, _caching.makeStrongCache)(envName => buildOverrideEnvDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, index, envName)))); function buildRootChain(opts, context) { const programmaticChain = loadProgrammaticChain({ options: opts, dirname: context.cwd }, context); if (!programmaticChain) return null; let configFile; if (typeof opts.configFile === "string") { configFile = (0, _files.loadConfig)(opts.configFile, context.cwd, context.envName, context.caller); } else if (opts.configFile !== false) { configFile = (0, _files.findRootConfig)(context.root, context.envName, context.caller); } let { babelrc, babelrcRoots } = opts; let babelrcRootsDirectory = context.cwd; const configFileChain = emptyChain(); if (configFile) { const validatedFile = validateConfigFile(configFile); const result = loadFileChain(validatedFile, context); if (!result) return null; if (babelrc === undefined) { babelrc = validatedFile.options.babelrc; } if (babelrcRoots === undefined) { babelrcRootsDirectory = validatedFile.dirname; babelrcRoots = validatedFile.options.babelrcRoots; } mergeChain(configFileChain, result); } const pkgData = typeof context.filename === "string" ? (0, _files.findPackageData)(context.filename) : null; let ignoreFile, babelrcFile; const fileChain = emptyChain(); if ((babelrc === true || babelrc === undefined) && pkgData && babelrcLoadEnabled(context, pkgData, babelrcRoots, babelrcRootsDirectory)) { ({ ignore: ignoreFile, config: babelrcFile } = (0, _files.findRelativeConfig)(pkgData, context.envName, context.caller)); if (ignoreFile && shouldIgnore(context, ignoreFile.ignore, null, ignoreFile.dirname)) { return null; } if (babelrcFile) { const result = loadFileChain(validateBabelrcFile(babelrcFile), context); if (!result) return null; mergeChain(fileChain, result); } } const chain = mergeChain(mergeChain(mergeChain(emptyChain(), configFileChain), fileChain), programmaticChain); return { plugins: dedupDescriptors(chain.plugins), presets: dedupDescriptors(chain.presets), options: chain.options.map(o => normalizeOptions(o)), ignore: ignoreFile || undefined, babelrc: babelrcFile || undefined, config: configFile || undefined }; } function babelrcLoadEnabled(context, pkgData, babelrcRoots, babelrcRootsDirectory) { if (typeof babelrcRoots === "boolean") return babelrcRoots; const absoluteRoot = context.root; if (babelrcRoots === undefined) { return pkgData.directories.indexOf(absoluteRoot) !== -1; } let babelrcPatterns = babelrcRoots; if (!Array.isArray(babelrcPatterns)) babelrcPatterns = [babelrcPatterns]; babelrcPatterns = babelrcPatterns.map(pat => { return typeof pat === "string" ? _path().default.resolve(babelrcRootsDirectory, pat) : pat; }); if (babelrcPatterns.length === 1 && babelrcPatterns[0] === absoluteRoot) { return pkgData.directories.indexOf(absoluteRoot) !== -1; } return babelrcPatterns.some(pat => { if (typeof pat === "string") { pat = (0, _patternToRegex.default)(pat, babelrcRootsDirectory); } return pkgData.directories.some(directory => { return matchPattern(pat, babelrcRootsDirectory, directory, context); }); }); } const validateConfigFile = (0, _caching.makeWeakCache)(file => ({ filepath: file.filepath, dirname: file.dirname, options: (0, _options.validate)("configfile", file.options) })); const validateBabelrcFile = (0, _caching.makeWeakCache)(file => ({ filepath: file.filepath, dirname: file.dirname, options: (0, _options.validate)("babelrcfile", file.options) })); const validateExtendFile = (0, _caching.makeWeakCache)(file => ({ filepath: file.filepath, dirname: file.dirname, options: (0, _options.validate)("extendsfile", file.options) })); const loadProgrammaticChain = makeChainWalker({ root: input => buildRootDescriptors(input, "base", _configDescriptors.createCachedDescriptors), env: (input, envName) => buildEnvDescriptors(input, "base", _configDescriptors.createCachedDescriptors, envName), overrides: (input, index) => buildOverrideDescriptors(input, "base", _configDescriptors.createCachedDescriptors, index), overridesEnv: (input, index, envName) => buildOverrideEnvDescriptors(input, "base", _configDescriptors.createCachedDescriptors, index, envName) }); const loadFileChain = makeChainWalker({ root: file => loadFileDescriptors(file), env: (file, envName) => loadFileEnvDescriptors(file)(envName), overrides: (file, index) => loadFileOverridesDescriptors(file)(index), overridesEnv: (file, index, envName) => loadFileOverridesEnvDescriptors(file)(index)(envName) }); const loadFileDescriptors = (0, _caching.makeWeakCache)(file => buildRootDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors)); const loadFileEnvDescriptors = (0, _caching.makeWeakCache)(file => (0, _caching.makeStrongCache)(envName => buildEnvDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors, envName))); const loadFileOverridesDescriptors = (0, _caching.makeWeakCache)(file => (0, _caching.makeStrongCache)(index => buildOverrideDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors, index))); const loadFileOverridesEnvDescriptors = (0, _caching.makeWeakCache)(file => (0, _caching.makeStrongCache)(index => (0, _caching.makeStrongCache)(envName => buildOverrideEnvDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors, index, envName)))); function buildRootDescriptors({ dirname, options }, alias, descriptors) { return descriptors(dirname, options, alias); } function buildEnvDescriptors({ dirname, options }, alias, descriptors, envName) { const opts = options.env && options.env[envName]; return opts ? descriptors(dirname, opts, `${alias}.env["${envName}"]`) : null; } function buildOverrideDescriptors({ dirname, options }, alias, descriptors, index) { const opts = options.overrides && options.overrides[index]; if (!opts) throw new Error("Assertion failure - missing override"); return descriptors(dirname, opts, `${alias}.overrides[${index}]`); } function buildOverrideEnvDescriptors({ dirname, options }, alias, descriptors, index, envName) { const override = options.overrides && options.overrides[index]; if (!override) throw new Error("Assertion failure - missing override"); const opts = override.env && override.env[envName]; return opts ? descriptors(dirname, opts, `${alias}.overrides[${index}].env["${envName}"]`) : null; } function makeChainWalker({ root, env, overrides, overridesEnv }) { return (input, context, files = new Set()) => { const { dirname } = input; const flattenedConfigs = []; const rootOpts = root(input); if (configIsApplicable(rootOpts, dirname, context)) { flattenedConfigs.push(rootOpts); const envOpts = env(input, context.envName); if (envOpts && configIsApplicable(envOpts, dirname, context)) { flattenedConfigs.push(envOpts); } (rootOpts.options.overrides || []).forEach((_, index) => { const overrideOps = overrides(input, index); if (configIsApplicable(overrideOps, dirname, context)) { flattenedConfigs.push(overrideOps); const overrideEnvOpts = overridesEnv(input, index, context.envName); if (overrideEnvOpts && configIsApplicable(overrideEnvOpts, dirname, context)) { flattenedConfigs.push(overrideEnvOpts); } } }); } if (flattenedConfigs.some(({ options: { ignore, only } }) => shouldIgnore(context, ignore, only, dirname))) { return null; } const chain = emptyChain(); for (const op of flattenedConfigs) { if (!mergeExtendsChain(chain, op.options, dirname, context, files)) { return null; } mergeChainOpts(chain, op); } return chain; }; } function mergeExtendsChain(chain, opts, dirname, context, files) { if (opts.extends === undefined) return true; const file = (0, _files.loadConfig)(opts.extends, dirname, context.envName, context.caller); if (files.has(file)) { throw new Error(`Configuration cycle detected loading ${file.filepath}.\n` + `File already loaded following the config chain:\n` + Array.from(files, file => ` - ${file.filepath}`).join("\n")); } files.add(file); const fileChain = loadFileChain(validateExtendFile(file), context, files); files.delete(file); if (!fileChain) return false; mergeChain(chain, fileChain); return true; } function mergeChain(target, source) { target.options.push(...source.options); target.plugins.push(...source.plugins); target.presets.push(...source.presets); return target; } function mergeChainOpts(target, { options, plugins, presets }) { target.options.push(options); target.plugins.push(...plugins()); target.presets.push(...presets()); return target; } function emptyChain() { return { options: [], presets: [], plugins: [] }; } function normalizeOptions(opts) { const options = Object.assign({}, opts); delete options.extends; delete options.env; delete options.overrides; delete options.plugins; delete options.presets; delete options.passPerPreset; delete options.ignore; delete options.only; delete options.test; delete options.include; delete options.exclude; if (options.hasOwnProperty("sourceMap")) { options.sourceMaps = options.sourceMap; delete options.sourceMap; } return options; } function dedupDescriptors(items) { const map = new Map(); const descriptors = []; for (const item of items) { if (typeof item.value === "function") { const fnKey = item.value; let nameMap = map.get(fnKey); if (!nameMap) { nameMap = new Map(); map.set(fnKey, nameMap); } let desc = nameMap.get(item.name); if (!desc) { desc = { value: item }; descriptors.push(desc); if (!item.ownPass) nameMap.set(item.name, desc); } else { desc.value = item; } } else { descriptors.push({ value: item }); } } return descriptors.reduce((acc, desc) => { acc.push(desc.value); return acc; }, []); } function configIsApplicable({ options }, dirname, context) { return (options.test === undefined || configFieldIsApplicable(context, options.test, dirname)) && (options.include === undefined || configFieldIsApplicable(context, options.include, dirname)) && (options.exclude === undefined || !configFieldIsApplicable(context, options.exclude, dirname)); } function configFieldIsApplicable(context, test, dirname) { const patterns = Array.isArray(test) ? test : [test]; return matchesPatterns(context, patterns, dirname); } function shouldIgnore(context, ignore, only, dirname) { if (ignore && matchesPatterns(context, ignore, dirname)) { debug("Ignored %o because it matched one of %O from %o", context.filename, ignore, dirname); return true; } if (only && !matchesPatterns(context, only, dirname)) { debug("Ignored %o because it failed to match one of %O from %o", context.filename, only, dirname); return true; } return false; } function matchesPatterns(context, patterns, dirname) { return patterns.some(pattern => matchPattern(pattern, dirname, context.filename, context)); } function matchPattern(pattern, dirname, pathToTest, context) { if (typeof pattern === "function") { return !!pattern(pathToTest, { dirname, envName: context.envName, caller: context.caller }); } if (typeof pathToTest !== "string") { throw new Error(`Configuration contains string/RegExp pattern, but no filename was passed to Babel`); } if (typeof pattern === "string") { pattern = (0, _patternToRegex.default)(pattern, dirname); } return pattern.test(pathToTest); } },{"./caching":9,"./config-descriptors":11,"./files":12,"./pattern-to-regex":19,"./validation/options":23,"debug":191,"path":403}],11:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createCachedDescriptors = createCachedDescriptors; exports.createUncachedDescriptors = createUncachedDescriptors; exports.createDescriptor = createDescriptor; var _files = require("./files"); var _item = require("./item"); var _caching = require("./caching"); function isEqualDescriptor(a, b) { return a.name === b.name && a.value === b.value && a.options === b.options && a.dirname === b.dirname && a.alias === b.alias && a.ownPass === b.ownPass && (a.file && a.file.request) === (b.file && b.file.request) && (a.file && a.file.resolved) === (b.file && b.file.resolved); } function createCachedDescriptors(dirname, options, alias) { const { plugins, presets, passPerPreset } = options; return { options, plugins: plugins ? () => createCachedPluginDescriptors(plugins, dirname)(alias) : () => [], presets: presets ? () => createCachedPresetDescriptors(presets, dirname)(alias)(!!passPerPreset) : () => [] }; } function createUncachedDescriptors(dirname, options, alias) { let plugins; let presets; return { options, plugins: () => { if (!plugins) { plugins = createPluginDescriptors(options.plugins || [], dirname, alias); } return plugins; }, presets: () => { if (!presets) { presets = createPresetDescriptors(options.presets || [], dirname, alias, !!options.passPerPreset); } return presets; } }; } const PRESET_DESCRIPTOR_CACHE = new WeakMap(); const createCachedPresetDescriptors = (0, _caching.makeWeakCache)((items, cache) => { const dirname = cache.using(dir => dir); return (0, _caching.makeStrongCache)(alias => (0, _caching.makeStrongCache)(passPerPreset => createPresetDescriptors(items, dirname, alias, passPerPreset).map(desc => loadCachedDescriptor(PRESET_DESCRIPTOR_CACHE, desc)))); }); const PLUGIN_DESCRIPTOR_CACHE = new WeakMap(); const createCachedPluginDescriptors = (0, _caching.makeWeakCache)((items, cache) => { const dirname = cache.using(dir => dir); return (0, _caching.makeStrongCache)(alias => createPluginDescriptors(items, dirname, alias).map(desc => loadCachedDescriptor(PLUGIN_DESCRIPTOR_CACHE, desc))); }); const DEFAULT_OPTIONS = {}; function loadCachedDescriptor(cache, desc) { const { value, options = DEFAULT_OPTIONS } = desc; if (options === false) return desc; let cacheByOptions = cache.get(value); if (!cacheByOptions) { cacheByOptions = new WeakMap(); cache.set(value, cacheByOptions); } let possibilities = cacheByOptions.get(options); if (!possibilities) { possibilities = []; cacheByOptions.set(options, possibilities); } if (possibilities.indexOf(desc) === -1) { const matches = possibilities.filter(possibility => isEqualDescriptor(possibility, desc)); if (matches.length > 0) { return matches[0]; } possibilities.push(desc); } return desc; } function createPresetDescriptors(items, dirname, alias, passPerPreset) { return createDescriptors("preset", items, dirname, alias, passPerPreset); } function createPluginDescriptors(items, dirname, alias) { return createDescriptors("plugin", items, dirname, alias); } function createDescriptors(type, items, dirname, alias, ownPass) { const descriptors = items.map((item, index) => createDescriptor(item, dirname, { type, alias: `${alias}$${index}`, ownPass: !!ownPass })); assertNoDuplicates(descriptors); return descriptors; } function createDescriptor(pair, dirname, { type, alias, ownPass }) { const desc = (0, _item.getItemDescriptor)(pair); if (desc) { return desc; } let name; let options; let value = pair; if (Array.isArray(value)) { if (value.length === 3) { [value, options, name] = value; } else { [value, options] = value; } } let file = undefined; let filepath = null; if (typeof value === "string") { if (typeof type !== "string") { throw new Error("To resolve a string-based item, the type of item must be given"); } const resolver = type === "plugin" ? _files.loadPlugin : _files.loadPreset; const request = value; ({ filepath, value } = resolver(value, dirname)); file = { request, resolved: filepath }; } if (!value) { throw new Error(`Unexpected falsy value: ${String(value)}`); } if (typeof value === "object" && value.__esModule) { if (value.default) { value = value.default; } else { throw new Error("Must export a default export when using ES6 modules."); } } if (typeof value !== "object" && typeof value !== "function") { throw new Error(`Unsupported format: ${typeof value}. Expected an object or a function.`); } if (filepath !== null && typeof value === "object" && value) { throw new Error(`Plugin/Preset files are not allowed to export objects, only functions. In ${filepath}`); } return { name, alias: filepath || alias, value, options, dirname, ownPass, file }; } function assertNoDuplicates(items) { const map = new Map(); for (const item of items) { if (typeof item.value !== "function") continue; let nameMap = map.get(item.value); if (!nameMap) { nameMap = new Set(); map.set(item.value, nameMap); } if (nameMap.has(item.name)) { throw new Error([`Duplicate plugin/preset detected.`, `If you'd like to use two separate instances of a plugin,`, `they need separate names, e.g.`, ``, ` plugins: [`, ` ['some-plugin', {}],`, ` ['some-plugin', {}, 'some unique name'],`, ` ]`].join("\n")); } nameMap.add(item.name); } } },{"./caching":9,"./files":12,"./item":17}],12:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.findConfigUpwards = findConfigUpwards; exports.findPackageData = findPackageData; exports.findRelativeConfig = findRelativeConfig; exports.findRootConfig = findRootConfig; exports.loadConfig = loadConfig; exports.resolvePlugin = resolvePlugin; exports.resolvePreset = resolvePreset; exports.loadPlugin = loadPlugin; exports.loadPreset = loadPreset; function findConfigUpwards(rootDir) { return null; } function findPackageData(filepath) { return { filepath, directories: [], pkg: null, isPackage: false }; } function findRelativeConfig(pkgData, envName, caller) { return { pkg: null, config: null, ignore: null }; } function findRootConfig(dirname, envName, caller) { return null; } function loadConfig(name, dirname, envName, caller) { throw new Error(`Cannot load ${name} relative to ${dirname} in a browser`); } function resolvePlugin(name, dirname) { return null; } function resolvePreset(name, dirname) { return null; } function loadPlugin(name, dirname) { throw new Error(`Cannot load plugin ${name} relative to ${dirname} in a browser`); } function loadPreset(name, dirname) { throw new Error(`Cannot load preset ${name} relative to ${dirname} in a browser`); } },{}],13:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = loadFullConfig; var _util = require("./util"); var context = _interopRequireWildcard(require("../index")); var _plugin = _interopRequireDefault(require("./plugin")); var _item = require("./item"); var _configChain = require("./config-chain"); function _traverse() { const data = _interopRequireDefault(require("@babel/traverse")); _traverse = function () { return data; }; return data; } var _caching = require("./caching"); var _options = require("./validation/options"); var _plugins = require("./validation/plugins"); var _configApi = _interopRequireDefault(require("./helpers/config-api")); var _partial = _interopRequireDefault(require("./partial")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function loadFullConfig(inputOpts) { const result = (0, _partial.default)(inputOpts); if (!result) { return null; } const { options, context } = result; const optionDefaults = {}; const passes = [[]]; try { const { plugins, presets } = options; if (!plugins || !presets) { throw new Error("Assertion failure - plugins and presets exist"); } const ignored = function recurseDescriptors(config, pass) { const plugins = config.plugins.reduce((acc, descriptor) => { if (descriptor.options !== false) { acc.push(loadPluginDescriptor(descriptor, context)); } return acc; }, []); const presets = config.presets.reduce((acc, descriptor) => { if (descriptor.options !== false) { acc.push({ preset: loadPresetDescriptor(descriptor, context), pass: descriptor.ownPass ? [] : pass }); } return acc; }, []); if (presets.length > 0) { passes.splice(1, 0, ...presets.map(o => o.pass).filter(p => p !== pass)); for (const _ref of presets) { const { preset, pass } = _ref; if (!preset) return true; const ignored = recurseDescriptors({ plugins: preset.plugins, presets: preset.presets }, pass); if (ignored) return true; preset.options.forEach(opts => { (0, _util.mergeOptions)(optionDefaults, opts); }); } } if (plugins.length > 0) { pass.unshift(...plugins); } }({ plugins: plugins.map(item => { const desc = (0, _item.getItemDescriptor)(item); if (!desc) { throw new Error("Assertion failure - must be config item"); } return desc; }), presets: presets.map(item => { const desc = (0, _item.getItemDescriptor)(item); if (!desc) { throw new Error("Assertion failure - must be config item"); } return desc; }) }, passes[0]); if (ignored) return null; } catch (e) { if (!/^\[BABEL\]/.test(e.message)) { e.message = `[BABEL] ${context.filename || "unknown"}: ${e.message}`; } throw e; } const opts = optionDefaults; (0, _util.mergeOptions)(opts, options); opts.plugins = passes[0]; opts.presets = passes.slice(1).filter(plugins => plugins.length > 0).map(plugins => ({ plugins })); opts.passPerPreset = opts.presets.length > 0; return { options: opts, passes: passes }; } const loadDescriptor = (0, _caching.makeWeakCache)(({ value, options, dirname, alias }, cache) => { if (options === false) throw new Error("Assertion failure"); options = options || {}; let item = value; if (typeof value === "function") { const api = Object.assign({}, context, (0, _configApi.default)(cache)); try { item = value(api, options, dirname); } catch (e) { if (alias) { e.message += ` (While processing: ${JSON.stringify(alias)})`; } throw e; } } if (!item || typeof item !== "object") { throw new Error("Plugin/Preset did not return an object."); } if (typeof item.then === "function") { throw new Error(`You appear to be using an async plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, ` + `you may need to upgrade your @babel/core version.`); } return { value: item, options, dirname, alias }; }); function loadPluginDescriptor(descriptor, context) { if (descriptor.value instanceof _plugin.default) { if (descriptor.options) { throw new Error("Passed options to an existing Plugin instance will not work."); } return descriptor.value; } return instantiatePlugin(loadDescriptor(descriptor, context), context); } const instantiatePlugin = (0, _caching.makeWeakCache)(({ value, options, dirname, alias }, cache) => { const pluginObj = (0, _plugins.validatePluginObject)(value); const plugin = Object.assign({}, pluginObj); if (plugin.visitor) { plugin.visitor = _traverse().default.explode(Object.assign({}, plugin.visitor)); } if (plugin.inherits) { const inheritsDescriptor = { name: undefined, alias: `${alias}$inherits`, value: plugin.inherits, options, dirname }; const inherits = cache.invalidate(data => loadPluginDescriptor(inheritsDescriptor, data)); plugin.pre = chain(inherits.pre, plugin.pre); plugin.post = chain(inherits.post, plugin.post); plugin.manipulateOptions = chain(inherits.manipulateOptions, plugin.manipulateOptions); plugin.visitor = _traverse().default.visitors.merge([inherits.visitor || {}, plugin.visitor || {}]); } return new _plugin.default(plugin, options, alias); }); const loadPresetDescriptor = (descriptor, context) => { return (0, _configChain.buildPresetChain)(instantiatePreset(loadDescriptor(descriptor, context)), context); }; const instantiatePreset = (0, _caching.makeWeakCache)(({ value, dirname, alias }) => { return { options: (0, _options.validate)("preset", value), alias, dirname }; }); function chain(a, b) { const fns = [a, b].filter(Boolean); if (fns.length <= 1) return fns[0]; return function (...args) { for (const fn of fns) { fn.apply(this, args); } }; } },{"../index":26,"./caching":9,"./config-chain":10,"./helpers/config-api":14,"./item":17,"./partial":18,"./plugin":20,"./util":21,"./validation/options":23,"./validation/plugins":24,"@babel/traverse":79}],14:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = makeAPI; function _semver() { const data = _interopRequireDefault(require("semver")); _semver = function () { return data; }; return data; } var _ = require("../../"); var _caching = require("../caching"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function makeAPI(cache) { const env = value => cache.using(data => { if (typeof value === "undefined") return data.envName; if (typeof value === "function") { return (0, _caching.assertSimpleType)(value(data.envName)); } if (!Array.isArray(value)) value = [value]; return value.some(entry => { if (typeof entry !== "string") { throw new Error("Unexpected non-string value"); } return entry === data.envName; }); }); const caller = cb => cache.using(data => (0, _caching.assertSimpleType)(cb(data.caller))); return { version: _.version, cache: cache.simple(), env, async: () => false, caller, assertVersion, tokTypes: undefined }; } function assertVersion(range) { if (typeof range === "number") { if (!Number.isInteger(range)) { throw new Error("Expected string or integer value."); } range = `^${range}.0.0-0`; } if (typeof range !== "string") { throw new Error("Expected string or integer value."); } if (_semver().default.satisfies(_.version, range)) return; const limit = Error.stackTraceLimit; if (typeof limit === "number" && limit < 25) { Error.stackTraceLimit = 25; } const err = new Error(`Requires Babel "${range}", but was loaded with "${_.version}". ` + `If you are sure you have a compatible version of @babel/core, ` + `it is likely that something in your build process is loading the ` + `wrong version. Inspect the stack trace of this error to look for ` + `the first entry that doesn't mention "@babel/core" or "babel-core" ` + `to see what is calling Babel.`); if (typeof limit === "number") { Error.stackTraceLimit = limit; } throw Object.assign(err, { code: "BABEL_VERSION_UNSUPPORTED", version: _.version, range }); } },{"../../":26,"../caching":9,"semver":438}],15:[function(require,module,exports){ (function (process){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getEnv = getEnv; function getEnv(defaultValue = "development") { return process.env.BABEL_ENV || process.env.NODE_ENV || defaultValue; } }).call(this,require('_process')) },{"_process":405}],16:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.loadOptions = loadOptions; Object.defineProperty(exports, "default", { enumerable: true, get: function () { return _full.default; } }); Object.defineProperty(exports, "loadPartialConfig", { enumerable: true, get: function () { return _partial.loadPartialConfig; } }); var _full = _interopRequireDefault(require("./full")); var _partial = require("./partial"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function loadOptions(opts) { const config = (0, _full.default)(opts); return config ? config.options : null; } },{"./full":13,"./partial":18}],17:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createItemFromDescriptor = createItemFromDescriptor; exports.createConfigItem = createConfigItem; exports.getItemDescriptor = getItemDescriptor; function _path() { const data = _interopRequireDefault(require("path")); _path = function () { return data; }; return data; } var _configDescriptors = require("./config-descriptors"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function createItemFromDescriptor(desc) { return new ConfigItem(desc); } function createConfigItem(value, { dirname = ".", type } = {}) { const descriptor = (0, _configDescriptors.createDescriptor)(value, _path().default.resolve(dirname), { type, alias: "programmatic item" }); return createItemFromDescriptor(descriptor); } function getItemDescriptor(item) { if (item instanceof ConfigItem) { return item._descriptor; } return undefined; } class ConfigItem { constructor(descriptor) { this._descriptor = descriptor; Object.defineProperty(this, "_descriptor", { enumerable: false }); this.value = this._descriptor.value; this.options = this._descriptor.options; this.dirname = this._descriptor.dirname; this.name = this._descriptor.name; this.file = this._descriptor.file ? { request: this._descriptor.file.request, resolved: this._descriptor.file.resolved } : undefined; Object.freeze(this); } } Object.freeze(ConfigItem.prototype); },{"./config-descriptors":11,"path":403}],18:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = loadPrivatePartialConfig; exports.loadPartialConfig = loadPartialConfig; function _path() { const data = _interopRequireDefault(require("path")); _path = function () { return data; }; return data; } var _plugin = _interopRequireDefault(require("./plugin")); var _util = require("./util"); var _item = require("./item"); var _configChain = require("./config-chain"); var _environment = require("./helpers/environment"); var _options = require("./validation/options"); var _files = require("./files"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function resolveRootMode(rootDir, rootMode) { switch (rootMode) { case "root": return rootDir; case "upward-optional": { const upwardRootDir = (0, _files.findConfigUpwards)(rootDir); return upwardRootDir === null ? rootDir : upwardRootDir; } case "upward": { const upwardRootDir = (0, _files.findConfigUpwards)(rootDir); if (upwardRootDir !== null) return upwardRootDir; throw Object.assign(new Error(`Babel was run with rootMode:"upward" but a root could not ` + `be found when searching upward from "${rootDir}"`), { code: "BABEL_ROOT_NOT_FOUND", dirname: rootDir }); } default: throw new Error(`Assertion failure - unknown rootMode value`); } } function loadPrivatePartialConfig(inputOpts) { if (inputOpts != null && (typeof inputOpts !== "object" || Array.isArray(inputOpts))) { throw new Error("Babel options must be an object, null, or undefined"); } const args = inputOpts ? (0, _options.validate)("arguments", inputOpts) : {}; const { envName = (0, _environment.getEnv)(), cwd = ".", root: rootDir = ".", rootMode = "root", caller } = args; const absoluteCwd = _path().default.resolve(cwd); const absoluteRootDir = resolveRootMode(_path().default.resolve(absoluteCwd, rootDir), rootMode); const context = { filename: typeof args.filename === "string" ? _path().default.resolve(cwd, args.filename) : undefined, cwd: absoluteCwd, root: absoluteRootDir, envName, caller }; const configChain = (0, _configChain.buildRootChain)(args, context); if (!configChain) return null; const options = {}; configChain.options.forEach(opts => { (0, _util.mergeOptions)(options, opts); }); options.babelrc = false; options.configFile = false; options.passPerPreset = false; options.envName = context.envName; options.cwd = context.cwd; options.root = context.root; options.filename = typeof context.filename === "string" ? context.filename : undefined; options.plugins = configChain.plugins.map(descriptor => (0, _item.createItemFromDescriptor)(descriptor)); options.presets = configChain.presets.map(descriptor => (0, _item.createItemFromDescriptor)(descriptor)); return { options, context, ignore: configChain.ignore, babelrc: configChain.babelrc, config: configChain.config }; } function loadPartialConfig(inputOpts) { const result = loadPrivatePartialConfig(inputOpts); if (!result) return null; const { options, babelrc, ignore, config } = result; (options.plugins || []).forEach(item => { if (item.value instanceof _plugin.default) { throw new Error("Passing cached plugin instances is not supported in " + "babel.loadPartialConfig()"); } }); return new PartialConfig(options, babelrc ? babelrc.filepath : undefined, ignore ? ignore.filepath : undefined, config ? config.filepath : undefined); } class PartialConfig { constructor(options, babelrc, ignore, config) { this.options = options; this.babelignore = ignore; this.babelrc = babelrc; this.config = config; Object.freeze(this); } hasFilesystemConfig() { return this.babelrc !== undefined || this.config !== undefined; } } Object.freeze(PartialConfig.prototype); },{"./config-chain":10,"./files":12,"./helpers/environment":15,"./item":17,"./plugin":20,"./util":21,"./validation/options":23,"path":403}],19:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = pathToPattern; function _path() { const data = _interopRequireDefault(require("path")); _path = function () { return data; }; return data; } function _escapeRegExp() { const data = _interopRequireDefault(require("lodash/escapeRegExp")); _escapeRegExp = function () { return data; }; return data; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const sep = `\\${_path().default.sep}`; const endSep = `(?:${sep}|$)`; const substitution = `[^${sep}]+`; const starPat = `(?:${substitution}${sep})`; const starPatLast = `(?:${substitution}${endSep})`; const starStarPat = `${starPat}*?`; const starStarPatLast = `${starPat}*?${starPatLast}?`; function pathToPattern(pattern, dirname) { const parts = _path().default.resolve(dirname, pattern).split(_path().default.sep); return new RegExp(["^", ...parts.map((part, i) => { const last = i === parts.length - 1; if (part === "**") return last ? starStarPatLast : starStarPat; if (part === "*") return last ? starPatLast : starPat; if (part.indexOf("*.") === 0) { return substitution + (0, _escapeRegExp().default)(part.slice(1)) + (last ? endSep : sep); } return (0, _escapeRegExp().default)(part) + (last ? endSep : sep); })].join("")); } },{"lodash/escapeRegExp":365,"path":403}],20:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; class Plugin { constructor(plugin, options, key) { this.key = plugin.name || key; this.manipulateOptions = plugin.manipulateOptions; this.post = plugin.post; this.pre = plugin.pre; this.visitor = plugin.visitor || {}; this.parserOverride = plugin.parserOverride; this.generatorOverride = plugin.generatorOverride; this.options = options; } } exports.default = Plugin; },{}],21:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.mergeOptions = mergeOptions; function mergeOptions(target, source) { for (const k of Object.keys(source)) { if (k === "parserOpts" && source.parserOpts) { const parserOpts = source.parserOpts; const targetObj = target.parserOpts = target.parserOpts || {}; mergeDefaultFields(targetObj, parserOpts); } else if (k === "generatorOpts" && source.generatorOpts) { const generatorOpts = source.generatorOpts; const targetObj = target.generatorOpts = target.generatorOpts || {}; mergeDefaultFields(targetObj, generatorOpts); } else { const val = source[k]; if (val !== undefined) target[k] = val; } } } function mergeDefaultFields(target, source) { for (const k of Object.keys(source)) { const val = source[k]; if (val !== undefined) target[k] = val; } } },{}],22:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.msg = msg; exports.access = access; exports.assertRootMode = assertRootMode; exports.assertSourceMaps = assertSourceMaps; exports.assertCompact = assertCompact; exports.assertSourceType = assertSourceType; exports.assertCallerMetadata = assertCallerMetadata; exports.assertInputSourceMap = assertInputSourceMap; exports.assertString = assertString; exports.assertFunction = assertFunction; exports.assertBoolean = assertBoolean; exports.assertObject = assertObject; exports.assertArray = assertArray; exports.assertIgnoreList = assertIgnoreList; exports.assertConfigApplicableTest = assertConfigApplicableTest; exports.assertConfigFileSearch = assertConfigFileSearch; exports.assertBabelrcSearch = assertBabelrcSearch; exports.assertPluginList = assertPluginList; function msg(loc) { switch (loc.type) { case "root": return ``; case "env": return `${msg(loc.parent)}.env["${loc.name}"]`; case "overrides": return `${msg(loc.parent)}.overrides[${loc.index}]`; case "option": return `${msg(loc.parent)}.${loc.name}`; case "access": return `${msg(loc.parent)}[${JSON.stringify(loc.name)}]`; default: throw new Error(`Assertion failure: Unknown type ${loc.type}`); } } function access(loc, name) { return { type: "access", name, parent: loc }; } function assertRootMode(loc, value) { if (value !== undefined && value !== "root" && value !== "upward" && value !== "upward-optional") { throw new Error(`${msg(loc)} must be a "root", "upward", "upward-optional" or undefined`); } return value; } function assertSourceMaps(loc, value) { if (value !== undefined && typeof value !== "boolean" && value !== "inline" && value !== "both") { throw new Error(`${msg(loc)} must be a boolean, "inline", "both", or undefined`); } return value; } function assertCompact(loc, value) { if (value !== undefined && typeof value !== "boolean" && value !== "auto") { throw new Error(`${msg(loc)} must be a boolean, "auto", or undefined`); } return value; } function assertSourceType(loc, value) { if (value !== undefined && value !== "module" && value !== "script" && value !== "unambiguous") { throw new Error(`${msg(loc)} must be "module", "script", "unambiguous", or undefined`); } return value; } function assertCallerMetadata(loc, value) { const obj = assertObject(loc, value); if (obj) { if (typeof obj["name"] !== "string") { throw new Error(`${msg(loc)} set but does not contain "name" property string`); } for (const prop of Object.keys(obj)) { const propLoc = access(loc, prop); const value = obj[prop]; if (value != null && typeof value !== "boolean" && typeof value !== "string" && typeof value !== "number") { throw new Error(`${msg(propLoc)} must be null, undefined, a boolean, a string, or a number.`); } } } return value; } function assertInputSourceMap(loc, value) { if (value !== undefined && typeof value !== "boolean" && (typeof value !== "object" || !value)) { throw new Error(`${msg(loc)} must be a boolean, object, or undefined`); } return value; } function assertString(loc, value) { if (value !== undefined && typeof value !== "string") { throw new Error(`${msg(loc)} must be a string, or undefined`); } return value; } function assertFunction(loc, value) { if (value !== undefined && typeof value !== "function") { throw new Error(`${msg(loc)} must be a function, or undefined`); } return value; } function assertBoolean(loc, value) { if (value !== undefined && typeof value !== "boolean") { throw new Error(`${msg(loc)} must be a boolean, or undefined`); } return value; } function assertObject(loc, value) { if (value !== undefined && (typeof value !== "object" || Array.isArray(value) || !value)) { throw new Error(`${msg(loc)} must be an object, or undefined`); } return value; } function assertArray(loc, value) { if (value != null && !Array.isArray(value)) { throw new Error(`${msg(loc)} must be an array, or undefined`); } return value; } function assertIgnoreList(loc, value) { const arr = assertArray(loc, value); if (arr) { arr.forEach((item, i) => assertIgnoreItem(access(loc, i), item)); } return arr; } function assertIgnoreItem(loc, value) { if (typeof value !== "string" && typeof value !== "function" && !(value instanceof RegExp)) { throw new Error(`${msg(loc)} must be an array of string/Funtion/RegExp values, or undefined`); } return value; } function assertConfigApplicableTest(loc, value) { if (value === undefined) return value; if (Array.isArray(value)) { value.forEach((item, i) => { if (!checkValidTest(item)) { throw new Error(`${msg(access(loc, i))} must be a string/Function/RegExp.`); } }); } else if (!checkValidTest(value)) { throw new Error(`${msg(loc)} must be a string/Function/RegExp, or an array of those`); } return value; } function checkValidTest(value) { return typeof value === "string" || typeof value === "function" || value instanceof RegExp; } function assertConfigFileSearch(loc, value) { if (value !== undefined && typeof value !== "boolean" && typeof value !== "string") { throw new Error(`${msg(loc)} must be a undefined, a boolean, a string, ` + `got ${JSON.stringify(value)}`); } return value; } function assertBabelrcSearch(loc, value) { if (value === undefined || typeof value === "boolean") return value; if (Array.isArray(value)) { value.forEach((item, i) => { if (!checkValidTest(item)) { throw new Error(`${msg(access(loc, i))} must be a string/Function/RegExp.`); } }); } else if (!checkValidTest(value)) { throw new Error(`${msg(loc)} must be a undefined, a boolean, a string/Function/RegExp ` + `or an array of those, got ${JSON.stringify(value)}`); } return value; } function assertPluginList(loc, value) { const arr = assertArray(loc, value); if (arr) { arr.forEach((item, i) => assertPluginItem(access(loc, i), item)); } return arr; } function assertPluginItem(loc, value) { if (Array.isArray(value)) { if (value.length === 0) { throw new Error(`${msg(loc)} must include an object`); } if (value.length > 3) { throw new Error(`${msg(loc)} may only be a two-tuple or three-tuple`); } assertPluginTarget(access(loc, 0), value[0]); if (value.length > 1) { const opts = value[1]; if (opts !== undefined && opts !== false && (typeof opts !== "object" || Array.isArray(opts) || opts === null)) { throw new Error(`${msg(access(loc, 1))} must be an object, false, or undefined`); } } if (value.length === 3) { const name = value[2]; if (name !== undefined && typeof name !== "string") { throw new Error(`${msg(access(loc, 2))} must be a string, or undefined`); } } } else { assertPluginTarget(loc, value); } return value; } function assertPluginTarget(loc, value) { if ((typeof value !== "object" || !value) && typeof value !== "string" && typeof value !== "function") { throw new Error(`${msg(loc)} must be a string, object, function`); } return value; } },{}],23:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validate = validate; var _plugin = _interopRequireDefault(require("../plugin")); var _removed = _interopRequireDefault(require("./removed")); var _optionAssertions = require("./option-assertions"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const ROOT_VALIDATORS = { cwd: _optionAssertions.assertString, root: _optionAssertions.assertString, rootMode: _optionAssertions.assertRootMode, configFile: _optionAssertions.assertConfigFileSearch, caller: _optionAssertions.assertCallerMetadata, filename: _optionAssertions.assertString, filenameRelative: _optionAssertions.assertString, code: _optionAssertions.assertBoolean, ast: _optionAssertions.assertBoolean, envName: _optionAssertions.assertString }; const BABELRC_VALIDATORS = { babelrc: _optionAssertions.assertBoolean, babelrcRoots: _optionAssertions.assertBabelrcSearch }; const NONPRESET_VALIDATORS = { extends: _optionAssertions.assertString, ignore: _optionAssertions.assertIgnoreList, only: _optionAssertions.assertIgnoreList }; const COMMON_VALIDATORS = { inputSourceMap: _optionAssertions.assertInputSourceMap, presets: _optionAssertions.assertPluginList, plugins: _optionAssertions.assertPluginList, passPerPreset: _optionAssertions.assertBoolean, env: assertEnvSet, overrides: assertOverridesList, test: _optionAssertions.assertConfigApplicableTest, include: _optionAssertions.assertConfigApplicableTest, exclude: _optionAssertions.assertConfigApplicableTest, retainLines: _optionAssertions.assertBoolean, comments: _optionAssertions.assertBoolean, shouldPrintComment: _optionAssertions.assertFunction, compact: _optionAssertions.assertCompact, minified: _optionAssertions.assertBoolean, auxiliaryCommentBefore: _optionAssertions.assertString, auxiliaryCommentAfter: _optionAssertions.assertString, sourceType: _optionAssertions.assertSourceType, wrapPluginVisitorMethod: _optionAssertions.assertFunction, highlightCode: _optionAssertions.assertBoolean, sourceMaps: _optionAssertions.assertSourceMaps, sourceMap: _optionAssertions.assertSourceMaps, sourceFileName: _optionAssertions.assertString, sourceRoot: _optionAssertions.assertString, getModuleId: _optionAssertions.assertFunction, moduleRoot: _optionAssertions.assertString, moduleIds: _optionAssertions.assertBoolean, moduleId: _optionAssertions.assertString, parserOpts: _optionAssertions.assertObject, generatorOpts: _optionAssertions.assertObject }; function getSource(loc) { return loc.type === "root" ? loc.source : getSource(loc.parent); } function validate(type, opts) { return validateNested({ type: "root", source: type }, opts); } function validateNested(loc, opts) { const type = getSource(loc); assertNoDuplicateSourcemap(opts); Object.keys(opts).forEach(key => { const optLoc = { type: "option", name: key, parent: loc }; if (type === "preset" && NONPRESET_VALIDATORS[key]) { throw new Error(`${(0, _optionAssertions.msg)(optLoc)} is not allowed in preset options`); } if (type !== "arguments" && ROOT_VALIDATORS[key]) { throw new Error(`${(0, _optionAssertions.msg)(optLoc)} is only allowed in root programmatic options`); } if (type !== "arguments" && type !== "configfile" && BABELRC_VALIDATORS[key]) { if (type === "babelrcfile" || type === "extendsfile") { throw new Error(`${(0, _optionAssertions.msg)(optLoc)} is not allowed in .babelrc or "extends"ed files, only in root programmatic options, ` + `or babel.config.js/config file options`); } throw new Error(`${(0, _optionAssertions.msg)(optLoc)} is only allowed in root programmatic options, or babel.config.js/config file options`); } const validator = COMMON_VALIDATORS[key] || NONPRESET_VALIDATORS[key] || BABELRC_VALIDATORS[key] || ROOT_VALIDATORS[key] || throwUnknownError; validator(optLoc, opts[key]); }); return opts; } function throwUnknownError(loc) { const key = loc.name; if (_removed.default[key]) { const { message, version = 5 } = _removed.default[key]; throw new ReferenceError(`Using removed Babel ${version} option: ${(0, _optionAssertions.msg)(loc)} - ${message}`); } else { const unknownOptErr = `Unknown option: ${(0, _optionAssertions.msg)(loc)}. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.`; throw new ReferenceError(unknownOptErr); } } function has(obj, key) { return Object.prototype.hasOwnProperty.call(obj, key); } function assertNoDuplicateSourcemap(opts) { if (has(opts, "sourceMap") && has(opts, "sourceMaps")) { throw new Error(".sourceMap is an alias for .sourceMaps, cannot use both"); } } function assertEnvSet(loc, value) { if (loc.parent.type === "env") { throw new Error(`${(0, _optionAssertions.msg)(loc)} is not allowed inside of another .env block`); } const parent = loc.parent; const obj = (0, _optionAssertions.assertObject)(loc, value); if (obj) { for (const envName of Object.keys(obj)) { const env = (0, _optionAssertions.assertObject)((0, _optionAssertions.access)(loc, envName), obj[envName]); if (!env) continue; const envLoc = { type: "env", name: envName, parent }; validateNested(envLoc, env); } } return obj; } function assertOverridesList(loc, value) { if (loc.parent.type === "env") { throw new Error(`${(0, _optionAssertions.msg)(loc)} is not allowed inside an .env block`); } if (loc.parent.type === "overrides") { throw new Error(`${(0, _optionAssertions.msg)(loc)} is not allowed inside an .overrides block`); } const parent = loc.parent; const arr = (0, _optionAssertions.assertArray)(loc, value); if (arr) { for (const [index, item] of arr.entries()) { const objLoc = (0, _optionAssertions.access)(loc, index); const env = (0, _optionAssertions.assertObject)(objLoc, item); if (!env) throw new Error(`${(0, _optionAssertions.msg)(objLoc)} must be an object`); const overridesLoc = { type: "overrides", index, parent }; validateNested(overridesLoc, env); } } return arr; } },{"../plugin":20,"./option-assertions":22,"./removed":25}],24:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validatePluginObject = validatePluginObject; var _optionAssertions = require("./option-assertions"); const VALIDATORS = { name: _optionAssertions.assertString, manipulateOptions: _optionAssertions.assertFunction, pre: _optionAssertions.assertFunction, post: _optionAssertions.assertFunction, inherits: _optionAssertions.assertFunction, visitor: assertVisitorMap, parserOverride: _optionAssertions.assertFunction, generatorOverride: _optionAssertions.assertFunction }; function assertVisitorMap(key, value) { const obj = (0, _optionAssertions.assertObject)(key, value); if (obj) { Object.keys(obj).forEach(prop => assertVisitorHandler(prop, obj[prop])); if (obj.enter || obj.exit) { throw new Error(`.${key} cannot contain catch-all "enter" or "exit" handlers. Please target individual nodes.`); } } return obj; } function assertVisitorHandler(key, value) { if (value && typeof value === "object") { Object.keys(value).forEach(handler => { if (handler !== "enter" && handler !== "exit") { throw new Error(`.visitor["${key}"] may only have .enter and/or .exit handlers.`); } }); } else if (typeof value !== "function") { throw new Error(`.visitor["${key}"] must be a function`); } return value; } function validatePluginObject(obj) { Object.keys(obj).forEach(key => { const validator = VALIDATORS[key]; if (validator) validator(key, obj[key]);else throw new Error(`.${key} is not a valid Plugin property`); }); return obj; } },{"./option-assertions":22}],25:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _default = { auxiliaryComment: { message: "Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`" }, blacklist: { message: "Put the specific transforms you want in the `plugins` option" }, breakConfig: { message: "This is not a necessary option in Babel 6" }, experimental: { message: "Put the specific transforms you want in the `plugins` option" }, externalHelpers: { message: "Use the `external-helpers` plugin instead. " + "Check out http://babeljs.io/docs/plugins/external-helpers/" }, extra: { message: "" }, jsxPragma: { message: "use the `pragma` option in the `react-jsx` plugin. " + "Check out http://babeljs.io/docs/plugins/transform-react-jsx/" }, loose: { message: "Specify the `loose` option for the relevant plugin you are using " + "or use a preset that sets the option." }, metadataUsedHelpers: { message: "Not required anymore as this is enabled by default" }, modules: { message: "Use the corresponding module transform plugin in the `plugins` option. " + "Check out http://babeljs.io/docs/plugins/#modules" }, nonStandard: { message: "Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. " + "Also check out the react preset http://babeljs.io/docs/plugins/preset-react/" }, optional: { message: "Put the specific transforms you want in the `plugins` option" }, sourceMapName: { message: "The `sourceMapName` option has been removed because it makes more sense for the " + "tooling that calls Babel to assign `map.file` themselves." }, stage: { message: "Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets" }, whitelist: { message: "Put the specific transforms you want in the `plugins` option" }, resolveModuleSource: { version: 6, message: "Use `babel-plugin-module-resolver@3`'s 'resolvePath' options" }, metadata: { version: 6, message: "Generated plugin metadata is always included in the output result" }, sourceMapTarget: { version: 6, message: "The `sourceMapTarget` option has been removed because it makes more sense for the tooling " + "that calls Babel to assign `map.file` themselves." } }; exports.default = _default; },{}],26:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Plugin = Plugin; Object.defineProperty(exports, "File", { enumerable: true, get: function () { return _file.default; } }); Object.defineProperty(exports, "buildExternalHelpers", { enumerable: true, get: function () { return _buildExternalHelpers.default; } }); Object.defineProperty(exports, "resolvePlugin", { enumerable: true, get: function () { return _files.resolvePlugin; } }); Object.defineProperty(exports, "resolvePreset", { enumerable: true, get: function () { return _files.resolvePreset; } }); Object.defineProperty(exports, "version", { enumerable: true, get: function () { return _package.version; } }); Object.defineProperty(exports, "getEnv", { enumerable: true, get: function () { return _environment.getEnv; } }); Object.defineProperty(exports, "tokTypes", { enumerable: true, get: function () { return _parser().tokTypes; } }); Object.defineProperty(exports, "traverse", { enumerable: true, get: function () { return _traverse().default; } }); Object.defineProperty(exports, "template", { enumerable: true, get: function () { return _template().default; } }); Object.defineProperty(exports, "createConfigItem", { enumerable: true, get: function () { return _item.createConfigItem; } }); Object.defineProperty(exports, "loadPartialConfig", { enumerable: true, get: function () { return _config.loadPartialConfig; } }); Object.defineProperty(exports, "loadOptions", { enumerable: true, get: function () { return _config.loadOptions; } }); Object.defineProperty(exports, "transform", { enumerable: true, get: function () { return _transform.transform; } }); Object.defineProperty(exports, "transformSync", { enumerable: true, get: function () { return _transform.transformSync; } }); Object.defineProperty(exports, "transformAsync", { enumerable: true, get: function () { return _transform.transformAsync; } }); Object.defineProperty(exports, "transformFile", { enumerable: true, get: function () { return _transformFile.transformFile; } }); Object.defineProperty(exports, "transformFileSync", { enumerable: true, get: function () { return _transformFile.transformFileSync; } }); Object.defineProperty(exports, "transformFileAsync", { enumerable: true, get: function () { return _transformFile.transformFileAsync; } }); Object.defineProperty(exports, "transformFromAst", { enumerable: true, get: function () { return _transformAst.transformFromAst; } }); Object.defineProperty(exports, "transformFromAstSync", { enumerable: true, get: function () { return _transformAst.transformFromAstSync; } }); Object.defineProperty(exports, "transformFromAstAsync", { enumerable: true, get: function () { return _transformAst.transformFromAstAsync; } }); Object.defineProperty(exports, "parse", { enumerable: true, get: function () { return _parse.parse; } }); Object.defineProperty(exports, "parseSync", { enumerable: true, get: function () { return _parse.parseSync; } }); Object.defineProperty(exports, "parseAsync", { enumerable: true, get: function () { return _parse.parseAsync; } }); exports.types = exports.OptionManager = exports.DEFAULT_EXTENSIONS = void 0; var _file = _interopRequireDefault(require("./transformation/file/file")); var _buildExternalHelpers = _interopRequireDefault(require("./tools/build-external-helpers")); var _files = require("./config/files"); var _package = require("../package.json"); var _environment = require("./config/helpers/environment"); function _types() { const data = _interopRequireWildcard(require("@babel/types")); _types = function () { return data; }; return data; } Object.defineProperty(exports, "types", { enumerable: true, get: function () { return _types(); } }); function _parser() { const data = require("@babel/parser"); _parser = function () { return data; }; return data; } function _traverse() { const data = _interopRequireDefault(require("@babel/traverse")); _traverse = function () { return data; }; return data; } function _template() { const data = _interopRequireDefault(require("@babel/template")); _template = function () { return data; }; return data; } var _item = require("./config/item"); var _config = require("./config"); var _transform = require("./transform"); var _transformFile = require("./transform-file"); var _transformAst = require("./transform-ast"); var _parse = require("./parse"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const DEFAULT_EXTENSIONS = Object.freeze([".js", ".jsx", ".es6", ".es", ".mjs"]); exports.DEFAULT_EXTENSIONS = DEFAULT_EXTENSIONS; class OptionManager { init(opts) { return (0, _config.loadOptions)(opts); } } exports.OptionManager = OptionManager; function Plugin(alias) { throw new Error(`The (${alias}) Babel 5 plugin is being run with an unsupported Babel version.`); } },{"../package.json":41,"./config":16,"./config/files":12,"./config/helpers/environment":15,"./config/item":17,"./parse":27,"./tools/build-external-helpers":28,"./transform":31,"./transform-ast":29,"./transform-file":30,"./transformation/file/file":33,"@babel/parser":67,"@babel/template":70,"@babel/traverse":79,"@babel/types":142}],27:[function(require,module,exports){ (function (process){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseSync = parseSync; exports.parseAsync = parseAsync; exports.parse = void 0; var _config = _interopRequireDefault(require("./config")); var _normalizeFile = _interopRequireDefault(require("./transformation/normalize-file")); var _normalizeOpts = _interopRequireDefault(require("./transformation/normalize-opts")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const parse = function parse(code, opts, callback) { if (typeof opts === "function") { callback = opts; opts = undefined; } if (callback === undefined) return parseSync(code, opts); const config = (0, _config.default)(opts); if (config === null) { return null; } const cb = callback; process.nextTick(() => { let ast = null; try { const cfg = (0, _config.default)(opts); if (cfg === null) return cb(null, null); ast = (0, _normalizeFile.default)(cfg.passes, (0, _normalizeOpts.default)(cfg), code).ast; } catch (err) { return cb(err); } cb(null, ast); }); }; exports.parse = parse; function parseSync(code, opts) { const config = (0, _config.default)(opts); if (config === null) { return null; } return (0, _normalizeFile.default)(config.passes, (0, _normalizeOpts.default)(config), code).ast; } function parseAsync(code, opts) { return new Promise((res, rej) => { parse(code, opts, (err, result) => { if (err == null) res(result);else rej(err); }); }); } }).call(this,require('_process')) },{"./config":16,"./transformation/normalize-file":37,"./transformation/normalize-opts":38,"_process":405}],28:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = _default; function helpers() { const data = _interopRequireWildcard(require("@babel/helpers")); helpers = function () { return data; }; return data; } function _generator() { const data = _interopRequireDefault(require("@babel/generator")); _generator = function () { return data; }; return data; } function _template() { const data = _interopRequireDefault(require("@babel/template")); _template = function () { return data; }; return data; } function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } const buildUmdWrapper = replacements => _template().default` (function (root, factory) { if (typeof define === "function" && define.amd) { define(AMD_ARGUMENTS, factory); } else if (typeof exports === "object") { factory(COMMON_ARGUMENTS); } else { factory(BROWSER_ARGUMENTS); } })(UMD_ROOT, function (FACTORY_PARAMETERS) { FACTORY_BODY }); `(replacements); function buildGlobal(whitelist) { const namespace = t().identifier("babelHelpers"); const body = []; const container = t().functionExpression(null, [t().identifier("global")], t().blockStatement(body)); const tree = t().program([t().expressionStatement(t().callExpression(container, [t().conditionalExpression(t().binaryExpression("===", t().unaryExpression("typeof", t().identifier("global")), t().stringLiteral("undefined")), t().identifier("self"), t().identifier("global"))]))]); body.push(t().variableDeclaration("var", [t().variableDeclarator(namespace, t().assignmentExpression("=", t().memberExpression(t().identifier("global"), namespace), t().objectExpression([])))])); buildHelpers(body, namespace, whitelist); return tree; } function buildModule(whitelist) { const body = []; const refs = buildHelpers(body, null, whitelist); body.unshift(t().exportNamedDeclaration(null, Object.keys(refs).map(name => { return t().exportSpecifier(t().cloneNode(refs[name]), t().identifier(name)); }))); return t().program(body, [], "module"); } function buildUmd(whitelist) { const namespace = t().identifier("babelHelpers"); const body = []; body.push(t().variableDeclaration("var", [t().variableDeclarator(namespace, t().identifier("global"))])); buildHelpers(body, namespace, whitelist); return t().program([buildUmdWrapper({ FACTORY_PARAMETERS: t().identifier("global"), BROWSER_ARGUMENTS: t().assignmentExpression("=", t().memberExpression(t().identifier("root"), namespace), t().objectExpression([])), COMMON_ARGUMENTS: t().identifier("exports"), AMD_ARGUMENTS: t().arrayExpression([t().stringLiteral("exports")]), FACTORY_BODY: body, UMD_ROOT: t().identifier("this") })]); } function buildVar(whitelist) { const namespace = t().identifier("babelHelpers"); const body = []; body.push(t().variableDeclaration("var", [t().variableDeclarator(namespace, t().objectExpression([]))])); const tree = t().program(body); buildHelpers(body, namespace, whitelist); body.push(t().expressionStatement(namespace)); return tree; } function buildHelpers(body, namespace, whitelist) { const getHelperReference = name => { return namespace ? t().memberExpression(namespace, t().identifier(name)) : t().identifier(`_${name}`); }; const refs = {}; helpers().list.forEach(function (name) { if (whitelist && whitelist.indexOf(name) < 0) return; const ref = refs[name] = getHelperReference(name); const { nodes } = helpers().get(name, getHelperReference, ref); body.push(...nodes); }); return refs; } function _default(whitelist, outputType = "global") { let tree; const build = { global: buildGlobal, module: buildModule, umd: buildUmd, var: buildVar }[outputType]; if (build) { tree = build(whitelist); } else { throw new Error(`Unsupported output type ${outputType}`); } return (0, _generator().default)(tree).code; } },{"@babel/generator":55,"@babel/helpers":65,"@babel/template":70,"@babel/types":142}],29:[function(require,module,exports){ (function (process){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.transformFromAstSync = transformFromAstSync; exports.transformFromAstAsync = transformFromAstAsync; exports.transformFromAst = void 0; var _config = _interopRequireDefault(require("./config")); var _transformation = require("./transformation"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const transformFromAst = function transformFromAst(ast, code, opts, callback) { if (typeof opts === "function") { callback = opts; opts = undefined; } if (callback === undefined) return transformFromAstSync(ast, code, opts); const cb = callback; process.nextTick(() => { let cfg; try { cfg = (0, _config.default)(opts); if (cfg === null) return cb(null, null); } catch (err) { return cb(err); } if (!ast) return cb(new Error("No AST given")); (0, _transformation.runAsync)(cfg, code, ast, cb); }); }; exports.transformFromAst = transformFromAst; function transformFromAstSync(ast, code, opts) { const config = (0, _config.default)(opts); if (config === null) return null; if (!ast) throw new Error("No AST given"); return (0, _transformation.runSync)(config, code, ast); } function transformFromAstAsync(ast, code, opts) { return new Promise((res, rej) => { transformFromAst(ast, code, opts, (err, result) => { if (err == null) res(result);else rej(err); }); }); } }).call(this,require('_process')) },{"./config":16,"./transformation":36,"_process":405}],30:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.transformFileSync = transformFileSync; exports.transformFileAsync = transformFileAsync; exports.transformFile = void 0; const transformFile = function transformFile(filename, opts, callback) { if (typeof opts === "function") { callback = opts; } callback(new Error("Transforming files is not supported in browsers"), null); }; exports.transformFile = transformFile; function transformFileSync() { throw new Error("Transforming files is not supported in browsers"); } function transformFileAsync() { return Promise.reject(new Error("Transforming files is not supported in browsers")); } },{}],31:[function(require,module,exports){ (function (process){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.transformSync = transformSync; exports.transformAsync = transformAsync; exports.transform = void 0; var _config = _interopRequireDefault(require("./config")); var _transformation = require("./transformation"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const transform = function transform(code, opts, callback) { if (typeof opts === "function") { callback = opts; opts = undefined; } if (callback === undefined) return transformSync(code, opts); const cb = callback; process.nextTick(() => { let cfg; try { cfg = (0, _config.default)(opts); if (cfg === null) return cb(null, null); } catch (err) { return cb(err); } (0, _transformation.runAsync)(cfg, code, null, cb); }); }; exports.transform = transform; function transformSync(code, opts) { const config = (0, _config.default)(opts); if (config === null) return null; return (0, _transformation.runSync)(config, code); } function transformAsync(code, opts) { return new Promise((res, rej) => { transform(code, opts, (err, result) => { if (err == null) res(result);else rej(err); }); }); } }).call(this,require('_process')) },{"./config":16,"./transformation":36,"_process":405}],32:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = loadBlockHoistPlugin; function _sortBy() { const data = _interopRequireDefault(require("lodash/sortBy")); _sortBy = function () { return data; }; return data; } var _config = _interopRequireDefault(require("../config")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } let LOADED_PLUGIN; function loadBlockHoistPlugin() { if (!LOADED_PLUGIN) { const config = (0, _config.default)({ babelrc: false, configFile: false, plugins: [blockHoistPlugin] }); LOADED_PLUGIN = config ? config.passes[0][0] : undefined; if (!LOADED_PLUGIN) throw new Error("Assertion failure"); } return LOADED_PLUGIN; } const blockHoistPlugin = { name: "internal.blockHoist", visitor: { Block: { exit({ node }) { let hasChange = false; for (let i = 0; i < node.body.length; i++) { const bodyNode = node.body[i]; if (bodyNode && bodyNode._blockHoist != null) { hasChange = true; break; } } if (!hasChange) return; node.body = (0, _sortBy().default)(node.body, function (bodyNode) { let priority = bodyNode && bodyNode._blockHoist; if (priority == null) priority = 1; if (priority === true) priority = 2; return -1 * priority; }); } } } }; },{"../config":16,"lodash/sortBy":392}],33:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; function helpers() { const data = _interopRequireWildcard(require("@babel/helpers")); helpers = function () { return data; }; return data; } function _traverse() { const data = _interopRequireWildcard(require("@babel/traverse")); _traverse = function () { return data; }; return data; } function _codeFrame() { const data = require("@babel/code-frame"); _codeFrame = function () { return data; }; return data; } function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } function _semver() { const data = _interopRequireDefault(require("semver")); _semver = function () { return data; }; return data; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } const errorVisitor = { enter(path, state) { const loc = path.node.loc; if (loc) { state.loc = loc; path.stop(); } } }; class File { constructor(options, { code, ast, inputMap }) { this._map = new Map(); this.declarations = {}; this.path = null; this.ast = {}; this.metadata = {}; this.code = ""; this.inputMap = null; this.hub = { file: this, getCode: () => this.code, getScope: () => this.scope, addHelper: this.addHelper.bind(this), buildError: this.buildCodeFrameError.bind(this) }; this.opts = options; this.code = code; this.ast = ast; this.inputMap = inputMap; this.path = _traverse().NodePath.get({ hub: this.hub, parentPath: null, parent: this.ast, container: this.ast, key: "program" }).setContext(); this.scope = this.path.scope; } get shebang() { const { interpreter } = this.path.node; return interpreter ? interpreter.value : ""; } set shebang(value) { if (value) { this.path.get("interpreter").replaceWith(t().interpreterDirective(value)); } else { this.path.get("interpreter").remove(); } } set(key, val) { if (key === "helpersNamespace") { throw new Error("Babel 7.0.0-beta.56 has dropped support for the 'helpersNamespace' utility." + "If you are using @babel/plugin-external-helpers you will need to use a newer " + "version than the one you currently have installed. " + "If you have your own implementation, you'll want to explore using 'helperGenerator' " + "alongside 'file.availableHelper()'."); } this._map.set(key, val); } get(key) { return this._map.get(key); } has(key) { return this._map.has(key); } getModuleName() { const { filename, filenameRelative = filename, moduleId, moduleIds = !!moduleId, getModuleId, sourceRoot: sourceRootTmp, moduleRoot = sourceRootTmp, sourceRoot = moduleRoot } = this.opts; if (!moduleIds) return null; if (moduleId != null && !getModuleId) { return moduleId; } let moduleName = moduleRoot != null ? moduleRoot + "/" : ""; if (filenameRelative) { const sourceRootReplacer = sourceRoot != null ? new RegExp("^" + sourceRoot + "/?") : ""; moduleName += filenameRelative.replace(sourceRootReplacer, "").replace(/\.(\w*?)$/, ""); } moduleName = moduleName.replace(/\\/g, "/"); if (getModuleId) { return getModuleId(moduleName) || moduleName; } else { return moduleName; } } addImport() { throw new Error("This API has been removed. If you're looking for this " + "functionality in Babel 7, you should import the " + "'@babel/helper-module-imports' module and use the functions exposed " + " from that module, such as 'addNamed' or 'addDefault'."); } availableHelper(name, versionRange) { let minVersion; try { minVersion = helpers().minVersion(name); } catch (err) { if (err.code !== "BABEL_HELPER_UNKNOWN") throw err; return false; } if (typeof versionRange !== "string") return true; if (_semver().default.valid(versionRange)) versionRange = `^${versionRange}`; return !_semver().default.intersects(`<${minVersion}`, versionRange) && !_semver().default.intersects(`>=8.0.0`, versionRange); } addHelper(name) { const declar = this.declarations[name]; if (declar) return t().cloneNode(declar); const generator = this.get("helperGenerator"); if (generator) { const res = generator(name); if (res) return res; } const uid = this.declarations[name] = this.scope.generateUidIdentifier(name); const dependencies = {}; for (const dep of helpers().getDependencies(name)) { dependencies[dep] = this.addHelper(dep); } const { nodes, globals } = helpers().get(name, dep => dependencies[dep], uid, Object.keys(this.scope.getAllBindings())); globals.forEach(name => { if (this.path.scope.hasBinding(name, true)) { this.path.scope.rename(name); } }); nodes.forEach(node => { node._compact = true; }); this.path.unshiftContainer("body", nodes); this.path.get("body").forEach(path => { if (nodes.indexOf(path.node) === -1) return; if (path.isVariableDeclaration()) this.scope.registerDeclaration(path); }); return uid; } addTemplateObject() { throw new Error("This function has been moved into the template literal transform itself."); } buildCodeFrameError(node, msg, Error = SyntaxError) { let loc = node && (node.loc || node._loc); msg = `${this.opts.filename}: ${msg}`; if (!loc && node) { const state = { loc: null }; (0, _traverse().default)(node, errorVisitor, this.scope, state); loc = state.loc; let txt = "This is an error on an internal node. Probably an internal error."; if (loc) txt += " Location has been estimated."; msg += ` (${txt})`; } if (loc) { const { highlightCode = true } = this.opts; msg += "\n" + (0, _codeFrame().codeFrameColumns)(this.code, { start: { line: loc.start.line, column: loc.start.column + 1 } }, { highlightCode }); } return new Error(msg); } } exports.default = File; },{"@babel/code-frame":8,"@babel/helpers":65,"@babel/traverse":79,"@babel/types":142,"semver":438}],34:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = generateCode; function _convertSourceMap() { const data = _interopRequireDefault(require("convert-source-map")); _convertSourceMap = function () { return data; }; return data; } function _generator() { const data = _interopRequireDefault(require("@babel/generator")); _generator = function () { return data; }; return data; } var _mergeMap = _interopRequireDefault(require("./merge-map")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function generateCode(pluginPasses, file) { const { opts, ast, code, inputMap } = file; const results = []; for (const plugins of pluginPasses) { for (const plugin of plugins) { const { generatorOverride } = plugin; if (generatorOverride) { const result = generatorOverride(ast, opts.generatorOpts, code, _generator().default); if (result !== undefined) results.push(result); } } } let result; if (results.length === 0) { result = (0, _generator().default)(ast, opts.generatorOpts, code); } else if (results.length === 1) { result = results[0]; if (typeof result.then === "function") { throw new Error(`You appear to be using an async parser plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, ` + `you may need to upgrade your @babel/core version.`); } } else { throw new Error("More than one plugin attempted to override codegen."); } let { code: outputCode, map: outputMap } = result; if (outputMap && inputMap) { outputMap = (0, _mergeMap.default)(inputMap.toObject(), outputMap); } if (opts.sourceMaps === "inline" || opts.sourceMaps === "both") { outputCode += "\n" + _convertSourceMap().default.fromObject(outputMap).toComment(); } if (opts.sourceMaps === "inline") { outputMap = null; } return { outputCode, outputMap }; } },{"./merge-map":35,"@babel/generator":55,"convert-source-map":189}],35:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = mergeSourceMap; function _sourceMap() { const data = _interopRequireDefault(require("source-map")); _sourceMap = function () { return data; }; return data; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function mergeSourceMap(inputMap, map) { const input = buildMappingData(inputMap); const output = buildMappingData(map); const mergedGenerator = new (_sourceMap().default.SourceMapGenerator)(); for (const _ref of input.sources) { const { source } = _ref; if (typeof source.content === "string") { mergedGenerator.setSourceContent(source.path, source.content); } } if (output.sources.length === 1) { const defaultSource = output.sources[0]; const insertedMappings = new Map(); eachInputGeneratedRange(input, (generated, original, source) => { eachOverlappingGeneratedOutputRange(defaultSource, generated, item => { const key = makeMappingKey(item); if (insertedMappings.has(key)) return; insertedMappings.set(key, item); mergedGenerator.addMapping({ source: source.path, original: { line: original.line, column: original.columnStart }, generated: { line: item.line, column: item.columnStart }, name: original.name }); }); }); for (const item of insertedMappings.values()) { if (item.columnEnd === Infinity) { continue; } const clearItem = { line: item.line, columnStart: item.columnEnd }; const key = makeMappingKey(clearItem); if (insertedMappings.has(key)) { continue; } mergedGenerator.addMapping({ generated: { line: clearItem.line, column: clearItem.columnStart } }); } } const result = mergedGenerator.toJSON(); if (typeof input.sourceRoot === "string") { result.sourceRoot = input.sourceRoot; } return result; } function makeMappingKey(item) { return `${item.line}/${item.columnStart}`; } function eachOverlappingGeneratedOutputRange(outputFile, inputGeneratedRange, callback) { const overlappingOriginal = filterApplicableOriginalRanges(outputFile, inputGeneratedRange); for (const _ref2 of overlappingOriginal) { const { generated } = _ref2; for (const item of generated) { callback(item); } } } function filterApplicableOriginalRanges({ mappings }, { line, columnStart, columnEnd }) { return filterSortedArray(mappings, ({ original: outOriginal }) => { if (line > outOriginal.line) return -1; if (line < outOriginal.line) return 1; if (columnStart >= outOriginal.columnEnd) return -1; if (columnEnd <= outOriginal.columnStart) return 1; return 0; }); } function eachInputGeneratedRange(map, callback) { for (const _ref3 of map.sources) { const { source, mappings } = _ref3; for (const _ref4 of mappings) { const { original, generated } = _ref4; for (const item of generated) { callback(item, original, source); } } } } function buildMappingData(map) { const consumer = new (_sourceMap().default.SourceMapConsumer)(Object.assign({}, map, { sourceRoot: null })); const sources = new Map(); const mappings = new Map(); let last = null; consumer.computeColumnSpans(); consumer.eachMapping(m => { if (m.originalLine === null) return; let source = sources.get(m.source); if (!source) { source = { path: m.source, content: consumer.sourceContentFor(m.source, true) }; sources.set(m.source, source); } let sourceData = mappings.get(source); if (!sourceData) { sourceData = { source, mappings: [] }; mappings.set(source, sourceData); } const obj = { line: m.originalLine, columnStart: m.originalColumn, columnEnd: Infinity, name: m.name }; if (last && last.source === source && last.mapping.line === m.originalLine) { last.mapping.columnEnd = m.originalColumn; } last = { source, mapping: obj }; sourceData.mappings.push({ original: obj, generated: consumer.allGeneratedPositionsFor({ source: m.source, line: m.originalLine, column: m.originalColumn }).map(item => ({ line: item.line, columnStart: item.column, columnEnd: item.lastColumn + 1 })) }); }, null, _sourceMap().default.SourceMapConsumer.ORIGINAL_ORDER); return { file: map.file, sourceRoot: map.sourceRoot, sources: Array.from(mappings.values()) }; } function findInsertionLocation(array, callback) { let left = 0; let right = array.length; while (left < right) { const mid = Math.floor((left + right) / 2); const item = array[mid]; const result = callback(item); if (result === 0) { left = mid; break; } if (result >= 0) { right = mid; } else { left = mid + 1; } } let i = left; if (i < array.length) { while (i >= 0 && callback(array[i]) >= 0) { i--; } return i + 1; } return i; } function filterSortedArray(array, callback) { const start = findInsertionLocation(array, callback); const results = []; for (let i = start; i < array.length && callback(array[i]) === 0; i++) { results.push(array[i]); } return results; } },{"source-map":449}],36:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.runAsync = runAsync; exports.runSync = runSync; function _traverse() { const data = _interopRequireDefault(require("@babel/traverse")); _traverse = function () { return data; }; return data; } var _pluginPass = _interopRequireDefault(require("./plugin-pass")); var _blockHoistPlugin = _interopRequireDefault(require("./block-hoist-plugin")); var _normalizeOpts = _interopRequireDefault(require("./normalize-opts")); var _normalizeFile = _interopRequireDefault(require("./normalize-file")); var _generate = _interopRequireDefault(require("./file/generate")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function runAsync(config, code, ast, callback) { let result; try { result = runSync(config, code, ast); } catch (err) { return callback(err); } return callback(null, result); } function runSync(config, code, ast) { const file = (0, _normalizeFile.default)(config.passes, (0, _normalizeOpts.default)(config), code, ast); transformFile(file, config.passes); const opts = file.opts; const { outputCode, outputMap } = opts.code !== false ? (0, _generate.default)(config.passes, file) : {}; return { metadata: file.metadata, options: opts, ast: opts.ast === true ? file.ast : null, code: outputCode === undefined ? null : outputCode, map: outputMap === undefined ? null : outputMap, sourceType: file.ast.program.sourceType }; } function transformFile(file, pluginPasses) { for (const pluginPairs of pluginPasses) { const passPairs = []; const passes = []; const visitors = []; for (const plugin of pluginPairs.concat([(0, _blockHoistPlugin.default)()])) { const pass = new _pluginPass.default(file, plugin.key, plugin.options); passPairs.push([plugin, pass]); passes.push(pass); visitors.push(plugin.visitor); } for (const [plugin, pass] of passPairs) { const fn = plugin.pre; if (fn) { const result = fn.call(pass, file); if (isThenable(result)) { throw new Error(`You appear to be using an plugin with an async .pre, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, you may need to upgrade ` + `your @babel/core version.`); } } } const visitor = _traverse().default.visitors.merge(visitors, passes, file.opts.wrapPluginVisitorMethod); (0, _traverse().default)(file.ast, visitor, file.scope); for (const [plugin, pass] of passPairs) { const fn = plugin.post; if (fn) { const result = fn.call(pass, file); if (isThenable(result)) { throw new Error(`You appear to be using an plugin with an async .post, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, you may need to upgrade ` + `your @babel/core version.`); } } } } } function isThenable(val) { return !!val && (typeof val === "object" || typeof val === "function") && !!val.then && typeof val.then === "function"; } },{"./block-hoist-plugin":32,"./file/generate":34,"./normalize-file":37,"./normalize-opts":38,"./plugin-pass":39,"@babel/traverse":79}],37:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = normalizeFile; function _path() { const data = _interopRequireDefault(require("path")); _path = function () { return data; }; return data; } function _debug() { const data = _interopRequireDefault(require("debug")); _debug = function () { return data; }; return data; } function _cloneDeep() { const data = _interopRequireDefault(require("lodash/cloneDeep")); _cloneDeep = function () { return data; }; return data; } function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } function _convertSourceMap() { const data = _interopRequireDefault(require("convert-source-map")); _convertSourceMap = function () { return data; }; return data; } function _parser() { const data = require("@babel/parser"); _parser = function () { return data; }; return data; } function _codeFrame() { const data = require("@babel/code-frame"); _codeFrame = function () { return data; }; return data; } var _file = _interopRequireDefault(require("./file/file")); var _missingPluginHelper = _interopRequireDefault(require("./util/missing-plugin-helper")); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug().default)("babel:transform:file"); function normalizeFile(pluginPasses, options, code, ast) { code = `${code || ""}`; let inputMap = null; if (options.inputSourceMap !== false) { if (typeof options.inputSourceMap === "object") { inputMap = _convertSourceMap().default.fromObject(options.inputSourceMap); } if (!inputMap) { try { inputMap = _convertSourceMap().default.fromSource(code); if (inputMap) { code = _convertSourceMap().default.removeComments(code); } } catch (err) { debug("discarding unknown inline input sourcemap", err); code = _convertSourceMap().default.removeComments(code); } } if (!inputMap) { if (typeof options.filename === "string") { try { inputMap = _convertSourceMap().default.fromMapFileSource(code, _path().default.dirname(options.filename)); if (inputMap) { code = _convertSourceMap().default.removeMapFileComments(code); } } catch (err) { debug("discarding unknown file input sourcemap", err); code = _convertSourceMap().default.removeMapFileComments(code); } } else { debug("discarding un-loadable file input sourcemap"); code = _convertSourceMap().default.removeMapFileComments(code); } } } if (ast) { if (ast.type === "Program") { ast = t().file(ast, [], []); } else if (ast.type !== "File") { throw new Error("AST root must be a Program or File node"); } ast = (0, _cloneDeep().default)(ast); } else { ast = parser(pluginPasses, options, code); } return new _file.default(options, { code, ast, inputMap }); } function parser(pluginPasses, { parserOpts, highlightCode = true, filename = "unknown" }, code) { try { const results = []; for (const plugins of pluginPasses) { for (const plugin of plugins) { const { parserOverride } = plugin; if (parserOverride) { const ast = parserOverride(code, parserOpts, _parser().parse); if (ast !== undefined) results.push(ast); } } } if (results.length === 0) { return (0, _parser().parse)(code, parserOpts); } else if (results.length === 1) { if (typeof results[0].then === "function") { throw new Error(`You appear to be using an async codegen plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, you may need to upgrade ` + `your @babel/core version.`); } return results[0]; } throw new Error("More than one plugin attempted to override parsing."); } catch (err) { if (err.code === "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED") { err.message += "\nConsider renaming the file to '.mjs', or setting sourceType:module " + "or sourceType:unambiguous in your Babel config for this file."; } const { loc, missingPlugin } = err; if (loc) { const codeFrame = (0, _codeFrame().codeFrameColumns)(code, { start: { line: loc.line, column: loc.column + 1 } }, { highlightCode }); if (missingPlugin) { err.message = `${filename}: ` + (0, _missingPluginHelper.default)(missingPlugin[0], loc, codeFrame); } else { err.message = `${filename}: ${err.message}\n\n` + codeFrame; } err.code = "BABEL_PARSE_ERROR"; } throw err; } } },{"./file/file":33,"./util/missing-plugin-helper":40,"@babel/code-frame":8,"@babel/parser":67,"@babel/types":142,"convert-source-map":189,"debug":191,"lodash/cloneDeep":361,"path":403}],38:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = normalizeOptions; function _path() { const data = _interopRequireDefault(require("path")); _path = function () { return data; }; return data; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function normalizeOptions(config) { const { filename, cwd, filenameRelative = typeof filename === "string" ? _path().default.relative(cwd, filename) : "unknown", sourceType = "module", inputSourceMap, sourceMaps = !!inputSourceMap, moduleRoot, sourceRoot = moduleRoot, sourceFileName = _path().default.basename(filenameRelative), comments = true, compact = "auto" } = config.options; const opts = config.options; const options = Object.assign({}, opts, { parserOpts: Object.assign({ sourceType: _path().default.extname(filenameRelative) === ".mjs" ? "module" : sourceType, sourceFileName: filename, plugins: [] }, opts.parserOpts), generatorOpts: Object.assign({ filename, auxiliaryCommentBefore: opts.auxiliaryCommentBefore, auxiliaryCommentAfter: opts.auxiliaryCommentAfter, retainLines: opts.retainLines, comments, shouldPrintComment: opts.shouldPrintComment, compact, minified: opts.minified, sourceMaps, sourceRoot, sourceFileName }, opts.generatorOpts) }); for (const plugins of config.passes) { for (const plugin of plugins) { if (plugin.manipulateOptions) { plugin.manipulateOptions(options, options.parserOpts); } } } return options; } },{"path":403}],39:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; class PluginPass { constructor(file, key, options) { this._map = new Map(); this.key = key; this.file = file; this.opts = options || {}; this.cwd = file.opts.cwd; this.filename = file.opts.filename; } set(key, val) { this._map.set(key, val); } get(key) { return this._map.get(key); } availableHelper(name, versionRange) { return this.file.availableHelper(name, versionRange); } addHelper(name) { return this.file.addHelper(name); } addImport() { return this.file.addImport(); } getModuleName() { return this.file.getModuleName(); } buildCodeFrameError(node, msg, Error) { return this.file.buildCodeFrameError(node, msg, Error); } } exports.default = PluginPass; },{}],40:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = generateMissingPluginMessage; const pluginNameMap = { classProperties: { syntax: { name: "@babel/plugin-syntax-class-properties", url: "https://git.io/vb4yQ" }, transform: { name: "@babel/plugin-proposal-class-properties", url: "https://git.io/vb4SL" } }, decorators: { syntax: { name: "@babel/plugin-syntax-decorators", url: "https://git.io/vb4y9" }, transform: { name: "@babel/plugin-proposal-decorators", url: "https://git.io/vb4ST" } }, doExpressions: { syntax: { name: "@babel/plugin-syntax-do-expressions", url: "https://git.io/vb4yh" }, transform: { name: "@babel/plugin-proposal-do-expressions", url: "https://git.io/vb4S3" } }, dynamicImport: { syntax: { name: "@babel/plugin-syntax-dynamic-import", url: "https://git.io/vb4Sv" } }, exportDefaultFrom: { syntax: { name: "@babel/plugin-syntax-export-default-from", url: "https://git.io/vb4SO" }, transform: { name: "@babel/plugin-proposal-export-default-from", url: "https://git.io/vb4yH" } }, exportNamespaceFrom: { syntax: { name: "@babel/plugin-syntax-export-namespace-from", url: "https://git.io/vb4Sf" }, transform: { name: "@babel/plugin-proposal-export-namespace-from", url: "https://git.io/vb4SG" } }, flow: { syntax: { name: "@babel/plugin-syntax-flow", url: "https://git.io/vb4yb" }, transform: { name: "@babel/plugin-transform-flow-strip-types", url: "https://git.io/vb49g" } }, functionBind: { syntax: { name: "@babel/plugin-syntax-function-bind", url: "https://git.io/vb4y7" }, transform: { name: "@babel/plugin-proposal-function-bind", url: "https://git.io/vb4St" } }, functionSent: { syntax: { name: "@babel/plugin-syntax-function-sent", url: "https://git.io/vb4yN" }, transform: { name: "@babel/plugin-proposal-function-sent", url: "https://git.io/vb4SZ" } }, importMeta: { syntax: { name: "@babel/plugin-syntax-import-meta", url: "https://git.io/vbKK6" } }, jsx: { syntax: { name: "@babel/plugin-syntax-jsx", url: "https://git.io/vb4yA" }, transform: { name: "@babel/plugin-transform-react-jsx", url: "https://git.io/vb4yd" } }, logicalAssignment: { syntax: { name: "@babel/plugin-syntax-logical-assignment-operators", url: "https://git.io/vAlBp" }, transform: { name: "@babel/plugin-proposal-logical-assignment-operators", url: "https://git.io/vAlRe" } }, nullishCoalescingOperator: { syntax: { name: "@babel/plugin-syntax-nullish-coalescing-operator", url: "https://git.io/vb4yx" }, transform: { name: "@babel/plugin-proposal-nullish-coalescing-operator", url: "https://git.io/vb4Se" } }, numericSeparator: { syntax: { name: "@babel/plugin-syntax-numeric-separator", url: "https://git.io/vb4Sq" }, transform: { name: "@babel/plugin-proposal-numeric-separator", url: "https://git.io/vb4yS" } }, optionalChaining: { syntax: { name: "@babel/plugin-syntax-optional-chaining", url: "https://git.io/vb4Sc" }, transform: { name: "@babel/plugin-proposal-optional-chaining", url: "https://git.io/vb4Sk" } }, pipelineOperator: { syntax: { name: "@babel/plugin-syntax-pipeline-operator", url: "https://git.io/vb4yj" }, transform: { name: "@babel/plugin-proposal-pipeline-operator", url: "https://git.io/vb4SU" } }, throwExpressions: { syntax: { name: "@babel/plugin-syntax-throw-expressions", url: "https://git.io/vb4SJ" }, transform: { name: "@babel/plugin-proposal-throw-expressions", url: "https://git.io/vb4yF" } }, typescript: { syntax: { name: "@babel/plugin-syntax-typescript", url: "https://git.io/vb4SC" }, transform: { name: "@babel/plugin-transform-typescript", url: "https://git.io/vb4Sm" } }, asyncGenerators: { syntax: { name: "@babel/plugin-syntax-async-generators", url: "https://git.io/vb4SY" }, transform: { name: "@babel/plugin-proposal-async-generator-functions", url: "https://git.io/vb4yp" } }, objectRestSpread: { syntax: { name: "@babel/plugin-syntax-object-rest-spread", url: "https://git.io/vb4y5" }, transform: { name: "@babel/plugin-proposal-object-rest-spread", url: "https://git.io/vb4Ss" } }, optionalCatchBinding: { syntax: { name: "@babel/plugin-syntax-optional-catch-binding", url: "https://git.io/vb4Sn" }, transform: { name: "@babel/plugin-proposal-optional-catch-binding", url: "https://git.io/vb4SI" } } }; const getNameURLCombination = ({ name, url }) => `${name} (${url})`; function generateMissingPluginMessage(missingPluginName, loc, codeFrame) { let helpMessage = `Support for the experimental syntax '${missingPluginName}' isn't currently enabled ` + `(${loc.line}:${loc.column + 1}):\n\n` + codeFrame; const pluginInfo = pluginNameMap[missingPluginName]; if (pluginInfo) { const { syntax: syntaxPlugin, transform: transformPlugin } = pluginInfo; if (syntaxPlugin) { if (transformPlugin) { const transformPluginInfo = getNameURLCombination(transformPlugin); helpMessage += `\n\nAdd ${transformPluginInfo} to the 'plugins' section of your Babel config ` + `to enable transformation.`; } else { const syntaxPluginInfo = getNameURLCombination(syntaxPlugin); helpMessage += `\n\nAdd ${syntaxPluginInfo} to the 'plugins' section of your Babel config ` + `to enable parsing.`; } } } return helpMessage; } },{}],41:[function(require,module,exports){ module.exports={ "_from": "@babel/core@^7.2.2", "_id": "@babel/core@7.4.5", "_inBundle": false, "_integrity": "sha512-OvjIh6aqXtlsA8ujtGKfC7LYWksYSX8yQcM8Ay3LuvVeQ63lcOKgoZWVqcpFwkd29aYU9rVx7jxhfhiEDV9MZA==", "_location": "/@babel/core", "_phantomChildren": {}, "_requested": { "type": "range", "registry": true, "raw": "@babel/core@^7.2.2", "name": "@babel/core", "escapedName": "@babel%2fcore", "scope": "@babel", "rawSpec": "^7.2.2", "saveSpec": null, "fetchSpec": "^7.2.2" }, "_requiredBy": [ "#DEV:/", "#USER" ], "_resolved": "https://registry.npmjs.org/@babel/core/-/core-7.4.5.tgz", "_shasum": "081f97e8ffca65a9b4b0fdc7e274e703f000c06a", "_spec": "@babel/core@^7.2.2", "_where": "/Users/m.kapshtyk/WORK/i-finish/portal.i-finish.nl/bin", "author": { "name": "Sebastian McKenzie", "email": "sebmck@gmail.com" }, "browser": { "./lib/config/files/index.js": "./lib/config/files/index-browser.js", "./lib/transform-file.js": "./lib/transform-file-browser.js" }, "bundleDependencies": false, "dependencies": { "@babel/code-frame": "^7.0.0", "@babel/generator": "^7.4.4", "@babel/helpers": "^7.4.4", "@babel/parser": "^7.4.5", "@babel/template": "^7.4.4", "@babel/traverse": "^7.4.5", "@babel/types": "^7.4.4", "convert-source-map": "^1.1.0", "debug": "^4.1.0", "json5": "^2.1.0", "lodash": "^4.17.11", "resolve": "^1.3.2", "semver": "^5.4.1", "source-map": "^0.5.0" }, "deprecated": false, "description": "Babel compiler core.", "devDependencies": { "@babel/helper-transform-fixture-test-runner": "^7.4.4", "@babel/register": "^7.4.4" }, "engines": { "node": ">=6.9.0" }, "gitHead": "33ab4f166117e2380de3955a0842985f578b01b8", "homepage": "https://babeljs.io/", "keywords": [ "6to5", "babel", "classes", "const", "es6", "harmony", "let", "modules", "transpile", "transpiler", "var", "babel-core", "compiler" ], "license": "MIT", "main": "lib/index.js", "name": "@babel/core", "publishConfig": { "access": "public" }, "repository": { "type": "git", "url": "https://github.com/babel/babel/tree/master/packages/babel-core" }, "version": "7.4.5" } },{}],42:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; function _trimRight() { const data = _interopRequireDefault(require("trim-right")); _trimRight = function () { return data; }; return data; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const SPACES_RE = /^[ \t]+$/; class Buffer { constructor(map) { this._map = null; this._buf = []; this._last = ""; this._queue = []; this._position = { line: 1, column: 0 }; this._sourcePosition = { identifierName: null, line: null, column: null, filename: null }; this._disallowedPop = null; this._map = map; } get() { this._flush(); const map = this._map; const result = { code: (0, _trimRight().default)(this._buf.join("")), map: null, rawMappings: map && map.getRawMappings() }; if (map) { Object.defineProperty(result, "map", { configurable: true, enumerable: true, get() { return this.map = map.get(); }, set(value) { Object.defineProperty(this, "map", { value, writable: true }); } }); } return result; } append(str) { this._flush(); const { line, column, filename, identifierName, force } = this._sourcePosition; this._append(str, line, column, identifierName, filename, force); } queue(str) { if (str === "\n") { while (this._queue.length > 0 && SPACES_RE.test(this._queue[0][0])) { this._queue.shift(); } } const { line, column, filename, identifierName, force } = this._sourcePosition; this._queue.unshift([str, line, column, identifierName, filename, force]); } _flush() { let item; while (item = this._queue.pop()) this._append(...item); } _append(str, line, column, identifierName, filename, force) { if (this._map && str[0] !== "\n") { this._map.mark(this._position.line, this._position.column, line, column, identifierName, filename, force); } this._buf.push(str); this._last = str[str.length - 1]; for (let i = 0; i < str.length; i++) { if (str[i] === "\n") { this._position.line++; this._position.column = 0; } else { this._position.column++; } } } removeTrailingNewline() { if (this._queue.length > 0 && this._queue[0][0] === "\n") { this._queue.shift(); } } removeLastSemicolon() { if (this._queue.length > 0 && this._queue[0][0] === ";") { this._queue.shift(); } } endsWith(suffix) { if (suffix.length === 1) { let last; if (this._queue.length > 0) { const str = this._queue[0][0]; last = str[str.length - 1]; } else { last = this._last; } return last === suffix; } const end = this._last + this._queue.reduce((acc, item) => item[0] + acc, ""); if (suffix.length <= end.length) { return end.slice(-suffix.length) === suffix; } return false; } hasContent() { return this._queue.length > 0 || !!this._last; } exactSource(loc, cb) { this.source("start", loc, true); cb(); this.source("end", loc); this._disallowPop("start", loc); } source(prop, loc, force) { if (prop && !loc) return; this._normalizePosition(prop, loc, this._sourcePosition, force); } withSource(prop, loc, cb) { if (!this._map) return cb(); const originalLine = this._sourcePosition.line; const originalColumn = this._sourcePosition.column; const originalFilename = this._sourcePosition.filename; const originalIdentifierName = this._sourcePosition.identifierName; this.source(prop, loc); cb(); if ((!this._sourcePosition.force || this._sourcePosition.line !== originalLine || this._sourcePosition.column !== originalColumn || this._sourcePosition.filename !== originalFilename) && (!this._disallowedPop || this._disallowedPop.line !== originalLine || this._disallowedPop.column !== originalColumn || this._disallowedPop.filename !== originalFilename)) { this._sourcePosition.line = originalLine; this._sourcePosition.column = originalColumn; this._sourcePosition.filename = originalFilename; this._sourcePosition.identifierName = originalIdentifierName; this._sourcePosition.force = false; this._disallowedPop = null; } } _disallowPop(prop, loc) { if (prop && !loc) return; this._disallowedPop = this._normalizePosition(prop, loc); } _normalizePosition(prop, loc, targetObj, force) { const pos = loc ? loc[prop] : null; if (targetObj === undefined) { targetObj = { identifierName: null, line: null, column: null, filename: null, force: false }; } const origLine = targetObj.line; const origColumn = targetObj.column; const origFilename = targetObj.filename; targetObj.identifierName = prop === "start" && loc && loc.identifierName || null; targetObj.line = pos ? pos.line : null; targetObj.column = pos ? pos.column : null; targetObj.filename = loc && loc.filename || null; if (force || targetObj.line !== origLine || targetObj.column !== origColumn || targetObj.filename !== origFilename) { targetObj.force = force; } return targetObj; } getCurrentColumn() { const extra = this._queue.reduce((acc, item) => item[0] + acc, ""); const lastIndex = extra.lastIndexOf("\n"); return lastIndex === -1 ? this._position.column + extra.length : extra.length - 1 - lastIndex; } getCurrentLine() { const extra = this._queue.reduce((acc, item) => item[0] + acc, ""); let count = 0; for (let i = 0; i < extra.length; i++) { if (extra[i] === "\n") count++; } return this._position.line + count; } } exports.default = Buffer; },{"trim-right":457}],43:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.File = File; exports.Program = Program; exports.BlockStatement = BlockStatement; exports.Noop = Noop; exports.Directive = Directive; exports.DirectiveLiteral = DirectiveLiteral; exports.InterpreterDirective = InterpreterDirective; exports.Placeholder = Placeholder; function File(node) { if (node.program) { this.print(node.program.interpreter, node); } this.print(node.program, node); } function Program(node) { this.printInnerComments(node, false); this.printSequence(node.directives, node); if (node.directives && node.directives.length) this.newline(); this.printSequence(node.body, node); } function BlockStatement(node) { this.token("{"); this.printInnerComments(node); const hasDirectives = node.directives && node.directives.length; if (node.body.length || hasDirectives) { this.newline(); this.printSequence(node.directives, node, { indent: true }); if (hasDirectives) this.newline(); this.printSequence(node.body, node, { indent: true }); this.removeTrailingNewline(); this.source("end", node.loc); if (!this.endsWith("\n")) this.newline(); this.rightBrace(); } else { this.source("end", node.loc); this.token("}"); } } function Noop() {} function Directive(node) { this.print(node.value, node); this.semicolon(); } const unescapedSingleQuoteRE = /(?:^|[^\\])(?:\\\\)*'/; const unescapedDoubleQuoteRE = /(?:^|[^\\])(?:\\\\)*"/; function DirectiveLiteral(node) { const raw = this.getPossibleRaw(node); if (raw != null) { this.token(raw); return; } const { value } = node; if (!unescapedDoubleQuoteRE.test(value)) { this.token(`"${value}"`); } else if (!unescapedSingleQuoteRE.test(value)) { this.token(`'${value}'`); } else { throw new Error("Malformed AST: it is not possible to print a directive containing" + " both unescaped single and double quotes."); } } function InterpreterDirective(node) { this.token(`#!${node.value}\n`); } function Placeholder(node) { this.token("%%"); this.print(node.name); this.token("%%"); if (node.expectedNode === "Statement") { this.semicolon(); } } },{}],44:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ClassExpression = exports.ClassDeclaration = ClassDeclaration; exports.ClassBody = ClassBody; exports.ClassProperty = ClassProperty; exports.ClassPrivateProperty = ClassPrivateProperty; exports.ClassMethod = ClassMethod; exports.ClassPrivateMethod = ClassPrivateMethod; exports._classMethodHead = _classMethodHead; function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function ClassDeclaration(node, parent) { if (!this.format.decoratorsBeforeExport || !t().isExportDefaultDeclaration(parent) && !t().isExportNamedDeclaration(parent)) { this.printJoin(node.decorators, node); } if (node.declare) { this.word("declare"); this.space(); } if (node.abstract) { this.word("abstract"); this.space(); } this.word("class"); if (node.id) { this.space(); this.print(node.id, node); } this.print(node.typeParameters, node); if (node.superClass) { this.space(); this.word("extends"); this.space(); this.print(node.superClass, node); this.print(node.superTypeParameters, node); } if (node.implements) { this.space(); this.word("implements"); this.space(); this.printList(node.implements, node); } this.space(); this.print(node.body, node); } function ClassBody(node) { this.token("{"); this.printInnerComments(node); if (node.body.length === 0) { this.token("}"); } else { this.newline(); this.indent(); this.printSequence(node.body, node); this.dedent(); if (!this.endsWith("\n")) this.newline(); this.rightBrace(); } } function ClassProperty(node) { this.printJoin(node.decorators, node); if (node.accessibility) { this.word(node.accessibility); this.space(); } if (node.static) { this.word("static"); this.space(); } if (node.abstract) { this.word("abstract"); this.space(); } if (node.readonly) { this.word("readonly"); this.space(); } if (node.computed) { this.token("["); this.print(node.key, node); this.token("]"); } else { this._variance(node); this.print(node.key, node); } if (node.optional) { this.token("?"); } if (node.definite) { this.token("!"); } this.print(node.typeAnnotation, node); if (node.value) { this.space(); this.token("="); this.space(); this.print(node.value, node); } this.semicolon(); } function ClassPrivateProperty(node) { if (node.static) { this.word("static"); this.space(); } this.print(node.key, node); this.print(node.typeAnnotation, node); if (node.value) { this.space(); this.token("="); this.space(); this.print(node.value, node); } this.semicolon(); } function ClassMethod(node) { this._classMethodHead(node); this.space(); this.print(node.body, node); } function ClassPrivateMethod(node) { this._classMethodHead(node); this.space(); this.print(node.body, node); } function _classMethodHead(node) { this.printJoin(node.decorators, node); if (node.accessibility) { this.word(node.accessibility); this.space(); } if (node.abstract) { this.word("abstract"); this.space(); } if (node.static) { this.word("static"); this.space(); } this._methodHead(node); } },{"@babel/types":142}],45:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.UnaryExpression = UnaryExpression; exports.DoExpression = DoExpression; exports.ParenthesizedExpression = ParenthesizedExpression; exports.UpdateExpression = UpdateExpression; exports.ConditionalExpression = ConditionalExpression; exports.NewExpression = NewExpression; exports.SequenceExpression = SequenceExpression; exports.ThisExpression = ThisExpression; exports.Super = Super; exports.Decorator = Decorator; exports.OptionalMemberExpression = OptionalMemberExpression; exports.OptionalCallExpression = OptionalCallExpression; exports.CallExpression = CallExpression; exports.Import = Import; exports.EmptyStatement = EmptyStatement; exports.ExpressionStatement = ExpressionStatement; exports.AssignmentPattern = AssignmentPattern; exports.LogicalExpression = exports.BinaryExpression = exports.AssignmentExpression = AssignmentExpression; exports.BindExpression = BindExpression; exports.MemberExpression = MemberExpression; exports.MetaProperty = MetaProperty; exports.PrivateName = PrivateName; exports.AwaitExpression = exports.YieldExpression = void 0; function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } var n = _interopRequireWildcard(require("../node")); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function UnaryExpression(node) { if (node.operator === "void" || node.operator === "delete" || node.operator === "typeof" || node.operator === "throw") { this.word(node.operator); this.space(); } else { this.token(node.operator); } this.print(node.argument, node); } function DoExpression(node) { this.word("do"); this.space(); this.print(node.body, node); } function ParenthesizedExpression(node) { this.token("("); this.print(node.expression, node); this.token(")"); } function UpdateExpression(node) { if (node.prefix) { this.token(node.operator); this.print(node.argument, node); } else { this.startTerminatorless(true); this.print(node.argument, node); this.endTerminatorless(); this.token(node.operator); } } function ConditionalExpression(node) { this.print(node.test, node); this.space(); this.token("?"); this.space(); this.print(node.consequent, node); this.space(); this.token(":"); this.space(); this.print(node.alternate, node); } function NewExpression(node, parent) { this.word("new"); this.space(); this.print(node.callee, node); if (this.format.minified && node.arguments.length === 0 && !node.optional && !t().isCallExpression(parent, { callee: node }) && !t().isMemberExpression(parent) && !t().isNewExpression(parent)) { return; } this.print(node.typeArguments, node); this.print(node.typeParameters, node); if (node.optional) { this.token("?."); } this.token("("); this.printList(node.arguments, node); this.token(")"); } function SequenceExpression(node) { this.printList(node.expressions, node); } function ThisExpression() { this.word("this"); } function Super() { this.word("super"); } function Decorator(node) { this.token("@"); this.print(node.expression, node); this.newline(); } function OptionalMemberExpression(node) { this.print(node.object, node); if (!node.computed && t().isMemberExpression(node.property)) { throw new TypeError("Got a MemberExpression for MemberExpression property"); } let computed = node.computed; if (t().isLiteral(node.property) && typeof node.property.value === "number") { computed = true; } if (node.optional) { this.token("?."); } if (computed) { this.token("["); this.print(node.property, node); this.token("]"); } else { if (!node.optional) { this.token("."); } this.print(node.property, node); } } function OptionalCallExpression(node) { this.print(node.callee, node); this.print(node.typeArguments, node); this.print(node.typeParameters, node); if (node.optional) { this.token("?."); } this.token("("); this.printList(node.arguments, node); this.token(")"); } function CallExpression(node) { this.print(node.callee, node); this.print(node.typeArguments, node); this.print(node.typeParameters, node); this.token("("); this.printList(node.arguments, node); this.token(")"); } function Import() { this.word("import"); } function buildYieldAwait(keyword) { return function (node) { this.word(keyword); if (node.delegate) { this.token("*"); } if (node.argument) { this.space(); const terminatorState = this.startTerminatorless(); this.print(node.argument, node); this.endTerminatorless(terminatorState); } }; } const YieldExpression = buildYieldAwait("yield"); exports.YieldExpression = YieldExpression; const AwaitExpression = buildYieldAwait("await"); exports.AwaitExpression = AwaitExpression; function EmptyStatement() { this.semicolon(true); } function ExpressionStatement(node) { this.print(node.expression, node); this.semicolon(); } function AssignmentPattern(node) { this.print(node.left, node); if (node.left.optional) this.token("?"); this.print(node.left.typeAnnotation, node); this.space(); this.token("="); this.space(); this.print(node.right, node); } function AssignmentExpression(node, parent) { const parens = this.inForStatementInitCounter && node.operator === "in" && !n.needsParens(node, parent); if (parens) { this.token("("); } this.print(node.left, node); this.space(); if (node.operator === "in" || node.operator === "instanceof") { this.word(node.operator); } else { this.token(node.operator); } this.space(); this.print(node.right, node); if (parens) { this.token(")"); } } function BindExpression(node) { this.print(node.object, node); this.token("::"); this.print(node.callee, node); } function MemberExpression(node) { this.print(node.object, node); if (!node.computed && t().isMemberExpression(node.property)) { throw new TypeError("Got a MemberExpression for MemberExpression property"); } let computed = node.computed; if (t().isLiteral(node.property) && typeof node.property.value === "number") { computed = true; } if (computed) { this.token("["); this.print(node.property, node); this.token("]"); } else { this.token("."); this.print(node.property, node); } } function MetaProperty(node) { this.print(node.meta, node); this.token("."); this.print(node.property, node); } function PrivateName(node) { this.token("#"); this.print(node.id, node); } },{"../node":56,"@babel/types":142}],46:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AnyTypeAnnotation = AnyTypeAnnotation; exports.ArrayTypeAnnotation = ArrayTypeAnnotation; exports.BooleanTypeAnnotation = BooleanTypeAnnotation; exports.BooleanLiteralTypeAnnotation = BooleanLiteralTypeAnnotation; exports.NullLiteralTypeAnnotation = NullLiteralTypeAnnotation; exports.DeclareClass = DeclareClass; exports.DeclareFunction = DeclareFunction; exports.InferredPredicate = InferredPredicate; exports.DeclaredPredicate = DeclaredPredicate; exports.DeclareInterface = DeclareInterface; exports.DeclareModule = DeclareModule; exports.DeclareModuleExports = DeclareModuleExports; exports.DeclareTypeAlias = DeclareTypeAlias; exports.DeclareOpaqueType = DeclareOpaqueType; exports.DeclareVariable = DeclareVariable; exports.DeclareExportDeclaration = DeclareExportDeclaration; exports.DeclareExportAllDeclaration = DeclareExportAllDeclaration; exports.ExistsTypeAnnotation = ExistsTypeAnnotation; exports.FunctionTypeAnnotation = FunctionTypeAnnotation; exports.FunctionTypeParam = FunctionTypeParam; exports.GenericTypeAnnotation = exports.ClassImplements = exports.InterfaceExtends = InterfaceExtends; exports._interfaceish = _interfaceish; exports._variance = _variance; exports.InterfaceDeclaration = InterfaceDeclaration; exports.InterfaceTypeAnnotation = InterfaceTypeAnnotation; exports.IntersectionTypeAnnotation = IntersectionTypeAnnotation; exports.MixedTypeAnnotation = MixedTypeAnnotation; exports.EmptyTypeAnnotation = EmptyTypeAnnotation; exports.NullableTypeAnnotation = NullableTypeAnnotation; exports.NumberTypeAnnotation = NumberTypeAnnotation; exports.StringTypeAnnotation = StringTypeAnnotation; exports.ThisTypeAnnotation = ThisTypeAnnotation; exports.TupleTypeAnnotation = TupleTypeAnnotation; exports.TypeofTypeAnnotation = TypeofTypeAnnotation; exports.TypeAlias = TypeAlias; exports.TypeAnnotation = TypeAnnotation; exports.TypeParameterDeclaration = exports.TypeParameterInstantiation = TypeParameterInstantiation; exports.TypeParameter = TypeParameter; exports.OpaqueType = OpaqueType; exports.ObjectTypeAnnotation = ObjectTypeAnnotation; exports.ObjectTypeInternalSlot = ObjectTypeInternalSlot; exports.ObjectTypeCallProperty = ObjectTypeCallProperty; exports.ObjectTypeIndexer = ObjectTypeIndexer; exports.ObjectTypeProperty = ObjectTypeProperty; exports.ObjectTypeSpreadProperty = ObjectTypeSpreadProperty; exports.QualifiedTypeIdentifier = QualifiedTypeIdentifier; exports.UnionTypeAnnotation = UnionTypeAnnotation; exports.TypeCastExpression = TypeCastExpression; exports.Variance = Variance; exports.VoidTypeAnnotation = VoidTypeAnnotation; Object.defineProperty(exports, "NumberLiteralTypeAnnotation", { enumerable: true, get: function () { return _types2.NumericLiteral; } }); Object.defineProperty(exports, "StringLiteralTypeAnnotation", { enumerable: true, get: function () { return _types2.StringLiteral; } }); function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } var _modules = require("./modules"); var _types2 = require("./types"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function AnyTypeAnnotation() { this.word("any"); } function ArrayTypeAnnotation(node) { this.print(node.elementType, node); this.token("["); this.token("]"); } function BooleanTypeAnnotation() { this.word("boolean"); } function BooleanLiteralTypeAnnotation(node) { this.word(node.value ? "true" : "false"); } function NullLiteralTypeAnnotation() { this.word("null"); } function DeclareClass(node, parent) { if (!t().isDeclareExportDeclaration(parent)) { this.word("declare"); this.space(); } this.word("class"); this.space(); this._interfaceish(node); } function DeclareFunction(node, parent) { if (!t().isDeclareExportDeclaration(parent)) { this.word("declare"); this.space(); } this.word("function"); this.space(); this.print(node.id, node); this.print(node.id.typeAnnotation.typeAnnotation, node); if (node.predicate) { this.space(); this.print(node.predicate, node); } this.semicolon(); } function InferredPredicate() { this.token("%"); this.word("checks"); } function DeclaredPredicate(node) { this.token("%"); this.word("checks"); this.token("("); this.print(node.value, node); this.token(")"); } function DeclareInterface(node) { this.word("declare"); this.space(); this.InterfaceDeclaration(node); } function DeclareModule(node) { this.word("declare"); this.space(); this.word("module"); this.space(); this.print(node.id, node); this.space(); this.print(node.body, node); } function DeclareModuleExports(node) { this.word("declare"); this.space(); this.word("module"); this.token("."); this.word("exports"); this.print(node.typeAnnotation, node); } function DeclareTypeAlias(node) { this.word("declare"); this.space(); this.TypeAlias(node); } function DeclareOpaqueType(node, parent) { if (!t().isDeclareExportDeclaration(parent)) { this.word("declare"); this.space(); } this.OpaqueType(node); } function DeclareVariable(node, parent) { if (!t().isDeclareExportDeclaration(parent)) { this.word("declare"); this.space(); } this.word("var"); this.space(); this.print(node.id, node); this.print(node.id.typeAnnotation, node); this.semicolon(); } function DeclareExportDeclaration(node) { this.word("declare"); this.space(); this.word("export"); this.space(); if (node.default) { this.word("default"); this.space(); } FlowExportDeclaration.apply(this, arguments); } function DeclareExportAllDeclaration() { this.word("declare"); this.space(); _modules.ExportAllDeclaration.apply(this, arguments); } function FlowExportDeclaration(node) { if (node.declaration) { const declar = node.declaration; this.print(declar, node); if (!t().isStatement(declar)) this.semicolon(); } else { this.token("{"); if (node.specifiers.length) { this.space(); this.printList(node.specifiers, node); this.space(); } this.token("}"); if (node.source) { this.space(); this.word("from"); this.space(); this.print(node.source, node); } this.semicolon(); } } function ExistsTypeAnnotation() { this.token("*"); } function FunctionTypeAnnotation(node, parent) { this.print(node.typeParameters, node); this.token("("); this.printList(node.params, node); if (node.rest) { if (node.params.length) { this.token(","); this.space(); } this.token("..."); this.print(node.rest, node); } this.token(")"); if (parent.type === "ObjectTypeCallProperty" || parent.type === "DeclareFunction" || parent.type === "ObjectTypeProperty" && parent.method) { this.token(":"); } else { this.space(); this.token("=>"); } this.space(); this.print(node.returnType, node); } function FunctionTypeParam(node) { this.print(node.name, node); if (node.optional) this.token("?"); if (node.name) { this.token(":"); this.space(); } this.print(node.typeAnnotation, node); } function InterfaceExtends(node) { this.print(node.id, node); this.print(node.typeParameters, node); } function _interfaceish(node) { this.print(node.id, node); this.print(node.typeParameters, node); if (node.extends.length) { this.space(); this.word("extends"); this.space(); this.printList(node.extends, node); } if (node.mixins && node.mixins.length) { this.space(); this.word("mixins"); this.space(); this.printList(node.mixins, node); } if (node.implements && node.implements.length) { this.space(); this.word("implements"); this.space(); this.printList(node.implements, node); } this.space(); this.print(node.body, node); } function _variance(node) { if (node.variance) { if (node.variance.kind === "plus") { this.token("+"); } else if (node.variance.kind === "minus") { this.token("-"); } } } function InterfaceDeclaration(node) { this.word("interface"); this.space(); this._interfaceish(node); } function andSeparator() { this.space(); this.token("&"); this.space(); } function InterfaceTypeAnnotation(node) { this.word("interface"); if (node.extends && node.extends.length) { this.space(); this.word("extends"); this.space(); this.printList(node.extends, node); } this.space(); this.print(node.body, node); } function IntersectionTypeAnnotation(node) { this.printJoin(node.types, node, { separator: andSeparator }); } function MixedTypeAnnotation() { this.word("mixed"); } function EmptyTypeAnnotation() { this.word("empty"); } function NullableTypeAnnotation(node) { this.token("?"); this.print(node.typeAnnotation, node); } function NumberTypeAnnotation() { this.word("number"); } function StringTypeAnnotation() { this.word("string"); } function ThisTypeAnnotation() { this.word("this"); } function TupleTypeAnnotation(node) { this.token("["); this.printList(node.types, node); this.token("]"); } function TypeofTypeAnnotation(node) { this.word("typeof"); this.space(); this.print(node.argument, node); } function TypeAlias(node) { this.word("type"); this.space(); this.print(node.id, node); this.print(node.typeParameters, node); this.space(); this.token("="); this.space(); this.print(node.right, node); this.semicolon(); } function TypeAnnotation(node) { this.token(":"); this.space(); if (node.optional) this.token("?"); this.print(node.typeAnnotation, node); } function TypeParameterInstantiation(node) { this.token("<"); this.printList(node.params, node, {}); this.token(">"); } function TypeParameter(node) { this._variance(node); this.word(node.name); if (node.bound) { this.print(node.bound, node); } if (node.default) { this.space(); this.token("="); this.space(); this.print(node.default, node); } } function OpaqueType(node) { this.word("opaque"); this.space(); this.word("type"); this.space(); this.print(node.id, node); this.print(node.typeParameters, node); if (node.supertype) { this.token(":"); this.space(); this.print(node.supertype, node); } if (node.impltype) { this.space(); this.token("="); this.space(); this.print(node.impltype, node); } this.semicolon(); } function ObjectTypeAnnotation(node) { if (node.exact) { this.token("{|"); } else { this.token("{"); } const props = node.properties.concat(node.callProperties || [], node.indexers || [], node.internalSlots || []); if (props.length) { this.space(); this.printJoin(props, node, { addNewlines(leading) { if (leading && !props[0]) return 1; }, indent: true, statement: true, iterator: () => { if (props.length !== 1) { this.token(","); this.space(); } } }); this.space(); } if (node.exact) { this.token("|}"); } else { this.token("}"); } } function ObjectTypeInternalSlot(node) { if (node.static) { this.word("static"); this.space(); } this.token("["); this.token("["); this.print(node.id, node); this.token("]"); this.token("]"); if (node.optional) this.token("?"); if (!node.method) { this.token(":"); this.space(); } this.print(node.value, node); } function ObjectTypeCallProperty(node) { if (node.static) { this.word("static"); this.space(); } this.print(node.value, node); } function ObjectTypeIndexer(node) { if (node.static) { this.word("static"); this.space(); } this._variance(node); this.token("["); if (node.id) { this.print(node.id, node); this.token(":"); this.space(); } this.print(node.key, node); this.token("]"); this.token(":"); this.space(); this.print(node.value, node); } function ObjectTypeProperty(node) { if (node.proto) { this.word("proto"); this.space(); } if (node.static) { this.word("static"); this.space(); } this._variance(node); this.print(node.key, node); if (node.optional) this.token("?"); if (!node.method) { this.token(":"); this.space(); } this.print(node.value, node); } function ObjectTypeSpreadProperty(node) { this.token("..."); this.print(node.argument, node); } function QualifiedTypeIdentifier(node) { this.print(node.qualification, node); this.token("."); this.print(node.id, node); } function orSeparator() { this.space(); this.token("|"); this.space(); } function UnionTypeAnnotation(node) { this.printJoin(node.types, node, { separator: orSeparator }); } function TypeCastExpression(node) { this.token("("); this.print(node.expression, node); this.print(node.typeAnnotation, node); this.token(")"); } function Variance(node) { if (node.kind === "plus") { this.token("+"); } else { this.token("-"); } } function VoidTypeAnnotation() { this.word("void"); } },{"./modules":50,"./types":53,"@babel/types":142}],47:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _templateLiterals = require("./template-literals"); Object.keys(_templateLiterals).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _templateLiterals[key]; } }); }); var _expressions = require("./expressions"); Object.keys(_expressions).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _expressions[key]; } }); }); var _statements = require("./statements"); Object.keys(_statements).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _statements[key]; } }); }); var _classes = require("./classes"); Object.keys(_classes).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _classes[key]; } }); }); var _methods = require("./methods"); Object.keys(_methods).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _methods[key]; } }); }); var _modules = require("./modules"); Object.keys(_modules).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _modules[key]; } }); }); var _types = require("./types"); Object.keys(_types).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _types[key]; } }); }); var _flow = require("./flow"); Object.keys(_flow).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _flow[key]; } }); }); var _base = require("./base"); Object.keys(_base).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _base[key]; } }); }); var _jsx = require("./jsx"); Object.keys(_jsx).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _jsx[key]; } }); }); var _typescript = require("./typescript"); Object.keys(_typescript).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _typescript[key]; } }); }); },{"./base":43,"./classes":44,"./expressions":45,"./flow":46,"./jsx":48,"./methods":49,"./modules":50,"./statements":51,"./template-literals":52,"./types":53,"./typescript":54}],48:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.JSXAttribute = JSXAttribute; exports.JSXIdentifier = JSXIdentifier; exports.JSXNamespacedName = JSXNamespacedName; exports.JSXMemberExpression = JSXMemberExpression; exports.JSXSpreadAttribute = JSXSpreadAttribute; exports.JSXExpressionContainer = JSXExpressionContainer; exports.JSXSpreadChild = JSXSpreadChild; exports.JSXText = JSXText; exports.JSXElement = JSXElement; exports.JSXOpeningElement = JSXOpeningElement; exports.JSXClosingElement = JSXClosingElement; exports.JSXEmptyExpression = JSXEmptyExpression; exports.JSXFragment = JSXFragment; exports.JSXOpeningFragment = JSXOpeningFragment; exports.JSXClosingFragment = JSXClosingFragment; function JSXAttribute(node) { this.print(node.name, node); if (node.value) { this.token("="); this.print(node.value, node); } } function JSXIdentifier(node) { this.word(node.name); } function JSXNamespacedName(node) { this.print(node.namespace, node); this.token(":"); this.print(node.name, node); } function JSXMemberExpression(node) { this.print(node.object, node); this.token("."); this.print(node.property, node); } function JSXSpreadAttribute(node) { this.token("{"); this.token("..."); this.print(node.argument, node); this.token("}"); } function JSXExpressionContainer(node) { this.token("{"); this.print(node.expression, node); this.token("}"); } function JSXSpreadChild(node) { this.token("{"); this.token("..."); this.print(node.expression, node); this.token("}"); } function JSXText(node) { const raw = this.getPossibleRaw(node); if (raw != null) { this.token(raw); } else { this.token(node.value); } } function JSXElement(node) { const open = node.openingElement; this.print(open, node); if (open.selfClosing) return; this.indent(); for (const child of node.children) { this.print(child, node); } this.dedent(); this.print(node.closingElement, node); } function spaceSeparator() { this.space(); } function JSXOpeningElement(node) { this.token("<"); this.print(node.name, node); this.print(node.typeParameters, node); if (node.attributes.length > 0) { this.space(); this.printJoin(node.attributes, node, { separator: spaceSeparator }); } if (node.selfClosing) { this.space(); this.token("/>"); } else { this.token(">"); } } function JSXClosingElement(node) { this.token(""); } function JSXEmptyExpression(node) { this.printInnerComments(node); } function JSXFragment(node) { this.print(node.openingFragment, node); this.indent(); for (const child of node.children) { this.print(child, node); } this.dedent(); this.print(node.closingFragment, node); } function JSXOpeningFragment() { this.token("<"); this.token(">"); } function JSXClosingFragment() { this.token(""); } },{}],49:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports._params = _params; exports._parameters = _parameters; exports._param = _param; exports._methodHead = _methodHead; exports._predicate = _predicate; exports._functionHead = _functionHead; exports.FunctionDeclaration = exports.FunctionExpression = FunctionExpression; exports.ArrowFunctionExpression = ArrowFunctionExpression; function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function _params(node) { this.print(node.typeParameters, node); this.token("("); this._parameters(node.params, node); this.token(")"); this.print(node.returnType, node); } function _parameters(parameters, parent) { for (let i = 0; i < parameters.length; i++) { this._param(parameters[i], parent); if (i < parameters.length - 1) { this.token(","); this.space(); } } } function _param(parameter, parent) { this.printJoin(parameter.decorators, parameter); this.print(parameter, parent); if (parameter.optional) this.token("?"); this.print(parameter.typeAnnotation, parameter); } function _methodHead(node) { const kind = node.kind; const key = node.key; if (kind === "get" || kind === "set") { this.word(kind); this.space(); } if (node.async) { this.word("async"); this.space(); } if (kind === "method" || kind === "init") { if (node.generator) { this.token("*"); } } if (node.computed) { this.token("["); this.print(key, node); this.token("]"); } else { this.print(key, node); } if (node.optional) { this.token("?"); } this._params(node); } function _predicate(node) { if (node.predicate) { if (!node.returnType) { this.token(":"); } this.space(); this.print(node.predicate, node); } } function _functionHead(node) { if (node.async) { this.word("async"); this.space(); } this.word("function"); if (node.generator) this.token("*"); this.space(); if (node.id) { this.print(node.id, node); } this._params(node); this._predicate(node); } function FunctionExpression(node) { this._functionHead(node); this.space(); this.print(node.body, node); } function ArrowFunctionExpression(node) { if (node.async) { this.word("async"); this.space(); } const firstParam = node.params[0]; if (node.params.length === 1 && t().isIdentifier(firstParam) && !hasTypes(node, firstParam)) { if (this.format.retainLines && node.loc && node.body.loc && node.loc.start.line < node.body.loc.start.line) { this.token("("); if (firstParam.loc && firstParam.loc.start.line > node.loc.start.line) { this.indent(); this.print(firstParam, node); this.dedent(); this._catchUp("start", node.body.loc); } else { this.print(firstParam, node); } this.token(")"); } else { this.print(firstParam, node); } } else { this._params(node); } this._predicate(node); this.space(); this.token("=>"); this.space(); this.print(node.body, node); } function hasTypes(node, param) { return node.typeParameters || node.returnType || param.typeAnnotation || param.optional || param.trailingComments; } },{"@babel/types":142}],50:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ImportSpecifier = ImportSpecifier; exports.ImportDefaultSpecifier = ImportDefaultSpecifier; exports.ExportDefaultSpecifier = ExportDefaultSpecifier; exports.ExportSpecifier = ExportSpecifier; exports.ExportNamespaceSpecifier = ExportNamespaceSpecifier; exports.ExportAllDeclaration = ExportAllDeclaration; exports.ExportNamedDeclaration = ExportNamedDeclaration; exports.ExportDefaultDeclaration = ExportDefaultDeclaration; exports.ImportDeclaration = ImportDeclaration; exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier; function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function ImportSpecifier(node) { if (node.importKind === "type" || node.importKind === "typeof") { this.word(node.importKind); this.space(); } this.print(node.imported, node); if (node.local && node.local.name !== node.imported.name) { this.space(); this.word("as"); this.space(); this.print(node.local, node); } } function ImportDefaultSpecifier(node) { this.print(node.local, node); } function ExportDefaultSpecifier(node) { this.print(node.exported, node); } function ExportSpecifier(node) { this.print(node.local, node); if (node.exported && node.local.name !== node.exported.name) { this.space(); this.word("as"); this.space(); this.print(node.exported, node); } } function ExportNamespaceSpecifier(node) { this.token("*"); this.space(); this.word("as"); this.space(); this.print(node.exported, node); } function ExportAllDeclaration(node) { this.word("export"); this.space(); if (node.exportKind === "type") { this.word("type"); this.space(); } this.token("*"); this.space(); this.word("from"); this.space(); this.print(node.source, node); this.semicolon(); } function ExportNamedDeclaration(node) { if (this.format.decoratorsBeforeExport && t().isClassDeclaration(node.declaration)) { this.printJoin(node.declaration.decorators, node); } this.word("export"); this.space(); ExportDeclaration.apply(this, arguments); } function ExportDefaultDeclaration(node) { if (this.format.decoratorsBeforeExport && t().isClassDeclaration(node.declaration)) { this.printJoin(node.declaration.decorators, node); } this.word("export"); this.space(); this.word("default"); this.space(); ExportDeclaration.apply(this, arguments); } function ExportDeclaration(node) { if (node.declaration) { const declar = node.declaration; this.print(declar, node); if (!t().isStatement(declar)) this.semicolon(); } else { if (node.exportKind === "type") { this.word("type"); this.space(); } const specifiers = node.specifiers.slice(0); let hasSpecial = false; while (true) { const first = specifiers[0]; if (t().isExportDefaultSpecifier(first) || t().isExportNamespaceSpecifier(first)) { hasSpecial = true; this.print(specifiers.shift(), node); if (specifiers.length) { this.token(","); this.space(); } } else { break; } } if (specifiers.length || !specifiers.length && !hasSpecial) { this.token("{"); if (specifiers.length) { this.space(); this.printList(specifiers, node); this.space(); } this.token("}"); } if (node.source) { this.space(); this.word("from"); this.space(); this.print(node.source, node); } this.semicolon(); } } function ImportDeclaration(node) { this.word("import"); this.space(); if (node.importKind === "type" || node.importKind === "typeof") { this.word(node.importKind); this.space(); } const specifiers = node.specifiers.slice(0); if (specifiers && specifiers.length) { while (true) { const first = specifiers[0]; if (t().isImportDefaultSpecifier(first) || t().isImportNamespaceSpecifier(first)) { this.print(specifiers.shift(), node); if (specifiers.length) { this.token(","); this.space(); } } else { break; } } if (specifiers.length) { this.token("{"); this.space(); this.printList(specifiers, node); this.space(); this.token("}"); } this.space(); this.word("from"); this.space(); } this.print(node.source, node); this.semicolon(); } function ImportNamespaceSpecifier(node) { this.token("*"); this.space(); this.word("as"); this.space(); this.print(node.local, node); } },{"@babel/types":142}],51:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WithStatement = WithStatement; exports.IfStatement = IfStatement; exports.ForStatement = ForStatement; exports.WhileStatement = WhileStatement; exports.DoWhileStatement = DoWhileStatement; exports.LabeledStatement = LabeledStatement; exports.TryStatement = TryStatement; exports.CatchClause = CatchClause; exports.SwitchStatement = SwitchStatement; exports.SwitchCase = SwitchCase; exports.DebuggerStatement = DebuggerStatement; exports.VariableDeclaration = VariableDeclaration; exports.VariableDeclarator = VariableDeclarator; exports.ThrowStatement = exports.BreakStatement = exports.ReturnStatement = exports.ContinueStatement = exports.ForOfStatement = exports.ForInStatement = void 0; function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function WithStatement(node) { this.word("with"); this.space(); this.token("("); this.print(node.object, node); this.token(")"); this.printBlock(node); } function IfStatement(node) { this.word("if"); this.space(); this.token("("); this.print(node.test, node); this.token(")"); this.space(); const needsBlock = node.alternate && t().isIfStatement(getLastStatement(node.consequent)); if (needsBlock) { this.token("{"); this.newline(); this.indent(); } this.printAndIndentOnComments(node.consequent, node); if (needsBlock) { this.dedent(); this.newline(); this.token("}"); } if (node.alternate) { if (this.endsWith("}")) this.space(); this.word("else"); this.space(); this.printAndIndentOnComments(node.alternate, node); } } function getLastStatement(statement) { if (!t().isStatement(statement.body)) return statement; return getLastStatement(statement.body); } function ForStatement(node) { this.word("for"); this.space(); this.token("("); this.inForStatementInitCounter++; this.print(node.init, node); this.inForStatementInitCounter--; this.token(";"); if (node.test) { this.space(); this.print(node.test, node); } this.token(";"); if (node.update) { this.space(); this.print(node.update, node); } this.token(")"); this.printBlock(node); } function WhileStatement(node) { this.word("while"); this.space(); this.token("("); this.print(node.test, node); this.token(")"); this.printBlock(node); } const buildForXStatement = function (op) { return function (node) { this.word("for"); this.space(); if (op === "of" && node.await) { this.word("await"); this.space(); } this.token("("); this.print(node.left, node); this.space(); this.word(op); this.space(); this.print(node.right, node); this.token(")"); this.printBlock(node); }; }; const ForInStatement = buildForXStatement("in"); exports.ForInStatement = ForInStatement; const ForOfStatement = buildForXStatement("of"); exports.ForOfStatement = ForOfStatement; function DoWhileStatement(node) { this.word("do"); this.space(); this.print(node.body, node); this.space(); this.word("while"); this.space(); this.token("("); this.print(node.test, node); this.token(")"); this.semicolon(); } function buildLabelStatement(prefix, key = "label") { return function (node) { this.word(prefix); const label = node[key]; if (label) { this.space(); const isLabel = key == "label"; const terminatorState = this.startTerminatorless(isLabel); this.print(label, node); this.endTerminatorless(terminatorState); } this.semicolon(); }; } const ContinueStatement = buildLabelStatement("continue"); exports.ContinueStatement = ContinueStatement; const ReturnStatement = buildLabelStatement("return", "argument"); exports.ReturnStatement = ReturnStatement; const BreakStatement = buildLabelStatement("break"); exports.BreakStatement = BreakStatement; const ThrowStatement = buildLabelStatement("throw", "argument"); exports.ThrowStatement = ThrowStatement; function LabeledStatement(node) { this.print(node.label, node); this.token(":"); this.space(); this.print(node.body, node); } function TryStatement(node) { this.word("try"); this.space(); this.print(node.block, node); this.space(); if (node.handlers) { this.print(node.handlers[0], node); } else { this.print(node.handler, node); } if (node.finalizer) { this.space(); this.word("finally"); this.space(); this.print(node.finalizer, node); } } function CatchClause(node) { this.word("catch"); this.space(); if (node.param) { this.token("("); this.print(node.param, node); this.token(")"); this.space(); } this.print(node.body, node); } function SwitchStatement(node) { this.word("switch"); this.space(); this.token("("); this.print(node.discriminant, node); this.token(")"); this.space(); this.token("{"); this.printSequence(node.cases, node, { indent: true, addNewlines(leading, cas) { if (!leading && node.cases[node.cases.length - 1] === cas) return -1; } }); this.token("}"); } function SwitchCase(node) { if (node.test) { this.word("case"); this.space(); this.print(node.test, node); this.token(":"); } else { this.word("default"); this.token(":"); } if (node.consequent.length) { this.newline(); this.printSequence(node.consequent, node, { indent: true }); } } function DebuggerStatement() { this.word("debugger"); this.semicolon(); } function variableDeclarationIndent() { this.token(","); this.newline(); if (this.endsWith("\n")) for (let i = 0; i < 4; i++) this.space(true); } function constDeclarationIndent() { this.token(","); this.newline(); if (this.endsWith("\n")) for (let i = 0; i < 6; i++) this.space(true); } function VariableDeclaration(node, parent) { if (node.declare) { this.word("declare"); this.space(); } this.word(node.kind); this.space(); let hasInits = false; if (!t().isFor(parent)) { for (const declar of node.declarations) { if (declar.init) { hasInits = true; } } } let separator; if (hasInits) { separator = node.kind === "const" ? constDeclarationIndent : variableDeclarationIndent; } this.printList(node.declarations, node, { separator }); if (t().isFor(parent)) { if (parent.left === node || parent.init === node) return; } this.semicolon(); } function VariableDeclarator(node) { this.print(node.id, node); if (node.definite) this.token("!"); this.print(node.id.typeAnnotation, node); if (node.init) { this.space(); this.token("="); this.space(); this.print(node.init, node); } } },{"@babel/types":142}],52:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TaggedTemplateExpression = TaggedTemplateExpression; exports.TemplateElement = TemplateElement; exports.TemplateLiteral = TemplateLiteral; function TaggedTemplateExpression(node) { this.print(node.tag, node); this.print(node.typeParameters, node); this.print(node.quasi, node); } function TemplateElement(node, parent) { const isFirst = parent.quasis[0] === node; const isLast = parent.quasis[parent.quasis.length - 1] === node; const value = (isFirst ? "`" : "}") + node.value.raw + (isLast ? "`" : "${"); this.token(value); } function TemplateLiteral(node) { const quasis = node.quasis; for (let i = 0; i < quasis.length; i++) { this.print(quasis[i], node); if (i + 1 < quasis.length) { this.print(node.expressions[i], node); } } } },{}],53:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Identifier = Identifier; exports.ArgumentPlaceholder = ArgumentPlaceholder; exports.SpreadElement = exports.RestElement = RestElement; exports.ObjectPattern = exports.ObjectExpression = ObjectExpression; exports.ObjectMethod = ObjectMethod; exports.ObjectProperty = ObjectProperty; exports.ArrayPattern = exports.ArrayExpression = ArrayExpression; exports.RegExpLiteral = RegExpLiteral; exports.BooleanLiteral = BooleanLiteral; exports.NullLiteral = NullLiteral; exports.NumericLiteral = NumericLiteral; exports.StringLiteral = StringLiteral; exports.BigIntLiteral = BigIntLiteral; exports.PipelineTopicExpression = PipelineTopicExpression; exports.PipelineBareFunction = PipelineBareFunction; exports.PipelinePrimaryTopicReference = PipelinePrimaryTopicReference; function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } function _jsesc() { const data = _interopRequireDefault(require("jsesc")); _jsesc = function () { return data; }; return data; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function Identifier(node) { this.exactSource(node.loc, () => { this.word(node.name); }); } function ArgumentPlaceholder() { this.token("?"); } function RestElement(node) { this.token("..."); this.print(node.argument, node); } function ObjectExpression(node) { const props = node.properties; this.token("{"); this.printInnerComments(node); if (props.length) { this.space(); this.printList(props, node, { indent: true, statement: true }); this.space(); } this.token("}"); } function ObjectMethod(node) { this.printJoin(node.decorators, node); this._methodHead(node); this.space(); this.print(node.body, node); } function ObjectProperty(node) { this.printJoin(node.decorators, node); if (node.computed) { this.token("["); this.print(node.key, node); this.token("]"); } else { if (t().isAssignmentPattern(node.value) && t().isIdentifier(node.key) && node.key.name === node.value.left.name) { this.print(node.value, node); return; } this.print(node.key, node); if (node.shorthand && t().isIdentifier(node.key) && t().isIdentifier(node.value) && node.key.name === node.value.name) { return; } } this.token(":"); this.space(); this.print(node.value, node); } function ArrayExpression(node) { const elems = node.elements; const len = elems.length; this.token("["); this.printInnerComments(node); for (let i = 0; i < elems.length; i++) { const elem = elems[i]; if (elem) { if (i > 0) this.space(); this.print(elem, node); if (i < len - 1) this.token(","); } else { this.token(","); } } this.token("]"); } function RegExpLiteral(node) { this.word(`/${node.pattern}/${node.flags}`); } function BooleanLiteral(node) { this.word(node.value ? "true" : "false"); } function NullLiteral() { this.word("null"); } function NumericLiteral(node) { const raw = this.getPossibleRaw(node); const value = node.value + ""; if (raw == null) { this.number(value); } else if (this.format.minified) { this.number(raw.length < value.length ? raw : value); } else { this.number(raw); } } function StringLiteral(node) { const raw = this.getPossibleRaw(node); if (!this.format.minified && raw != null) { this.token(raw); return; } const opts = this.format.jsescOption; if (this.format.jsonCompatibleStrings) { opts.json = true; } const val = (0, _jsesc().default)(node.value, opts); return this.token(val); } function BigIntLiteral(node) { const raw = this.getPossibleRaw(node); if (!this.format.minified && raw != null) { this.token(raw); return; } this.token(node.value); } function PipelineTopicExpression(node) { this.print(node.expression, node); } function PipelineBareFunction(node) { this.print(node.callee, node); } function PipelinePrimaryTopicReference() { this.token("#"); } },{"@babel/types":142,"jsesc":207}],54:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TSTypeAnnotation = TSTypeAnnotation; exports.TSTypeParameterDeclaration = exports.TSTypeParameterInstantiation = TSTypeParameterInstantiation; exports.TSTypeParameter = TSTypeParameter; exports.TSParameterProperty = TSParameterProperty; exports.TSDeclareFunction = TSDeclareFunction; exports.TSDeclareMethod = TSDeclareMethod; exports.TSQualifiedName = TSQualifiedName; exports.TSCallSignatureDeclaration = TSCallSignatureDeclaration; exports.TSConstructSignatureDeclaration = TSConstructSignatureDeclaration; exports.TSPropertySignature = TSPropertySignature; exports.tsPrintPropertyOrMethodName = tsPrintPropertyOrMethodName; exports.TSMethodSignature = TSMethodSignature; exports.TSIndexSignature = TSIndexSignature; exports.TSAnyKeyword = TSAnyKeyword; exports.TSUnknownKeyword = TSUnknownKeyword; exports.TSNumberKeyword = TSNumberKeyword; exports.TSObjectKeyword = TSObjectKeyword; exports.TSBooleanKeyword = TSBooleanKeyword; exports.TSStringKeyword = TSStringKeyword; exports.TSSymbolKeyword = TSSymbolKeyword; exports.TSVoidKeyword = TSVoidKeyword; exports.TSUndefinedKeyword = TSUndefinedKeyword; exports.TSNullKeyword = TSNullKeyword; exports.TSNeverKeyword = TSNeverKeyword; exports.TSThisType = TSThisType; exports.TSFunctionType = TSFunctionType; exports.TSConstructorType = TSConstructorType; exports.tsPrintFunctionOrConstructorType = tsPrintFunctionOrConstructorType; exports.TSTypeReference = TSTypeReference; exports.TSTypePredicate = TSTypePredicate; exports.TSTypeQuery = TSTypeQuery; exports.TSTypeLiteral = TSTypeLiteral; exports.tsPrintTypeLiteralOrInterfaceBody = tsPrintTypeLiteralOrInterfaceBody; exports.tsPrintBraced = tsPrintBraced; exports.TSArrayType = TSArrayType; exports.TSTupleType = TSTupleType; exports.TSOptionalType = TSOptionalType; exports.TSRestType = TSRestType; exports.TSUnionType = TSUnionType; exports.TSIntersectionType = TSIntersectionType; exports.tsPrintUnionOrIntersectionType = tsPrintUnionOrIntersectionType; exports.TSConditionalType = TSConditionalType; exports.TSInferType = TSInferType; exports.TSParenthesizedType = TSParenthesizedType; exports.TSTypeOperator = TSTypeOperator; exports.TSIndexedAccessType = TSIndexedAccessType; exports.TSMappedType = TSMappedType; exports.TSLiteralType = TSLiteralType; exports.TSExpressionWithTypeArguments = TSExpressionWithTypeArguments; exports.TSInterfaceDeclaration = TSInterfaceDeclaration; exports.TSInterfaceBody = TSInterfaceBody; exports.TSTypeAliasDeclaration = TSTypeAliasDeclaration; exports.TSAsExpression = TSAsExpression; exports.TSTypeAssertion = TSTypeAssertion; exports.TSEnumDeclaration = TSEnumDeclaration; exports.TSEnumMember = TSEnumMember; exports.TSModuleDeclaration = TSModuleDeclaration; exports.TSModuleBlock = TSModuleBlock; exports.TSImportType = TSImportType; exports.TSImportEqualsDeclaration = TSImportEqualsDeclaration; exports.TSExternalModuleReference = TSExternalModuleReference; exports.TSNonNullExpression = TSNonNullExpression; exports.TSExportAssignment = TSExportAssignment; exports.TSNamespaceExportDeclaration = TSNamespaceExportDeclaration; exports.tsPrintSignatureDeclarationBase = tsPrintSignatureDeclarationBase; function TSTypeAnnotation(node) { this.token(":"); this.space(); if (node.optional) this.token("?"); this.print(node.typeAnnotation, node); } function TSTypeParameterInstantiation(node) { this.token("<"); this.printList(node.params, node, {}); this.token(">"); } function TSTypeParameter(node) { this.word(node.name); if (node.constraint) { this.space(); this.word("extends"); this.space(); this.print(node.constraint, node); } if (node.default) { this.space(); this.token("="); this.space(); this.print(node.default, node); } } function TSParameterProperty(node) { if (node.accessibility) { this.word(node.accessibility); this.space(); } if (node.readonly) { this.word("readonly"); this.space(); } this._param(node.parameter); } function TSDeclareFunction(node) { if (node.declare) { this.word("declare"); this.space(); } this._functionHead(node); this.token(";"); } function TSDeclareMethod(node) { this._classMethodHead(node); this.token(";"); } function TSQualifiedName(node) { this.print(node.left, node); this.token("."); this.print(node.right, node); } function TSCallSignatureDeclaration(node) { this.tsPrintSignatureDeclarationBase(node); } function TSConstructSignatureDeclaration(node) { this.word("new"); this.space(); this.tsPrintSignatureDeclarationBase(node); } function TSPropertySignature(node) { const { readonly, initializer } = node; if (readonly) { this.word("readonly"); this.space(); } this.tsPrintPropertyOrMethodName(node); this.print(node.typeAnnotation, node); if (initializer) { this.space(); this.token("="); this.space(); this.print(initializer, node); } this.token(";"); } function tsPrintPropertyOrMethodName(node) { if (node.computed) { this.token("["); } this.print(node.key, node); if (node.computed) { this.token("]"); } if (node.optional) { this.token("?"); } } function TSMethodSignature(node) { this.tsPrintPropertyOrMethodName(node); this.tsPrintSignatureDeclarationBase(node); this.token(";"); } function TSIndexSignature(node) { const { readonly } = node; if (readonly) { this.word("readonly"); this.space(); } this.token("["); this._parameters(node.parameters, node); this.token("]"); this.print(node.typeAnnotation, node); this.token(";"); } function TSAnyKeyword() { this.word("any"); } function TSUnknownKeyword() { this.word("unknown"); } function TSNumberKeyword() { this.word("number"); } function TSObjectKeyword() { this.word("object"); } function TSBooleanKeyword() { this.word("boolean"); } function TSStringKeyword() { this.word("string"); } function TSSymbolKeyword() { this.word("symbol"); } function TSVoidKeyword() { this.word("void"); } function TSUndefinedKeyword() { this.word("undefined"); } function TSNullKeyword() { this.word("null"); } function TSNeverKeyword() { this.word("never"); } function TSThisType() { this.word("this"); } function TSFunctionType(node) { this.tsPrintFunctionOrConstructorType(node); } function TSConstructorType(node) { this.word("new"); this.space(); this.tsPrintFunctionOrConstructorType(node); } function tsPrintFunctionOrConstructorType(node) { const { typeParameters, parameters } = node; this.print(typeParameters, node); this.token("("); this._parameters(parameters, node); this.token(")"); this.space(); this.token("=>"); this.space(); this.print(node.typeAnnotation.typeAnnotation, node); } function TSTypeReference(node) { this.print(node.typeName, node); this.print(node.typeParameters, node); } function TSTypePredicate(node) { this.print(node.parameterName); this.space(); this.word("is"); this.space(); this.print(node.typeAnnotation.typeAnnotation); } function TSTypeQuery(node) { this.word("typeof"); this.space(); this.print(node.exprName); } function TSTypeLiteral(node) { this.tsPrintTypeLiteralOrInterfaceBody(node.members, node); } function tsPrintTypeLiteralOrInterfaceBody(members, node) { this.tsPrintBraced(members, node); } function tsPrintBraced(members, node) { this.token("{"); if (members.length) { this.indent(); this.newline(); for (const member of members) { this.print(member, node); this.newline(); } this.dedent(); this.rightBrace(); } else { this.token("}"); } } function TSArrayType(node) { this.print(node.elementType, node); this.token("[]"); } function TSTupleType(node) { this.token("["); this.printList(node.elementTypes, node); this.token("]"); } function TSOptionalType(node) { this.print(node.typeAnnotation, node); this.token("?"); } function TSRestType(node) { this.token("..."); this.print(node.typeAnnotation, node); } function TSUnionType(node) { this.tsPrintUnionOrIntersectionType(node, "|"); } function TSIntersectionType(node) { this.tsPrintUnionOrIntersectionType(node, "&"); } function tsPrintUnionOrIntersectionType(node, sep) { this.printJoin(node.types, node, { separator() { this.space(); this.token(sep); this.space(); } }); } function TSConditionalType(node) { this.print(node.checkType); this.space(); this.word("extends"); this.space(); this.print(node.extendsType); this.space(); this.token("?"); this.space(); this.print(node.trueType); this.space(); this.token(":"); this.space(); this.print(node.falseType); } function TSInferType(node) { this.token("infer"); this.space(); this.print(node.typeParameter); } function TSParenthesizedType(node) { this.token("("); this.print(node.typeAnnotation, node); this.token(")"); } function TSTypeOperator(node) { this.token(node.operator); this.space(); this.print(node.typeAnnotation, node); } function TSIndexedAccessType(node) { this.print(node.objectType, node); this.token("["); this.print(node.indexType, node); this.token("]"); } function TSMappedType(node) { const { readonly, typeParameter, optional } = node; this.token("{"); this.space(); if (readonly) { tokenIfPlusMinus(this, readonly); this.word("readonly"); this.space(); } this.token("["); this.word(typeParameter.name); this.space(); this.word("in"); this.space(); this.print(typeParameter.constraint, typeParameter); this.token("]"); if (optional) { tokenIfPlusMinus(this, optional); this.token("?"); } this.token(":"); this.space(); this.print(node.typeAnnotation, node); this.space(); this.token("}"); } function tokenIfPlusMinus(self, tok) { if (tok !== true) { self.token(tok); } } function TSLiteralType(node) { this.print(node.literal, node); } function TSExpressionWithTypeArguments(node) { this.print(node.expression, node); this.print(node.typeParameters, node); } function TSInterfaceDeclaration(node) { const { declare, id, typeParameters, extends: extendz, body } = node; if (declare) { this.word("declare"); this.space(); } this.word("interface"); this.space(); this.print(id, node); this.print(typeParameters, node); if (extendz) { this.space(); this.word("extends"); this.space(); this.printList(extendz, node); } this.space(); this.print(body, node); } function TSInterfaceBody(node) { this.tsPrintTypeLiteralOrInterfaceBody(node.body, node); } function TSTypeAliasDeclaration(node) { const { declare, id, typeParameters, typeAnnotation } = node; if (declare) { this.word("declare"); this.space(); } this.word("type"); this.space(); this.print(id, node); this.print(typeParameters, node); this.space(); this.token("="); this.space(); this.print(typeAnnotation, node); this.token(";"); } function TSAsExpression(node) { const { expression, typeAnnotation } = node; this.print(expression, node); this.space(); this.word("as"); this.space(); this.print(typeAnnotation, node); } function TSTypeAssertion(node) { const { typeAnnotation, expression } = node; this.token("<"); this.print(typeAnnotation, node); this.token(">"); this.space(); this.print(expression, node); } function TSEnumDeclaration(node) { const { declare, const: isConst, id, members } = node; if (declare) { this.word("declare"); this.space(); } if (isConst) { this.word("const"); this.space(); } this.word("enum"); this.space(); this.print(id, node); this.space(); this.tsPrintBraced(members, node); } function TSEnumMember(node) { const { id, initializer } = node; this.print(id, node); if (initializer) { this.space(); this.token("="); this.space(); this.print(initializer, node); } this.token(","); } function TSModuleDeclaration(node) { const { declare, id } = node; if (declare) { this.word("declare"); this.space(); } if (!node.global) { this.word(id.type === "Identifier" ? "namespace" : "module"); this.space(); } this.print(id, node); if (!node.body) { this.token(";"); return; } let body = node.body; while (body.type === "TSModuleDeclaration") { this.token("."); this.print(body.id, body); body = body.body; } this.space(); this.print(body, node); } function TSModuleBlock(node) { this.tsPrintBraced(node.body, node); } function TSImportType(node) { const { argument, qualifier, typeParameters } = node; this.word("import"); this.token("("); this.print(argument, node); this.token(")"); if (qualifier) { this.token("."); this.print(qualifier, node); } if (typeParameters) { this.print(typeParameters, node); } } function TSImportEqualsDeclaration(node) { const { isExport, id, moduleReference } = node; if (isExport) { this.word("export"); this.space(); } this.word("import"); this.space(); this.print(id, node); this.space(); this.token("="); this.space(); this.print(moduleReference, node); this.token(";"); } function TSExternalModuleReference(node) { this.token("require("); this.print(node.expression, node); this.token(")"); } function TSNonNullExpression(node) { this.print(node.expression, node); this.token("!"); } function TSExportAssignment(node) { this.word("export"); this.space(); this.token("="); this.space(); this.print(node.expression, node); this.token(";"); } function TSNamespaceExportDeclaration(node) { this.word("export"); this.space(); this.word("as"); this.space(); this.word("namespace"); this.space(); this.print(node.id, node); } function tsPrintSignatureDeclarationBase(node) { const { typeParameters, parameters } = node; this.print(typeParameters, node); this.token("("); this._parameters(parameters, node); this.token(")"); this.print(node.typeAnnotation, node); } },{}],55:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = _default; exports.CodeGenerator = void 0; var _sourceMap = _interopRequireDefault(require("./source-map")); var _printer = _interopRequireDefault(require("./printer")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } class Generator extends _printer.default { constructor(ast, opts = {}, code) { const format = normalizeOptions(code, opts); const map = opts.sourceMaps ? new _sourceMap.default(opts, code) : null; super(format, map); this.ast = ast; } generate() { return super.generate(this.ast); } } function normalizeOptions(code, opts) { const format = { auxiliaryCommentBefore: opts.auxiliaryCommentBefore, auxiliaryCommentAfter: opts.auxiliaryCommentAfter, shouldPrintComment: opts.shouldPrintComment, retainLines: opts.retainLines, retainFunctionParens: opts.retainFunctionParens, comments: opts.comments == null || opts.comments, compact: opts.compact, minified: opts.minified, concise: opts.concise, jsonCompatibleStrings: opts.jsonCompatibleStrings, indent: { adjustMultilineComment: true, style: " ", base: 0 }, decoratorsBeforeExport: !!opts.decoratorsBeforeExport, jsescOption: Object.assign({ quotes: "double", wrap: true }, opts.jsescOption) }; if (format.minified) { format.compact = true; format.shouldPrintComment = format.shouldPrintComment || (() => format.comments); } else { format.shouldPrintComment = format.shouldPrintComment || (value => format.comments || value.indexOf("@license") >= 0 || value.indexOf("@preserve") >= 0); } if (format.compact === "auto") { format.compact = code.length > 500000; if (format.compact) { console.error("[BABEL] Note: The code generator has deoptimised the styling of " + `${opts.filename} as it exceeds the max of ${"500KB"}.`); } } if (format.compact) { format.indent.adjustMultilineComment = false; } return format; } class CodeGenerator { constructor(ast, opts, code) { this._generator = new Generator(ast, opts, code); } generate() { return this._generator.generate(); } } exports.CodeGenerator = CodeGenerator; function _default(ast, opts, code) { const gen = new Generator(ast, opts, code); return gen.generate(); } },{"./printer":59,"./source-map":60}],56:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.needsWhitespace = needsWhitespace; exports.needsWhitespaceBefore = needsWhitespaceBefore; exports.needsWhitespaceAfter = needsWhitespaceAfter; exports.needsParens = needsParens; var whitespace = _interopRequireWildcard(require("./whitespace")); var parens = _interopRequireWildcard(require("./parentheses")); function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function expandAliases(obj) { const newObj = {}; function add(type, func) { const fn = newObj[type]; newObj[type] = fn ? function (node, parent, stack) { const result = fn(node, parent, stack); return result == null ? func(node, parent, stack) : result; } : func; } for (const type of Object.keys(obj)) { const aliases = t().FLIPPED_ALIAS_KEYS[type]; if (aliases) { for (const alias of aliases) { add(alias, obj[type]); } } else { add(type, obj[type]); } } return newObj; } const expandedParens = expandAliases(parens); const expandedWhitespaceNodes = expandAliases(whitespace.nodes); const expandedWhitespaceList = expandAliases(whitespace.list); function find(obj, node, parent, printStack) { const fn = obj[node.type]; return fn ? fn(node, parent, printStack) : null; } function isOrHasCallExpression(node) { if (t().isCallExpression(node)) { return true; } if (t().isMemberExpression(node)) { return isOrHasCallExpression(node.object) || !node.computed && isOrHasCallExpression(node.property); } else { return false; } } function needsWhitespace(node, parent, type) { if (!node) return 0; if (t().isExpressionStatement(node)) { node = node.expression; } let linesInfo = find(expandedWhitespaceNodes, node, parent); if (!linesInfo) { const items = find(expandedWhitespaceList, node, parent); if (items) { for (let i = 0; i < items.length; i++) { linesInfo = needsWhitespace(items[i], node, type); if (linesInfo) break; } } } if (typeof linesInfo === "object" && linesInfo !== null) { return linesInfo[type] || 0; } return 0; } function needsWhitespaceBefore(node, parent) { return needsWhitespace(node, parent, "before"); } function needsWhitespaceAfter(node, parent) { return needsWhitespace(node, parent, "after"); } function needsParens(node, parent, printStack) { if (!parent) return false; if (t().isNewExpression(parent) && parent.callee === node) { if (isOrHasCallExpression(node)) return true; } return find(expandedParens, node, parent, printStack); } },{"./parentheses":57,"./whitespace":58,"@babel/types":142}],57:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.NullableTypeAnnotation = NullableTypeAnnotation; exports.FunctionTypeAnnotation = FunctionTypeAnnotation; exports.UpdateExpression = UpdateExpression; exports.ObjectExpression = ObjectExpression; exports.DoExpression = DoExpression; exports.Binary = Binary; exports.IntersectionTypeAnnotation = exports.UnionTypeAnnotation = UnionTypeAnnotation; exports.TSAsExpression = TSAsExpression; exports.TSTypeAssertion = TSTypeAssertion; exports.TSIntersectionType = exports.TSUnionType = TSUnionType; exports.BinaryExpression = BinaryExpression; exports.SequenceExpression = SequenceExpression; exports.AwaitExpression = exports.YieldExpression = YieldExpression; exports.ClassExpression = ClassExpression; exports.UnaryLike = UnaryLike; exports.FunctionExpression = FunctionExpression; exports.ArrowFunctionExpression = ArrowFunctionExpression; exports.ConditionalExpression = ConditionalExpression; exports.OptionalMemberExpression = OptionalMemberExpression; exports.AssignmentExpression = AssignmentExpression; exports.NewExpression = NewExpression; function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } const PRECEDENCE = { "||": 0, "&&": 1, "|": 2, "^": 3, "&": 4, "==": 5, "===": 5, "!=": 5, "!==": 5, "<": 6, ">": 6, "<=": 6, ">=": 6, in: 6, instanceof: 6, ">>": 7, "<<": 7, ">>>": 7, "+": 8, "-": 8, "*": 9, "/": 9, "%": 9, "**": 10 }; const isClassExtendsClause = (node, parent) => (t().isClassDeclaration(parent) || t().isClassExpression(parent)) && parent.superClass === node; function NullableTypeAnnotation(node, parent) { return t().isArrayTypeAnnotation(parent); } function FunctionTypeAnnotation(node, parent) { return t().isUnionTypeAnnotation(parent) || t().isIntersectionTypeAnnotation(parent) || t().isArrayTypeAnnotation(parent); } function UpdateExpression(node, parent) { return t().isMemberExpression(parent, { object: node }) || t().isCallExpression(parent, { callee: node }) || t().isNewExpression(parent, { callee: node }) || isClassExtendsClause(node, parent); } function ObjectExpression(node, parent, printStack) { return isFirstInStatement(printStack, { considerArrow: true }); } function DoExpression(node, parent, printStack) { return isFirstInStatement(printStack); } function Binary(node, parent) { if (node.operator === "**" && t().isBinaryExpression(parent, { operator: "**" })) { return parent.left === node; } if (isClassExtendsClause(node, parent)) { return true; } if ((t().isCallExpression(parent) || t().isNewExpression(parent)) && parent.callee === node || t().isUnaryLike(parent) || t().isMemberExpression(parent) && parent.object === node || t().isAwaitExpression(parent)) { return true; } if (t().isBinary(parent)) { const parentOp = parent.operator; const parentPos = PRECEDENCE[parentOp]; const nodeOp = node.operator; const nodePos = PRECEDENCE[nodeOp]; if (parentPos === nodePos && parent.right === node && !t().isLogicalExpression(parent) || parentPos > nodePos) { return true; } } return false; } function UnionTypeAnnotation(node, parent) { return t().isArrayTypeAnnotation(parent) || t().isNullableTypeAnnotation(parent) || t().isIntersectionTypeAnnotation(parent) || t().isUnionTypeAnnotation(parent); } function TSAsExpression() { return true; } function TSTypeAssertion() { return true; } function TSUnionType(node, parent) { return t().isTSArrayType(parent) || t().isTSOptionalType(parent) || t().isTSIntersectionType(parent) || t().isTSUnionType(parent) || t().isTSRestType(parent); } function BinaryExpression(node, parent) { return node.operator === "in" && (t().isVariableDeclarator(parent) || t().isFor(parent)); } function SequenceExpression(node, parent) { if (t().isForStatement(parent) || t().isThrowStatement(parent) || t().isReturnStatement(parent) || t().isIfStatement(parent) && parent.test === node || t().isWhileStatement(parent) && parent.test === node || t().isForInStatement(parent) && parent.right === node || t().isSwitchStatement(parent) && parent.discriminant === node || t().isExpressionStatement(parent) && parent.expression === node) { return false; } return true; } function YieldExpression(node, parent) { return t().isBinary(parent) || t().isUnaryLike(parent) || t().isCallExpression(parent) || t().isMemberExpression(parent) || t().isNewExpression(parent) || t().isAwaitExpression(parent) && t().isYieldExpression(node) || t().isConditionalExpression(parent) && node === parent.test || isClassExtendsClause(node, parent); } function ClassExpression(node, parent, printStack) { return isFirstInStatement(printStack, { considerDefaultExports: true }); } function UnaryLike(node, parent) { return t().isMemberExpression(parent, { object: node }) || t().isCallExpression(parent, { callee: node }) || t().isNewExpression(parent, { callee: node }) || t().isBinaryExpression(parent, { operator: "**", left: node }) || isClassExtendsClause(node, parent); } function FunctionExpression(node, parent, printStack) { return isFirstInStatement(printStack, { considerDefaultExports: true }); } function ArrowFunctionExpression(node, parent) { return t().isExportDeclaration(parent) || ConditionalExpression(node, parent); } function ConditionalExpression(node, parent) { if (t().isUnaryLike(parent) || t().isBinary(parent) || t().isConditionalExpression(parent, { test: node }) || t().isAwaitExpression(parent) || t().isOptionalMemberExpression(parent) || t().isTaggedTemplateExpression(parent) || t().isTSTypeAssertion(parent) || t().isTSAsExpression(parent)) { return true; } return UnaryLike(node, parent); } function OptionalMemberExpression(node, parent) { return t().isCallExpression(parent) || t().isMemberExpression(parent); } function AssignmentExpression(node) { if (t().isObjectPattern(node.left)) { return true; } else { return ConditionalExpression(...arguments); } } function NewExpression(node, parent) { return isClassExtendsClause(node, parent); } function isFirstInStatement(printStack, { considerArrow = false, considerDefaultExports = false } = {}) { let i = printStack.length - 1; let node = printStack[i]; i--; let parent = printStack[i]; while (i > 0) { if (t().isExpressionStatement(parent, { expression: node }) || t().isTaggedTemplateExpression(parent) || considerDefaultExports && t().isExportDefaultDeclaration(parent, { declaration: node }) || considerArrow && t().isArrowFunctionExpression(parent, { body: node })) { return true; } if (t().isCallExpression(parent, { callee: node }) || t().isSequenceExpression(parent) && parent.expressions[0] === node || t().isMemberExpression(parent, { object: node }) || t().isConditional(parent, { test: node }) || t().isBinary(parent, { left: node }) || t().isAssignmentExpression(parent, { left: node })) { node = parent; i--; parent = printStack[i]; } else { return false; } } return false; } },{"@babel/types":142}],58:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.list = exports.nodes = void 0; function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function crawl(node, state = {}) { if (t().isMemberExpression(node)) { crawl(node.object, state); if (node.computed) crawl(node.property, state); } else if (t().isBinary(node) || t().isAssignmentExpression(node)) { crawl(node.left, state); crawl(node.right, state); } else if (t().isCallExpression(node)) { state.hasCall = true; crawl(node.callee, state); } else if (t().isFunction(node)) { state.hasFunction = true; } else if (t().isIdentifier(node)) { state.hasHelper = state.hasHelper || isHelper(node.callee); } return state; } function isHelper(node) { if (t().isMemberExpression(node)) { return isHelper(node.object) || isHelper(node.property); } else if (t().isIdentifier(node)) { return node.name === "require" || node.name[0] === "_"; } else if (t().isCallExpression(node)) { return isHelper(node.callee); } else if (t().isBinary(node) || t().isAssignmentExpression(node)) { return t().isIdentifier(node.left) && isHelper(node.left) || isHelper(node.right); } else { return false; } } function isType(node) { return t().isLiteral(node) || t().isObjectExpression(node) || t().isArrayExpression(node) || t().isIdentifier(node) || t().isMemberExpression(node); } const nodes = { AssignmentExpression(node) { const state = crawl(node.right); if (state.hasCall && state.hasHelper || state.hasFunction) { return { before: state.hasFunction, after: true }; } }, SwitchCase(node, parent) { return { before: node.consequent.length || parent.cases[0] === node, after: !node.consequent.length && parent.cases[parent.cases.length - 1] === node }; }, LogicalExpression(node) { if (t().isFunction(node.left) || t().isFunction(node.right)) { return { after: true }; } }, Literal(node) { if (node.value === "use strict") { return { after: true }; } }, CallExpression(node) { if (t().isFunction(node.callee) || isHelper(node)) { return { before: true, after: true }; } }, VariableDeclaration(node) { for (let i = 0; i < node.declarations.length; i++) { const declar = node.declarations[i]; let enabled = isHelper(declar.id) && !isType(declar.init); if (!enabled) { const state = crawl(declar.init); enabled = isHelper(declar.init) && state.hasCall || state.hasFunction; } if (enabled) { return { before: true, after: true }; } } }, IfStatement(node) { if (t().isBlockStatement(node.consequent)) { return { before: true, after: true }; } } }; exports.nodes = nodes; nodes.ObjectProperty = nodes.ObjectTypeProperty = nodes.ObjectMethod = function (node, parent) { if (parent.properties[0] === node) { return { before: true }; } }; nodes.ObjectTypeCallProperty = function (node, parent) { if (parent.callProperties[0] === node && (!parent.properties || !parent.properties.length)) { return { before: true }; } }; nodes.ObjectTypeIndexer = function (node, parent) { if (parent.indexers[0] === node && (!parent.properties || !parent.properties.length) && (!parent.callProperties || !parent.callProperties.length)) { return { before: true }; } }; nodes.ObjectTypeInternalSlot = function (node, parent) { if (parent.internalSlots[0] === node && (!parent.properties || !parent.properties.length) && (!parent.callProperties || !parent.callProperties.length) && (!parent.indexers || !parent.indexers.length)) { return { before: true }; } }; const list = { VariableDeclaration(node) { return node.declarations.map(decl => decl.init); }, ArrayExpression(node) { return node.elements; }, ObjectExpression(node) { return node.properties; } }; exports.list = list; [["Function", true], ["Class", true], ["Loop", true], ["LabeledStatement", true], ["SwitchStatement", true], ["TryStatement", true]].forEach(function ([type, amounts]) { if (typeof amounts === "boolean") { amounts = { after: amounts, before: amounts }; } [type].concat(t().FLIPPED_ALIAS_KEYS[type] || []).forEach(function (type) { nodes[type] = function () { return amounts; }; }); }); },{"@babel/types":142}],59:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; function _isInteger() { const data = _interopRequireDefault(require("lodash/isInteger")); _isInteger = function () { return data; }; return data; } function _repeat() { const data = _interopRequireDefault(require("lodash/repeat")); _repeat = function () { return data; }; return data; } var _buffer = _interopRequireDefault(require("./buffer")); var n = _interopRequireWildcard(require("./node")); function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } var generatorFunctions = _interopRequireWildcard(require("./generators")); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const SCIENTIFIC_NOTATION = /e/i; const ZERO_DECIMAL_INTEGER = /\.0+$/; const NON_DECIMAL_LITERAL = /^0[box]/; class Printer { constructor(format, map) { this.inForStatementInitCounter = 0; this._printStack = []; this._indent = 0; this._insideAux = false; this._printedCommentStarts = {}; this._parenPushNewlineState = null; this._noLineTerminator = false; this._printAuxAfterOnNextUserNode = false; this._printedComments = new WeakSet(); this._endsWithInteger = false; this._endsWithWord = false; this.format = format || {}; this._buf = new _buffer.default(map); } generate(ast) { this.print(ast); this._maybeAddAuxComment(); return this._buf.get(); } indent() { if (this.format.compact || this.format.concise) return; this._indent++; } dedent() { if (this.format.compact || this.format.concise) return; this._indent--; } semicolon(force = false) { this._maybeAddAuxComment(); this._append(";", !force); } rightBrace() { if (this.format.minified) { this._buf.removeLastSemicolon(); } this.token("}"); } space(force = false) { if (this.format.compact) return; if (this._buf.hasContent() && !this.endsWith(" ") && !this.endsWith("\n") || force) { this._space(); } } word(str) { if (this._endsWithWord || this.endsWith("/") && str.indexOf("/") === 0) { this._space(); } this._maybeAddAuxComment(); this._append(str); this._endsWithWord = true; } number(str) { this.word(str); this._endsWithInteger = (0, _isInteger().default)(+str) && !NON_DECIMAL_LITERAL.test(str) && !SCIENTIFIC_NOTATION.test(str) && !ZERO_DECIMAL_INTEGER.test(str) && str[str.length - 1] !== "."; } token(str) { if (str === "--" && this.endsWith("!") || str[0] === "+" && this.endsWith("+") || str[0] === "-" && this.endsWith("-") || str[0] === "." && this._endsWithInteger) { this._space(); } this._maybeAddAuxComment(); this._append(str); } newline(i) { if (this.format.retainLines || this.format.compact) return; if (this.format.concise) { this.space(); return; } if (this.endsWith("\n\n")) return; if (typeof i !== "number") i = 1; i = Math.min(2, i); if (this.endsWith("{\n") || this.endsWith(":\n")) i--; if (i <= 0) return; for (let j = 0; j < i; j++) { this._newline(); } } endsWith(str) { return this._buf.endsWith(str); } removeTrailingNewline() { this._buf.removeTrailingNewline(); } exactSource(loc, cb) { this._catchUp("start", loc); this._buf.exactSource(loc, cb); } source(prop, loc) { this._catchUp(prop, loc); this._buf.source(prop, loc); } withSource(prop, loc, cb) { this._catchUp(prop, loc); this._buf.withSource(prop, loc, cb); } _space() { this._append(" ", true); } _newline() { this._append("\n", true); } _append(str, queue = false) { this._maybeAddParen(str); this._maybeIndent(str); if (queue) this._buf.queue(str);else this._buf.append(str); this._endsWithWord = false; this._endsWithInteger = false; } _maybeIndent(str) { if (this._indent && this.endsWith("\n") && str[0] !== "\n") { this._buf.queue(this._getIndent()); } } _maybeAddParen(str) { const parenPushNewlineState = this._parenPushNewlineState; if (!parenPushNewlineState) return; this._parenPushNewlineState = null; let i; for (i = 0; i < str.length && str[i] === " "; i++) continue; if (i === str.length) return; const cha = str[i]; if (cha !== "\n") { if (cha !== "/") return; if (i + 1 === str.length) return; const chaPost = str[i + 1]; if (chaPost !== "/" && chaPost !== "*") return; } this.token("("); this.indent(); parenPushNewlineState.printed = true; } _catchUp(prop, loc) { if (!this.format.retainLines) return; const pos = loc ? loc[prop] : null; if (pos && pos.line !== null) { const count = pos.line - this._buf.getCurrentLine(); for (let i = 0; i < count; i++) { this._newline(); } } } _getIndent() { return (0, _repeat().default)(this.format.indent.style, this._indent); } startTerminatorless(isLabel = false) { if (isLabel) { this._noLineTerminator = true; return null; } else { return this._parenPushNewlineState = { printed: false }; } } endTerminatorless(state) { this._noLineTerminator = false; if (state && state.printed) { this.dedent(); this.newline(); this.token(")"); } } print(node, parent) { if (!node) return; const oldConcise = this.format.concise; if (node._compact) { this.format.concise = true; } const printMethod = this[node.type]; if (!printMethod) { throw new ReferenceError(`unknown node of type ${JSON.stringify(node.type)} with constructor ${JSON.stringify(node && node.constructor.name)}`); } this._printStack.push(node); const oldInAux = this._insideAux; this._insideAux = !node.loc; this._maybeAddAuxComment(this._insideAux && !oldInAux); let needsParens = n.needsParens(node, parent, this._printStack); if (this.format.retainFunctionParens && node.type === "FunctionExpression" && node.extra && node.extra.parenthesized) { needsParens = true; } if (needsParens) this.token("("); this._printLeadingComments(node); const loc = t().isProgram(node) || t().isFile(node) ? null : node.loc; this.withSource("start", loc, () => { printMethod.call(this, node, parent); }); this._printTrailingComments(node); if (needsParens) this.token(")"); this._printStack.pop(); this.format.concise = oldConcise; this._insideAux = oldInAux; } _maybeAddAuxComment(enteredPositionlessNode) { if (enteredPositionlessNode) this._printAuxBeforeComment(); if (!this._insideAux) this._printAuxAfterComment(); } _printAuxBeforeComment() { if (this._printAuxAfterOnNextUserNode) return; this._printAuxAfterOnNextUserNode = true; const comment = this.format.auxiliaryCommentBefore; if (comment) { this._printComment({ type: "CommentBlock", value: comment }); } } _printAuxAfterComment() { if (!this._printAuxAfterOnNextUserNode) return; this._printAuxAfterOnNextUserNode = false; const comment = this.format.auxiliaryCommentAfter; if (comment) { this._printComment({ type: "CommentBlock", value: comment }); } } getPossibleRaw(node) { const extra = node.extra; if (extra && extra.raw != null && extra.rawValue != null && node.value === extra.rawValue) { return extra.raw; } } printJoin(nodes, parent, opts = {}) { if (!nodes || !nodes.length) return; if (opts.indent) this.indent(); const newlineOpts = { addNewlines: opts.addNewlines }; for (let i = 0; i < nodes.length; i++) { const node = nodes[i]; if (!node) continue; if (opts.statement) this._printNewline(true, node, parent, newlineOpts); this.print(node, parent); if (opts.iterator) { opts.iterator(node, i); } if (opts.separator && i < nodes.length - 1) { opts.separator.call(this); } if (opts.statement) this._printNewline(false, node, parent, newlineOpts); } if (opts.indent) this.dedent(); } printAndIndentOnComments(node, parent) { const indent = node.leadingComments && node.leadingComments.length > 0; if (indent) this.indent(); this.print(node, parent); if (indent) this.dedent(); } printBlock(parent) { const node = parent.body; if (!t().isEmptyStatement(node)) { this.space(); } this.print(node, parent); } _printTrailingComments(node) { this._printComments(this._getComments(false, node)); } _printLeadingComments(node) { this._printComments(this._getComments(true, node)); } printInnerComments(node, indent = true) { if (!node.innerComments || !node.innerComments.length) return; if (indent) this.indent(); this._printComments(node.innerComments); if (indent) this.dedent(); } printSequence(nodes, parent, opts = {}) { opts.statement = true; return this.printJoin(nodes, parent, opts); } printList(items, parent, opts = {}) { if (opts.separator == null) { opts.separator = commaSeparator; } return this.printJoin(items, parent, opts); } _printNewline(leading, node, parent, opts) { if (this.format.retainLines || this.format.compact) return; if (this.format.concise) { this.space(); return; } let lines = 0; if (this._buf.hasContent()) { if (!leading) lines++; if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0; const needs = leading ? n.needsWhitespaceBefore : n.needsWhitespaceAfter; if (needs(node, parent)) lines++; } this.newline(lines); } _getComments(leading, node) { return node && (leading ? node.leadingComments : node.trailingComments) || []; } _printComment(comment) { if (!this.format.shouldPrintComment(comment.value)) return; if (comment.ignore) return; if (this._printedComments.has(comment)) return; this._printedComments.add(comment); if (comment.start != null) { if (this._printedCommentStarts[comment.start]) return; this._printedCommentStarts[comment.start] = true; } const isBlockComment = comment.type === "CommentBlock"; this.newline(this._buf.hasContent() && !this._noLineTerminator && isBlockComment ? 1 : 0); if (!this.endsWith("[") && !this.endsWith("{")) this.space(); let val = !isBlockComment && !this._noLineTerminator ? `//${comment.value}\n` : `/*${comment.value}*/`; if (isBlockComment && this.format.indent.adjustMultilineComment) { const offset = comment.loc && comment.loc.start.column; if (offset) { const newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g"); val = val.replace(newlineRegex, "\n"); } const indentSize = Math.max(this._getIndent().length, this._buf.getCurrentColumn()); val = val.replace(/\n(?!$)/g, `\n${(0, _repeat().default)(" ", indentSize)}`); } if (this.endsWith("/")) this._space(); this.withSource("start", comment.loc, () => { this._append(val); }); this.newline(isBlockComment && !this._noLineTerminator ? 1 : 0); } _printComments(comments) { if (!comments || !comments.length) return; for (const comment of comments) { this._printComment(comment); } } } exports.default = Printer; Object.assign(Printer.prototype, generatorFunctions); function commaSeparator() { this.token(","); this.space(); } },{"./buffer":42,"./generators":47,"./node":56,"@babel/types":142,"lodash/isInteger":375,"lodash/repeat":391}],60:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; function _sourceMap() { const data = _interopRequireDefault(require("source-map")); _sourceMap = function () { return data; }; return data; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } class SourceMap { constructor(opts, code) { this._cachedMap = null; this._code = code; this._opts = opts; this._rawMappings = []; } get() { if (!this._cachedMap) { const map = this._cachedMap = new (_sourceMap().default.SourceMapGenerator)({ sourceRoot: this._opts.sourceRoot }); const code = this._code; if (typeof code === "string") { map.setSourceContent(this._opts.sourceFileName, code); } else if (typeof code === "object") { Object.keys(code).forEach(sourceFileName => { map.setSourceContent(sourceFileName, code[sourceFileName]); }); } this._rawMappings.forEach(map.addMapping, map); } return this._cachedMap.toJSON(); } getRawMappings() { return this._rawMappings.slice(); } mark(generatedLine, generatedColumn, line, column, identifierName, filename, force) { if (this._lastGenLine !== generatedLine && line === null) return; if (!force && this._lastGenLine === generatedLine && this._lastSourceLine === line && this._lastSourceColumn === column) { return; } this._cachedMap = null; this._lastGenLine = generatedLine; this._lastSourceLine = line; this._lastSourceColumn = column; this._rawMappings.push({ name: identifierName || undefined, generated: { line: generatedLine, column: generatedColumn }, source: line == null ? undefined : filename || this._opts.sourceFileName, original: line == null ? undefined : { line: line, column: column } }); } } exports.default = SourceMap; },{"source-map":449}],61:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = _default; function _helperGetFunctionArity() { const data = _interopRequireDefault(require("@babel/helper-get-function-arity")); _helperGetFunctionArity = function () { return data; }; return data; } function _template() { const data = _interopRequireDefault(require("@babel/template")); _template = function () { return data; }; return data; } function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const buildPropertyMethodAssignmentWrapper = (0, _template().default)(` (function (FUNCTION_KEY) { function FUNCTION_ID() { return FUNCTION_KEY.apply(this, arguments); } FUNCTION_ID.toString = function () { return FUNCTION_KEY.toString(); } return FUNCTION_ID; })(FUNCTION) `); const buildGeneratorPropertyMethodAssignmentWrapper = (0, _template().default)(` (function (FUNCTION_KEY) { function* FUNCTION_ID() { return yield* FUNCTION_KEY.apply(this, arguments); } FUNCTION_ID.toString = function () { return FUNCTION_KEY.toString(); }; return FUNCTION_ID; })(FUNCTION) `); const visitor = { "ReferencedIdentifier|BindingIdentifier"(path, state) { if (path.node.name !== state.name) return; const localDeclar = path.scope.getBindingIdentifier(state.name); if (localDeclar !== state.outerDeclar) return; state.selfReference = true; path.stop(); } }; function getNameFromLiteralId(id) { if (t().isNullLiteral(id)) { return "null"; } if (t().isRegExpLiteral(id)) { return `_${id.pattern}_${id.flags}`; } if (t().isTemplateLiteral(id)) { return id.quasis.map(quasi => quasi.value.raw).join(""); } if (id.value !== undefined) { return id.value + ""; } return ""; } function wrap(state, method, id, scope) { if (state.selfReference) { if (scope.hasBinding(id.name) && !scope.hasGlobal(id.name)) { scope.rename(id.name); } else { if (!t().isFunction(method)) return; let build = buildPropertyMethodAssignmentWrapper; if (method.generator) { build = buildGeneratorPropertyMethodAssignmentWrapper; } const template = build({ FUNCTION: method, FUNCTION_ID: id, FUNCTION_KEY: scope.generateUidIdentifier(id.name) }).expression; const params = template.callee.body.body[0].params; for (let i = 0, len = (0, _helperGetFunctionArity().default)(method); i < len; i++) { params.push(scope.generateUidIdentifier("x")); } return template; } } method.id = id; scope.getProgramParent().references[id.name] = true; } function visit(node, name, scope) { const state = { selfAssignment: false, selfReference: false, outerDeclar: scope.getBindingIdentifier(name), references: [], name: name }; const binding = scope.getOwnBinding(name); if (binding) { if (binding.kind === "param") { state.selfReference = true; } else {} } else if (state.outerDeclar || scope.hasGlobal(name)) { scope.traverse(node, visitor, state); } return state; } function _default({ node, parent, scope, id }, localBinding = false) { if (node.id) return; if ((t().isObjectProperty(parent) || t().isObjectMethod(parent, { kind: "method" })) && (!parent.computed || t().isLiteral(parent.key))) { id = parent.key; } else if (t().isVariableDeclarator(parent)) { id = parent.id; if (t().isIdentifier(id) && !localBinding) { const binding = scope.parent.getBinding(id.name); if (binding && binding.constant && scope.getBinding(id.name) === binding) { node.id = t().cloneNode(id); node.id[t().NOT_LOCAL_BINDING] = true; return; } } } else if (t().isAssignmentExpression(parent)) { id = parent.left; } else if (!id) { return; } let name; if (id && t().isLiteral(id)) { name = getNameFromLiteralId(id); } else if (id && t().isIdentifier(id)) { name = id.name; } if (name === undefined) { return; } name = t().toBindingIdentifierName(name); id = t().identifier(name); id[t().NOT_LOCAL_BINDING] = true; const state = visit(node, name, scope); return wrap(state, node, id, scope) || node; } },{"@babel/helper-get-function-arity":62,"@babel/template":70,"@babel/types":142}],62:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = _default; function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function _default(node) { const params = node.params; for (let i = 0; i < params.length; i++) { const param = params[i]; if (t().isAssignmentPattern(param) || t().isRestElement(param)) { return i; } } return params.length; } },{"@babel/types":142}],63:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = splitExportDeclaration; function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function splitExportDeclaration(exportDeclaration) { if (!exportDeclaration.isExportDeclaration()) { throw new Error("Only export declarations can be splitted."); } const isDefault = exportDeclaration.isExportDefaultDeclaration(); const declaration = exportDeclaration.get("declaration"); const isClassDeclaration = declaration.isClassDeclaration(); if (isDefault) { const standaloneDeclaration = declaration.isFunctionDeclaration() || isClassDeclaration; const scope = declaration.isScope() ? declaration.scope.parent : declaration.scope; let id = declaration.node.id; let needBindingRegistration = false; if (!id) { needBindingRegistration = true; id = scope.generateUidIdentifier("default"); if (standaloneDeclaration || declaration.isFunctionExpression() || declaration.isClassExpression()) { declaration.node.id = t().cloneNode(id); } } const updatedDeclaration = standaloneDeclaration ? declaration : t().variableDeclaration("var", [t().variableDeclarator(t().cloneNode(id), declaration.node)]); const updatedExportDeclaration = t().exportNamedDeclaration(null, [t().exportSpecifier(t().cloneNode(id), t().identifier("default"))]); exportDeclaration.insertAfter(updatedExportDeclaration); exportDeclaration.replaceWith(updatedDeclaration); if (needBindingRegistration) { scope.registerDeclaration(exportDeclaration); } return exportDeclaration; } if (exportDeclaration.get("specifiers").length > 0) { throw new Error("It doesn't make sense to split exported specifiers."); } const bindingIdentifiers = declaration.getOuterBindingIdentifiers(); const specifiers = Object.keys(bindingIdentifiers).map(name => { return t().exportSpecifier(t().identifier(name), t().identifier(name)); }); const aliasDeclar = t().exportNamedDeclaration(null, specifiers); exportDeclaration.insertAfter(aliasDeclar); exportDeclaration.replaceWith(declaration.node); return exportDeclaration; } },{"@babel/types":142}],64:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; function _template() { const data = _interopRequireDefault(require("@babel/template")); _template = function () { return data; }; return data; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const helpers = Object.create(null); var _default = helpers; exports.default = _default; const helper = minVersion => tpl => ({ minVersion, ast: () => _template().default.program.ast(tpl) }); helpers.typeof = helper("7.0.0-beta.0")` export default function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function (obj) { return typeof obj; }; } else { _typeof = function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } `; helpers.jsx = helper("7.0.0-beta.0")` var REACT_ELEMENT_TYPE; export default function _createRawReactElement(type, props, key, children) { if (!REACT_ELEMENT_TYPE) { REACT_ELEMENT_TYPE = ( typeof Symbol === "function" && Symbol.for && Symbol.for("react.element") ) || 0xeac7; } var defaultProps = type && type.defaultProps; var childrenLength = arguments.length - 3; if (!props && childrenLength !== 0) { // If we're going to assign props.children, we create a new object now // to avoid mutating defaultProps. props = { children: void 0, }; } if (props && defaultProps) { for (var propName in defaultProps) { if (props[propName] === void 0) { props[propName] = defaultProps[propName]; } } } else if (!props) { props = defaultProps || {}; } if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = new Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 3]; } props.children = childArray; } return { $$typeof: REACT_ELEMENT_TYPE, type: type, key: key === undefined ? null : '' + key, ref: null, props: props, _owner: null, }; } `; helpers.asyncIterator = helper("7.0.0-beta.0")` export default function _asyncIterator(iterable) { var method if (typeof Symbol !== "undefined") { if (Symbol.asyncIterator) { method = iterable[Symbol.asyncIterator] if (method != null) return method.call(iterable); } if (Symbol.iterator) { method = iterable[Symbol.iterator] if (method != null) return method.call(iterable); } } throw new TypeError("Object is not async iterable"); } `; helpers.AwaitValue = helper("7.0.0-beta.0")` export default function _AwaitValue(value) { this.wrapped = value; } `; helpers.AsyncGenerator = helper("7.0.0-beta.0")` import AwaitValue from "AwaitValue"; export default function AsyncGenerator(gen) { var front, back; function send(key, arg) { return new Promise(function (resolve, reject) { var request = { key: key, arg: arg, resolve: resolve, reject: reject, next: null, }; if (back) { back = back.next = request; } else { front = back = request; resume(key, arg); } }); } function resume(key, arg) { try { var result = gen[key](arg) var value = result.value; var wrappedAwait = value instanceof AwaitValue; Promise.resolve(wrappedAwait ? value.wrapped : value).then( function (arg) { if (wrappedAwait) { resume("next", arg); return } settle(result.done ? "return" : "normal", arg); }, function (err) { resume("throw", err); }); } catch (err) { settle("throw", err); } } function settle(type, value) { switch (type) { case "return": front.resolve({ value: value, done: true }); break; case "throw": front.reject(value); break; default: front.resolve({ value: value, done: false }); break; } front = front.next; if (front) { resume(front.key, front.arg); } else { back = null; } } this._invoke = send; // Hide "return" method if generator return is not supported if (typeof gen.return !== "function") { this.return = undefined; } } if (typeof Symbol === "function" && Symbol.asyncIterator) { AsyncGenerator.prototype[Symbol.asyncIterator] = function () { return this; }; } AsyncGenerator.prototype.next = function (arg) { return this._invoke("next", arg); }; AsyncGenerator.prototype.throw = function (arg) { return this._invoke("throw", arg); }; AsyncGenerator.prototype.return = function (arg) { return this._invoke("return", arg); }; `; helpers.wrapAsyncGenerator = helper("7.0.0-beta.0")` import AsyncGenerator from "AsyncGenerator"; export default function _wrapAsyncGenerator(fn) { return function () { return new AsyncGenerator(fn.apply(this, arguments)); }; } `; helpers.awaitAsyncGenerator = helper("7.0.0-beta.0")` import AwaitValue from "AwaitValue"; export default function _awaitAsyncGenerator(value) { return new AwaitValue(value); } `; helpers.asyncGeneratorDelegate = helper("7.0.0-beta.0")` export default function _asyncGeneratorDelegate(inner, awaitWrap) { var iter = {}, waiting = false; function pump(key, value) { waiting = true; value = new Promise(function (resolve) { resolve(inner[key](value)); }); return { done: false, value: awaitWrap(value) }; }; if (typeof Symbol === "function" && Symbol.iterator) { iter[Symbol.iterator] = function () { return this; }; } iter.next = function (value) { if (waiting) { waiting = false; return value; } return pump("next", value); }; if (typeof inner.throw === "function") { iter.throw = function (value) { if (waiting) { waiting = false; throw value; } return pump("throw", value); }; } if (typeof inner.return === "function") { iter.return = function (value) { return pump("return", value); }; } return iter; } `; helpers.asyncToGenerator = helper("7.0.0-beta.0")` function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } export default function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } `; helpers.classCallCheck = helper("7.0.0-beta.0")` export default function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } `; helpers.createClass = helper("7.0.0-beta.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); } } export default function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } `; helpers.defineEnumerableProperties = helper("7.0.0-beta.0")` export default function _defineEnumerableProperties(obj, descs) { for (var key in descs) { var desc = descs[key]; desc.configurable = desc.enumerable = true; if ("value" in desc) desc.writable = true; Object.defineProperty(obj, key, desc); } // Symbols are not enumerated over by for-in loops. If native // Symbols are available, fetch all of the descs object's own // symbol properties and define them on our target object too. if (Object.getOwnPropertySymbols) { var objectSymbols = Object.getOwnPropertySymbols(descs); for (var i = 0; i < objectSymbols.length; i++) { var sym = objectSymbols[i]; var desc = descs[sym]; desc.configurable = desc.enumerable = true; if ("value" in desc) desc.writable = true; Object.defineProperty(obj, sym, desc); } } return obj; } `; helpers.defaults = helper("7.0.0-beta.0")` export default function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; } `; helpers.defineProperty = helper("7.0.0-beta.0")` export default function _defineProperty(obj, key, value) { // Shortcircuit the slow defineProperty path when possible. // We are trying to avoid issues where setters defined on the // prototype cause side effects under the fast path of simple // assignment. By checking for existence of the property with // the in operator, we can optimize most of this overhead away. if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } `; helpers.extends = helper("7.0.0-beta.0")` export default 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); } `; helpers.objectSpread = helper("7.0.0-beta.0")` import defineProperty from "defineProperty"; export default function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = (arguments[i] != null) ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function(key) { defineProperty(target, key, source[key]); }); } return target; } `; helpers.inherits = helper("7.0.0-beta.0")` import setPrototypeOf from "setPrototypeOf"; export default function _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); } `; helpers.inheritsLoose = helper("7.0.0-beta.0")` export default function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } `; helpers.getPrototypeOf = helper("7.0.0-beta.0")` export default function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } `; helpers.setPrototypeOf = helper("7.0.0-beta.0")` export default function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } `; helpers.construct = helper("7.0.0-beta.0")` import setPrototypeOf from "setPrototypeOf"; function isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; // core-js@3 if (Reflect.construct.sham) return false; // Proxy can't be polyfilled. Every browser implemented // proxies before or at the same time as Reflect.construct, // so if they support Proxy they also support Reflect.construct. if (typeof Proxy === "function") return true; // Since Reflect.construct can't be properly polyfilled, some // implementations (e.g. core-js@2) don't set the correct internal slots. // Those polyfills don't allow us to subclass built-ins, so we need to // use our fallback implementation. try { // If the internal slots aren't set, this throws an error similar to // TypeError: this is not a Date object. Date.prototype.toString.call(Reflect.construct(Date, [], function() {})); return true; } catch (e) { return false; } } export default function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { // NOTE: If Parent !== Class, the correct __proto__ is set *after* // calling the constructor. _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; }; } // Avoid issues with Class being present but undefined when it wasn't // present in the original call. return _construct.apply(null, arguments); } `; helpers.isNativeFunction = helper("7.0.0-beta.0")` export default function _isNativeFunction(fn) { // Note: This function returns "true" for core-js functions. return Function.toString.call(fn).indexOf("[native code]") !== -1; } `; helpers.wrapNativeSuper = helper("7.0.0-beta.0")` import getPrototypeOf from "getPrototypeOf"; import setPrototypeOf from "setPrototypeOf"; import isNativeFunction from "isNativeFunction"; import construct from "construct"; export default 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) } `; helpers.instanceof = helper("7.0.0-beta.0")` export default function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return right[Symbol.hasInstance](left); } else { return left instanceof right; } } `; helpers.interopRequireDefault = helper("7.0.0-beta.0")` export default function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } `; helpers.interopRequireWildcard = helper("7.0.0-beta.0")` export default function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } `; helpers.newArrowCheck = helper("7.0.0-beta.0")` export default function _newArrowCheck(innerThis, boundThis) { if (innerThis !== boundThis) { throw new TypeError("Cannot instantiate an arrow function"); } } `; helpers.objectDestructuringEmpty = helper("7.0.0-beta.0")` export default function _objectDestructuringEmpty(obj) { if (obj == null) throw new TypeError("Cannot destructure undefined"); } `; helpers.objectWithoutPropertiesLoose = helper("7.0.0-beta.0")` export default 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; } `; helpers.objectWithoutProperties = helper("7.0.0-beta.0")` import objectWithoutPropertiesLoose from "objectWithoutPropertiesLoose"; export default function _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; } `; helpers.assertThisInitialized = helper("7.0.0-beta.0")` export default function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } `; helpers.possibleConstructorReturn = helper("7.0.0-beta.0")` import assertThisInitialized from "assertThisInitialized"; export default function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return assertThisInitialized(self); } `; helpers.superPropBase = helper("7.0.0-beta.0")` import getPrototypeOf from "getPrototypeOf"; export default function _superPropBase(object, property) { // Yes, this throws if object is null to being with, that's on purpose. while (!Object.prototype.hasOwnProperty.call(object, property)) { object = getPrototypeOf(object); if (object === null) break; } return object; } `; helpers.get = helper("7.0.0-beta.0")` import getPrototypeOf from "getPrototypeOf"; import superPropBase from "superPropBase"; export default function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } `; helpers.set = helper("7.0.0-beta.0")` import getPrototypeOf from "getPrototypeOf"; import superPropBase from "superPropBase"; import defineProperty from "defineProperty"; function set(target, property, value, receiver) { if (typeof Reflect !== "undefined" && Reflect.set) { set = Reflect.set; } else { set = function set(target, property, value, receiver) { var base = superPropBase(target, property); var desc; if (base) { desc = Object.getOwnPropertyDescriptor(base, property); if (desc.set) { desc.set.call(receiver, value); return true; } else if (!desc.writable) { // Both getter and non-writable fall into this. return false; } } // Without a super that defines the property, spec boils down to // "define on receiver" for some reason. desc = Object.getOwnPropertyDescriptor(receiver, property); if (desc) { if (!desc.writable) { // Setter, getter, and non-writable fall into this. return false; } desc.value = value; Object.defineProperty(receiver, property, desc); } else { // Avoid setters that may be defined on Sub's prototype, but not on // the instance. defineProperty(receiver, property, value); } return true; }; } return set(target, property, value, receiver); } export default function _set(target, property, value, receiver, isStrict) { var s = set(target, property, value, receiver || target); if (!s && isStrict) { throw new Error('failed to set property'); } return value; } `; helpers.taggedTemplateLiteral = helper("7.0.0-beta.0")` export default function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); } `; helpers.taggedTemplateLiteralLoose = helper("7.0.0-beta.0")` export default function _taggedTemplateLiteralLoose(strings, raw) { if (!raw) { raw = strings.slice(0); } strings.raw = raw; return strings; } `; helpers.temporalRef = helper("7.0.0-beta.0")` import undef from "temporalUndefined"; export default function _temporalRef(val, name) { if (val === undef) { throw new ReferenceError(name + " is not defined - temporal dead zone"); } else { return val; } } `; helpers.readOnlyError = helper("7.0.0-beta.0")` export default function _readOnlyError(name) { throw new Error("\\"" + name + "\\" is read-only"); } `; helpers.classNameTDZError = helper("7.0.0-beta.0")` export default function _classNameTDZError(name) { throw new Error("Class \\"" + name + "\\" cannot be referenced in computed property keys."); } `; helpers.temporalUndefined = helper("7.0.0-beta.0")` export default {}; `; helpers.slicedToArray = helper("7.0.0-beta.0")` import arrayWithHoles from "arrayWithHoles"; import iterableToArrayLimit from "iterableToArrayLimit"; import nonIterableRest from "nonIterableRest"; export default function _slicedToArray(arr, i) { return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || nonIterableRest(); } `; helpers.slicedToArrayLoose = helper("7.0.0-beta.0")` import arrayWithHoles from "arrayWithHoles"; import iterableToArrayLimitLoose from "iterableToArrayLimitLoose"; import nonIterableRest from "nonIterableRest"; export default function _slicedToArrayLoose(arr, i) { return arrayWithHoles(arr) || iterableToArrayLimitLoose(arr, i) || nonIterableRest(); } `; helpers.toArray = helper("7.0.0-beta.0")` import arrayWithHoles from "arrayWithHoles"; import iterableToArray from "iterableToArray"; import nonIterableRest from "nonIterableRest"; export default function _toArray(arr) { return arrayWithHoles(arr) || iterableToArray(arr) || nonIterableRest(); } `; helpers.toConsumableArray = helper("7.0.0-beta.0")` import arrayWithoutHoles from "arrayWithoutHoles"; import iterableToArray from "iterableToArray"; import nonIterableSpread from "nonIterableSpread"; export default function _toConsumableArray(arr) { return arrayWithoutHoles(arr) || iterableToArray(arr) || nonIterableSpread(); } `; helpers.arrayWithoutHoles = helper("7.0.0-beta.0")` export default function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } } `; helpers.arrayWithHoles = helper("7.0.0-beta.0")` export default function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } `; helpers.iterableToArray = helper("7.0.0-beta.0")` export default function _iterableToArray(iter) { if ( Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]" ) return Array.from(iter); } `; helpers.iterableToArrayLimit = helper("7.0.0-beta.0")` export default function _iterableToArrayLimit(arr, i) { // this is an expanded form of \`for...of\` that properly supports abrupt completions of // iterators etc. variable names have been minimised to reduce the size of this massive // helper. sometimes spec compliancy is annoying :( // // _n = _iteratorNormalCompletion // _d = _didIteratorError // _e = _iteratorError // _i = _iterator // _s = _step 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; } `; helpers.iterableToArrayLimitLoose = helper("7.0.0-beta.0")` export default function _iterableToArrayLimitLoose(arr, i) { var _arr = []; for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { _arr.push(_step.value); if (i && _arr.length === i) break; } return _arr; } `; helpers.nonIterableSpread = helper("7.0.0-beta.0")` export default function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } `; helpers.nonIterableRest = helper("7.0.0-beta.0")` export default function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } `; helpers.skipFirstGeneratorNext = helper("7.0.0-beta.0")` export default function _skipFirstGeneratorNext(fn) { return function () { var it = fn.apply(this, arguments); it.next(); return it; } } `; helpers.toPrimitive = helper("7.1.5")` export default function _toPrimitive( input, hint /*: "default" | "string" | "number" | void */ ) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } `; helpers.toPropertyKey = helper("7.1.5")` import toPrimitive from "toPrimitive"; export default function _toPropertyKey(arg) { var key = toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } `; helpers.initializerWarningHelper = helper("7.0.0-beta.0")` export default function _initializerWarningHelper(descriptor, context){ throw new Error( 'Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and set to use loose mode. ' + 'To use proposal-class-properties in spec mode with decorators, wait for ' + 'the next major version of decorators in stage 2.' ); } `; helpers.initializerDefineProperty = helper("7.0.0-beta.0")` export default function _initializerDefineProperty(target, property, descriptor, context){ if (!descriptor) return; Object.defineProperty(target, property, { enumerable: descriptor.enumerable, configurable: descriptor.configurable, writable: descriptor.writable, value: descriptor.initializer ? descriptor.initializer.call(context) : void 0, }); } `; helpers.applyDecoratedDescriptor = helper("7.0.0-beta.0")` export default function _applyDecoratedDescriptor(target, property, decorators, descriptor, context){ var desc = {}; Object.keys(descriptor).forEach(function(key){ desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer){ desc.writable = true; } desc = decorators.slice().reverse().reduce(function(desc, decorator){ return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0){ desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0){ // This is a hack to avoid this being processed by 'transform-runtime'. // See issue #9. Object.defineProperty(target, property, desc); desc = null; } return desc; } `; helpers.classPrivateFieldLooseKey = helper("7.0.0-beta.0")` var id = 0; export default function _classPrivateFieldKey(name) { return "__private_" + (id++) + "_" + name; } `; helpers.classPrivateFieldLooseBase = helper("7.0.0-beta.0")` export default function _classPrivateFieldBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError("attempted to use private field on non-instance"); } return receiver; } `; helpers.classPrivateFieldGet = helper("7.0.0-beta.0")` export default function _classPrivateFieldGet(receiver, privateMap) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } var descriptor = privateMap.get(receiver); if (descriptor.get) { return descriptor.get.call(receiver); } return descriptor.value; } `; helpers.classPrivateFieldSet = helper("7.0.0-beta.0")` export default function _classPrivateFieldSet(receiver, privateMap, value) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to set private field on non-instance"); } var descriptor = privateMap.get(receiver); if (descriptor.set) { descriptor.set.call(receiver, value); } else { if (!descriptor.writable) { // This should only throw in strict mode, but class bodies are // always strict and private fields can only be used inside // class bodies. throw new TypeError("attempted to set read only private field"); } descriptor.value = value; } return value; } `; helpers.classStaticPrivateFieldSpecGet = helper("7.0.2")` export default function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { if (receiver !== classConstructor) { throw new TypeError("Private static access of wrong provenance"); } return descriptor.value; } `; helpers.classStaticPrivateFieldSpecSet = helper("7.0.2")` export default function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { if (receiver !== classConstructor) { throw new TypeError("Private static access of wrong provenance"); } if (!descriptor.writable) { // This should only throw in strict mode, but class bodies are // always strict and private fields can only be used inside // class bodies. throw new TypeError("attempted to set read only private field"); } descriptor.value = value; return value; } `; helpers.classStaticPrivateMethodGet = helper("7.3.2")` export default function _classStaticPrivateMethodGet(receiver, classConstructor, method) { if (receiver !== classConstructor) { throw new TypeError("Private static access of wrong provenance"); } return method; } `; helpers.classStaticPrivateMethodSet = helper("7.3.2")` export default function _classStaticPrivateMethodSet() { throw new TypeError("attempted to set read only static private field"); } `; helpers.decorate = helper("7.1.5")` import toArray from "toArray"; import toPropertyKey from "toPropertyKey"; // These comments are stripped by @babel/template /*:: type PropertyDescriptor = | { value: any, writable: boolean, configurable: boolean, enumerable: boolean, } | { get?: () => any, set?: (v: any) => void, configurable: boolean, enumerable: boolean, }; type FieldDescriptor ={ writable: boolean, configurable: boolean, enumerable: boolean, }; type Placement = "static" | "prototype" | "own"; type Key = string | symbol; // PrivateName is not supported yet. type ElementDescriptor = | { kind: "method", key: Key, placement: Placement, descriptor: PropertyDescriptor } | { kind: "field", key: Key, placement: Placement, descriptor: FieldDescriptor, initializer?: () => any, }; // This is exposed to the user code type ElementObjectInput = ElementDescriptor & { [@@toStringTag]?: "Descriptor" }; // This is exposed to the user code type ElementObjectOutput = ElementDescriptor & { [@@toStringTag]?: "Descriptor" extras?: ElementDescriptor[], finisher?: ClassFinisher, }; // This is exposed to the user code type ClassObject = { [@@toStringTag]?: "Descriptor", kind: "class", elements: ElementDescriptor[], }; type ElementDecorator = (descriptor: ElementObjectInput) => ?ElementObjectOutput; type ClassDecorator = (descriptor: ClassObject) => ?ClassObject; type ClassFinisher = (cl: Class) => Class; // Only used by Babel in the transform output, not part of the spec. type ElementDefinition = | { kind: "method", value: any, key: Key, static?: boolean, decorators?: ElementDecorator[], } | { kind: "field", value: () => any, key: Key, static?: boolean, decorators?: ElementDecorator[], }; declare function ClassFactory(initialize: (instance: C) => void): { F: Class, d: ElementDefinition[] } */ /*:: // Various combinations with/without extras and with one or many finishers type ElementFinisherExtras = { element: ElementDescriptor, finisher?: ClassFinisher, extras?: ElementDescriptor[], }; type ElementFinishersExtras = { element: ElementDescriptor, finishers: ClassFinisher[], extras: ElementDescriptor[], }; type ElementsFinisher = { elements: ElementDescriptor[], finisher?: ClassFinisher, }; type ElementsFinishers = { elements: ElementDescriptor[], finishers: ClassFinisher[], }; */ /*:: type Placements = { static: Key[], prototype: Key[], own: Key[], }; */ // ClassDefinitionEvaluation (Steps 26-*) export default function _decorate( decorators /*: ClassDecorator[] */, factory /*: ClassFactory */, superClass /*: ?Class<*> */, mixins /*: ?Array */, ) /*: Class<*> */ { var api = _getDecoratorsApi(); if (mixins) { for (var i = 0; i < mixins.length; i++) { api = mixins[i](api); } } var r = factory(function initialize(O) { api.initializeInstanceElements(O, decorated.elements); }, superClass); var decorated = api.decorateClass( _coalesceClassElements(r.d.map(_createElementDescriptor)), decorators, ); api.initializeClassElements(r.F, decorated.elements); return api.runClassFinishers(r.F, decorated.finishers); } function _getDecoratorsApi() { _getDecoratorsApi = function() { return api; }; var api = { elementsDefinitionOrder: [["method"], ["field"]], // InitializeInstanceElements initializeInstanceElements: function( /*::*/ O /*: C */, elements /*: ElementDescriptor[] */, ) { ["method", "field"].forEach(function(kind) { elements.forEach(function(element /*: ElementDescriptor */) { if (element.kind === kind && element.placement === "own") { this.defineClassElement(O, element); } }, this); }, this); }, // InitializeClassElements initializeClassElements: function( /*::*/ F /*: Class */, elements /*: ElementDescriptor[] */, ) { var proto = F.prototype; ["method", "field"].forEach(function(kind) { elements.forEach(function(element /*: ElementDescriptor */) { var placement = element.placement; if ( element.kind === kind && (placement === "static" || placement === "prototype") ) { var receiver = placement === "static" ? F : proto; this.defineClassElement(receiver, element); } }, this); }, this); }, // DefineClassElement defineClassElement: function( /*::*/ receiver /*: C | Class */, element /*: ElementDescriptor */, ) { var descriptor /*: PropertyDescriptor */ = element.descriptor; if (element.kind === "field") { var initializer = element.initializer; descriptor = { enumerable: descriptor.enumerable, writable: descriptor.writable, configurable: descriptor.configurable, value: initializer === void 0 ? void 0 : initializer.call(receiver), }; } Object.defineProperty(receiver, element.key, descriptor); }, // DecorateClass decorateClass: function( elements /*: ElementDescriptor[] */, decorators /*: ClassDecorator[] */, ) /*: ElementsFinishers */ { var newElements /*: ElementDescriptor[] */ = []; var finishers /*: ClassFinisher[] */ = []; var placements /*: Placements */ = { static: [], prototype: [], own: [], }; elements.forEach(function(element /*: ElementDescriptor */) { this.addElementPlacement(element, placements); }, this); elements.forEach(function(element /*: ElementDescriptor */) { if (!_hasDecorators(element)) return newElements.push(element); var elementFinishersExtras /*: ElementFinishersExtras */ = this.decorateElement( element, placements, ); newElements.push(elementFinishersExtras.element); newElements.push.apply(newElements, elementFinishersExtras.extras); finishers.push.apply(finishers, elementFinishersExtras.finishers); }, this); if (!decorators) { return { elements: newElements, finishers: finishers }; } var result /*: ElementsFinishers */ = this.decorateConstructor( newElements, decorators, ); finishers.push.apply(finishers, result.finishers); result.finishers = finishers; return result; }, // AddElementPlacement addElementPlacement: function( element /*: ElementDescriptor */, placements /*: Placements */, silent /*: boolean */, ) { var keys = placements[element.placement]; if (!silent && keys.indexOf(element.key) !== -1) { throw new TypeError("Duplicated element (" + element.key + ")"); } keys.push(element.key); }, // DecorateElement decorateElement: function( element /*: ElementDescriptor */, placements /*: Placements */, ) /*: ElementFinishersExtras */ { var extras /*: ElementDescriptor[] */ = []; var finishers /*: ClassFinisher[] */ = []; for ( var decorators = element.decorators, i = decorators.length - 1; i >= 0; i-- ) { // (inlined) RemoveElementPlacement var keys = placements[element.placement]; keys.splice(keys.indexOf(element.key), 1); var elementObject /*: ElementObjectInput */ = this.fromElementDescriptor( element, ); var elementFinisherExtras /*: ElementFinisherExtras */ = this.toElementFinisherExtras( (0, decorators[i])(elementObject) /*: ElementObjectOutput */ || elementObject, ); element = elementFinisherExtras.element; this.addElementPlacement(element, placements); if (elementFinisherExtras.finisher) { finishers.push(elementFinisherExtras.finisher); } var newExtras /*: ElementDescriptor[] | void */ = elementFinisherExtras.extras; if (newExtras) { for (var j = 0; j < newExtras.length; j++) { this.addElementPlacement(newExtras[j], placements); } extras.push.apply(extras, newExtras); } } return { element: element, finishers: finishers, extras: extras }; }, // DecorateConstructor decorateConstructor: function( elements /*: ElementDescriptor[] */, decorators /*: ClassDecorator[] */, ) /*: ElementsFinishers */ { var finishers /*: ClassFinisher[] */ = []; for (var i = decorators.length - 1; i >= 0; i--) { var obj /*: ClassObject */ = this.fromClassDescriptor(elements); var elementsAndFinisher /*: ElementsFinisher */ = this.toClassDescriptor( (0, decorators[i])(obj) /*: ClassObject */ || obj, ); if (elementsAndFinisher.finisher !== undefined) { finishers.push(elementsAndFinisher.finisher); } if (elementsAndFinisher.elements !== undefined) { elements = elementsAndFinisher.elements; for (var j = 0; j < elements.length - 1; j++) { for (var k = j + 1; k < elements.length; k++) { if ( elements[j].key === elements[k].key && elements[j].placement === elements[k].placement ) { throw new TypeError( "Duplicated element (" + elements[j].key + ")", ); } } } } } return { elements: elements, finishers: finishers }; }, // FromElementDescriptor fromElementDescriptor: function( element /*: ElementDescriptor */, ) /*: ElementObject */ { var obj /*: ElementObject */ = { kind: element.kind, key: element.key, placement: element.placement, descriptor: element.descriptor, }; var desc = { value: "Descriptor", configurable: true, }; Object.defineProperty(obj, Symbol.toStringTag, desc); if (element.kind === "field") obj.initializer = element.initializer; return obj; }, // ToElementDescriptors toElementDescriptors: function( elementObjects /*: ElementObject[] */, ) /*: ElementDescriptor[] */ { if (elementObjects === undefined) return; return toArray(elementObjects).map(function(elementObject) { var element = this.toElementDescriptor(elementObject); this.disallowProperty(elementObject, "finisher", "An element descriptor"); this.disallowProperty(elementObject, "extras", "An element descriptor"); return element; }, this); }, // ToElementDescriptor toElementDescriptor: function( elementObject /*: ElementObject */, ) /*: ElementDescriptor */ { var kind = String(elementObject.kind); if (kind !== "method" && kind !== "field") { throw new TypeError( 'An element descriptor\\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"', ); } var key = toPropertyKey(elementObject.key); var placement = String(elementObject.placement); if ( placement !== "static" && placement !== "prototype" && placement !== "own" ) { throw new TypeError( 'An element descriptor\\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"', ); } var descriptor /*: PropertyDescriptor */ = elementObject.descriptor; this.disallowProperty(elementObject, "elements", "An element descriptor"); var element /*: ElementDescriptor */ = { kind: kind, key: key, placement: placement, descriptor: Object.assign({}, descriptor), }; if (kind !== "field") { this.disallowProperty(elementObject, "initializer", "A method descriptor"); } else { this.disallowProperty( descriptor, "get", "The property descriptor of a field descriptor", ); this.disallowProperty( descriptor, "set", "The property descriptor of a field descriptor", ); this.disallowProperty( descriptor, "value", "The property descriptor of a field descriptor", ); element.initializer = elementObject.initializer; } return element; }, toElementFinisherExtras: function( elementObject /*: ElementObject */, ) /*: ElementFinisherExtras */ { var element /*: ElementDescriptor */ = this.toElementDescriptor( elementObject, ); var finisher /*: ClassFinisher */ = _optionalCallableProperty( elementObject, "finisher", ); var extras /*: ElementDescriptors[] */ = this.toElementDescriptors( elementObject.extras, ); return { element: element, finisher: finisher, extras: extras }; }, // FromClassDescriptor fromClassDescriptor: function( elements /*: ElementDescriptor[] */, ) /*: ClassObject */ { var obj = { kind: "class", elements: elements.map(this.fromElementDescriptor, this), }; var desc = { value: "Descriptor", configurable: true }; Object.defineProperty(obj, Symbol.toStringTag, desc); return obj; }, // ToClassDescriptor toClassDescriptor: function( obj /*: ClassObject */, ) /*: ElementsFinisher */ { var kind = String(obj.kind); if (kind !== "class") { throw new TypeError( 'A class descriptor\\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"', ); } this.disallowProperty(obj, "key", "A class descriptor"); this.disallowProperty(obj, "placement", "A class descriptor"); this.disallowProperty(obj, "descriptor", "A class descriptor"); this.disallowProperty(obj, "initializer", "A class descriptor"); this.disallowProperty(obj, "extras", "A class descriptor"); var finisher = _optionalCallableProperty(obj, "finisher"); var elements = this.toElementDescriptors(obj.elements); return { elements: elements, finisher: finisher }; }, // RunClassFinishers runClassFinishers: function( constructor /*: Class<*> */, finishers /*: ClassFinisher[] */, ) /*: Class<*> */ { for (var i = 0; i < finishers.length; i++) { var newConstructor /*: ?Class<*> */ = (0, finishers[i])(constructor); if (newConstructor !== undefined) { // NOTE: This should check if IsConstructor(newConstructor) is false. if (typeof newConstructor !== "function") { throw new TypeError("Finishers must return a constructor."); } constructor = newConstructor; } } return constructor; }, disallowProperty: function(obj, name, objectType) { if (obj[name] !== undefined) { throw new TypeError(objectType + " can't have a ." + name + " property."); } } }; return api; } // ClassElementEvaluation function _createElementDescriptor( def /*: ElementDefinition */, ) /*: ElementDescriptor */ { var key = toPropertyKey(def.key); var descriptor /*: PropertyDescriptor */; if (def.kind === "method") { descriptor = { value: def.value, writable: true, configurable: true, enumerable: false, }; } else if (def.kind === "get") { descriptor = { get: def.value, configurable: true, enumerable: false }; } else if (def.kind === "set") { descriptor = { set: def.value, configurable: true, enumerable: false }; } else if (def.kind === "field") { descriptor = { configurable: true, writable: true, enumerable: true }; } var element /*: ElementDescriptor */ = { kind: def.kind === "field" ? "field" : "method", key: key, placement: def.static ? "static" : def.kind === "field" ? "own" : "prototype", descriptor: descriptor, }; if (def.decorators) element.decorators = def.decorators; if (def.kind === "field") element.initializer = def.value; return element; } // CoalesceGetterSetter function _coalesceGetterSetter( element /*: ElementDescriptor */, other /*: ElementDescriptor */, ) { if (element.descriptor.get !== undefined) { other.descriptor.get = element.descriptor.get; } else { other.descriptor.set = element.descriptor.set; } } // CoalesceClassElements function _coalesceClassElements( elements /*: ElementDescriptor[] */, ) /*: ElementDescriptor[] */ { var newElements /*: ElementDescriptor[] */ = []; var isSameElement = function( other /*: ElementDescriptor */, ) /*: boolean */ { return ( other.kind === "method" && other.key === element.key && other.placement === element.placement ); }; for (var i = 0; i < elements.length; i++) { var element /*: ElementDescriptor */ = elements[i]; var other /*: ElementDescriptor */; if ( element.kind === "method" && (other = newElements.find(isSameElement)) ) { if ( _isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor) ) { if (_hasDecorators(element) || _hasDecorators(other)) { throw new ReferenceError( "Duplicated methods (" + element.key + ") can't be decorated.", ); } other.descriptor = element.descriptor; } else { if (_hasDecorators(element)) { if (_hasDecorators(other)) { throw new ReferenceError( "Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ").", ); } other.decorators = element.decorators; } _coalesceGetterSetter(element, other); } } else { newElements.push(element); } } return newElements; } function _hasDecorators(element /*: ElementDescriptor */) /*: boolean */ { return element.decorators && element.decorators.length; } function _isDataDescriptor(desc /*: PropertyDescriptor */) /*: boolean */ { return ( desc !== undefined && !(desc.value === undefined && desc.writable === undefined) ); } function _optionalCallableProperty /*::*/( obj /*: T */, name /*: $Keys */, ) /*: ?Function */ { var value = obj[name]; if (value !== undefined && typeof value !== "function") { throw new TypeError("Expected '" + name + "' to be a function"); } return value; } `; helpers.classPrivateMethodGet = helper("7.1.6")` export default function _classPrivateMethodGet(receiver, privateSet, fn) { if (!privateSet.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } return fn; } `; helpers.classPrivateMethodSet = helper("7.1.6")` export default function _classPrivateMethodSet() { throw new TypeError("attempted to reassign private method"); } `; helpers.wrapRegExp = helper("7.2.6")` import wrapNativeSuper from "wrapNativeSuper"; import getPrototypeOf from "getPrototypeOf"; import possibleConstructorReturn from "possibleConstructorReturn"; import inherits from "inherits"; export default function _wrapRegExp(re, groups) { _wrapRegExp = function(re, groups) { return new BabelRegExp(re, groups); }; var _RegExp = wrapNativeSuper(RegExp); var _super = RegExp.prototype; var _groups = new WeakMap(); function BabelRegExp(re, groups) { var _this = _RegExp.call(this, re); _groups.set(_this, groups); return _this; } inherits(BabelRegExp, _RegExp); BabelRegExp.prototype.exec = function(str) { var result = _super.exec.call(this, str); if (result) result.groups = buildGroups(result, this); return result; }; BabelRegExp.prototype[Symbol.replace] = function(str, substitution) { if (typeof substitution === "string") { var groups = _groups.get(this); return _super[Symbol.replace].call( this, str, substitution.replace(/\\$<([^>]+)>/g, function(_, name) { return "$" + groups[name]; }) ); } else if (typeof substitution === "function") { var _this = this; return _super[Symbol.replace].call( this, str, function() { var args = []; args.push.apply(args, arguments); if (typeof args[args.length - 1] !== "object") { // Modern engines already pass result.groups as the last arg. args.push(buildGroups(args, _this)); } return substitution.apply(this, args); } ); } else { return _super[Symbol.replace].call(this, str, substitution); } } function buildGroups(result, re) { // NOTE: This function should return undefined if there are no groups, // but in that case Babel doesn't add the wrapper anyway. var g = _groups.get(re); return Object.keys(g).reduce(function(groups, name) { groups[name] = result[g[name]]; return groups; }, Object.create(null)); } return _wrapRegExp.apply(this, arguments); } `; },{"@babel/template":70}],65:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.get = get; exports.minVersion = minVersion; exports.getDependencies = getDependencies; exports.default = exports.list = void 0; function _traverse() { const data = _interopRequireDefault(require("@babel/traverse")); _traverse = function () { return data; }; return data; } function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } var _helpers = _interopRequireDefault(require("./helpers")); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function makePath(path) { const parts = []; for (; path.parentPath; path = path.parentPath) { parts.push(path.key); if (path.inList) parts.push(path.listKey); } return parts.reverse().join("."); } function getHelperMetadata(file) { const globals = new Set(); const localBindingNames = new Set(); const dependencies = new Map(); let exportName; let exportPath; const exportBindingAssignments = []; const importPaths = []; const importBindingsReferences = []; (0, _traverse().default)(file, { ImportDeclaration(child) { const name = child.node.source.value; if (!_helpers.default[name]) { throw child.buildCodeFrameError(`Unknown helper ${name}`); } if (child.get("specifiers").length !== 1 || !child.get("specifiers.0").isImportDefaultSpecifier()) { throw child.buildCodeFrameError("Helpers can only import a default value"); } const bindingIdentifier = child.node.specifiers[0].local; dependencies.set(bindingIdentifier, name); importPaths.push(makePath(child)); }, ExportDefaultDeclaration(child) { const decl = child.get("declaration"); if (decl.isFunctionDeclaration()) { if (!decl.node.id) { throw decl.buildCodeFrameError("Helpers should give names to their exported func declaration"); } exportName = decl.node.id.name; } exportPath = makePath(child); }, ExportAllDeclaration(child) { throw child.buildCodeFrameError("Helpers can only export default"); }, ExportNamedDeclaration(child) { throw child.buildCodeFrameError("Helpers can only export default"); }, Statement(child) { if (child.isModuleDeclaration()) return; child.skip(); } }); (0, _traverse().default)(file, { Program(path) { const bindings = path.scope.getAllBindings(); Object.keys(bindings).forEach(name => { if (name === exportName) return; if (dependencies.has(bindings[name].identifier)) return; localBindingNames.add(name); }); }, ReferencedIdentifier(child) { const name = child.node.name; const binding = child.scope.getBinding(name, true); if (!binding) { globals.add(name); } else if (dependencies.has(binding.identifier)) { importBindingsReferences.push(makePath(child)); } }, AssignmentExpression(child) { const left = child.get("left"); if (!(exportName in left.getBindingIdentifiers())) return; if (!left.isIdentifier()) { throw left.buildCodeFrameError("Only simple assignments to exports are allowed in helpers"); } const binding = child.scope.getBinding(exportName); if (binding && binding.scope.path.isProgram()) { exportBindingAssignments.push(makePath(child)); } } }); if (!exportPath) throw new Error("Helpers must default-export something."); exportBindingAssignments.reverse(); return { globals: Array.from(globals), localBindingNames: Array.from(localBindingNames), dependencies, exportBindingAssignments, exportPath, exportName, importBindingsReferences, importPaths }; } function permuteHelperAST(file, metadata, id, localBindings, getDependency) { if (localBindings && !id) { throw new Error("Unexpected local bindings for module-based helpers."); } if (!id) return; const { localBindingNames, dependencies, exportBindingAssignments, exportPath, exportName, importBindingsReferences, importPaths } = metadata; const dependenciesRefs = {}; dependencies.forEach((name, id) => { dependenciesRefs[id.name] = typeof getDependency === "function" && getDependency(name) || id; }); const toRename = {}; const bindings = new Set(localBindings || []); localBindingNames.forEach(name => { let newName = name; while (bindings.has(newName)) newName = "_" + newName; if (newName !== name) toRename[name] = newName; }); if (id.type === "Identifier" && exportName !== id.name) { toRename[exportName] = id.name; } (0, _traverse().default)(file, { Program(path) { const exp = path.get(exportPath); const imps = importPaths.map(p => path.get(p)); const impsBindingRefs = importBindingsReferences.map(p => path.get(p)); const decl = exp.get("declaration"); if (id.type === "Identifier") { if (decl.isFunctionDeclaration()) { exp.replaceWith(decl); } else { exp.replaceWith(t().variableDeclaration("var", [t().variableDeclarator(id, decl.node)])); } } else if (id.type === "MemberExpression") { if (decl.isFunctionDeclaration()) { exportBindingAssignments.forEach(assignPath => { const assign = path.get(assignPath); assign.replaceWith(t().assignmentExpression("=", id, assign.node)); }); exp.replaceWith(decl); path.pushContainer("body", t().expressionStatement(t().assignmentExpression("=", id, t().identifier(exportName)))); } else { exp.replaceWith(t().expressionStatement(t().assignmentExpression("=", id, decl.node))); } } else { throw new Error("Unexpected helper format."); } Object.keys(toRename).forEach(name => { path.scope.rename(name, toRename[name]); }); for (const path of imps) path.remove(); for (const path of impsBindingRefs) { const node = t().cloneNode(dependenciesRefs[path.node.name]); path.replaceWith(node); } path.stop(); } }); } const helperData = Object.create(null); function loadHelper(name) { if (!helperData[name]) { const helper = _helpers.default[name]; if (!helper) { throw Object.assign(new ReferenceError(`Unknown helper ${name}`), { code: "BABEL_HELPER_UNKNOWN", helper: name }); } const fn = () => { return t().file(helper.ast()); }; const metadata = getHelperMetadata(fn()); helperData[name] = { build(getDependency, id, localBindings) { const file = fn(); permuteHelperAST(file, metadata, id, localBindings, getDependency); return { nodes: file.program.body, globals: metadata.globals }; }, minVersion() { return helper.minVersion; }, dependencies: metadata.dependencies }; } return helperData[name]; } function get(name, getDependency, id, localBindings) { return loadHelper(name).build(getDependency, id, localBindings); } function minVersion(name) { return loadHelper(name).minVersion(); } function getDependencies(name) { return Array.from(loadHelper(name).dependencies.values()); } const list = Object.keys(_helpers.default).map(name => name.replace(/^_/, "")).filter(name => name !== "__esModule"); exports.list = list; var _default = get; exports.default = _default; },{"./helpers":64,"@babel/traverse":79,"@babel/types":142}],66:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.shouldHighlight = shouldHighlight; exports.getChalk = getChalk; exports.default = highlight; function _jsTokens() { const data = _interopRequireWildcard(require("js-tokens")); _jsTokens = function () { return data; }; return data; } function _esutils() { const data = _interopRequireDefault(require("esutils")); _esutils = function () { return data; }; return data; } function _chalk() { const data = _interopRequireDefault(require("chalk")); _chalk = function () { return data; }; return data; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function getDefs(chalk) { return { keyword: chalk.cyan, capitalized: chalk.yellow, jsx_tag: chalk.yellow, punctuator: chalk.yellow, number: chalk.magenta, string: chalk.green, regex: chalk.magenta, comment: chalk.grey, invalid: chalk.white.bgRed.bold }; } const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; const JSX_TAG = /^[a-z][\w-]*$/i; const BRACKET = /^[()[\]{}]$/; function getTokenType(match) { const [offset, text] = match.slice(-2); const token = (0, _jsTokens().matchToToken)(match); if (token.type === "name") { if (_esutils().default.keyword.isReservedWordES6(token.value)) { return "keyword"; } if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == " colorize(str)).join("\n"); } else { return args[0]; } }); } function shouldHighlight(options) { return _chalk().default.supportsColor || options.forceColor; } function getChalk(options) { let chalk = _chalk().default; if (options.forceColor) { chalk = new (_chalk().default.constructor)({ enabled: true, level: 1 }); } return chalk; } function highlight(code, options = {}) { if (shouldHighlight(options)) { const chalk = getChalk(options); const defs = getDefs(chalk); return highlightTokens(defs, code); } else { return code; } } },{"chalk":183,"esutils":198,"js-tokens":206}],67:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); const beforeExpr = true; const startsExpr = true; const isLoop = true; const isAssign = true; const prefix = true; const postfix = true; class TokenType { constructor(label, conf = {}) { this.label = label; this.keyword = conf.keyword; this.beforeExpr = !!conf.beforeExpr; this.startsExpr = !!conf.startsExpr; this.rightAssociative = !!conf.rightAssociative; this.isLoop = !!conf.isLoop; this.isAssign = !!conf.isAssign; this.prefix = !!conf.prefix; this.postfix = !!conf.postfix; this.binop = conf.binop != null ? conf.binop : null; this.updateContext = null; } } const keywords = new Map(); function createKeyword(name, options = {}) { options.keyword = name; const token = new TokenType(name, options); keywords.set(name, token); return token; } function createBinop(name, binop) { return new TokenType(name, { beforeExpr, binop }); } const types = { num: new TokenType("num", { startsExpr }), bigint: new TokenType("bigint", { startsExpr }), regexp: new TokenType("regexp", { startsExpr }), string: new TokenType("string", { startsExpr }), name: new TokenType("name", { startsExpr }), eof: new TokenType("eof"), bracketL: new TokenType("[", { beforeExpr, startsExpr }), bracketR: new TokenType("]"), braceL: new TokenType("{", { beforeExpr, startsExpr }), braceBarL: new TokenType("{|", { beforeExpr, startsExpr }), braceR: new TokenType("}"), braceBarR: new TokenType("|}"), parenL: new TokenType("(", { beforeExpr, startsExpr }), parenR: new TokenType(")"), comma: new TokenType(",", { beforeExpr }), semi: new TokenType(";", { beforeExpr }), colon: new TokenType(":", { beforeExpr }), doubleColon: new TokenType("::", { beforeExpr }), dot: new TokenType("."), question: new TokenType("?", { beforeExpr }), questionDot: new TokenType("?."), arrow: new TokenType("=>", { beforeExpr }), template: new TokenType("template"), ellipsis: new TokenType("...", { beforeExpr }), backQuote: new TokenType("`", { startsExpr }), dollarBraceL: new TokenType("${", { beforeExpr, startsExpr }), at: new TokenType("@"), hash: new TokenType("#", { startsExpr }), interpreterDirective: new TokenType("#!..."), eq: new TokenType("=", { beforeExpr, isAssign }), assign: new TokenType("_=", { beforeExpr, isAssign }), incDec: new TokenType("++/--", { prefix, postfix, startsExpr }), bang: new TokenType("!", { beforeExpr, prefix, startsExpr }), tilde: new TokenType("~", { beforeExpr, prefix, startsExpr }), pipeline: createBinop("|>", 0), nullishCoalescing: createBinop("??", 1), logicalOR: createBinop("||", 1), logicalAND: createBinop("&&", 2), bitwiseOR: createBinop("|", 3), bitwiseXOR: createBinop("^", 4), bitwiseAND: createBinop("&", 5), equality: createBinop("==/!=/===/!==", 6), relational: createBinop("/<=/>=", 7), bitShift: createBinop("<>/>>>", 8), plusMin: new TokenType("+/-", { beforeExpr, binop: 9, prefix, startsExpr }), modulo: createBinop("%", 10), star: createBinop("*", 10), slash: createBinop("/", 10), exponent: new TokenType("**", { beforeExpr, binop: 11, rightAssociative: true }), _break: createKeyword("break"), _case: createKeyword("case", { beforeExpr }), _catch: createKeyword("catch"), _continue: createKeyword("continue"), _debugger: createKeyword("debugger"), _default: createKeyword("default", { beforeExpr }), _do: createKeyword("do", { isLoop, beforeExpr }), _else: createKeyword("else", { beforeExpr }), _finally: createKeyword("finally"), _for: createKeyword("for", { isLoop }), _function: createKeyword("function", { startsExpr }), _if: createKeyword("if"), _return: createKeyword("return", { beforeExpr }), _switch: createKeyword("switch"), _throw: createKeyword("throw", { beforeExpr, prefix, startsExpr }), _try: createKeyword("try"), _var: createKeyword("var"), _const: createKeyword("const"), _while: createKeyword("while", { isLoop }), _with: createKeyword("with"), _new: createKeyword("new", { beforeExpr, startsExpr }), _this: createKeyword("this", { startsExpr }), _super: createKeyword("super", { startsExpr }), _class: createKeyword("class", { startsExpr }), _extends: createKeyword("extends", { beforeExpr }), _export: createKeyword("export"), _import: createKeyword("import", { startsExpr }), _null: createKeyword("null", { startsExpr }), _true: createKeyword("true", { startsExpr }), _false: createKeyword("false", { startsExpr }), _in: createKeyword("in", { beforeExpr, binop: 7 }), _instanceof: createKeyword("instanceof", { beforeExpr, binop: 7 }), _typeof: createKeyword("typeof", { beforeExpr, prefix, startsExpr }), _void: createKeyword("void", { beforeExpr, prefix, startsExpr }), _delete: createKeyword("delete", { beforeExpr, prefix, startsExpr }) }; const SCOPE_OTHER = 0b000000000, SCOPE_PROGRAM = 0b000000001, SCOPE_FUNCTION = 0b000000010, SCOPE_ASYNC = 0b000000100, SCOPE_GENERATOR = 0b000001000, SCOPE_ARROW = 0b000010000, SCOPE_SIMPLE_CATCH = 0b000100000, SCOPE_SUPER = 0b001000000, SCOPE_DIRECT_SUPER = 0b010000000, SCOPE_CLASS = 0b100000000, SCOPE_VAR = SCOPE_PROGRAM | SCOPE_FUNCTION; function functionFlags(isAsync, isGenerator) { return SCOPE_FUNCTION | (isAsync ? SCOPE_ASYNC : 0) | (isGenerator ? SCOPE_GENERATOR : 0); } const BIND_KIND_VALUE = 0b00000000001, BIND_KIND_TYPE = 0b00000000010, BIND_SCOPE_VAR = 0b00000000100, BIND_SCOPE_LEXICAL = 0b00000001000, BIND_SCOPE_FUNCTION = 0b00000010000, BIND_FLAGS_NONE = 0b00001000000, BIND_FLAGS_CLASS = 0b00010000000, BIND_FLAGS_TS_ENUM = 0b00100000000, BIND_FLAGS_TS_CONST_ENUM = 0b01000000000, BIND_FLAGS_TS_EXPORT_ONLY = 0b10000000000; const BIND_CLASS = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_CLASS, BIND_LEXICAL = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | 0, BIND_VAR = BIND_KIND_VALUE | 0 | BIND_SCOPE_VAR | 0, BIND_FUNCTION = BIND_KIND_VALUE | 0 | BIND_SCOPE_FUNCTION | 0, BIND_TS_INTERFACE = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_CLASS, BIND_TS_TYPE = 0 | BIND_KIND_TYPE | 0 | 0, BIND_TS_ENUM = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_TS_ENUM, BIND_TS_FN_TYPE = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY, BIND_NONE = 0 | 0 | 0 | BIND_FLAGS_NONE, BIND_OUTSIDE = BIND_KIND_VALUE | 0 | 0 | BIND_FLAGS_NONE, BIND_TS_CONST_ENUM = BIND_TS_ENUM | BIND_FLAGS_TS_CONST_ENUM, BIND_TS_NAMESPACE = BIND_TS_FN_TYPE; function isSimpleProperty(node) { return node != null && node.type === "Property" && node.kind === "init" && node.method === false; } var estree = (superClass => class extends superClass { estreeParseRegExpLiteral({ pattern, flags }) { let regex = null; try { regex = new RegExp(pattern, flags); } catch (e) {} const node = this.estreeParseLiteral(regex); node.regex = { pattern, flags }; return node; } estreeParseLiteral(value) { return this.parseLiteral(value, "Literal"); } directiveToStmt(directive) { const directiveLiteral = directive.value; const stmt = this.startNodeAt(directive.start, directive.loc.start); const expression = this.startNodeAt(directiveLiteral.start, directiveLiteral.loc.start); expression.value = directiveLiteral.value; expression.raw = directiveLiteral.extra.raw; stmt.expression = this.finishNodeAt(expression, "Literal", directiveLiteral.end, directiveLiteral.loc.end); stmt.directive = directiveLiteral.extra.raw.slice(1, -1); return this.finishNodeAt(stmt, "ExpressionStatement", directive.end, directive.loc.end); } initFunction(node, isAsync) { super.initFunction(node, isAsync); node.expression = false; } checkDeclaration(node) { if (isSimpleProperty(node)) { this.checkDeclaration(node.value); } else { super.checkDeclaration(node); } } checkGetterSetterParams(method) { const prop = method; const paramCount = prop.kind === "get" ? 0 : 1; const start = prop.start; if (prop.value.params.length !== paramCount) { if (prop.kind === "get") { this.raise(start, "getter must not have any formal parameters"); } else { this.raise(start, "setter must have exactly one formal parameter"); } } if (prop.kind === "set" && prop.value.params[0].type === "RestElement") { this.raise(start, "setter function argument must not be a rest parameter"); } } checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription) { switch (expr.type) { case "ObjectPattern": expr.properties.forEach(prop => { this.checkLVal(prop.type === "Property" ? prop.value : prop, bindingType, checkClashes, "object destructuring pattern"); }); break; default: super.checkLVal(expr, bindingType, checkClashes, contextDescription); } } checkPropClash(prop, propHash) { if (prop.type === "SpreadElement" || prop.computed || prop.method || prop.shorthand) { return; } const key = prop.key; const name = key.type === "Identifier" ? key.name : String(key.value); if (name === "__proto__" && prop.kind === "init") { if (propHash.proto) { this.raise(key.start, "Redefinition of __proto__ property"); } propHash.proto = true; } } isStrictBody(node) { const isBlockStatement = node.body.type === "BlockStatement"; if (isBlockStatement && node.body.body.length > 0) { for (let _i = 0, _node$body$body = node.body.body; _i < _node$body$body.length; _i++) { const directive = _node$body$body[_i]; if (directive.type === "ExpressionStatement" && directive.expression.type === "Literal") { if (directive.expression.value === "use strict") return true; } else { break; } } } return false; } isValidDirective(stmt) { return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && (!stmt.expression.extra || !stmt.expression.extra.parenthesized); } stmtToDirective(stmt) { const directive = super.stmtToDirective(stmt); const value = stmt.expression.value; directive.value.value = value; return directive; } parseBlockBody(node, allowDirectives, topLevel, end) { super.parseBlockBody(node, allowDirectives, topLevel, end); const directiveStatements = node.directives.map(d => this.directiveToStmt(d)); node.body = directiveStatements.concat(node.body); delete node.directives; } pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true); if (method.typeParameters) { method.value.typeParameters = method.typeParameters; delete method.typeParameters; } classBody.body.push(method); } parseExprAtom(refShorthandDefaultPos) { switch (this.state.type) { case types.regexp: return this.estreeParseRegExpLiteral(this.state.value); case types.num: case types.string: return this.estreeParseLiteral(this.state.value); case types._null: return this.estreeParseLiteral(null); case types._true: return this.estreeParseLiteral(true); case types._false: return this.estreeParseLiteral(false); default: return super.parseExprAtom(refShorthandDefaultPos); } } parseLiteral(value, type, startPos, startLoc) { const node = super.parseLiteral(value, type, startPos, startLoc); node.raw = node.extra.raw; delete node.extra; return node; } parseFunctionBody(node, allowExpression, isMethod = false) { super.parseFunctionBody(node, allowExpression, isMethod); node.expression = node.body.type !== "BlockStatement"; } parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) { let funcNode = this.startNode(); funcNode.kind = node.kind; funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope); funcNode.type = "FunctionExpression"; delete funcNode.kind; node.value = funcNode; type = type === "ClassMethod" ? "MethodDefinition" : type; return this.finishNode(node, type); } parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc) { const node = super.parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc); if (node) { node.type = "Property"; if (node.kind === "method") node.kind = "init"; node.shorthand = false; } return node; } parseObjectProperty(prop, startPos, startLoc, isPattern, refShorthandDefaultPos) { const node = super.parseObjectProperty(prop, startPos, startLoc, isPattern, refShorthandDefaultPos); if (node) { node.kind = "init"; node.type = "Property"; } return node; } toAssignable(node, isBinding, contextDescription) { if (isSimpleProperty(node)) { this.toAssignable(node.value, isBinding, contextDescription); return node; } return super.toAssignable(node, isBinding, contextDescription); } toAssignableObjectExpressionProp(prop, isBinding, isLast) { if (prop.kind === "get" || prop.kind === "set") { this.raise(prop.key.start, "Object pattern can't contain getter or setter"); } else if (prop.method) { this.raise(prop.key.start, "Object pattern can't contain methods"); } else { super.toAssignableObjectExpressionProp(prop, isBinding, isLast); } } }); const lineBreak = /\r\n?|[\n\u2028\u2029]/; const lineBreakG = new RegExp(lineBreak.source, "g"); function isNewLine(code) { switch (code) { case 10: case 13: case 8232: case 8233: return true; default: return false; } } const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; function isWhitespace(code) { switch (code) { case 0x0009: case 0x000b: case 0x000c: case 32: case 160: case 5760: case 0x2000: case 0x2001: case 0x2002: case 0x2003: case 0x2004: case 0x2005: case 0x2006: case 0x2007: case 0x2008: case 0x2009: case 0x200a: case 0x202f: case 0x205f: case 0x3000: case 0xfeff: return true; default: return false; } } class TokContext { constructor(token, isExpr, preserveSpace, override) { this.token = token; this.isExpr = !!isExpr; this.preserveSpace = !!preserveSpace; this.override = override; } } const types$1 = { braceStatement: new TokContext("{", false), braceExpression: new TokContext("{", true), templateQuasi: new TokContext("${", false), parenStatement: new TokContext("(", false), parenExpression: new TokContext("(", true), template: new TokContext("`", true, true, p => p.readTmplToken()), functionExpression: new TokContext("function", true), functionStatement: new TokContext("function", false) }; types.parenR.updateContext = types.braceR.updateContext = function () { if (this.state.context.length === 1) { this.state.exprAllowed = true; return; } let out = this.state.context.pop(); if (out === types$1.braceStatement && this.curContext().token === "function") { out = this.state.context.pop(); } this.state.exprAllowed = !out.isExpr; }; types.name.updateContext = function (prevType) { let allowed = false; if (prevType !== types.dot) { if (this.state.value === "of" && !this.state.exprAllowed || this.state.value === "yield" && this.scope.inGenerator) { allowed = true; } } this.state.exprAllowed = allowed; if (this.state.isIterator) { this.state.isIterator = false; } }; types.braceL.updateContext = function (prevType) { this.state.context.push(this.braceIsBlock(prevType) ? types$1.braceStatement : types$1.braceExpression); this.state.exprAllowed = true; }; types.dollarBraceL.updateContext = function () { this.state.context.push(types$1.templateQuasi); this.state.exprAllowed = true; }; types.parenL.updateContext = function (prevType) { const statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while; this.state.context.push(statementParens ? types$1.parenStatement : types$1.parenExpression); this.state.exprAllowed = true; }; types.incDec.updateContext = function () {}; types._function.updateContext = types._class.updateContext = function (prevType) { if (prevType.beforeExpr && prevType !== types.semi && prevType !== types._else && !(prevType === types._return && lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start))) && !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat)) { this.state.context.push(types$1.functionExpression); } else { this.state.context.push(types$1.functionStatement); } this.state.exprAllowed = false; }; types.backQuote.updateContext = function () { if (this.curContext() === types$1.template) { this.state.context.pop(); } else { this.state.context.push(types$1.template); } this.state.exprAllowed = false; }; const reservedWords = { strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"], strictBind: ["eval", "arguments"] }; const reservedWordsStrictSet = new Set(reservedWords.strict); const reservedWordsStrictBindSet = new Set(reservedWords.strict.concat(reservedWords.strictBind)); const isReservedWord = (word, inModule) => { return inModule && word === "await" || word === "enum"; }; function isStrictReservedWord(word, inModule) { return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word); } function isStrictBindReservedWord(word, inModule) { return isReservedWord(word, inModule) || reservedWordsStrictBindSet.has(word); } function isKeyword(word) { return keywords.has(word); } const keywordRelationalOperator = /^in(stanceof)?$/; let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08bd\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fef\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7c6\ua7f7-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab67\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 477, 28, 11, 0, 9, 21, 155, 22, 13, 52, 76, 44, 33, 24, 27, 35, 30, 0, 12, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 0, 33, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 230, 43, 117, 63, 32, 0, 161, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 35, 56, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 270, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 754, 9486, 286, 50, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 2357, 44, 11, 6, 17, 0, 370, 43, 1301, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42710, 42, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541]; const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 525, 10, 176, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 4, 9, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 232, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 135, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 19723, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 419, 13, 1495, 6, 110, 6, 6, 9, 792487, 239]; function isInAstralSet(code, set) { let pos = 0x10000; for (let i = 0, length = set.length; i < length; i += 2) { pos += set[i]; if (pos > code) return false; pos += set[i + 1]; if (pos >= code) return true; } return false; } function isIdentifierStart(code) { if (code < 65) return code === 36; if (code <= 90) return true; if (code < 97) return code === 95; if (code <= 122) return true; if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); } return isInAstralSet(code, astralIdentifierStartCodes); } function isIteratorStart(current, next) { return current === 64 && next === 64; } function isIdentifierChar(code) { if (code < 48) return code === 36; if (code < 58) return true; if (code < 65) return false; if (code <= 90) return true; if (code < 97) return code === 95; if (code <= 122) return true; if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); } return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); } const reservedTypes = ["any", "bool", "boolean", "empty", "false", "mixed", "null", "number", "static", "string", "true", "typeof", "void", "interface", "extends", "_"]; function isEsModuleType(bodyElement) { return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration"); } function hasTypeImportKind(node) { return node.importKind === "type" || node.importKind === "typeof"; } function isMaybeDefaultImport(state) { return (state.type === types.name || !!state.type.keyword) && state.value !== "from"; } const exportSuggestions = { const: "declare export var", let: "declare export var", type: "export type", interface: "export interface" }; function partition(list, test) { const list1 = []; const list2 = []; for (let i = 0; i < list.length; i++) { (test(list[i], i, list) ? list1 : list2).push(list[i]); } return [list1, list2]; } const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/; var flow = (superClass => class extends superClass { constructor(options, input) { super(options, input); this.flowPragma = undefined; } shouldParseTypes() { return this.getPluginOption("flow", "all") || this.flowPragma === "flow"; } finishToken(type, val) { if (type !== types.string && type !== types.semi && type !== types.interpreterDirective) { if (this.flowPragma === undefined) { this.flowPragma = null; } } return super.finishToken(type, val); } addComment(comment) { if (this.flowPragma === undefined) { const matches = FLOW_PRAGMA_REGEX.exec(comment.value); if (!matches) ; else if (matches[1] === "flow") { this.flowPragma = "flow"; } else if (matches[1] === "noflow") { this.flowPragma = "noflow"; } else { throw new Error("Unexpected flow pragma"); } } return super.addComment(comment); } flowParseTypeInitialiser(tok) { const oldInType = this.state.inType; this.state.inType = true; this.expect(tok || types.colon); const type = this.flowParseType(); this.state.inType = oldInType; return type; } flowParsePredicate() { const node = this.startNode(); const moduloLoc = this.state.startLoc; const moduloPos = this.state.start; this.expect(types.modulo); const checksLoc = this.state.startLoc; this.expectContextual("checks"); if (moduloLoc.line !== checksLoc.line || moduloLoc.column !== checksLoc.column - 1) { this.raise(moduloPos, "Spaces between ´%´ and ´checks´ are not allowed here."); } if (this.eat(types.parenL)) { node.value = this.parseExpression(); this.expect(types.parenR); return this.finishNode(node, "DeclaredPredicate"); } else { return this.finishNode(node, "InferredPredicate"); } } flowParseTypeAndPredicateInitialiser() { const oldInType = this.state.inType; this.state.inType = true; this.expect(types.colon); let type = null; let predicate = null; if (this.match(types.modulo)) { this.state.inType = oldInType; predicate = this.flowParsePredicate(); } else { type = this.flowParseType(); this.state.inType = oldInType; if (this.match(types.modulo)) { predicate = this.flowParsePredicate(); } } return [type, predicate]; } flowParseDeclareClass(node) { this.next(); this.flowParseInterfaceish(node, true); return this.finishNode(node, "DeclareClass"); } flowParseDeclareFunction(node) { this.next(); const id = node.id = this.parseIdentifier(); const typeNode = this.startNode(); const typeContainer = this.startNode(); if (this.isRelational("<")) { typeNode.typeParameters = this.flowParseTypeParameterDeclaration(); } else { typeNode.typeParameters = null; } this.expect(types.parenL); const tmp = this.flowParseFunctionTypeParams(); typeNode.params = tmp.params; typeNode.rest = tmp.rest; this.expect(types.parenR); [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser(); typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation"); id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation"); this.resetEndLocation(id); this.semicolon(); return this.finishNode(node, "DeclareFunction"); } flowParseDeclare(node, insideModule) { if (this.match(types._class)) { return this.flowParseDeclareClass(node); } else if (this.match(types._function)) { return this.flowParseDeclareFunction(node); } else if (this.match(types._var)) { return this.flowParseDeclareVariable(node); } else if (this.eatContextual("module")) { if (this.match(types.dot)) { return this.flowParseDeclareModuleExports(node); } else { if (insideModule) { this.unexpected(this.state.lastTokStart, "`declare module` cannot be used inside another `declare module`"); } return this.flowParseDeclareModule(node); } } else if (this.isContextual("type")) { return this.flowParseDeclareTypeAlias(node); } else if (this.isContextual("opaque")) { return this.flowParseDeclareOpaqueType(node); } else if (this.isContextual("interface")) { return this.flowParseDeclareInterface(node); } else if (this.match(types._export)) { return this.flowParseDeclareExportDeclaration(node, insideModule); } else { throw this.unexpected(); } } flowParseDeclareVariable(node) { this.next(); node.id = this.flowParseTypeAnnotatableIdentifier(true); this.semicolon(); return this.finishNode(node, "DeclareVariable"); } flowParseDeclareModule(node) { this.scope.enter(SCOPE_OTHER); if (this.match(types.string)) { node.id = this.parseExprAtom(); } else { node.id = this.parseIdentifier(); } const bodyNode = node.body = this.startNode(); const body = bodyNode.body = []; this.expect(types.braceL); while (!this.match(types.braceR)) { let bodyNode = this.startNode(); if (this.match(types._import)) { this.next(); if (!this.isContextual("type") && !this.isContextual("typeof")) { this.unexpected(this.state.lastTokStart, "Imports within a `declare module` body must always be `import type` or `import typeof`"); } this.parseImport(bodyNode); } else { this.expectContextual("declare", "Only declares and type imports are allowed inside declare module"); bodyNode = this.flowParseDeclare(bodyNode, true); } body.push(bodyNode); } this.scope.exit(); this.expect(types.braceR); this.finishNode(bodyNode, "BlockStatement"); let kind = null; let hasModuleExport = false; const errorMessage = "Found both `declare module.exports` and `declare export` in the same module. " + "Modules can only have 1 since they are either an ES module or they are a CommonJS module"; body.forEach(bodyElement => { if (isEsModuleType(bodyElement)) { if (kind === "CommonJS") { this.unexpected(bodyElement.start, errorMessage); } kind = "ES"; } else if (bodyElement.type === "DeclareModuleExports") { if (hasModuleExport) { this.unexpected(bodyElement.start, "Duplicate `declare module.exports` statement"); } if (kind === "ES") this.unexpected(bodyElement.start, errorMessage); kind = "CommonJS"; hasModuleExport = true; } }); node.kind = kind || "CommonJS"; return this.finishNode(node, "DeclareModule"); } flowParseDeclareExportDeclaration(node, insideModule) { this.expect(types._export); if (this.eat(types._default)) { if (this.match(types._function) || this.match(types._class)) { node.declaration = this.flowParseDeclare(this.startNode()); } else { node.declaration = this.flowParseType(); this.semicolon(); } node.default = true; return this.finishNode(node, "DeclareExportDeclaration"); } else { if (this.match(types._const) || this.isLet() || (this.isContextual("type") || this.isContextual("interface")) && !insideModule) { const label = this.state.value; const suggestion = exportSuggestions[label]; this.unexpected(this.state.start, `\`declare export ${label}\` is not supported. Use \`${suggestion}\` instead`); } if (this.match(types._var) || this.match(types._function) || this.match(types._class) || this.isContextual("opaque")) { node.declaration = this.flowParseDeclare(this.startNode()); node.default = false; return this.finishNode(node, "DeclareExportDeclaration"); } else if (this.match(types.star) || this.match(types.braceL) || this.isContextual("interface") || this.isContextual("type") || this.isContextual("opaque")) { node = this.parseExport(node); if (node.type === "ExportNamedDeclaration") { node.type = "ExportDeclaration"; node.default = false; delete node.exportKind; } node.type = "Declare" + node.type; return node; } } throw this.unexpected(); } flowParseDeclareModuleExports(node) { this.next(); this.expectContextual("exports"); node.typeAnnotation = this.flowParseTypeAnnotation(); this.semicolon(); return this.finishNode(node, "DeclareModuleExports"); } flowParseDeclareTypeAlias(node) { this.next(); this.flowParseTypeAlias(node); node.type = "DeclareTypeAlias"; return node; } flowParseDeclareOpaqueType(node) { this.next(); this.flowParseOpaqueType(node, true); node.type = "DeclareOpaqueType"; return node; } flowParseDeclareInterface(node) { this.next(); this.flowParseInterfaceish(node); return this.finishNode(node, "DeclareInterface"); } flowParseInterfaceish(node, isClass = false) { node.id = this.flowParseRestrictedIdentifier(!isClass); if (this.isRelational("<")) { node.typeParameters = this.flowParseTypeParameterDeclaration(); } else { node.typeParameters = null; } node.extends = []; node.implements = []; node.mixins = []; if (this.eat(types._extends)) { do { node.extends.push(this.flowParseInterfaceExtends()); } while (!isClass && this.eat(types.comma)); } if (this.isContextual("mixins")) { this.next(); do { node.mixins.push(this.flowParseInterfaceExtends()); } while (this.eat(types.comma)); } if (this.isContextual("implements")) { this.next(); do { node.implements.push(this.flowParseInterfaceExtends()); } while (this.eat(types.comma)); } node.body = this.flowParseObjectType({ allowStatic: isClass, allowExact: false, allowSpread: false, allowProto: isClass, allowInexact: false }); } flowParseInterfaceExtends() { const node = this.startNode(); node.id = this.flowParseQualifiedTypeIdentifier(); if (this.isRelational("<")) { node.typeParameters = this.flowParseTypeParameterInstantiation(); } else { node.typeParameters = null; } return this.finishNode(node, "InterfaceExtends"); } flowParseInterface(node) { this.flowParseInterfaceish(node); return this.finishNode(node, "InterfaceDeclaration"); } checkNotUnderscore(word) { if (word === "_") { throw this.unexpected(null, "`_` is only allowed as a type argument to call or new"); } } checkReservedType(word, startLoc) { if (reservedTypes.indexOf(word) > -1) { this.raise(startLoc, `Cannot overwrite reserved type ${word}`); } } flowParseRestrictedIdentifier(liberal) { this.checkReservedType(this.state.value, this.state.start); return this.parseIdentifier(liberal); } flowParseTypeAlias(node) { node.id = this.flowParseRestrictedIdentifier(); this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start); if (this.isRelational("<")) { node.typeParameters = this.flowParseTypeParameterDeclaration(); } else { node.typeParameters = null; } node.right = this.flowParseTypeInitialiser(types.eq); this.semicolon(); return this.finishNode(node, "TypeAlias"); } flowParseOpaqueType(node, declare) { this.expectContextual("type"); node.id = this.flowParseRestrictedIdentifier(true); this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start); if (this.isRelational("<")) { node.typeParameters = this.flowParseTypeParameterDeclaration(); } else { node.typeParameters = null; } node.supertype = null; if (this.match(types.colon)) { node.supertype = this.flowParseTypeInitialiser(types.colon); } node.impltype = null; if (!declare) { node.impltype = this.flowParseTypeInitialiser(types.eq); } this.semicolon(); return this.finishNode(node, "OpaqueType"); } flowParseTypeParameter(allowDefault = true, requireDefault = false) { if (!allowDefault && requireDefault) { throw new Error("Cannot disallow a default value (`allowDefault`) while also requiring it (`requireDefault`)."); } const nodeStart = this.state.start; const node = this.startNode(); const variance = this.flowParseVariance(); const ident = this.flowParseTypeAnnotatableIdentifier(); node.name = ident.name; node.variance = variance; node.bound = ident.typeAnnotation; if (this.match(types.eq)) { if (allowDefault) { this.eat(types.eq); node.default = this.flowParseType(); } else { this.unexpected(); } } else { if (requireDefault) { this.unexpected(nodeStart, "Type parameter declaration needs a default, since a preceding type parameter declaration has a default."); } } return this.finishNode(node, "TypeParameter"); } flowParseTypeParameterDeclaration(allowDefault = true) { const oldInType = this.state.inType; const node = this.startNode(); node.params = []; this.state.inType = true; if (this.isRelational("<") || this.match(types.jsxTagStart)) { this.next(); } else { this.unexpected(); } let defaultRequired = false; do { const typeParameter = this.flowParseTypeParameter(allowDefault, defaultRequired); node.params.push(typeParameter); if (typeParameter.default) { defaultRequired = true; } if (!this.isRelational(">")) { this.expect(types.comma); } } while (!this.isRelational(">")); this.expectRelational(">"); this.state.inType = oldInType; return this.finishNode(node, "TypeParameterDeclaration"); } flowParseTypeParameterInstantiation() { const node = this.startNode(); const oldInType = this.state.inType; node.params = []; this.state.inType = true; this.expectRelational("<"); const oldNoAnonFunctionType = this.state.noAnonFunctionType; this.state.noAnonFunctionType = false; while (!this.isRelational(">")) { node.params.push(this.flowParseType()); if (!this.isRelational(">")) { this.expect(types.comma); } } this.state.noAnonFunctionType = oldNoAnonFunctionType; this.expectRelational(">"); this.state.inType = oldInType; return this.finishNode(node, "TypeParameterInstantiation"); } flowParseTypeParameterInstantiationCallOrNew() { const node = this.startNode(); const oldInType = this.state.inType; node.params = []; this.state.inType = true; this.expectRelational("<"); while (!this.isRelational(">")) { node.params.push(this.flowParseTypeOrImplicitInstantiation()); if (!this.isRelational(">")) { this.expect(types.comma); } } this.expectRelational(">"); this.state.inType = oldInType; return this.finishNode(node, "TypeParameterInstantiation"); } flowParseInterfaceType() { const node = this.startNode(); this.expectContextual("interface"); node.extends = []; if (this.eat(types._extends)) { do { node.extends.push(this.flowParseInterfaceExtends()); } while (this.eat(types.comma)); } node.body = this.flowParseObjectType({ allowStatic: false, allowExact: false, allowSpread: false, allowProto: false, allowInexact: false }); return this.finishNode(node, "InterfaceTypeAnnotation"); } flowParseObjectPropertyKey() { return this.match(types.num) || this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true); } flowParseObjectTypeIndexer(node, isStatic, variance) { node.static = isStatic; if (this.lookahead().type === types.colon) { node.id = this.flowParseObjectPropertyKey(); node.key = this.flowParseTypeInitialiser(); } else { node.id = null; node.key = this.flowParseType(); } this.expect(types.bracketR); node.value = this.flowParseTypeInitialiser(); node.variance = variance; return this.finishNode(node, "ObjectTypeIndexer"); } flowParseObjectTypeInternalSlot(node, isStatic) { node.static = isStatic; node.id = this.flowParseObjectPropertyKey(); this.expect(types.bracketR); this.expect(types.bracketR); if (this.isRelational("<") || this.match(types.parenL)) { node.method = true; node.optional = false; node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start)); } else { node.method = false; if (this.eat(types.question)) { node.optional = true; } node.value = this.flowParseTypeInitialiser(); } return this.finishNode(node, "ObjectTypeInternalSlot"); } flowParseObjectTypeMethodish(node) { node.params = []; node.rest = null; node.typeParameters = null; if (this.isRelational("<")) { node.typeParameters = this.flowParseTypeParameterDeclaration(false); } this.expect(types.parenL); while (!this.match(types.parenR) && !this.match(types.ellipsis)) { node.params.push(this.flowParseFunctionTypeParam()); if (!this.match(types.parenR)) { this.expect(types.comma); } } if (this.eat(types.ellipsis)) { node.rest = this.flowParseFunctionTypeParam(); } this.expect(types.parenR); node.returnType = this.flowParseTypeInitialiser(); return this.finishNode(node, "FunctionTypeAnnotation"); } flowParseObjectTypeCallProperty(node, isStatic) { const valueNode = this.startNode(); node.static = isStatic; node.value = this.flowParseObjectTypeMethodish(valueNode); return this.finishNode(node, "ObjectTypeCallProperty"); } flowParseObjectType({ allowStatic, allowExact, allowSpread, allowProto, allowInexact }) { const oldInType = this.state.inType; this.state.inType = true; const nodeStart = this.startNode(); nodeStart.callProperties = []; nodeStart.properties = []; nodeStart.indexers = []; nodeStart.internalSlots = []; let endDelim; let exact; let inexact = false; if (allowExact && this.match(types.braceBarL)) { this.expect(types.braceBarL); endDelim = types.braceBarR; exact = true; } else { this.expect(types.braceL); endDelim = types.braceR; exact = false; } nodeStart.exact = exact; while (!this.match(endDelim)) { let isStatic = false; let protoStart = null; const node = this.startNode(); if (allowProto && this.isContextual("proto")) { const lookahead = this.lookahead(); if (lookahead.type !== types.colon && lookahead.type !== types.question) { this.next(); protoStart = this.state.start; allowStatic = false; } } if (allowStatic && this.isContextual("static")) { const lookahead = this.lookahead(); if (lookahead.type !== types.colon && lookahead.type !== types.question) { this.next(); isStatic = true; } } const variance = this.flowParseVariance(); if (this.eat(types.bracketL)) { if (protoStart != null) { this.unexpected(protoStart); } if (this.eat(types.bracketL)) { if (variance) { this.unexpected(variance.start); } nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic)); } else { nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance)); } } else if (this.match(types.parenL) || this.isRelational("<")) { if (protoStart != null) { this.unexpected(protoStart); } if (variance) { this.unexpected(variance.start); } nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic)); } else { let kind = "init"; if (this.isContextual("get") || this.isContextual("set")) { const lookahead = this.lookahead(); if (lookahead.type === types.name || lookahead.type === types.string || lookahead.type === types.num) { kind = this.state.value; this.next(); } } const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact); if (propOrInexact === null) { inexact = true; } else { nodeStart.properties.push(propOrInexact); } } this.flowObjectTypeSemicolon(); } this.expect(endDelim); if (allowSpread) { nodeStart.inexact = inexact; } const out = this.finishNode(nodeStart, "ObjectTypeAnnotation"); this.state.inType = oldInType; return out; } flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact) { if (this.match(types.ellipsis)) { if (!allowSpread) { this.unexpected(null, "Spread operator cannot appear in class or interface definitions"); } if (protoStart != null) { this.unexpected(protoStart); } if (variance) { this.unexpected(variance.start, "Spread properties cannot have variance"); } this.expect(types.ellipsis); const isInexactToken = this.eat(types.comma) || this.eat(types.semi); if (this.match(types.braceR)) { if (allowInexact) return null; this.unexpected(null, "Explicit inexact syntax is only allowed inside inexact objects"); } if (this.match(types.braceBarR)) { this.unexpected(null, "Explicit inexact syntax cannot appear inside an explicit exact object type"); } if (isInexactToken) { this.unexpected(null, "Explicit inexact syntax must appear at the end of an inexact object"); } node.argument = this.flowParseType(); return this.finishNode(node, "ObjectTypeSpreadProperty"); } else { node.key = this.flowParseObjectPropertyKey(); node.static = isStatic; node.proto = protoStart != null; node.kind = kind; let optional = false; if (this.isRelational("<") || this.match(types.parenL)) { node.method = true; if (protoStart != null) { this.unexpected(protoStart); } if (variance) { this.unexpected(variance.start); } node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start)); if (kind === "get" || kind === "set") { this.flowCheckGetterSetterParams(node); } } else { if (kind !== "init") this.unexpected(); node.method = false; if (this.eat(types.question)) { optional = true; } node.value = this.flowParseTypeInitialiser(); node.variance = variance; } node.optional = optional; return this.finishNode(node, "ObjectTypeProperty"); } } flowCheckGetterSetterParams(property) { const paramCount = property.kind === "get" ? 0 : 1; const start = property.start; const length = property.value.params.length + (property.value.rest ? 1 : 0); if (length !== paramCount) { if (property.kind === "get") { this.raise(start, "getter must not have any formal parameters"); } else { this.raise(start, "setter must have exactly one formal parameter"); } } if (property.kind === "set" && property.value.rest) { this.raise(start, "setter function argument must not be a rest parameter"); } } flowObjectTypeSemicolon() { if (!this.eat(types.semi) && !this.eat(types.comma) && !this.match(types.braceR) && !this.match(types.braceBarR)) { this.unexpected(); } } flowParseQualifiedTypeIdentifier(startPos, startLoc, id) { startPos = startPos || this.state.start; startLoc = startLoc || this.state.startLoc; let node = id || this.parseIdentifier(); while (this.eat(types.dot)) { const node2 = this.startNodeAt(startPos, startLoc); node2.qualification = node; node2.id = this.parseIdentifier(); node = this.finishNode(node2, "QualifiedTypeIdentifier"); } return node; } flowParseGenericType(startPos, startLoc, id) { const node = this.startNodeAt(startPos, startLoc); node.typeParameters = null; node.id = this.flowParseQualifiedTypeIdentifier(startPos, startLoc, id); if (this.isRelational("<")) { node.typeParameters = this.flowParseTypeParameterInstantiation(); } return this.finishNode(node, "GenericTypeAnnotation"); } flowParseTypeofType() { const node = this.startNode(); this.expect(types._typeof); node.argument = this.flowParsePrimaryType(); return this.finishNode(node, "TypeofTypeAnnotation"); } flowParseTupleType() { const node = this.startNode(); node.types = []; this.expect(types.bracketL); while (this.state.pos < this.length && !this.match(types.bracketR)) { node.types.push(this.flowParseType()); if (this.match(types.bracketR)) break; this.expect(types.comma); } this.expect(types.bracketR); return this.finishNode(node, "TupleTypeAnnotation"); } flowParseFunctionTypeParam() { let name = null; let optional = false; let typeAnnotation = null; const node = this.startNode(); const lh = this.lookahead(); if (lh.type === types.colon || lh.type === types.question) { name = this.parseIdentifier(); if (this.eat(types.question)) { optional = true; } typeAnnotation = this.flowParseTypeInitialiser(); } else { typeAnnotation = this.flowParseType(); } node.name = name; node.optional = optional; node.typeAnnotation = typeAnnotation; return this.finishNode(node, "FunctionTypeParam"); } reinterpretTypeAsFunctionTypeParam(type) { const node = this.startNodeAt(type.start, type.loc.start); node.name = null; node.optional = false; node.typeAnnotation = type; return this.finishNode(node, "FunctionTypeParam"); } flowParseFunctionTypeParams(params = []) { let rest = null; while (!this.match(types.parenR) && !this.match(types.ellipsis)) { params.push(this.flowParseFunctionTypeParam()); if (!this.match(types.parenR)) { this.expect(types.comma); } } if (this.eat(types.ellipsis)) { rest = this.flowParseFunctionTypeParam(); } return { params, rest }; } flowIdentToTypeAnnotation(startPos, startLoc, node, id) { switch (id.name) { case "any": return this.finishNode(node, "AnyTypeAnnotation"); case "bool": case "boolean": return this.finishNode(node, "BooleanTypeAnnotation"); case "mixed": return this.finishNode(node, "MixedTypeAnnotation"); case "empty": return this.finishNode(node, "EmptyTypeAnnotation"); case "number": return this.finishNode(node, "NumberTypeAnnotation"); case "string": return this.finishNode(node, "StringTypeAnnotation"); default: this.checkNotUnderscore(id.name); return this.flowParseGenericType(startPos, startLoc, id); } } flowParsePrimaryType() { const startPos = this.state.start; const startLoc = this.state.startLoc; const node = this.startNode(); let tmp; let type; let isGroupedType = false; const oldNoAnonFunctionType = this.state.noAnonFunctionType; switch (this.state.type) { case types.name: if (this.isContextual("interface")) { return this.flowParseInterfaceType(); } return this.flowIdentToTypeAnnotation(startPos, startLoc, node, this.parseIdentifier()); case types.braceL: return this.flowParseObjectType({ allowStatic: false, allowExact: false, allowSpread: true, allowProto: false, allowInexact: true }); case types.braceBarL: return this.flowParseObjectType({ allowStatic: false, allowExact: true, allowSpread: true, allowProto: false, allowInexact: false }); case types.bracketL: return this.flowParseTupleType(); case types.relational: if (this.state.value === "<") { node.typeParameters = this.flowParseTypeParameterDeclaration(false); this.expect(types.parenL); tmp = this.flowParseFunctionTypeParams(); node.params = tmp.params; node.rest = tmp.rest; this.expect(types.parenR); this.expect(types.arrow); node.returnType = this.flowParseType(); return this.finishNode(node, "FunctionTypeAnnotation"); } break; case types.parenL: this.next(); if (!this.match(types.parenR) && !this.match(types.ellipsis)) { if (this.match(types.name)) { const token = this.lookahead().type; isGroupedType = token !== types.question && token !== types.colon; } else { isGroupedType = true; } } if (isGroupedType) { this.state.noAnonFunctionType = false; type = this.flowParseType(); this.state.noAnonFunctionType = oldNoAnonFunctionType; if (this.state.noAnonFunctionType || !(this.match(types.comma) || this.match(types.parenR) && this.lookahead().type === types.arrow)) { this.expect(types.parenR); return type; } else { this.eat(types.comma); } } if (type) { tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]); } else { tmp = this.flowParseFunctionTypeParams(); } node.params = tmp.params; node.rest = tmp.rest; this.expect(types.parenR); this.expect(types.arrow); node.returnType = this.flowParseType(); node.typeParameters = null; return this.finishNode(node, "FunctionTypeAnnotation"); case types.string: return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation"); case types._true: case types._false: node.value = this.match(types._true); this.next(); return this.finishNode(node, "BooleanLiteralTypeAnnotation"); case types.plusMin: if (this.state.value === "-") { this.next(); if (!this.match(types.num)) { this.unexpected(null, `Unexpected token, expected "number"`); } return this.parseLiteral(-this.state.value, "NumberLiteralTypeAnnotation", node.start, node.loc.start); } this.unexpected(); case types.num: return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation"); case types._void: this.next(); return this.finishNode(node, "VoidTypeAnnotation"); case types._null: this.next(); return this.finishNode(node, "NullLiteralTypeAnnotation"); case types._this: this.next(); return this.finishNode(node, "ThisTypeAnnotation"); case types.star: this.next(); return this.finishNode(node, "ExistsTypeAnnotation"); default: if (this.state.type.keyword === "typeof") { return this.flowParseTypeofType(); } else if (this.state.type.keyword) { const label = this.state.type.label; this.next(); return super.createIdentifier(node, label); } } throw this.unexpected(); } flowParsePostfixType() { const startPos = this.state.start, startLoc = this.state.startLoc; let type = this.flowParsePrimaryType(); while (this.match(types.bracketL) && !this.canInsertSemicolon()) { const node = this.startNodeAt(startPos, startLoc); node.elementType = type; this.expect(types.bracketL); this.expect(types.bracketR); type = this.finishNode(node, "ArrayTypeAnnotation"); } return type; } flowParsePrefixType() { const node = this.startNode(); if (this.eat(types.question)) { node.typeAnnotation = this.flowParsePrefixType(); return this.finishNode(node, "NullableTypeAnnotation"); } else { return this.flowParsePostfixType(); } } flowParseAnonFunctionWithoutParens() { const param = this.flowParsePrefixType(); if (!this.state.noAnonFunctionType && this.eat(types.arrow)) { const node = this.startNodeAt(param.start, param.loc.start); node.params = [this.reinterpretTypeAsFunctionTypeParam(param)]; node.rest = null; node.returnType = this.flowParseType(); node.typeParameters = null; return this.finishNode(node, "FunctionTypeAnnotation"); } return param; } flowParseIntersectionType() { const node = this.startNode(); this.eat(types.bitwiseAND); const type = this.flowParseAnonFunctionWithoutParens(); node.types = [type]; while (this.eat(types.bitwiseAND)) { node.types.push(this.flowParseAnonFunctionWithoutParens()); } return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation"); } flowParseUnionType() { const node = this.startNode(); this.eat(types.bitwiseOR); const type = this.flowParseIntersectionType(); node.types = [type]; while (this.eat(types.bitwiseOR)) { node.types.push(this.flowParseIntersectionType()); } return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation"); } flowParseType() { const oldInType = this.state.inType; this.state.inType = true; const type = this.flowParseUnionType(); this.state.inType = oldInType; this.state.exprAllowed = this.state.exprAllowed || this.state.noAnonFunctionType; return type; } flowParseTypeOrImplicitInstantiation() { if (this.state.type === types.name && this.state.value === "_") { const startPos = this.state.start; const startLoc = this.state.startLoc; const node = this.parseIdentifier(); return this.flowParseGenericType(startPos, startLoc, node); } else { return this.flowParseType(); } } flowParseTypeAnnotation() { const node = this.startNode(); node.typeAnnotation = this.flowParseTypeInitialiser(); return this.finishNode(node, "TypeAnnotation"); } flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) { const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier(); if (this.match(types.colon)) { ident.typeAnnotation = this.flowParseTypeAnnotation(); this.resetEndLocation(ident); } return ident; } typeCastToParameter(node) { node.expression.typeAnnotation = node.typeAnnotation; this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end); return node.expression; } flowParseVariance() { let variance = null; if (this.match(types.plusMin)) { variance = this.startNode(); if (this.state.value === "+") { variance.kind = "plus"; } else { variance.kind = "minus"; } this.next(); this.finishNode(variance, "Variance"); } return variance; } parseFunctionBody(node, allowExpressionBody, isMethod = false) { if (allowExpressionBody) { return this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod)); } return super.parseFunctionBody(node, false, isMethod); } parseFunctionBodyAndFinish(node, type, isMethod = false) { if (this.match(types.colon)) { const typeNode = this.startNode(); [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser(); node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null; } super.parseFunctionBodyAndFinish(node, type, isMethod); } parseStatement(context, topLevel) { if (this.state.strict && this.match(types.name) && this.state.value === "interface") { const node = this.startNode(); this.next(); return this.flowParseInterface(node); } else { const stmt = super.parseStatement(context, topLevel); if (this.flowPragma === undefined && !this.isValidDirective(stmt)) { this.flowPragma = null; } return stmt; } } parseExpressionStatement(node, expr) { if (expr.type === "Identifier") { if (expr.name === "declare") { if (this.match(types._class) || this.match(types.name) || this.match(types._function) || this.match(types._var) || this.match(types._export)) { return this.flowParseDeclare(node); } } else if (this.match(types.name)) { if (expr.name === "interface") { return this.flowParseInterface(node); } else if (expr.name === "type") { return this.flowParseTypeAlias(node); } else if (expr.name === "opaque") { return this.flowParseOpaqueType(node, false); } } } return super.parseExpressionStatement(node, expr); } shouldParseExportDeclaration() { return this.isContextual("type") || this.isContextual("interface") || this.isContextual("opaque") || super.shouldParseExportDeclaration(); } isExportDefaultSpecifier() { if (this.match(types.name) && (this.state.value === "type" || this.state.value === "interface" || this.state.value === "opaque")) { return false; } return super.isExportDefaultSpecifier(); } parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos) { if (!this.match(types.question)) return expr; if (refNeedsArrowPos) { const state = this.state.clone(); try { return super.parseConditional(expr, noIn, startPos, startLoc); } catch (err) { if (err instanceof SyntaxError) { this.state = state; refNeedsArrowPos.start = err.pos || this.state.start; return expr; } else { throw err; } } } this.expect(types.question); const state = this.state.clone(); const originalNoArrowAt = this.state.noArrowAt; const node = this.startNodeAt(startPos, startLoc); let { consequent, failed } = this.tryParseConditionalConsequent(); let [valid, invalid] = this.getArrowLikeExpressions(consequent); if (failed || invalid.length > 0) { const noArrowAt = [...originalNoArrowAt]; if (invalid.length > 0) { this.state = state; this.state.noArrowAt = noArrowAt; for (let i = 0; i < invalid.length; i++) { noArrowAt.push(invalid[i].start); } ({ consequent, failed } = this.tryParseConditionalConsequent()); [valid, invalid] = this.getArrowLikeExpressions(consequent); } if (failed && valid.length > 1) { this.raise(state.start, "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate."); } if (failed && valid.length === 1) { this.state = state; this.state.noArrowAt = noArrowAt.concat(valid[0].start); ({ consequent, failed } = this.tryParseConditionalConsequent()); } this.getArrowLikeExpressions(consequent, true); } this.state.noArrowAt = originalNoArrowAt; this.expect(types.colon); node.test = expr; node.consequent = consequent; node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(noIn, undefined, undefined, undefined)); return this.finishNode(node, "ConditionalExpression"); } tryParseConditionalConsequent() { this.state.noArrowParamsConversionAt.push(this.state.start); const consequent = this.parseMaybeAssign(); const failed = !this.match(types.colon); this.state.noArrowParamsConversionAt.pop(); return { consequent, failed }; } getArrowLikeExpressions(node, disallowInvalid) { const stack = [node]; const arrows = []; while (stack.length !== 0) { const node = stack.pop(); if (node.type === "ArrowFunctionExpression") { if (node.typeParameters || !node.returnType) { this.toAssignableList(node.params, true, "arrow function parameters"); this.scope.enter(functionFlags(false, false) | SCOPE_ARROW); super.checkParams(node, false, true); this.scope.exit(); } else { arrows.push(node); } stack.push(node.body); } else if (node.type === "ConditionalExpression") { stack.push(node.consequent); stack.push(node.alternate); } } if (disallowInvalid) { for (let i = 0; i < arrows.length; i++) { this.toAssignableList(node.params, true, "arrow function parameters"); } return [arrows, []]; } return partition(arrows, node => { try { this.toAssignableList(node.params, true, "arrow function parameters"); return true; } catch (err) { return false; } }); } forwardNoArrowParamsConversionAt(node, parse) { let result; if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) { this.state.noArrowParamsConversionAt.push(this.state.start); result = parse(); this.state.noArrowParamsConversionAt.pop(); } else { result = parse(); } return result; } parseParenItem(node, startPos, startLoc) { node = super.parseParenItem(node, startPos, startLoc); if (this.eat(types.question)) { node.optional = true; this.resetEndLocation(node); } if (this.match(types.colon)) { const typeCastNode = this.startNodeAt(startPos, startLoc); typeCastNode.expression = node; typeCastNode.typeAnnotation = this.flowParseTypeAnnotation(); return this.finishNode(typeCastNode, "TypeCastExpression"); } return node; } assertModuleNodeAllowed(node) { if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") { return; } super.assertModuleNodeAllowed(node); } parseExport(node) { const decl = super.parseExport(node); if (decl.type === "ExportNamedDeclaration" || decl.type === "ExportAllDeclaration") { decl.exportKind = decl.exportKind || "value"; } return decl; } parseExportDeclaration(node) { if (this.isContextual("type")) { node.exportKind = "type"; const declarationNode = this.startNode(); this.next(); if (this.match(types.braceL)) { node.specifiers = this.parseExportSpecifiers(); this.parseExportFrom(node); return null; } else { return this.flowParseTypeAlias(declarationNode); } } else if (this.isContextual("opaque")) { node.exportKind = "type"; const declarationNode = this.startNode(); this.next(); return this.flowParseOpaqueType(declarationNode, false); } else if (this.isContextual("interface")) { node.exportKind = "type"; const declarationNode = this.startNode(); this.next(); return this.flowParseInterface(declarationNode); } else { return super.parseExportDeclaration(node); } } eatExportStar(node) { if (super.eatExportStar(...arguments)) return true; if (this.isContextual("type") && this.lookahead().type === types.star) { node.exportKind = "type"; this.next(); this.next(); return true; } return false; } maybeParseExportNamespaceSpecifier(node) { const pos = this.state.start; const hasNamespace = super.maybeParseExportNamespaceSpecifier(node); if (hasNamespace && node.exportKind === "type") { this.unexpected(pos); } return hasNamespace; } parseClassId(node, isStatement, optionalId) { super.parseClassId(node, isStatement, optionalId); if (this.isRelational("<")) { node.typeParameters = this.flowParseTypeParameterDeclaration(); } } getTokenFromCode(code) { const next = this.input.charCodeAt(this.state.pos + 1); if (code === 123 && next === 124) { return this.finishOp(types.braceBarL, 2); } else if (this.state.inType && (code === 62 || code === 60)) { return this.finishOp(types.relational, 1); } else if (isIteratorStart(code, next)) { this.state.isIterator = true; return super.readWord(); } else { return super.getTokenFromCode(code); } } toAssignable(node, isBinding, contextDescription) { if (node.type === "TypeCastExpression") { return super.toAssignable(this.typeCastToParameter(node), isBinding, contextDescription); } else { return super.toAssignable(node, isBinding, contextDescription); } } toAssignableList(exprList, isBinding, contextDescription) { for (let i = 0; i < exprList.length; i++) { const expr = exprList[i]; if (expr && expr.type === "TypeCastExpression") { exprList[i] = this.typeCastToParameter(expr); } } return super.toAssignableList(exprList, isBinding, contextDescription); } toReferencedList(exprList, isParenthesizedExpr) { for (let i = 0; i < exprList.length; i++) { const expr = exprList[i]; if (expr && expr.type === "TypeCastExpression" && (!expr.extra || !expr.extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) { this.raise(expr.typeAnnotation.start, "The type cast expression is expected to be wrapped with parenthesis"); } } return exprList; } checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription) { if (expr.type !== "TypeCastExpression") { return super.checkLVal(expr, bindingType, checkClashes, contextDescription); } } parseClassProperty(node) { if (this.match(types.colon)) { node.typeAnnotation = this.flowParseTypeAnnotation(); } return super.parseClassProperty(node); } parseClassPrivateProperty(node) { if (this.match(types.colon)) { node.typeAnnotation = this.flowParseTypeAnnotation(); } return super.parseClassPrivateProperty(node); } isClassMethod() { return this.isRelational("<") || super.isClassMethod(); } isClassProperty() { return this.match(types.colon) || super.isClassProperty(); } isNonstaticConstructor(method) { return !this.match(types.colon) && super.isNonstaticConstructor(method); } pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { if (method.variance) { this.unexpected(method.variance.start); } delete method.variance; if (this.isRelational("<")) { method.typeParameters = this.flowParseTypeParameterDeclaration(false); } super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper); } pushClassPrivateMethod(classBody, method, isGenerator, isAsync) { if (method.variance) { this.unexpected(method.variance.start); } delete method.variance; if (this.isRelational("<")) { method.typeParameters = this.flowParseTypeParameterDeclaration(); } super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync); } parseClassSuper(node) { super.parseClassSuper(node); if (node.superClass && this.isRelational("<")) { node.superTypeParameters = this.flowParseTypeParameterInstantiation(); } if (this.isContextual("implements")) { this.next(); const implemented = node.implements = []; do { const node = this.startNode(); node.id = this.flowParseRestrictedIdentifier(true); if (this.isRelational("<")) { node.typeParameters = this.flowParseTypeParameterInstantiation(); } else { node.typeParameters = null; } implemented.push(this.finishNode(node, "ClassImplements")); } while (this.eat(types.comma)); } } parsePropertyName(node) { const variance = this.flowParseVariance(); const key = super.parsePropertyName(node); node.variance = variance; return key; } parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refShorthandDefaultPos, containsEsc) { if (prop.variance) { this.unexpected(prop.variance.start); } delete prop.variance; let typeParameters; if (this.isRelational("<")) { typeParameters = this.flowParseTypeParameterDeclaration(false); if (!this.match(types.parenL)) this.unexpected(); } super.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refShorthandDefaultPos, containsEsc); if (typeParameters) { (prop.value || prop).typeParameters = typeParameters; } } parseAssignableListItemTypes(param) { if (this.eat(types.question)) { if (param.type !== "Identifier") { throw this.raise(param.start, "A binding pattern parameter cannot be optional in an implementation signature."); } param.optional = true; } if (this.match(types.colon)) { param.typeAnnotation = this.flowParseTypeAnnotation(); } this.resetEndLocation(param); return param; } parseMaybeDefault(startPos, startLoc, left) { const node = super.parseMaybeDefault(startPos, startLoc, left); if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) { this.raise(node.typeAnnotation.start, "Type annotations must come before default assignments, " + "e.g. instead of `age = 25: number` use `age: number = 25`"); } return node; } shouldParseDefaultImport(node) { if (!hasTypeImportKind(node)) { return super.shouldParseDefaultImport(node); } return isMaybeDefaultImport(this.state); } parseImportSpecifierLocal(node, specifier, type, contextDescription) { specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true) : this.parseIdentifier(); this.checkLVal(specifier.local, BIND_LEXICAL, undefined, contextDescription); node.specifiers.push(this.finishNode(specifier, type)); } maybeParseDefaultImportSpecifier(node) { node.importKind = "value"; let kind = null; if (this.match(types._typeof)) { kind = "typeof"; } else if (this.isContextual("type")) { kind = "type"; } if (kind) { const lh = this.lookahead(); if (kind === "type" && lh.type === types.star) { this.unexpected(lh.start); } if (isMaybeDefaultImport(lh) || lh.type === types.braceL || lh.type === types.star) { this.next(); node.importKind = kind; } } return super.maybeParseDefaultImportSpecifier(node); } parseImportSpecifier(node) { const specifier = this.startNode(); const firstIdentLoc = this.state.start; const firstIdent = this.parseIdentifier(true); let specifierTypeKind = null; if (firstIdent.name === "type") { specifierTypeKind = "type"; } else if (firstIdent.name === "typeof") { specifierTypeKind = "typeof"; } let isBinding = false; if (this.isContextual("as") && !this.isLookaheadContextual("as")) { const as_ident = this.parseIdentifier(true); if (specifierTypeKind !== null && !this.match(types.name) && !this.state.type.keyword) { specifier.imported = as_ident; specifier.importKind = specifierTypeKind; specifier.local = as_ident.__clone(); } else { specifier.imported = firstIdent; specifier.importKind = null; specifier.local = this.parseIdentifier(); } } else if (specifierTypeKind !== null && (this.match(types.name) || this.state.type.keyword)) { specifier.imported = this.parseIdentifier(true); specifier.importKind = specifierTypeKind; if (this.eatContextual("as")) { specifier.local = this.parseIdentifier(); } else { isBinding = true; specifier.local = specifier.imported.__clone(); } } else { isBinding = true; specifier.imported = firstIdent; specifier.importKind = null; specifier.local = specifier.imported.__clone(); } const nodeIsTypeImport = hasTypeImportKind(node); const specifierIsTypeImport = hasTypeImportKind(specifier); if (nodeIsTypeImport && specifierIsTypeImport) { this.raise(firstIdentLoc, "The `type` and `typeof` keywords on named imports can only be used on regular " + "`import` statements. It cannot be used with `import type` or `import typeof` statements"); } if (nodeIsTypeImport || specifierIsTypeImport) { this.checkReservedType(specifier.local.name, specifier.local.start); } if (isBinding && !nodeIsTypeImport && !specifierIsTypeImport) { this.checkReservedWord(specifier.local.name, specifier.start, true, true); } this.checkLVal(specifier.local, BIND_LEXICAL, undefined, "import specifier"); node.specifiers.push(this.finishNode(specifier, "ImportSpecifier")); } parseFunctionParams(node, allowModifiers) { const kind = node.kind; if (kind !== "get" && kind !== "set" && this.isRelational("<")) { node.typeParameters = this.flowParseTypeParameterDeclaration(false); } super.parseFunctionParams(node, allowModifiers); } parseVarId(decl, kind) { super.parseVarId(decl, kind); if (this.match(types.colon)) { decl.id.typeAnnotation = this.flowParseTypeAnnotation(); this.resetEndLocation(decl.id); } } parseAsyncArrowFromCallExpression(node, call) { if (this.match(types.colon)) { const oldNoAnonFunctionType = this.state.noAnonFunctionType; this.state.noAnonFunctionType = true; node.returnType = this.flowParseTypeAnnotation(); this.state.noAnonFunctionType = oldNoAnonFunctionType; } return super.parseAsyncArrowFromCallExpression(node, call); } shouldParseAsyncArrow() { return this.match(types.colon) || super.shouldParseAsyncArrow(); } parseMaybeAssign(noIn, refShorthandDefaultPos, afterLeftParse, refNeedsArrowPos) { let jsxError = null; if (this.hasPlugin("jsx") && (this.match(types.jsxTagStart) || this.isRelational("<"))) { const state = this.state.clone(); try { return super.parseMaybeAssign(noIn, refShorthandDefaultPos, afterLeftParse, refNeedsArrowPos); } catch (err) { if (err instanceof SyntaxError) { this.state = state; const cLength = this.state.context.length; if (this.state.context[cLength - 1] === types$1.j_oTag) { this.state.context.length -= 2; } jsxError = err; } else { throw err; } } } if (jsxError != null || this.isRelational("<")) { let arrowExpression; let typeParameters; try { typeParameters = this.flowParseTypeParameterDeclaration(); arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => super.parseMaybeAssign(noIn, refShorthandDefaultPos, afterLeftParse, refNeedsArrowPos)); arrowExpression.typeParameters = typeParameters; this.resetStartLocationFromNode(arrowExpression, typeParameters); } catch (err) { throw jsxError || err; } if (arrowExpression.type === "ArrowFunctionExpression") { return arrowExpression; } else if (jsxError != null) { throw jsxError; } else { this.raise(typeParameters.start, "Expected an arrow function after this type parameter declaration"); } } return super.parseMaybeAssign(noIn, refShorthandDefaultPos, afterLeftParse, refNeedsArrowPos); } parseArrow(node) { if (this.match(types.colon)) { const state = this.state.clone(); try { const oldNoAnonFunctionType = this.state.noAnonFunctionType; this.state.noAnonFunctionType = true; const typeNode = this.startNode(); [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser(); this.state.noAnonFunctionType = oldNoAnonFunctionType; if (this.canInsertSemicolon()) this.unexpected(); if (!this.match(types.arrow)) this.unexpected(); node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null; } catch (err) { if (err instanceof SyntaxError) { this.state = state; } else { throw err; } } } return super.parseArrow(node); } shouldParseArrow() { return this.match(types.colon) || super.shouldParseArrow(); } setArrowFunctionParameters(node, params) { if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) { node.params = params; } else { super.setArrowFunctionParameters(node, params); } } checkParams(node, allowDuplicates, isArrowFunction) { if (isArrowFunction && this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) { return; } return super.checkParams(node, allowDuplicates, isArrowFunction); } parseParenAndDistinguishExpression(canBeArrow) { return super.parseParenAndDistinguishExpression(canBeArrow && this.state.noArrowAt.indexOf(this.state.start) === -1); } parseSubscripts(base, startPos, startLoc, noCalls) { if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.indexOf(startPos) !== -1) { this.next(); const node = this.startNodeAt(startPos, startLoc); node.callee = base; node.arguments = this.parseCallExpressionArguments(types.parenR, false); base = this.finishNode(node, "CallExpression"); } else if (base.type === "Identifier" && base.name === "async" && this.isRelational("<")) { const state = this.state.clone(); let error; try { const node = this.parseAsyncArrowWithTypeParameters(startPos, startLoc); if (node) return node; } catch (e) { error = e; } this.state = state; try { return super.parseSubscripts(base, startPos, startLoc, noCalls); } catch (e) { throw error || e; } } return super.parseSubscripts(base, startPos, startLoc, noCalls); } parseSubscript(base, startPos, startLoc, noCalls, subscriptState, maybeAsyncArrow) { if (this.match(types.questionDot) && this.isLookaheadRelational("<")) { this.expectPlugin("optionalChaining"); subscriptState.optionalChainMember = true; if (noCalls) { subscriptState.stop = true; return base; } this.next(); const node = this.startNodeAt(startPos, startLoc); node.callee = base; node.typeArguments = this.flowParseTypeParameterInstantiation(); this.expect(types.parenL); node.arguments = this.parseCallExpressionArguments(types.parenR, false); node.optional = true; return this.finishNode(node, "OptionalCallExpression"); } else if (!noCalls && this.shouldParseTypes() && this.isRelational("<")) { const node = this.startNodeAt(startPos, startLoc); node.callee = base; const state = this.state.clone(); try { node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew(); this.expect(types.parenL); node.arguments = this.parseCallExpressionArguments(types.parenR, false); if (subscriptState.optionalChainMember) { node.optional = false; return this.finishNode(node, "OptionalCallExpression"); } return this.finishNode(node, "CallExpression"); } catch (e) { if (e instanceof SyntaxError) { this.state = state; } else { throw e; } } } return super.parseSubscript(base, startPos, startLoc, noCalls, subscriptState, maybeAsyncArrow); } parseNewArguments(node) { let targs = null; if (this.shouldParseTypes() && this.isRelational("<")) { const state = this.state.clone(); try { targs = this.flowParseTypeParameterInstantiationCallOrNew(); } catch (e) { if (e instanceof SyntaxError) { this.state = state; } else { throw e; } } } node.typeArguments = targs; super.parseNewArguments(node); } parseAsyncArrowWithTypeParameters(startPos, startLoc) { const node = this.startNodeAt(startPos, startLoc); this.parseFunctionParams(node); if (!this.parseArrow(node)) return; return this.parseArrowExpression(node, undefined, true); } readToken_mult_modulo(code) { const next = this.input.charCodeAt(this.state.pos + 1); if (code === 42 && next === 47 && this.state.hasFlowComment) { this.state.hasFlowComment = false; this.state.pos += 2; this.nextToken(); return; } super.readToken_mult_modulo(code); } readToken_pipe_amp(code) { const next = this.input.charCodeAt(this.state.pos + 1); if (code === 124 && next === 125) { this.finishOp(types.braceBarR, 2); return; } super.readToken_pipe_amp(code); } parseTopLevel(file, program) { const fileNode = super.parseTopLevel(file, program); if (this.state.hasFlowComment) { this.unexpected(null, "Unterminated flow-comment"); } return fileNode; } skipBlockComment() { if (this.hasPlugin("flowComments") && this.skipFlowComment()) { if (this.state.hasFlowComment) { this.unexpected(null, "Cannot have a flow comment inside another flow comment"); } this.hasFlowCommentCompletion(); this.state.pos += this.skipFlowComment(); this.state.hasFlowComment = true; return; } if (this.state.hasFlowComment) { const end = this.input.indexOf("*-/", this.state.pos += 2); if (end === -1) this.raise(this.state.pos - 2, "Unterminated comment"); this.state.pos = end + 3; return; } super.skipBlockComment(); } skipFlowComment() { const { pos } = this.state; let shiftToFirstNonWhiteSpace = 2; while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) { shiftToFirstNonWhiteSpace++; } const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos); const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1); if (ch2 === 58 && ch3 === 58) { return shiftToFirstNonWhiteSpace + 2; } if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") { return shiftToFirstNonWhiteSpace + 12; } if (ch2 === 58 && ch3 !== 58) { return shiftToFirstNonWhiteSpace; } return false; } hasFlowCommentCompletion() { const end = this.input.indexOf("*/", this.state.pos); if (end === -1) { this.raise(this.state.pos, "Unterminated comment"); } } }); const entities = { quot: "\u0022", amp: "&", apos: "\u0027", lt: "<", gt: ">", nbsp: "\u00A0", iexcl: "\u00A1", cent: "\u00A2", pound: "\u00A3", curren: "\u00A4", yen: "\u00A5", brvbar: "\u00A6", sect: "\u00A7", uml: "\u00A8", copy: "\u00A9", ordf: "\u00AA", laquo: "\u00AB", not: "\u00AC", shy: "\u00AD", reg: "\u00AE", macr: "\u00AF", deg: "\u00B0", plusmn: "\u00B1", sup2: "\u00B2", sup3: "\u00B3", acute: "\u00B4", micro: "\u00B5", para: "\u00B6", middot: "\u00B7", cedil: "\u00B8", sup1: "\u00B9", ordm: "\u00BA", raquo: "\u00BB", frac14: "\u00BC", frac12: "\u00BD", frac34: "\u00BE", iquest: "\u00BF", Agrave: "\u00C0", Aacute: "\u00C1", Acirc: "\u00C2", Atilde: "\u00C3", Auml: "\u00C4", Aring: "\u00C5", AElig: "\u00C6", Ccedil: "\u00C7", Egrave: "\u00C8", Eacute: "\u00C9", Ecirc: "\u00CA", Euml: "\u00CB", Igrave: "\u00CC", Iacute: "\u00CD", Icirc: "\u00CE", Iuml: "\u00CF", ETH: "\u00D0", Ntilde: "\u00D1", Ograve: "\u00D2", Oacute: "\u00D3", Ocirc: "\u00D4", Otilde: "\u00D5", Ouml: "\u00D6", times: "\u00D7", Oslash: "\u00D8", Ugrave: "\u00D9", Uacute: "\u00DA", Ucirc: "\u00DB", Uuml: "\u00DC", Yacute: "\u00DD", THORN: "\u00DE", szlig: "\u00DF", agrave: "\u00E0", aacute: "\u00E1", acirc: "\u00E2", atilde: "\u00E3", auml: "\u00E4", aring: "\u00E5", aelig: "\u00E6", ccedil: "\u00E7", egrave: "\u00E8", eacute: "\u00E9", ecirc: "\u00EA", euml: "\u00EB", igrave: "\u00EC", iacute: "\u00ED", icirc: "\u00EE", iuml: "\u00EF", eth: "\u00F0", ntilde: "\u00F1", ograve: "\u00F2", oacute: "\u00F3", ocirc: "\u00F4", otilde: "\u00F5", ouml: "\u00F6", divide: "\u00F7", oslash: "\u00F8", ugrave: "\u00F9", uacute: "\u00FA", ucirc: "\u00FB", uuml: "\u00FC", yacute: "\u00FD", thorn: "\u00FE", yuml: "\u00FF", OElig: "\u0152", oelig: "\u0153", Scaron: "\u0160", scaron: "\u0161", Yuml: "\u0178", fnof: "\u0192", circ: "\u02C6", tilde: "\u02DC", Alpha: "\u0391", Beta: "\u0392", Gamma: "\u0393", Delta: "\u0394", Epsilon: "\u0395", Zeta: "\u0396", Eta: "\u0397", Theta: "\u0398", Iota: "\u0399", Kappa: "\u039A", Lambda: "\u039B", Mu: "\u039C", Nu: "\u039D", Xi: "\u039E", Omicron: "\u039F", Pi: "\u03A0", Rho: "\u03A1", Sigma: "\u03A3", Tau: "\u03A4", Upsilon: "\u03A5", Phi: "\u03A6", Chi: "\u03A7", Psi: "\u03A8", Omega: "\u03A9", alpha: "\u03B1", beta: "\u03B2", gamma: "\u03B3", delta: "\u03B4", epsilon: "\u03B5", zeta: "\u03B6", eta: "\u03B7", theta: "\u03B8", iota: "\u03B9", kappa: "\u03BA", lambda: "\u03BB", mu: "\u03BC", nu: "\u03BD", xi: "\u03BE", omicron: "\u03BF", pi: "\u03C0", rho: "\u03C1", sigmaf: "\u03C2", sigma: "\u03C3", tau: "\u03C4", upsilon: "\u03C5", phi: "\u03C6", chi: "\u03C7", psi: "\u03C8", omega: "\u03C9", thetasym: "\u03D1", upsih: "\u03D2", piv: "\u03D6", ensp: "\u2002", emsp: "\u2003", thinsp: "\u2009", zwnj: "\u200C", zwj: "\u200D", lrm: "\u200E", rlm: "\u200F", ndash: "\u2013", mdash: "\u2014", lsquo: "\u2018", rsquo: "\u2019", sbquo: "\u201A", ldquo: "\u201C", rdquo: "\u201D", bdquo: "\u201E", dagger: "\u2020", Dagger: "\u2021", bull: "\u2022", hellip: "\u2026", permil: "\u2030", prime: "\u2032", Prime: "\u2033", lsaquo: "\u2039", rsaquo: "\u203A", oline: "\u203E", frasl: "\u2044", euro: "\u20AC", image: "\u2111", weierp: "\u2118", real: "\u211C", trade: "\u2122", alefsym: "\u2135", larr: "\u2190", uarr: "\u2191", rarr: "\u2192", darr: "\u2193", harr: "\u2194", crarr: "\u21B5", lArr: "\u21D0", uArr: "\u21D1", rArr: "\u21D2", dArr: "\u21D3", hArr: "\u21D4", forall: "\u2200", part: "\u2202", exist: "\u2203", empty: "\u2205", nabla: "\u2207", isin: "\u2208", notin: "\u2209", ni: "\u220B", prod: "\u220F", sum: "\u2211", minus: "\u2212", lowast: "\u2217", radic: "\u221A", prop: "\u221D", infin: "\u221E", ang: "\u2220", and: "\u2227", or: "\u2228", cap: "\u2229", cup: "\u222A", int: "\u222B", there4: "\u2234", sim: "\u223C", cong: "\u2245", asymp: "\u2248", ne: "\u2260", equiv: "\u2261", le: "\u2264", ge: "\u2265", sub: "\u2282", sup: "\u2283", nsub: "\u2284", sube: "\u2286", supe: "\u2287", oplus: "\u2295", otimes: "\u2297", perp: "\u22A5", sdot: "\u22C5", lceil: "\u2308", rceil: "\u2309", lfloor: "\u230A", rfloor: "\u230B", lang: "\u2329", rang: "\u232A", loz: "\u25CA", spades: "\u2660", clubs: "\u2663", hearts: "\u2665", diams: "\u2666" }; const HEX_NUMBER = /^[\da-fA-F]+$/; const DECIMAL_NUMBER = /^\d+$/; types$1.j_oTag = new TokContext("...", true, true); types.jsxName = new TokenType("jsxName"); types.jsxText = new TokenType("jsxText", { beforeExpr: true }); types.jsxTagStart = new TokenType("jsxTagStart", { startsExpr: true }); types.jsxTagEnd = new TokenType("jsxTagEnd"); types.jsxTagStart.updateContext = function () { this.state.context.push(types$1.j_expr); this.state.context.push(types$1.j_oTag); this.state.exprAllowed = false; }; types.jsxTagEnd.updateContext = function (prevType) { const out = this.state.context.pop(); if (out === types$1.j_oTag && prevType === types.slash || out === types$1.j_cTag) { this.state.context.pop(); this.state.exprAllowed = this.curContext() === types$1.j_expr; } else { this.state.exprAllowed = true; } }; function isFragment(object) { return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false; } function getQualifiedJSXName(object) { if (object.type === "JSXIdentifier") { return object.name; } if (object.type === "JSXNamespacedName") { return object.namespace.name + ":" + object.name.name; } if (object.type === "JSXMemberExpression") { return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property); } throw new Error("Node had unexpected type: " + object.type); } var jsx = (superClass => class extends superClass { jsxReadToken() { let out = ""; let chunkStart = this.state.pos; for (;;) { if (this.state.pos >= this.length) { this.raise(this.state.start, "Unterminated JSX contents"); } const ch = this.input.charCodeAt(this.state.pos); switch (ch) { case 60: case 123: if (this.state.pos === this.state.start) { if (ch === 60 && this.state.exprAllowed) { ++this.state.pos; return this.finishToken(types.jsxTagStart); } return super.getTokenFromCode(ch); } out += this.input.slice(chunkStart, this.state.pos); return this.finishToken(types.jsxText, out); case 38: out += this.input.slice(chunkStart, this.state.pos); out += this.jsxReadEntity(); chunkStart = this.state.pos; break; default: if (isNewLine(ch)) { out += this.input.slice(chunkStart, this.state.pos); out += this.jsxReadNewLine(true); chunkStart = this.state.pos; } else { ++this.state.pos; } } } } jsxReadNewLine(normalizeCRLF) { const ch = this.input.charCodeAt(this.state.pos); let out; ++this.state.pos; if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) { ++this.state.pos; out = normalizeCRLF ? "\n" : "\r\n"; } else { out = String.fromCharCode(ch); } ++this.state.curLine; this.state.lineStart = this.state.pos; return out; } jsxReadString(quote) { let out = ""; let chunkStart = ++this.state.pos; for (;;) { if (this.state.pos >= this.length) { this.raise(this.state.start, "Unterminated string constant"); } const ch = this.input.charCodeAt(this.state.pos); if (ch === quote) break; if (ch === 38) { out += this.input.slice(chunkStart, this.state.pos); out += this.jsxReadEntity(); chunkStart = this.state.pos; } else if (isNewLine(ch)) { out += this.input.slice(chunkStart, this.state.pos); out += this.jsxReadNewLine(false); chunkStart = this.state.pos; } else { ++this.state.pos; } } out += this.input.slice(chunkStart, this.state.pos++); return this.finishToken(types.string, out); } jsxReadEntity() { let str = ""; let count = 0; let entity; let ch = this.input[this.state.pos]; const startPos = ++this.state.pos; while (this.state.pos < this.length && count++ < 10) { ch = this.input[this.state.pos++]; if (ch === ";") { if (str[0] === "#") { if (str[1] === "x") { str = str.substr(2); if (HEX_NUMBER.test(str)) { entity = String.fromCodePoint(parseInt(str, 16)); } } else { str = str.substr(1); if (DECIMAL_NUMBER.test(str)) { entity = String.fromCodePoint(parseInt(str, 10)); } } } else { entity = entities[str]; } break; } str += ch; } if (!entity) { this.state.pos = startPos; return "&"; } return entity; } jsxReadWord() { let ch; const start = this.state.pos; do { ch = this.input.charCodeAt(++this.state.pos); } while (isIdentifierChar(ch) || ch === 45); return this.finishToken(types.jsxName, this.input.slice(start, this.state.pos)); } jsxParseIdentifier() { const node = this.startNode(); if (this.match(types.jsxName)) { node.name = this.state.value; } else if (this.state.type.keyword) { node.name = this.state.type.keyword; } else { this.unexpected(); } this.next(); return this.finishNode(node, "JSXIdentifier"); } jsxParseNamespacedName() { const startPos = this.state.start; const startLoc = this.state.startLoc; const name = this.jsxParseIdentifier(); if (!this.eat(types.colon)) return name; const node = this.startNodeAt(startPos, startLoc); node.namespace = name; node.name = this.jsxParseIdentifier(); return this.finishNode(node, "JSXNamespacedName"); } jsxParseElementName() { const startPos = this.state.start; const startLoc = this.state.startLoc; let node = this.jsxParseNamespacedName(); while (this.eat(types.dot)) { const newNode = this.startNodeAt(startPos, startLoc); newNode.object = node; newNode.property = this.jsxParseIdentifier(); node = this.finishNode(newNode, "JSXMemberExpression"); } return node; } jsxParseAttributeValue() { let node; switch (this.state.type) { case types.braceL: node = this.startNode(); this.next(); node = this.jsxParseExpressionContainer(node); if (node.expression.type === "JSXEmptyExpression") { throw this.raise(node.start, "JSX attributes must only be assigned a non-empty expression"); } else { return node; } case types.jsxTagStart: case types.string: return this.parseExprAtom(); default: throw this.raise(this.state.start, "JSX value should be either an expression or a quoted JSX text"); } } jsxParseEmptyExpression() { const node = this.startNodeAt(this.state.lastTokEnd, this.state.lastTokEndLoc); return this.finishNodeAt(node, "JSXEmptyExpression", this.state.start, this.state.startLoc); } jsxParseSpreadChild(node) { this.next(); node.expression = this.parseExpression(); this.expect(types.braceR); return this.finishNode(node, "JSXSpreadChild"); } jsxParseExpressionContainer(node) { if (this.match(types.braceR)) { node.expression = this.jsxParseEmptyExpression(); } else { node.expression = this.parseExpression(); } this.expect(types.braceR); return this.finishNode(node, "JSXExpressionContainer"); } jsxParseAttribute() { const node = this.startNode(); if (this.eat(types.braceL)) { this.expect(types.ellipsis); node.argument = this.parseMaybeAssign(); this.expect(types.braceR); return this.finishNode(node, "JSXSpreadAttribute"); } node.name = this.jsxParseNamespacedName(); node.value = this.eat(types.eq) ? this.jsxParseAttributeValue() : null; return this.finishNode(node, "JSXAttribute"); } jsxParseOpeningElementAt(startPos, startLoc) { const node = this.startNodeAt(startPos, startLoc); if (this.match(types.jsxTagEnd)) { this.expect(types.jsxTagEnd); return this.finishNode(node, "JSXOpeningFragment"); } node.name = this.jsxParseElementName(); return this.jsxParseOpeningElementAfterName(node); } jsxParseOpeningElementAfterName(node) { const attributes = []; while (!this.match(types.slash) && !this.match(types.jsxTagEnd)) { attributes.push(this.jsxParseAttribute()); } node.attributes = attributes; node.selfClosing = this.eat(types.slash); this.expect(types.jsxTagEnd); return this.finishNode(node, "JSXOpeningElement"); } jsxParseClosingElementAt(startPos, startLoc) { const node = this.startNodeAt(startPos, startLoc); if (this.match(types.jsxTagEnd)) { this.expect(types.jsxTagEnd); return this.finishNode(node, "JSXClosingFragment"); } node.name = this.jsxParseElementName(); this.expect(types.jsxTagEnd); return this.finishNode(node, "JSXClosingElement"); } jsxParseElementAt(startPos, startLoc) { const node = this.startNodeAt(startPos, startLoc); const children = []; const openingElement = this.jsxParseOpeningElementAt(startPos, startLoc); let closingElement = null; if (!openingElement.selfClosing) { contents: for (;;) { switch (this.state.type) { case types.jsxTagStart: startPos = this.state.start; startLoc = this.state.startLoc; this.next(); if (this.eat(types.slash)) { closingElement = this.jsxParseClosingElementAt(startPos, startLoc); break contents; } children.push(this.jsxParseElementAt(startPos, startLoc)); break; case types.jsxText: children.push(this.parseExprAtom()); break; case types.braceL: { const node = this.startNode(); this.next(); if (this.match(types.ellipsis)) { children.push(this.jsxParseSpreadChild(node)); } else { children.push(this.jsxParseExpressionContainer(node)); } break; } default: throw this.unexpected(); } } if (isFragment(openingElement) && !isFragment(closingElement)) { this.raise(closingElement.start, "Expected corresponding JSX closing tag for <>"); } else if (!isFragment(openingElement) && isFragment(closingElement)) { this.raise(closingElement.start, "Expected corresponding JSX closing tag for <" + getQualifiedJSXName(openingElement.name) + ">"); } else if (!isFragment(openingElement) && !isFragment(closingElement)) { if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) { this.raise(closingElement.start, "Expected corresponding JSX closing tag for <" + getQualifiedJSXName(openingElement.name) + ">"); } } } if (isFragment(openingElement)) { node.openingFragment = openingElement; node.closingFragment = closingElement; } else { node.openingElement = openingElement; node.closingElement = closingElement; } node.children = children; if (this.match(types.relational) && this.state.value === "<") { this.raise(this.state.start, "Adjacent JSX elements must be wrapped in an enclosing tag. " + "Did you want a JSX fragment <>...?"); } return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement"); } jsxParseElement() { const startPos = this.state.start; const startLoc = this.state.startLoc; this.next(); return this.jsxParseElementAt(startPos, startLoc); } parseExprAtom(refShortHandDefaultPos) { if (this.match(types.jsxText)) { return this.parseLiteral(this.state.value, "JSXText"); } else if (this.match(types.jsxTagStart)) { return this.jsxParseElement(); } else if (this.isRelational("<") && this.input.charCodeAt(this.state.pos) !== 33) { this.finishToken(types.jsxTagStart); return this.jsxParseElement(); } else { return super.parseExprAtom(refShortHandDefaultPos); } } getTokenFromCode(code) { if (this.state.inPropertyName) return super.getTokenFromCode(code); const context = this.curContext(); if (context === types$1.j_expr) { return this.jsxReadToken(); } if (context === types$1.j_oTag || context === types$1.j_cTag) { if (isIdentifierStart(code)) { return this.jsxReadWord(); } if (code === 62) { ++this.state.pos; return this.finishToken(types.jsxTagEnd); } if ((code === 34 || code === 39) && context === types$1.j_oTag) { return this.jsxReadString(code); } } if (code === 60 && this.state.exprAllowed && this.input.charCodeAt(this.state.pos + 1) !== 33) { ++this.state.pos; return this.finishToken(types.jsxTagStart); } return super.getTokenFromCode(code); } updateContext(prevType) { if (this.match(types.braceL)) { const curContext = this.curContext(); if (curContext === types$1.j_oTag) { this.state.context.push(types$1.braceExpression); } else if (curContext === types$1.j_expr) { this.state.context.push(types$1.templateQuasi); } else { super.updateContext(prevType); } this.state.exprAllowed = true; } else if (this.match(types.slash) && prevType === types.jsxTagStart) { this.state.context.length -= 2; this.state.context.push(types$1.j_cTag); this.state.exprAllowed = false; } else { return super.updateContext(prevType); } } }); class Scope { constructor(flags) { this.var = []; this.lexical = []; this.functions = []; this.flags = flags; } } class ScopeHandler { constructor(raise, inModule) { this.scopeStack = []; this.undefinedExports = new Map(); this.raise = raise; this.inModule = inModule; } get inFunction() { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0; } get inGenerator() { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0; } get inAsync() { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0; } get allowSuper() { return (this.currentThisScope().flags & SCOPE_SUPER) > 0; } get allowDirectSuper() { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0; } get inNonArrowFunction() { return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0; } get treatFunctionsAsVar() { return this.treatFunctionsAsVarInScope(this.currentScope()); } createScope(flags) { return new Scope(flags); } enter(flags) { this.scopeStack.push(this.createScope(flags)); } exit() { this.scopeStack.pop(); } treatFunctionsAsVarInScope(scope) { return !!(scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_PROGRAM); } declareName(name, bindingType, pos) { let scope = this.currentScope(); if (bindingType & BIND_SCOPE_LEXICAL || bindingType & BIND_SCOPE_FUNCTION) { this.checkRedeclarationInScope(scope, name, bindingType, pos); if (bindingType & BIND_SCOPE_FUNCTION) { scope.functions.push(name); } else { scope.lexical.push(name); } if (bindingType & BIND_SCOPE_LEXICAL) { this.maybeExportDefined(scope, name); } } else if (bindingType & BIND_SCOPE_VAR) { for (let i = this.scopeStack.length - 1; i >= 0; --i) { scope = this.scopeStack[i]; this.checkRedeclarationInScope(scope, name, bindingType, pos); scope.var.push(name); this.maybeExportDefined(scope, name); if (scope.flags & SCOPE_VAR) break; } } if (this.inModule && scope.flags & SCOPE_PROGRAM) { this.undefinedExports.delete(name); } } maybeExportDefined(scope, name) { if (this.inModule && scope.flags & SCOPE_PROGRAM) { this.undefinedExports.delete(name); } } checkRedeclarationInScope(scope, name, bindingType, pos) { if (this.isRedeclaredInScope(scope, name, bindingType)) { this.raise(pos, `Identifier '${name}' has already been declared`); } } isRedeclaredInScope(scope, name, bindingType) { if (!(bindingType & BIND_KIND_VALUE)) return false; if (bindingType & BIND_SCOPE_LEXICAL) { return scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1; } if (bindingType & BIND_SCOPE_FUNCTION) { return scope.lexical.indexOf(name) > -1 || !this.treatFunctionsAsVarInScope(scope) && scope.var.indexOf(name) > -1; } return scope.lexical.indexOf(name) > -1 && !(scope.flags & SCOPE_SIMPLE_CATCH && scope.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.indexOf(name) > -1; } checkLocalExport(id) { if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && this.scopeStack[0].var.indexOf(id.name) === -1 && this.scopeStack[0].functions.indexOf(id.name) === -1) { this.undefinedExports.set(id.name, id.start); } } currentScope() { return this.scopeStack[this.scopeStack.length - 1]; } currentVarScope() { for (let i = this.scopeStack.length - 1;; i--) { const scope = this.scopeStack[i]; if (scope.flags & SCOPE_VAR) { return scope; } } } currentThisScope() { for (let i = this.scopeStack.length - 1;; i--) { const scope = this.scopeStack[i]; if ((scope.flags & SCOPE_VAR || scope.flags & SCOPE_CLASS) && !(scope.flags & SCOPE_ARROW)) { return scope; } } } } class TypeScriptScope extends Scope { constructor(...args) { super(...args); this.types = []; this.enums = []; this.constEnums = []; this.classes = []; this.exportOnlyBindings = []; } } class TypeScriptScopeHandler extends ScopeHandler { createScope(flags) { return new TypeScriptScope(flags); } declareName(name, bindingType, pos) { const scope = this.currentScope(); if (bindingType & BIND_FLAGS_TS_EXPORT_ONLY) { this.maybeExportDefined(scope, name); scope.exportOnlyBindings.push(name); return; } super.declareName(...arguments); if (bindingType & BIND_KIND_TYPE) { if (!(bindingType & BIND_KIND_VALUE)) { this.checkRedeclarationInScope(scope, name, bindingType, pos); this.maybeExportDefined(scope, name); } scope.types.push(name); } if (bindingType & BIND_FLAGS_TS_ENUM) scope.enums.push(name); if (bindingType & BIND_FLAGS_TS_CONST_ENUM) scope.constEnums.push(name); if (bindingType & BIND_FLAGS_CLASS) scope.classes.push(name); } isRedeclaredInScope(scope, name, bindingType) { if (scope.enums.indexOf(name) > -1) { if (bindingType & BIND_FLAGS_TS_ENUM) { const isConst = !!(bindingType & BIND_FLAGS_TS_CONST_ENUM); const wasConst = scope.constEnums.indexOf(name) > -1; return isConst !== wasConst; } return true; } if (bindingType & BIND_FLAGS_CLASS && scope.classes.indexOf(name) > -1) { if (scope.lexical.indexOf(name) > -1) { return !!(bindingType & BIND_KIND_VALUE); } else { return false; } } if (bindingType & BIND_KIND_TYPE && scope.types.indexOf(name) > -1) { return true; } return super.isRedeclaredInScope(...arguments); } checkLocalExport(id) { if (this.scopeStack[0].types.indexOf(id.name) === -1 && this.scopeStack[0].exportOnlyBindings.indexOf(id.name) === -1) { super.checkLocalExport(id); } } } function nonNull(x) { if (x == null) { throw new Error(`Unexpected ${x} value.`); } return x; } function assert(x) { if (!x) { throw new Error("Assert fail"); } } function keywordTypeFromName(value) { switch (value) { case "any": return "TSAnyKeyword"; case "boolean": return "TSBooleanKeyword"; case "bigint": return "TSBigIntKeyword"; case "never": return "TSNeverKeyword"; case "number": return "TSNumberKeyword"; case "object": return "TSObjectKeyword"; case "string": return "TSStringKeyword"; case "symbol": return "TSSymbolKeyword"; case "undefined": return "TSUndefinedKeyword"; case "unknown": return "TSUnknownKeyword"; default: return undefined; } } var typescript = (superClass => class extends superClass { getScopeHandler() { return TypeScriptScopeHandler; } tsIsIdentifier() { return this.match(types.name); } tsNextTokenCanFollowModifier() { this.next(); return !this.hasPrecedingLineBreak() && !this.match(types.parenL) && !this.match(types.parenR) && !this.match(types.colon) && !this.match(types.eq) && !this.match(types.question) && !this.match(types.bang); } tsParseModifier(allowedModifiers) { if (!this.match(types.name)) { return undefined; } const modifier = this.state.value; if (allowedModifiers.indexOf(modifier) !== -1 && this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) { return modifier; } return undefined; } tsIsListTerminator(kind) { switch (kind) { case "EnumMembers": case "TypeMembers": return this.match(types.braceR); case "HeritageClauseElement": return this.match(types.braceL); case "TupleElementTypes": return this.match(types.bracketR); case "TypeParametersOrArguments": return this.isRelational(">"); } throw new Error("Unreachable"); } tsParseList(kind, parseElement) { const result = []; while (!this.tsIsListTerminator(kind)) { result.push(parseElement()); } return result; } tsParseDelimitedList(kind, parseElement) { return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true)); } tsTryParseDelimitedList(kind, parseElement) { return this.tsParseDelimitedListWorker(kind, parseElement, false); } tsParseDelimitedListWorker(kind, parseElement, expectSuccess) { const result = []; while (true) { if (this.tsIsListTerminator(kind)) { break; } const element = parseElement(); if (element == null) { return undefined; } result.push(element); if (this.eat(types.comma)) { continue; } if (this.tsIsListTerminator(kind)) { break; } if (expectSuccess) { this.expect(types.comma); } return undefined; } return result; } tsParseBracketedList(kind, parseElement, bracket, skipFirstToken) { if (!skipFirstToken) { if (bracket) { this.expect(types.bracketL); } else { this.expectRelational("<"); } } const result = this.tsParseDelimitedList(kind, parseElement); if (bracket) { this.expect(types.bracketR); } else { this.expectRelational(">"); } return result; } tsParseImportType() { const node = this.startNode(); this.expect(types._import); this.expect(types.parenL); if (!this.match(types.string)) { throw this.unexpected(null, "Argument in a type import must be a string literal"); } node.argument = this.parseExprAtom(); this.expect(types.parenR); if (this.eat(types.dot)) { node.qualifier = this.tsParseEntityName(true); } if (this.isRelational("<")) { node.typeParameters = this.tsParseTypeArguments(); } return this.finishNode(node, "TSImportType"); } tsParseEntityName(allowReservedWords) { let entity = this.parseIdentifier(); while (this.eat(types.dot)) { const node = this.startNodeAtNode(entity); node.left = entity; node.right = this.parseIdentifier(allowReservedWords); entity = this.finishNode(node, "TSQualifiedName"); } return entity; } tsParseTypeReference() { const node = this.startNode(); node.typeName = this.tsParseEntityName(false); if (!this.hasPrecedingLineBreak() && this.isRelational("<")) { node.typeParameters = this.tsParseTypeArguments(); } return this.finishNode(node, "TSTypeReference"); } tsParseThisTypePredicate(lhs) { this.next(); const node = this.startNodeAtNode(lhs); node.parameterName = lhs; node.typeAnnotation = this.tsParseTypeAnnotation(false); return this.finishNode(node, "TSTypePredicate"); } tsParseThisTypeNode() { const node = this.startNode(); this.next(); return this.finishNode(node, "TSThisType"); } tsParseTypeQuery() { const node = this.startNode(); this.expect(types._typeof); if (this.match(types._import)) { node.exprName = this.tsParseImportType(); } else { node.exprName = this.tsParseEntityName(true); } return this.finishNode(node, "TSTypeQuery"); } tsParseTypeParameter() { const node = this.startNode(); node.name = this.parseIdentifierName(node.start); node.constraint = this.tsEatThenParseType(types._extends); node.default = this.tsEatThenParseType(types.eq); return this.finishNode(node, "TSTypeParameter"); } tsTryParseTypeParameters() { if (this.isRelational("<")) { return this.tsParseTypeParameters(); } } tsParseTypeParameters() { const node = this.startNode(); if (this.isRelational("<") || this.match(types.jsxTagStart)) { this.next(); } else { this.unexpected(); } node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this), false, true); return this.finishNode(node, "TSTypeParameterDeclaration"); } tsTryNextParseConstantContext() { if (this.lookahead().type === types._const) { this.next(); return this.tsParseTypeReference(); } return null; } tsFillSignature(returnToken, signature) { const returnTokenRequired = returnToken === types.arrow; signature.typeParameters = this.tsTryParseTypeParameters(); this.expect(types.parenL); signature.parameters = this.tsParseBindingListForSignature(); if (returnTokenRequired) { signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken); } else if (this.match(returnToken)) { signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken); } } tsParseBindingListForSignature() { return this.parseBindingList(types.parenR).map(pattern => { if (pattern.type !== "Identifier" && pattern.type !== "RestElement" && pattern.type !== "ObjectPattern" && pattern.type !== "ArrayPattern") { throw this.unexpected(pattern.start, `Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got ${pattern.type}`); } return pattern; }); } tsParseTypeMemberSemicolon() { if (!this.eat(types.comma)) { this.semicolon(); } } tsParseSignatureMember(kind, node) { this.tsFillSignature(types.colon, node); this.tsParseTypeMemberSemicolon(); return this.finishNode(node, kind); } tsIsUnambiguouslyIndexSignature() { this.next(); return this.eat(types.name) && this.match(types.colon); } tsTryParseIndexSignature(node) { if (!(this.match(types.bracketL) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) { return undefined; } this.expect(types.bracketL); const id = this.parseIdentifier(); id.typeAnnotation = this.tsParseTypeAnnotation(); this.resetEndLocation(id); this.expect(types.bracketR); node.parameters = [id]; const type = this.tsTryParseTypeAnnotation(); if (type) node.typeAnnotation = type; this.tsParseTypeMemberSemicolon(); return this.finishNode(node, "TSIndexSignature"); } tsParsePropertyOrMethodSignature(node, readonly) { if (this.eat(types.question)) node.optional = true; const nodeAny = node; if (!readonly && (this.match(types.parenL) || this.isRelational("<"))) { const method = nodeAny; this.tsFillSignature(types.colon, method); this.tsParseTypeMemberSemicolon(); return this.finishNode(method, "TSMethodSignature"); } else { const property = nodeAny; if (readonly) property.readonly = true; const type = this.tsTryParseTypeAnnotation(); if (type) property.typeAnnotation = type; this.tsParseTypeMemberSemicolon(); return this.finishNode(property, "TSPropertySignature"); } } tsParseTypeMember() { const node = this.startNode(); if (this.match(types.parenL) || this.isRelational("<")) { return this.tsParseSignatureMember("TSCallSignatureDeclaration", node); } if (this.match(types._new)) { const id = this.startNode(); this.next(); if (this.match(types.parenL) || this.isRelational("<")) { return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node); } else { node.key = this.createIdentifier(id, "new"); return this.tsParsePropertyOrMethodSignature(node, false); } } const readonly = !!this.tsParseModifier(["readonly"]); const idx = this.tsTryParseIndexSignature(node); if (idx) { if (readonly) node.readonly = true; return idx; } this.parsePropertyName(node); return this.tsParsePropertyOrMethodSignature(node, readonly); } tsParseTypeLiteral() { const node = this.startNode(); node.members = this.tsParseObjectTypeMembers(); return this.finishNode(node, "TSTypeLiteral"); } tsParseObjectTypeMembers() { this.expect(types.braceL); const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this)); this.expect(types.braceR); return members; } tsIsStartOfMappedType() { this.next(); if (this.eat(types.plusMin)) { return this.isContextual("readonly"); } if (this.isContextual("readonly")) { this.next(); } if (!this.match(types.bracketL)) { return false; } this.next(); if (!this.tsIsIdentifier()) { return false; } this.next(); return this.match(types._in); } tsParseMappedTypeParameter() { const node = this.startNode(); node.name = this.parseIdentifierName(node.start); node.constraint = this.tsExpectThenParseType(types._in); return this.finishNode(node, "TSTypeParameter"); } tsParseMappedType() { const node = this.startNode(); this.expect(types.braceL); if (this.match(types.plusMin)) { node.readonly = this.state.value; this.next(); this.expectContextual("readonly"); } else if (this.eatContextual("readonly")) { node.readonly = true; } this.expect(types.bracketL); node.typeParameter = this.tsParseMappedTypeParameter(); this.expect(types.bracketR); if (this.match(types.plusMin)) { node.optional = this.state.value; this.next(); this.expect(types.question); } else if (this.eat(types.question)) { node.optional = true; } node.typeAnnotation = this.tsTryParseType(); this.semicolon(); this.expect(types.braceR); return this.finishNode(node, "TSMappedType"); } tsParseTupleType() { const node = this.startNode(); node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false); let seenOptionalElement = false; node.elementTypes.forEach(elementNode => { if (elementNode.type === "TSOptionalType") { seenOptionalElement = true; } else if (seenOptionalElement && elementNode.type !== "TSRestType") { this.raise(elementNode.start, "A required element cannot follow an optional element."); } }); return this.finishNode(node, "TSTupleType"); } tsParseTupleElementType() { if (this.match(types.ellipsis)) { const restNode = this.startNode(); this.next(); restNode.typeAnnotation = this.tsParseType(); this.checkCommaAfterRest(); return this.finishNode(restNode, "TSRestType"); } const type = this.tsParseType(); if (this.eat(types.question)) { const optionalTypeNode = this.startNodeAtNode(type); optionalTypeNode.typeAnnotation = type; return this.finishNode(optionalTypeNode, "TSOptionalType"); } return type; } tsParseParenthesizedType() { const node = this.startNode(); this.expect(types.parenL); node.typeAnnotation = this.tsParseType(); this.expect(types.parenR); return this.finishNode(node, "TSParenthesizedType"); } tsParseFunctionOrConstructorType(type) { const node = this.startNode(); if (type === "TSConstructorType") { this.expect(types._new); } this.tsFillSignature(types.arrow, node); return this.finishNode(node, type); } tsParseLiteralTypeNode() { const node = this.startNode(); node.literal = (() => { switch (this.state.type) { case types.num: case types.string: case types._true: case types._false: return this.parseExprAtom(); default: throw this.unexpected(); } })(); return this.finishNode(node, "TSLiteralType"); } tsParseTemplateLiteralType() { const node = this.startNode(); const templateNode = this.parseTemplate(false); if (templateNode.expressions.length > 0) { throw this.raise(templateNode.expressions[0].start, "Template literal types cannot have any substitution"); } node.literal = templateNode; return this.finishNode(node, "TSLiteralType"); } tsParseNonArrayType() { switch (this.state.type) { case types.name: case types._void: case types._null: { const type = this.match(types._void) ? "TSVoidKeyword" : this.match(types._null) ? "TSNullKeyword" : keywordTypeFromName(this.state.value); if (type !== undefined && this.lookahead().type !== types.dot) { const node = this.startNode(); this.next(); return this.finishNode(node, type); } return this.tsParseTypeReference(); } case types.string: case types.num: case types._true: case types._false: return this.tsParseLiteralTypeNode(); case types.plusMin: if (this.state.value === "-") { const node = this.startNode(); if (this.lookahead().type !== types.num) { throw this.unexpected(); } node.literal = this.parseMaybeUnary(); return this.finishNode(node, "TSLiteralType"); } break; case types._this: { const thisKeyword = this.tsParseThisTypeNode(); if (this.isContextual("is") && !this.hasPrecedingLineBreak()) { return this.tsParseThisTypePredicate(thisKeyword); } else { return thisKeyword; } } case types._typeof: return this.tsParseTypeQuery(); case types._import: return this.tsParseImportType(); case types.braceL: return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral(); case types.bracketL: return this.tsParseTupleType(); case types.parenL: return this.tsParseParenthesizedType(); case types.backQuote: return this.tsParseTemplateLiteralType(); } throw this.unexpected(); } tsParseArrayTypeOrHigher() { let type = this.tsParseNonArrayType(); while (!this.hasPrecedingLineBreak() && this.eat(types.bracketL)) { if (this.match(types.bracketR)) { const node = this.startNodeAtNode(type); node.elementType = type; this.expect(types.bracketR); type = this.finishNode(node, "TSArrayType"); } else { const node = this.startNodeAtNode(type); node.objectType = type; node.indexType = this.tsParseType(); this.expect(types.bracketR); type = this.finishNode(node, "TSIndexedAccessType"); } } return type; } tsParseTypeOperator(operator) { const node = this.startNode(); this.expectContextual(operator); node.operator = operator; node.typeAnnotation = this.tsParseTypeOperatorOrHigher(); if (operator === "readonly") { this.tsCheckTypeAnnotationForReadOnly(node); } return this.finishNode(node, "TSTypeOperator"); } tsCheckTypeAnnotationForReadOnly(node) { switch (node.typeAnnotation.type) { case "TSTupleType": case "TSArrayType": return; default: this.raise(node.start, "'readonly' type modifier is only permitted on array and tuple literal types."); } } tsParseInferType() { const node = this.startNode(); this.expectContextual("infer"); const typeParameter = this.startNode(); typeParameter.name = this.parseIdentifierName(typeParameter.start); node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter"); return this.finishNode(node, "TSInferType"); } tsParseTypeOperatorOrHigher() { const operator = ["keyof", "unique", "readonly"].find(kw => this.isContextual(kw)); return operator ? this.tsParseTypeOperator(operator) : this.isContextual("infer") ? this.tsParseInferType() : this.tsParseArrayTypeOrHigher(); } tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) { this.eat(operator); let type = parseConstituentType(); if (this.match(operator)) { const types = [type]; while (this.eat(operator)) { types.push(parseConstituentType()); } const node = this.startNodeAtNode(type); node.types = types; type = this.finishNode(node, kind); } return type; } tsParseIntersectionTypeOrHigher() { return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), types.bitwiseAND); } tsParseUnionTypeOrHigher() { return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), types.bitwiseOR); } tsIsStartOfFunctionType() { if (this.isRelational("<")) { return true; } return this.match(types.parenL) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this)); } tsSkipParameterStart() { if (this.match(types.name) || this.match(types._this)) { this.next(); return true; } if (this.match(types.braceL)) { let braceStackCounter = 1; this.next(); while (braceStackCounter > 0) { if (this.match(types.braceL)) { ++braceStackCounter; } else if (this.match(types.braceR)) { --braceStackCounter; } this.next(); } return true; } if (this.match(types.bracketL)) { let braceStackCounter = 1; this.next(); while (braceStackCounter > 0) { if (this.match(types.bracketL)) { ++braceStackCounter; } else if (this.match(types.bracketR)) { --braceStackCounter; } this.next(); } return true; } return false; } tsIsUnambiguouslyStartOfFunctionType() { this.next(); if (this.match(types.parenR) || this.match(types.ellipsis)) { return true; } if (this.tsSkipParameterStart()) { if (this.match(types.colon) || this.match(types.comma) || this.match(types.question) || this.match(types.eq)) { return true; } if (this.match(types.parenR)) { this.next(); if (this.match(types.arrow)) { return true; } } } return false; } tsParseTypeOrTypePredicateAnnotation(returnToken) { return this.tsInType(() => { const t = this.startNode(); this.expect(returnToken); const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this)); if (!typePredicateVariable) { return this.tsParseTypeAnnotation(false, t); } const type = this.tsParseTypeAnnotation(false); const node = this.startNodeAtNode(typePredicateVariable); node.parameterName = typePredicateVariable; node.typeAnnotation = type; t.typeAnnotation = this.finishNode(node, "TSTypePredicate"); return this.finishNode(t, "TSTypeAnnotation"); }); } tsTryParseTypeOrTypePredicateAnnotation() { return this.match(types.colon) ? this.tsParseTypeOrTypePredicateAnnotation(types.colon) : undefined; } tsTryParseTypeAnnotation() { return this.match(types.colon) ? this.tsParseTypeAnnotation() : undefined; } tsTryParseType() { return this.tsEatThenParseType(types.colon); } tsParseTypePredicatePrefix() { const id = this.parseIdentifier(); if (this.isContextual("is") && !this.hasPrecedingLineBreak()) { this.next(); return id; } } tsParseTypeAnnotation(eatColon = true, t = this.startNode()) { this.tsInType(() => { if (eatColon) this.expect(types.colon); t.typeAnnotation = this.tsParseType(); }); return this.finishNode(t, "TSTypeAnnotation"); } tsParseType() { assert(this.state.inType); const type = this.tsParseNonConditionalType(); if (this.hasPrecedingLineBreak() || !this.eat(types._extends)) { return type; } const node = this.startNodeAtNode(type); node.checkType = type; node.extendsType = this.tsParseNonConditionalType(); this.expect(types.question); node.trueType = this.tsParseType(); this.expect(types.colon); node.falseType = this.tsParseType(); return this.finishNode(node, "TSConditionalType"); } tsParseNonConditionalType() { if (this.tsIsStartOfFunctionType()) { return this.tsParseFunctionOrConstructorType("TSFunctionType"); } if (this.match(types._new)) { return this.tsParseFunctionOrConstructorType("TSConstructorType"); } return this.tsParseUnionTypeOrHigher(); } tsParseTypeAssertion() { const node = this.startNode(); const _const = this.tsTryNextParseConstantContext(); node.typeAnnotation = _const || this.tsNextThenParseType(); this.expectRelational(">"); node.expression = this.parseMaybeUnary(); return this.finishNode(node, "TSTypeAssertion"); } tsParseHeritageClause(descriptor) { const originalStart = this.state.start; const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", this.tsParseExpressionWithTypeArguments.bind(this)); if (!delimitedList.length) { this.raise(originalStart, `'${descriptor}' list cannot be empty.`); } return delimitedList; } tsParseExpressionWithTypeArguments() { const node = this.startNode(); node.expression = this.tsParseEntityName(false); if (this.isRelational("<")) { node.typeParameters = this.tsParseTypeArguments(); } return this.finishNode(node, "TSExpressionWithTypeArguments"); } tsParseInterfaceDeclaration(node) { node.id = this.parseIdentifier(); this.checkLVal(node.id, BIND_TS_INTERFACE, undefined, "typescript interface declaration"); node.typeParameters = this.tsTryParseTypeParameters(); if (this.eat(types._extends)) { node.extends = this.tsParseHeritageClause("extends"); } const body = this.startNode(); body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this)); node.body = this.finishNode(body, "TSInterfaceBody"); return this.finishNode(node, "TSInterfaceDeclaration"); } tsParseTypeAliasDeclaration(node) { node.id = this.parseIdentifier(); this.checkLVal(node.id, BIND_TS_TYPE, undefined, "typescript type alias"); node.typeParameters = this.tsTryParseTypeParameters(); node.typeAnnotation = this.tsExpectThenParseType(types.eq); this.semicolon(); return this.finishNode(node, "TSTypeAliasDeclaration"); } tsInNoContext(cb) { const oldContext = this.state.context; this.state.context = [oldContext[0]]; try { return cb(); } finally { this.state.context = oldContext; } } tsInType(cb) { const oldInType = this.state.inType; this.state.inType = true; try { return cb(); } finally { this.state.inType = oldInType; } } tsEatThenParseType(token) { return !this.match(token) ? undefined : this.tsNextThenParseType(); } tsExpectThenParseType(token) { return this.tsDoThenParseType(() => this.expect(token)); } tsNextThenParseType() { return this.tsDoThenParseType(() => this.next()); } tsDoThenParseType(cb) { return this.tsInType(() => { cb(); return this.tsParseType(); }); } tsParseEnumMember() { const node = this.startNode(); node.id = this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true); if (this.eat(types.eq)) { node.initializer = this.parseMaybeAssign(); } return this.finishNode(node, "TSEnumMember"); } tsParseEnumDeclaration(node, isConst) { if (isConst) node.const = true; node.id = this.parseIdentifier(); this.checkLVal(node.id, isConst ? BIND_TS_CONST_ENUM : BIND_TS_ENUM, undefined, "typescript enum declaration"); this.expect(types.braceL); node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this)); this.expect(types.braceR); return this.finishNode(node, "TSEnumDeclaration"); } tsParseModuleBlock() { const node = this.startNode(); this.scope.enter(SCOPE_OTHER); this.expect(types.braceL); this.parseBlockOrModuleBlockBody(node.body = [], undefined, true, types.braceR); this.scope.exit(); return this.finishNode(node, "TSModuleBlock"); } tsParseModuleOrNamespaceDeclaration(node, nested = false) { node.id = this.parseIdentifier(); if (!nested) { this.checkLVal(node.id, BIND_TS_NAMESPACE, null, "module or namespace declaration"); } if (this.eat(types.dot)) { const inner = this.startNode(); this.tsParseModuleOrNamespaceDeclaration(inner, true); node.body = inner; } else { node.body = this.tsParseModuleBlock(); } return this.finishNode(node, "TSModuleDeclaration"); } tsParseAmbientExternalModuleDeclaration(node) { if (this.isContextual("global")) { node.global = true; node.id = this.parseIdentifier(); } else if (this.match(types.string)) { node.id = this.parseExprAtom(); } else { this.unexpected(); } if (this.match(types.braceL)) { node.body = this.tsParseModuleBlock(); } else { this.semicolon(); } return this.finishNode(node, "TSModuleDeclaration"); } tsParseImportEqualsDeclaration(node, isExport) { node.isExport = isExport || false; node.id = this.parseIdentifier(); this.expect(types.eq); node.moduleReference = this.tsParseModuleReference(); this.semicolon(); return this.finishNode(node, "TSImportEqualsDeclaration"); } tsIsExternalModuleReference() { return this.isContextual("require") && this.lookahead().type === types.parenL; } tsParseModuleReference() { return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(false); } tsParseExternalModuleReference() { const node = this.startNode(); this.expectContextual("require"); this.expect(types.parenL); if (!this.match(types.string)) { throw this.unexpected(); } node.expression = this.parseExprAtom(); this.expect(types.parenR); return this.finishNode(node, "TSExternalModuleReference"); } tsLookAhead(f) { const state = this.state.clone(); const res = f(); this.state = state; return res; } tsTryParseAndCatch(f) { const state = this.state.clone(); try { return f(); } catch (e) { if (e instanceof SyntaxError) { this.state = state; return undefined; } throw e; } } tsTryParse(f) { const state = this.state.clone(); const result = f(); if (result !== undefined && result !== false) { return result; } else { this.state = state; return undefined; } } nodeWithSamePosition(original, type) { const node = this.startNodeAtNode(original); node.type = type; node.end = original.end; node.loc.end = original.loc.end; if (original.leadingComments) { node.leadingComments = original.leadingComments; } if (original.trailingComments) { node.trailingComments = original.trailingComments; } if (original.innerComments) node.innerComments = original.innerComments; return node; } tsTryParseDeclare(nany) { if (this.isLineTerminator()) { return; } let starttype = this.state.type; let kind; if (this.isContextual("let")) { starttype = types._var; kind = "let"; } switch (starttype) { case types._function: return this.parseFunctionStatement(nany, false, true); case types._class: return this.parseClass(nany, true, false); case types._const: if (this.match(types._const) && this.isLookaheadContextual("enum")) { this.expect(types._const); this.expectContextual("enum"); return this.tsParseEnumDeclaration(nany, true); } case types._var: kind = kind || this.state.value; return this.parseVarStatement(nany, kind); case types.name: { const value = this.state.value; if (value === "global") { return this.tsParseAmbientExternalModuleDeclaration(nany); } else { return this.tsParseDeclaration(nany, value, true); } } } } tsTryParseExportDeclaration() { return this.tsParseDeclaration(this.startNode(), this.state.value, true); } tsParseExpressionStatement(node, expr) { switch (expr.name) { case "declare": { const declaration = this.tsTryParseDeclare(node); if (declaration) { declaration.declare = true; return declaration; } break; } case "global": if (this.match(types.braceL)) { const mod = node; mod.global = true; mod.id = expr; mod.body = this.tsParseModuleBlock(); return this.finishNode(mod, "TSModuleDeclaration"); } break; default: return this.tsParseDeclaration(node, expr.name, false); } } tsParseDeclaration(node, value, next) { switch (value) { case "abstract": if (this.tsCheckLineTerminatorAndMatch(types._class, next)) { const cls = node; cls.abstract = true; if (next) { this.next(); if (!this.match(types._class)) { this.unexpected(null, types._class); } } return this.parseClass(cls, true, false); } break; case "enum": if (next || this.match(types.name)) { if (next) this.next(); return this.tsParseEnumDeclaration(node, false); } break; case "interface": if (this.tsCheckLineTerminatorAndMatch(types.name, next)) { if (next) this.next(); return this.tsParseInterfaceDeclaration(node); } break; case "module": if (next) this.next(); if (this.match(types.string)) { return this.tsParseAmbientExternalModuleDeclaration(node); } else if (this.tsCheckLineTerminatorAndMatch(types.name, next)) { return this.tsParseModuleOrNamespaceDeclaration(node); } break; case "namespace": if (this.tsCheckLineTerminatorAndMatch(types.name, next)) { if (next) this.next(); return this.tsParseModuleOrNamespaceDeclaration(node); } break; case "type": if (this.tsCheckLineTerminatorAndMatch(types.name, next)) { if (next) this.next(); return this.tsParseTypeAliasDeclaration(node); } break; } } tsCheckLineTerminatorAndMatch(tokenType, next) { return (next || this.match(tokenType)) && !this.isLineTerminator(); } tsTryParseGenericAsyncArrowFunction(startPos, startLoc) { if (!this.isRelational("<")) { return undefined; } const res = this.tsTryParseAndCatch(() => { const node = this.startNodeAt(startPos, startLoc); node.typeParameters = this.tsParseTypeParameters(); super.parseFunctionParams(node); node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation(); this.expect(types.arrow); return node; }); if (!res) { return undefined; } return this.parseArrowExpression(res, null, true); } tsParseTypeArguments() { const node = this.startNode(); node.params = this.tsInType(() => this.tsInNoContext(() => { this.expectRelational("<"); return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this)); })); this.state.exprAllowed = false; this.expectRelational(">"); return this.finishNode(node, "TSTypeParameterInstantiation"); } tsIsDeclarationStart() { if (this.match(types.name)) { switch (this.state.value) { case "abstract": case "declare": case "enum": case "interface": case "module": case "namespace": case "type": return true; } } return false; } isExportDefaultSpecifier() { if (this.tsIsDeclarationStart()) return false; return super.isExportDefaultSpecifier(); } parseAssignableListItem(allowModifiers, decorators) { const startPos = this.state.start; const startLoc = this.state.startLoc; let accessibility; let readonly = false; if (allowModifiers) { accessibility = this.parseAccessModifier(); readonly = !!this.tsParseModifier(["readonly"]); } const left = this.parseMaybeDefault(); this.parseAssignableListItemTypes(left); const elt = this.parseMaybeDefault(left.start, left.loc.start, left); if (accessibility || readonly) { const pp = this.startNodeAt(startPos, startLoc); if (decorators.length) { pp.decorators = decorators; } if (accessibility) pp.accessibility = accessibility; if (readonly) pp.readonly = readonly; if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") { throw this.raise(pp.start, "A parameter property may not be declared using a binding pattern."); } pp.parameter = elt; return this.finishNode(pp, "TSParameterProperty"); } if (decorators.length) { left.decorators = decorators; } return elt; } parseFunctionBodyAndFinish(node, type, isMethod = false) { if (this.match(types.colon)) { node.returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon); } const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" ? "TSDeclareMethod" : undefined; if (bodilessType && !this.match(types.braceL) && this.isLineTerminator()) { this.finishNode(node, bodilessType); return; } super.parseFunctionBodyAndFinish(node, type, isMethod); } checkFunctionStatementId(node) { if (!node.body && node.id) { this.checkLVal(node.id, BIND_TS_FN_TYPE, null, "function name"); } else { super.checkFunctionStatementId(...arguments); } } parseSubscript(base, startPos, startLoc, noCalls, state, maybeAsyncArrow) { if (!this.hasPrecedingLineBreak() && this.match(types.bang)) { this.state.exprAllowed = false; this.next(); const nonNullExpression = this.startNodeAt(startPos, startLoc); nonNullExpression.expression = base; return this.finishNode(nonNullExpression, "TSNonNullExpression"); } if (this.isRelational("<")) { const result = this.tsTryParseAndCatch(() => { if (!noCalls && this.atPossibleAsync(base)) { const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startPos, startLoc); if (asyncArrowFn) { return asyncArrowFn; } } const node = this.startNodeAt(startPos, startLoc); node.callee = base; const typeArguments = this.tsParseTypeArguments(); if (typeArguments) { if (!noCalls && this.eat(types.parenL)) { node.arguments = this.parseCallExpressionArguments(types.parenR, false); node.typeParameters = typeArguments; return this.finishCallExpression(node); } else if (this.match(types.backQuote)) { return this.parseTaggedTemplateExpression(startPos, startLoc, base, state, typeArguments); } } this.unexpected(); }); if (result) return result; } return super.parseSubscript(base, startPos, startLoc, noCalls, state, maybeAsyncArrow); } parseNewArguments(node) { if (this.isRelational("<")) { const typeParameters = this.tsTryParseAndCatch(() => { const args = this.tsParseTypeArguments(); if (!this.match(types.parenL)) this.unexpected(); return args; }); if (typeParameters) { node.typeParameters = typeParameters; } } super.parseNewArguments(node); } parseExprOp(left, leftStartPos, leftStartLoc, minPrec, noIn) { if (nonNull(types._in.binop) > minPrec && !this.hasPrecedingLineBreak() && this.isContextual("as")) { const node = this.startNodeAt(leftStartPos, leftStartLoc); node.expression = left; const _const = this.tsTryNextParseConstantContext(); if (_const) { node.typeAnnotation = _const; } else { node.typeAnnotation = this.tsNextThenParseType(); } this.finishNode(node, "TSAsExpression"); return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn); } return super.parseExprOp(left, leftStartPos, leftStartLoc, minPrec, noIn); } checkReservedWord(word, startLoc, checkKeywords, isBinding) {} checkDuplicateExports() {} parseImport(node) { if (this.match(types.name) && this.lookahead().type === types.eq) { return this.tsParseImportEqualsDeclaration(node); } return super.parseImport(node); } parseExport(node) { if (this.match(types._import)) { this.expect(types._import); return this.tsParseImportEqualsDeclaration(node, true); } else if (this.eat(types.eq)) { const assign = node; assign.expression = this.parseExpression(); this.semicolon(); return this.finishNode(assign, "TSExportAssignment"); } else if (this.eatContextual("as")) { const decl = node; this.expectContextual("namespace"); decl.id = this.parseIdentifier(); this.semicolon(); return this.finishNode(decl, "TSNamespaceExportDeclaration"); } else { return super.parseExport(node); } } isAbstractClass() { return this.isContextual("abstract") && this.lookahead().type === types._class; } parseExportDefaultExpression() { if (this.isAbstractClass()) { const cls = this.startNode(); this.next(); this.parseClass(cls, true, true); cls.abstract = true; return cls; } if (this.state.value === "interface") { const result = this.tsParseDeclaration(this.startNode(), this.state.value, true); if (result) return result; } return super.parseExportDefaultExpression(); } parseStatementContent(context, topLevel) { if (this.state.type === types._const) { const ahead = this.lookahead(); if (ahead.type === types.name && ahead.value === "enum") { const node = this.startNode(); this.expect(types._const); this.expectContextual("enum"); return this.tsParseEnumDeclaration(node, true); } } return super.parseStatementContent(context, topLevel); } parseAccessModifier() { return this.tsParseModifier(["public", "protected", "private"]); } parseClassMember(classBody, member, state, constructorAllowsSuper) { const accessibility = this.parseAccessModifier(); if (accessibility) member.accessibility = accessibility; super.parseClassMember(classBody, member, state, constructorAllowsSuper); } parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper) { const methodOrProp = member; const prop = member; const propOrIdx = member; let abstract = false, readonly = false; const mod = this.tsParseModifier(["abstract", "readonly"]); switch (mod) { case "readonly": readonly = true; abstract = !!this.tsParseModifier(["abstract"]); break; case "abstract": abstract = true; readonly = !!this.tsParseModifier(["readonly"]); break; } if (abstract) methodOrProp.abstract = true; if (readonly) propOrIdx.readonly = true; if (!abstract && !isStatic && !methodOrProp.accessibility) { const idx = this.tsTryParseIndexSignature(member); if (idx) { classBody.body.push(idx); return; } } if (readonly) { methodOrProp.static = isStatic; this.parseClassPropertyName(prop); this.parsePostMemberNameModifiers(methodOrProp); this.pushClassProperty(classBody, prop); return; } super.parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper); } parsePostMemberNameModifiers(methodOrProp) { const optional = this.eat(types.question); if (optional) methodOrProp.optional = true; } parseExpressionStatement(node, expr) { const decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node, expr) : undefined; return decl || super.parseExpressionStatement(node, expr); } shouldParseExportDeclaration() { if (this.tsIsDeclarationStart()) return true; return super.shouldParseExportDeclaration(); } parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos) { if (!refNeedsArrowPos || !this.match(types.question)) { return super.parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos); } const state = this.state.clone(); try { return super.parseConditional(expr, noIn, startPos, startLoc); } catch (err) { if (!(err instanceof SyntaxError)) { throw err; } this.state = state; refNeedsArrowPos.start = err.pos || this.state.start; return expr; } } parseParenItem(node, startPos, startLoc) { node = super.parseParenItem(node, startPos, startLoc); if (this.eat(types.question)) { node.optional = true; this.resetEndLocation(node); } if (this.match(types.colon)) { const typeCastNode = this.startNodeAt(startPos, startLoc); typeCastNode.expression = node; typeCastNode.typeAnnotation = this.tsParseTypeAnnotation(); return this.finishNode(typeCastNode, "TSTypeCastExpression"); } return node; } parseExportDeclaration(node) { const startPos = this.state.start; const startLoc = this.state.startLoc; const isDeclare = this.eatContextual("declare"); let declaration; if (this.match(types.name)) { declaration = this.tsTryParseExportDeclaration(); } if (!declaration) { declaration = super.parseExportDeclaration(node); } if (declaration && isDeclare) { this.resetStartLocation(declaration, startPos, startLoc); declaration.declare = true; } return declaration; } parseClassId(node, isStatement, optionalId) { if ((!isStatement || optionalId) && this.isContextual("implements")) { return; } super.parseClassId(...arguments); const typeParameters = this.tsTryParseTypeParameters(); if (typeParameters) node.typeParameters = typeParameters; } parseClassProperty(node) { if (!node.optional && this.eat(types.bang)) { node.definite = true; } const type = this.tsTryParseTypeAnnotation(); if (type) node.typeAnnotation = type; return super.parseClassProperty(node); } pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { const typeParameters = this.tsTryParseTypeParameters(); if (typeParameters) method.typeParameters = typeParameters; super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper); } pushClassPrivateMethod(classBody, method, isGenerator, isAsync) { const typeParameters = this.tsTryParseTypeParameters(); if (typeParameters) method.typeParameters = typeParameters; super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync); } parseClassSuper(node) { super.parseClassSuper(node); if (node.superClass && this.isRelational("<")) { node.superTypeParameters = this.tsParseTypeArguments(); } if (this.eatContextual("implements")) { node.implements = this.tsParseHeritageClause("implements"); } } parseObjPropValue(prop, ...args) { const typeParameters = this.tsTryParseTypeParameters(); if (typeParameters) prop.typeParameters = typeParameters; super.parseObjPropValue(prop, ...args); } parseFunctionParams(node, allowModifiers) { const typeParameters = this.tsTryParseTypeParameters(); if (typeParameters) node.typeParameters = typeParameters; super.parseFunctionParams(node, allowModifiers); } parseVarId(decl, kind) { super.parseVarId(decl, kind); if (decl.id.type === "Identifier" && this.eat(types.bang)) { decl.definite = true; } const type = this.tsTryParseTypeAnnotation(); if (type) { decl.id.typeAnnotation = type; this.resetEndLocation(decl.id); } } parseAsyncArrowFromCallExpression(node, call) { if (this.match(types.colon)) { node.returnType = this.tsParseTypeAnnotation(); } return super.parseAsyncArrowFromCallExpression(node, call); } parseMaybeAssign(...args) { let jsxError; if (this.match(types.jsxTagStart)) { const context = this.curContext(); assert(context === types$1.j_oTag); assert(this.state.context[this.state.context.length - 2] === types$1.j_expr); const state = this.state.clone(); try { return super.parseMaybeAssign(...args); } catch (err) { if (!(err instanceof SyntaxError)) { throw err; } this.state = state; assert(this.curContext() === types$1.j_oTag); this.state.context.pop(); assert(this.curContext() === types$1.j_expr); this.state.context.pop(); jsxError = err; } } if (jsxError === undefined && !this.isRelational("<")) { return super.parseMaybeAssign(...args); } let arrowExpression; let typeParameters; const state = this.state.clone(); try { typeParameters = this.tsParseTypeParameters(); arrowExpression = super.parseMaybeAssign(...args); if (arrowExpression.type !== "ArrowFunctionExpression" || arrowExpression.extra && arrowExpression.extra.parenthesized) { this.unexpected(); } } catch (err) { if (!(err instanceof SyntaxError)) { throw err; } if (jsxError) { throw jsxError; } assert(!this.hasPlugin("jsx")); this.state = state; return super.parseMaybeAssign(...args); } if (typeParameters && typeParameters.params.length !== 0) { this.resetStartLocationFromNode(arrowExpression, typeParameters); } arrowExpression.typeParameters = typeParameters; return arrowExpression; } parseMaybeUnary(refShorthandDefaultPos) { if (!this.hasPlugin("jsx") && this.isRelational("<")) { return this.tsParseTypeAssertion(); } else { return super.parseMaybeUnary(refShorthandDefaultPos); } } parseArrow(node) { if (this.match(types.colon)) { const state = this.state.clone(); try { const returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon); if (this.canInsertSemicolon() || !this.match(types.arrow)) { this.state = state; return undefined; } node.returnType = returnType; } catch (err) { if (err instanceof SyntaxError) { this.state = state; } else { throw err; } } } return super.parseArrow(node); } parseAssignableListItemTypes(param) { if (this.eat(types.question)) { if (param.type !== "Identifier") { throw this.raise(param.start, "A binding pattern parameter cannot be optional in an implementation signature."); } param.optional = true; } const type = this.tsTryParseTypeAnnotation(); if (type) param.typeAnnotation = type; this.resetEndLocation(param); return param; } toAssignable(node, isBinding, contextDescription) { switch (node.type) { case "TSTypeCastExpression": return super.toAssignable(this.typeCastToParameter(node), isBinding, contextDescription); case "TSParameterProperty": return super.toAssignable(node, isBinding, contextDescription); case "TSAsExpression": case "TSNonNullExpression": case "TSTypeAssertion": node.expression = this.toAssignable(node.expression, isBinding, contextDescription); return node; default: return super.toAssignable(node, isBinding, contextDescription); } } checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription) { switch (expr.type) { case "TSTypeCastExpression": return; case "TSParameterProperty": this.checkLVal(expr.parameter, bindingType, checkClashes, "parameter property"); return; case "TSAsExpression": case "TSNonNullExpression": case "TSTypeAssertion": this.checkLVal(expr.expression, bindingType, checkClashes, contextDescription); return; default: super.checkLVal(expr, bindingType, checkClashes, contextDescription); return; } } parseBindingAtom() { switch (this.state.type) { case types._this: return this.parseIdentifier(true); default: return super.parseBindingAtom(); } } parseMaybeDecoratorArguments(expr) { if (this.isRelational("<")) { const typeArguments = this.tsParseTypeArguments(); if (this.match(types.parenL)) { const call = super.parseMaybeDecoratorArguments(expr); call.typeParameters = typeArguments; return call; } this.unexpected(this.state.start, types.parenL); } return super.parseMaybeDecoratorArguments(expr); } isClassMethod() { return this.isRelational("<") || super.isClassMethod(); } isClassProperty() { return this.match(types.bang) || this.match(types.colon) || super.isClassProperty(); } parseMaybeDefault(...args) { const node = super.parseMaybeDefault(...args); if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) { this.raise(node.typeAnnotation.start, "Type annotations must come before default assignments, " + "e.g. instead of `age = 25: number` use `age: number = 25`"); } return node; } getTokenFromCode(code) { if (this.state.inType && (code === 62 || code === 60)) { return this.finishOp(types.relational, 1); } else { return super.getTokenFromCode(code); } } toAssignableList(exprList, isBinding, contextDescription) { for (let i = 0; i < exprList.length; i++) { const expr = exprList[i]; if (!expr) continue; switch (expr.type) { case "TSTypeCastExpression": exprList[i] = this.typeCastToParameter(expr); break; case "TSAsExpression": case "TSTypeAssertion": this.raise(expr.start, "Unexpected type cast in parameter position."); break; } } return super.toAssignableList(exprList, isBinding, contextDescription); } typeCastToParameter(node) { node.expression.typeAnnotation = node.typeAnnotation; this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end); return node.expression; } toReferencedList(exprList, isInParens) { for (let i = 0; i < exprList.length; i++) { const expr = exprList[i]; if (expr && expr._exprListItem && expr.type === "TsTypeCastExpression") { this.raise(expr.start, "Did not expect a type annotation here."); } } return exprList; } shouldParseArrow() { return this.match(types.colon) || super.shouldParseArrow(); } shouldParseAsyncArrow() { return this.match(types.colon) || super.shouldParseAsyncArrow(); } canHaveLeadingDecorator() { return super.canHaveLeadingDecorator() || this.isAbstractClass(); } jsxParseOpeningElementAfterName(node) { if (this.isRelational("<")) { const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArguments()); if (typeArguments) node.typeParameters = typeArguments; } return super.jsxParseOpeningElementAfterName(node); } getGetterSetterExpectedParamCount(method) { const baseCount = super.getGetterSetterExpectedParamCount(method); const firstParam = method.params[0]; const hasContextParam = firstParam && firstParam.type === "Identifier" && firstParam.name === "this"; return hasContextParam ? baseCount + 1 : baseCount; } }); types.placeholder = new TokenType("%%", { startsExpr: true }); var placeholders = (superClass => class extends superClass { parsePlaceholder(expectedNode) { if (this.match(types.placeholder)) { const node = this.startNode(); this.next(); this.assertNoSpace("Unexpected space in placeholder."); node.name = super.parseIdentifier(true); this.assertNoSpace("Unexpected space in placeholder."); this.expect(types.placeholder); return this.finishPlaceholder(node, expectedNode); } } finishPlaceholder(node, expectedNode) { const isFinished = !!(node.expectedNode && node.type === "Placeholder"); node.expectedNode = expectedNode; return isFinished ? node : this.finishNode(node, "Placeholder"); } getTokenFromCode(code) { if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) { return this.finishOp(types.placeholder, 2); } return super.getTokenFromCode(...arguments); } parseExprAtom() { return this.parsePlaceholder("Expression") || super.parseExprAtom(...arguments); } parseIdentifier() { return this.parsePlaceholder("Identifier") || super.parseIdentifier(...arguments); } checkReservedWord(word) { if (word !== undefined) super.checkReservedWord(...arguments); } parseBindingAtom() { return this.parsePlaceholder("Pattern") || super.parseBindingAtom(...arguments); } checkLVal(expr) { if (expr.type !== "Placeholder") super.checkLVal(...arguments); } toAssignable(node) { if (node && node.type === "Placeholder" && node.expectedNode === "Expression") { node.expectedNode = "Pattern"; return node; } return super.toAssignable(...arguments); } verifyBreakContinue(node) { if (node.label && node.label.type === "Placeholder") return; super.verifyBreakContinue(...arguments); } parseExpressionStatement(node, expr) { if (expr.type !== "Placeholder" || expr.extra && expr.extra.parenthesized) { return super.parseExpressionStatement(...arguments); } if (this.match(types.colon)) { const stmt = node; stmt.label = this.finishPlaceholder(expr, "Identifier"); this.next(); stmt.body = this.parseStatement("label"); return this.finishNode(stmt, "LabeledStatement"); } this.semicolon(); node.name = expr.name; return this.finishPlaceholder(node, "Statement"); } parseBlock() { return this.parsePlaceholder("BlockStatement") || super.parseBlock(...arguments); } parseFunctionId() { return this.parsePlaceholder("Identifier") || super.parseFunctionId(...arguments); } parseClass(node, isStatement, optionalId) { const type = isStatement ? "ClassDeclaration" : "ClassExpression"; this.next(); this.takeDecorators(node); const placeholder = this.parsePlaceholder("Identifier"); if (placeholder) { if (this.match(types._extends) || this.match(types.placeholder) || this.match(types.braceL)) { node.id = placeholder; } else if (optionalId || !isStatement) { node.id = null; node.body = this.finishPlaceholder(placeholder, "ClassBody"); return this.finishNode(node, type); } else { this.unexpected(null, "A class name is required"); } } else { this.parseClassId(node, isStatement, optionalId); } this.parseClassSuper(node); node.body = this.parsePlaceholder("ClassBody") || this.parseClassBody(!!node.superClass); return this.finishNode(node, type); } parseExport(node) { const placeholder = this.parsePlaceholder("Identifier"); if (!placeholder) return super.parseExport(...arguments); if (!this.isContextual("from") && !this.match(types.comma)) { node.specifiers = []; node.source = null; node.declaration = this.finishPlaceholder(placeholder, "Declaration"); return this.finishNode(node, "ExportNamedDeclaration"); } this.expectPlugin("exportDefaultFrom"); const specifier = this.startNode(); specifier.exported = placeholder; node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")]; return super.parseExport(node); } maybeParseExportDefaultSpecifier(node) { if (node.specifiers && node.specifiers.length > 0) { return true; } return super.maybeParseExportDefaultSpecifier(...arguments); } checkExport(node) { const { specifiers } = node; if (specifiers && specifiers.length) { node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder"); } super.checkExport(node); node.specifiers = specifiers; } parseImport(node) { const placeholder = this.parsePlaceholder("Identifier"); if (!placeholder) return super.parseImport(...arguments); node.specifiers = []; if (!this.isContextual("from") && !this.match(types.comma)) { node.source = this.finishPlaceholder(placeholder, "StringLiteral"); this.semicolon(); return this.finishNode(node, "ImportDeclaration"); } const specifier = this.startNodeAtNode(placeholder); specifier.local = placeholder; this.finishNode(specifier, "ImportDefaultSpecifier"); node.specifiers.push(specifier); if (this.eat(types.comma)) { const hasStarImport = this.maybeParseStarImportSpecifier(node); if (!hasStarImport) this.parseNamedImportSpecifiers(node); } this.expectContextual("from"); node.source = this.parseImportSource(); this.semicolon(); return this.finishNode(node, "ImportDeclaration"); } parseImportSource() { return this.parsePlaceholder("StringLiteral") || super.parseImportSource(...arguments); } }); function hasPlugin(plugins, name) { return plugins.some(plugin => { if (Array.isArray(plugin)) { return plugin[0] === name; } else { return plugin === name; } }); } function getPluginOption(plugins, name, option) { const plugin = plugins.find(plugin => { if (Array.isArray(plugin)) { return plugin[0] === name; } else { return plugin === name; } }); if (plugin && Array.isArray(plugin)) { return plugin[1][option]; } return null; } const PIPELINE_PROPOSALS = ["minimal", "smart"]; function validatePlugins(plugins) { if (hasPlugin(plugins, "decorators")) { if (hasPlugin(plugins, "decorators-legacy")) { throw new Error("Cannot use the decorators and decorators-legacy plugin together"); } const decoratorsBeforeExport = getPluginOption(plugins, "decorators", "decoratorsBeforeExport"); if (decoratorsBeforeExport == null) { throw new Error("The 'decorators' plugin requires a 'decoratorsBeforeExport' option," + " whose value must be a boolean. If you are migrating from" + " Babylon/Babel 6 or want to use the old decorators proposal, you" + " should use the 'decorators-legacy' plugin instead of 'decorators'."); } else if (typeof decoratorsBeforeExport !== "boolean") { throw new Error("'decoratorsBeforeExport' must be a boolean."); } } if (hasPlugin(plugins, "flow") && hasPlugin(plugins, "typescript")) { throw new Error("Cannot combine flow and typescript plugins."); } if (hasPlugin(plugins, "pipelineOperator") && !PIPELINE_PROPOSALS.includes(getPluginOption(plugins, "pipelineOperator", "proposal"))) { throw new Error("'pipelineOperator' requires 'proposal' option whose value should be one of: " + PIPELINE_PROPOSALS.map(p => `'${p}'`).join(", ")); } } const mixinPlugins = { estree, jsx, flow, typescript, placeholders }; const mixinPluginNames = Object.keys(mixinPlugins); const defaultOptions = { sourceType: "script", sourceFilename: undefined, startLine: 1, allowAwaitOutsideFunction: false, allowReturnOutsideFunction: false, allowImportExportEverywhere: false, allowSuperOutsideMethod: false, plugins: [], strictMode: null, ranges: false, tokens: false, createParenthesizedExpressions: false }; function getOptions(opts) { const options = {}; for (let _i = 0, _Object$keys = Object.keys(defaultOptions); _i < _Object$keys.length; _i++) { const key = _Object$keys[_i]; options[key] = opts && opts[key] != null ? opts[key] : defaultOptions[key]; } return options; } class Position { constructor(line, col) { this.line = line; this.column = col; } } class SourceLocation { constructor(start, end) { this.start = start; this.end = end; } } function getLineInfo(input, offset) { let line = 1; let lineStart = 0; let match; lineBreakG.lastIndex = 0; while ((match = lineBreakG.exec(input)) && match.index < offset) { line++; lineStart = lineBreakG.lastIndex; } return new Position(line, offset - lineStart); } class BaseParser { constructor() { this.sawUnambiguousESM = false; } hasPlugin(name) { return this.plugins.has(name); } getPluginOption(plugin, name) { if (this.hasPlugin(plugin)) return this.plugins.get(plugin)[name]; } } function last(stack) { return stack[stack.length - 1]; } class CommentsParser extends BaseParser { addComment(comment) { if (this.filename) comment.loc.filename = this.filename; this.state.trailingComments.push(comment); this.state.leadingComments.push(comment); } processComment(node) { if (node.type === "Program" && node.body.length > 0) return; const stack = this.state.commentStack; let firstChild, lastChild, trailingComments, i, j; if (this.state.trailingComments.length > 0) { if (this.state.trailingComments[0].start >= node.end) { trailingComments = this.state.trailingComments; this.state.trailingComments = []; } else { this.state.trailingComments.length = 0; } } else if (stack.length > 0) { const lastInStack = last(stack); if (lastInStack.trailingComments && lastInStack.trailingComments[0].start >= node.end) { trailingComments = lastInStack.trailingComments; delete lastInStack.trailingComments; } } if (stack.length > 0 && last(stack).start >= node.start) { firstChild = stack.pop(); } while (stack.length > 0 && last(stack).start >= node.start) { lastChild = stack.pop(); } if (!lastChild && firstChild) lastChild = firstChild; if (firstChild && this.state.leadingComments.length > 0) { const lastComment = last(this.state.leadingComments); if (firstChild.type === "ObjectProperty") { if (lastComment.start >= node.start) { if (this.state.commentPreviousNode) { for (j = 0; j < this.state.leadingComments.length; j++) { if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) { this.state.leadingComments.splice(j, 1); j--; } } if (this.state.leadingComments.length > 0) { firstChild.trailingComments = this.state.leadingComments; this.state.leadingComments = []; } } } } else if (node.type === "CallExpression" && node.arguments && node.arguments.length) { const lastArg = last(node.arguments); if (lastArg && lastComment.start >= lastArg.start && lastComment.end <= node.end) { if (this.state.commentPreviousNode) { for (j = 0; j < this.state.leadingComments.length; j++) { if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) { this.state.leadingComments.splice(j, 1); j--; } } if (this.state.leadingComments.length > 0) { lastArg.trailingComments = this.state.leadingComments; this.state.leadingComments = []; } } } } } if (lastChild) { if (lastChild.leadingComments) { if (lastChild !== node && lastChild.leadingComments.length > 0 && last(lastChild.leadingComments).end <= node.start) { node.leadingComments = lastChild.leadingComments; delete lastChild.leadingComments; } else { for (i = lastChild.leadingComments.length - 2; i >= 0; --i) { if (lastChild.leadingComments[i].end <= node.start) { node.leadingComments = lastChild.leadingComments.splice(0, i + 1); break; } } } } } else if (this.state.leadingComments.length > 0) { if (last(this.state.leadingComments).end <= node.start) { if (this.state.commentPreviousNode) { for (j = 0; j < this.state.leadingComments.length; j++) { if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) { this.state.leadingComments.splice(j, 1); j--; } } } if (this.state.leadingComments.length > 0) { node.leadingComments = this.state.leadingComments; this.state.leadingComments = []; } } else { for (i = 0; i < this.state.leadingComments.length; i++) { if (this.state.leadingComments[i].end > node.start) { break; } } const leadingComments = this.state.leadingComments.slice(0, i); if (leadingComments.length) { node.leadingComments = leadingComments; } trailingComments = this.state.leadingComments.slice(i); if (trailingComments.length === 0) { trailingComments = null; } } } this.state.commentPreviousNode = node; if (trailingComments) { if (trailingComments.length && trailingComments[0].start >= node.start && last(trailingComments).end <= node.end) { node.innerComments = trailingComments; } else { node.trailingComments = trailingComments; } } stack.push(node); } } class LocationParser extends CommentsParser { getLocationForPosition(pos) { let loc; if (pos === this.state.start) loc = this.state.startLoc;else if (pos === this.state.lastTokStart) loc = this.state.lastTokStartLoc;else if (pos === this.state.end) loc = this.state.endLoc;else if (pos === this.state.lastTokEnd) loc = this.state.lastTokEndLoc;else loc = getLineInfo(this.input, pos); return loc; } raise(pos, message, { missingPluginNames, code } = {}) { const loc = this.getLocationForPosition(pos); message += ` (${loc.line}:${loc.column})`; const err = new SyntaxError(message); err.pos = pos; err.loc = loc; if (missingPluginNames) { err.missingPlugin = missingPluginNames; } if (code !== undefined) { err.code = code; } throw err; } } class State { constructor() { this.potentialArrowAt = -1; this.noArrowAt = []; this.noArrowParamsConversionAt = []; this.commaAfterSpreadAt = -1; this.inParameters = false; this.maybeInArrowParameters = false; this.inPipeline = false; this.inType = false; this.noAnonFunctionType = false; this.inPropertyName = false; this.inClassProperty = false; this.hasFlowComment = false; this.isIterator = false; this.topicContext = { maxNumOfResolvableTopics: 0, maxTopicIndex: null }; this.classLevel = 0; this.labels = []; this.decoratorStack = [[]]; this.yieldPos = 0; this.awaitPos = 0; this.tokens = []; this.comments = []; this.trailingComments = []; this.leadingComments = []; this.commentStack = []; this.commentPreviousNode = null; this.pos = 0; this.lineStart = 0; this.type = types.eof; this.value = null; this.start = 0; this.end = 0; this.lastTokEndLoc = null; this.lastTokStartLoc = null; this.lastTokStart = 0; this.lastTokEnd = 0; this.context = [types$1.braceStatement]; this.exprAllowed = true; this.containsEsc = false; this.containsOctal = false; this.octalPosition = null; this.exportedIdentifiers = []; this.invalidTemplateEscapePosition = null; } init(options) { this.strict = options.strictMode === false ? false : options.sourceType === "module"; this.curLine = options.startLine; this.startLoc = this.endLoc = this.curPosition(); } curPosition() { return new Position(this.curLine, this.pos - this.lineStart); } clone(skipArrays) { const state = new State(); const keys = Object.keys(this); for (let i = 0, length = keys.length; i < length; i++) { const key = keys[i]; let val = this[key]; if (!skipArrays && Array.isArray(val)) { val = val.slice(); } state[key] = val; } return state; } } var _isDigit = function isDigit(code) { return code >= 48 && code <= 57; }; const VALID_REGEX_FLAGS = new Set(["g", "m", "s", "i", "y", "u"]); const forbiddenNumericSeparatorSiblings = { decBinOct: [46, 66, 69, 79, 95, 98, 101, 111], hex: [46, 88, 95, 120] }; const allowedNumericSeparatorSiblings = {}; allowedNumericSeparatorSiblings.bin = [48, 49]; allowedNumericSeparatorSiblings.oct = [...allowedNumericSeparatorSiblings.bin, 50, 51, 52, 53, 54, 55]; allowedNumericSeparatorSiblings.dec = [...allowedNumericSeparatorSiblings.oct, 56, 57]; allowedNumericSeparatorSiblings.hex = [...allowedNumericSeparatorSiblings.dec, 65, 66, 67, 68, 69, 70, 97, 98, 99, 100, 101, 102]; class Token { constructor(state) { this.type = state.type; this.value = state.value; this.start = state.start; this.end = state.end; this.loc = new SourceLocation(state.startLoc, state.endLoc); } } class Tokenizer extends LocationParser { constructor(options, input) { super(); this.state = new State(); this.state.init(options); this.input = input; this.length = input.length; this.isLookahead = false; } next() { if (this.options.tokens && !this.isLookahead) { this.state.tokens.push(new Token(this.state)); } this.state.lastTokEnd = this.state.end; this.state.lastTokStart = this.state.start; this.state.lastTokEndLoc = this.state.endLoc; this.state.lastTokStartLoc = this.state.startLoc; this.nextToken(); } eat(type) { if (this.match(type)) { this.next(); return true; } else { return false; } } match(type) { return this.state.type === type; } lookahead() { const old = this.state; this.state = old.clone(true); this.isLookahead = true; this.next(); this.isLookahead = false; const curr = this.state; this.state = old; return curr; } setStrict(strict) { this.state.strict = strict; if (!this.match(types.num) && !this.match(types.string)) return; this.state.pos = this.state.start; while (this.state.pos < this.state.lineStart) { this.state.lineStart = this.input.lastIndexOf("\n", this.state.lineStart - 2) + 1; --this.state.curLine; } this.nextToken(); } curContext() { return this.state.context[this.state.context.length - 1]; } nextToken() { const curContext = this.curContext(); if (!curContext || !curContext.preserveSpace) this.skipSpace(); this.state.containsOctal = false; this.state.octalPosition = null; this.state.start = this.state.pos; this.state.startLoc = this.state.curPosition(); if (this.state.pos >= this.length) { this.finishToken(types.eof); return; } if (curContext.override) { curContext.override(this); } else { this.getTokenFromCode(this.input.codePointAt(this.state.pos)); } } pushComment(block, text, start, end, startLoc, endLoc) { const comment = { type: block ? "CommentBlock" : "CommentLine", value: text, start: start, end: end, loc: new SourceLocation(startLoc, endLoc) }; if (this.options.tokens) this.state.tokens.push(comment); this.state.comments.push(comment); this.addComment(comment); } skipBlockComment() { const startLoc = this.state.curPosition(); const start = this.state.pos; const end = this.input.indexOf("*/", this.state.pos += 2); if (end === -1) this.raise(this.state.pos - 2, "Unterminated comment"); this.state.pos = end + 2; lineBreakG.lastIndex = start; let match; while ((match = lineBreakG.exec(this.input)) && match.index < this.state.pos) { ++this.state.curLine; this.state.lineStart = match.index + match[0].length; } if (this.isLookahead) return; this.pushComment(true, this.input.slice(start + 2, end), start, this.state.pos, startLoc, this.state.curPosition()); } skipLineComment(startSkip) { const start = this.state.pos; const startLoc = this.state.curPosition(); let ch = this.input.charCodeAt(this.state.pos += startSkip); if (this.state.pos < this.length) { while (ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233 && ++this.state.pos < this.length) { ch = this.input.charCodeAt(this.state.pos); } } if (this.isLookahead) return; this.pushComment(false, this.input.slice(start + startSkip, this.state.pos), start, this.state.pos, startLoc, this.state.curPosition()); } skipSpace() { loop: while (this.state.pos < this.length) { const ch = this.input.charCodeAt(this.state.pos); switch (ch) { case 32: case 160: case 9: ++this.state.pos; break; case 13: if (this.input.charCodeAt(this.state.pos + 1) === 10) { ++this.state.pos; } case 10: case 8232: case 8233: ++this.state.pos; ++this.state.curLine; this.state.lineStart = this.state.pos; break; case 47: switch (this.input.charCodeAt(this.state.pos + 1)) { case 42: this.skipBlockComment(); break; case 47: this.skipLineComment(2); break; default: break loop; } break; default: if (isWhitespace(ch)) { ++this.state.pos; } else { break loop; } } } } finishToken(type, val) { this.state.end = this.state.pos; this.state.endLoc = this.state.curPosition(); const prevType = this.state.type; this.state.type = type; this.state.value = val; if (!this.isLookahead) this.updateContext(prevType); } readToken_numberSign() { if (this.state.pos === 0 && this.readToken_interpreter()) { return; } const nextPos = this.state.pos + 1; const next = this.input.charCodeAt(nextPos); if (next >= 48 && next <= 57) { this.raise(this.state.pos, "Unexpected digit after hash token"); } if ((this.hasPlugin("classPrivateProperties") || this.hasPlugin("classPrivateMethods")) && this.state.classLevel > 0) { ++this.state.pos; this.finishToken(types.hash); return; } else if (this.getPluginOption("pipelineOperator", "proposal") === "smart") { this.finishOp(types.hash, 1); } else { this.raise(this.state.pos, "Unexpected character '#'"); } } readToken_dot() { const next = this.input.charCodeAt(this.state.pos + 1); if (next >= 48 && next <= 57) { this.readNumber(true); return; } const next2 = this.input.charCodeAt(this.state.pos + 2); if (next === 46 && next2 === 46) { this.state.pos += 3; this.finishToken(types.ellipsis); } else { ++this.state.pos; this.finishToken(types.dot); } } readToken_slash() { if (this.state.exprAllowed && !this.state.inType) { ++this.state.pos; this.readRegexp(); return; } const next = this.input.charCodeAt(this.state.pos + 1); if (next === 61) { this.finishOp(types.assign, 2); } else { this.finishOp(types.slash, 1); } } readToken_interpreter() { if (this.state.pos !== 0 || this.length < 2) return false; const start = this.state.pos; this.state.pos += 1; let ch = this.input.charCodeAt(this.state.pos); if (ch !== 33) return false; while (ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233 && ++this.state.pos < this.length) { ch = this.input.charCodeAt(this.state.pos); } const value = this.input.slice(start + 2, this.state.pos); this.finishToken(types.interpreterDirective, value); return true; } readToken_mult_modulo(code) { let type = code === 42 ? types.star : types.modulo; let width = 1; let next = this.input.charCodeAt(this.state.pos + 1); const exprAllowed = this.state.exprAllowed; if (code === 42 && next === 42) { width++; next = this.input.charCodeAt(this.state.pos + 2); type = types.exponent; } if (next === 61 && !exprAllowed) { width++; type = types.assign; } this.finishOp(type, width); } readToken_pipe_amp(code) { const next = this.input.charCodeAt(this.state.pos + 1); if (next === code) { if (this.input.charCodeAt(this.state.pos + 2) === 61) { this.finishOp(types.assign, 3); } else { this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2); } return; } if (code === 124) { if (next === 62) { this.finishOp(types.pipeline, 2); return; } } if (next === 61) { this.finishOp(types.assign, 2); return; } this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1); } readToken_caret() { const next = this.input.charCodeAt(this.state.pos + 1); if (next === 61) { this.finishOp(types.assign, 2); } else { this.finishOp(types.bitwiseXOR, 1); } } readToken_plus_min(code) { const next = this.input.charCodeAt(this.state.pos + 1); if (next === code) { if (next === 45 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 62 && (this.state.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.pos)))) { this.skipLineComment(3); this.skipSpace(); this.nextToken(); return; } this.finishOp(types.incDec, 2); return; } if (next === 61) { this.finishOp(types.assign, 2); } else { this.finishOp(types.plusMin, 1); } } readToken_lt_gt(code) { const next = this.input.charCodeAt(this.state.pos + 1); let size = 1; if (next === code) { size = code === 62 && this.input.charCodeAt(this.state.pos + 2) === 62 ? 3 : 2; if (this.input.charCodeAt(this.state.pos + size) === 61) { this.finishOp(types.assign, size + 1); return; } this.finishOp(types.bitShift, size); return; } if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 45 && this.input.charCodeAt(this.state.pos + 3) === 45) { this.skipLineComment(4); this.skipSpace(); this.nextToken(); return; } if (next === 61) { size = 2; } this.finishOp(types.relational, size); } readToken_eq_excl(code) { const next = this.input.charCodeAt(this.state.pos + 1); if (next === 61) { this.finishOp(types.equality, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2); return; } if (code === 61 && next === 62) { this.state.pos += 2; this.finishToken(types.arrow); return; } this.finishOp(code === 61 ? types.eq : types.bang, 1); } readToken_question() { const next = this.input.charCodeAt(this.state.pos + 1); const next2 = this.input.charCodeAt(this.state.pos + 2); if (next === 63 && !this.state.inType) { if (next2 === 61) { this.finishOp(types.assign, 3); } else { this.finishOp(types.nullishCoalescing, 2); } } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) { this.state.pos += 2; this.finishToken(types.questionDot); } else { ++this.state.pos; this.finishToken(types.question); } } getTokenFromCode(code) { switch (code) { case 46: this.readToken_dot(); return; case 40: ++this.state.pos; this.finishToken(types.parenL); return; case 41: ++this.state.pos; this.finishToken(types.parenR); return; case 59: ++this.state.pos; this.finishToken(types.semi); return; case 44: ++this.state.pos; this.finishToken(types.comma); return; case 91: ++this.state.pos; this.finishToken(types.bracketL); return; case 93: ++this.state.pos; this.finishToken(types.bracketR); return; case 123: ++this.state.pos; this.finishToken(types.braceL); return; case 125: ++this.state.pos; this.finishToken(types.braceR); return; case 58: if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) { this.finishOp(types.doubleColon, 2); } else { ++this.state.pos; this.finishToken(types.colon); } return; case 63: this.readToken_question(); return; case 96: ++this.state.pos; this.finishToken(types.backQuote); return; case 48: { const next = this.input.charCodeAt(this.state.pos + 1); if (next === 120 || next === 88) { this.readRadixNumber(16); return; } if (next === 111 || next === 79) { this.readRadixNumber(8); return; } if (next === 98 || next === 66) { this.readRadixNumber(2); return; } } case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: this.readNumber(false); return; case 34: case 39: this.readString(code); return; case 47: this.readToken_slash(); return; case 37: case 42: this.readToken_mult_modulo(code); return; case 124: case 38: this.readToken_pipe_amp(code); return; case 94: this.readToken_caret(); return; case 43: case 45: this.readToken_plus_min(code); return; case 60: case 62: this.readToken_lt_gt(code); return; case 61: case 33: this.readToken_eq_excl(code); return; case 126: this.finishOp(types.tilde, 1); return; case 64: ++this.state.pos; this.finishToken(types.at); return; case 35: this.readToken_numberSign(); return; case 92: this.readWord(); return; default: if (isIdentifierStart(code)) { this.readWord(); return; } } this.raise(this.state.pos, `Unexpected character '${String.fromCodePoint(code)}'`); } finishOp(type, size) { const str = this.input.slice(this.state.pos, this.state.pos + size); this.state.pos += size; this.finishToken(type, str); } readRegexp() { const start = this.state.pos; let escaped, inClass; for (;;) { if (this.state.pos >= this.length) { this.raise(start, "Unterminated regular expression"); } const ch = this.input.charAt(this.state.pos); if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); } if (escaped) { escaped = false; } else { if (ch === "[") { inClass = true; } else if (ch === "]" && inClass) { inClass = false; } else if (ch === "/" && !inClass) { break; } escaped = ch === "\\"; } ++this.state.pos; } const content = this.input.slice(start, this.state.pos); ++this.state.pos; let mods = ""; while (this.state.pos < this.length) { const char = this.input[this.state.pos]; const charCode = this.input.codePointAt(this.state.pos); if (VALID_REGEX_FLAGS.has(char)) { if (mods.indexOf(char) > -1) { this.raise(this.state.pos + 1, "Duplicate regular expression flag"); } ++this.state.pos; mods += char; } else if (isIdentifierChar(charCode) || charCode === 92) { this.raise(this.state.pos + 1, "Invalid regular expression flag"); } else { break; } } this.finishToken(types.regexp, { pattern: content, flags: mods }); } readInt(radix, len) { const start = this.state.pos; const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct; const allowedSiblings = radix === 16 ? allowedNumericSeparatorSiblings.hex : radix === 10 ? allowedNumericSeparatorSiblings.dec : radix === 8 ? allowedNumericSeparatorSiblings.oct : allowedNumericSeparatorSiblings.bin; let total = 0; for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) { const code = this.input.charCodeAt(this.state.pos); let val; if (this.hasPlugin("numericSeparator")) { const prev = this.input.charCodeAt(this.state.pos - 1); const next = this.input.charCodeAt(this.state.pos + 1); if (code === 95) { if (allowedSiblings.indexOf(next) === -1) { this.raise(this.state.pos, "Invalid or unexpected token"); } if (forbiddenSiblings.indexOf(prev) > -1 || forbiddenSiblings.indexOf(next) > -1 || Number.isNaN(next)) { this.raise(this.state.pos, "Invalid or unexpected token"); } ++this.state.pos; continue; } } if (code >= 97) { val = code - 97 + 10; } else if (code >= 65) { val = code - 65 + 10; } else if (_isDigit(code)) { val = code - 48; } else { val = Infinity; } if (val >= radix) break; ++this.state.pos; total = total * radix + val; } if (this.state.pos === start || len != null && this.state.pos - start !== len) { return null; } return total; } readRadixNumber(radix) { const start = this.state.pos; let isBigInt = false; this.state.pos += 2; const val = this.readInt(radix); if (val == null) { this.raise(this.state.start + 2, "Expected number in radix " + radix); } if (this.hasPlugin("bigInt")) { if (this.input.charCodeAt(this.state.pos) === 110) { ++this.state.pos; isBigInt = true; } } if (isIdentifierStart(this.input.codePointAt(this.state.pos))) { this.raise(this.state.pos, "Identifier directly after number"); } if (isBigInt) { const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, ""); this.finishToken(types.bigint, str); return; } this.finishToken(types.num, val); } readNumber(startsWithDot) { const start = this.state.pos; let isFloat = false; let isBigInt = false; if (!startsWithDot && this.readInt(10) === null) { this.raise(start, "Invalid number"); } let octal = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48; if (octal) { if (this.state.strict) { this.raise(start, "Legacy octal literals are not allowed in strict mode"); } if (/[89]/.test(this.input.slice(start, this.state.pos))) { octal = false; } } let next = this.input.charCodeAt(this.state.pos); if (next === 46 && !octal) { ++this.state.pos; this.readInt(10); isFloat = true; next = this.input.charCodeAt(this.state.pos); } if ((next === 69 || next === 101) && !octal) { next = this.input.charCodeAt(++this.state.pos); if (next === 43 || next === 45) { ++this.state.pos; } if (this.readInt(10) === null) this.raise(start, "Invalid number"); isFloat = true; next = this.input.charCodeAt(this.state.pos); } if (this.hasPlugin("bigInt")) { if (next === 110) { if (isFloat || octal) this.raise(start, "Invalid BigIntLiteral"); ++this.state.pos; isBigInt = true; } } if (isIdentifierStart(this.input.codePointAt(this.state.pos))) { this.raise(this.state.pos, "Identifier directly after number"); } const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, ""); if (isBigInt) { this.finishToken(types.bigint, str); return; } const val = octal ? parseInt(str, 8) : parseFloat(str); this.finishToken(types.num, val); } readCodePoint(throwOnInvalid) { const ch = this.input.charCodeAt(this.state.pos); let code; if (ch === 123) { const codePos = ++this.state.pos; code = this.readHexChar(this.input.indexOf("}", this.state.pos) - this.state.pos, throwOnInvalid); ++this.state.pos; if (code === null) { --this.state.invalidTemplateEscapePosition; } else if (code > 0x10ffff) { if (throwOnInvalid) { this.raise(codePos, "Code point out of bounds"); } else { this.state.invalidTemplateEscapePosition = codePos - 2; return null; } } } else { code = this.readHexChar(4, throwOnInvalid); } return code; } readString(quote) { let out = "", chunkStart = ++this.state.pos; for (;;) { if (this.state.pos >= this.length) { this.raise(this.state.start, "Unterminated string constant"); } const ch = this.input.charCodeAt(this.state.pos); if (ch === quote) break; if (ch === 92) { out += this.input.slice(chunkStart, this.state.pos); out += this.readEscapedChar(false); chunkStart = this.state.pos; } else if (ch === 8232 || ch === 8233) { ++this.state.pos; ++this.state.curLine; } else if (isNewLine(ch)) { this.raise(this.state.start, "Unterminated string constant"); } else { ++this.state.pos; } } out += this.input.slice(chunkStart, this.state.pos++); this.finishToken(types.string, out); } readTmplToken() { let out = "", chunkStart = this.state.pos, containsInvalid = false; for (;;) { if (this.state.pos >= this.length) { this.raise(this.state.start, "Unterminated template"); } const ch = this.input.charCodeAt(this.state.pos); if (ch === 96 || ch === 36 && this.input.charCodeAt(this.state.pos + 1) === 123) { if (this.state.pos === this.state.start && this.match(types.template)) { if (ch === 36) { this.state.pos += 2; this.finishToken(types.dollarBraceL); return; } else { ++this.state.pos; this.finishToken(types.backQuote); return; } } out += this.input.slice(chunkStart, this.state.pos); this.finishToken(types.template, containsInvalid ? null : out); return; } if (ch === 92) { out += this.input.slice(chunkStart, this.state.pos); const escaped = this.readEscapedChar(true); if (escaped === null) { containsInvalid = true; } else { out += escaped; } chunkStart = this.state.pos; } else if (isNewLine(ch)) { out += this.input.slice(chunkStart, this.state.pos); ++this.state.pos; switch (ch) { case 13: if (this.input.charCodeAt(this.state.pos) === 10) { ++this.state.pos; } case 10: out += "\n"; break; default: out += String.fromCharCode(ch); break; } ++this.state.curLine; this.state.lineStart = this.state.pos; chunkStart = this.state.pos; } else { ++this.state.pos; } } } readEscapedChar(inTemplate) { const throwOnInvalid = !inTemplate; const ch = this.input.charCodeAt(++this.state.pos); ++this.state.pos; switch (ch) { case 110: return "\n"; case 114: return "\r"; case 120: { const code = this.readHexChar(2, throwOnInvalid); return code === null ? null : String.fromCharCode(code); } case 117: { const code = this.readCodePoint(throwOnInvalid); return code === null ? null : String.fromCodePoint(code); } case 116: return "\t"; case 98: return "\b"; case 118: return "\u000b"; case 102: return "\f"; case 13: if (this.input.charCodeAt(this.state.pos) === 10) { ++this.state.pos; } case 10: this.state.lineStart = this.state.pos; ++this.state.curLine; case 8232: case 8233: return ""; default: if (ch >= 48 && ch <= 55) { const codePos = this.state.pos - 1; let octalStr = this.input.substr(this.state.pos - 1, 3).match(/^[0-7]+/)[0]; let octal = parseInt(octalStr, 8); if (octal > 255) { octalStr = octalStr.slice(0, -1); octal = parseInt(octalStr, 8); } this.state.pos += octalStr.length - 1; const next = this.input.charCodeAt(this.state.pos); if (octalStr !== "0" || next === 56 || next === 57) { if (inTemplate) { this.state.invalidTemplateEscapePosition = codePos; return null; } else if (this.state.strict) { this.raise(codePos, "Octal literal in strict mode"); } else if (!this.state.containsOctal) { this.state.containsOctal = true; this.state.octalPosition = codePos; } } return String.fromCharCode(octal); } return String.fromCharCode(ch); } } readHexChar(len, throwOnInvalid) { const codePos = this.state.pos; const n = this.readInt(16, len); if (n === null) { if (throwOnInvalid) { this.raise(codePos, "Bad character escape sequence"); } else { this.state.pos = codePos - 1; this.state.invalidTemplateEscapePosition = codePos - 1; } } return n; } readWord1() { let word = ""; this.state.containsEsc = false; const start = this.state.pos; let chunkStart = this.state.pos; while (this.state.pos < this.length) { const ch = this.input.codePointAt(this.state.pos); if (isIdentifierChar(ch)) { this.state.pos += ch <= 0xffff ? 1 : 2; } else if (this.state.isIterator && ch === 64) { ++this.state.pos; } else if (ch === 92) { this.state.containsEsc = true; word += this.input.slice(chunkStart, this.state.pos); const escStart = this.state.pos; const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar; if (this.input.charCodeAt(++this.state.pos) !== 117) { this.raise(this.state.pos, "Expecting Unicode escape sequence \\uXXXX"); } ++this.state.pos; const esc = this.readCodePoint(true); if (!identifierCheck(esc, true)) { this.raise(escStart, "Invalid Unicode escape"); } word += String.fromCodePoint(esc); chunkStart = this.state.pos; } else { break; } } return word + this.input.slice(chunkStart, this.state.pos); } isIterator(word) { return word === "@@iterator" || word === "@@asyncIterator"; } readWord() { const word = this.readWord1(); const type = keywords.get(word) || types.name; if (type.keyword && this.state.containsEsc) { this.raise(this.state.pos, `Escape sequence in keyword ${word}`); } if (this.state.isIterator && (!this.isIterator(word) || !this.state.inType)) { this.raise(this.state.pos, `Invalid identifier ${word}`); } this.finishToken(type, word); } braceIsBlock(prevType) { const parent = this.curContext(); if (parent === types$1.functionExpression || parent === types$1.functionStatement) { return true; } if (prevType === types.colon && (parent === types$1.braceStatement || parent === types$1.braceExpression)) { return !parent.isExpr; } if (prevType === types._return || prevType === types.name && this.state.exprAllowed) { return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start)); } if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow) { return true; } if (prevType === types.braceL) { return parent === types$1.braceStatement; } if (prevType === types._var || prevType === types._const || prevType === types.name) { return false; } if (prevType === types.relational) { return true; } return !this.state.exprAllowed; } updateContext(prevType) { const type = this.state.type; let update; if (type.keyword && (prevType === types.dot || prevType === types.questionDot)) { this.state.exprAllowed = false; } else if (update = type.updateContext) { update.call(this, prevType); } else { this.state.exprAllowed = type.beforeExpr; } } } const literal = /^('|")((?:\\?.)*?)\1/; class UtilParser extends Tokenizer { addExtra(node, key, val) { if (!node) return; const extra = node.extra = node.extra || {}; extra[key] = val; } isRelational(op) { return this.match(types.relational) && this.state.value === op; } isLookaheadRelational(op) { const l = this.lookahead(); return l.type === types.relational && l.value === op; } expectRelational(op) { if (this.isRelational(op)) { this.next(); } else { this.unexpected(null, types.relational); } } eatRelational(op) { if (this.isRelational(op)) { this.next(); return true; } return false; } isContextual(name) { return this.match(types.name) && this.state.value === name && !this.state.containsEsc; } isLookaheadContextual(name) { const l = this.lookahead(); return l.type === types.name && l.value === name; } eatContextual(name) { return this.isContextual(name) && this.eat(types.name); } expectContextual(name, message) { if (!this.eatContextual(name)) this.unexpected(null, message); } canInsertSemicolon() { return this.match(types.eof) || this.match(types.braceR) || this.hasPrecedingLineBreak(); } hasPrecedingLineBreak() { return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start)); } isLineTerminator() { return this.eat(types.semi) || this.canInsertSemicolon(); } semicolon() { if (!this.isLineTerminator()) this.unexpected(null, types.semi); } expect(type, pos) { this.eat(type) || this.unexpected(pos, type); } assertNoSpace(message = "Unexpected space.") { if (this.state.start > this.state.lastTokEnd) { this.raise(this.state.lastTokEnd, message); } } unexpected(pos, messageOrType = "Unexpected token") { if (typeof messageOrType !== "string") { messageOrType = `Unexpected token, expected "${messageOrType.label}"`; } throw this.raise(pos != null ? pos : this.state.start, messageOrType); } expectPlugin(name, pos) { if (!this.hasPlugin(name)) { throw this.raise(pos != null ? pos : this.state.start, `This experimental syntax requires enabling the parser plugin: '${name}'`, { missingPluginNames: [name] }); } return true; } expectOnePlugin(names, pos) { if (!names.some(n => this.hasPlugin(n))) { throw this.raise(pos != null ? pos : this.state.start, `This experimental syntax requires enabling one of the following parser plugin(s): '${names.join(", ")}'`, { missingPluginNames: names }); } } checkYieldAwaitInDefaultParams() { if (this.state.yieldPos && (!this.state.awaitPos || this.state.yieldPos < this.state.awaitPos)) { this.raise(this.state.yieldPos, "Yield cannot be used as name inside a generator function"); } if (this.state.awaitPos) { this.raise(this.state.awaitPos, "Await cannot be used as name inside an async function"); } } strictDirective(start) { for (;;) { skipWhiteSpace.lastIndex = start; start += skipWhiteSpace.exec(this.input)[0].length; const match = literal.exec(this.input.slice(start)); if (!match) break; if (match[2] === "use strict") return true; start += match[0].length; skipWhiteSpace.lastIndex = start; start += skipWhiteSpace.exec(this.input)[0].length; if (this.input[start] === ";") { start++; } } return false; } } class Node { constructor(parser, pos, loc) { this.type = ""; this.start = pos; this.end = 0; this.loc = new SourceLocation(loc); if (parser && parser.options.ranges) this.range = [pos, 0]; if (parser && parser.filename) this.loc.filename = parser.filename; } __clone() { const newNode = new Node(); const keys = Object.keys(this); for (let i = 0, length = keys.length; i < length; i++) { const key = keys[i]; if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") { newNode[key] = this[key]; } } return newNode; } } class NodeUtils extends UtilParser { startNode() { return new Node(this, this.state.start, this.state.startLoc); } startNodeAt(pos, loc) { return new Node(this, pos, loc); } startNodeAtNode(type) { return this.startNodeAt(type.start, type.loc.start); } finishNode(node, type) { return this.finishNodeAt(node, type, this.state.lastTokEnd, this.state.lastTokEndLoc); } finishNodeAt(node, type, pos, loc) { node.type = type; node.end = pos; node.loc.end = loc; if (this.options.ranges) node.range[1] = pos; this.processComment(node); return node; } resetStartLocation(node, start, startLoc) { node.start = start; node.loc.start = startLoc; if (this.options.ranges) node.range[0] = start; } resetEndLocation(node, end = this.state.lastTokEnd, endLoc = this.state.lastTokEndLoc) { node.end = end; node.loc.end = endLoc; if (this.options.ranges) node.range[1] = end; } resetStartLocationFromNode(node, locationNode) { this.resetStartLocation(node, locationNode.start, locationNode.loc.start); } } class LValParser extends NodeUtils { toAssignable(node, isBinding, contextDescription) { if (node) { switch (node.type) { case "Identifier": case "ObjectPattern": case "ArrayPattern": case "AssignmentPattern": break; case "ObjectExpression": node.type = "ObjectPattern"; for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) { const prop = node.properties[i]; const isLast = i === last; this.toAssignableObjectExpressionProp(prop, isBinding, isLast); } break; case "ObjectProperty": this.toAssignable(node.value, isBinding, contextDescription); break; case "SpreadElement": { this.checkToRestConversion(node); node.type = "RestElement"; const arg = node.argument; this.toAssignable(arg, isBinding, contextDescription); break; } case "ArrayExpression": node.type = "ArrayPattern"; this.toAssignableList(node.elements, isBinding, contextDescription); break; case "AssignmentExpression": if (node.operator === "=") { node.type = "AssignmentPattern"; delete node.operator; } else { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); } break; case "ParenthesizedExpression": node.expression = this.toAssignable(node.expression, isBinding, contextDescription); break; case "MemberExpression": if (!isBinding) break; default: { const message = "Invalid left-hand side" + (contextDescription ? " in " + contextDescription : "expression"); this.raise(node.start, message); } } } return node; } toAssignableObjectExpressionProp(prop, isBinding, isLast) { if (prop.type === "ObjectMethod") { const error = prop.kind === "get" || prop.kind === "set" ? "Object pattern can't contain getter or setter" : "Object pattern can't contain methods"; this.raise(prop.key.start, error); } else if (prop.type === "SpreadElement" && !isLast) { this.raiseRestNotLast(prop.start); } else { this.toAssignable(prop, isBinding, "object destructuring pattern"); } } toAssignableList(exprList, isBinding, contextDescription) { let end = exprList.length; if (end) { const last = exprList[end - 1]; if (last && last.type === "RestElement") { --end; } else if (last && last.type === "SpreadElement") { last.type = "RestElement"; const arg = last.argument; this.toAssignable(arg, isBinding, contextDescription); if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern" && arg.type !== "ObjectPattern") { this.unexpected(arg.start); } --end; } } for (let i = 0; i < end; i++) { const elt = exprList[i]; if (elt) { this.toAssignable(elt, isBinding, contextDescription); if (elt.type === "RestElement") { this.raiseRestNotLast(elt.start); } } } return exprList; } toReferencedList(exprList, isParenthesizedExpr) { return exprList; } toReferencedListDeep(exprList, isParenthesizedExpr) { this.toReferencedList(exprList, isParenthesizedExpr); for (let _i = 0; _i < exprList.length; _i++) { const expr = exprList[_i]; if (expr && expr.type === "ArrayExpression") { this.toReferencedListDeep(expr.elements); } } return exprList; } parseSpread(refShorthandDefaultPos, refNeedsArrowPos) { const node = this.startNode(); this.next(); node.argument = this.parseMaybeAssign(false, refShorthandDefaultPos, undefined, refNeedsArrowPos); if (this.state.commaAfterSpreadAt === -1 && this.match(types.comma)) { this.state.commaAfterSpreadAt = this.state.start; } return this.finishNode(node, "SpreadElement"); } parseRestBinding() { const node = this.startNode(); this.next(); node.argument = this.parseBindingAtom(); return this.finishNode(node, "RestElement"); } parseBindingAtom() { switch (this.state.type) { case types.bracketL: { const node = this.startNode(); this.next(); node.elements = this.parseBindingList(types.bracketR, true); return this.finishNode(node, "ArrayPattern"); } case types.braceL: return this.parseObj(true); } return this.parseIdentifier(); } parseBindingList(close, allowEmpty, allowModifiers) { const elts = []; let first = true; while (!this.eat(close)) { if (first) { first = false; } else { this.expect(types.comma); } if (allowEmpty && this.match(types.comma)) { elts.push(null); } else if (this.eat(close)) { break; } else if (this.match(types.ellipsis)) { elts.push(this.parseAssignableListItemTypes(this.parseRestBinding())); this.checkCommaAfterRest(); this.expect(close); break; } else { const decorators = []; if (this.match(types.at) && this.hasPlugin("decorators")) { this.raise(this.state.start, "Stage 2 decorators cannot be used to decorate parameters"); } while (this.match(types.at)) { decorators.push(this.parseDecorator()); } elts.push(this.parseAssignableListItem(allowModifiers, decorators)); } } return elts; } parseAssignableListItem(allowModifiers, decorators) { const left = this.parseMaybeDefault(); this.parseAssignableListItemTypes(left); const elt = this.parseMaybeDefault(left.start, left.loc.start, left); if (decorators.length) { left.decorators = decorators; } return elt; } parseAssignableListItemTypes(param) { return param; } parseMaybeDefault(startPos, startLoc, left) { startLoc = startLoc || this.state.startLoc; startPos = startPos || this.state.start; left = left || this.parseBindingAtom(); if (!this.eat(types.eq)) return left; const node = this.startNodeAt(startPos, startLoc); node.left = left; node.right = this.parseMaybeAssign(); return this.finishNode(node, "AssignmentPattern"); } checkLVal(expr, bindingType = BIND_NONE, checkClashes, contextDescription) { switch (expr.type) { case "Identifier": if (this.state.strict && isStrictBindReservedWord(expr.name, this.inModule)) { this.raise(expr.start, `${bindingType === BIND_NONE ? "Assigning to" : "Binding"} '${expr.name}' in strict mode`); } if (checkClashes) { const key = `_${expr.name}`; if (checkClashes[key]) { this.raise(expr.start, "Argument name clash"); } else { checkClashes[key] = true; } } if (!(bindingType & BIND_NONE)) { this.scope.declareName(expr.name, bindingType, expr.start); } break; case "MemberExpression": if (bindingType !== BIND_NONE) { this.raise(expr.start, "Binding member expression"); } break; case "ObjectPattern": for (let _i2 = 0, _expr$properties = expr.properties; _i2 < _expr$properties.length; _i2++) { let prop = _expr$properties[_i2]; if (prop.type === "ObjectProperty") prop = prop.value; this.checkLVal(prop, bindingType, checkClashes, "object destructuring pattern"); } break; case "ArrayPattern": for (let _i3 = 0, _expr$elements = expr.elements; _i3 < _expr$elements.length; _i3++) { const elem = _expr$elements[_i3]; if (elem) { this.checkLVal(elem, bindingType, checkClashes, "array destructuring pattern"); } } break; case "AssignmentPattern": this.checkLVal(expr.left, bindingType, checkClashes, "assignment pattern"); break; case "RestElement": this.checkLVal(expr.argument, bindingType, checkClashes, "rest element"); break; case "ParenthesizedExpression": this.checkLVal(expr.expression, bindingType, checkClashes, "parenthesized expression"); break; default: { const message = (bindingType === BIND_NONE ? "Invalid" : "Binding invalid") + " left-hand side" + (contextDescription ? " in " + contextDescription : "expression"); this.raise(expr.start, message); } } } checkToRestConversion(node) { if (node.argument.type !== "Identifier" && node.argument.type !== "MemberExpression") { this.raise(node.argument.start, "Invalid rest operator's argument"); } } checkCommaAfterRest() { if (this.match(types.comma)) { this.raiseRestNotLast(this.state.start); } } checkCommaAfterRestFromSpread() { if (this.state.commaAfterSpreadAt > -1) { this.raiseRestNotLast(this.state.commaAfterSpreadAt); } } raiseRestNotLast(pos) { this.raise(pos, `Rest element must be last element`); } } const unwrapParenthesizedExpression = node => { return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node; }; class ExpressionParser extends LValParser { checkPropClash(prop, propHash) { if (prop.type === "SpreadElement" || prop.computed || prop.kind || prop.shorthand) { return; } const key = prop.key; const name = key.type === "Identifier" ? key.name : String(key.value); if (name === "__proto__") { if (propHash.proto) { this.raise(key.start, "Redefinition of __proto__ property"); } propHash.proto = true; } } getExpression() { this.scope.enter(SCOPE_PROGRAM); this.nextToken(); const expr = this.parseExpression(); if (!this.match(types.eof)) { this.unexpected(); } expr.comments = this.state.comments; return expr; } parseExpression(noIn, refShorthandDefaultPos) { const startPos = this.state.start; const startLoc = this.state.startLoc; const expr = this.parseMaybeAssign(noIn, refShorthandDefaultPos); if (this.match(types.comma)) { const node = this.startNodeAt(startPos, startLoc); node.expressions = [expr]; while (this.eat(types.comma)) { node.expressions.push(this.parseMaybeAssign(noIn, refShorthandDefaultPos)); } this.toReferencedList(node.expressions); return this.finishNode(node, "SequenceExpression"); } return expr; } parseMaybeAssign(noIn, refShorthandDefaultPos, afterLeftParse, refNeedsArrowPos) { const startPos = this.state.start; const startLoc = this.state.startLoc; if (this.isContextual("yield")) { if (this.scope.inGenerator) { let left = this.parseYield(noIn); if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); } return left; } else { this.state.exprAllowed = false; } } const oldCommaAfterSpreadAt = this.state.commaAfterSpreadAt; this.state.commaAfterSpreadAt = -1; let failOnShorthandAssign; if (refShorthandDefaultPos) { failOnShorthandAssign = false; } else { refShorthandDefaultPos = { start: 0 }; failOnShorthandAssign = true; } if (this.match(types.parenL) || this.match(types.name)) { this.state.potentialArrowAt = this.state.start; } let left = this.parseMaybeConditional(noIn, refShorthandDefaultPos, refNeedsArrowPos); if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); } if (this.state.type.isAssign) { const node = this.startNodeAt(startPos, startLoc); const operator = this.state.value; node.operator = operator; if (operator === "??=") { this.expectPlugin("nullishCoalescingOperator"); this.expectPlugin("logicalAssignment"); } if (operator === "||=" || operator === "&&=") { this.expectPlugin("logicalAssignment"); } node.left = this.match(types.eq) ? this.toAssignable(left, undefined, "assignment expression") : left; refShorthandDefaultPos.start = 0; this.checkLVal(left, undefined, undefined, "assignment expression"); const maybePattern = unwrapParenthesizedExpression(left); let patternErrorMsg; if (maybePattern.type === "ObjectPattern") { patternErrorMsg = "`({a}) = 0` use `({a} = 0)`"; } else if (maybePattern.type === "ArrayPattern") { patternErrorMsg = "`([a]) = 0` use `([a] = 0)`"; } if (patternErrorMsg && (left.extra && left.extra.parenthesized || left.type === "ParenthesizedExpression")) { this.raise(maybePattern.start, `You're trying to assign to a parenthesized expression, eg. instead of ${patternErrorMsg}`); } if (patternErrorMsg) this.checkCommaAfterRestFromSpread(); this.state.commaAfterSpreadAt = oldCommaAfterSpreadAt; this.next(); node.right = this.parseMaybeAssign(noIn); return this.finishNode(node, "AssignmentExpression"); } else if (failOnShorthandAssign && refShorthandDefaultPos.start) { this.unexpected(refShorthandDefaultPos.start); } this.state.commaAfterSpreadAt = oldCommaAfterSpreadAt; return left; } parseMaybeConditional(noIn, refShorthandDefaultPos, refNeedsArrowPos) { const startPos = this.state.start; const startLoc = this.state.startLoc; const potentialArrowAt = this.state.potentialArrowAt; const expr = this.parseExprOps(noIn, refShorthandDefaultPos); if (expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt) { return expr; } if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr; return this.parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos); } parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos) { if (this.eat(types.question)) { const node = this.startNodeAt(startPos, startLoc); node.test = expr; node.consequent = this.parseMaybeAssign(); this.expect(types.colon); node.alternate = this.parseMaybeAssign(noIn); return this.finishNode(node, "ConditionalExpression"); } return expr; } parseExprOps(noIn, refShorthandDefaultPos) { const startPos = this.state.start; const startLoc = this.state.startLoc; const potentialArrowAt = this.state.potentialArrowAt; const expr = this.parseMaybeUnary(refShorthandDefaultPos); if (expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt) { return expr; } if (refShorthandDefaultPos && refShorthandDefaultPos.start) { return expr; } return this.parseExprOp(expr, startPos, startLoc, -1, noIn); } parseExprOp(left, leftStartPos, leftStartLoc, minPrec, noIn) { const prec = this.state.type.binop; if (prec != null && (!noIn || !this.match(types._in))) { if (prec > minPrec) { const node = this.startNodeAt(leftStartPos, leftStartLoc); const operator = this.state.value; node.left = left; node.operator = operator; if (operator === "**" && left.type === "UnaryExpression" && (this.options.createParenthesizedExpressions || !(left.extra && left.extra.parenthesized))) { this.raise(left.argument.start, "Illegal expression. Wrap left hand side or entire exponentiation in parentheses."); } const op = this.state.type; if (op === types.pipeline) { this.expectPlugin("pipelineOperator"); this.state.inPipeline = true; this.checkPipelineAtInfixOperator(left, leftStartPos); } else if (op === types.nullishCoalescing) { this.expectPlugin("nullishCoalescingOperator"); } this.next(); if (op === types.pipeline && this.getPluginOption("pipelineOperator", "proposal") === "minimal") { if (this.match(types.name) && this.state.value === "await" && this.scope.inAsync) { throw this.raise(this.state.start, `Unexpected "await" after pipeline body; await must have parentheses in minimal proposal`); } } node.right = this.parseExprOpRightExpr(op, prec, noIn); this.finishNode(node, op === types.logicalOR || op === types.logicalAND || op === types.nullishCoalescing ? "LogicalExpression" : "BinaryExpression"); return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn); } } return left; } parseExprOpRightExpr(op, prec, noIn) { switch (op) { case types.pipeline: if (this.getPluginOption("pipelineOperator", "proposal") === "smart") { const startPos = this.state.start; const startLoc = this.state.startLoc; return this.withTopicPermittingContext(() => { return this.parseSmartPipelineBody(this.parseExprOpBaseRightExpr(op, prec, noIn), startPos, startLoc); }); } default: return this.parseExprOpBaseRightExpr(op, prec, noIn); } } parseExprOpBaseRightExpr(op, prec, noIn) { const startPos = this.state.start; const startLoc = this.state.startLoc; return this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, op.rightAssociative ? prec - 1 : prec, noIn); } parseMaybeUnary(refShorthandDefaultPos) { if (this.isContextual("await") && (this.scope.inAsync || !this.scope.inFunction && this.options.allowAwaitOutsideFunction)) { return this.parseAwait(); } else if (this.state.type.prefix) { const node = this.startNode(); const update = this.match(types.incDec); node.operator = this.state.value; node.prefix = true; if (node.operator === "throw") { this.expectPlugin("throwExpressions"); } this.next(); node.argument = this.parseMaybeUnary(); if (refShorthandDefaultPos && refShorthandDefaultPos.start) { this.unexpected(refShorthandDefaultPos.start); } if (update) { this.checkLVal(node.argument, undefined, undefined, "prefix operation"); } else if (this.state.strict && node.operator === "delete") { const arg = node.argument; if (arg.type === "Identifier") { this.raise(node.start, "Deleting local variable in strict mode"); } else if (arg.type === "MemberExpression" && arg.property.type === "PrivateName") { this.raise(node.start, "Deleting a private field is not allowed"); } } return this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); } const startPos = this.state.start; const startLoc = this.state.startLoc; let expr = this.parseExprSubscripts(refShorthandDefaultPos); if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr; while (this.state.type.postfix && !this.canInsertSemicolon()) { const node = this.startNodeAt(startPos, startLoc); node.operator = this.state.value; node.prefix = false; node.argument = expr; this.checkLVal(expr, undefined, undefined, "postfix operation"); this.next(); expr = this.finishNode(node, "UpdateExpression"); } return expr; } parseExprSubscripts(refShorthandDefaultPos) { const startPos = this.state.start; const startLoc = this.state.startLoc; const potentialArrowAt = this.state.potentialArrowAt; const expr = this.parseExprAtom(refShorthandDefaultPos); if (expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt) { return expr; } if (refShorthandDefaultPos && refShorthandDefaultPos.start) { return expr; } return this.parseSubscripts(expr, startPos, startLoc); } parseSubscripts(base, startPos, startLoc, noCalls) { const maybeAsyncArrow = this.atPossibleAsync(base); const state = { optionalChainMember: false, stop: false }; do { base = this.parseSubscript(base, startPos, startLoc, noCalls, state, maybeAsyncArrow); } while (!state.stop); return base; } parseSubscript(base, startPos, startLoc, noCalls, state, maybeAsyncArrow) { if (!noCalls && this.eat(types.doubleColon)) { const node = this.startNodeAt(startPos, startLoc); node.object = base; node.callee = this.parseNoCallExpr(); state.stop = true; return this.parseSubscripts(this.finishNode(node, "BindExpression"), startPos, startLoc, noCalls); } else if (this.match(types.questionDot)) { this.expectPlugin("optionalChaining"); state.optionalChainMember = true; if (noCalls && this.lookahead().type === types.parenL) { state.stop = true; return base; } this.next(); const node = this.startNodeAt(startPos, startLoc); if (this.eat(types.bracketL)) { node.object = base; node.property = this.parseExpression(); node.computed = true; node.optional = true; this.expect(types.bracketR); return this.finishNode(node, "OptionalMemberExpression"); } else if (this.eat(types.parenL)) { node.callee = base; node.arguments = this.parseCallExpressionArguments(types.parenR, false); node.optional = true; return this.finishNode(node, "OptionalCallExpression"); } else { node.object = base; node.property = this.parseIdentifier(true); node.computed = false; node.optional = true; return this.finishNode(node, "OptionalMemberExpression"); } } else if (this.eat(types.dot)) { const node = this.startNodeAt(startPos, startLoc); node.object = base; node.property = this.parseMaybePrivateName(); node.computed = false; if (state.optionalChainMember) { node.optional = false; return this.finishNode(node, "OptionalMemberExpression"); } return this.finishNode(node, "MemberExpression"); } else if (this.eat(types.bracketL)) { const node = this.startNodeAt(startPos, startLoc); node.object = base; node.property = this.parseExpression(); node.computed = true; this.expect(types.bracketR); if (state.optionalChainMember) { node.optional = false; return this.finishNode(node, "OptionalMemberExpression"); } return this.finishNode(node, "MemberExpression"); } else if (!noCalls && this.match(types.parenL)) { const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; const oldYieldPos = this.state.yieldPos; const oldAwaitPos = this.state.awaitPos; this.state.maybeInArrowParameters = true; this.state.yieldPos = 0; this.state.awaitPos = 0; this.next(); let node = this.startNodeAt(startPos, startLoc); node.callee = base; const oldCommaAfterSpreadAt = this.state.commaAfterSpreadAt; this.state.commaAfterSpreadAt = -1; node.arguments = this.parseCallExpressionArguments(types.parenR, maybeAsyncArrow, base.type === "Import", base.type !== "Super"); if (!state.optionalChainMember) { this.finishCallExpression(node); } else { this.finishOptionalCallExpression(node); } if (maybeAsyncArrow && this.shouldParseAsyncArrow()) { state.stop = true; this.checkCommaAfterRestFromSpread(); node = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startPos, startLoc), node); this.checkYieldAwaitInDefaultParams(); this.state.yieldPos = oldYieldPos; this.state.awaitPos = oldAwaitPos; } else { this.toReferencedListDeep(node.arguments); this.state.yieldPos = oldYieldPos || this.state.yieldPos; this.state.awaitPos = oldAwaitPos || this.state.awaitPos; } this.state.maybeInArrowParameters = oldMaybeInArrowParameters; this.state.commaAfterSpreadAt = oldCommaAfterSpreadAt; return node; } else if (this.match(types.backQuote)) { return this.parseTaggedTemplateExpression(startPos, startLoc, base, state); } else { state.stop = true; return base; } } parseTaggedTemplateExpression(startPos, startLoc, base, state, typeArguments) { const node = this.startNodeAt(startPos, startLoc); node.tag = base; node.quasi = this.parseTemplate(true); if (typeArguments) node.typeParameters = typeArguments; if (state.optionalChainMember) { this.raise(startPos, "Tagged Template Literals are not allowed in optionalChain"); } return this.finishNode(node, "TaggedTemplateExpression"); } atPossibleAsync(base) { return base.type === "Identifier" && base.name === "async" && this.state.lastTokEnd === base.end && !this.canInsertSemicolon() && this.input.slice(base.start, base.end) === "async"; } finishCallExpression(node) { if (node.callee.type === "Import") { if (node.arguments.length !== 1) { this.raise(node.start, "import() requires exactly one argument"); } const importArg = node.arguments[0]; if (importArg && importArg.type === "SpreadElement") { this.raise(importArg.start, "... is not allowed in import()"); } } return this.finishNode(node, "CallExpression"); } finishOptionalCallExpression(node) { if (node.callee.type === "Import") { if (node.arguments.length !== 1) { this.raise(node.start, "import() requires exactly one argument"); } const importArg = node.arguments[0]; if (importArg && importArg.type === "SpreadElement") { this.raise(importArg.start, "... is not allowed in import()"); } } return this.finishNode(node, "OptionalCallExpression"); } parseCallExpressionArguments(close, possibleAsyncArrow, dynamicImport, allowPlaceholder) { const elts = []; let innerParenStart; let first = true; while (!this.eat(close)) { if (first) { first = false; } else { this.expect(types.comma); if (this.eat(close)) { if (dynamicImport) { this.raise(this.state.lastTokStart, "Trailing comma is disallowed inside import(...) arguments"); } break; } } if (this.match(types.parenL) && !innerParenStart) { innerParenStart = this.state.start; } elts.push(this.parseExprListItem(false, possibleAsyncArrow ? { start: 0 } : undefined, possibleAsyncArrow ? { start: 0 } : undefined, allowPlaceholder)); } if (possibleAsyncArrow && innerParenStart && this.shouldParseAsyncArrow()) { this.unexpected(); } return elts; } shouldParseAsyncArrow() { return this.match(types.arrow) && !this.canInsertSemicolon(); } parseAsyncArrowFromCallExpression(node, call) { this.expect(types.arrow); this.parseArrowExpression(node, call.arguments, true); return node; } parseNoCallExpr() { const startPos = this.state.start; const startLoc = this.state.startLoc; return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true); } parseExprAtom(refShorthandDefaultPos) { if (this.state.type === types.slash) this.readRegexp(); const canBeArrow = this.state.potentialArrowAt === this.state.start; let node; switch (this.state.type) { case types._super: if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) { this.raise(this.state.start, "super is only allowed in object methods and classes"); } node = this.startNode(); this.next(); if (this.match(types.parenL) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) { this.raise(node.start, "super() is only valid inside a class constructor of a subclass. " + "Maybe a typo in the method name ('constructor') or not extending another class?"); } if (!this.match(types.parenL) && !this.match(types.bracketL) && !this.match(types.dot)) { this.unexpected(); } return this.finishNode(node, "Super"); case types._import: node = this.startNode(); this.next(); if (this.match(types.dot)) { return this.parseImportMetaProperty(node); } this.expectPlugin("dynamicImport", node.start); if (!this.match(types.parenL)) { this.unexpected(null, types.parenL); } return this.finishNode(node, "Import"); case types._this: node = this.startNode(); this.next(); return this.finishNode(node, "ThisExpression"); case types.name: { node = this.startNode(); const containsEsc = this.state.containsEsc; const id = this.parseIdentifier(); if (!containsEsc && id.name === "async" && this.match(types._function) && !this.canInsertSemicolon()) { this.next(); return this.parseFunction(node, undefined, true); } else if (canBeArrow && !containsEsc && id.name === "async" && this.match(types.name) && !this.canInsertSemicolon()) { const params = [this.parseIdentifier()]; this.expect(types.arrow); this.parseArrowExpression(node, params, true); return node; } if (canBeArrow && this.match(types.arrow) && !this.canInsertSemicolon()) { this.next(); this.parseArrowExpression(node, [id], false); return node; } return id; } case types._do: { this.expectPlugin("doExpressions"); const node = this.startNode(); this.next(); const oldLabels = this.state.labels; this.state.labels = []; node.body = this.parseBlock(); this.state.labels = oldLabels; return this.finishNode(node, "DoExpression"); } case types.regexp: { const value = this.state.value; node = this.parseLiteral(value.value, "RegExpLiteral"); node.pattern = value.pattern; node.flags = value.flags; return node; } case types.num: return this.parseLiteral(this.state.value, "NumericLiteral"); case types.bigint: return this.parseLiteral(this.state.value, "BigIntLiteral"); case types.string: return this.parseLiteral(this.state.value, "StringLiteral"); case types._null: node = this.startNode(); this.next(); return this.finishNode(node, "NullLiteral"); case types._true: case types._false: return this.parseBooleanLiteral(); case types.parenL: return this.parseParenAndDistinguishExpression(canBeArrow); case types.bracketL: node = this.startNode(); this.next(); node.elements = this.parseExprList(types.bracketR, true, refShorthandDefaultPos); if (!this.state.maybeInArrowParameters) { this.toReferencedList(node.elements); } return this.finishNode(node, "ArrayExpression"); case types.braceL: return this.parseObj(false, refShorthandDefaultPos); case types._function: return this.parseFunctionExpression(); case types.at: this.parseDecorators(); case types._class: node = this.startNode(); this.takeDecorators(node); return this.parseClass(node, false); case types._new: return this.parseNew(); case types.backQuote: return this.parseTemplate(false); case types.doubleColon: { node = this.startNode(); this.next(); node.object = null; const callee = node.callee = this.parseNoCallExpr(); if (callee.type === "MemberExpression") { return this.finishNode(node, "BindExpression"); } else { throw this.raise(callee.start, "Binding should be performed on object property."); } } case types.hash: { if (this.state.inPipeline) { node = this.startNode(); if (this.getPluginOption("pipelineOperator", "proposal") !== "smart") { this.raise(node.start, "Primary Topic Reference found but pipelineOperator not passed 'smart' for 'proposal' option."); } this.next(); if (this.primaryTopicReferenceIsAllowedInCurrentTopicContext()) { this.registerTopicReference(); return this.finishNode(node, "PipelinePrimaryTopicReference"); } else { throw this.raise(node.start, `Topic reference was used in a lexical context without topic binding`); } } } default: throw this.unexpected(); } } parseBooleanLiteral() { const node = this.startNode(); node.value = this.match(types._true); this.next(); return this.finishNode(node, "BooleanLiteral"); } parseMaybePrivateName() { const isPrivate = this.match(types.hash); if (isPrivate) { this.expectOnePlugin(["classPrivateProperties", "classPrivateMethods"]); const node = this.startNode(); this.next(); this.assertNoSpace("Unexpected space between # and identifier"); node.id = this.parseIdentifier(true); return this.finishNode(node, "PrivateName"); } else { return this.parseIdentifier(true); } } parseFunctionExpression() { const node = this.startNode(); let meta = this.startNode(); this.next(); meta = this.createIdentifier(meta, "function"); if (this.scope.inGenerator && this.eat(types.dot)) { return this.parseMetaProperty(node, meta, "sent"); } return this.parseFunction(node); } parseMetaProperty(node, meta, propertyName) { node.meta = meta; if (meta.name === "function" && propertyName === "sent") { if (this.isContextual(propertyName)) { this.expectPlugin("functionSent"); } else if (!this.hasPlugin("functionSent")) { this.unexpected(); } } const containsEsc = this.state.containsEsc; node.property = this.parseIdentifier(true); if (node.property.name !== propertyName || containsEsc) { this.raise(node.property.start, `The only valid meta property for ${meta.name} is ${meta.name}.${propertyName}`); } return this.finishNode(node, "MetaProperty"); } parseImportMetaProperty(node) { const id = this.createIdentifier(this.startNodeAtNode(node), "import"); this.expect(types.dot); if (this.isContextual("meta")) { this.expectPlugin("importMeta"); } else if (!this.hasPlugin("importMeta")) { this.raise(id.start, `Dynamic imports require a parameter: import('a.js')`); } if (!this.inModule) { this.raise(id.start, `import.meta may appear only with 'sourceType: "module"'`, { code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED" }); } this.sawUnambiguousESM = true; return this.parseMetaProperty(node, id, "meta"); } parseLiteral(value, type, startPos, startLoc) { startPos = startPos || this.state.start; startLoc = startLoc || this.state.startLoc; const node = this.startNodeAt(startPos, startLoc); this.addExtra(node, "rawValue", value); this.addExtra(node, "raw", this.input.slice(startPos, this.state.end)); node.value = value; this.next(); return this.finishNode(node, type); } parseParenAndDistinguishExpression(canBeArrow) { const startPos = this.state.start; const startLoc = this.state.startLoc; let val; this.expect(types.parenL); const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; const oldYieldPos = this.state.yieldPos; const oldAwaitPos = this.state.awaitPos; this.state.maybeInArrowParameters = true; this.state.yieldPos = 0; this.state.awaitPos = 0; const innerStartPos = this.state.start; const innerStartLoc = this.state.startLoc; const exprList = []; const refShorthandDefaultPos = { start: 0 }; const refNeedsArrowPos = { start: 0 }; let first = true; let spreadStart; let optionalCommaStart; while (!this.match(types.parenR)) { if (first) { first = false; } else { this.expect(types.comma, refNeedsArrowPos.start || null); if (this.match(types.parenR)) { optionalCommaStart = this.state.start; break; } } if (this.match(types.ellipsis)) { const spreadNodeStartPos = this.state.start; const spreadNodeStartLoc = this.state.startLoc; spreadStart = this.state.start; exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartPos, spreadNodeStartLoc)); this.checkCommaAfterRest(); break; } else { exprList.push(this.parseMaybeAssign(false, refShorthandDefaultPos, this.parseParenItem, refNeedsArrowPos)); } } const innerEndPos = this.state.start; const innerEndLoc = this.state.startLoc; this.expect(types.parenR); this.state.maybeInArrowParameters = oldMaybeInArrowParameters; let arrowNode = this.startNodeAt(startPos, startLoc); if (canBeArrow && this.shouldParseArrow() && (arrowNode = this.parseArrow(arrowNode))) { this.checkYieldAwaitInDefaultParams(); this.state.yieldPos = oldYieldPos; this.state.awaitPos = oldAwaitPos; for (let _i = 0; _i < exprList.length; _i++) { const param = exprList[_i]; if (param.extra && param.extra.parenthesized) { this.unexpected(param.extra.parenStart); } } this.parseArrowExpression(arrowNode, exprList, false); return arrowNode; } this.state.yieldPos = oldYieldPos || this.state.yieldPos; this.state.awaitPos = oldAwaitPos || this.state.awaitPos; if (!exprList.length) { this.unexpected(this.state.lastTokStart); } if (optionalCommaStart) this.unexpected(optionalCommaStart); if (spreadStart) this.unexpected(spreadStart); if (refShorthandDefaultPos.start) { this.unexpected(refShorthandDefaultPos.start); } if (refNeedsArrowPos.start) this.unexpected(refNeedsArrowPos.start); this.toReferencedListDeep(exprList, true); if (exprList.length > 1) { val = this.startNodeAt(innerStartPos, innerStartLoc); val.expressions = exprList; this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); } else { val = exprList[0]; } if (!this.options.createParenthesizedExpressions) { this.addExtra(val, "parenthesized", true); this.addExtra(val, "parenStart", startPos); return val; } const parenExpression = this.startNodeAt(startPos, startLoc); parenExpression.expression = val; this.finishNode(parenExpression, "ParenthesizedExpression"); return parenExpression; } shouldParseArrow() { return !this.canInsertSemicolon(); } parseArrow(node) { if (this.eat(types.arrow)) { return node; } } parseParenItem(node, startPos, startLoc) { return node; } parseNew() { const node = this.startNode(); const meta = this.parseIdentifier(true); if (this.eat(types.dot)) { const metaProp = this.parseMetaProperty(node, meta, "target"); if (!this.scope.inNonArrowFunction && !this.state.inClassProperty) { let error = "new.target can only be used in functions"; if (this.hasPlugin("classProperties")) { error += " or class properties"; } this.raise(metaProp.start, error); } return metaProp; } node.callee = this.parseNoCallExpr(); if (node.callee.type === "Import") { this.raise(node.callee.start, "Cannot use new with import(...)"); } else if (node.callee.type === "OptionalMemberExpression" || node.callee.type === "OptionalCallExpression") { this.raise(this.state.lastTokEnd, "constructors in/after an Optional Chain are not allowed"); } else if (this.eat(types.questionDot)) { this.raise(this.state.start, "constructors in/after an Optional Chain are not allowed"); } this.parseNewArguments(node); return this.finishNode(node, "NewExpression"); } parseNewArguments(node) { if (this.eat(types.parenL)) { const args = this.parseExprList(types.parenR); this.toReferencedList(args); node.arguments = args; } else { node.arguments = []; } } parseTemplateElement(isTagged) { const elem = this.startNode(); if (this.state.value === null) { if (!isTagged) { this.raise(this.state.invalidTemplateEscapePosition || 0, "Invalid escape sequence in template"); } else { this.state.invalidTemplateEscapePosition = null; } } elem.value = { raw: this.input.slice(this.state.start, this.state.end).replace(/\r\n?/g, "\n"), cooked: this.state.value }; this.next(); elem.tail = this.match(types.backQuote); return this.finishNode(elem, "TemplateElement"); } parseTemplate(isTagged) { const node = this.startNode(); this.next(); node.expressions = []; let curElt = this.parseTemplateElement(isTagged); node.quasis = [curElt]; while (!curElt.tail) { this.expect(types.dollarBraceL); node.expressions.push(this.parseExpression()); this.expect(types.braceR); node.quasis.push(curElt = this.parseTemplateElement(isTagged)); } this.next(); return this.finishNode(node, "TemplateLiteral"); } parseObj(isPattern, refShorthandDefaultPos) { const propHash = Object.create(null); let first = true; const node = this.startNode(); node.properties = []; this.next(); while (!this.eat(types.braceR)) { if (first) { first = false; } else { this.expect(types.comma); if (this.eat(types.braceR)) break; } const prop = this.parseObjectMember(isPattern, refShorthandDefaultPos); if (!isPattern) this.checkPropClash(prop, propHash); if (prop.shorthand) { this.addExtra(prop, "shorthand", true); } node.properties.push(prop); } return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression"); } isAsyncProp(prop) { return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && (this.match(types.name) || this.match(types.num) || this.match(types.string) || this.match(types.bracketL) || this.state.type.keyword || this.match(types.star)) && !this.hasPrecedingLineBreak(); } parseObjectMember(isPattern, refShorthandDefaultPos) { let decorators = []; if (this.match(types.at)) { if (this.hasPlugin("decorators")) { this.raise(this.state.start, "Stage 2 decorators disallow object literal property decorators"); } else { while (this.match(types.at)) { decorators.push(this.parseDecorator()); } } } const prop = this.startNode(); let isGenerator = false; let isAsync = false; let startPos; let startLoc; if (this.match(types.ellipsis)) { if (decorators.length) this.unexpected(); if (isPattern) { this.next(); prop.argument = this.parseIdentifier(); this.checkCommaAfterRest(); return this.finishNode(prop, "RestElement"); } return this.parseSpread(); } if (decorators.length) { prop.decorators = decorators; decorators = []; } prop.method = false; if (isPattern || refShorthandDefaultPos) { startPos = this.state.start; startLoc = this.state.startLoc; } if (!isPattern) { isGenerator = this.eat(types.star); } const containsEsc = this.state.containsEsc; this.parsePropertyName(prop); if (!isPattern && !containsEsc && !isGenerator && this.isAsyncProp(prop)) { isAsync = true; isGenerator = this.eat(types.star); this.parsePropertyName(prop); } else { isAsync = false; } this.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refShorthandDefaultPos, containsEsc); return prop; } isGetterOrSetterMethod(prop, isPattern) { return !isPattern && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && (this.match(types.string) || this.match(types.num) || this.match(types.bracketL) || this.match(types.name) || !!this.state.type.keyword); } getGetterSetterExpectedParamCount(method) { return method.kind === "get" ? 0 : 1; } checkGetterSetterParams(method) { const paramCount = this.getGetterSetterExpectedParamCount(method); const start = method.start; if (method.params.length !== paramCount) { if (method.kind === "get") { this.raise(start, "getter must not have any formal parameters"); } else { this.raise(start, "setter must have exactly one formal parameter"); } } if (method.kind === "set" && method.params[method.params.length - 1].type === "RestElement") { this.raise(start, "setter function argument must not be a rest parameter"); } } parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc) { if (isAsync || isGenerator || this.match(types.parenL)) { if (isPattern) this.unexpected(); prop.kind = "method"; prop.method = true; return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod"); } if (!containsEsc && this.isGetterOrSetterMethod(prop, isPattern)) { if (isGenerator || isAsync) this.unexpected(); prop.kind = prop.key.name; this.parsePropertyName(prop); this.parseMethod(prop, false, false, false, false, "ObjectMethod"); this.checkGetterSetterParams(prop); return prop; } } parseObjectProperty(prop, startPos, startLoc, isPattern, refShorthandDefaultPos) { prop.shorthand = false; if (this.eat(types.colon)) { prop.value = isPattern ? this.parseMaybeDefault(this.state.start, this.state.startLoc) : this.parseMaybeAssign(false, refShorthandDefaultPos); return this.finishNode(prop, "ObjectProperty"); } if (!prop.computed && prop.key.type === "Identifier") { this.checkReservedWord(prop.key.name, prop.key.start, true, true); if (isPattern) { prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone()); } else if (this.match(types.eq) && refShorthandDefaultPos) { if (!refShorthandDefaultPos.start) { refShorthandDefaultPos.start = this.state.start; } prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone()); } else { prop.value = prop.key.__clone(); } prop.shorthand = true; return this.finishNode(prop, "ObjectProperty"); } } parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refShorthandDefaultPos, containsEsc) { const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, containsEsc) || this.parseObjectProperty(prop, startPos, startLoc, isPattern, refShorthandDefaultPos); if (!node) this.unexpected(); return node; } parsePropertyName(prop) { if (this.eat(types.bracketL)) { prop.computed = true; prop.key = this.parseMaybeAssign(); this.expect(types.bracketR); } else { const oldInPropertyName = this.state.inPropertyName; this.state.inPropertyName = true; prop.key = this.match(types.num) || this.match(types.string) ? this.parseExprAtom() : this.parseMaybePrivateName(); if (prop.key.type !== "PrivateName") { prop.computed = false; } this.state.inPropertyName = oldInPropertyName; } return prop.key; } initFunction(node, isAsync) { node.id = null; node.generator = false; node.async = !!isAsync; } parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) { const oldYieldPos = this.state.yieldPos; const oldAwaitPos = this.state.awaitPos; this.state.yieldPos = 0; this.state.awaitPos = 0; this.initFunction(node, isAsync); node.generator = !!isGenerator; const allowModifiers = isConstructor; this.scope.enter(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (inClassScope ? SCOPE_CLASS : 0) | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); this.parseFunctionParams(node, allowModifiers); this.checkYieldAwaitInDefaultParams(); this.parseFunctionBodyAndFinish(node, type, true); this.scope.exit(); this.state.yieldPos = oldYieldPos; this.state.awaitPos = oldAwaitPos; return node; } parseArrowExpression(node, params, isAsync) { this.scope.enter(functionFlags(isAsync, false) | SCOPE_ARROW); this.initFunction(node, isAsync); const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; const oldYieldPos = this.state.yieldPos; const oldAwaitPos = this.state.awaitPos; this.state.maybeInArrowParameters = false; this.state.yieldPos = 0; this.state.awaitPos = 0; if (params) this.setArrowFunctionParameters(node, params); this.parseFunctionBody(node, true); this.scope.exit(); this.state.maybeInArrowParameters = oldMaybeInArrowParameters; this.state.yieldPos = oldYieldPos; this.state.awaitPos = oldAwaitPos; return this.finishNode(node, "ArrowFunctionExpression"); } setArrowFunctionParameters(node, params) { node.params = this.toAssignableList(params, true, "arrow function parameters"); } isStrictBody(node) { const isBlockStatement = node.body.type === "BlockStatement"; if (isBlockStatement && node.body.directives.length) { for (let _i2 = 0, _node$body$directives = node.body.directives; _i2 < _node$body$directives.length; _i2++) { const directive = _node$body$directives[_i2]; if (directive.value.value === "use strict") { return true; } } } return false; } parseFunctionBodyAndFinish(node, type, isMethod = false) { this.parseFunctionBody(node, false, isMethod); this.finishNode(node, type); } parseFunctionBody(node, allowExpression, isMethod = false) { const isExpression = allowExpression && !this.match(types.braceL); const oldStrict = this.state.strict; let useStrict = false; const oldInParameters = this.state.inParameters; this.state.inParameters = false; if (isExpression) { node.body = this.parseMaybeAssign(); this.checkParams(node, false, allowExpression); } else { const nonSimple = !this.isSimpleParamList(node.params); if (!oldStrict || nonSimple) { useStrict = this.strictDirective(this.state.end); if (useStrict && nonSimple) { const errorPos = (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.end : node.start; this.raise(errorPos, "Illegal 'use strict' directive in function with non-simple parameter list"); } } const oldLabels = this.state.labels; this.state.labels = []; if (useStrict) this.state.strict = true; this.checkParams(node, !oldStrict && !useStrict && !allowExpression && !isMethod && !nonSimple, allowExpression); node.body = this.parseBlock(true, false); this.state.labels = oldLabels; } this.state.inParameters = oldInParameters; if (this.state.strict && node.id) { this.checkLVal(node.id, BIND_OUTSIDE, undefined, "function name"); } this.state.strict = oldStrict; } isSimpleParamList(params) { for (let i = 0, len = params.length; i < len; i++) { if (params[i].type !== "Identifier") return false; } return true; } checkParams(node, allowDuplicates, isArrowFunction) { const nameHash = Object.create(null); for (let i = 0; i < node.params.length; i++) { this.checkLVal(node.params[i], BIND_VAR, allowDuplicates ? null : nameHash, "function paramter list"); } } parseExprList(close, allowEmpty, refShorthandDefaultPos) { const elts = []; let first = true; while (!this.eat(close)) { if (first) { first = false; } else { this.expect(types.comma); if (this.eat(close)) break; } elts.push(this.parseExprListItem(allowEmpty, refShorthandDefaultPos)); } return elts; } parseExprListItem(allowEmpty, refShorthandDefaultPos, refNeedsArrowPos, allowPlaceholder) { let elt; if (allowEmpty && this.match(types.comma)) { elt = null; } else if (this.match(types.ellipsis)) { const spreadNodeStartPos = this.state.start; const spreadNodeStartLoc = this.state.startLoc; elt = this.parseParenItem(this.parseSpread(refShorthandDefaultPos, refNeedsArrowPos), spreadNodeStartPos, spreadNodeStartLoc); } else if (this.match(types.question)) { this.expectPlugin("partialApplication"); if (!allowPlaceholder) { this.raise(this.state.start, "Unexpected argument placeholder"); } const node = this.startNode(); this.next(); elt = this.finishNode(node, "ArgumentPlaceholder"); } else { elt = this.parseMaybeAssign(false, refShorthandDefaultPos, this.parseParenItem, refNeedsArrowPos); } return elt; } parseIdentifier(liberal) { const node = this.startNode(); const name = this.parseIdentifierName(node.start, liberal); return this.createIdentifier(node, name); } createIdentifier(node, name) { node.name = name; node.loc.identifierName = name; return this.finishNode(node, "Identifier"); } parseIdentifierName(pos, liberal) { let name; if (this.match(types.name)) { name = this.state.value; } else if (this.state.type.keyword) { name = this.state.type.keyword; if ((name === "class" || name === "function") && (this.state.lastTokEnd !== this.state.lastTokStart + 1 || this.input.charCodeAt(this.state.lastTokStart) !== 46)) { this.state.context.pop(); } } else { throw this.unexpected(); } if (!liberal) { this.checkReservedWord(name, this.state.start, !!this.state.type.keyword, false); } this.next(); return name; } checkReservedWord(word, startLoc, checkKeywords, isBinding) { if (this.scope.inGenerator && word === "yield") { this.raise(startLoc, "Can not use 'yield' as identifier inside a generator"); } if (this.scope.inAsync && word === "await") { this.raise(startLoc, "Can not use 'await' as identifier inside an async function"); } if (this.state.inClassProperty && word === "arguments") { this.raise(startLoc, "'arguments' is not allowed in class field initializer"); } if (checkKeywords && isKeyword(word)) { this.raise(startLoc, `Unexpected keyword '${word}'`); } const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord; if (reservedTest(word, this.inModule)) { if (!this.scope.inAsync && word === "await") { this.raise(startLoc, "Can not use keyword 'await' outside an async function"); } this.raise(startLoc, `Unexpected reserved word '${word}'`); } } parseAwait() { if (!this.state.awaitPos) { this.state.awaitPos = this.state.start; } const node = this.startNode(); this.next(); if (this.state.inParameters) { this.raise(node.start, "await is not allowed in async function parameters"); } if (this.match(types.star)) { this.raise(node.start, "await* has been removed from the async functions proposal. Use Promise.all() instead."); } node.argument = this.parseMaybeUnary(); return this.finishNode(node, "AwaitExpression"); } parseYield(noIn) { if (!this.state.yieldPos) { this.state.yieldPos = this.state.start; } const node = this.startNode(); if (this.state.inParameters) { this.raise(node.start, "yield is not allowed in generator parameters"); } this.next(); if (this.match(types.semi) || !this.match(types.star) && !this.state.type.startsExpr || this.canInsertSemicolon()) { node.delegate = false; node.argument = null; } else { node.delegate = this.eat(types.star); node.argument = this.parseMaybeAssign(noIn); } return this.finishNode(node, "YieldExpression"); } checkPipelineAtInfixOperator(left, leftStartPos) { if (this.getPluginOption("pipelineOperator", "proposal") === "smart") { if (left.type === "SequenceExpression") { throw this.raise(leftStartPos, `Pipeline head should not be a comma-separated sequence expression`); } } } parseSmartPipelineBody(childExpression, startPos, startLoc) { const pipelineStyle = this.checkSmartPipelineBodyStyle(childExpression); this.checkSmartPipelineBodyEarlyErrors(childExpression, pipelineStyle, startPos); return this.parseSmartPipelineBodyInStyle(childExpression, pipelineStyle, startPos, startLoc); } checkSmartPipelineBodyEarlyErrors(childExpression, pipelineStyle, startPos) { if (this.match(types.arrow)) { throw this.raise(this.state.start, `Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized`); } else if (pipelineStyle === "PipelineTopicExpression" && childExpression.type === "SequenceExpression") { throw this.raise(startPos, `Pipeline body may not be a comma-separated sequence expression`); } } parseSmartPipelineBodyInStyle(childExpression, pipelineStyle, startPos, startLoc) { const bodyNode = this.startNodeAt(startPos, startLoc); switch (pipelineStyle) { case "PipelineBareFunction": bodyNode.callee = childExpression; break; case "PipelineBareConstructor": bodyNode.callee = childExpression.callee; break; case "PipelineBareAwaitedFunction": bodyNode.callee = childExpression.argument; break; case "PipelineTopicExpression": if (!this.topicReferenceWasUsedInCurrentTopicContext()) { throw this.raise(startPos, `Pipeline is in topic style but does not use topic reference`); } bodyNode.expression = childExpression; break; default: throw this.raise(startPos, `Unknown pipeline style ${pipelineStyle}`); } return this.finishNode(bodyNode, pipelineStyle); } checkSmartPipelineBodyStyle(expression) { switch (expression.type) { default: return this.isSimpleReference(expression) ? "PipelineBareFunction" : "PipelineTopicExpression"; } } isSimpleReference(expression) { switch (expression.type) { case "MemberExpression": return !expression.computed && this.isSimpleReference(expression.object); case "Identifier": return true; default: return false; } } withTopicPermittingContext(callback) { const outerContextTopicState = this.state.topicContext; this.state.topicContext = { maxNumOfResolvableTopics: 1, maxTopicIndex: null }; try { return callback(); } finally { this.state.topicContext = outerContextTopicState; } } withTopicForbiddingContext(callback) { const outerContextTopicState = this.state.topicContext; this.state.topicContext = { maxNumOfResolvableTopics: 0, maxTopicIndex: null }; try { return callback(); } finally { this.state.topicContext = outerContextTopicState; } } registerTopicReference() { this.state.topicContext.maxTopicIndex = 0; } primaryTopicReferenceIsAllowedInCurrentTopicContext() { return this.state.topicContext.maxNumOfResolvableTopics >= 1; } topicReferenceWasUsedInCurrentTopicContext() { return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0; } } const loopLabel = { kind: "loop" }, switchLabel = { kind: "switch" }; const FUNC_NO_FLAGS = 0b000, FUNC_STATEMENT = 0b001, FUNC_HANGING_STATEMENT = 0b010, FUNC_NULLABLE_ID = 0b100; class StatementParser extends ExpressionParser { parseTopLevel(file, program) { program.sourceType = this.options.sourceType; program.interpreter = this.parseInterpreterDirective(); this.parseBlockBody(program, true, true, types.eof); if (this.inModule && this.scope.undefinedExports.size > 0) { for (let _i = 0, _Array$from = Array.from(this.scope.undefinedExports); _i < _Array$from.length; _i++) { const [name] = _Array$from[_i]; const pos = this.scope.undefinedExports.get(name); this.raise(pos, `Export '${name}' is not defined`); } } file.program = this.finishNode(program, "Program"); file.comments = this.state.comments; if (this.options.tokens) file.tokens = this.state.tokens; return this.finishNode(file, "File"); } stmtToDirective(stmt) { const expr = stmt.expression; const directiveLiteral = this.startNodeAt(expr.start, expr.loc.start); const directive = this.startNodeAt(stmt.start, stmt.loc.start); const raw = this.input.slice(expr.start, expr.end); const val = directiveLiteral.value = raw.slice(1, -1); this.addExtra(directiveLiteral, "raw", raw); this.addExtra(directiveLiteral, "rawValue", val); directive.value = this.finishNodeAt(directiveLiteral, "DirectiveLiteral", expr.end, expr.loc.end); return this.finishNodeAt(directive, "Directive", stmt.end, stmt.loc.end); } parseInterpreterDirective() { if (!this.match(types.interpreterDirective)) { return null; } const node = this.startNode(); node.value = this.state.value; this.next(); return this.finishNode(node, "InterpreterDirective"); } isLet(context) { if (!this.isContextual("let")) { return false; } skipWhiteSpace.lastIndex = this.state.pos; const skip = skipWhiteSpace.exec(this.input); const next = this.state.pos + skip[0].length; const nextCh = this.input.charCodeAt(next); if (nextCh === 91) return true; if (context) return false; if (nextCh === 123) return true; if (isIdentifierStart(nextCh)) { let pos = next + 1; while (isIdentifierChar(this.input.charCodeAt(pos))) { ++pos; } const ident = this.input.slice(next, pos); if (!keywordRelationalOperator.test(ident)) return true; } return false; } parseStatement(context, topLevel) { if (this.match(types.at)) { this.parseDecorators(true); } return this.parseStatementContent(context, topLevel); } parseStatementContent(context, topLevel) { let starttype = this.state.type; const node = this.startNode(); let kind; if (this.isLet(context)) { starttype = types._var; kind = "let"; } switch (starttype) { case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword); case types._debugger: return this.parseDebuggerStatement(node); case types._do: return this.parseDoStatement(node); case types._for: return this.parseForStatement(node); case types._function: if (this.lookahead().type === types.dot) break; if (context) { if (this.state.strict) { this.raise(this.state.start, "In strict mode code, functions can only be declared at top level or inside a block"); } else if (context !== "if" && context !== "label") { this.raise(this.state.start, "In non-strict mode code, functions can only be declared at top level, " + "inside a block, or as the body of an if statement"); } } return this.parseFunctionStatement(node, false, !context); case types._class: if (context) this.unexpected(); return this.parseClass(node, true); case types._if: return this.parseIfStatement(node); case types._return: return this.parseReturnStatement(node); case types._switch: return this.parseSwitchStatement(node); case types._throw: return this.parseThrowStatement(node); case types._try: return this.parseTryStatement(node); case types._const: case types._var: kind = kind || this.state.value; if (context && kind !== "var") { this.unexpected(this.state.start, "Lexical declaration cannot appear in a single-statement context"); } return this.parseVarStatement(node, kind); case types._while: return this.parseWhileStatement(node); case types._with: return this.parseWithStatement(node); case types.braceL: return this.parseBlock(); case types.semi: return this.parseEmptyStatement(node); case types._export: case types._import: { const nextToken = this.lookahead(); if (nextToken.type === types.parenL || nextToken.type === types.dot) { break; } if (!this.options.allowImportExportEverywhere && !topLevel) { this.raise(this.state.start, "'import' and 'export' may only appear at the top level"); } this.next(); let result; if (starttype === types._import) { result = this.parseImport(node); if (result.type === "ImportDeclaration" && (!result.importKind || result.importKind === "value")) { this.sawUnambiguousESM = true; } } else { result = this.parseExport(node); if (result.type === "ExportNamedDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportAllDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportDefaultDeclaration") { this.sawUnambiguousESM = true; } } this.assertModuleNodeAllowed(node); return result; } default: { if (this.isAsyncFunction()) { if (context) { this.unexpected(null, "Async functions can only be declared at the top level or inside a block"); } this.next(); return this.parseFunctionStatement(node, true, !context); } } } const maybeName = this.state.value; const expr = this.parseExpression(); if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) { return this.parseLabeledStatement(node, maybeName, expr, context); } else { return this.parseExpressionStatement(node, expr); } } assertModuleNodeAllowed(node) { if (!this.options.allowImportExportEverywhere && !this.inModule) { this.raise(node.start, `'import' and 'export' may appear only with 'sourceType: "module"'`, { code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED" }); } } takeDecorators(node) { const decorators = this.state.decoratorStack[this.state.decoratorStack.length - 1]; if (decorators.length) { node.decorators = decorators; this.resetStartLocationFromNode(node, decorators[0]); this.state.decoratorStack[this.state.decoratorStack.length - 1] = []; } } canHaveLeadingDecorator() { return this.match(types._class); } parseDecorators(allowExport) { const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1]; while (this.match(types.at)) { const decorator = this.parseDecorator(); currentContextDecorators.push(decorator); } if (this.match(types._export)) { if (!allowExport) { this.unexpected(); } if (this.hasPlugin("decorators") && !this.getPluginOption("decorators", "decoratorsBeforeExport")) { this.raise(this.state.start, "Using the export keyword between a decorator and a class is not allowed. " + "Please use `export @dec class` instead."); } } else if (!this.canHaveLeadingDecorator()) { this.raise(this.state.start, "Leading decorators must be attached to a class declaration"); } } parseDecorator() { this.expectOnePlugin(["decorators-legacy", "decorators"]); const node = this.startNode(); this.next(); if (this.hasPlugin("decorators")) { this.state.decoratorStack.push([]); const startPos = this.state.start; const startLoc = this.state.startLoc; let expr; if (this.eat(types.parenL)) { expr = this.parseExpression(); this.expect(types.parenR); } else { expr = this.parseIdentifier(false); while (this.eat(types.dot)) { const node = this.startNodeAt(startPos, startLoc); node.object = expr; node.property = this.parseIdentifier(true); node.computed = false; expr = this.finishNode(node, "MemberExpression"); } } node.expression = this.parseMaybeDecoratorArguments(expr); this.state.decoratorStack.pop(); } else { node.expression = this.parseMaybeAssign(); } return this.finishNode(node, "Decorator"); } parseMaybeDecoratorArguments(expr) { if (this.eat(types.parenL)) { const node = this.startNodeAtNode(expr); node.callee = expr; node.arguments = this.parseCallExpressionArguments(types.parenR, false); this.toReferencedList(node.arguments); return this.finishNode(node, "CallExpression"); } return expr; } parseBreakContinueStatement(node, keyword) { const isBreak = keyword === "break"; this.next(); if (this.isLineTerminator()) { node.label = null; } else { node.label = this.parseIdentifier(); this.semicolon(); } this.verifyBreakContinue(node, keyword); return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement"); } verifyBreakContinue(node, keyword) { const isBreak = keyword === "break"; let i; for (i = 0; i < this.state.labels.length; ++i) { const lab = this.state.labels[i]; if (node.label == null || lab.name === node.label.name) { if (lab.kind != null && (isBreak || lab.kind === "loop")) break; if (node.label && isBreak) break; } } if (i === this.state.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); } } parseDebuggerStatement(node) { this.next(); this.semicolon(); return this.finishNode(node, "DebuggerStatement"); } parseHeaderExpression() { this.expect(types.parenL); const val = this.parseExpression(); this.expect(types.parenR); return val; } parseDoStatement(node) { this.next(); this.state.labels.push(loopLabel); node.body = this.withTopicForbiddingContext(() => this.parseStatement("do")); this.state.labels.pop(); this.expect(types._while); node.test = this.parseHeaderExpression(); this.eat(types.semi); return this.finishNode(node, "DoWhileStatement"); } parseForStatement(node) { this.next(); this.state.labels.push(loopLabel); let awaitAt = -1; if ((this.scope.inAsync || !this.scope.inFunction && this.options.allowAwaitOutsideFunction) && this.eatContextual("await")) { awaitAt = this.state.lastTokStart; } this.scope.enter(SCOPE_OTHER); this.expect(types.parenL); if (this.match(types.semi)) { if (awaitAt > -1) { this.unexpected(awaitAt); } return this.parseFor(node, null); } const isLet = this.isLet(); if (this.match(types._var) || this.match(types._const) || isLet) { const init = this.startNode(); const kind = isLet ? "let" : this.state.value; this.next(); this.parseVar(init, true, kind); this.finishNode(init, "VariableDeclaration"); if ((this.match(types._in) || this.isContextual("of")) && init.declarations.length === 1) { return this.parseForIn(node, init, awaitAt); } if (awaitAt > -1) { this.unexpected(awaitAt); } return this.parseFor(node, init); } const refShorthandDefaultPos = { start: 0 }; const init = this.parseExpression(true, refShorthandDefaultPos); if (this.match(types._in) || this.isContextual("of")) { const description = this.isContextual("of") ? "for-of statement" : "for-in statement"; this.toAssignable(init, undefined, description); this.checkLVal(init, undefined, undefined, description); return this.parseForIn(node, init, awaitAt); } else if (refShorthandDefaultPos.start) { this.unexpected(refShorthandDefaultPos.start); } if (awaitAt > -1) { this.unexpected(awaitAt); } return this.parseFor(node, init); } parseFunctionStatement(node, isAsync, declarationPosition) { this.next(); return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), isAsync); } parseIfStatement(node) { this.next(); node.test = this.parseHeaderExpression(); node.consequent = this.parseStatement("if"); node.alternate = this.eat(types._else) ? this.parseStatement("if") : null; return this.finishNode(node, "IfStatement"); } parseReturnStatement(node) { if (!this.scope.inFunction && !this.options.allowReturnOutsideFunction) { this.raise(this.state.start, "'return' outside of function"); } this.next(); if (this.isLineTerminator()) { node.argument = null; } else { node.argument = this.parseExpression(); this.semicolon(); } return this.finishNode(node, "ReturnStatement"); } parseSwitchStatement(node) { this.next(); node.discriminant = this.parseHeaderExpression(); const cases = node.cases = []; this.expect(types.braceL); this.state.labels.push(switchLabel); this.scope.enter(SCOPE_OTHER); let cur; for (let sawDefault; !this.match(types.braceR);) { if (this.match(types._case) || this.match(types._default)) { const isCase = this.match(types._case); if (cur) this.finishNode(cur, "SwitchCase"); cases.push(cur = this.startNode()); cur.consequent = []; this.next(); if (isCase) { cur.test = this.parseExpression(); } else { if (sawDefault) { this.raise(this.state.lastTokStart, "Multiple default clauses"); } sawDefault = true; cur.test = null; } this.expect(types.colon); } else { if (cur) { cur.consequent.push(this.parseStatement(null)); } else { this.unexpected(); } } } this.scope.exit(); if (cur) this.finishNode(cur, "SwitchCase"); this.next(); this.state.labels.pop(); return this.finishNode(node, "SwitchStatement"); } parseThrowStatement(node) { this.next(); if (lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start))) { this.raise(this.state.lastTokEnd, "Illegal newline after throw"); } node.argument = this.parseExpression(); this.semicolon(); return this.finishNode(node, "ThrowStatement"); } parseTryStatement(node) { this.next(); node.block = this.parseBlock(); node.handler = null; if (this.match(types._catch)) { const clause = this.startNode(); this.next(); if (this.match(types.parenL)) { this.expect(types.parenL); clause.param = this.parseBindingAtom(); const simple = clause.param.type === "Identifier"; this.scope.enter(simple ? SCOPE_SIMPLE_CATCH : 0); this.checkLVal(clause.param, BIND_LEXICAL, null, "catch clause"); this.expect(types.parenR); } else { clause.param = null; this.scope.enter(SCOPE_OTHER); } clause.body = this.withTopicForbiddingContext(() => this.parseBlock(false, false)); this.scope.exit(); node.handler = this.finishNode(clause, "CatchClause"); } node.finalizer = this.eat(types._finally) ? this.parseBlock() : null; if (!node.handler && !node.finalizer) { this.raise(node.start, "Missing catch or finally clause"); } return this.finishNode(node, "TryStatement"); } parseVarStatement(node, kind) { this.next(); this.parseVar(node, false, kind); this.semicolon(); return this.finishNode(node, "VariableDeclaration"); } parseWhileStatement(node) { this.next(); node.test = this.parseHeaderExpression(); this.state.labels.push(loopLabel); node.body = this.withTopicForbiddingContext(() => this.parseStatement("while")); this.state.labels.pop(); return this.finishNode(node, "WhileStatement"); } parseWithStatement(node) { if (this.state.strict) { this.raise(this.state.start, "'with' in strict mode"); } this.next(); node.object = this.parseHeaderExpression(); node.body = this.withTopicForbiddingContext(() => this.parseStatement("with")); return this.finishNode(node, "WithStatement"); } parseEmptyStatement(node) { this.next(); return this.finishNode(node, "EmptyStatement"); } parseLabeledStatement(node, maybeName, expr, context) { for (let _i2 = 0, _this$state$labels = this.state.labels; _i2 < _this$state$labels.length; _i2++) { const label = _this$state$labels[_i2]; if (label.name === maybeName) { this.raise(expr.start, `Label '${maybeName}' is already declared`); } } const kind = this.state.type.isLoop ? "loop" : this.match(types._switch) ? "switch" : null; for (let i = this.state.labels.length - 1; i >= 0; i--) { const label = this.state.labels[i]; if (label.statementStart === node.start) { label.statementStart = this.state.start; label.kind = kind; } else { break; } } this.state.labels.push({ name: maybeName, kind: kind, statementStart: this.state.start }); node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); this.state.labels.pop(); node.label = expr; return this.finishNode(node, "LabeledStatement"); } parseExpressionStatement(node, expr) { node.expression = expr; this.semicolon(); return this.finishNode(node, "ExpressionStatement"); } parseBlock(allowDirectives = false, createNewLexicalScope = true) { const node = this.startNode(); this.expect(types.braceL); if (createNewLexicalScope) { this.scope.enter(SCOPE_OTHER); } this.parseBlockBody(node, allowDirectives, false, types.braceR); if (createNewLexicalScope) { this.scope.exit(); } return this.finishNode(node, "BlockStatement"); } isValidDirective(stmt) { return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized; } parseBlockBody(node, allowDirectives, topLevel, end) { const body = node.body = []; const directives = node.directives = []; this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end); } parseBlockOrModuleBlockBody(body, directives, topLevel, end) { let parsedNonDirective = false; let oldStrict; let octalPosition; while (!this.eat(end)) { if (!parsedNonDirective && this.state.containsOctal && !octalPosition) { octalPosition = this.state.octalPosition; } const stmt = this.parseStatement(null, topLevel); if (directives && !parsedNonDirective && this.isValidDirective(stmt)) { const directive = this.stmtToDirective(stmt); directives.push(directive); if (oldStrict === undefined && directive.value.value === "use strict") { oldStrict = this.state.strict; this.setStrict(true); if (octalPosition) { this.raise(octalPosition, "Octal literal in strict mode"); } } continue; } parsedNonDirective = true; body.push(stmt); } if (oldStrict === false) { this.setStrict(false); } } parseFor(node, init) { node.init = init; this.expect(types.semi); node.test = this.match(types.semi) ? null : this.parseExpression(); this.expect(types.semi); node.update = this.match(types.parenR) ? null : this.parseExpression(); this.expect(types.parenR); node.body = this.withTopicForbiddingContext(() => this.parseStatement("for")); this.scope.exit(); this.state.labels.pop(); return this.finishNode(node, "ForStatement"); } parseForIn(node, init, awaitAt) { const isForIn = this.match(types._in); this.next(); if (isForIn) { if (awaitAt > -1) this.unexpected(awaitAt); } else { node.await = awaitAt > -1; } if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) { this.raise(init.start, `${isForIn ? "for-in" : "for-of"} loop variable declaration may not have an initializer`); } else if (init.type === "AssignmentPattern") { this.raise(init.start, "Invalid left-hand side in for-loop"); } node.left = init; node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign(); this.expect(types.parenR); node.body = this.withTopicForbiddingContext(() => this.parseStatement("for")); this.scope.exit(); this.state.labels.pop(); return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement"); } parseVar(node, isFor, kind) { const declarations = node.declarations = []; const isTypescript = this.hasPlugin("typescript"); node.kind = kind; for (;;) { const decl = this.startNode(); this.parseVarId(decl, kind); if (this.eat(types.eq)) { decl.init = this.parseMaybeAssign(isFor); } else { if (kind === "const" && !(this.match(types._in) || this.isContextual("of"))) { if (!isTypescript) { this.unexpected(); } } else if (decl.id.type !== "Identifier" && !(isFor && (this.match(types._in) || this.isContextual("of")))) { this.raise(this.state.lastTokEnd, "Complex binding patterns require an initialization value"); } decl.init = null; } declarations.push(this.finishNode(decl, "VariableDeclarator")); if (!this.eat(types.comma)) break; } return node; } parseVarId(decl, kind) { if ((kind === "const" || kind === "let") && this.isContextual("let")) { this.unexpected(null, "let is disallowed as a lexically bound name"); } decl.id = this.parseBindingAtom(); this.checkLVal(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, undefined, "variable declaration"); } parseFunction(node, statement = FUNC_NO_FLAGS, isAsync = false) { const isStatement = statement & FUNC_STATEMENT; const isHangingStatement = statement & FUNC_HANGING_STATEMENT; const requireId = !!isStatement && !(statement & FUNC_NULLABLE_ID); this.initFunction(node, isAsync); if (this.match(types.star) && isHangingStatement) { this.unexpected(this.state.start, "Generators can only be declared at the top level or inside a block"); } node.generator = this.eat(types.star); if (isStatement) { node.id = this.parseFunctionId(requireId); } const oldInClassProperty = this.state.inClassProperty; const oldYieldPos = this.state.yieldPos; const oldAwaitPos = this.state.awaitPos; this.state.inClassProperty = false; this.state.yieldPos = 0; this.state.awaitPos = 0; this.scope.enter(functionFlags(node.async, node.generator)); if (!isStatement) { node.id = this.parseFunctionId(); } this.parseFunctionParams(node); this.withTopicForbiddingContext(() => { this.parseFunctionBodyAndFinish(node, isStatement ? "FunctionDeclaration" : "FunctionExpression"); }); this.scope.exit(); if (isStatement && !isHangingStatement) { this.checkFunctionStatementId(node); } this.state.inClassProperty = oldInClassProperty; this.state.yieldPos = oldYieldPos; this.state.awaitPos = oldAwaitPos; return node; } parseFunctionId(requireId) { return requireId || this.match(types.name) ? this.parseIdentifier() : null; } parseFunctionParams(node, allowModifiers) { const oldInParameters = this.state.inParameters; this.state.inParameters = true; this.expect(types.parenL); node.params = this.parseBindingList(types.parenR, false, allowModifiers); this.state.inParameters = oldInParameters; this.checkYieldAwaitInDefaultParams(); } checkFunctionStatementId(node) { if (!node.id) return; this.checkLVal(node.id, this.state.strict || node.generator || node.async ? this.scope.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION, null, "function name"); } parseClass(node, isStatement, optionalId) { this.next(); this.takeDecorators(node); const oldStrict = this.state.strict; this.state.strict = true; this.parseClassId(node, isStatement, optionalId); this.parseClassSuper(node); node.body = this.parseClassBody(!!node.superClass); this.state.strict = oldStrict; return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression"); } isClassProperty() { return this.match(types.eq) || this.match(types.semi) || this.match(types.braceR); } isClassMethod() { return this.match(types.parenL); } isNonstaticConstructor(method) { return !method.computed && !method.static && (method.key.name === "constructor" || method.key.value === "constructor"); } parseClassBody(constructorAllowsSuper) { this.state.classLevel++; const state = { hadConstructor: false }; let decorators = []; const classBody = this.startNode(); classBody.body = []; this.expect(types.braceL); this.withTopicForbiddingContext(() => { while (!this.eat(types.braceR)) { if (this.eat(types.semi)) { if (decorators.length > 0) { this.raise(this.state.lastTokEnd, "Decorators must not be followed by a semicolon"); } continue; } if (this.match(types.at)) { decorators.push(this.parseDecorator()); continue; } const member = this.startNode(); if (decorators.length) { member.decorators = decorators; this.resetStartLocationFromNode(member, decorators[0]); decorators = []; } this.parseClassMember(classBody, member, state, constructorAllowsSuper); if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) { this.raise(member.start, "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?"); } } }); if (decorators.length) { this.raise(this.state.start, "You have trailing decorators with no method"); } this.state.classLevel--; return this.finishNode(classBody, "ClassBody"); } parseClassMember(classBody, member, state, constructorAllowsSuper) { let isStatic = false; const containsEsc = this.state.containsEsc; if (this.match(types.name) && this.state.value === "static") { const key = this.parseIdentifier(true); if (this.isClassMethod()) { const method = member; method.kind = "method"; method.computed = false; method.key = key; method.static = false; this.pushClassMethod(classBody, method, false, false, false, false); return; } else if (this.isClassProperty()) { const prop = member; prop.computed = false; prop.key = key; prop.static = false; classBody.body.push(this.parseClassProperty(prop)); return; } else if (containsEsc) { throw this.unexpected(); } isStatic = true; } this.parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper); } parseClassMemberWithIsStatic(classBody, member, state, isStatic, constructorAllowsSuper) { const publicMethod = member; const privateMethod = member; const publicProp = member; const privateProp = member; const method = publicMethod; const publicMember = publicMethod; member.static = isStatic; if (this.eat(types.star)) { method.kind = "method"; this.parseClassPropertyName(method); if (method.key.type === "PrivateName") { this.pushClassPrivateMethod(classBody, privateMethod, true, false); return; } if (this.isNonstaticConstructor(publicMethod)) { this.raise(publicMethod.key.start, "Constructor can't be a generator"); } this.pushClassMethod(classBody, publicMethod, true, false, false, false); return; } const containsEsc = this.state.containsEsc; const key = this.parseClassPropertyName(member); const isPrivate = key.type === "PrivateName"; const isSimple = key.type === "Identifier"; this.parsePostMemberNameModifiers(publicMember); if (this.isClassMethod()) { method.kind = "method"; if (isPrivate) { this.pushClassPrivateMethod(classBody, privateMethod, false, false); return; } const isConstructor = this.isNonstaticConstructor(publicMethod); let allowsDirectSuper = false; if (isConstructor) { publicMethod.kind = "constructor"; if (publicMethod.decorators) { this.raise(publicMethod.start, "You can't attach decorators to a class constructor"); } if (state.hadConstructor && !this.hasPlugin("typescript")) { this.raise(key.start, "Duplicate constructor in the same class"); } state.hadConstructor = true; allowsDirectSuper = constructorAllowsSuper; } this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper); } else if (this.isClassProperty()) { if (isPrivate) { this.pushClassPrivateProperty(classBody, privateProp); } else { this.pushClassProperty(classBody, publicProp); } } else if (isSimple && key.name === "async" && !containsEsc && !this.isLineTerminator()) { const isGenerator = this.eat(types.star); method.kind = "method"; this.parseClassPropertyName(method); if (method.key.type === "PrivateName") { this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true); } else { if (this.isNonstaticConstructor(publicMethod)) { this.raise(publicMethod.key.start, "Constructor can't be an async function"); } this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false); } } else if (isSimple && (key.name === "get" || key.name === "set") && !containsEsc && !(this.match(types.star) && this.isLineTerminator())) { method.kind = key.name; this.parseClassPropertyName(publicMethod); if (method.key.type === "PrivateName") { this.pushClassPrivateMethod(classBody, privateMethod, false, false); } else { if (this.isNonstaticConstructor(publicMethod)) { this.raise(publicMethod.key.start, "Constructor can't have get/set modifier"); } this.pushClassMethod(classBody, publicMethod, false, false, false, false); } this.checkGetterSetterParams(publicMethod); } else if (this.isLineTerminator()) { if (isPrivate) { this.pushClassPrivateProperty(classBody, privateProp); } else { this.pushClassProperty(classBody, publicProp); } } else { this.unexpected(); } } parseClassPropertyName(member) { const key = this.parsePropertyName(member); if (!member.computed && member.static && (key.name === "prototype" || key.value === "prototype")) { this.raise(key.start, "Classes may not have static property named prototype"); } if (key.type === "PrivateName" && key.id.name === "constructor") { this.raise(key.start, "Classes may not have a private field named '#constructor'"); } return key; } pushClassProperty(classBody, prop) { if (this.isNonstaticConstructor(prop)) { this.raise(prop.key.start, "Classes may not have a non-static field named 'constructor'"); } classBody.body.push(this.parseClassProperty(prop)); } pushClassPrivateProperty(classBody, prop) { this.expectPlugin("classPrivateProperties", prop.key.start); classBody.body.push(this.parseClassPrivateProperty(prop)); } pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true)); } pushClassPrivateMethod(classBody, method, isGenerator, isAsync) { this.expectPlugin("classPrivateMethods", method.key.start); classBody.body.push(this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true)); } parsePostMemberNameModifiers(methodOrProp) {} parseAccessModifier() { return undefined; } parseClassPrivateProperty(node) { this.state.inClassProperty = true; this.scope.enter(SCOPE_CLASS | SCOPE_SUPER); node.value = this.eat(types.eq) ? this.parseMaybeAssign() : null; this.semicolon(); this.state.inClassProperty = false; this.scope.exit(); return this.finishNode(node, "ClassPrivateProperty"); } parseClassProperty(node) { if (!node.typeAnnotation) { this.expectPlugin("classProperties"); } this.state.inClassProperty = true; this.scope.enter(SCOPE_CLASS | SCOPE_SUPER); if (this.match(types.eq)) { this.expectPlugin("classProperties"); this.next(); node.value = this.parseMaybeAssign(); } else { node.value = null; } this.semicolon(); this.state.inClassProperty = false; this.scope.exit(); return this.finishNode(node, "ClassProperty"); } parseClassId(node, isStatement, optionalId) { if (this.match(types.name)) { node.id = this.parseIdentifier(); if (isStatement) { this.checkLVal(node.id, BIND_CLASS, undefined, "class name"); } } else { if (optionalId || !isStatement) { node.id = null; } else { this.unexpected(null, "A class name is required"); } } } parseClassSuper(node) { node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null; } parseExport(node) { const hasDefault = this.maybeParseExportDefaultSpecifier(node); const parseAfterDefault = !hasDefault || this.eat(types.comma); const hasStar = parseAfterDefault && this.eatExportStar(node); const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node); const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(types.comma)); const isFromRequired = hasDefault || hasStar; if (hasStar && !hasNamespace) { if (hasDefault) this.unexpected(); this.parseExportFrom(node, true); return this.finishNode(node, "ExportAllDeclaration"); } const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node); if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers || hasNamespace && parseAfterNamespace && !hasSpecifiers) { throw this.unexpected(null, types.braceL); } let hasDeclaration; if (isFromRequired || hasSpecifiers) { hasDeclaration = false; this.parseExportFrom(node, isFromRequired); } else { hasDeclaration = this.maybeParseExportDeclaration(node); } if (isFromRequired || hasSpecifiers || hasDeclaration) { this.checkExport(node, true, false, !!node.source); return this.finishNode(node, "ExportNamedDeclaration"); } if (this.eat(types._default)) { node.declaration = this.parseExportDefaultExpression(); this.checkExport(node, true, true); return this.finishNode(node, "ExportDefaultDeclaration"); } throw this.unexpected(null, types.braceL); } eatExportStar(node) { return this.eat(types.star); } maybeParseExportDefaultSpecifier(node) { if (this.isExportDefaultSpecifier()) { this.expectPlugin("exportDefaultFrom"); const specifier = this.startNode(); specifier.exported = this.parseIdentifier(true); node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")]; return true; } return false; } maybeParseExportNamespaceSpecifier(node) { if (this.isContextual("as")) { if (!node.specifiers) node.specifiers = []; this.expectPlugin("exportNamespaceFrom"); const specifier = this.startNodeAt(this.state.lastTokStart, this.state.lastTokStartLoc); this.next(); specifier.exported = this.parseIdentifier(true); node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier")); return true; } return false; } maybeParseExportNamedSpecifiers(node) { if (this.match(types.braceL)) { if (!node.specifiers) node.specifiers = []; node.specifiers.push(...this.parseExportSpecifiers()); node.source = null; node.declaration = null; return true; } return false; } maybeParseExportDeclaration(node) { if (this.shouldParseExportDeclaration()) { if (this.isContextual("async")) { const next = this.lookahead(); if (next.type !== types._function) { this.unexpected(next.start, `Unexpected token, expected "function"`); } } node.specifiers = []; node.source = null; node.declaration = this.parseExportDeclaration(node); return true; } return false; } isAsyncFunction() { if (!this.isContextual("async")) return false; const { pos } = this.state; skipWhiteSpace.lastIndex = pos; const skip = skipWhiteSpace.exec(this.input); if (!skip || !skip.length) return false; const next = pos + skip[0].length; return !lineBreak.test(this.input.slice(pos, next)) && this.input.slice(next, next + 8) === "function" && (next + 8 === this.length || !isIdentifierChar(this.input.charCodeAt(next + 8))); } parseExportDefaultExpression() { const expr = this.startNode(); const isAsync = this.isAsyncFunction(); if (this.match(types._function) || isAsync) { this.next(); if (isAsync) { this.next(); } return this.parseFunction(expr, FUNC_STATEMENT | FUNC_NULLABLE_ID, isAsync); } else if (this.match(types._class)) { return this.parseClass(expr, true, true); } else if (this.match(types.at)) { if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport")) { this.unexpected(this.state.start, "Decorators must be placed *before* the 'export' keyword." + " You can set the 'decoratorsBeforeExport' option to false to use" + " the 'export @decorator class {}' syntax"); } this.parseDecorators(false); return this.parseClass(expr, true, true); } else if (this.match(types._const) || this.match(types._var) || this.isLet()) { return this.raise(this.state.start, "Only expressions, functions or classes are allowed as the `default` export."); } else { const res = this.parseMaybeAssign(); this.semicolon(); return res; } } parseExportDeclaration(node) { return this.parseStatement(null); } isExportDefaultSpecifier() { if (this.match(types.name)) { return this.state.value !== "async" && this.state.value !== "let"; } if (!this.match(types._default)) { return false; } const lookahead = this.lookahead(); return lookahead.type === types.comma || lookahead.type === types.name && lookahead.value === "from"; } parseExportFrom(node, expect) { if (this.eatContextual("from")) { node.source = this.parseImportSource(); this.checkExport(node); } else { if (expect) { this.unexpected(); } else { node.source = null; } } this.semicolon(); } shouldParseExportDeclaration() { if (this.match(types.at)) { this.expectOnePlugin(["decorators", "decorators-legacy"]); if (this.hasPlugin("decorators")) { if (this.getPluginOption("decorators", "decoratorsBeforeExport")) { this.unexpected(this.state.start, "Decorators must be placed *before* the 'export' keyword." + " You can set the 'decoratorsBeforeExport' option to false to use" + " the 'export @decorator class {}' syntax"); } else { return true; } } } return this.state.type.keyword === "var" || this.state.type.keyword === "const" || this.state.type.keyword === "function" || this.state.type.keyword === "class" || this.isLet() || this.isAsyncFunction(); } checkExport(node, checkNames, isDefault, isFrom) { if (checkNames) { if (isDefault) { this.checkDuplicateExports(node, "default"); } else if (node.specifiers && node.specifiers.length) { for (let _i3 = 0, _node$specifiers = node.specifiers; _i3 < _node$specifiers.length; _i3++) { const specifier = _node$specifiers[_i3]; this.checkDuplicateExports(specifier, specifier.exported.name); if (!isFrom && specifier.local) { this.checkReservedWord(specifier.local.name, specifier.local.start, true, false); this.scope.checkLocalExport(specifier.local); } } } else if (node.declaration) { if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") { const id = node.declaration.id; if (!id) throw new Error("Assertion failure"); this.checkDuplicateExports(node, id.name); } else if (node.declaration.type === "VariableDeclaration") { for (let _i4 = 0, _node$declaration$dec = node.declaration.declarations; _i4 < _node$declaration$dec.length; _i4++) { const declaration = _node$declaration$dec[_i4]; this.checkDeclaration(declaration.id); } } } } const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1]; if (currentContextDecorators.length) { const isClass = node.declaration && (node.declaration.type === "ClassDeclaration" || node.declaration.type === "ClassExpression"); if (!node.declaration || !isClass) { throw this.raise(node.start, "You can only use decorators on an export when exporting a class"); } this.takeDecorators(node.declaration); } } checkDeclaration(node) { if (node.type === "Identifier") { this.checkDuplicateExports(node, node.name); } else if (node.type === "ObjectPattern") { for (let _i5 = 0, _node$properties = node.properties; _i5 < _node$properties.length; _i5++) { const prop = _node$properties[_i5]; this.checkDeclaration(prop); } } else if (node.type === "ArrayPattern") { for (let _i6 = 0, _node$elements = node.elements; _i6 < _node$elements.length; _i6++) { const elem = _node$elements[_i6]; if (elem) { this.checkDeclaration(elem); } } } else if (node.type === "ObjectProperty") { this.checkDeclaration(node.value); } else if (node.type === "RestElement") { this.checkDeclaration(node.argument); } else if (node.type === "AssignmentPattern") { this.checkDeclaration(node.left); } } checkDuplicateExports(node, name) { if (this.state.exportedIdentifiers.indexOf(name) > -1) { throw this.raise(node.start, name === "default" ? "Only one default export allowed per module." : `\`${name}\` has already been exported. Exported identifiers must be unique.`); } this.state.exportedIdentifiers.push(name); } parseExportSpecifiers() { const nodes = []; let first = true; this.expect(types.braceL); while (!this.eat(types.braceR)) { if (first) { first = false; } else { this.expect(types.comma); if (this.eat(types.braceR)) break; } const node = this.startNode(); node.local = this.parseIdentifier(true); node.exported = this.eatContextual("as") ? this.parseIdentifier(true) : node.local.__clone(); nodes.push(this.finishNode(node, "ExportSpecifier")); } return nodes; } parseImport(node) { node.specifiers = []; if (!this.match(types.string)) { const hasDefault = this.maybeParseDefaultImportSpecifier(node); const parseNext = !hasDefault || this.eat(types.comma); const hasStar = parseNext && this.maybeParseStarImportSpecifier(node); if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node); this.expectContextual("from"); } node.source = this.parseImportSource(); this.semicolon(); return this.finishNode(node, "ImportDeclaration"); } parseImportSource() { if (!this.match(types.string)) this.unexpected(); return this.parseExprAtom(); } shouldParseDefaultImport(node) { return this.match(types.name); } parseImportSpecifierLocal(node, specifier, type, contextDescription) { specifier.local = this.parseIdentifier(); this.checkLVal(specifier.local, BIND_LEXICAL, undefined, contextDescription); node.specifiers.push(this.finishNode(specifier, type)); } maybeParseDefaultImportSpecifier(node) { if (this.shouldParseDefaultImport(node)) { this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier", "default import specifier"); return true; } return false; } maybeParseStarImportSpecifier(node) { if (this.match(types.star)) { const specifier = this.startNode(); this.next(); this.expectContextual("as"); this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier", "import namespace specifier"); return true; } return false; } parseNamedImportSpecifiers(node) { let first = true; this.expect(types.braceL); while (!this.eat(types.braceR)) { if (first) { first = false; } else { if (this.eat(types.colon)) { this.unexpected(null, "ES2015 named imports do not destructure. " + "Use another statement for destructuring after the import."); } this.expect(types.comma); if (this.eat(types.braceR)) break; } this.parseImportSpecifier(node); } } parseImportSpecifier(node) { const specifier = this.startNode(); specifier.imported = this.parseIdentifier(true); if (this.eatContextual("as")) { specifier.local = this.parseIdentifier(); } else { this.checkReservedWord(specifier.imported.name, specifier.start, true, true); specifier.local = specifier.imported.__clone(); } this.checkLVal(specifier.local, BIND_LEXICAL, undefined, "import specifier"); node.specifiers.push(this.finishNode(specifier, "ImportSpecifier")); } } class Parser extends StatementParser { constructor(options, input) { options = getOptions(options); super(options, input); const ScopeHandler = this.getScopeHandler(); this.options = options; this.inModule = this.options.sourceType === "module"; this.scope = new ScopeHandler(this.raise.bind(this), this.inModule); this.plugins = pluginsMap(this.options.plugins); this.filename = options.sourceFilename; } getScopeHandler() { return ScopeHandler; } parse() { this.scope.enter(SCOPE_PROGRAM); const file = this.startNode(); const program = this.startNode(); this.nextToken(); return this.parseTopLevel(file, program); } } function pluginsMap(plugins) { const pluginMap = new Map(); for (let _i = 0; _i < plugins.length; _i++) { const plugin = plugins[_i]; const [name, options] = Array.isArray(plugin) ? plugin : [plugin, {}]; if (!pluginMap.has(name)) pluginMap.set(name, options || {}); } return pluginMap; } function parse(input, options) { if (options && options.sourceType === "unambiguous") { options = Object.assign({}, options); try { options.sourceType = "module"; const parser = getParser(options, input); const ast = parser.parse(); if (!parser.sawUnambiguousESM) ast.program.sourceType = "script"; return ast; } catch (moduleError) { try { options.sourceType = "script"; return getParser(options, input).parse(); } catch (scriptError) {} throw moduleError; } } else { return getParser(options, input).parse(); } } function parseExpression(input, options) { const parser = getParser(options, input); if (parser.options.strictMode) { parser.state.strict = true; } return parser.getExpression(); } function getParser(options, input) { let cls = Parser; if (options && options.plugins) { validatePlugins(options.plugins); cls = getParserClass(options.plugins); } return new cls(options, input); } const parserClassCache = {}; function getParserClass(pluginsFromOptions) { const pluginList = mixinPluginNames.filter(name => hasPlugin(pluginsFromOptions, name)); const key = pluginList.join("/"); let cls = parserClassCache[key]; if (!cls) { cls = Parser; for (let _i = 0; _i < pluginList.length; _i++) { const plugin = pluginList[_i]; cls = mixinPlugins[plugin](cls); } parserClassCache[key] = cls; } return cls; } exports.parse = parse; exports.parseExpression = parseExpression; exports.tokTypes = types; },{}],68:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = createTemplateBuilder; var _options = require("./options"); var _string = _interopRequireDefault(require("./string")); var _literal = _interopRequireDefault(require("./literal")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const NO_PLACEHOLDER = (0, _options.validate)({ placeholderPattern: false }); function createTemplateBuilder(formatter, defaultOpts) { const templateFnCache = new WeakMap(); const templateAstCache = new WeakMap(); const cachedOpts = defaultOpts || (0, _options.validate)(null); return Object.assign((tpl, ...args) => { if (typeof tpl === "string") { if (args.length > 1) throw new Error("Unexpected extra params."); return extendedTrace((0, _string.default)(formatter, tpl, (0, _options.merge)(cachedOpts, (0, _options.validate)(args[0])))); } else if (Array.isArray(tpl)) { let builder = templateFnCache.get(tpl); if (!builder) { builder = (0, _literal.default)(formatter, tpl, cachedOpts); templateFnCache.set(tpl, builder); } return extendedTrace(builder(args)); } else if (typeof tpl === "object" && tpl) { if (args.length > 0) throw new Error("Unexpected extra params."); return createTemplateBuilder(formatter, (0, _options.merge)(cachedOpts, (0, _options.validate)(tpl))); } throw new Error(`Unexpected template param ${typeof tpl}`); }, { ast: (tpl, ...args) => { if (typeof tpl === "string") { if (args.length > 1) throw new Error("Unexpected extra params."); return (0, _string.default)(formatter, tpl, (0, _options.merge)((0, _options.merge)(cachedOpts, (0, _options.validate)(args[0])), NO_PLACEHOLDER))(); } else if (Array.isArray(tpl)) { let builder = templateAstCache.get(tpl); if (!builder) { builder = (0, _literal.default)(formatter, tpl, (0, _options.merge)(cachedOpts, NO_PLACEHOLDER)); templateAstCache.set(tpl, builder); } return builder(args)(); } throw new Error(`Unexpected template param ${typeof tpl}`); } }); } function extendedTrace(fn) { let rootStack = ""; try { throw new Error(); } catch (error) { if (error.stack) { rootStack = error.stack.split("\n").slice(3).join("\n"); } } return arg => { try { return fn(arg); } catch (err) { err.stack += `\n =============\n${rootStack}`; throw err; } }; } },{"./literal":71,"./options":72,"./string":75}],69:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.program = exports.expression = exports.statement = exports.statements = exports.smart = void 0; function makeStatementFormatter(fn) { return { code: str => `/* @babel/template */;\n${str}`, validate: () => {}, unwrap: ast => { return fn(ast.program.body.slice(1)); } }; } const smart = makeStatementFormatter(body => { if (body.length > 1) { return body; } else { return body[0]; } }); exports.smart = smart; const statements = makeStatementFormatter(body => body); exports.statements = statements; const statement = makeStatementFormatter(body => { if (body.length === 0) { throw new Error("Found nothing to return."); } if (body.length > 1) { throw new Error("Found multiple statements but wanted one"); } return body[0]; }); exports.statement = statement; const expression = { code: str => `(\n${str}\n)`, validate: ({ program }) => { if (program.body.length > 1) { throw new Error("Found multiple statements but wanted one"); } const expression = program.body[0].expression; if (expression.start === 0) { throw new Error("Parse result included parens."); } }, unwrap: ast => ast.program.body[0].expression }; exports.expression = expression; const program = { code: str => str, validate: () => {}, unwrap: ast => ast.program }; exports.program = program; },{}],70:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = exports.program = exports.expression = exports.statements = exports.statement = exports.smart = void 0; var formatters = _interopRequireWildcard(require("./formatters")); var _builder = _interopRequireDefault(require("./builder")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } const smart = (0, _builder.default)(formatters.smart); exports.smart = smart; const statement = (0, _builder.default)(formatters.statement); exports.statement = statement; const statements = (0, _builder.default)(formatters.statements); exports.statements = statements; const expression = (0, _builder.default)(formatters.expression); exports.expression = expression; const program = (0, _builder.default)(formatters.program); exports.program = program; var _default = Object.assign(smart.bind(undefined), { smart, statement, statements, expression, program, ast: smart.ast }); exports.default = _default; },{"./builder":68,"./formatters":69}],71:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = literalTemplate; var _options = require("./options"); var _parse = _interopRequireDefault(require("./parse")); var _populate = _interopRequireDefault(require("./populate")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function literalTemplate(formatter, tpl, opts) { const { metadata, names } = buildLiteralData(formatter, tpl, opts); return arg => { const defaultReplacements = arg.reduce((acc, replacement, i) => { acc[names[i]] = replacement; return acc; }, {}); return arg => { const replacements = (0, _options.normalizeReplacements)(arg); if (replacements) { Object.keys(replacements).forEach(key => { if (Object.prototype.hasOwnProperty.call(defaultReplacements, key)) { throw new Error("Unexpected replacement overlap."); } }); } return formatter.unwrap((0, _populate.default)(metadata, replacements ? Object.assign(replacements, defaultReplacements) : defaultReplacements)); }; }; } function buildLiteralData(formatter, tpl, opts) { let names; let nameSet; let metadata; let prefix = ""; do { prefix += "$"; const result = buildTemplateCode(tpl, prefix); names = result.names; nameSet = new Set(names); metadata = (0, _parse.default)(formatter, formatter.code(result.code), { parser: opts.parser, placeholderWhitelist: new Set(result.names.concat(opts.placeholderWhitelist ? Array.from(opts.placeholderWhitelist) : [])), placeholderPattern: opts.placeholderPattern, preserveComments: opts.preserveComments, syntacticPlaceholders: opts.syntacticPlaceholders }); } while (metadata.placeholders.some(placeholder => placeholder.isDuplicate && nameSet.has(placeholder.name))); return { metadata, names }; } function buildTemplateCode(tpl, prefix) { const names = []; let code = tpl[0]; for (let i = 1; i < tpl.length; i++) { const value = `${prefix}${i - 1}`; names.push(value); code += value + tpl[i]; } return { names, code }; } },{"./options":72,"./parse":73,"./populate":74}],72:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.merge = merge; exports.validate = validate; exports.normalizeReplacements = normalizeReplacements; 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; } function merge(a, b) { const { placeholderWhitelist = a.placeholderWhitelist, placeholderPattern = a.placeholderPattern, preserveComments = a.preserveComments, syntacticPlaceholders = a.syntacticPlaceholders } = b; return { parser: Object.assign({}, a.parser, b.parser), placeholderWhitelist, placeholderPattern, preserveComments, syntacticPlaceholders }; } function validate(opts) { if (opts != null && typeof opts !== "object") { throw new Error("Unknown template options."); } const _ref = opts || {}, { placeholderWhitelist, placeholderPattern, preserveComments, syntacticPlaceholders } = _ref, parser = _objectWithoutPropertiesLoose(_ref, ["placeholderWhitelist", "placeholderPattern", "preserveComments", "syntacticPlaceholders"]); if (placeholderWhitelist != null && !(placeholderWhitelist instanceof Set)) { throw new Error("'.placeholderWhitelist' must be a Set, null, or undefined"); } if (placeholderPattern != null && !(placeholderPattern instanceof RegExp) && placeholderPattern !== false) { throw new Error("'.placeholderPattern' must be a RegExp, false, null, or undefined"); } if (preserveComments != null && typeof preserveComments !== "boolean") { throw new Error("'.preserveComments' must be a boolean, null, or undefined"); } if (syntacticPlaceholders != null && typeof syntacticPlaceholders !== "boolean") { throw new Error("'.syntacticPlaceholders' must be a boolean, null, or undefined"); } if (syntacticPlaceholders === true && (placeholderWhitelist != null || placeholderPattern != null)) { throw new Error("'.placeholderWhitelist' and '.placeholderPattern' aren't compatible" + " with '.syntacticPlaceholders: true'"); } return { parser, placeholderWhitelist: placeholderWhitelist || undefined, placeholderPattern: placeholderPattern == null ? undefined : placeholderPattern, preserveComments: preserveComments == null ? false : preserveComments, syntacticPlaceholders: syntacticPlaceholders == null ? undefined : syntacticPlaceholders }; } function normalizeReplacements(replacements) { if (Array.isArray(replacements)) { return replacements.reduce((acc, replacement, i) => { acc["$" + i] = replacement; return acc; }, {}); } else if (typeof replacements === "object" || replacements == null) { return replacements || undefined; } throw new Error("Template replacements must be an array, object, null, or undefined"); } },{}],73:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = parseAndBuildMetadata; function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } function _parser() { const data = require("@babel/parser"); _parser = function () { return data; }; return data; } function _codeFrame() { const data = require("@babel/code-frame"); _codeFrame = function () { return data; }; return data; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } const PATTERN = /^[_$A-Z0-9]+$/; function parseAndBuildMetadata(formatter, code, opts) { const ast = parseWithCodeFrame(code, opts.parser); const { placeholderWhitelist, placeholderPattern, preserveComments, syntacticPlaceholders } = opts; t().removePropertiesDeep(ast, { preserveComments }); formatter.validate(ast); const syntactic = { placeholders: [], placeholderNames: new Set() }; const legacy = { placeholders: [], placeholderNames: new Set() }; const isLegacyRef = { value: undefined }; t().traverse(ast, placeholderVisitorHandler, { syntactic, legacy, isLegacyRef, placeholderWhitelist, placeholderPattern, syntacticPlaceholders }); return Object.assign({ ast }, isLegacyRef.value ? legacy : syntactic); } function placeholderVisitorHandler(node, ancestors, state) { let name; if (t().isPlaceholder(node)) { if (state.syntacticPlaceholders === false) { throw new Error("%%foo%%-style placeholders can't be used when " + "'.syntacticPlaceholders' is false."); } else { name = node.name.name; state.isLegacyRef.value = false; } } else if (state.isLegacyRef.value === false || state.syntacticPlaceholders) { return; } else if (t().isIdentifier(node) || t().isJSXIdentifier(node)) { name = node.name; state.isLegacyRef.value = true; } else if (t().isStringLiteral(node)) { name = node.value; state.isLegacyRef.value = true; } else { return; } if (!state.isLegacyRef.value && (state.placeholderPattern != null || state.placeholderWhitelist != null)) { throw new Error("'.placeholderWhitelist' and '.placeholderPattern' aren't compatible" + " with '.syntacticPlaceholders: true'"); } if (state.isLegacyRef.value && (state.placeholderPattern === false || !(state.placeholderPattern || PATTERN).test(name)) && (!state.placeholderWhitelist || !state.placeholderWhitelist.has(name))) { return; } ancestors = ancestors.slice(); const { node: parent, key } = ancestors[ancestors.length - 1]; let type; if (t().isStringLiteral(node) || t().isPlaceholder(node, { expectedNode: "StringLiteral" })) { type = "string"; } else if (t().isNewExpression(parent) && key === "arguments" || t().isCallExpression(parent) && key === "arguments" || t().isFunction(parent) && key === "params") { type = "param"; } else if (t().isExpressionStatement(parent) && !t().isPlaceholder(node)) { type = "statement"; ancestors = ancestors.slice(0, -1); } else if (t().isStatement(node) && t().isPlaceholder(node)) { type = "statement"; } else { type = "other"; } const { placeholders, placeholderNames } = state.isLegacyRef.value ? state.legacy : state.syntactic; placeholders.push({ name, type, resolve: ast => resolveAncestors(ast, ancestors), isDuplicate: placeholderNames.has(name) }); placeholderNames.add(name); } function resolveAncestors(ast, ancestors) { let parent = ast; for (let i = 0; i < ancestors.length - 1; i++) { const { key, index } = ancestors[i]; if (index === undefined) { parent = parent[key]; } else { parent = parent[key][index]; } } const { key, index } = ancestors[ancestors.length - 1]; return { parent, key, index }; } function parseWithCodeFrame(code, parserOpts) { parserOpts = Object.assign({ allowReturnOutsideFunction: true, allowSuperOutsideMethod: true, sourceType: "module" }, parserOpts, { plugins: (parserOpts.plugins || []).concat("placeholders") }); try { return (0, _parser().parse)(code, parserOpts); } catch (err) { const loc = err.loc; if (loc) { err.message += "\n" + (0, _codeFrame().codeFrameColumns)(code, { start: loc }); err.code = "BABEL_TEMPLATE_PARSE_ERROR"; } throw err; } } },{"@babel/code-frame":8,"@babel/parser":67,"@babel/types":142}],74:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = populatePlaceholders; function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function populatePlaceholders(metadata, replacements) { const ast = t().cloneNode(metadata.ast); if (replacements) { metadata.placeholders.forEach(placeholder => { if (!Object.prototype.hasOwnProperty.call(replacements, placeholder.name)) { const placeholderName = placeholder.name; throw new Error(`Error: No substitution given for "${placeholderName}". If this is not meant to be a placeholder you may want to consider passing one of the following options to @babel/template: - { placeholderPattern: false, placeholderWhitelist: new Set(['${placeholderName}'])} - { placeholderPattern: /^${placeholderName}$/ }`); } }); Object.keys(replacements).forEach(key => { if (!metadata.placeholderNames.has(key)) { throw new Error(`Unknown substitution "${key}" given`); } }); } metadata.placeholders.slice().reverse().forEach(placeholder => { try { applyReplacement(placeholder, ast, replacements && replacements[placeholder.name] || null); } catch (e) { e.message = `@babel/template placeholder "${placeholder.name}": ${e.message}`; throw e; } }); return ast; } function applyReplacement(placeholder, ast, replacement) { if (placeholder.isDuplicate) { if (Array.isArray(replacement)) { replacement = replacement.map(node => t().cloneNode(node)); } else if (typeof replacement === "object") { replacement = t().cloneNode(replacement); } } const { parent, key, index } = placeholder.resolve(ast); if (placeholder.type === "string") { if (typeof replacement === "string") { replacement = t().stringLiteral(replacement); } if (!replacement || !t().isStringLiteral(replacement)) { throw new Error("Expected string substitution"); } } else if (placeholder.type === "statement") { if (index === undefined) { if (!replacement) { replacement = t().emptyStatement(); } else if (Array.isArray(replacement)) { replacement = t().blockStatement(replacement); } else if (typeof replacement === "string") { replacement = t().expressionStatement(t().identifier(replacement)); } else if (!t().isStatement(replacement)) { replacement = t().expressionStatement(replacement); } } else { if (replacement && !Array.isArray(replacement)) { if (typeof replacement === "string") { replacement = t().identifier(replacement); } if (!t().isStatement(replacement)) { replacement = t().expressionStatement(replacement); } } } } else if (placeholder.type === "param") { if (typeof replacement === "string") { replacement = t().identifier(replacement); } if (index === undefined) throw new Error("Assertion failure."); } else { if (typeof replacement === "string") { replacement = t().identifier(replacement); } if (Array.isArray(replacement)) { throw new Error("Cannot replace single expression with an array."); } } if (index === undefined) { t().validate(parent, key, replacement); parent[key] = replacement; } else { const items = parent[key].slice(); if (placeholder.type === "statement" || placeholder.type === "param") { if (replacement == null) { items.splice(index, 1); } else if (Array.isArray(replacement)) { items.splice(index, 1, ...replacement); } else { items[index] = replacement; } } else { items[index] = replacement; } t().validate(parent, key, items); parent[key] = items; } } },{"@babel/types":142}],75:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = stringTemplate; var _options = require("./options"); var _parse = _interopRequireDefault(require("./parse")); var _populate = _interopRequireDefault(require("./populate")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function stringTemplate(formatter, code, opts) { code = formatter.code(code); let metadata; return arg => { const replacements = (0, _options.normalizeReplacements)(arg); if (!metadata) metadata = (0, _parse.default)(formatter, code, opts); return formatter.unwrap((0, _populate.default)(metadata, replacements)); }; } },{"./options":72,"./parse":73,"./populate":74}],76:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.clear = clear; exports.clearPath = clearPath; exports.clearScope = clearScope; exports.scope = exports.path = void 0; let path = new WeakMap(); exports.path = path; let scope = new WeakMap(); exports.scope = scope; function clear() { clearPath(); clearScope(); } function clearPath() { exports.path = path = new WeakMap(); } function clearScope() { exports.scope = scope = new WeakMap(); } },{}],77:[function(require,module,exports){ (function (process){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _path = _interopRequireDefault(require("./path")); function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const testing = process.env.NODE_ENV === "test"; class TraversalContext { constructor(scope, opts, state, parentPath) { this.queue = null; this.parentPath = parentPath; this.scope = scope; this.state = state; this.opts = opts; } shouldVisit(node) { const opts = this.opts; if (opts.enter || opts.exit) return true; if (opts[node.type]) return true; const keys = t().VISITOR_KEYS[node.type]; if (!keys || !keys.length) return false; for (const key of keys) { if (node[key]) return true; } return false; } create(node, obj, key, listKey) { return _path.default.get({ parentPath: this.parentPath, parent: node, container: obj, key: key, listKey }); } maybeQueue(path, notPriority) { if (this.trap) { throw new Error("Infinite cycle detected"); } if (this.queue) { if (notPriority) { this.queue.push(path); } else { this.priorityQueue.push(path); } } } visitMultiple(container, parent, listKey) { if (container.length === 0) return false; const queue = []; for (let key = 0; key < container.length; key++) { const node = container[key]; if (node && this.shouldVisit(node)) { queue.push(this.create(parent, container, key, listKey)); } } return this.visitQueue(queue); } visitSingle(node, key) { if (this.shouldVisit(node[key])) { return this.visitQueue([this.create(node, node, key)]); } else { return false; } } visitQueue(queue) { this.queue = queue; this.priorityQueue = []; const visited = []; let stop = false; for (const path of queue) { path.resync(); if (path.contexts.length === 0 || path.contexts[path.contexts.length - 1] !== this) { path.pushContext(this); } if (path.key === null) continue; if (testing && queue.length >= 10000) { this.trap = true; } if (visited.indexOf(path.node) >= 0) continue; visited.push(path.node); if (path.visit()) { stop = true; break; } if (this.priorityQueue.length) { stop = this.visitQueue(this.priorityQueue); this.priorityQueue = []; this.queue = queue; if (stop) break; } } for (const path of queue) { path.popContext(); } this.queue = null; return stop; } visit(node, key) { const nodes = node[key]; if (!nodes) return false; if (Array.isArray(nodes)) { return this.visitMultiple(nodes, node, key); } else { return this.visitSingle(node, key); } } } exports.default = TraversalContext; }).call(this,require('_process')) },{"./path":86,"@babel/types":142,"_process":405}],78:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; class Hub { getCode() {} getScope() {} addHelper() { throw new Error("Helpers are not supported by the default hub."); } buildError(node, msg, Error = TypeError) { return new Error(msg); } } exports.default = Hub; },{}],79:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = traverse; Object.defineProperty(exports, "NodePath", { enumerable: true, get: function () { return _path.default; } }); Object.defineProperty(exports, "Scope", { enumerable: true, get: function () { return _scope.default; } }); Object.defineProperty(exports, "Hub", { enumerable: true, get: function () { return _hub.default; } }); exports.visitors = void 0; var _context = _interopRequireDefault(require("./context")); var visitors = _interopRequireWildcard(require("./visitors")); exports.visitors = visitors; function _includes() { const data = _interopRequireDefault(require("lodash/includes")); _includes = function () { return data; }; return data; } function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } var cache = _interopRequireWildcard(require("./cache")); var _path = _interopRequireDefault(require("./path")); var _scope = _interopRequireDefault(require("./scope")); var _hub = _interopRequireDefault(require("./hub")); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function traverse(parent, opts, scope, state, parentPath) { if (!parent) return; if (!opts) opts = {}; if (!opts.noScope && !scope) { if (parent.type !== "Program" && parent.type !== "File") { throw new Error("You must pass a scope and parentPath unless traversing a Program/File. " + `Instead of that you tried to traverse a ${parent.type} node without ` + "passing scope and parentPath."); } } visitors.explode(opts); traverse.node(parent, opts, scope, state, parentPath); } traverse.visitors = visitors; traverse.verify = visitors.verify; traverse.explode = visitors.explode; traverse.cheap = function (node, enter) { return t().traverseFast(node, enter); }; traverse.node = function (node, opts, scope, state, parentPath, skipKeys) { const keys = t().VISITOR_KEYS[node.type]; if (!keys) return; const context = new _context.default(scope, opts, state, parentPath); for (const key of keys) { if (skipKeys && skipKeys[key]) continue; if (context.visit(node, key)) return; } }; traverse.clearNode = function (node, opts) { t().removeProperties(node, opts); cache.path.delete(node); }; traverse.removeProperties = function (tree, opts) { t().traverseFast(tree, traverse.clearNode, opts); return tree; }; function hasBlacklistedType(path, state) { if (path.node.type === state.type) { state.has = true; path.stop(); } } traverse.hasType = function (tree, type, blacklistTypes) { if ((0, _includes().default)(blacklistTypes, tree.type)) return false; if (tree.type === type) return true; const state = { has: false, type: type }; traverse(tree, { noScope: true, blacklist: blacklistTypes, enter: hasBlacklistedType }, null, state); return state.has; }; traverse.cache = cache; },{"./cache":76,"./context":77,"./hub":78,"./path":86,"./scope":98,"./visitors":100,"@babel/types":142,"lodash/includes":369}],80:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.findParent = findParent; exports.find = find; exports.getFunctionParent = getFunctionParent; exports.getStatementParent = getStatementParent; exports.getEarliestCommonAncestorFrom = getEarliestCommonAncestorFrom; exports.getDeepestCommonAncestorFrom = getDeepestCommonAncestorFrom; exports.getAncestry = getAncestry; exports.isAncestor = isAncestor; exports.isDescendant = isDescendant; exports.inType = inType; function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } var _index = _interopRequireDefault(require("./index")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function findParent(callback) { let path = this; while (path = path.parentPath) { if (callback(path)) return path; } return null; } function find(callback) { let path = this; do { if (callback(path)) return path; } while (path = path.parentPath); return null; } function getFunctionParent() { return this.findParent(p => p.isFunction()); } function getStatementParent() { let path = this; do { if (!path.parentPath || Array.isArray(path.container) && path.isStatement()) { break; } else { path = path.parentPath; } } while (path); if (path && (path.isProgram() || path.isFile())) { throw new Error("File/Program node, we can't possibly find a statement parent to this"); } return path; } function getEarliestCommonAncestorFrom(paths) { return this.getDeepestCommonAncestorFrom(paths, function (deepest, i, ancestries) { let earliest; const keys = t().VISITOR_KEYS[deepest.type]; for (const ancestry of ancestries) { const path = ancestry[i + 1]; if (!earliest) { earliest = path; continue; } if (path.listKey && earliest.listKey === path.listKey) { if (path.key < earliest.key) { earliest = path; continue; } } const earliestKeyIndex = keys.indexOf(earliest.parentKey); const currentKeyIndex = keys.indexOf(path.parentKey); if (earliestKeyIndex > currentKeyIndex) { earliest = path; } } return earliest; }); } function getDeepestCommonAncestorFrom(paths, filter) { if (!paths.length) { return this; } if (paths.length === 1) { return paths[0]; } let minDepth = Infinity; let lastCommonIndex, lastCommon; const ancestries = paths.map(path => { const ancestry = []; do { ancestry.unshift(path); } while ((path = path.parentPath) && path !== this); if (ancestry.length < minDepth) { minDepth = ancestry.length; } return ancestry; }); const first = ancestries[0]; depthLoop: for (let i = 0; i < minDepth; i++) { const shouldMatch = first[i]; for (const ancestry of ancestries) { if (ancestry[i] !== shouldMatch) { break depthLoop; } } lastCommonIndex = i; lastCommon = shouldMatch; } if (lastCommon) { if (filter) { return filter(lastCommon, lastCommonIndex, ancestries); } else { return lastCommon; } } else { throw new Error("Couldn't find intersection"); } } function getAncestry() { let path = this; const paths = []; do { paths.push(path); } while (path = path.parentPath); return paths; } function isAncestor(maybeDescendant) { return maybeDescendant.isDescendant(this); } function isDescendant(maybeAncestor) { return !!this.findParent(parent => parent === maybeAncestor); } function inType() { let path = this; while (path) { for (const type of arguments) { if (path.node.type === type) return true; } path = path.parentPath; } return false; } },{"./index":86,"@babel/types":142}],81:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.shareCommentsWithSiblings = shareCommentsWithSiblings; exports.addComment = addComment; exports.addComments = addComments; function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function shareCommentsWithSiblings() { if (typeof this.key === "string") return; const node = this.node; if (!node) return; const trailing = node.trailingComments; const leading = node.leadingComments; if (!trailing && !leading) return; const prev = this.getSibling(this.key - 1); const next = this.getSibling(this.key + 1); const hasPrev = Boolean(prev.node); const hasNext = Boolean(next.node); if (hasPrev && hasNext) {} else if (hasPrev) { prev.addComments("trailing", trailing); } else if (hasNext) { next.addComments("leading", leading); } } function addComment(type, content, line) { t().addComment(this.node, type, content, line); } function addComments(type, comments) { t().addComments(this.node, type, comments); } },{"@babel/types":142}],82:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.call = call; exports._call = _call; exports.isBlacklisted = isBlacklisted; exports.visit = visit; exports.skip = skip; exports.skipKey = skipKey; exports.stop = stop; exports.setScope = setScope; exports.setContext = setContext; exports.resync = resync; exports._resyncParent = _resyncParent; exports._resyncKey = _resyncKey; exports._resyncList = _resyncList; exports._resyncRemoved = _resyncRemoved; exports.popContext = popContext; exports.pushContext = pushContext; exports.setup = setup; exports.setKey = setKey; exports.requeue = requeue; exports._getQueueContexts = _getQueueContexts; var _index = _interopRequireDefault(require("../index")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function call(key) { const opts = this.opts; this.debug(key); if (this.node) { if (this._call(opts[key])) return true; } if (this.node) { return this._call(opts[this.node.type] && opts[this.node.type][key]); } return false; } function _call(fns) { if (!fns) return false; for (const fn of fns) { if (!fn) continue; const node = this.node; if (!node) return true; const ret = fn.call(this.state, this, this.state); if (ret && typeof ret === "object" && typeof ret.then === "function") { throw new Error(`You appear to be using a plugin with an async traversal visitor, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, you may need to upgrade ` + `your @babel/core version.`); } if (ret) { throw new Error(`Unexpected return value from visitor method ${fn}`); } if (this.node !== node) return true; if (this.shouldStop || this.shouldSkip || this.removed) return true; } return false; } function isBlacklisted() { const blacklist = this.opts.blacklist; return blacklist && blacklist.indexOf(this.node.type) > -1; } function visit() { if (!this.node) { return false; } if (this.isBlacklisted()) { return false; } if (this.opts.shouldSkip && this.opts.shouldSkip(this)) { return false; } if (this.call("enter") || this.shouldSkip) { this.debug("Skip..."); return this.shouldStop; } this.debug("Recursing into..."); _index.default.node(this.node, this.opts, this.scope, this.state, this, this.skipKeys); this.call("exit"); return this.shouldStop; } function skip() { this.shouldSkip = true; } function skipKey(key) { this.skipKeys[key] = true; } function stop() { this.shouldStop = true; this.shouldSkip = true; } function setScope() { if (this.opts && this.opts.noScope) return; let path = this.parentPath; let target; while (path && !target) { if (path.opts && path.opts.noScope) return; target = path.scope; path = path.parentPath; } this.scope = this.getScope(target); if (this.scope) this.scope.init(); } function setContext(context) { this.shouldSkip = false; this.shouldStop = false; this.removed = false; this.skipKeys = {}; if (context) { this.context = context; this.state = context.state; this.opts = context.opts; } this.setScope(); return this; } function resync() { if (this.removed) return; this._resyncParent(); this._resyncList(); this._resyncKey(); } function _resyncParent() { if (this.parentPath) { this.parent = this.parentPath.node; } } function _resyncKey() { if (!this.container) return; if (this.node === this.container[this.key]) return; if (Array.isArray(this.container)) { for (let i = 0; i < this.container.length; i++) { if (this.container[i] === this.node) { return this.setKey(i); } } } else { for (const key of Object.keys(this.container)) { if (this.container[key] === this.node) { return this.setKey(key); } } } this.key = null; } function _resyncList() { if (!this.parent || !this.inList) return; const newContainer = this.parent[this.listKey]; if (this.container === newContainer) return; this.container = newContainer || null; } function _resyncRemoved() { if (this.key == null || !this.container || this.container[this.key] !== this.node) { this._markRemoved(); } } function popContext() { this.contexts.pop(); if (this.contexts.length > 0) { this.setContext(this.contexts[this.contexts.length - 1]); } else { this.setContext(undefined); } } function pushContext(context) { this.contexts.push(context); this.setContext(context); } function setup(parentPath, container, listKey, key) { this.inList = !!listKey; this.listKey = listKey; this.parentKey = listKey || key; this.container = container; this.parentPath = parentPath || this.parentPath; this.setKey(key); } function setKey(key) { this.key = key; this.node = this.container[this.key]; this.type = this.node && this.node.type; } function requeue(pathToQueue = this) { if (pathToQueue.removed) return; const contexts = this.contexts; for (const context of contexts) { context.maybeQueue(pathToQueue); } } function _getQueueContexts() { let path = this; let contexts = this.contexts; while (!contexts.length) { path = path.parentPath; if (!path) break; contexts = path.contexts; } return contexts; } },{"../index":79}],83:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.toComputedKey = toComputedKey; exports.ensureBlock = ensureBlock; exports.arrowFunctionToShadowed = arrowFunctionToShadowed; exports.unwrapFunctionEnvironment = unwrapFunctionEnvironment; exports.arrowFunctionToExpression = arrowFunctionToExpression; function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } function _helperFunctionName() { const data = _interopRequireDefault(require("@babel/helper-function-name")); _helperFunctionName = function () { return data; }; return data; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function toComputedKey() { const node = this.node; let key; if (this.isMemberExpression()) { key = node.property; } else if (this.isProperty() || this.isMethod()) { key = node.key; } else { throw new ReferenceError("todo"); } if (!node.computed) { if (t().isIdentifier(key)) key = t().stringLiteral(key.name); } return key; } function ensureBlock() { const body = this.get("body"); const bodyNode = body.node; if (Array.isArray(body)) { throw new Error("Can't convert array path to a block statement"); } if (!bodyNode) { throw new Error("Can't convert node without a body"); } if (body.isBlockStatement()) { return bodyNode; } const statements = []; let stringPath = "body"; let key; let listKey; if (body.isStatement()) { listKey = "body"; key = 0; statements.push(body.node); } else { stringPath += ".body.0"; if (this.isFunction()) { key = "argument"; statements.push(t().returnStatement(body.node)); } else { key = "expression"; statements.push(t().expressionStatement(body.node)); } } this.node.body = t().blockStatement(statements); const parentPath = this.get(stringPath); body.setup(parentPath, listKey ? parentPath.node[listKey] : parentPath.node, listKey, key); return this.node; } function arrowFunctionToShadowed() { if (!this.isArrowFunctionExpression()) return; this.arrowFunctionToExpression(); } function unwrapFunctionEnvironment() { if (!this.isArrowFunctionExpression() && !this.isFunctionExpression() && !this.isFunctionDeclaration()) { throw this.buildCodeFrameError("Can only unwrap the environment of a function."); } hoistFunctionEnvironment(this); } function arrowFunctionToExpression({ allowInsertArrow = true, specCompliant = false } = {}) { if (!this.isArrowFunctionExpression()) { throw this.buildCodeFrameError("Cannot convert non-arrow function to a function expression."); } const thisBinding = hoistFunctionEnvironment(this, specCompliant, allowInsertArrow); this.ensureBlock(); this.node.type = "FunctionExpression"; if (specCompliant) { const checkBinding = thisBinding ? null : this.parentPath.scope.generateUidIdentifier("arrowCheckId"); if (checkBinding) { this.parentPath.scope.push({ id: checkBinding, init: t().objectExpression([]) }); } this.get("body").unshiftContainer("body", t().expressionStatement(t().callExpression(this.hub.addHelper("newArrowCheck"), [t().thisExpression(), checkBinding ? t().identifier(checkBinding.name) : t().identifier(thisBinding)]))); this.replaceWith(t().callExpression(t().memberExpression((0, _helperFunctionName().default)(this, true) || this.node, t().identifier("bind")), [checkBinding ? t().identifier(checkBinding.name) : t().thisExpression()])); } } function hoistFunctionEnvironment(fnPath, specCompliant = false, allowInsertArrow = true) { const thisEnvFn = fnPath.findParent(p => { return p.isFunction() && !p.isArrowFunctionExpression() || p.isProgram() || p.isClassProperty({ static: false }); }); const inConstructor = thisEnvFn && thisEnvFn.node.kind === "constructor"; if (thisEnvFn.isClassProperty()) { throw fnPath.buildCodeFrameError("Unable to transform arrow inside class property"); } const { thisPaths, argumentsPaths, newTargetPaths, superProps, superCalls } = getScopeInformation(fnPath); if (inConstructor && superCalls.length > 0) { if (!allowInsertArrow) { throw superCalls[0].buildCodeFrameError("Unable to handle nested super() usage in arrow"); } const allSuperCalls = []; thisEnvFn.traverse({ Function(child) { if (child.isArrowFunctionExpression()) return; child.skip(); }, ClassProperty(child) { child.skip(); }, CallExpression(child) { if (!child.get("callee").isSuper()) return; allSuperCalls.push(child); } }); const superBinding = getSuperBinding(thisEnvFn); allSuperCalls.forEach(superCall => { const callee = t().identifier(superBinding); callee.loc = superCall.node.callee.loc; superCall.get("callee").replaceWith(callee); }); } let thisBinding; if (thisPaths.length > 0 || specCompliant) { thisBinding = getThisBinding(thisEnvFn, inConstructor); if (!specCompliant || inConstructor && hasSuperClass(thisEnvFn)) { thisPaths.forEach(thisChild => { const thisRef = thisChild.isJSX() ? t().jsxIdentifier(thisBinding) : t().identifier(thisBinding); thisRef.loc = thisChild.node.loc; thisChild.replaceWith(thisRef); }); if (specCompliant) thisBinding = null; } } if (argumentsPaths.length > 0) { const argumentsBinding = getBinding(thisEnvFn, "arguments", () => t().identifier("arguments")); argumentsPaths.forEach(argumentsChild => { const argsRef = t().identifier(argumentsBinding); argsRef.loc = argumentsChild.node.loc; argumentsChild.replaceWith(argsRef); }); } if (newTargetPaths.length > 0) { const newTargetBinding = getBinding(thisEnvFn, "newtarget", () => t().metaProperty(t().identifier("new"), t().identifier("target"))); newTargetPaths.forEach(targetChild => { const targetRef = t().identifier(newTargetBinding); targetRef.loc = targetChild.node.loc; targetChild.replaceWith(targetRef); }); } if (superProps.length > 0) { if (!allowInsertArrow) { throw superProps[0].buildCodeFrameError("Unable to handle nested super.prop usage"); } const flatSuperProps = superProps.reduce((acc, superProp) => acc.concat(standardizeSuperProperty(superProp)), []); flatSuperProps.forEach(superProp => { const key = superProp.node.computed ? "" : superProp.get("property").node.name; if (superProp.parentPath.isCallExpression({ callee: superProp.node })) { const superBinding = getSuperPropCallBinding(thisEnvFn, key); if (superProp.node.computed) { const prop = superProp.get("property").node; superProp.replaceWith(t().identifier(superBinding)); superProp.parentPath.node.arguments.unshift(prop); } else { superProp.replaceWith(t().identifier(superBinding)); } } else { const isAssignment = superProp.parentPath.isAssignmentExpression({ left: superProp.node }); const superBinding = getSuperPropBinding(thisEnvFn, isAssignment, key); const args = []; if (superProp.node.computed) { args.push(superProp.get("property").node); } if (isAssignment) { const value = superProp.parentPath.node.right; args.push(value); superProp.parentPath.replaceWith(t().callExpression(t().identifier(superBinding), args)); } else { superProp.replaceWith(t().callExpression(t().identifier(superBinding), args)); } } }); } return thisBinding; } function standardizeSuperProperty(superProp) { if (superProp.parentPath.isAssignmentExpression() && superProp.parentPath.node.operator !== "=") { const assignmentPath = superProp.parentPath; const op = assignmentPath.node.operator.slice(0, -1); const value = assignmentPath.node.right; assignmentPath.node.operator = "="; if (superProp.node.computed) { const tmp = superProp.scope.generateDeclaredUidIdentifier("tmp"); assignmentPath.get("left").replaceWith(t().memberExpression(superProp.node.object, t().assignmentExpression("=", tmp, superProp.node.property), true)); assignmentPath.get("right").replaceWith(t().binaryExpression(op, t().memberExpression(superProp.node.object, t().identifier(tmp.name), true), value)); } else { assignmentPath.get("left").replaceWith(t().memberExpression(superProp.node.object, superProp.node.property)); assignmentPath.get("right").replaceWith(t().binaryExpression(op, t().memberExpression(superProp.node.object, t().identifier(superProp.node.property.name)), value)); } return [assignmentPath.get("left"), assignmentPath.get("right").get("left")]; } else if (superProp.parentPath.isUpdateExpression()) { const updateExpr = superProp.parentPath; const tmp = superProp.scope.generateDeclaredUidIdentifier("tmp"); const computedKey = superProp.node.computed ? superProp.scope.generateDeclaredUidIdentifier("prop") : null; const parts = [t().assignmentExpression("=", tmp, t().memberExpression(superProp.node.object, computedKey ? t().assignmentExpression("=", computedKey, superProp.node.property) : superProp.node.property, superProp.node.computed)), t().assignmentExpression("=", t().memberExpression(superProp.node.object, computedKey ? t().identifier(computedKey.name) : superProp.node.property, superProp.node.computed), t().binaryExpression("+", t().identifier(tmp.name), t().numericLiteral(1)))]; if (!superProp.parentPath.node.prefix) { parts.push(t().identifier(tmp.name)); } updateExpr.replaceWith(t().sequenceExpression(parts)); const left = updateExpr.get("expressions.0.right"); const right = updateExpr.get("expressions.1.left"); return [left, right]; } return [superProp]; } function hasSuperClass(thisEnvFn) { return thisEnvFn.isClassMethod() && !!thisEnvFn.parentPath.parentPath.node.superClass; } function getThisBinding(thisEnvFn, inConstructor) { return getBinding(thisEnvFn, "this", thisBinding => { if (!inConstructor || !hasSuperClass(thisEnvFn)) return t().thisExpression(); const supers = new WeakSet(); thisEnvFn.traverse({ Function(child) { if (child.isArrowFunctionExpression()) return; child.skip(); }, ClassProperty(child) { child.skip(); }, CallExpression(child) { if (!child.get("callee").isSuper()) return; if (supers.has(child.node)) return; supers.add(child.node); child.replaceWithMultiple([child.node, t().assignmentExpression("=", t().identifier(thisBinding), t().identifier("this"))]); } }); }); } function getSuperBinding(thisEnvFn) { return getBinding(thisEnvFn, "supercall", () => { const argsBinding = thisEnvFn.scope.generateUidIdentifier("args"); return t().arrowFunctionExpression([t().restElement(argsBinding)], t().callExpression(t().super(), [t().spreadElement(t().identifier(argsBinding.name))])); }); } function getSuperPropCallBinding(thisEnvFn, propName) { return getBinding(thisEnvFn, `superprop_call:${propName || ""}`, () => { const argsBinding = thisEnvFn.scope.generateUidIdentifier("args"); const argsList = [t().restElement(argsBinding)]; let fnBody; if (propName) { fnBody = t().callExpression(t().memberExpression(t().super(), t().identifier(propName)), [t().spreadElement(t().identifier(argsBinding.name))]); } else { const method = thisEnvFn.scope.generateUidIdentifier("prop"); argsList.unshift(method); fnBody = t().callExpression(t().memberExpression(t().super(), t().identifier(method.name), true), [t().spreadElement(t().identifier(argsBinding.name))]); } return t().arrowFunctionExpression(argsList, fnBody); }); } function getSuperPropBinding(thisEnvFn, isAssignment, propName) { const op = isAssignment ? "set" : "get"; return getBinding(thisEnvFn, `superprop_${op}:${propName || ""}`, () => { const argsList = []; let fnBody; if (propName) { fnBody = t().memberExpression(t().super(), t().identifier(propName)); } else { const method = thisEnvFn.scope.generateUidIdentifier("prop"); argsList.unshift(method); fnBody = t().memberExpression(t().super(), t().identifier(method.name), true); } if (isAssignment) { const valueIdent = thisEnvFn.scope.generateUidIdentifier("value"); argsList.push(valueIdent); fnBody = t().assignmentExpression("=", fnBody, t().identifier(valueIdent.name)); } return t().arrowFunctionExpression(argsList, fnBody); }); } function getBinding(thisEnvFn, key, init) { const cacheKey = "binding:" + key; let data = thisEnvFn.getData(cacheKey); if (!data) { const id = thisEnvFn.scope.generateUidIdentifier(key); data = id.name; thisEnvFn.setData(cacheKey, data); thisEnvFn.scope.push({ id: id, init: init(data) }); } return data; } function getScopeInformation(fnPath) { const thisPaths = []; const argumentsPaths = []; const newTargetPaths = []; const superProps = []; const superCalls = []; fnPath.traverse({ ClassProperty(child) { child.skip(); }, Function(child) { if (child.isArrowFunctionExpression()) return; child.skip(); }, ThisExpression(child) { thisPaths.push(child); }, JSXIdentifier(child) { if (child.node.name !== "this") return; if (!child.parentPath.isJSXMemberExpression({ object: child.node }) && !child.parentPath.isJSXOpeningElement({ name: child.node })) { return; } thisPaths.push(child); }, CallExpression(child) { if (child.get("callee").isSuper()) superCalls.push(child); }, MemberExpression(child) { if (child.get("object").isSuper()) superProps.push(child); }, ReferencedIdentifier(child) { if (child.node.name !== "arguments") return; argumentsPaths.push(child); }, MetaProperty(child) { if (!child.get("meta").isIdentifier({ name: "new" })) return; if (!child.get("property").isIdentifier({ name: "target" })) return; newTargetPaths.push(child); } }); return { thisPaths, argumentsPaths, newTargetPaths, superProps, superCalls }; } },{"@babel/helper-function-name":61,"@babel/types":142}],84:[function(require,module,exports){ (function (global){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.evaluateTruthy = evaluateTruthy; exports.evaluate = evaluate; const VALID_CALLEES = ["String", "Number", "Math"]; const INVALID_METHODS = ["random"]; function evaluateTruthy() { const res = this.evaluate(); if (res.confident) return !!res.value; } function deopt(path, state) { if (!state.confident) return; state.deoptPath = path; state.confident = false; } function evaluateCached(path, state) { const { node } = path; const { seen } = state; if (seen.has(node)) { const existing = seen.get(node); if (existing.resolved) { return existing.value; } else { deopt(path, state); return; } } else { const item = { resolved: false }; seen.set(node, item); const val = _evaluate(path, state); if (state.confident) { item.resolved = true; item.value = val; } return val; } } function _evaluate(path, state) { if (!state.confident) return; const { node } = path; if (path.isSequenceExpression()) { const exprs = path.get("expressions"); return evaluateCached(exprs[exprs.length - 1], state); } if (path.isStringLiteral() || path.isNumericLiteral() || path.isBooleanLiteral()) { return node.value; } if (path.isNullLiteral()) { return null; } if (path.isTemplateLiteral()) { return evaluateQuasis(path, node.quasis, state); } if (path.isTaggedTemplateExpression() && path.get("tag").isMemberExpression()) { const object = path.get("tag.object"); const { node: { name } } = object; const property = path.get("tag.property"); if (object.isIdentifier() && name === "String" && !path.scope.getBinding(name, true) && property.isIdentifier && property.node.name === "raw") { return evaluateQuasis(path, node.quasi.quasis, state, true); } } if (path.isConditionalExpression()) { const testResult = evaluateCached(path.get("test"), state); if (!state.confident) return; if (testResult) { return evaluateCached(path.get("consequent"), state); } else { return evaluateCached(path.get("alternate"), state); } } if (path.isExpressionWrapper()) { return evaluateCached(path.get("expression"), state); } if (path.isMemberExpression() && !path.parentPath.isCallExpression({ callee: node })) { const property = path.get("property"); const object = path.get("object"); if (object.isLiteral() && property.isIdentifier()) { const value = object.node.value; const type = typeof value; if (type === "number" || type === "string") { return value[property.node.name]; } } } if (path.isReferencedIdentifier()) { const binding = path.scope.getBinding(node.name); if (binding && binding.constantViolations.length > 0) { return deopt(binding.path, state); } if (binding && path.node.start < binding.path.node.end) { return deopt(binding.path, state); } if (binding && binding.hasValue) { return binding.value; } else { if (node.name === "undefined") { return binding ? deopt(binding.path, state) : undefined; } else if (node.name === "Infinity") { return binding ? deopt(binding.path, state) : Infinity; } else if (node.name === "NaN") { return binding ? deopt(binding.path, state) : NaN; } const resolved = path.resolve(); if (resolved === path) { return deopt(path, state); } else { return evaluateCached(resolved, state); } } } if (path.isUnaryExpression({ prefix: true })) { if (node.operator === "void") { return undefined; } const argument = path.get("argument"); if (node.operator === "typeof" && (argument.isFunction() || argument.isClass())) { return "function"; } const arg = evaluateCached(argument, state); if (!state.confident) return; switch (node.operator) { case "!": return !arg; case "+": return +arg; case "-": return -arg; case "~": return ~arg; case "typeof": return typeof arg; } } if (path.isArrayExpression()) { const arr = []; const elems = path.get("elements"); for (const elem of elems) { const elemValue = elem.evaluate(); if (elemValue.confident) { arr.push(elemValue.value); } else { return deopt(elem, state); } } return arr; } if (path.isObjectExpression()) { const obj = {}; const props = path.get("properties"); for (const prop of props) { if (prop.isObjectMethod() || prop.isSpreadElement()) { return deopt(prop, state); } const keyPath = prop.get("key"); let key = keyPath; if (prop.node.computed) { key = key.evaluate(); if (!key.confident) { return deopt(keyPath, state); } key = key.value; } else if (key.isIdentifier()) { key = key.node.name; } else { key = key.node.value; } const valuePath = prop.get("value"); let value = valuePath.evaluate(); if (!value.confident) { return deopt(valuePath, state); } value = value.value; obj[key] = value; } return obj; } if (path.isLogicalExpression()) { const wasConfident = state.confident; const left = evaluateCached(path.get("left"), state); const leftConfident = state.confident; state.confident = wasConfident; const right = evaluateCached(path.get("right"), state); const rightConfident = state.confident; switch (node.operator) { case "||": state.confident = leftConfident && (!!left || rightConfident); if (!state.confident) return; return left || right; case "&&": state.confident = leftConfident && (!left || rightConfident); if (!state.confident) return; return left && right; } } if (path.isBinaryExpression()) { const left = evaluateCached(path.get("left"), state); if (!state.confident) return; const right = evaluateCached(path.get("right"), state); if (!state.confident) return; switch (node.operator) { case "-": return left - right; case "+": return left + right; case "/": return left / right; case "*": return left * right; case "%": return left % right; case "**": return Math.pow(left, right); case "<": return left < right; case ">": return left > right; case "<=": return left <= right; case ">=": return left >= right; case "==": return left == right; case "!=": return left != right; case "===": return left === right; case "!==": return left !== right; case "|": return left | right; case "&": return left & right; case "^": return left ^ right; case "<<": return left << right; case ">>": return left >> right; case ">>>": return left >>> right; } } if (path.isCallExpression()) { const callee = path.get("callee"); let context; let func; if (callee.isIdentifier() && !path.scope.getBinding(callee.node.name, true) && VALID_CALLEES.indexOf(callee.node.name) >= 0) { func = global[node.callee.name]; } if (callee.isMemberExpression()) { const object = callee.get("object"); const property = callee.get("property"); if (object.isIdentifier() && property.isIdentifier() && VALID_CALLEES.indexOf(object.node.name) >= 0 && INVALID_METHODS.indexOf(property.node.name) < 0) { context = global[object.node.name]; func = context[property.node.name]; } if (object.isLiteral() && property.isIdentifier()) { const type = typeof object.node.value; if (type === "string" || type === "number") { context = object.node.value; func = context[property.node.name]; } } } if (func) { const args = path.get("arguments").map(arg => evaluateCached(arg, state)); if (!state.confident) return; return func.apply(context, args); } } deopt(path, state); } function evaluateQuasis(path, quasis, state, raw = false) { let str = ""; let i = 0; const exprs = path.get("expressions"); for (const elem of quasis) { if (!state.confident) break; str += raw ? elem.value.raw : elem.value.cooked; const expr = exprs[i++]; if (expr) str += String(evaluateCached(expr, state)); } if (!state.confident) return; return str; } function evaluate() { const state = { confident: true, deoptPath: null, seen: new Map() }; let value = evaluateCached(this, state); if (!state.confident) value = undefined; return { confident: state.confident, deopt: state.deoptPath, value: value }; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],85:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getOpposite = getOpposite; exports.getCompletionRecords = getCompletionRecords; exports.getSibling = getSibling; exports.getPrevSibling = getPrevSibling; exports.getNextSibling = getNextSibling; exports.getAllNextSiblings = getAllNextSiblings; exports.getAllPrevSiblings = getAllPrevSiblings; exports.get = get; exports._getKey = _getKey; exports._getPattern = _getPattern; exports.getBindingIdentifiers = getBindingIdentifiers; exports.getOuterBindingIdentifiers = getOuterBindingIdentifiers; exports.getBindingIdentifierPaths = getBindingIdentifierPaths; exports.getOuterBindingIdentifierPaths = getOuterBindingIdentifierPaths; var _index = _interopRequireDefault(require("./index")); function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function getOpposite() { if (this.key === "left") { return this.getSibling("right"); } else if (this.key === "right") { return this.getSibling("left"); } } function addCompletionRecords(path, paths) { if (path) return paths.concat(path.getCompletionRecords()); return paths; } function getCompletionRecords() { let paths = []; if (this.isIfStatement()) { paths = addCompletionRecords(this.get("consequent"), paths); paths = addCompletionRecords(this.get("alternate"), paths); } else if (this.isDoExpression() || this.isFor() || this.isWhile()) { paths = addCompletionRecords(this.get("body"), paths); } else if (this.isProgram() || this.isBlockStatement()) { paths = addCompletionRecords(this.get("body").pop(), paths); } else if (this.isFunction()) { return this.get("body").getCompletionRecords(); } else if (this.isTryStatement()) { paths = addCompletionRecords(this.get("block"), paths); paths = addCompletionRecords(this.get("handler"), paths); paths = addCompletionRecords(this.get("finalizer"), paths); } else if (this.isCatchClause()) { paths = addCompletionRecords(this.get("body"), paths); } else { paths.push(this); } return paths; } function getSibling(key) { return _index.default.get({ parentPath: this.parentPath, parent: this.parent, container: this.container, listKey: this.listKey, key: key }); } function getPrevSibling() { return this.getSibling(this.key - 1); } function getNextSibling() { return this.getSibling(this.key + 1); } function getAllNextSiblings() { let _key = this.key; let sibling = this.getSibling(++_key); const siblings = []; while (sibling.node) { siblings.push(sibling); sibling = this.getSibling(++_key); } return siblings; } function getAllPrevSiblings() { let _key = this.key; let sibling = this.getSibling(--_key); const siblings = []; while (sibling.node) { siblings.push(sibling); sibling = this.getSibling(--_key); } return siblings; } function get(key, context) { if (context === true) context = this.context; const parts = key.split("."); if (parts.length === 1) { return this._getKey(key, context); } else { return this._getPattern(parts, context); } } function _getKey(key, context) { const node = this.node; const container = node[key]; if (Array.isArray(container)) { return container.map((_, i) => { return _index.default.get({ listKey: key, parentPath: this, parent: node, container: container, key: i }).setContext(context); }); } else { return _index.default.get({ parentPath: this, parent: node, container: node, key: key }).setContext(context); } } function _getPattern(parts, context) { let path = this; for (const part of parts) { if (part === ".") { path = path.parentPath; } else { if (Array.isArray(path)) { path = path[part]; } else { path = path.get(part, context); } } } return path; } function getBindingIdentifiers(duplicates) { return t().getBindingIdentifiers(this.node, duplicates); } function getOuterBindingIdentifiers(duplicates) { return t().getOuterBindingIdentifiers(this.node, duplicates); } function getBindingIdentifierPaths(duplicates = false, outerOnly = false) { const path = this; let search = [].concat(path); const ids = Object.create(null); while (search.length) { const id = search.shift(); if (!id) continue; if (!id.node) continue; const keys = t().getBindingIdentifiers.keys[id.node.type]; if (id.isIdentifier()) { if (duplicates) { const _ids = ids[id.node.name] = ids[id.node.name] || []; _ids.push(id); } else { ids[id.node.name] = id; } continue; } if (id.isExportDeclaration()) { const declaration = id.get("declaration"); if (declaration.isDeclaration()) { search.push(declaration); } continue; } if (outerOnly) { if (id.isFunctionDeclaration()) { search.push(id.get("id")); continue; } if (id.isFunctionExpression()) { continue; } } if (keys) { for (let i = 0; i < keys.length; i++) { const key = keys[i]; const child = id.get(key); if (Array.isArray(child) || child.node) { search = search.concat(child); } } } } return ids; } function getOuterBindingIdentifierPaths(duplicates) { return this.getBindingIdentifierPaths(duplicates, true); } },{"./index":86,"@babel/types":142}],86:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var virtualTypes = _interopRequireWildcard(require("./lib/virtual-types")); function _debug() { const data = _interopRequireDefault(require("debug")); _debug = function () { return data; }; return data; } var _index = _interopRequireDefault(require("../index")); var _scope = _interopRequireDefault(require("../scope")); function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } var _cache = require("../cache"); function _generator() { const data = _interopRequireDefault(require("@babel/generator")); _generator = function () { return data; }; return data; } var NodePath_ancestry = _interopRequireWildcard(require("./ancestry")); var NodePath_inference = _interopRequireWildcard(require("./inference")); var NodePath_replacement = _interopRequireWildcard(require("./replacement")); var NodePath_evaluation = _interopRequireWildcard(require("./evaluation")); var NodePath_conversion = _interopRequireWildcard(require("./conversion")); var NodePath_introspection = _interopRequireWildcard(require("./introspection")); var NodePath_context = _interopRequireWildcard(require("./context")); var NodePath_removal = _interopRequireWildcard(require("./removal")); var NodePath_modification = _interopRequireWildcard(require("./modification")); var NodePath_family = _interopRequireWildcard(require("./family")); var NodePath_comments = _interopRequireWildcard(require("./comments")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } const debug = (0, _debug().default)("babel"); class NodePath { constructor(hub, parent) { this.parent = parent; this.hub = hub; this.contexts = []; this.data = Object.create(null); this.shouldSkip = false; this.shouldStop = false; this.removed = false; this.state = null; this.opts = null; this.skipKeys = null; this.parentPath = null; this.context = null; this.container = null; this.listKey = null; this.inList = false; this.parentKey = null; this.key = null; this.node = null; this.scope = null; this.type = null; this.typeAnnotation = null; } static get({ hub, parentPath, parent, container, listKey, key }) { if (!hub && parentPath) { hub = parentPath.hub; } if (!parent) { throw new Error("To get a node path the parent needs to exist"); } const targetNode = container[key]; const paths = _cache.path.get(parent) || []; if (!_cache.path.has(parent)) { _cache.path.set(parent, paths); } let path; for (let i = 0; i < paths.length; i++) { const pathCheck = paths[i]; if (pathCheck.node === targetNode) { path = pathCheck; break; } } if (!path) { path = new NodePath(hub, parent); paths.push(path); } path.setup(parentPath, container, listKey, key); return path; } getScope(scope) { return this.isScope() ? new _scope.default(this) : scope; } setData(key, val) { return this.data[key] = val; } getData(key, def) { let val = this.data[key]; if (val === undefined && def !== undefined) val = this.data[key] = def; return val; } buildCodeFrameError(msg, Error = SyntaxError) { return this.hub.buildError(this.node, msg, Error); } traverse(visitor, state) { (0, _index.default)(this.node, visitor, this.scope, state, this); } set(key, node) { t().validate(this.node, key, node); this.node[key] = node; } getPathLocation() { const parts = []; let path = this; do { let key = path.key; if (path.inList) key = `${path.listKey}[${key}]`; parts.unshift(key); } while (path = path.parentPath); return parts.join("."); } debug(message) { if (!debug.enabled) return; debug(`${this.getPathLocation()} ${this.type}: ${message}`); } toString() { return (0, _generator().default)(this.node).code; } } exports.default = NodePath; Object.assign(NodePath.prototype, NodePath_ancestry, NodePath_inference, NodePath_replacement, NodePath_evaluation, NodePath_conversion, NodePath_introspection, NodePath_context, NodePath_removal, NodePath_modification, NodePath_family, NodePath_comments); for (const type of t().TYPES) { const typeKey = `is${type}`; const fn = t()[typeKey]; NodePath.prototype[typeKey] = function (opts) { return fn(this.node, opts); }; NodePath.prototype[`assert${type}`] = function (opts) { if (!fn(this.node, opts)) { throw new TypeError(`Expected node path of type ${type}`); } }; } for (const type of Object.keys(virtualTypes)) { if (type[0] === "_") continue; if (t().TYPES.indexOf(type) < 0) t().TYPES.push(type); const virtualType = virtualTypes[type]; NodePath.prototype[`is${type}`] = function (opts) { return virtualType.checkPath(this, opts); }; } },{"../cache":76,"../index":79,"../scope":98,"./ancestry":80,"./comments":81,"./context":82,"./conversion":83,"./evaluation":84,"./family":85,"./inference":87,"./introspection":90,"./lib/virtual-types":93,"./modification":94,"./removal":95,"./replacement":96,"@babel/generator":55,"@babel/types":142,"debug":191}],87:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getTypeAnnotation = getTypeAnnotation; exports._getTypeAnnotation = _getTypeAnnotation; exports.isBaseType = isBaseType; exports.couldBeBaseType = couldBeBaseType; exports.baseTypeStrictlyMatches = baseTypeStrictlyMatches; exports.isGenericType = isGenericType; var inferers = _interopRequireWildcard(require("./inferers")); function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function getTypeAnnotation() { if (this.typeAnnotation) return this.typeAnnotation; let type = this._getTypeAnnotation() || t().anyTypeAnnotation(); if (t().isTypeAnnotation(type)) type = type.typeAnnotation; return this.typeAnnotation = type; } function _getTypeAnnotation() { const node = this.node; if (!node) { if (this.key === "init" && this.parentPath.isVariableDeclarator()) { const declar = this.parentPath.parentPath; const declarParent = declar.parentPath; if (declar.key === "left" && declarParent.isForInStatement()) { return t().stringTypeAnnotation(); } if (declar.key === "left" && declarParent.isForOfStatement()) { return t().anyTypeAnnotation(); } return t().voidTypeAnnotation(); } else { return; } } if (node.typeAnnotation) { return node.typeAnnotation; } let inferer = inferers[node.type]; if (inferer) { return inferer.call(this, node); } inferer = inferers[this.parentPath.type]; if (inferer && inferer.validParent) { return this.parentPath.getTypeAnnotation(); } } function isBaseType(baseName, soft) { return _isBaseType(baseName, this.getTypeAnnotation(), soft); } function _isBaseType(baseName, type, soft) { if (baseName === "string") { return t().isStringTypeAnnotation(type); } else if (baseName === "number") { return t().isNumberTypeAnnotation(type); } else if (baseName === "boolean") { return t().isBooleanTypeAnnotation(type); } else if (baseName === "any") { return t().isAnyTypeAnnotation(type); } else if (baseName === "mixed") { return t().isMixedTypeAnnotation(type); } else if (baseName === "empty") { return t().isEmptyTypeAnnotation(type); } else if (baseName === "void") { return t().isVoidTypeAnnotation(type); } else { if (soft) { return false; } else { throw new Error(`Unknown base type ${baseName}`); } } } function couldBeBaseType(name) { const type = this.getTypeAnnotation(); if (t().isAnyTypeAnnotation(type)) return true; if (t().isUnionTypeAnnotation(type)) { for (const type2 of type.types) { if (t().isAnyTypeAnnotation(type2) || _isBaseType(name, type2, true)) { return true; } } return false; } else { return _isBaseType(name, type, true); } } function baseTypeStrictlyMatches(right) { const left = this.getTypeAnnotation(); right = right.getTypeAnnotation(); if (!t().isAnyTypeAnnotation(left) && t().isFlowBaseAnnotation(left)) { return right.type === left.type; } } function isGenericType(genericName) { const type = this.getTypeAnnotation(); return t().isGenericTypeAnnotation(type) && t().isIdentifier(type.id, { name: genericName }); } },{"./inferers":89,"@babel/types":142}],88:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = _default; function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function _default(node) { if (!this.isReferenced()) return; const binding = this.scope.getBinding(node.name); if (binding) { if (binding.identifier.typeAnnotation) { return binding.identifier.typeAnnotation; } else { return getTypeAnnotationBindingConstantViolations(binding, this, node.name); } } if (node.name === "undefined") { return t().voidTypeAnnotation(); } else if (node.name === "NaN" || node.name === "Infinity") { return t().numberTypeAnnotation(); } else if (node.name === "arguments") {} } function getTypeAnnotationBindingConstantViolations(binding, path, name) { const types = []; const functionConstantViolations = []; let constantViolations = getConstantViolationsBefore(binding, path, functionConstantViolations); const testType = getConditionalAnnotation(binding, path, name); if (testType) { const testConstantViolations = getConstantViolationsBefore(binding, testType.ifStatement); constantViolations = constantViolations.filter(path => testConstantViolations.indexOf(path) < 0); types.push(testType.typeAnnotation); } if (constantViolations.length) { constantViolations = constantViolations.concat(functionConstantViolations); for (const violation of constantViolations) { types.push(violation.getTypeAnnotation()); } } if (types.length) { return t().createUnionTypeAnnotation(types); } } function getConstantViolationsBefore(binding, path, functions) { const violations = binding.constantViolations.slice(); violations.unshift(binding.path); return violations.filter(violation => { violation = violation.resolve(); const status = violation._guessExecutionStatusRelativeTo(path); if (functions && status === "function") functions.push(violation); return status === "before"; }); } function inferAnnotationFromBinaryExpression(name, path) { const operator = path.node.operator; const right = path.get("right").resolve(); const left = path.get("left").resolve(); let target; if (left.isIdentifier({ name })) { target = right; } else if (right.isIdentifier({ name })) { target = left; } if (target) { if (operator === "===") { return target.getTypeAnnotation(); } if (t().BOOLEAN_NUMBER_BINARY_OPERATORS.indexOf(operator) >= 0) { return t().numberTypeAnnotation(); } return; } if (operator !== "===" && operator !== "==") return; let typeofPath; let typePath; if (left.isUnaryExpression({ operator: "typeof" })) { typeofPath = left; typePath = right; } else if (right.isUnaryExpression({ operator: "typeof" })) { typeofPath = right; typePath = left; } if (!typeofPath) return; if (!typeofPath.get("argument").isIdentifier({ name })) return; typePath = typePath.resolve(); if (!typePath.isLiteral()) return; const typeValue = typePath.node.value; if (typeof typeValue !== "string") return; return t().createTypeAnnotationBasedOnTypeof(typeValue); } function getParentConditionalPath(binding, path, name) { let parentPath; while (parentPath = path.parentPath) { if (parentPath.isIfStatement() || parentPath.isConditionalExpression()) { if (path.key === "test") { return; } return parentPath; } if (parentPath.isFunction()) { if (parentPath.parentPath.scope.getBinding(name) !== binding) return; } path = parentPath; } } function getConditionalAnnotation(binding, path, name) { const ifStatement = getParentConditionalPath(binding, path, name); if (!ifStatement) return; const test = ifStatement.get("test"); const paths = [test]; const types = []; for (let i = 0; i < paths.length; i++) { const path = paths[i]; if (path.isLogicalExpression()) { if (path.node.operator === "&&") { paths.push(path.get("left")); paths.push(path.get("right")); } } else if (path.isBinaryExpression()) { const type = inferAnnotationFromBinaryExpression(name, path); if (type) types.push(type); } } if (types.length) { return { typeAnnotation: t().createUnionTypeAnnotation(types), ifStatement }; } return getConditionalAnnotation(ifStatement, name); } },{"@babel/types":142}],89:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.VariableDeclarator = VariableDeclarator; exports.TypeCastExpression = TypeCastExpression; exports.NewExpression = NewExpression; exports.TemplateLiteral = TemplateLiteral; exports.UnaryExpression = UnaryExpression; exports.BinaryExpression = BinaryExpression; exports.LogicalExpression = LogicalExpression; exports.ConditionalExpression = ConditionalExpression; exports.SequenceExpression = SequenceExpression; exports.ParenthesizedExpression = ParenthesizedExpression; exports.AssignmentExpression = AssignmentExpression; exports.UpdateExpression = UpdateExpression; exports.StringLiteral = StringLiteral; exports.NumericLiteral = NumericLiteral; exports.BooleanLiteral = BooleanLiteral; exports.NullLiteral = NullLiteral; exports.RegExpLiteral = RegExpLiteral; exports.ObjectExpression = ObjectExpression; exports.ArrayExpression = ArrayExpression; exports.RestElement = RestElement; exports.ClassDeclaration = exports.ClassExpression = exports.FunctionDeclaration = exports.ArrowFunctionExpression = exports.FunctionExpression = Func; exports.CallExpression = CallExpression; exports.TaggedTemplateExpression = TaggedTemplateExpression; Object.defineProperty(exports, "Identifier", { enumerable: true, get: function () { return _infererReference.default; } }); function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } var _infererReference = _interopRequireDefault(require("./inferer-reference")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function VariableDeclarator() { const id = this.get("id"); if (!id.isIdentifier()) return; const init = this.get("init"); let type = init.getTypeAnnotation(); if (type && type.type === "AnyTypeAnnotation") { if (init.isCallExpression() && init.get("callee").isIdentifier({ name: "Array" }) && !init.scope.hasBinding("Array", true)) { type = ArrayExpression(); } } return type; } function TypeCastExpression(node) { return node.typeAnnotation; } TypeCastExpression.validParent = true; function NewExpression(node) { if (this.get("callee").isIdentifier()) { return t().genericTypeAnnotation(node.callee); } } function TemplateLiteral() { return t().stringTypeAnnotation(); } function UnaryExpression(node) { const operator = node.operator; if (operator === "void") { return t().voidTypeAnnotation(); } else if (t().NUMBER_UNARY_OPERATORS.indexOf(operator) >= 0) { return t().numberTypeAnnotation(); } else if (t().STRING_UNARY_OPERATORS.indexOf(operator) >= 0) { return t().stringTypeAnnotation(); } else if (t().BOOLEAN_UNARY_OPERATORS.indexOf(operator) >= 0) { return t().booleanTypeAnnotation(); } } function BinaryExpression(node) { const operator = node.operator; if (t().NUMBER_BINARY_OPERATORS.indexOf(operator) >= 0) { return t().numberTypeAnnotation(); } else if (t().BOOLEAN_BINARY_OPERATORS.indexOf(operator) >= 0) { return t().booleanTypeAnnotation(); } else if (operator === "+") { const right = this.get("right"); const left = this.get("left"); if (left.isBaseType("number") && right.isBaseType("number")) { return t().numberTypeAnnotation(); } else if (left.isBaseType("string") || right.isBaseType("string")) { return t().stringTypeAnnotation(); } return t().unionTypeAnnotation([t().stringTypeAnnotation(), t().numberTypeAnnotation()]); } } function LogicalExpression() { return t().createUnionTypeAnnotation([this.get("left").getTypeAnnotation(), this.get("right").getTypeAnnotation()]); } function ConditionalExpression() { return t().createUnionTypeAnnotation([this.get("consequent").getTypeAnnotation(), this.get("alternate").getTypeAnnotation()]); } function SequenceExpression() { return this.get("expressions").pop().getTypeAnnotation(); } function ParenthesizedExpression() { return this.get("expression").getTypeAnnotation(); } function AssignmentExpression() { return this.get("right").getTypeAnnotation(); } function UpdateExpression(node) { const operator = node.operator; if (operator === "++" || operator === "--") { return t().numberTypeAnnotation(); } } function StringLiteral() { return t().stringTypeAnnotation(); } function NumericLiteral() { return t().numberTypeAnnotation(); } function BooleanLiteral() { return t().booleanTypeAnnotation(); } function NullLiteral() { return t().nullLiteralTypeAnnotation(); } function RegExpLiteral() { return t().genericTypeAnnotation(t().identifier("RegExp")); } function ObjectExpression() { return t().genericTypeAnnotation(t().identifier("Object")); } function ArrayExpression() { return t().genericTypeAnnotation(t().identifier("Array")); } function RestElement() { return ArrayExpression(); } RestElement.validParent = true; function Func() { return t().genericTypeAnnotation(t().identifier("Function")); } const isArrayFrom = t().buildMatchMemberExpression("Array.from"); const isObjectKeys = t().buildMatchMemberExpression("Object.keys"); const isObjectValues = t().buildMatchMemberExpression("Object.values"); const isObjectEntries = t().buildMatchMemberExpression("Object.entries"); function CallExpression() { const { callee } = this.node; if (isObjectKeys(callee)) { return t().arrayTypeAnnotation(t().stringTypeAnnotation()); } else if (isArrayFrom(callee) || isObjectValues(callee)) { return t().arrayTypeAnnotation(t().anyTypeAnnotation()); } else if (isObjectEntries(callee)) { return t().arrayTypeAnnotation(t().tupleTypeAnnotation([t().stringTypeAnnotation(), t().anyTypeAnnotation()])); } return resolveCall(this.get("callee")); } function TaggedTemplateExpression() { return resolveCall(this.get("tag")); } function resolveCall(callee) { callee = callee.resolve(); if (callee.isFunction()) { if (callee.is("async")) { if (callee.is("generator")) { return t().genericTypeAnnotation(t().identifier("AsyncIterator")); } else { return t().genericTypeAnnotation(t().identifier("Promise")); } } else { if (callee.node.returnType) { return callee.node.returnType; } else {} } } } },{"./inferer-reference":88,"@babel/types":142}],90:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.matchesPattern = matchesPattern; exports.has = has; exports.isStatic = isStatic; exports.isnt = isnt; exports.equals = equals; exports.isNodeType = isNodeType; exports.canHaveVariableDeclarationOrExpression = canHaveVariableDeclarationOrExpression; exports.canSwapBetweenExpressionAndStatement = canSwapBetweenExpressionAndStatement; exports.isCompletionRecord = isCompletionRecord; exports.isStatementOrBlock = isStatementOrBlock; exports.referencesImport = referencesImport; exports.getSource = getSource; exports.willIMaybeExecuteBefore = willIMaybeExecuteBefore; exports._guessExecutionStatusRelativeTo = _guessExecutionStatusRelativeTo; exports._guessExecutionStatusRelativeToDifferentFunctions = _guessExecutionStatusRelativeToDifferentFunctions; exports.resolve = resolve; exports._resolve = _resolve; exports.isConstantExpression = isConstantExpression; exports.isInStrictMode = isInStrictMode; exports.is = void 0; function _includes() { const data = _interopRequireDefault(require("lodash/includes")); _includes = function () { return data; }; return data; } function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function matchesPattern(pattern, allowPartial) { return t().matchesPattern(this.node, pattern, allowPartial); } function has(key) { const val = this.node && this.node[key]; if (val && Array.isArray(val)) { return !!val.length; } else { return !!val; } } function isStatic() { return this.scope.isStatic(this.node); } const is = has; exports.is = is; function isnt(key) { return !this.has(key); } function equals(key, value) { return this.node[key] === value; } function isNodeType(type) { return t().isType(this.type, type); } function canHaveVariableDeclarationOrExpression() { return (this.key === "init" || this.key === "left") && this.parentPath.isFor(); } function canSwapBetweenExpressionAndStatement(replacement) { if (this.key !== "body" || !this.parentPath.isArrowFunctionExpression()) { return false; } if (this.isExpression()) { return t().isBlockStatement(replacement); } else if (this.isBlockStatement()) { return t().isExpression(replacement); } return false; } function isCompletionRecord(allowInsideFunction) { let path = this; let first = true; do { const container = path.container; if (path.isFunction() && !first) { return !!allowInsideFunction; } first = false; if (Array.isArray(container) && path.key !== container.length - 1) { return false; } } while ((path = path.parentPath) && !path.isProgram()); return true; } function isStatementOrBlock() { if (this.parentPath.isLabeledStatement() || t().isBlockStatement(this.container)) { return false; } else { return (0, _includes().default)(t().STATEMENT_OR_BLOCK_KEYS, this.key); } } function referencesImport(moduleSource, importName) { if (!this.isReferencedIdentifier()) return false; const binding = this.scope.getBinding(this.node.name); if (!binding || binding.kind !== "module") return false; const path = binding.path; const parent = path.parentPath; if (!parent.isImportDeclaration()) return false; if (parent.node.source.value === moduleSource) { if (!importName) return true; } else { return false; } if (path.isImportDefaultSpecifier() && importName === "default") { return true; } if (path.isImportNamespaceSpecifier() && importName === "*") { return true; } if (path.isImportSpecifier() && path.node.imported.name === importName) { return true; } return false; } function getSource() { const node = this.node; if (node.end) { const code = this.hub.getCode(); if (code) return code.slice(node.start, node.end); } return ""; } function willIMaybeExecuteBefore(target) { return this._guessExecutionStatusRelativeTo(target) !== "after"; } function _guessExecutionStatusRelativeTo(target) { const targetFuncParent = target.scope.getFunctionParent() || target.scope.getProgramParent(); const selfFuncParent = this.scope.getFunctionParent() || target.scope.getProgramParent(); if (targetFuncParent.node !== selfFuncParent.node) { const status = this._guessExecutionStatusRelativeToDifferentFunctions(targetFuncParent); if (status) { return status; } else { target = targetFuncParent.path; } } const targetPaths = target.getAncestry(); if (targetPaths.indexOf(this) >= 0) return "after"; const selfPaths = this.getAncestry(); let commonPath; let targetIndex; let selfIndex; for (selfIndex = 0; selfIndex < selfPaths.length; selfIndex++) { const selfPath = selfPaths[selfIndex]; targetIndex = targetPaths.indexOf(selfPath); if (targetIndex >= 0) { commonPath = selfPath; break; } } if (!commonPath) { return "before"; } const targetRelationship = targetPaths[targetIndex - 1]; const selfRelationship = selfPaths[selfIndex - 1]; if (!targetRelationship || !selfRelationship) { return "before"; } if (targetRelationship.listKey && targetRelationship.container === selfRelationship.container) { return targetRelationship.key > selfRelationship.key ? "before" : "after"; } const keys = t().VISITOR_KEYS[commonPath.type]; const targetKeyPosition = keys.indexOf(targetRelationship.key); const selfKeyPosition = keys.indexOf(selfRelationship.key); return targetKeyPosition > selfKeyPosition ? "before" : "after"; } function _guessExecutionStatusRelativeToDifferentFunctions(targetFuncParent) { const targetFuncPath = targetFuncParent.path; if (!targetFuncPath.isFunctionDeclaration()) return; const binding = targetFuncPath.scope.getBinding(targetFuncPath.node.id.name); if (!binding.references) return "before"; const referencePaths = binding.referencePaths; for (const path of referencePaths) { if (path.key !== "callee" || !path.parentPath.isCallExpression()) { return; } } let allStatus; for (const path of referencePaths) { const childOfFunction = !!path.find(path => path.node === targetFuncPath.node); if (childOfFunction) continue; const status = this._guessExecutionStatusRelativeTo(path); if (allStatus) { if (allStatus !== status) return; } else { allStatus = status; } } return allStatus; } function resolve(dangerous, resolved) { return this._resolve(dangerous, resolved) || this; } function _resolve(dangerous, resolved) { if (resolved && resolved.indexOf(this) >= 0) return; resolved = resolved || []; resolved.push(this); if (this.isVariableDeclarator()) { if (this.get("id").isIdentifier()) { return this.get("init").resolve(dangerous, resolved); } else {} } else if (this.isReferencedIdentifier()) { const binding = this.scope.getBinding(this.node.name); if (!binding) return; if (!binding.constant) return; if (binding.kind === "module") return; if (binding.path !== this) { const ret = binding.path.resolve(dangerous, resolved); if (this.find(parent => parent.node === ret.node)) return; return ret; } } else if (this.isTypeCastExpression()) { return this.get("expression").resolve(dangerous, resolved); } else if (dangerous && this.isMemberExpression()) { const targetKey = this.toComputedKey(); if (!t().isLiteral(targetKey)) return; const targetName = targetKey.value; const target = this.get("object").resolve(dangerous, resolved); if (target.isObjectExpression()) { const props = target.get("properties"); for (const prop of props) { if (!prop.isProperty()) continue; const key = prop.get("key"); let match = prop.isnt("computed") && key.isIdentifier({ name: targetName }); match = match || key.isLiteral({ value: targetName }); if (match) return prop.get("value").resolve(dangerous, resolved); } } else if (target.isArrayExpression() && !isNaN(+targetName)) { const elems = target.get("elements"); const elem = elems[targetName]; if (elem) return elem.resolve(dangerous, resolved); } } } function isConstantExpression() { if (this.isIdentifier()) { const binding = this.scope.getBinding(this.node.name); if (!binding) return false; return binding.constant; } if (this.isLiteral()) { if (this.isRegExpLiteral()) { return false; } if (this.isTemplateLiteral()) { return this.get("expressions").every(expression => expression.isConstantExpression()); } return true; } if (this.isUnaryExpression()) { if (this.get("operator").node !== "void") { return false; } return this.get("argument").isConstantExpression(); } if (this.isBinaryExpression()) { return this.get("left").isConstantExpression() && this.get("right").isConstantExpression(); } return false; } function isInStrictMode() { const start = this.isProgram() ? this : this.parentPath; const strictParent = start.find(path => { if (path.isProgram({ sourceType: "module" })) return true; if (path.isClass()) return true; if (!path.isProgram() && !path.isFunction()) return false; if (path.isArrowFunctionExpression() && !path.get("body").isBlockStatement()) { return false; } let { node } = path; if (path.isFunction()) node = node.body; for (const directive of node.directives) { if (directive.value.value === "use strict") { return true; } } }); return !!strictParent; } },{"@babel/types":142,"lodash/includes":369}],91:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } const referenceVisitor = { ReferencedIdentifier(path, state) { if (path.isJSXIdentifier() && t().react.isCompatTag(path.node.name) && !path.parentPath.isJSXMemberExpression()) { return; } if (path.node.name === "this") { let scope = path.scope; do { if (scope.path.isFunction() && !scope.path.isArrowFunctionExpression()) { break; } } while (scope = scope.parent); if (scope) state.breakOnScopePaths.push(scope.path); } const binding = path.scope.getBinding(path.node.name); if (!binding) return; if (binding !== state.scope.getBinding(path.node.name)) return; state.bindings[path.node.name] = binding; } }; class PathHoister { constructor(path, scope) { this.breakOnScopePaths = []; this.bindings = {}; this.scopes = []; this.scope = scope; this.path = path; this.attachAfter = false; } isCompatibleScope(scope) { for (const key of Object.keys(this.bindings)) { const binding = this.bindings[key]; if (!scope.bindingIdentifierEquals(key, binding.identifier)) { return false; } } return true; } getCompatibleScopes() { let scope = this.path.scope; do { if (this.isCompatibleScope(scope)) { this.scopes.push(scope); } else { break; } if (this.breakOnScopePaths.indexOf(scope.path) >= 0) { break; } } while (scope = scope.parent); } getAttachmentPath() { let path = this._getAttachmentPath(); if (!path) return; let targetScope = path.scope; if (targetScope.path === path) { targetScope = path.scope.parent; } if (targetScope.path.isProgram() || targetScope.path.isFunction()) { for (const name of Object.keys(this.bindings)) { if (!targetScope.hasOwnBinding(name)) continue; const binding = this.bindings[name]; if (binding.kind === "param" || binding.path.parentKey === "params") { continue; } const bindingParentPath = this.getAttachmentParentForPath(binding.path); if (bindingParentPath.key >= path.key) { this.attachAfter = true; path = binding.path; for (const violationPath of binding.constantViolations) { if (this.getAttachmentParentForPath(violationPath).key > path.key) { path = violationPath; } } } } } return path; } _getAttachmentPath() { const scopes = this.scopes; const scope = scopes.pop(); if (!scope) return; if (scope.path.isFunction()) { if (this.hasOwnParamBindings(scope)) { if (this.scope === scope) return; const bodies = scope.path.get("body").get("body"); for (let i = 0; i < bodies.length; i++) { if (bodies[i].node._blockHoist) continue; return bodies[i]; } } else { return this.getNextScopeAttachmentParent(); } } else if (scope.path.isProgram()) { return this.getNextScopeAttachmentParent(); } } getNextScopeAttachmentParent() { const scope = this.scopes.pop(); if (scope) return this.getAttachmentParentForPath(scope.path); } getAttachmentParentForPath(path) { do { if (!path.parentPath || Array.isArray(path.container) && path.isStatement()) { return path; } } while (path = path.parentPath); } hasOwnParamBindings(scope) { for (const name of Object.keys(this.bindings)) { if (!scope.hasOwnBinding(name)) continue; const binding = this.bindings[name]; if (binding.kind === "param" && binding.constant) return true; } return false; } run() { this.path.traverse(referenceVisitor, this); this.getCompatibleScopes(); const attachTo = this.getAttachmentPath(); if (!attachTo) return; if (attachTo.getFunctionParent() === this.path.getFunctionParent()) return; let uid = attachTo.scope.generateUidIdentifier("ref"); const declarator = t().variableDeclarator(uid, this.path.node); const insertFn = this.attachAfter ? "insertAfter" : "insertBefore"; const [attached] = attachTo[insertFn]([attachTo.isVariableDeclarator() ? declarator : t().variableDeclaration("var", [declarator])]); const parent = this.path.parentPath; if (parent.isJSXElement() && this.path.container === parent.node.children) { uid = t().JSXExpressionContainer(uid); } this.path.replaceWith(t().cloneNode(uid)); return attachTo.isVariableDeclarator() ? attached.get("init") : attached.get("declarations.0.init"); } } exports.default = PathHoister; },{"@babel/types":142}],92:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.hooks = void 0; const hooks = [function (self, parent) { const removeParent = self.key === "test" && (parent.isWhile() || parent.isSwitchCase()) || self.key === "declaration" && parent.isExportDeclaration() || self.key === "body" && parent.isLabeledStatement() || self.listKey === "declarations" && parent.isVariableDeclaration() && parent.node.declarations.length === 1 || self.key === "expression" && parent.isExpressionStatement(); if (removeParent) { parent.remove(); return true; } }, function (self, parent) { if (parent.isSequenceExpression() && parent.node.expressions.length === 1) { parent.replaceWith(parent.node.expressions[0]); return true; } }, function (self, parent) { if (parent.isBinary()) { if (self.key === "left") { parent.replaceWith(parent.node.right); } else { parent.replaceWith(parent.node.left); } return true; } }, function (self, parent) { if (parent.isIfStatement() && (self.key === "consequent" || self.key === "alternate") || self.key === "body" && (parent.isLoop() || parent.isArrowFunctionExpression())) { self.replaceWith({ type: "BlockStatement", body: [] }); return true; } }]; exports.hooks = hooks; },{}],93:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ForAwaitStatement = exports.NumericLiteralTypeAnnotation = exports.ExistentialTypeParam = exports.SpreadProperty = exports.RestProperty = exports.Flow = exports.Pure = exports.Generated = exports.User = exports.Var = exports.BlockScoped = exports.Referenced = exports.Scope = exports.Expression = exports.Statement = exports.BindingIdentifier = exports.ReferencedMemberExpression = exports.ReferencedIdentifier = void 0; function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } const ReferencedIdentifier = { types: ["Identifier", "JSXIdentifier"], checkPath(path, opts) { const { node, parent } = path; if (!t().isIdentifier(node, opts) && !t().isJSXMemberExpression(parent, opts)) { if (t().isJSXIdentifier(node, opts)) { if (t().react.isCompatTag(node.name)) return false; } else { return false; } } return t().isReferenced(node, parent, path.parentPath.parent); } }; exports.ReferencedIdentifier = ReferencedIdentifier; const ReferencedMemberExpression = { types: ["MemberExpression"], checkPath({ node, parent }) { return t().isMemberExpression(node) && t().isReferenced(node, parent); } }; exports.ReferencedMemberExpression = ReferencedMemberExpression; const BindingIdentifier = { types: ["Identifier"], checkPath(path) { const { node, parent } = path; const grandparent = path.parentPath.parent; return t().isIdentifier(node) && t().isBinding(node, parent, grandparent); } }; exports.BindingIdentifier = BindingIdentifier; const Statement = { types: ["Statement"], checkPath({ node, parent }) { if (t().isStatement(node)) { if (t().isVariableDeclaration(node)) { if (t().isForXStatement(parent, { left: node })) return false; if (t().isForStatement(parent, { init: node })) return false; } return true; } else { return false; } } }; exports.Statement = Statement; const Expression = { types: ["Expression"], checkPath(path) { if (path.isIdentifier()) { return path.isReferencedIdentifier(); } else { return t().isExpression(path.node); } } }; exports.Expression = Expression; const Scope = { types: ["Scopable"], checkPath(path) { return t().isScope(path.node, path.parent); } }; exports.Scope = Scope; const Referenced = { checkPath(path) { return t().isReferenced(path.node, path.parent); } }; exports.Referenced = Referenced; const BlockScoped = { checkPath(path) { return t().isBlockScoped(path.node); } }; exports.BlockScoped = BlockScoped; const Var = { types: ["VariableDeclaration"], checkPath(path) { return t().isVar(path.node); } }; exports.Var = Var; const User = { checkPath(path) { return path.node && !!path.node.loc; } }; exports.User = User; const Generated = { checkPath(path) { return !path.isUser(); } }; exports.Generated = Generated; const Pure = { checkPath(path, opts) { return path.scope.isPure(path.node, opts); } }; exports.Pure = Pure; const Flow = { types: ["Flow", "ImportDeclaration", "ExportDeclaration", "ImportSpecifier"], checkPath({ node }) { if (t().isFlow(node)) { return true; } else if (t().isImportDeclaration(node)) { return node.importKind === "type" || node.importKind === "typeof"; } else if (t().isExportDeclaration(node)) { return node.exportKind === "type"; } else if (t().isImportSpecifier(node)) { return node.importKind === "type" || node.importKind === "typeof"; } else { return false; } } }; exports.Flow = Flow; const RestProperty = { types: ["RestElement"], checkPath(path) { return path.parentPath && path.parentPath.isObjectPattern(); } }; exports.RestProperty = RestProperty; const SpreadProperty = { types: ["RestElement"], checkPath(path) { return path.parentPath && path.parentPath.isObjectExpression(); } }; exports.SpreadProperty = SpreadProperty; const ExistentialTypeParam = { types: ["ExistsTypeAnnotation"] }; exports.ExistentialTypeParam = ExistentialTypeParam; const NumericLiteralTypeAnnotation = { types: ["NumberLiteralTypeAnnotation"] }; exports.NumericLiteralTypeAnnotation = NumericLiteralTypeAnnotation; const ForAwaitStatement = { types: ["ForOfStatement"], checkPath({ node }) { return node.await === true; } }; exports.ForAwaitStatement = ForAwaitStatement; },{"@babel/types":142}],94:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.insertBefore = insertBefore; exports._containerInsert = _containerInsert; exports._containerInsertBefore = _containerInsertBefore; exports._containerInsertAfter = _containerInsertAfter; exports.insertAfter = insertAfter; exports.updateSiblingKeys = updateSiblingKeys; exports._verifyNodeList = _verifyNodeList; exports.unshiftContainer = unshiftContainer; exports.pushContainer = pushContainer; exports.hoist = hoist; var _cache = require("../cache"); var _hoister = _interopRequireDefault(require("./lib/hoister")); var _index = _interopRequireDefault(require("./index")); function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function insertBefore(nodes) { this._assertUnremoved(); nodes = this._verifyNodeList(nodes); const { parentPath } = this; if (parentPath.isExpressionStatement() || parentPath.isLabeledStatement() || parentPath.isExportNamedDeclaration() || parentPath.isExportDefaultDeclaration() && this.isDeclaration()) { return parentPath.insertBefore(nodes); } else if (this.isNodeType("Expression") && this.listKey !== "params" && this.listKey !== "arguments" || parentPath.isForStatement() && this.key === "init") { if (this.node) nodes.push(this.node); return this.replaceExpressionWithStatements(nodes); } else if (Array.isArray(this.container)) { return this._containerInsertBefore(nodes); } else if (this.isStatementOrBlock()) { const shouldInsertCurrentNode = this.node && (!this.isExpressionStatement() || this.node.expression != null); this.replaceWith(t().blockStatement(shouldInsertCurrentNode ? [this.node] : [])); return this.unshiftContainer("body", nodes); } else { throw new Error("We don't know what to do with this node type. " + "We were previously a Statement but we can't fit in here?"); } } function _containerInsert(from, nodes) { this.updateSiblingKeys(from, nodes.length); const paths = []; this.container.splice(from, 0, ...nodes); for (let i = 0; i < nodes.length; i++) { const to = from + i; const path = this.getSibling(to); paths.push(path); if (this.context && this.context.queue) { path.pushContext(this.context); } } const contexts = this._getQueueContexts(); for (const path of paths) { path.setScope(); path.debug("Inserted."); for (const context of contexts) { context.maybeQueue(path, true); } } return paths; } function _containerInsertBefore(nodes) { return this._containerInsert(this.key, nodes); } function _containerInsertAfter(nodes) { return this._containerInsert(this.key + 1, nodes); } function insertAfter(nodes) { this._assertUnremoved(); nodes = this._verifyNodeList(nodes); const { parentPath } = this; if (parentPath.isExpressionStatement() || parentPath.isLabeledStatement() || parentPath.isExportNamedDeclaration() || parentPath.isExportDefaultDeclaration() && this.isDeclaration()) { return parentPath.insertAfter(nodes.map(node => { return t().isExpression(node) ? t().expressionStatement(node) : node; })); } else if (this.isNodeType("Expression") && !this.isJSXElement() || parentPath.isForStatement() && this.key === "init") { if (this.node) { let { scope } = this; if (parentPath.isMethod({ computed: true, key: this.node })) { scope = scope.parent; } const temp = scope.generateDeclaredUidIdentifier(); nodes.unshift(t().expressionStatement(t().assignmentExpression("=", t().cloneNode(temp), this.node))); nodes.push(t().expressionStatement(t().cloneNode(temp))); } return this.replaceExpressionWithStatements(nodes); } else if (Array.isArray(this.container)) { return this._containerInsertAfter(nodes); } else if (this.isStatementOrBlock()) { const shouldInsertCurrentNode = this.node && (!this.isExpressionStatement() || this.node.expression != null); this.replaceWith(t().blockStatement(shouldInsertCurrentNode ? [this.node] : [])); return this.pushContainer("body", nodes); } else { throw new Error("We don't know what to do with this node type. " + "We were previously a Statement but we can't fit in here?"); } } function updateSiblingKeys(fromIndex, incrementBy) { if (!this.parent) return; const paths = _cache.path.get(this.parent); for (let i = 0; i < paths.length; i++) { const path = paths[i]; if (path.key >= fromIndex) { path.key += incrementBy; } } } function _verifyNodeList(nodes) { if (!nodes) { return []; } if (nodes.constructor !== Array) { nodes = [nodes]; } for (let i = 0; i < nodes.length; i++) { const node = nodes[i]; let msg; if (!node) { msg = "has falsy node"; } else if (typeof node !== "object") { msg = "contains a non-object node"; } else if (!node.type) { msg = "without a type"; } else if (node instanceof _index.default) { msg = "has a NodePath when it expected a raw object"; } if (msg) { const type = Array.isArray(node) ? "array" : typeof node; throw new Error(`Node list ${msg} with the index of ${i} and type of ${type}`); } } return nodes; } function unshiftContainer(listKey, nodes) { this._assertUnremoved(); nodes = this._verifyNodeList(nodes); const path = _index.default.get({ parentPath: this, parent: this.node, container: this.node[listKey], listKey, key: 0 }); return path.insertBefore(nodes); } function pushContainer(listKey, nodes) { this._assertUnremoved(); nodes = this._verifyNodeList(nodes); const container = this.node[listKey]; const path = _index.default.get({ parentPath: this, parent: this.node, container: container, listKey, key: container.length }); return path.replaceWithMultiple(nodes); } function hoist(scope = this.scope) { const hoister = new _hoister.default(this, scope); return hoister.run(); } },{"../cache":76,"./index":86,"./lib/hoister":91,"@babel/types":142}],95:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.remove = remove; exports._removeFromScope = _removeFromScope; exports._callRemovalHooks = _callRemovalHooks; exports._remove = _remove; exports._markRemoved = _markRemoved; exports._assertUnremoved = _assertUnremoved; var _removalHooks = require("./lib/removal-hooks"); function remove() { this._assertUnremoved(); this.resync(); this._removeFromScope(); if (this._callRemovalHooks()) { this._markRemoved(); return; } this.shareCommentsWithSiblings(); this._remove(); this._markRemoved(); } function _removeFromScope() { const bindings = this.getBindingIdentifiers(); Object.keys(bindings).forEach(name => this.scope.removeBinding(name)); } function _callRemovalHooks() { for (const fn of _removalHooks.hooks) { if (fn(this, this.parentPath)) return true; } } function _remove() { if (Array.isArray(this.container)) { this.container.splice(this.key, 1); this.updateSiblingKeys(this.key, -1); } else { this._replaceWith(null); } } function _markRemoved() { this.shouldSkip = true; this.removed = true; this.node = null; } function _assertUnremoved() { if (this.removed) { throw this.buildCodeFrameError("NodePath has been removed so is read-only."); } } },{"./lib/removal-hooks":92}],96:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.replaceWithMultiple = replaceWithMultiple; exports.replaceWithSourceString = replaceWithSourceString; exports.replaceWith = replaceWith; exports._replaceWith = _replaceWith; exports.replaceExpressionWithStatements = replaceExpressionWithStatements; exports.replaceInline = replaceInline; function _codeFrame() { const data = require("@babel/code-frame"); _codeFrame = function () { return data; }; return data; } var _index = _interopRequireDefault(require("../index")); var _index2 = _interopRequireDefault(require("./index")); function _parser() { const data = require("@babel/parser"); _parser = function () { return data; }; return data; } function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const hoistVariablesVisitor = { Function(path) { path.skip(); }, VariableDeclaration(path) { if (path.node.kind !== "var") return; const bindings = path.getBindingIdentifiers(); for (const key of Object.keys(bindings)) { path.scope.push({ id: bindings[key] }); } const exprs = []; for (const declar of path.node.declarations) { if (declar.init) { exprs.push(t().expressionStatement(t().assignmentExpression("=", declar.id, declar.init))); } } path.replaceWithMultiple(exprs); } }; function replaceWithMultiple(nodes) { this.resync(); nodes = this._verifyNodeList(nodes); t().inheritLeadingComments(nodes[0], this.node); t().inheritTrailingComments(nodes[nodes.length - 1], this.node); this.node = this.container[this.key] = null; const paths = this.insertAfter(nodes); if (this.node) { this.requeue(); } else { this.remove(); } return paths; } function replaceWithSourceString(replacement) { this.resync(); try { replacement = `(${replacement})`; replacement = (0, _parser().parse)(replacement); } catch (err) { const loc = err.loc; if (loc) { err.message += " - make sure this is an expression.\n" + (0, _codeFrame().codeFrameColumns)(replacement, { start: { line: loc.line, column: loc.column + 1 } }); err.code = "BABEL_REPLACE_SOURCE_ERROR"; } throw err; } replacement = replacement.program.body[0].expression; _index.default.removeProperties(replacement); return this.replaceWith(replacement); } function replaceWith(replacement) { this.resync(); if (this.removed) { throw new Error("You can't replace this node, we've already removed it"); } if (replacement instanceof _index2.default) { replacement = replacement.node; } if (!replacement) { throw new Error("You passed `path.replaceWith()` a falsy node, use `path.remove()` instead"); } if (this.node === replacement) { return [this]; } if (this.isProgram() && !t().isProgram(replacement)) { throw new Error("You can only replace a Program root node with another Program node"); } if (Array.isArray(replacement)) { throw new Error("Don't use `path.replaceWith()` with an array of nodes, use `path.replaceWithMultiple()`"); } if (typeof replacement === "string") { throw new Error("Don't use `path.replaceWith()` with a source string, use `path.replaceWithSourceString()`"); } let nodePath = ""; if (this.isNodeType("Statement") && t().isExpression(replacement)) { if (!this.canHaveVariableDeclarationOrExpression() && !this.canSwapBetweenExpressionAndStatement(replacement) && !this.parentPath.isExportDefaultDeclaration()) { replacement = t().expressionStatement(replacement); nodePath = "expression"; } } if (this.isNodeType("Expression") && t().isStatement(replacement)) { if (!this.canHaveVariableDeclarationOrExpression() && !this.canSwapBetweenExpressionAndStatement(replacement)) { return this.replaceExpressionWithStatements([replacement]); } } const oldNode = this.node; if (oldNode) { t().inheritsComments(replacement, oldNode); t().removeComments(oldNode); } this._replaceWith(replacement); this.type = replacement.type; this.setScope(); this.requeue(); return [nodePath ? this.get(nodePath) : this]; } function _replaceWith(node) { if (!this.container) { throw new ReferenceError("Container is falsy"); } if (this.inList) { t().validate(this.parent, this.key, [node]); } else { t().validate(this.parent, this.key, node); } this.debug(`Replace with ${node && node.type}`); this.node = this.container[this.key] = node; } function replaceExpressionWithStatements(nodes) { this.resync(); const toSequenceExpression = t().toSequenceExpression(nodes, this.scope); if (toSequenceExpression) { return this.replaceWith(toSequenceExpression)[0].get("expressions"); } const container = t().arrowFunctionExpression([], t().blockStatement(nodes)); this.replaceWith(t().callExpression(container, [])); this.traverse(hoistVariablesVisitor); const completionRecords = this.get("callee").getCompletionRecords(); for (const path of completionRecords) { if (!path.isExpressionStatement()) continue; const loop = path.findParent(path => path.isLoop()); if (loop) { let uid = loop.getData("expressionReplacementReturnUid"); if (!uid) { const callee = this.get("callee"); uid = callee.scope.generateDeclaredUidIdentifier("ret"); callee.get("body").pushContainer("body", t().returnStatement(t().cloneNode(uid))); loop.setData("expressionReplacementReturnUid", uid); } else { uid = t().identifier(uid.name); } path.get("expression").replaceWith(t().assignmentExpression("=", t().cloneNode(uid), path.node.expression)); } else { path.replaceWith(t().returnStatement(path.node.expression)); } } const callee = this.get("callee"); callee.arrowFunctionToExpression(); return callee.get("body.body"); } function replaceInline(nodes) { this.resync(); if (Array.isArray(nodes)) { if (Array.isArray(this.container)) { nodes = this._verifyNodeList(nodes); const paths = this._containerInsertAfter(nodes); this.remove(); return paths; } else { return this.replaceWithMultiple(nodes); } } else { return this.replaceWith(nodes); } } },{"../index":79,"./index":86,"@babel/code-frame":8,"@babel/parser":67,"@babel/types":142}],97:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; class Binding { constructor({ identifier, scope, path, kind }) { this.identifier = identifier; this.scope = scope; this.path = path; this.kind = kind; this.constantViolations = []; this.constant = true; this.referencePaths = []; this.referenced = false; this.references = 0; this.clearValue(); } deoptValue() { this.clearValue(); this.hasDeoptedValue = true; } setValue(value) { if (this.hasDeoptedValue) return; this.hasValue = true; this.value = value; } clearValue() { this.hasDeoptedValue = false; this.hasValue = false; this.value = null; } reassign(path) { this.constant = false; if (this.constantViolations.indexOf(path) !== -1) { return; } this.constantViolations.push(path); } reference(path) { if (this.referencePaths.indexOf(path) !== -1) { return; } this.referenced = true; this.references++; this.referencePaths.push(path); } dereference() { this.references--; this.referenced = !!this.references; } } exports.default = Binding; },{}],98:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; function _includes() { const data = _interopRequireDefault(require("lodash/includes")); _includes = function () { return data; }; return data; } function _repeat() { const data = _interopRequireDefault(require("lodash/repeat")); _repeat = function () { return data; }; return data; } var _renamer = _interopRequireDefault(require("./lib/renamer")); var _index = _interopRequireDefault(require("../index")); function _defaults() { const data = _interopRequireDefault(require("lodash/defaults")); _defaults = function () { return data; }; return data; } var _binding = _interopRequireDefault(require("./binding")); function _globals() { const data = _interopRequireDefault(require("globals")); _globals = function () { return data; }; return data; } function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } var _cache = require("../cache"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function gatherNodeParts(node, parts) { if (t().isModuleDeclaration(node)) { if (node.source) { gatherNodeParts(node.source, parts); } else if (node.specifiers && node.specifiers.length) { for (const specifier of node.specifiers) { gatherNodeParts(specifier, parts); } } else if (node.declaration) { gatherNodeParts(node.declaration, parts); } } else if (t().isModuleSpecifier(node)) { gatherNodeParts(node.local, parts); } else if (t().isMemberExpression(node)) { gatherNodeParts(node.object, parts); gatherNodeParts(node.property, parts); } else if (t().isIdentifier(node)) { parts.push(node.name); } else if (t().isLiteral(node)) { parts.push(node.value); } else if (t().isCallExpression(node)) { gatherNodeParts(node.callee, parts); } else if (t().isObjectExpression(node) || t().isObjectPattern(node)) { for (const prop of node.properties) { gatherNodeParts(prop.key || prop.argument, parts); } } else if (t().isPrivateName(node)) { gatherNodeParts(node.id, parts); } else if (t().isThisExpression(node)) { parts.push("this"); } else if (t().isSuper(node)) { parts.push("super"); } } const collectorVisitor = { For(path) { for (const key of t().FOR_INIT_KEYS) { const declar = path.get(key); if (declar.isVar()) { const parentScope = path.scope.getFunctionParent() || path.scope.getProgramParent(); parentScope.registerBinding("var", declar); } } }, Declaration(path) { if (path.isBlockScoped()) return; if (path.isExportDeclaration() && path.get("declaration").isDeclaration()) { return; } const parent = path.scope.getFunctionParent() || path.scope.getProgramParent(); parent.registerDeclaration(path); }, ReferencedIdentifier(path, state) { state.references.push(path); }, ForXStatement(path, state) { const left = path.get("left"); if (left.isPattern() || left.isIdentifier()) { state.constantViolations.push(path); } }, ExportDeclaration: { exit(path) { const { node, scope } = path; const declar = node.declaration; if (t().isClassDeclaration(declar) || t().isFunctionDeclaration(declar)) { const id = declar.id; if (!id) return; const binding = scope.getBinding(id.name); if (binding) binding.reference(path); } else if (t().isVariableDeclaration(declar)) { for (const decl of declar.declarations) { for (const name of Object.keys(t().getBindingIdentifiers(decl))) { const binding = scope.getBinding(name); if (binding) binding.reference(path); } } } } }, LabeledStatement(path) { path.scope.getProgramParent().addGlobal(path.node); path.scope.getBlockParent().registerDeclaration(path); }, AssignmentExpression(path, state) { state.assignments.push(path); }, UpdateExpression(path, state) { state.constantViolations.push(path); }, UnaryExpression(path, state) { if (path.node.operator === "delete") { state.constantViolations.push(path); } }, BlockScoped(path) { let scope = path.scope; if (scope.path === path) scope = scope.parent; scope.getBlockParent().registerDeclaration(path); }, ClassDeclaration(path) { const id = path.node.id; if (!id) return; const name = id.name; path.scope.bindings[name] = path.scope.getBinding(name); }, Block(path) { const paths = path.get("body"); for (const bodyPath of paths) { if (bodyPath.isFunctionDeclaration()) { path.scope.getBlockParent().registerDeclaration(bodyPath); } } } }; let uid = 0; class Scope { constructor(path) { const { node } = path; const cached = _cache.scope.get(node); if (cached && cached.path === path) { return cached; } _cache.scope.set(node, this); this.uid = uid++; this.block = node; this.path = path; this.labels = new Map(); } get parent() { const parent = this.path.findParent(p => p.isScope()); return parent && parent.scope; } get parentBlock() { return this.path.parent; } get hub() { return this.path.hub; } traverse(node, opts, state) { (0, _index.default)(node, opts, this, state, this.path); } generateDeclaredUidIdentifier(name) { const id = this.generateUidIdentifier(name); this.push({ id }); return t().cloneNode(id); } generateUidIdentifier(name) { return t().identifier(this.generateUid(name)); } generateUid(name = "temp") { name = t().toIdentifier(name).replace(/^_+/, "").replace(/[0-9]+$/g, ""); let uid; let i = 0; do { uid = this._generateUid(name, i); i++; } while (this.hasLabel(uid) || this.hasBinding(uid) || this.hasGlobal(uid) || this.hasReference(uid)); const program = this.getProgramParent(); program.references[uid] = true; program.uids[uid] = true; return uid; } _generateUid(name, i) { let id = name; if (i > 1) id += i; return `_${id}`; } generateUidBasedOnNode(parent, defaultName) { let node = parent; if (t().isAssignmentExpression(parent)) { node = parent.left; } else if (t().isVariableDeclarator(parent)) { node = parent.id; } else if (t().isObjectProperty(node) || t().isObjectMethod(node)) { node = node.key; } const parts = []; gatherNodeParts(node, parts); let id = parts.join("$"); id = id.replace(/^_/, "") || defaultName || "ref"; return this.generateUid(id.slice(0, 20)); } generateUidIdentifierBasedOnNode(parent, defaultName) { return t().identifier(this.generateUidBasedOnNode(parent, defaultName)); } isStatic(node) { if (t().isThisExpression(node) || t().isSuper(node)) { return true; } if (t().isIdentifier(node)) { const binding = this.getBinding(node.name); if (binding) { return binding.constant; } else { return this.hasBinding(node.name); } } return false; } maybeGenerateMemoised(node, dontPush) { if (this.isStatic(node)) { return null; } else { const id = this.generateUidIdentifierBasedOnNode(node); if (!dontPush) { this.push({ id }); return t().cloneNode(id); } return id; } } checkBlockScopedCollisions(local, kind, name, id) { if (kind === "param") return; if (local.kind === "local") return; const duplicate = kind === "let" || local.kind === "let" || local.kind === "const" || local.kind === "module" || local.kind === "param" && (kind === "let" || kind === "const"); if (duplicate) { throw this.hub.buildError(id, `Duplicate declaration "${name}"`, TypeError); } } rename(oldName, newName, block) { const binding = this.getBinding(oldName); if (binding) { newName = newName || this.generateUidIdentifier(oldName).name; return new _renamer.default(binding, oldName, newName).rename(block); } } _renameFromMap(map, oldName, newName, value) { if (map[oldName]) { map[newName] = value; map[oldName] = null; } } dump() { const sep = (0, _repeat().default)("-", 60); console.log(sep); let scope = this; do { console.log("#", scope.block.type); for (const name of Object.keys(scope.bindings)) { const binding = scope.bindings[name]; console.log(" -", name, { constant: binding.constant, references: binding.references, violations: binding.constantViolations.length, kind: binding.kind }); } } while (scope = scope.parent); console.log(sep); } toArray(node, i) { if (t().isIdentifier(node)) { const binding = this.getBinding(node.name); if (binding && binding.constant && binding.path.isGenericType("Array")) { return node; } } if (t().isArrayExpression(node)) { return node; } if (t().isIdentifier(node, { name: "arguments" })) { return t().callExpression(t().memberExpression(t().memberExpression(t().memberExpression(t().identifier("Array"), t().identifier("prototype")), t().identifier("slice")), t().identifier("call")), [node]); } let helperName; const args = [node]; if (i === true) { helperName = "toConsumableArray"; } else if (i) { args.push(t().numericLiteral(i)); helperName = "slicedToArray"; } else { helperName = "toArray"; } return t().callExpression(this.hub.addHelper(helperName), args); } hasLabel(name) { return !!this.getLabel(name); } getLabel(name) { return this.labels.get(name); } registerLabel(path) { this.labels.set(path.node.label.name, path); } registerDeclaration(path) { if (path.isLabeledStatement()) { this.registerLabel(path); } else if (path.isFunctionDeclaration()) { this.registerBinding("hoisted", path.get("id"), path); } else if (path.isVariableDeclaration()) { const declarations = path.get("declarations"); for (const declar of declarations) { this.registerBinding(path.node.kind, declar); } } else if (path.isClassDeclaration()) { this.registerBinding("let", path); } else if (path.isImportDeclaration()) { const specifiers = path.get("specifiers"); for (const specifier of specifiers) { this.registerBinding("module", specifier); } } else if (path.isExportDeclaration()) { const declar = path.get("declaration"); if (declar.isClassDeclaration() || declar.isFunctionDeclaration() || declar.isVariableDeclaration()) { this.registerDeclaration(declar); } } else { this.registerBinding("unknown", path); } } buildUndefinedNode() { if (this.hasBinding("undefined")) { return t().unaryExpression("void", t().numericLiteral(0), true); } else { return t().identifier("undefined"); } } registerConstantViolation(path) { const ids = path.getBindingIdentifiers(); for (const name of Object.keys(ids)) { const binding = this.getBinding(name); if (binding) binding.reassign(path); } } registerBinding(kind, path, bindingPath = path) { if (!kind) throw new ReferenceError("no `kind`"); if (path.isVariableDeclaration()) { const declarators = path.get("declarations"); for (const declar of declarators) { this.registerBinding(kind, declar); } return; } const parent = this.getProgramParent(); const ids = path.getOuterBindingIdentifiers(true); for (const name of Object.keys(ids)) { for (const id of ids[name]) { const local = this.getOwnBinding(name); if (local) { if (local.identifier === id) continue; this.checkBlockScopedCollisions(local, kind, name, id); } parent.references[name] = true; if (local) { this.registerConstantViolation(bindingPath); } else { this.bindings[name] = new _binding.default({ identifier: id, scope: this, path: bindingPath, kind: kind }); } } } } addGlobal(node) { this.globals[node.name] = node; } hasUid(name) { let scope = this; do { if (scope.uids[name]) return true; } while (scope = scope.parent); return false; } hasGlobal(name) { let scope = this; do { if (scope.globals[name]) return true; } while (scope = scope.parent); return false; } hasReference(name) { let scope = this; do { if (scope.references[name]) return true; } while (scope = scope.parent); return false; } isPure(node, constantsOnly) { if (t().isIdentifier(node)) { const binding = this.getBinding(node.name); if (!binding) return false; if (constantsOnly) return binding.constant; return true; } else if (t().isClass(node)) { if (node.superClass && !this.isPure(node.superClass, constantsOnly)) { return false; } return this.isPure(node.body, constantsOnly); } else if (t().isClassBody(node)) { for (const method of node.body) { if (!this.isPure(method, constantsOnly)) return false; } return true; } else if (t().isBinary(node)) { return this.isPure(node.left, constantsOnly) && this.isPure(node.right, constantsOnly); } else if (t().isArrayExpression(node)) { for (const elem of node.elements) { if (!this.isPure(elem, constantsOnly)) return false; } return true; } else if (t().isObjectExpression(node)) { for (const prop of node.properties) { if (!this.isPure(prop, constantsOnly)) return false; } return true; } else if (t().isClassMethod(node)) { if (node.computed && !this.isPure(node.key, constantsOnly)) return false; if (node.kind === "get" || node.kind === "set") return false; return true; } else if (t().isProperty(node)) { if (node.computed && !this.isPure(node.key, constantsOnly)) return false; return this.isPure(node.value, constantsOnly); } else if (t().isUnaryExpression(node)) { return this.isPure(node.argument, constantsOnly); } else if (t().isTaggedTemplateExpression(node)) { return t().matchesPattern(node.tag, "String.raw") && !this.hasBinding("String", true) && this.isPure(node.quasi, constantsOnly); } else if (t().isTemplateLiteral(node)) { for (const expression of node.expressions) { if (!this.isPure(expression, constantsOnly)) return false; } return true; } else { return t().isPureish(node); } } setData(key, val) { return this.data[key] = val; } getData(key) { let scope = this; do { const data = scope.data[key]; if (data != null) return data; } while (scope = scope.parent); } removeData(key) { let scope = this; do { const data = scope.data[key]; if (data != null) scope.data[key] = null; } while (scope = scope.parent); } init() { if (!this.references) this.crawl(); } crawl() { const path = this.path; this.references = Object.create(null); this.bindings = Object.create(null); this.globals = Object.create(null); this.uids = Object.create(null); this.data = Object.create(null); if (path.isLoop()) { for (const key of t().FOR_INIT_KEYS) { const node = path.get(key); if (node.isBlockScoped()) this.registerBinding(node.node.kind, node); } } if (path.isFunctionExpression() && path.has("id")) { if (!path.get("id").node[t().NOT_LOCAL_BINDING]) { this.registerBinding("local", path.get("id"), path); } } if (path.isClassExpression() && path.has("id")) { if (!path.get("id").node[t().NOT_LOCAL_BINDING]) { this.registerBinding("local", path); } } if (path.isFunction()) { const params = path.get("params"); for (const param of params) { this.registerBinding("param", param); } } if (path.isCatchClause()) { this.registerBinding("let", path); } const parent = this.getProgramParent(); if (parent.crawling) return; const state = { references: [], constantViolations: [], assignments: [] }; this.crawling = true; path.traverse(collectorVisitor, state); this.crawling = false; for (const path of state.assignments) { const ids = path.getBindingIdentifiers(); let programParent; for (const name of Object.keys(ids)) { if (path.scope.getBinding(name)) continue; programParent = programParent || path.scope.getProgramParent(); programParent.addGlobal(ids[name]); } path.scope.registerConstantViolation(path); } for (const ref of state.references) { const binding = ref.scope.getBinding(ref.node.name); if (binding) { binding.reference(ref); } else { ref.scope.getProgramParent().addGlobal(ref.node); } } for (const path of state.constantViolations) { path.scope.registerConstantViolation(path); } } push(opts) { let path = this.path; if (!path.isBlockStatement() && !path.isProgram()) { path = this.getBlockParent().path; } if (path.isSwitchStatement()) { path = (this.getFunctionParent() || this.getProgramParent()).path; } if (path.isLoop() || path.isCatchClause() || path.isFunction()) { path.ensureBlock(); path = path.get("body"); } const unique = opts.unique; const kind = opts.kind || "var"; const blockHoist = opts._blockHoist == null ? 2 : opts._blockHoist; const dataKey = `declaration:${kind}:${blockHoist}`; let declarPath = !unique && path.getData(dataKey); if (!declarPath) { const declar = t().variableDeclaration(kind, []); declar._blockHoist = blockHoist; [declarPath] = path.unshiftContainer("body", [declar]); if (!unique) path.setData(dataKey, declarPath); } const declarator = t().variableDeclarator(opts.id, opts.init); declarPath.node.declarations.push(declarator); this.registerBinding(kind, declarPath.get("declarations").pop()); } getProgramParent() { let scope = this; do { if (scope.path.isProgram()) { return scope; } } while (scope = scope.parent); throw new Error("Couldn't find a Program"); } getFunctionParent() { let scope = this; do { if (scope.path.isFunctionParent()) { return scope; } } while (scope = scope.parent); return null; } getBlockParent() { let scope = this; do { if (scope.path.isBlockParent()) { return scope; } } while (scope = scope.parent); throw new Error("We couldn't find a BlockStatement, For, Switch, Function, Loop or Program..."); } getAllBindings() { const ids = Object.create(null); let scope = this; do { (0, _defaults().default)(ids, scope.bindings); scope = scope.parent; } while (scope); return ids; } getAllBindingsOfKind() { const ids = Object.create(null); for (const kind of arguments) { let scope = this; do { for (const name of Object.keys(scope.bindings)) { const binding = scope.bindings[name]; if (binding.kind === kind) ids[name] = binding; } scope = scope.parent; } while (scope); } return ids; } bindingIdentifierEquals(name, node) { return this.getBindingIdentifier(name) === node; } getBinding(name) { let scope = this; do { const binding = scope.getOwnBinding(name); if (binding) return binding; } while (scope = scope.parent); } getOwnBinding(name) { return this.bindings[name]; } getBindingIdentifier(name) { const info = this.getBinding(name); return info && info.identifier; } getOwnBindingIdentifier(name) { const binding = this.bindings[name]; return binding && binding.identifier; } hasOwnBinding(name) { return !!this.getOwnBinding(name); } hasBinding(name, noGlobals) { if (!name) return false; if (this.hasOwnBinding(name)) return true; if (this.parentHasBinding(name, noGlobals)) return true; if (this.hasUid(name)) return true; if (!noGlobals && (0, _includes().default)(Scope.globals, name)) return true; if (!noGlobals && (0, _includes().default)(Scope.contextVariables, name)) return true; return false; } parentHasBinding(name, noGlobals) { return this.parent && this.parent.hasBinding(name, noGlobals); } moveBindingTo(name, scope) { const info = this.getBinding(name); if (info) { info.scope.removeOwnBinding(name); info.scope = scope; scope.bindings[name] = info; } } removeOwnBinding(name) { delete this.bindings[name]; } removeBinding(name) { const info = this.getBinding(name); if (info) { info.scope.removeOwnBinding(name); } let scope = this; do { if (scope.uids[name]) { scope.uids[name] = false; } } while (scope = scope.parent); } } exports.default = Scope; Scope.globals = Object.keys(_globals().default.builtin); Scope.contextVariables = ["arguments", "undefined", "Infinity", "NaN"]; },{"../cache":76,"../index":79,"./binding":97,"./lib/renamer":99,"@babel/types":142,"globals":201,"lodash/defaults":363,"lodash/includes":369,"lodash/repeat":391}],99:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _binding = _interopRequireDefault(require("../binding")); function _helperSplitExportDeclaration() { const data = _interopRequireDefault(require("@babel/helper-split-export-declaration")); _helperSplitExportDeclaration = function () { return data; }; return data; } function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const renameVisitor = { ReferencedIdentifier({ node }, state) { if (node.name === state.oldName) { node.name = state.newName; } }, Scope(path, state) { if (!path.scope.bindingIdentifierEquals(state.oldName, state.binding.identifier)) { path.skip(); } }, "AssignmentExpression|Declaration"(path, state) { const ids = path.getOuterBindingIdentifiers(); for (const name in ids) { if (name === state.oldName) ids[name].name = state.newName; } } }; class Renamer { constructor(binding, oldName, newName) { this.newName = newName; this.oldName = oldName; this.binding = binding; } maybeConvertFromExportDeclaration(parentDeclar) { const maybeExportDeclar = parentDeclar.parentPath; if (!maybeExportDeclar.isExportDeclaration()) { return; } if (maybeExportDeclar.isExportDefaultDeclaration() && !maybeExportDeclar.get("declaration").node.id) { return; } (0, _helperSplitExportDeclaration().default)(maybeExportDeclar); } maybeConvertFromClassFunctionDeclaration(path) { return; if (!path.isFunctionDeclaration() && !path.isClassDeclaration()) return; if (this.binding.kind !== "hoisted") return; path.node.id = t().identifier(this.oldName); path.node._blockHoist = 3; path.replaceWith(t().variableDeclaration("let", [t().variableDeclarator(t().identifier(this.newName), t().toExpression(path.node))])); } maybeConvertFromClassFunctionExpression(path) { return; if (!path.isFunctionExpression() && !path.isClassExpression()) return; if (this.binding.kind !== "local") return; path.node.id = t().identifier(this.oldName); this.binding.scope.parent.push({ id: t().identifier(this.newName) }); path.replaceWith(t().assignmentExpression("=", t().identifier(this.newName), path.node)); } rename(block) { const { binding, oldName, newName } = this; const { scope, path } = binding; const parentDeclar = path.find(path => path.isDeclaration() || path.isFunctionExpression() || path.isClassExpression()); if (parentDeclar) { const bindingIds = parentDeclar.getOuterBindingIdentifiers(); if (bindingIds[oldName] === binding.identifier) { this.maybeConvertFromExportDeclaration(parentDeclar); } } scope.traverse(block || scope.block, renameVisitor, this); if (!block) { scope.removeOwnBinding(oldName); scope.bindings[newName] = binding; this.binding.identifier.name = newName; } if (binding.type === "hoisted") {} if (parentDeclar) { this.maybeConvertFromClassFunctionDeclaration(parentDeclar); this.maybeConvertFromClassFunctionExpression(parentDeclar); } } } exports.default = Renamer; },{"../binding":97,"@babel/helper-split-export-declaration":63,"@babel/types":142}],100:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.explode = explode; exports.verify = verify; exports.merge = merge; var virtualTypes = _interopRequireWildcard(require("./path/lib/virtual-types")); function t() { const data = _interopRequireWildcard(require("@babel/types")); t = function () { return data; }; return data; } function _clone() { const data = _interopRequireDefault(require("lodash/clone")); _clone = function () { return data; }; return data; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function explode(visitor) { if (visitor._exploded) return visitor; visitor._exploded = true; for (const nodeType of Object.keys(visitor)) { if (shouldIgnoreKey(nodeType)) continue; const parts = nodeType.split("|"); if (parts.length === 1) continue; const fns = visitor[nodeType]; delete visitor[nodeType]; for (const part of parts) { visitor[part] = fns; } } verify(visitor); delete visitor.__esModule; ensureEntranceObjects(visitor); ensureCallbackArrays(visitor); for (const nodeType of Object.keys(visitor)) { if (shouldIgnoreKey(nodeType)) continue; const wrapper = virtualTypes[nodeType]; if (!wrapper) continue; const fns = visitor[nodeType]; for (const type of Object.keys(fns)) { fns[type] = wrapCheck(wrapper, fns[type]); } delete visitor[nodeType]; if (wrapper.types) { for (const type of wrapper.types) { if (visitor[type]) { mergePair(visitor[type], fns); } else { visitor[type] = fns; } } } else { mergePair(visitor, fns); } } for (const nodeType of Object.keys(visitor)) { if (shouldIgnoreKey(nodeType)) continue; const fns = visitor[nodeType]; let aliases = t().FLIPPED_ALIAS_KEYS[nodeType]; const deprecratedKey = t().DEPRECATED_KEYS[nodeType]; if (deprecratedKey) { console.trace(`Visitor defined for ${nodeType} but it has been renamed to ${deprecratedKey}`); aliases = [deprecratedKey]; } if (!aliases) continue; delete visitor[nodeType]; for (const alias of aliases) { const existing = visitor[alias]; if (existing) { mergePair(existing, fns); } else { visitor[alias] = (0, _clone().default)(fns); } } } for (const nodeType of Object.keys(visitor)) { if (shouldIgnoreKey(nodeType)) continue; ensureCallbackArrays(visitor[nodeType]); } return visitor; } function verify(visitor) { if (visitor._verified) return; if (typeof visitor === "function") { throw new Error("You passed `traverse()` a function when it expected a visitor object, " + "are you sure you didn't mean `{ enter: Function }`?"); } for (const nodeType of Object.keys(visitor)) { if (nodeType === "enter" || nodeType === "exit") { validateVisitorMethods(nodeType, visitor[nodeType]); } if (shouldIgnoreKey(nodeType)) continue; if (t().TYPES.indexOf(nodeType) < 0) { throw new Error(`You gave us a visitor for the node type ${nodeType} but it's not a valid type`); } const visitors = visitor[nodeType]; if (typeof visitors === "object") { for (const visitorKey of Object.keys(visitors)) { if (visitorKey === "enter" || visitorKey === "exit") { validateVisitorMethods(`${nodeType}.${visitorKey}`, visitors[visitorKey]); } else { throw new Error("You passed `traverse()` a visitor object with the property " + `${nodeType} that has the invalid property ${visitorKey}`); } } } } visitor._verified = true; } function validateVisitorMethods(path, val) { const fns = [].concat(val); for (const fn of fns) { if (typeof fn !== "function") { throw new TypeError(`Non-function found defined in ${path} with type ${typeof fn}`); } } } function merge(visitors, states = [], wrapper) { const rootVisitor = {}; for (let i = 0; i < visitors.length; i++) { const visitor = visitors[i]; const state = states[i]; explode(visitor); for (const type of Object.keys(visitor)) { let visitorType = visitor[type]; if (state || wrapper) { visitorType = wrapWithStateOrWrapper(visitorType, state, wrapper); } const nodeVisitor = rootVisitor[type] = rootVisitor[type] || {}; mergePair(nodeVisitor, visitorType); } } return rootVisitor; } function wrapWithStateOrWrapper(oldVisitor, state, wrapper) { const newVisitor = {}; for (const key of Object.keys(oldVisitor)) { let fns = oldVisitor[key]; if (!Array.isArray(fns)) continue; fns = fns.map(function (fn) { let newFn = fn; if (state) { newFn = function (path) { return fn.call(state, path, state); }; } if (wrapper) { newFn = wrapper(state.key, key, newFn); } return newFn; }); newVisitor[key] = fns; } return newVisitor; } function ensureEntranceObjects(obj) { for (const key of Object.keys(obj)) { if (shouldIgnoreKey(key)) continue; const fns = obj[key]; if (typeof fns === "function") { obj[key] = { enter: fns }; } } } function ensureCallbackArrays(obj) { if (obj.enter && !Array.isArray(obj.enter)) obj.enter = [obj.enter]; if (obj.exit && !Array.isArray(obj.exit)) obj.exit = [obj.exit]; } function wrapCheck(wrapper, fn) { const newFn = function (path) { if (wrapper.checkPath(path)) { return fn.apply(this, arguments); } }; newFn.toString = () => fn.toString(); return newFn; } function shouldIgnoreKey(key) { if (key[0] === "_") return true; if (key === "enter" || key === "exit" || key === "shouldSkip") return true; if (key === "blacklist" || key === "noScope" || key === "skipKeys") { return true; } return false; } function mergePair(dest, src) { for (const key of Object.keys(src)) { dest[key] = [].concat(dest[key] || [], src[key]); } } },{"./path/lib/virtual-types":93,"@babel/types":142,"lodash/clone":360}],101:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = assertNode; var _isNode = _interopRequireDefault(require("../validators/isNode")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function assertNode(node) { if (!(0, _isNode.default)(node)) { const type = node && node.type || JSON.stringify(node); throw new TypeError(`Not a valid node of type "${type}"`); } } },{"../validators/isNode":163}],102:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.assertArrayExpression = assertArrayExpression; exports.assertAssignmentExpression = assertAssignmentExpression; exports.assertBinaryExpression = assertBinaryExpression; exports.assertInterpreterDirective = assertInterpreterDirective; exports.assertDirective = assertDirective; exports.assertDirectiveLiteral = assertDirectiveLiteral; exports.assertBlockStatement = assertBlockStatement; exports.assertBreakStatement = assertBreakStatement; exports.assertCallExpression = assertCallExpression; exports.assertCatchClause = assertCatchClause; exports.assertConditionalExpression = assertConditionalExpression; exports.assertContinueStatement = assertContinueStatement; exports.assertDebuggerStatement = assertDebuggerStatement; exports.assertDoWhileStatement = assertDoWhileStatement; exports.assertEmptyStatement = assertEmptyStatement; exports.assertExpressionStatement = assertExpressionStatement; exports.assertFile = assertFile; exports.assertForInStatement = assertForInStatement; exports.assertForStatement = assertForStatement; exports.assertFunctionDeclaration = assertFunctionDeclaration; exports.assertFunctionExpression = assertFunctionExpression; exports.assertIdentifier = assertIdentifier; exports.assertIfStatement = assertIfStatement; exports.assertLabeledStatement = assertLabeledStatement; exports.assertStringLiteral = assertStringLiteral; exports.assertNumericLiteral = assertNumericLiteral; exports.assertNullLiteral = assertNullLiteral; exports.assertBooleanLiteral = assertBooleanLiteral; exports.assertRegExpLiteral = assertRegExpLiteral; exports.assertLogicalExpression = assertLogicalExpression; exports.assertMemberExpression = assertMemberExpression; exports.assertNewExpression = assertNewExpression; exports.assertProgram = assertProgram; exports.assertObjectExpression = assertObjectExpression; exports.assertObjectMethod = assertObjectMethod; exports.assertObjectProperty = assertObjectProperty; exports.assertRestElement = assertRestElement; exports.assertReturnStatement = assertReturnStatement; exports.assertSequenceExpression = assertSequenceExpression; exports.assertParenthesizedExpression = assertParenthesizedExpression; exports.assertSwitchCase = assertSwitchCase; exports.assertSwitchStatement = assertSwitchStatement; exports.assertThisExpression = assertThisExpression; exports.assertThrowStatement = assertThrowStatement; exports.assertTryStatement = assertTryStatement; exports.assertUnaryExpression = assertUnaryExpression; exports.assertUpdateExpression = assertUpdateExpression; exports.assertVariableDeclaration = assertVariableDeclaration; exports.assertVariableDeclarator = assertVariableDeclarator; exports.assertWhileStatement = assertWhileStatement; exports.assertWithStatement = assertWithStatement; exports.assertAssignmentPattern = assertAssignmentPattern; exports.assertArrayPattern = assertArrayPattern; exports.assertArrowFunctionExpression = assertArrowFunctionExpression; exports.assertClassBody = assertClassBody; exports.assertClassDeclaration = assertClassDeclaration; exports.assertClassExpression = assertClassExpression; exports.assertExportAllDeclaration = assertExportAllDeclaration; exports.assertExportDefaultDeclaration = assertExportDefaultDeclaration; exports.assertExportNamedDeclaration = assertExportNamedDeclaration; exports.assertExportSpecifier = assertExportSpecifier; exports.assertForOfStatement = assertForOfStatement; exports.assertImportDeclaration = assertImportDeclaration; exports.assertImportDefaultSpecifier = assertImportDefaultSpecifier; exports.assertImportNamespaceSpecifier = assertImportNamespaceSpecifier; exports.assertImportSpecifier = assertImportSpecifier; exports.assertMetaProperty = assertMetaProperty; exports.assertClassMethod = assertClassMethod; exports.assertObjectPattern = assertObjectPattern; exports.assertSpreadElement = assertSpreadElement; exports.assertSuper = assertSuper; exports.assertTaggedTemplateExpression = assertTaggedTemplateExpression; exports.assertTemplateElement = assertTemplateElement; exports.assertTemplateLiteral = assertTemplateLiteral; exports.assertYieldExpression = assertYieldExpression; exports.assertAnyTypeAnnotation = assertAnyTypeAnnotation; exports.assertArrayTypeAnnotation = assertArrayTypeAnnotation; exports.assertBooleanTypeAnnotation = assertBooleanTypeAnnotation; exports.assertBooleanLiteralTypeAnnotation = assertBooleanLiteralTypeAnnotation; exports.assertNullLiteralTypeAnnotation = assertNullLiteralTypeAnnotation; exports.assertClassImplements = assertClassImplements; exports.assertDeclareClass = assertDeclareClass; exports.assertDeclareFunction = assertDeclareFunction; exports.assertDeclareInterface = assertDeclareInterface; exports.assertDeclareModule = assertDeclareModule; exports.assertDeclareModuleExports = assertDeclareModuleExports; exports.assertDeclareTypeAlias = assertDeclareTypeAlias; exports.assertDeclareOpaqueType = assertDeclareOpaqueType; exports.assertDeclareVariable = assertDeclareVariable; exports.assertDeclareExportDeclaration = assertDeclareExportDeclaration; exports.assertDeclareExportAllDeclaration = assertDeclareExportAllDeclaration; exports.assertDeclaredPredicate = assertDeclaredPredicate; exports.assertExistsTypeAnnotation = assertExistsTypeAnnotation; exports.assertFunctionTypeAnnotation = assertFunctionTypeAnnotation; exports.assertFunctionTypeParam = assertFunctionTypeParam; exports.assertGenericTypeAnnotation = assertGenericTypeAnnotation; exports.assertInferredPredicate = assertInferredPredicate; exports.assertInterfaceExtends = assertInterfaceExtends; exports.assertInterfaceDeclaration = assertInterfaceDeclaration; exports.assertInterfaceTypeAnnotation = assertInterfaceTypeAnnotation; exports.assertIntersectionTypeAnnotation = assertIntersectionTypeAnnotation; exports.assertMixedTypeAnnotation = assertMixedTypeAnnotation; exports.assertEmptyTypeAnnotation = assertEmptyTypeAnnotation; exports.assertNullableTypeAnnotation = assertNullableTypeAnnotation; exports.assertNumberLiteralTypeAnnotation = assertNumberLiteralTypeAnnotation; exports.assertNumberTypeAnnotation = assertNumberTypeAnnotation; exports.assertObjectTypeAnnotation = assertObjectTypeAnnotation; exports.assertObjectTypeInternalSlot = assertObjectTypeInternalSlot; exports.assertObjectTypeCallProperty = assertObjectTypeCallProperty; exports.assertObjectTypeIndexer = assertObjectTypeIndexer; exports.assertObjectTypeProperty = assertObjectTypeProperty; exports.assertObjectTypeSpreadProperty = assertObjectTypeSpreadProperty; exports.assertOpaqueType = assertOpaqueType; exports.assertQualifiedTypeIdentifier = assertQualifiedTypeIdentifier; exports.assertStringLiteralTypeAnnotation = assertStringLiteralTypeAnnotation; exports.assertStringTypeAnnotation = assertStringTypeAnnotation; exports.assertThisTypeAnnotation = assertThisTypeAnnotation; exports.assertTupleTypeAnnotation = assertTupleTypeAnnotation; exports.assertTypeofTypeAnnotation = assertTypeofTypeAnnotation; exports.assertTypeAlias = assertTypeAlias; exports.assertTypeAnnotation = assertTypeAnnotation; exports.assertTypeCastExpression = assertTypeCastExpression; exports.assertTypeParameter = assertTypeParameter; exports.assertTypeParameterDeclaration = assertTypeParameterDeclaration; exports.assertTypeParameterInstantiation = assertTypeParameterInstantiation; exports.assertUnionTypeAnnotation = assertUnionTypeAnnotation; exports.assertVariance = assertVariance; exports.assertVoidTypeAnnotation = assertVoidTypeAnnotation; exports.assertJSXAttribute = assertJSXAttribute; exports.assertJSXClosingElement = assertJSXClosingElement; exports.assertJSXElement = assertJSXElement; exports.assertJSXEmptyExpression = assertJSXEmptyExpression; exports.assertJSXExpressionContainer = assertJSXExpressionContainer; exports.assertJSXSpreadChild = assertJSXSpreadChild; exports.assertJSXIdentifier = assertJSXIdentifier; exports.assertJSXMemberExpression = assertJSXMemberExpression; exports.assertJSXNamespacedName = assertJSXNamespacedName; exports.assertJSXOpeningElement = assertJSXOpeningElement; exports.assertJSXSpreadAttribute = assertJSXSpreadAttribute; exports.assertJSXText = assertJSXText; exports.assertJSXFragment = assertJSXFragment; exports.assertJSXOpeningFragment = assertJSXOpeningFragment; exports.assertJSXClosingFragment = assertJSXClosingFragment; exports.assertNoop = assertNoop; exports.assertPlaceholder = assertPlaceholder; exports.assertArgumentPlaceholder = assertArgumentPlaceholder; exports.assertAwaitExpression = assertAwaitExpression; exports.assertBindExpression = assertBindExpression; exports.assertClassProperty = assertClassProperty; exports.assertOptionalMemberExpression = assertOptionalMemberExpression; exports.assertPipelineTopicExpression = assertPipelineTopicExpression; exports.assertPipelineBareFunction = assertPipelineBareFunction; exports.assertPipelinePrimaryTopicReference = assertPipelinePrimaryTopicReference; exports.assertOptionalCallExpression = assertOptionalCallExpression; exports.assertClassPrivateProperty = assertClassPrivateProperty; exports.assertClassPrivateMethod = assertClassPrivateMethod; exports.assertImport = assertImport; exports.assertDecorator = assertDecorator; exports.assertDoExpression = assertDoExpression; exports.assertExportDefaultSpecifier = assertExportDefaultSpecifier; exports.assertExportNamespaceSpecifier = assertExportNamespaceSpecifier; exports.assertPrivateName = assertPrivateName; exports.assertBigIntLiteral = assertBigIntLiteral; exports.assertTSParameterProperty = assertTSParameterProperty; exports.assertTSDeclareFunction = assertTSDeclareFunction; exports.assertTSDeclareMethod = assertTSDeclareMethod; exports.assertTSQualifiedName = assertTSQualifiedName; exports.assertTSCallSignatureDeclaration = assertTSCallSignatureDeclaration; exports.assertTSConstructSignatureDeclaration = assertTSConstructSignatureDeclaration; exports.assertTSPropertySignature = assertTSPropertySignature; exports.assertTSMethodSignature = assertTSMethodSignature; exports.assertTSIndexSignature = assertTSIndexSignature; exports.assertTSAnyKeyword = assertTSAnyKeyword; exports.assertTSUnknownKeyword = assertTSUnknownKeyword; exports.assertTSNumberKeyword = assertTSNumberKeyword; exports.assertTSObjectKeyword = assertTSObjectKeyword; exports.assertTSBooleanKeyword = assertTSBooleanKeyword; exports.assertTSStringKeyword = assertTSStringKeyword; exports.assertTSSymbolKeyword = assertTSSymbolKeyword; exports.assertTSVoidKeyword = assertTSVoidKeyword; exports.assertTSUndefinedKeyword = assertTSUndefinedKeyword; exports.assertTSNullKeyword = assertTSNullKeyword; exports.assertTSNeverKeyword = assertTSNeverKeyword; exports.assertTSThisType = assertTSThisType; exports.assertTSFunctionType = assertTSFunctionType; exports.assertTSConstructorType = assertTSConstructorType; exports.assertTSTypeReference = assertTSTypeReference; exports.assertTSTypePredicate = assertTSTypePredicate; exports.assertTSTypeQuery = assertTSTypeQuery; exports.assertTSTypeLiteral = assertTSTypeLiteral; exports.assertTSArrayType = assertTSArrayType; exports.assertTSTupleType = assertTSTupleType; exports.assertTSOptionalType = assertTSOptionalType; exports.assertTSRestType = assertTSRestType; exports.assertTSUnionType = assertTSUnionType; exports.assertTSIntersectionType = assertTSIntersectionType; exports.assertTSConditionalType = assertTSConditionalType; exports.assertTSInferType = assertTSInferType; exports.assertTSParenthesizedType = assertTSParenthesizedType; exports.assertTSTypeOperator = assertTSTypeOperator; exports.assertTSIndexedAccessType = assertTSIndexedAccessType; exports.assertTSMappedType = assertTSMappedType; exports.assertTSLiteralType = assertTSLiteralType; exports.assertTSExpressionWithTypeArguments = assertTSExpressionWithTypeArguments; exports.assertTSInterfaceDeclaration = assertTSInterfaceDeclaration; exports.assertTSInterfaceBody = assertTSInterfaceBody; exports.assertTSTypeAliasDeclaration = assertTSTypeAliasDeclaration; exports.assertTSAsExpression = assertTSAsExpression; exports.assertTSTypeAssertion = assertTSTypeAssertion; exports.assertTSEnumDeclaration = assertTSEnumDeclaration; exports.assertTSEnumMember = assertTSEnumMember; exports.assertTSModuleDeclaration = assertTSModuleDeclaration; exports.assertTSModuleBlock = assertTSModuleBlock; exports.assertTSImportType = assertTSImportType; exports.assertTSImportEqualsDeclaration = assertTSImportEqualsDeclaration; exports.assertTSExternalModuleReference = assertTSExternalModuleReference; exports.assertTSNonNullExpression = assertTSNonNullExpression; exports.assertTSExportAssignment = assertTSExportAssignment; exports.assertTSNamespaceExportDeclaration = assertTSNamespaceExportDeclaration; exports.assertTSTypeAnnotation = assertTSTypeAnnotation; exports.assertTSTypeParameterInstantiation = assertTSTypeParameterInstantiation; exports.assertTSTypeParameterDeclaration = assertTSTypeParameterDeclaration; exports.assertTSTypeParameter = assertTSTypeParameter; exports.assertExpression = assertExpression; exports.assertBinary = assertBinary; exports.assertScopable = assertScopable; exports.assertBlockParent = assertBlockParent; exports.assertBlock = assertBlock; exports.assertStatement = assertStatement; exports.assertTerminatorless = assertTerminatorless; exports.assertCompletionStatement = assertCompletionStatement; exports.assertConditional = assertConditional; exports.assertLoop = assertLoop; exports.assertWhile = assertWhile; exports.assertExpressionWrapper = assertExpressionWrapper; exports.assertFor = assertFor; exports.assertForXStatement = assertForXStatement; exports.assertFunction = assertFunction; exports.assertFunctionParent = assertFunctionParent; exports.assertPureish = assertPureish; exports.assertDeclaration = assertDeclaration; exports.assertPatternLike = assertPatternLike; exports.assertLVal = assertLVal; exports.assertTSEntityName = assertTSEntityName; exports.assertLiteral = assertLiteral; exports.assertImmutable = assertImmutable; exports.assertUserWhitespacable = assertUserWhitespacable; exports.assertMethod = assertMethod; exports.assertObjectMember = assertObjectMember; exports.assertProperty = assertProperty; exports.assertUnaryLike = assertUnaryLike; exports.assertPattern = assertPattern; exports.assertClass = assertClass; exports.assertModuleDeclaration = assertModuleDeclaration; exports.assertExportDeclaration = assertExportDeclaration; exports.assertModuleSpecifier = assertModuleSpecifier; exports.assertFlow = assertFlow; exports.assertFlowType = assertFlowType; exports.assertFlowBaseAnnotation = assertFlowBaseAnnotation; exports.assertFlowDeclaration = assertFlowDeclaration; exports.assertFlowPredicate = assertFlowPredicate; exports.assertJSX = assertJSX; exports.assertPrivate = assertPrivate; exports.assertTSTypeElement = assertTSTypeElement; exports.assertTSType = assertTSType; exports.assertNumberLiteral = assertNumberLiteral; exports.assertRegexLiteral = assertRegexLiteral; exports.assertRestProperty = assertRestProperty; exports.assertSpreadProperty = assertSpreadProperty; var _is = _interopRequireDefault(require("../../validators/is")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function assert(type, node, opts) { if (!(0, _is.default)(type, node, opts)) { throw new Error(`Expected type "${type}" with option ${JSON.stringify(opts)}, but instead got "${node.type}".`); } } function assertArrayExpression(node, opts = {}) { assert("ArrayExpression", node, opts); } function assertAssignmentExpression(node, opts = {}) { assert("AssignmentExpression", node, opts); } function assertBinaryExpression(node, opts = {}) { assert("BinaryExpression", node, opts); } function assertInterpreterDirective(node, opts = {}) { assert("InterpreterDirective", node, opts); } function assertDirective(node, opts = {}) { assert("Directive", node, opts); } function assertDirectiveLiteral(node, opts = {}) { assert("DirectiveLiteral", node, opts); } function assertBlockStatement(node, opts = {}) { assert("BlockStatement", node, opts); } function assertBreakStatement(node, opts = {}) { assert("BreakStatement", node, opts); } function assertCallExpression(node, opts = {}) { assert("CallExpression", node, opts); } function assertCatchClause(node, opts = {}) { assert("CatchClause", node, opts); } function assertConditionalExpression(node, opts = {}) { assert("ConditionalExpression", node, opts); } function assertContinueStatement(node, opts = {}) { assert("ContinueStatement", node, opts); } function assertDebuggerStatement(node, opts = {}) { assert("DebuggerStatement", node, opts); } function assertDoWhileStatement(node, opts = {}) { assert("DoWhileStatement", node, opts); } function assertEmptyStatement(node, opts = {}) { assert("EmptyStatement", node, opts); } function assertExpressionStatement(node, opts = {}) { assert("ExpressionStatement", node, opts); } function assertFile(node, opts = {}) { assert("File", node, opts); } function assertForInStatement(node, opts = {}) { assert("ForInStatement", node, opts); } function assertForStatement(node, opts = {}) { assert("ForStatement", node, opts); } function assertFunctionDeclaration(node, opts = {}) { assert("FunctionDeclaration", node, opts); } function assertFunctionExpression(node, opts = {}) { assert("FunctionExpression", node, opts); } function assertIdentifier(node, opts = {}) { assert("Identifier", node, opts); } function assertIfStatement(node, opts = {}) { assert("IfStatement", node, opts); } function assertLabeledStatement(node, opts = {}) { assert("LabeledStatement", node, opts); } function assertStringLiteral(node, opts = {}) { assert("StringLiteral", node, opts); } function assertNumericLiteral(node, opts = {}) { assert("NumericLiteral", node, opts); } function assertNullLiteral(node, opts = {}) { assert("NullLiteral", node, opts); } function assertBooleanLiteral(node, opts = {}) { assert("BooleanLiteral", node, opts); } function assertRegExpLiteral(node, opts = {}) { assert("RegExpLiteral", node, opts); } function assertLogicalExpression(node, opts = {}) { assert("LogicalExpression", node, opts); } function assertMemberExpression(node, opts = {}) { assert("MemberExpression", node, opts); } function assertNewExpression(node, opts = {}) { assert("NewExpression", node, opts); } function assertProgram(node, opts = {}) { assert("Program", node, opts); } function assertObjectExpression(node, opts = {}) { assert("ObjectExpression", node, opts); } function assertObjectMethod(node, opts = {}) { assert("ObjectMethod", node, opts); } function assertObjectProperty(node, opts = {}) { assert("ObjectProperty", node, opts); } function assertRestElement(node, opts = {}) { assert("RestElement", node, opts); } function assertReturnStatement(node, opts = {}) { assert("ReturnStatement", node, opts); } function assertSequenceExpression(node, opts = {}) { assert("SequenceExpression", node, opts); } function assertParenthesizedExpression(node, opts = {}) { assert("ParenthesizedExpression", node, opts); } function assertSwitchCase(node, opts = {}) { assert("SwitchCase", node, opts); } function assertSwitchStatement(node, opts = {}) { assert("SwitchStatement", node, opts); } function assertThisExpression(node, opts = {}) { assert("ThisExpression", node, opts); } function assertThrowStatement(node, opts = {}) { assert("ThrowStatement", node, opts); } function assertTryStatement(node, opts = {}) { assert("TryStatement", node, opts); } function assertUnaryExpression(node, opts = {}) { assert("UnaryExpression", node, opts); } function assertUpdateExpression(node, opts = {}) { assert("UpdateExpression", node, opts); } function assertVariableDeclaration(node, opts = {}) { assert("VariableDeclaration", node, opts); } function assertVariableDeclarator(node, opts = {}) { assert("VariableDeclarator", node, opts); } function assertWhileStatement(node, opts = {}) { assert("WhileStatement", node, opts); } function assertWithStatement(node, opts = {}) { assert("WithStatement", node, opts); } function assertAssignmentPattern(node, opts = {}) { assert("AssignmentPattern", node, opts); } function assertArrayPattern(node, opts = {}) { assert("ArrayPattern", node, opts); } function assertArrowFunctionExpression(node, opts = {}) { assert("ArrowFunctionExpression", node, opts); } function assertClassBody(node, opts = {}) { assert("ClassBody", node, opts); } function assertClassDeclaration(node, opts = {}) { assert("ClassDeclaration", node, opts); } function assertClassExpression(node, opts = {}) { assert("ClassExpression", node, opts); } function assertExportAllDeclaration(node, opts = {}) { assert("ExportAllDeclaration", node, opts); } function assertExportDefaultDeclaration(node, opts = {}) { assert("ExportDefaultDeclaration", node, opts); } function assertExportNamedDeclaration(node, opts = {}) { assert("ExportNamedDeclaration", node, opts); } function assertExportSpecifier(node, opts = {}) { assert("ExportSpecifier", node, opts); } function assertForOfStatement(node, opts = {}) { assert("ForOfStatement", node, opts); } function assertImportDeclaration(node, opts = {}) { assert("ImportDeclaration", node, opts); } function assertImportDefaultSpecifier(node, opts = {}) { assert("ImportDefaultSpecifier", node, opts); } function assertImportNamespaceSpecifier(node, opts = {}) { assert("ImportNamespaceSpecifier", node, opts); } function assertImportSpecifier(node, opts = {}) { assert("ImportSpecifier", node, opts); } function assertMetaProperty(node, opts = {}) { assert("MetaProperty", node, opts); } function assertClassMethod(node, opts = {}) { assert("ClassMethod", node, opts); } function assertObjectPattern(node, opts = {}) { assert("ObjectPattern", node, opts); } function assertSpreadElement(node, opts = {}) { assert("SpreadElement", node, opts); } function assertSuper(node, opts = {}) { assert("Super", node, opts); } function assertTaggedTemplateExpression(node, opts = {}) { assert("TaggedTemplateExpression", node, opts); } function assertTemplateElement(node, opts = {}) { assert("TemplateElement", node, opts); } function assertTemplateLiteral(node, opts = {}) { assert("TemplateLiteral", node, opts); } function assertYieldExpression(node, opts = {}) { assert("YieldExpression", node, opts); } function assertAnyTypeAnnotation(node, opts = {}) { assert("AnyTypeAnnotation", node, opts); } function assertArrayTypeAnnotation(node, opts = {}) { assert("ArrayTypeAnnotation", node, opts); } function assertBooleanTypeAnnotation(node, opts = {}) { assert("BooleanTypeAnnotation", node, opts); } function assertBooleanLiteralTypeAnnotation(node, opts = {}) { assert("BooleanLiteralTypeAnnotation", node, opts); } function assertNullLiteralTypeAnnotation(node, opts = {}) { assert("NullLiteralTypeAnnotation", node, opts); } function assertClassImplements(node, opts = {}) { assert("ClassImplements", node, opts); } function assertDeclareClass(node, opts = {}) { assert("DeclareClass", node, opts); } function assertDeclareFunction(node, opts = {}) { assert("DeclareFunction", node, opts); } function assertDeclareInterface(node, opts = {}) { assert("DeclareInterface", node, opts); } function assertDeclareModule(node, opts = {}) { assert("DeclareModule", node, opts); } function assertDeclareModuleExports(node, opts = {}) { assert("DeclareModuleExports", node, opts); } function assertDeclareTypeAlias(node, opts = {}) { assert("DeclareTypeAlias", node, opts); } function assertDeclareOpaqueType(node, opts = {}) { assert("DeclareOpaqueType", node, opts); } function assertDeclareVariable(node, opts = {}) { assert("DeclareVariable", node, opts); } function assertDeclareExportDeclaration(node, opts = {}) { assert("DeclareExportDeclaration", node, opts); } function assertDeclareExportAllDeclaration(node, opts = {}) { assert("DeclareExportAllDeclaration", node, opts); } function assertDeclaredPredicate(node, opts = {}) { assert("DeclaredPredicate", node, opts); } function assertExistsTypeAnnotation(node, opts = {}) { assert("ExistsTypeAnnotation", node, opts); } function assertFunctionTypeAnnotation(node, opts = {}) { assert("FunctionTypeAnnotation", node, opts); } function assertFunctionTypeParam(node, opts = {}) { assert("FunctionTypeParam", node, opts); } function assertGenericTypeAnnotation(node, opts = {}) { assert("GenericTypeAnnotation", node, opts); } function assertInferredPredicate(node, opts = {}) { assert("InferredPredicate", node, opts); } function assertInterfaceExtends(node, opts = {}) { assert("InterfaceExtends", node, opts); } function assertInterfaceDeclaration(node, opts = {}) { assert("InterfaceDeclaration", node, opts); } function assertInterfaceTypeAnnotation(node, opts = {}) { assert("InterfaceTypeAnnotation", node, opts); } function assertIntersectionTypeAnnotation(node, opts = {}) { assert("IntersectionTypeAnnotation", node, opts); } function assertMixedTypeAnnotation(node, opts = {}) { assert("MixedTypeAnnotation", node, opts); } function assertEmptyTypeAnnotation(node, opts = {}) { assert("EmptyTypeAnnotation", node, opts); } function assertNullableTypeAnnotation(node, opts = {}) { assert("NullableTypeAnnotation", node, opts); } function assertNumberLiteralTypeAnnotation(node, opts = {}) { assert("NumberLiteralTypeAnnotation", node, opts); } function assertNumberTypeAnnotation(node, opts = {}) { assert("NumberTypeAnnotation", node, opts); } function assertObjectTypeAnnotation(node, opts = {}) { assert("ObjectTypeAnnotation", node, opts); } function assertObjectTypeInternalSlot(node, opts = {}) { assert("ObjectTypeInternalSlot", node, opts); } function assertObjectTypeCallProperty(node, opts = {}) { assert("ObjectTypeCallProperty", node, opts); } function assertObjectTypeIndexer(node, opts = {}) { assert("ObjectTypeIndexer", node, opts); } function assertObjectTypeProperty(node, opts = {}) { assert("ObjectTypeProperty", node, opts); } function assertObjectTypeSpreadProperty(node, opts = {}) { assert("ObjectTypeSpreadProperty", node, opts); } function assertOpaqueType(node, opts = {}) { assert("OpaqueType", node, opts); } function assertQualifiedTypeIdentifier(node, opts = {}) { assert("QualifiedTypeIdentifier", node, opts); } function assertStringLiteralTypeAnnotation(node, opts = {}) { assert("StringLiteralTypeAnnotation", node, opts); } function assertStringTypeAnnotation(node, opts = {}) { assert("StringTypeAnnotation", node, opts); } function assertThisTypeAnnotation(node, opts = {}) { assert("ThisTypeAnnotation", node, opts); } function assertTupleTypeAnnotation(node, opts = {}) { assert("TupleTypeAnnotation", node, opts); } function assertTypeofTypeAnnotation(node, opts = {}) { assert("TypeofTypeAnnotation", node, opts); } function assertTypeAlias(node, opts = {}) { assert("TypeAlias", node, opts); } function assertTypeAnnotation(node, opts = {}) { assert("TypeAnnotation", node, opts); } function assertTypeCastExpression(node, opts = {}) { assert("TypeCastExpression", node, opts); } function assertTypeParameter(node, opts = {}) { assert("TypeParameter", node, opts); } function assertTypeParameterDeclaration(node, opts = {}) { assert("TypeParameterDeclaration", node, opts); } function assertTypeParameterInstantiation(node, opts = {}) { assert("TypeParameterInstantiation", node, opts); } function assertUnionTypeAnnotation(node, opts = {}) { assert("UnionTypeAnnotation", node, opts); } function assertVariance(node, opts = {}) { assert("Variance", node, opts); } function assertVoidTypeAnnotation(node, opts = {}) { assert("VoidTypeAnnotation", node, opts); } function assertJSXAttribute(node, opts = {}) { assert("JSXAttribute", node, opts); } function assertJSXClosingElement(node, opts = {}) { assert("JSXClosingElement", node, opts); } function assertJSXElement(node, opts = {}) { assert("JSXElement", node, opts); } function assertJSXEmptyExpression(node, opts = {}) { assert("JSXEmptyExpression", node, opts); } function assertJSXExpressionContainer(node, opts = {}) { assert("JSXExpressionContainer", node, opts); } function assertJSXSpreadChild(node, opts = {}) { assert("JSXSpreadChild", node, opts); } function assertJSXIdentifier(node, opts = {}) { assert("JSXIdentifier", node, opts); } function assertJSXMemberExpression(node, opts = {}) { assert("JSXMemberExpression", node, opts); } function assertJSXNamespacedName(node, opts = {}) { assert("JSXNamespacedName", node, opts); } function assertJSXOpeningElement(node, opts = {}) { assert("JSXOpeningElement", node, opts); } function assertJSXSpreadAttribute(node, opts = {}) { assert("JSXSpreadAttribute", node, opts); } function assertJSXText(node, opts = {}) { assert("JSXText", node, opts); } function assertJSXFragment(node, opts = {}) { assert("JSXFragment", node, opts); } function assertJSXOpeningFragment(node, opts = {}) { assert("JSXOpeningFragment", node, opts); } function assertJSXClosingFragment(node, opts = {}) { assert("JSXClosingFragment", node, opts); } function assertNoop(node, opts = {}) { assert("Noop", node, opts); } function assertPlaceholder(node, opts = {}) { assert("Placeholder", node, opts); } function assertArgumentPlaceholder(node, opts = {}) { assert("ArgumentPlaceholder", node, opts); } function assertAwaitExpression(node, opts = {}) { assert("AwaitExpression", node, opts); } function assertBindExpression(node, opts = {}) { assert("BindExpression", node, opts); } function assertClassProperty(node, opts = {}) { assert("ClassProperty", node, opts); } function assertOptionalMemberExpression(node, opts = {}) { assert("OptionalMemberExpression", node, opts); } function assertPipelineTopicExpression(node, opts = {}) { assert("PipelineTopicExpression", node, opts); } function assertPipelineBareFunction(node, opts = {}) { assert("PipelineBareFunction", node, opts); } function assertPipelinePrimaryTopicReference(node, opts = {}) { assert("PipelinePrimaryTopicReference", node, opts); } function assertOptionalCallExpression(node, opts = {}) { assert("OptionalCallExpression", node, opts); } function assertClassPrivateProperty(node, opts = {}) { assert("ClassPrivateProperty", node, opts); } function assertClassPrivateMethod(node, opts = {}) { assert("ClassPrivateMethod", node, opts); } function assertImport(node, opts = {}) { assert("Import", node, opts); } function assertDecorator(node, opts = {}) { assert("Decorator", node, opts); } function assertDoExpression(node, opts = {}) { assert("DoExpression", node, opts); } function assertExportDefaultSpecifier(node, opts = {}) { assert("ExportDefaultSpecifier", node, opts); } function assertExportNamespaceSpecifier(node, opts = {}) { assert("ExportNamespaceSpecifier", node, opts); } function assertPrivateName(node, opts = {}) { assert("PrivateName", node, opts); } function assertBigIntLiteral(node, opts = {}) { assert("BigIntLiteral", node, opts); } function assertTSParameterProperty(node, opts = {}) { assert("TSParameterProperty", node, opts); } function assertTSDeclareFunction(node, opts = {}) { assert("TSDeclareFunction", node, opts); } function assertTSDeclareMethod(node, opts = {}) { assert("TSDeclareMethod", node, opts); } function assertTSQualifiedName(node, opts = {}) { assert("TSQualifiedName", node, opts); } function assertTSCallSignatureDeclaration(node, opts = {}) { assert("TSCallSignatureDeclaration", node, opts); } function assertTSConstructSignatureDeclaration(node, opts = {}) { assert("TSConstructSignatureDeclaration", node, opts); } function assertTSPropertySignature(node, opts = {}) { assert("TSPropertySignature", node, opts); } function assertTSMethodSignature(node, opts = {}) { assert("TSMethodSignature", node, opts); } function assertTSIndexSignature(node, opts = {}) { assert("TSIndexSignature", node, opts); } function assertTSAnyKeyword(node, opts = {}) { assert("TSAnyKeyword", node, opts); } function assertTSUnknownKeyword(node, opts = {}) { assert("TSUnknownKeyword", node, opts); } function assertTSNumberKeyword(node, opts = {}) { assert("TSNumberKeyword", node, opts); } function assertTSObjectKeyword(node, opts = {}) { assert("TSObjectKeyword", node, opts); } function assertTSBooleanKeyword(node, opts = {}) { assert("TSBooleanKeyword", node, opts); } function assertTSStringKeyword(node, opts = {}) { assert("TSStringKeyword", node, opts); } function assertTSSymbolKeyword(node, opts = {}) { assert("TSSymbolKeyword", node, opts); } function assertTSVoidKeyword(node, opts = {}) { assert("TSVoidKeyword", node, opts); } function assertTSUndefinedKeyword(node, opts = {}) { assert("TSUndefinedKeyword", node, opts); } function assertTSNullKeyword(node, opts = {}) { assert("TSNullKeyword", node, opts); } function assertTSNeverKeyword(node, opts = {}) { assert("TSNeverKeyword", node, opts); } function assertTSThisType(node, opts = {}) { assert("TSThisType", node, opts); } function assertTSFunctionType(node, opts = {}) { assert("TSFunctionType", node, opts); } function assertTSConstructorType(node, opts = {}) { assert("TSConstructorType", node, opts); } function assertTSTypeReference(node, opts = {}) { assert("TSTypeReference", node, opts); } function assertTSTypePredicate(node, opts = {}) { assert("TSTypePredicate", node, opts); } function assertTSTypeQuery(node, opts = {}) { assert("TSTypeQuery", node, opts); } function assertTSTypeLiteral(node, opts = {}) { assert("TSTypeLiteral", node, opts); } function assertTSArrayType(node, opts = {}) { assert("TSArrayType", node, opts); } function assertTSTupleType(node, opts = {}) { assert("TSTupleType", node, opts); } function assertTSOptionalType(node, opts = {}) { assert("TSOptionalType", node, opts); } function assertTSRestType(node, opts = {}) { assert("TSRestType", node, opts); } function assertTSUnionType(node, opts = {}) { assert("TSUnionType", node, opts); } function assertTSIntersectionType(node, opts = {}) { assert("TSIntersectionType", node, opts); } function assertTSConditionalType(node, opts = {}) { assert("TSConditionalType", node, opts); } function assertTSInferType(node, opts = {}) { assert("TSInferType", node, opts); } function assertTSParenthesizedType(node, opts = {}) { assert("TSParenthesizedType", node, opts); } function assertTSTypeOperator(node, opts = {}) { assert("TSTypeOperator", node, opts); } function assertTSIndexedAccessType(node, opts = {}) { assert("TSIndexedAccessType", node, opts); } function assertTSMappedType(node, opts = {}) { assert("TSMappedType", node, opts); } function assertTSLiteralType(node, opts = {}) { assert("TSLiteralType", node, opts); } function assertTSExpressionWithTypeArguments(node, opts = {}) { assert("TSExpressionWithTypeArguments", node, opts); } function assertTSInterfaceDeclaration(node, opts = {}) { assert("TSInterfaceDeclaration", node, opts); } function assertTSInterfaceBody(node, opts = {}) { assert("TSInterfaceBody", node, opts); } function assertTSTypeAliasDeclaration(node, opts = {}) { assert("TSTypeAliasDeclaration", node, opts); } function assertTSAsExpression(node, opts = {}) { assert("TSAsExpression", node, opts); } function assertTSTypeAssertion(node, opts = {}) { assert("TSTypeAssertion", node, opts); } function assertTSEnumDeclaration(node, opts = {}) { assert("TSEnumDeclaration", node, opts); } function assertTSEnumMember(node, opts = {}) { assert("TSEnumMember", node, opts); } function assertTSModuleDeclaration(node, opts = {}) { assert("TSModuleDeclaration", node, opts); } function assertTSModuleBlock(node, opts = {}) { assert("TSModuleBlock", node, opts); } function assertTSImportType(node, opts = {}) { assert("TSImportType", node, opts); } function assertTSImportEqualsDeclaration(node, opts = {}) { assert("TSImportEqualsDeclaration", node, opts); } function assertTSExternalModuleReference(node, opts = {}) { assert("TSExternalModuleReference", node, opts); } function assertTSNonNullExpression(node, opts = {}) { assert("TSNonNullExpression", node, opts); } function assertTSExportAssignment(node, opts = {}) { assert("TSExportAssignment", node, opts); } function assertTSNamespaceExportDeclaration(node, opts = {}) { assert("TSNamespaceExportDeclaration", node, opts); } function assertTSTypeAnnotation(node, opts = {}) { assert("TSTypeAnnotation", node, opts); } function assertTSTypeParameterInstantiation(node, opts = {}) { assert("TSTypeParameterInstantiation", node, opts); } function assertTSTypeParameterDeclaration(node, opts = {}) { assert("TSTypeParameterDeclaration", node, opts); } function assertTSTypeParameter(node, opts = {}) { assert("TSTypeParameter", node, opts); } function assertExpression(node, opts = {}) { assert("Expression", node, opts); } function assertBinary(node, opts = {}) { assert("Binary", node, opts); } function assertScopable(node, opts = {}) { assert("Scopable", node, opts); } function assertBlockParent(node, opts = {}) { assert("BlockParent", node, opts); } function assertBlock(node, opts = {}) { assert("Block", node, opts); } function assertStatement(node, opts = {}) { assert("Statement", node, opts); } function assertTerminatorless(node, opts = {}) { assert("Terminatorless", node, opts); } function assertCompletionStatement(node, opts = {}) { assert("CompletionStatement", node, opts); } function assertConditional(node, opts = {}) { assert("Conditional", node, opts); } function assertLoop(node, opts = {}) { assert("Loop", node, opts); } function assertWhile(node, opts = {}) { assert("While", node, opts); } function assertExpressionWrapper(node, opts = {}) { assert("ExpressionWrapper", node, opts); } function assertFor(node, opts = {}) { assert("For", node, opts); } function assertForXStatement(node, opts = {}) { assert("ForXStatement", node, opts); } function assertFunction(node, opts = {}) { assert("Function", node, opts); } function assertFunctionParent(node, opts = {}) { assert("FunctionParent", node, opts); } function assertPureish(node, opts = {}) { assert("Pureish", node, opts); } function assertDeclaration(node, opts = {}) { assert("Declaration", node, opts); } function assertPatternLike(node, opts = {}) { assert("PatternLike", node, opts); } function assertLVal(node, opts = {}) { assert("LVal", node, opts); } function assertTSEntityName(node, opts = {}) { assert("TSEntityName", node, opts); } function assertLiteral(node, opts = {}) { assert("Literal", node, opts); } function assertImmutable(node, opts = {}) { assert("Immutable", node, opts); } function assertUserWhitespacable(node, opts = {}) { assert("UserWhitespacable", node, opts); } function assertMethod(node, opts = {}) { assert("Method", node, opts); } function assertObjectMember(node, opts = {}) { assert("ObjectMember", node, opts); } function assertProperty(node, opts = {}) { assert("Property", node, opts); } function assertUnaryLike(node, opts = {}) { assert("UnaryLike", node, opts); } function assertPattern(node, opts = {}) { assert("Pattern", node, opts); } function assertClass(node, opts = {}) { assert("Class", node, opts); } function assertModuleDeclaration(node, opts = {}) { assert("ModuleDeclaration", node, opts); } function assertExportDeclaration(node, opts = {}) { assert("ExportDeclaration", node, opts); } function assertModuleSpecifier(node, opts = {}) { assert("ModuleSpecifier", node, opts); } function assertFlow(node, opts = {}) { assert("Flow", node, opts); } function assertFlowType(node, opts = {}) { assert("FlowType", node, opts); } function assertFlowBaseAnnotation(node, opts = {}) { assert("FlowBaseAnnotation", node, opts); } function assertFlowDeclaration(node, opts = {}) { assert("FlowDeclaration", node, opts); } function assertFlowPredicate(node, opts = {}) { assert("FlowPredicate", node, opts); } function assertJSX(node, opts = {}) { assert("JSX", node, opts); } function assertPrivate(node, opts = {}) { assert("Private", node, opts); } function assertTSTypeElement(node, opts = {}) { assert("TSTypeElement", node, opts); } function assertTSType(node, opts = {}) { assert("TSType", node, opts); } function assertNumberLiteral(node, opts) { console.trace("The node type NumberLiteral has been renamed to NumericLiteral"); assert("NumberLiteral", node, opts); } function assertRegexLiteral(node, opts) { console.trace("The node type RegexLiteral has been renamed to RegExpLiteral"); assert("RegexLiteral", node, opts); } function assertRestProperty(node, opts) { console.trace("The node type RestProperty has been renamed to RestElement"); assert("RestProperty", node, opts); } function assertSpreadProperty(node, opts) { console.trace("The node type SpreadProperty has been renamed to SpreadElement"); assert("SpreadProperty", node, opts); } },{"../../validators/is":158}],103:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = builder; function _clone() { const data = _interopRequireDefault(require("lodash/clone")); _clone = function () { return data; }; return data; } var _definitions = require("../definitions"); var _validate = _interopRequireDefault(require("../validators/validate")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function builder(type, ...args) { const keys = _definitions.BUILDER_KEYS[type]; const countArgs = args.length; if (countArgs > keys.length) { throw new Error(`${type}: Too many arguments passed. Received ${countArgs} but can receive no more than ${keys.length}`); } const node = { type }; let i = 0; keys.forEach(key => { const field = _definitions.NODE_FIELDS[type][key]; let arg; if (i < countArgs) arg = args[i]; if (arg === undefined) arg = (0, _clone().default)(field.default); node[key] = arg; i++; }); for (const key of Object.keys(node)) { (0, _validate.default)(node, key, node[key]); } return node; } },{"../definitions":136,"../validators/validate":176,"lodash/clone":360}],104:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = createTypeAnnotationBasedOnTypeof; var _generated = require("../generated"); function createTypeAnnotationBasedOnTypeof(type) { if (type === "string") { return (0, _generated.stringTypeAnnotation)(); } else if (type === "number") { return (0, _generated.numberTypeAnnotation)(); } else if (type === "undefined") { return (0, _generated.voidTypeAnnotation)(); } else if (type === "boolean") { return (0, _generated.booleanTypeAnnotation)(); } else if (type === "function") { return (0, _generated.genericTypeAnnotation)((0, _generated.identifier)("Function")); } else if (type === "object") { return (0, _generated.genericTypeAnnotation)((0, _generated.identifier)("Object")); } else if (type === "symbol") { return (0, _generated.genericTypeAnnotation)((0, _generated.identifier)("Symbol")); } else { throw new Error("Invalid typeof value"); } } },{"../generated":106}],105:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = createUnionTypeAnnotation; var _generated = require("../generated"); var _removeTypeDuplicates = _interopRequireDefault(require("../../modifications/flow/removeTypeDuplicates")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function createUnionTypeAnnotation(types) { const flattened = (0, _removeTypeDuplicates.default)(types); if (flattened.length === 1) { return flattened[0]; } else { return (0, _generated.unionTypeAnnotation)(flattened); } } },{"../../modifications/flow/removeTypeDuplicates":144,"../generated":106}],106:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.arrayExpression = exports.ArrayExpression = ArrayExpression; exports.assignmentExpression = exports.AssignmentExpression = AssignmentExpression; exports.binaryExpression = exports.BinaryExpression = BinaryExpression; exports.interpreterDirective = exports.InterpreterDirective = InterpreterDirective; exports.directive = exports.Directive = Directive; exports.directiveLiteral = exports.DirectiveLiteral = DirectiveLiteral; exports.blockStatement = exports.BlockStatement = BlockStatement; exports.breakStatement = exports.BreakStatement = BreakStatement; exports.callExpression = exports.CallExpression = CallExpression; exports.catchClause = exports.CatchClause = CatchClause; exports.conditionalExpression = exports.ConditionalExpression = ConditionalExpression; exports.continueStatement = exports.ContinueStatement = ContinueStatement; exports.debuggerStatement = exports.DebuggerStatement = DebuggerStatement; exports.doWhileStatement = exports.DoWhileStatement = DoWhileStatement; exports.emptyStatement = exports.EmptyStatement = EmptyStatement; exports.expressionStatement = exports.ExpressionStatement = ExpressionStatement; exports.file = exports.File = File; exports.forInStatement = exports.ForInStatement = ForInStatement; exports.forStatement = exports.ForStatement = ForStatement; exports.functionDeclaration = exports.FunctionDeclaration = FunctionDeclaration; exports.functionExpression = exports.FunctionExpression = FunctionExpression; exports.identifier = exports.Identifier = Identifier; exports.ifStatement = exports.IfStatement = IfStatement; exports.labeledStatement = exports.LabeledStatement = LabeledStatement; exports.stringLiteral = exports.StringLiteral = StringLiteral; exports.numericLiteral = exports.NumericLiteral = NumericLiteral; exports.nullLiteral = exports.NullLiteral = NullLiteral; exports.booleanLiteral = exports.BooleanLiteral = BooleanLiteral; exports.regExpLiteral = exports.RegExpLiteral = RegExpLiteral; exports.logicalExpression = exports.LogicalExpression = LogicalExpression; exports.memberExpression = exports.MemberExpression = MemberExpression; exports.newExpression = exports.NewExpression = NewExpression; exports.program = exports.Program = Program; exports.objectExpression = exports.ObjectExpression = ObjectExpression; exports.objectMethod = exports.ObjectMethod = ObjectMethod; exports.objectProperty = exports.ObjectProperty = ObjectProperty; exports.restElement = exports.RestElement = RestElement; exports.returnStatement = exports.ReturnStatement = ReturnStatement; exports.sequenceExpression = exports.SequenceExpression = SequenceExpression; exports.parenthesizedExpression = exports.ParenthesizedExpression = ParenthesizedExpression; exports.switchCase = exports.SwitchCase = SwitchCase; exports.switchStatement = exports.SwitchStatement = SwitchStatement; exports.thisExpression = exports.ThisExpression = ThisExpression; exports.throwStatement = exports.ThrowStatement = ThrowStatement; exports.tryStatement = exports.TryStatement = TryStatement; exports.unaryExpression = exports.UnaryExpression = UnaryExpression; exports.updateExpression = exports.UpdateExpression = UpdateExpression; exports.variableDeclaration = exports.VariableDeclaration = VariableDeclaration; exports.variableDeclarator = exports.VariableDeclarator = VariableDeclarator; exports.whileStatement = exports.WhileStatement = WhileStatement; exports.withStatement = exports.WithStatement = WithStatement; exports.assignmentPattern = exports.AssignmentPattern = AssignmentPattern; exports.arrayPattern = exports.ArrayPattern = ArrayPattern; exports.arrowFunctionExpression = exports.ArrowFunctionExpression = ArrowFunctionExpression; exports.classBody = exports.ClassBody = ClassBody; exports.classDeclaration = exports.ClassDeclaration = ClassDeclaration; exports.classExpression = exports.ClassExpression = ClassExpression; exports.exportAllDeclaration = exports.ExportAllDeclaration = ExportAllDeclaration; exports.exportDefaultDeclaration = exports.ExportDefaultDeclaration = ExportDefaultDeclaration; exports.exportNamedDeclaration = exports.ExportNamedDeclaration = ExportNamedDeclaration; exports.exportSpecifier = exports.ExportSpecifier = ExportSpecifier; exports.forOfStatement = exports.ForOfStatement = ForOfStatement; exports.importDeclaration = exports.ImportDeclaration = ImportDeclaration; exports.importDefaultSpecifier = exports.ImportDefaultSpecifier = ImportDefaultSpecifier; exports.importNamespaceSpecifier = exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier; exports.importSpecifier = exports.ImportSpecifier = ImportSpecifier; exports.metaProperty = exports.MetaProperty = MetaProperty; exports.classMethod = exports.ClassMethod = ClassMethod; exports.objectPattern = exports.ObjectPattern = ObjectPattern; exports.spreadElement = exports.SpreadElement = SpreadElement; exports.super = exports.Super = Super; exports.taggedTemplateExpression = exports.TaggedTemplateExpression = TaggedTemplateExpression; exports.templateElement = exports.TemplateElement = TemplateElement; exports.templateLiteral = exports.TemplateLiteral = TemplateLiteral; exports.yieldExpression = exports.YieldExpression = YieldExpression; exports.anyTypeAnnotation = exports.AnyTypeAnnotation = AnyTypeAnnotation; exports.arrayTypeAnnotation = exports.ArrayTypeAnnotation = ArrayTypeAnnotation; exports.booleanTypeAnnotation = exports.BooleanTypeAnnotation = BooleanTypeAnnotation; exports.booleanLiteralTypeAnnotation = exports.BooleanLiteralTypeAnnotation = BooleanLiteralTypeAnnotation; exports.nullLiteralTypeAnnotation = exports.NullLiteralTypeAnnotation = NullLiteralTypeAnnotation; exports.classImplements = exports.ClassImplements = ClassImplements; exports.declareClass = exports.DeclareClass = DeclareClass; exports.declareFunction = exports.DeclareFunction = DeclareFunction; exports.declareInterface = exports.DeclareInterface = DeclareInterface; exports.declareModule = exports.DeclareModule = DeclareModule; exports.declareModuleExports = exports.DeclareModuleExports = DeclareModuleExports; exports.declareTypeAlias = exports.DeclareTypeAlias = DeclareTypeAlias; exports.declareOpaqueType = exports.DeclareOpaqueType = DeclareOpaqueType; exports.declareVariable = exports.DeclareVariable = DeclareVariable; exports.declareExportDeclaration = exports.DeclareExportDeclaration = DeclareExportDeclaration; exports.declareExportAllDeclaration = exports.DeclareExportAllDeclaration = DeclareExportAllDeclaration; exports.declaredPredicate = exports.DeclaredPredicate = DeclaredPredicate; exports.existsTypeAnnotation = exports.ExistsTypeAnnotation = ExistsTypeAnnotation; exports.functionTypeAnnotation = exports.FunctionTypeAnnotation = FunctionTypeAnnotation; exports.functionTypeParam = exports.FunctionTypeParam = FunctionTypeParam; exports.genericTypeAnnotation = exports.GenericTypeAnnotation = GenericTypeAnnotation; exports.inferredPredicate = exports.InferredPredicate = InferredPredicate; exports.interfaceExtends = exports.InterfaceExtends = InterfaceExtends; exports.interfaceDeclaration = exports.InterfaceDeclaration = InterfaceDeclaration; exports.interfaceTypeAnnotation = exports.InterfaceTypeAnnotation = InterfaceTypeAnnotation; exports.intersectionTypeAnnotation = exports.IntersectionTypeAnnotation = IntersectionTypeAnnotation; exports.mixedTypeAnnotation = exports.MixedTypeAnnotation = MixedTypeAnnotation; exports.emptyTypeAnnotation = exports.EmptyTypeAnnotation = EmptyTypeAnnotation; exports.nullableTypeAnnotation = exports.NullableTypeAnnotation = NullableTypeAnnotation; exports.numberLiteralTypeAnnotation = exports.NumberLiteralTypeAnnotation = NumberLiteralTypeAnnotation; exports.numberTypeAnnotation = exports.NumberTypeAnnotation = NumberTypeAnnotation; exports.objectTypeAnnotation = exports.ObjectTypeAnnotation = ObjectTypeAnnotation; exports.objectTypeInternalSlot = exports.ObjectTypeInternalSlot = ObjectTypeInternalSlot; exports.objectTypeCallProperty = exports.ObjectTypeCallProperty = ObjectTypeCallProperty; exports.objectTypeIndexer = exports.ObjectTypeIndexer = ObjectTypeIndexer; exports.objectTypeProperty = exports.ObjectTypeProperty = ObjectTypeProperty; exports.objectTypeSpreadProperty = exports.ObjectTypeSpreadProperty = ObjectTypeSpreadProperty; exports.opaqueType = exports.OpaqueType = OpaqueType; exports.qualifiedTypeIdentifier = exports.QualifiedTypeIdentifier = QualifiedTypeIdentifier; exports.stringLiteralTypeAnnotation = exports.StringLiteralTypeAnnotation = StringLiteralTypeAnnotation; exports.stringTypeAnnotation = exports.StringTypeAnnotation = StringTypeAnnotation; exports.thisTypeAnnotation = exports.ThisTypeAnnotation = ThisTypeAnnotation; exports.tupleTypeAnnotation = exports.TupleTypeAnnotation = TupleTypeAnnotation; exports.typeofTypeAnnotation = exports.TypeofTypeAnnotation = TypeofTypeAnnotation; exports.typeAlias = exports.TypeAlias = TypeAlias; exports.typeAnnotation = exports.TypeAnnotation = TypeAnnotation; exports.typeCastExpression = exports.TypeCastExpression = TypeCastExpression; exports.typeParameter = exports.TypeParameter = TypeParameter; exports.typeParameterDeclaration = exports.TypeParameterDeclaration = TypeParameterDeclaration; exports.typeParameterInstantiation = exports.TypeParameterInstantiation = TypeParameterInstantiation; exports.unionTypeAnnotation = exports.UnionTypeAnnotation = UnionTypeAnnotation; exports.variance = exports.Variance = Variance; exports.voidTypeAnnotation = exports.VoidTypeAnnotation = VoidTypeAnnotation; exports.jSXAttribute = exports.jsxAttribute = exports.JSXAttribute = JSXAttribute; exports.jSXClosingElement = exports.jsxClosingElement = exports.JSXClosingElement = JSXClosingElement; exports.jSXElement = exports.jsxElement = exports.JSXElement = JSXElement; exports.jSXEmptyExpression = exports.jsxEmptyExpression = exports.JSXEmptyExpression = JSXEmptyExpression; exports.jSXExpressionContainer = exports.jsxExpressionContainer = exports.JSXExpressionContainer = JSXExpressionContainer; exports.jSXSpreadChild = exports.jsxSpreadChild = exports.JSXSpreadChild = JSXSpreadChild; exports.jSXIdentifier = exports.jsxIdentifier = exports.JSXIdentifier = JSXIdentifier; exports.jSXMemberExpression = exports.jsxMemberExpression = exports.JSXMemberExpression = JSXMemberExpression; exports.jSXNamespacedName = exports.jsxNamespacedName = exports.JSXNamespacedName = JSXNamespacedName; exports.jSXOpeningElement = exports.jsxOpeningElement = exports.JSXOpeningElement = JSXOpeningElement; exports.jSXSpreadAttribute = exports.jsxSpreadAttribute = exports.JSXSpreadAttribute = JSXSpreadAttribute; exports.jSXText = exports.jsxText = exports.JSXText = JSXText; exports.jSXFragment = exports.jsxFragment = exports.JSXFragment = JSXFragment; exports.jSXOpeningFragment = exports.jsxOpeningFragment = exports.JSXOpeningFragment = JSXOpeningFragment; exports.jSXClosingFragment = exports.jsxClosingFragment = exports.JSXClosingFragment = JSXClosingFragment; exports.noop = exports.Noop = Noop; exports.placeholder = exports.Placeholder = Placeholder; exports.argumentPlaceholder = exports.ArgumentPlaceholder = ArgumentPlaceholder; exports.awaitExpression = exports.AwaitExpression = AwaitExpression; exports.bindExpression = exports.BindExpression = BindExpression; exports.classProperty = exports.ClassProperty = ClassProperty; exports.optionalMemberExpression = exports.OptionalMemberExpression = OptionalMemberExpression; exports.pipelineTopicExpression = exports.PipelineTopicExpression = PipelineTopicExpression; exports.pipelineBareFunction = exports.PipelineBareFunction = PipelineBareFunction; exports.pipelinePrimaryTopicReference = exports.PipelinePrimaryTopicReference = PipelinePrimaryTopicReference; exports.optionalCallExpression = exports.OptionalCallExpression = OptionalCallExpression; exports.classPrivateProperty = exports.ClassPrivateProperty = ClassPrivateProperty; exports.classPrivateMethod = exports.ClassPrivateMethod = ClassPrivateMethod; exports.import = exports.Import = Import; exports.decorator = exports.Decorator = Decorator; exports.doExpression = exports.DoExpression = DoExpression; exports.exportDefaultSpecifier = exports.ExportDefaultSpecifier = ExportDefaultSpecifier; exports.exportNamespaceSpecifier = exports.ExportNamespaceSpecifier = ExportNamespaceSpecifier; exports.privateName = exports.PrivateName = PrivateName; exports.bigIntLiteral = exports.BigIntLiteral = BigIntLiteral; exports.tSParameterProperty = exports.tsParameterProperty = exports.TSParameterProperty = TSParameterProperty; exports.tSDeclareFunction = exports.tsDeclareFunction = exports.TSDeclareFunction = TSDeclareFunction; exports.tSDeclareMethod = exports.tsDeclareMethod = exports.TSDeclareMethod = TSDeclareMethod; exports.tSQualifiedName = exports.tsQualifiedName = exports.TSQualifiedName = TSQualifiedName; exports.tSCallSignatureDeclaration = exports.tsCallSignatureDeclaration = exports.TSCallSignatureDeclaration = TSCallSignatureDeclaration; exports.tSConstructSignatureDeclaration = exports.tsConstructSignatureDeclaration = exports.TSConstructSignatureDeclaration = TSConstructSignatureDeclaration; exports.tSPropertySignature = exports.tsPropertySignature = exports.TSPropertySignature = TSPropertySignature; exports.tSMethodSignature = exports.tsMethodSignature = exports.TSMethodSignature = TSMethodSignature; exports.tSIndexSignature = exports.tsIndexSignature = exports.TSIndexSignature = TSIndexSignature; exports.tSAnyKeyword = exports.tsAnyKeyword = exports.TSAnyKeyword = TSAnyKeyword; exports.tSUnknownKeyword = exports.tsUnknownKeyword = exports.TSUnknownKeyword = TSUnknownKeyword; exports.tSNumberKeyword = exports.tsNumberKeyword = exports.TSNumberKeyword = TSNumberKeyword; exports.tSObjectKeyword = exports.tsObjectKeyword = exports.TSObjectKeyword = TSObjectKeyword; exports.tSBooleanKeyword = exports.tsBooleanKeyword = exports.TSBooleanKeyword = TSBooleanKeyword; exports.tSStringKeyword = exports.tsStringKeyword = exports.TSStringKeyword = TSStringKeyword; exports.tSSymbolKeyword = exports.tsSymbolKeyword = exports.TSSymbolKeyword = TSSymbolKeyword; exports.tSVoidKeyword = exports.tsVoidKeyword = exports.TSVoidKeyword = TSVoidKeyword; exports.tSUndefinedKeyword = exports.tsUndefinedKeyword = exports.TSUndefinedKeyword = TSUndefinedKeyword; exports.tSNullKeyword = exports.tsNullKeyword = exports.TSNullKeyword = TSNullKeyword; exports.tSNeverKeyword = exports.tsNeverKeyword = exports.TSNeverKeyword = TSNeverKeyword; exports.tSThisType = exports.tsThisType = exports.TSThisType = TSThisType; exports.tSFunctionType = exports.tsFunctionType = exports.TSFunctionType = TSFunctionType; exports.tSConstructorType = exports.tsConstructorType = exports.TSConstructorType = TSConstructorType; exports.tSTypeReference = exports.tsTypeReference = exports.TSTypeReference = TSTypeReference; exports.tSTypePredicate = exports.tsTypePredicate = exports.TSTypePredicate = TSTypePredicate; exports.tSTypeQuery = exports.tsTypeQuery = exports.TSTypeQuery = TSTypeQuery; exports.tSTypeLiteral = exports.tsTypeLiteral = exports.TSTypeLiteral = TSTypeLiteral; exports.tSArrayType = exports.tsArrayType = exports.TSArrayType = TSArrayType; exports.tSTupleType = exports.tsTupleType = exports.TSTupleType = TSTupleType; exports.tSOptionalType = exports.tsOptionalType = exports.TSOptionalType = TSOptionalType; exports.tSRestType = exports.tsRestType = exports.TSRestType = TSRestType; exports.tSUnionType = exports.tsUnionType = exports.TSUnionType = TSUnionType; exports.tSIntersectionType = exports.tsIntersectionType = exports.TSIntersectionType = TSIntersectionType; exports.tSConditionalType = exports.tsConditionalType = exports.TSConditionalType = TSConditionalType; exports.tSInferType = exports.tsInferType = exports.TSInferType = TSInferType; exports.tSParenthesizedType = exports.tsParenthesizedType = exports.TSParenthesizedType = TSParenthesizedType; exports.tSTypeOperator = exports.tsTypeOperator = exports.TSTypeOperator = TSTypeOperator; exports.tSIndexedAccessType = exports.tsIndexedAccessType = exports.TSIndexedAccessType = TSIndexedAccessType; exports.tSMappedType = exports.tsMappedType = exports.TSMappedType = TSMappedType; exports.tSLiteralType = exports.tsLiteralType = exports.TSLiteralType = TSLiteralType; exports.tSExpressionWithTypeArguments = exports.tsExpressionWithTypeArguments = exports.TSExpressionWithTypeArguments = TSExpressionWithTypeArguments; exports.tSInterfaceDeclaration = exports.tsInterfaceDeclaration = exports.TSInterfaceDeclaration = TSInterfaceDeclaration; exports.tSInterfaceBody = exports.tsInterfaceBody = exports.TSInterfaceBody = TSInterfaceBody; exports.tSTypeAliasDeclaration = exports.tsTypeAliasDeclaration = exports.TSTypeAliasDeclaration = TSTypeAliasDeclaration; exports.tSAsExpression = exports.tsAsExpression = exports.TSAsExpression = TSAsExpression; exports.tSTypeAssertion = exports.tsTypeAssertion = exports.TSTypeAssertion = TSTypeAssertion; exports.tSEnumDeclaration = exports.tsEnumDeclaration = exports.TSEnumDeclaration = TSEnumDeclaration; exports.tSEnumMember = exports.tsEnumMember = exports.TSEnumMember = TSEnumMember; exports.tSModuleDeclaration = exports.tsModuleDeclaration = exports.TSModuleDeclaration = TSModuleDeclaration; exports.tSModuleBlock = exports.tsModuleBlock = exports.TSModuleBlock = TSModuleBlock; exports.tSImportType = exports.tsImportType = exports.TSImportType = TSImportType; exports.tSImportEqualsDeclaration = exports.tsImportEqualsDeclaration = exports.TSImportEqualsDeclaration = TSImportEqualsDeclaration; exports.tSExternalModuleReference = exports.tsExternalModuleReference = exports.TSExternalModuleReference = TSExternalModuleReference; exports.tSNonNullExpression = exports.tsNonNullExpression = exports.TSNonNullExpression = TSNonNullExpression; exports.tSExportAssignment = exports.tsExportAssignment = exports.TSExportAssignment = TSExportAssignment; exports.tSNamespaceExportDeclaration = exports.tsNamespaceExportDeclaration = exports.TSNamespaceExportDeclaration = TSNamespaceExportDeclaration; exports.tSTypeAnnotation = exports.tsTypeAnnotation = exports.TSTypeAnnotation = TSTypeAnnotation; exports.tSTypeParameterInstantiation = exports.tsTypeParameterInstantiation = exports.TSTypeParameterInstantiation = TSTypeParameterInstantiation; exports.tSTypeParameterDeclaration = exports.tsTypeParameterDeclaration = exports.TSTypeParameterDeclaration = TSTypeParameterDeclaration; exports.tSTypeParameter = exports.tsTypeParameter = exports.TSTypeParameter = TSTypeParameter; exports.numberLiteral = exports.NumberLiteral = NumberLiteral; exports.regexLiteral = exports.RegexLiteral = RegexLiteral; exports.restProperty = exports.RestProperty = RestProperty; exports.spreadProperty = exports.SpreadProperty = SpreadProperty; var _builder = _interopRequireDefault(require("../builder")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function ArrayExpression(...args) { return (0, _builder.default)("ArrayExpression", ...args); } function AssignmentExpression(...args) { return (0, _builder.default)("AssignmentExpression", ...args); } function BinaryExpression(...args) { return (0, _builder.default)("BinaryExpression", ...args); } function InterpreterDirective(...args) { return (0, _builder.default)("InterpreterDirective", ...args); } function Directive(...args) { return (0, _builder.default)("Directive", ...args); } function DirectiveLiteral(...args) { return (0, _builder.default)("DirectiveLiteral", ...args); } function BlockStatement(...args) { return (0, _builder.default)("BlockStatement", ...args); } function BreakStatement(...args) { return (0, _builder.default)("BreakStatement", ...args); } function CallExpression(...args) { return (0, _builder.default)("CallExpression", ...args); } function CatchClause(...args) { return (0, _builder.default)("CatchClause", ...args); } function ConditionalExpression(...args) { return (0, _builder.default)("ConditionalExpression", ...args); } function ContinueStatement(...args) { return (0, _builder.default)("ContinueStatement", ...args); } function DebuggerStatement(...args) { return (0, _builder.default)("DebuggerStatement", ...args); } function DoWhileStatement(...args) { return (0, _builder.default)("DoWhileStatement", ...args); } function EmptyStatement(...args) { return (0, _builder.default)("EmptyStatement", ...args); } function ExpressionStatement(...args) { return (0, _builder.default)("ExpressionStatement", ...args); } function File(...args) { return (0, _builder.default)("File", ...args); } function ForInStatement(...args) { return (0, _builder.default)("ForInStatement", ...args); } function ForStatement(...args) { return (0, _builder.default)("ForStatement", ...args); } function FunctionDeclaration(...args) { return (0, _builder.default)("FunctionDeclaration", ...args); } function FunctionExpression(...args) { return (0, _builder.default)("FunctionExpression", ...args); } function Identifier(...args) { return (0, _builder.default)("Identifier", ...args); } function IfStatement(...args) { return (0, _builder.default)("IfStatement", ...args); } function LabeledStatement(...args) { return (0, _builder.default)("LabeledStatement", ...args); } function StringLiteral(...args) { return (0, _builder.default)("StringLiteral", ...args); } function NumericLiteral(...args) { return (0, _builder.default)("NumericLiteral", ...args); } function NullLiteral(...args) { return (0, _builder.default)("NullLiteral", ...args); } function BooleanLiteral(...args) { return (0, _builder.default)("BooleanLiteral", ...args); } function RegExpLiteral(...args) { return (0, _builder.default)("RegExpLiteral", ...args); } function LogicalExpression(...args) { return (0, _builder.default)("LogicalExpression", ...args); } function MemberExpression(...args) { return (0, _builder.default)("MemberExpression", ...args); } function NewExpression(...args) { return (0, _builder.default)("NewExpression", ...args); } function Program(...args) { return (0, _builder.default)("Program", ...args); } function ObjectExpression(...args) { return (0, _builder.default)("ObjectExpression", ...args); } function ObjectMethod(...args) { return (0, _builder.default)("ObjectMethod", ...args); } function ObjectProperty(...args) { return (0, _builder.default)("ObjectProperty", ...args); } function RestElement(...args) { return (0, _builder.default)("RestElement", ...args); } function ReturnStatement(...args) { return (0, _builder.default)("ReturnStatement", ...args); } function SequenceExpression(...args) { return (0, _builder.default)("SequenceExpression", ...args); } function ParenthesizedExpression(...args) { return (0, _builder.default)("ParenthesizedExpression", ...args); } function SwitchCase(...args) { return (0, _builder.default)("SwitchCase", ...args); } function SwitchStatement(...args) { return (0, _builder.default)("SwitchStatement", ...args); } function ThisExpression(...args) { return (0, _builder.default)("ThisExpression", ...args); } function ThrowStatement(...args) { return (0, _builder.default)("ThrowStatement", ...args); } function TryStatement(...args) { return (0, _builder.default)("TryStatement", ...args); } function UnaryExpression(...args) { return (0, _builder.default)("UnaryExpression", ...args); } function UpdateExpression(...args) { return (0, _builder.default)("UpdateExpression", ...args); } function VariableDeclaration(...args) { return (0, _builder.default)("VariableDeclaration", ...args); } function VariableDeclarator(...args) { return (0, _builder.default)("VariableDeclarator", ...args); } function WhileStatement(...args) { return (0, _builder.default)("WhileStatement", ...args); } function WithStatement(...args) { return (0, _builder.default)("WithStatement", ...args); } function AssignmentPattern(...args) { return (0, _builder.default)("AssignmentPattern", ...args); } function ArrayPattern(...args) { return (0, _builder.default)("ArrayPattern", ...args); } function ArrowFunctionExpression(...args) { return (0, _builder.default)("ArrowFunctionExpression", ...args); } function ClassBody(...args) { return (0, _builder.default)("ClassBody", ...args); } function ClassDeclaration(...args) { return (0, _builder.default)("ClassDeclaration", ...args); } function ClassExpression(...args) { return (0, _builder.default)("ClassExpression", ...args); } function ExportAllDeclaration(...args) { return (0, _builder.default)("ExportAllDeclaration", ...args); } function ExportDefaultDeclaration(...args) { return (0, _builder.default)("ExportDefaultDeclaration", ...args); } function ExportNamedDeclaration(...args) { return (0, _builder.default)("ExportNamedDeclaration", ...args); } function ExportSpecifier(...args) { return (0, _builder.default)("ExportSpecifier", ...args); } function ForOfStatement(...args) { return (0, _builder.default)("ForOfStatement", ...args); } function ImportDeclaration(...args) { return (0, _builder.default)("ImportDeclaration", ...args); } function ImportDefaultSpecifier(...args) { return (0, _builder.default)("ImportDefaultSpecifier", ...args); } function ImportNamespaceSpecifier(...args) { return (0, _builder.default)("ImportNamespaceSpecifier", ...args); } function ImportSpecifier(...args) { return (0, _builder.default)("ImportSpecifier", ...args); } function MetaProperty(...args) { return (0, _builder.default)("MetaProperty", ...args); } function ClassMethod(...args) { return (0, _builder.default)("ClassMethod", ...args); } function ObjectPattern(...args) { return (0, _builder.default)("ObjectPattern", ...args); } function SpreadElement(...args) { return (0, _builder.default)("SpreadElement", ...args); } function Super(...args) { return (0, _builder.default)("Super", ...args); } function TaggedTemplateExpression(...args) { return (0, _builder.default)("TaggedTemplateExpression", ...args); } function TemplateElement(...args) { return (0, _builder.default)("TemplateElement", ...args); } function TemplateLiteral(...args) { return (0, _builder.default)("TemplateLiteral", ...args); } function YieldExpression(...args) { return (0, _builder.default)("YieldExpression", ...args); } function AnyTypeAnnotation(...args) { return (0, _builder.default)("AnyTypeAnnotation", ...args); } function ArrayTypeAnnotation(...args) { return (0, _builder.default)("ArrayTypeAnnotation", ...args); } function BooleanTypeAnnotation(...args) { return (0, _builder.default)("BooleanTypeAnnotation", ...args); } function BooleanLiteralTypeAnnotation(...args) { return (0, _builder.default)("BooleanLiteralTypeAnnotation", ...args); } function NullLiteralTypeAnnotation(...args) { return (0, _builder.default)("NullLiteralTypeAnnotation", ...args); } function ClassImplements(...args) { return (0, _builder.default)("ClassImplements", ...args); } function DeclareClass(...args) { return (0, _builder.default)("DeclareClass", ...args); } function DeclareFunction(...args) { return (0, _builder.default)("DeclareFunction", ...args); } function DeclareInterface(...args) { return (0, _builder.default)("DeclareInterface", ...args); } function DeclareModule(...args) { return (0, _builder.default)("DeclareModule", ...args); } function DeclareModuleExports(...args) { return (0, _builder.default)("DeclareModuleExports", ...args); } function DeclareTypeAlias(...args) { return (0, _builder.default)("DeclareTypeAlias", ...args); } function DeclareOpaqueType(...args) { return (0, _builder.default)("DeclareOpaqueType", ...args); } function DeclareVariable(...args) { return (0, _builder.default)("DeclareVariable", ...args); } function DeclareExportDeclaration(...args) { return (0, _builder.default)("DeclareExportDeclaration", ...args); } function DeclareExportAllDeclaration(...args) { return (0, _builder.default)("DeclareExportAllDeclaration", ...args); } function DeclaredPredicate(...args) { return (0, _builder.default)("DeclaredPredicate", ...args); } function ExistsTypeAnnotation(...args) { return (0, _builder.default)("ExistsTypeAnnotation", ...args); } function FunctionTypeAnnotation(...args) { return (0, _builder.default)("FunctionTypeAnnotation", ...args); } function FunctionTypeParam(...args) { return (0, _builder.default)("FunctionTypeParam", ...args); } function GenericTypeAnnotation(...args) { return (0, _builder.default)("GenericTypeAnnotation", ...args); } function InferredPredicate(...args) { return (0, _builder.default)("InferredPredicate", ...args); } function InterfaceExtends(...args) { return (0, _builder.default)("InterfaceExtends", ...args); } function InterfaceDeclaration(...args) { return (0, _builder.default)("InterfaceDeclaration", ...args); } function InterfaceTypeAnnotation(...args) { return (0, _builder.default)("InterfaceTypeAnnotation", ...args); } function IntersectionTypeAnnotation(...args) { return (0, _builder.default)("IntersectionTypeAnnotation", ...args); } function MixedTypeAnnotation(...args) { return (0, _builder.default)("MixedTypeAnnotation", ...args); } function EmptyTypeAnnotation(...args) { return (0, _builder.default)("EmptyTypeAnnotation", ...args); } function NullableTypeAnnotation(...args) { return (0, _builder.default)("NullableTypeAnnotation", ...args); } function NumberLiteralTypeAnnotation(...args) { return (0, _builder.default)("NumberLiteralTypeAnnotation", ...args); } function NumberTypeAnnotation(...args) { return (0, _builder.default)("NumberTypeAnnotation", ...args); } function ObjectTypeAnnotation(...args) { return (0, _builder.default)("ObjectTypeAnnotation", ...args); } function ObjectTypeInternalSlot(...args) { return (0, _builder.default)("ObjectTypeInternalSlot", ...args); } function ObjectTypeCallProperty(...args) { return (0, _builder.default)("ObjectTypeCallProperty", ...args); } function ObjectTypeIndexer(...args) { return (0, _builder.default)("ObjectTypeIndexer", ...args); } function ObjectTypeProperty(...args) { return (0, _builder.default)("ObjectTypeProperty", ...args); } function ObjectTypeSpreadProperty(...args) { return (0, _builder.default)("ObjectTypeSpreadProperty", ...args); } function OpaqueType(...args) { return (0, _builder.default)("OpaqueType", ...args); } function QualifiedTypeIdentifier(...args) { return (0, _builder.default)("QualifiedTypeIdentifier", ...args); } function StringLiteralTypeAnnotation(...args) { return (0, _builder.default)("StringLiteralTypeAnnotation", ...args); } function StringTypeAnnotation(...args) { return (0, _builder.default)("StringTypeAnnotation", ...args); } function ThisTypeAnnotation(...args) { return (0, _builder.default)("ThisTypeAnnotation", ...args); } function TupleTypeAnnotation(...args) { return (0, _builder.default)("TupleTypeAnnotation", ...args); } function TypeofTypeAnnotation(...args) { return (0, _builder.default)("TypeofTypeAnnotation", ...args); } function TypeAlias(...args) { return (0, _builder.default)("TypeAlias", ...args); } function TypeAnnotation(...args) { return (0, _builder.default)("TypeAnnotation", ...args); } function TypeCastExpression(...args) { return (0, _builder.default)("TypeCastExpression", ...args); } function TypeParameter(...args) { return (0, _builder.default)("TypeParameter", ...args); } function TypeParameterDeclaration(...args) { return (0, _builder.default)("TypeParameterDeclaration", ...args); } function TypeParameterInstantiation(...args) { return (0, _builder.default)("TypeParameterInstantiation", ...args); } function UnionTypeAnnotation(...args) { return (0, _builder.default)("UnionTypeAnnotation", ...args); } function Variance(...args) { return (0, _builder.default)("Variance", ...args); } function VoidTypeAnnotation(...args) { return (0, _builder.default)("VoidTypeAnnotation", ...args); } function JSXAttribute(...args) { return (0, _builder.default)("JSXAttribute", ...args); } function JSXClosingElement(...args) { return (0, _builder.default)("JSXClosingElement", ...args); } function JSXElement(...args) { return (0, _builder.default)("JSXElement", ...args); } function JSXEmptyExpression(...args) { return (0, _builder.default)("JSXEmptyExpression", ...args); } function JSXExpressionContainer(...args) { return (0, _builder.default)("JSXExpressionContainer", ...args); } function JSXSpreadChild(...args) { return (0, _builder.default)("JSXSpreadChild", ...args); } function JSXIdentifier(...args) { return (0, _builder.default)("JSXIdentifier", ...args); } function JSXMemberExpression(...args) { return (0, _builder.default)("JSXMemberExpression", ...args); } function JSXNamespacedName(...args) { return (0, _builder.default)("JSXNamespacedName", ...args); } function JSXOpeningElement(...args) { return (0, _builder.default)("JSXOpeningElement", ...args); } function JSXSpreadAttribute(...args) { return (0, _builder.default)("JSXSpreadAttribute", ...args); } function JSXText(...args) { return (0, _builder.default)("JSXText", ...args); } function JSXFragment(...args) { return (0, _builder.default)("JSXFragment", ...args); } function JSXOpeningFragment(...args) { return (0, _builder.default)("JSXOpeningFragment", ...args); } function JSXClosingFragment(...args) { return (0, _builder.default)("JSXClosingFragment", ...args); } function Noop(...args) { return (0, _builder.default)("Noop", ...args); } function Placeholder(...args) { return (0, _builder.default)("Placeholder", ...args); } function ArgumentPlaceholder(...args) { return (0, _builder.default)("ArgumentPlaceholder", ...args); } function AwaitExpression(...args) { return (0, _builder.default)("AwaitExpression", ...args); } function BindExpression(...args) { return (0, _builder.default)("BindExpression", ...args); } function ClassProperty(...args) { return (0, _builder.default)("ClassProperty", ...args); } function OptionalMemberExpression(...args) { return (0, _builder.default)("OptionalMemberExpression", ...args); } function PipelineTopicExpression(...args) { return (0, _builder.default)("PipelineTopicExpression", ...args); } function PipelineBareFunction(...args) { return (0, _builder.default)("PipelineBareFunction", ...args); } function PipelinePrimaryTopicReference(...args) { return (0, _builder.default)("PipelinePrimaryTopicReference", ...args); } function OptionalCallExpression(...args) { return (0, _builder.default)("OptionalCallExpression", ...args); } function ClassPrivateProperty(...args) { return (0, _builder.default)("ClassPrivateProperty", ...args); } function ClassPrivateMethod(...args) { return (0, _builder.default)("ClassPrivateMethod", ...args); } function Import(...args) { return (0, _builder.default)("Import", ...args); } function Decorator(...args) { return (0, _builder.default)("Decorator", ...args); } function DoExpression(...args) { return (0, _builder.default)("DoExpression", ...args); } function ExportDefaultSpecifier(...args) { return (0, _builder.default)("ExportDefaultSpecifier", ...args); } function ExportNamespaceSpecifier(...args) { return (0, _builder.default)("ExportNamespaceSpecifier", ...args); } function PrivateName(...args) { return (0, _builder.default)("PrivateName", ...args); } function BigIntLiteral(...args) { return (0, _builder.default)("BigIntLiteral", ...args); } function TSParameterProperty(...args) { return (0, _builder.default)("TSParameterProperty", ...args); } function TSDeclareFunction(...args) { return (0, _builder.default)("TSDeclareFunction", ...args); } function TSDeclareMethod(...args) { return (0, _builder.default)("TSDeclareMethod", ...args); } function TSQualifiedName(...args) { return (0, _builder.default)("TSQualifiedName", ...args); } function TSCallSignatureDeclaration(...args) { return (0, _builder.default)("TSCallSignatureDeclaration", ...args); } function TSConstructSignatureDeclaration(...args) { return (0, _builder.default)("TSConstructSignatureDeclaration", ...args); } function TSPropertySignature(...args) { return (0, _builder.default)("TSPropertySignature", ...args); } function TSMethodSignature(...args) { return (0, _builder.default)("TSMethodSignature", ...args); } function TSIndexSignature(...args) { return (0, _builder.default)("TSIndexSignature", ...args); } function TSAnyKeyword(...args) { return (0, _builder.default)("TSAnyKeyword", ...args); } function TSUnknownKeyword(...args) { return (0, _builder.default)("TSUnknownKeyword", ...args); } function TSNumberKeyword(...args) { return (0, _builder.default)("TSNumberKeyword", ...args); } function TSObjectKeyword(...args) { return (0, _builder.default)("TSObjectKeyword", ...args); } function TSBooleanKeyword(...args) { return (0, _builder.default)("TSBooleanKeyword", ...args); } function TSStringKeyword(...args) { return (0, _builder.default)("TSStringKeyword", ...args); } function TSSymbolKeyword(...args) { return (0, _builder.default)("TSSymbolKeyword", ...args); } function TSVoidKeyword(...args) { return (0, _builder.default)("TSVoidKeyword", ...args); } function TSUndefinedKeyword(...args) { return (0, _builder.default)("TSUndefinedKeyword", ...args); } function TSNullKeyword(...args) { return (0, _builder.default)("TSNullKeyword", ...args); } function TSNeverKeyword(...args) { return (0, _builder.default)("TSNeverKeyword", ...args); } function TSThisType(...args) { return (0, _builder.default)("TSThisType", ...args); } function TSFunctionType(...args) { return (0, _builder.default)("TSFunctionType", ...args); } function TSConstructorType(...args) { return (0, _builder.default)("TSConstructorType", ...args); } function TSTypeReference(...args) { return (0, _builder.default)("TSTypeReference", ...args); } function TSTypePredicate(...args) { return (0, _builder.default)("TSTypePredicate", ...args); } function TSTypeQuery(...args) { return (0, _builder.default)("TSTypeQuery", ...args); } function TSTypeLiteral(...args) { return (0, _builder.default)("TSTypeLiteral", ...args); } function TSArrayType(...args) { return (0, _builder.default)("TSArrayType", ...args); } function TSTupleType(...args) { return (0, _builder.default)("TSTupleType", ...args); } function TSOptionalType(...args) { return (0, _builder.default)("TSOptionalType", ...args); } function TSRestType(...args) { return (0, _builder.default)("TSRestType", ...args); } function TSUnionType(...args) { return (0, _builder.default)("TSUnionType", ...args); } function TSIntersectionType(...args) { return (0, _builder.default)("TSIntersectionType", ...args); } function TSConditionalType(...args) { return (0, _builder.default)("TSConditionalType", ...args); } function TSInferType(...args) { return (0, _builder.default)("TSInferType", ...args); } function TSParenthesizedType(...args) { return (0, _builder.default)("TSParenthesizedType", ...args); } function TSTypeOperator(...args) { return (0, _builder.default)("TSTypeOperator", ...args); } function TSIndexedAccessType(...args) { return (0, _builder.default)("TSIndexedAccessType", ...args); } function TSMappedType(...args) { return (0, _builder.default)("TSMappedType", ...args); } function TSLiteralType(...args) { return (0, _builder.default)("TSLiteralType", ...args); } function TSExpressionWithTypeArguments(...args) { return (0, _builder.default)("TSExpressionWithTypeArguments", ...args); } function TSInterfaceDeclaration(...args) { return (0, _builder.default)("TSInterfaceDeclaration", ...args); } function TSInterfaceBody(...args) { return (0, _builder.default)("TSInterfaceBody", ...args); } function TSTypeAliasDeclaration(...args) { return (0, _builder.default)("TSTypeAliasDeclaration", ...args); } function TSAsExpression(...args) { return (0, _builder.default)("TSAsExpression", ...args); } function TSTypeAssertion(...args) { return (0, _builder.default)("TSTypeAssertion", ...args); } function TSEnumDeclaration(...args) { return (0, _builder.default)("TSEnumDeclaration", ...args); } function TSEnumMember(...args) { return (0, _builder.default)("TSEnumMember", ...args); } function TSModuleDeclaration(...args) { return (0, _builder.default)("TSModuleDeclaration", ...args); } function TSModuleBlock(...args) { return (0, _builder.default)("TSModuleBlock", ...args); } function TSImportType(...args) { return (0, _builder.default)("TSImportType", ...args); } function TSImportEqualsDeclaration(...args) { return (0, _builder.default)("TSImportEqualsDeclaration", ...args); } function TSExternalModuleReference(...args) { return (0, _builder.default)("TSExternalModuleReference", ...args); } function TSNonNullExpression(...args) { return (0, _builder.default)("TSNonNullExpression", ...args); } function TSExportAssignment(...args) { return (0, _builder.default)("TSExportAssignment", ...args); } function TSNamespaceExportDeclaration(...args) { return (0, _builder.default)("TSNamespaceExportDeclaration", ...args); } function TSTypeAnnotation(...args) { return (0, _builder.default)("TSTypeAnnotation", ...args); } function TSTypeParameterInstantiation(...args) { return (0, _builder.default)("TSTypeParameterInstantiation", ...args); } function TSTypeParameterDeclaration(...args) { return (0, _builder.default)("TSTypeParameterDeclaration", ...args); } function TSTypeParameter(...args) { return (0, _builder.default)("TSTypeParameter", ...args); } function NumberLiteral(...args) { console.trace("The node type NumberLiteral has been renamed to NumericLiteral"); return NumberLiteral("NumberLiteral", ...args); } function RegexLiteral(...args) { console.trace("The node type RegexLiteral has been renamed to RegExpLiteral"); return RegexLiteral("RegexLiteral", ...args); } function RestProperty(...args) { console.trace("The node type RestProperty has been renamed to RestElement"); return RestProperty("RestProperty", ...args); } function SpreadProperty(...args) { console.trace("The node type SpreadProperty has been renamed to SpreadElement"); return SpreadProperty("SpreadProperty", ...args); } },{"../builder":103}],107:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = buildChildren; var _generated = require("../../validators/generated"); var _cleanJSXElementLiteralChild = _interopRequireDefault(require("../../utils/react/cleanJSXElementLiteralChild")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function buildChildren(node) { const elements = []; for (let i = 0; i < node.children.length; i++) { let child = node.children[i]; if ((0, _generated.isJSXText)(child)) { (0, _cleanJSXElementLiteralChild.default)(child, elements); continue; } if ((0, _generated.isJSXExpressionContainer)(child)) child = child.expression; if ((0, _generated.isJSXEmptyExpression)(child)) continue; elements.push(child); } return elements; } },{"../../utils/react/cleanJSXElementLiteralChild":154,"../../validators/generated":157}],108:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = clone; var _cloneNode = _interopRequireDefault(require("./cloneNode")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function clone(node) { return (0, _cloneNode.default)(node, false); } },{"./cloneNode":110}],109:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = cloneDeep; var _cloneNode = _interopRequireDefault(require("./cloneNode")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function cloneDeep(node) { return (0, _cloneNode.default)(node); } },{"./cloneNode":110}],110:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = cloneNode; var _definitions = require("../definitions"); const has = Function.call.bind(Object.prototype.hasOwnProperty); function cloneIfNode(obj, deep) { if (obj && typeof obj.type === "string" && obj.type !== "CommentLine" && obj.type !== "CommentBlock") { return cloneNode(obj, deep); } return obj; } function cloneIfNodeOrArray(obj, deep) { if (Array.isArray(obj)) { return obj.map(node => cloneIfNode(node, deep)); } return cloneIfNode(obj, deep); } function cloneNode(node, deep = true) { if (!node) return node; const { type } = node; const newNode = { type }; if (type === "Identifier") { newNode.name = node.name; if (has(node, "optional") && typeof node.optional === "boolean") { newNode.optional = node.optional; } if (has(node, "typeAnnotation")) { newNode.typeAnnotation = deep ? cloneIfNodeOrArray(node.typeAnnotation, true) : node.typeAnnotation; } } else if (!has(_definitions.NODE_FIELDS, type)) { throw new Error(`Unknown node type: "${type}"`); } else { for (const field of Object.keys(_definitions.NODE_FIELDS[type])) { if (has(node, field)) { newNode[field] = deep ? cloneIfNodeOrArray(node[field], true) : node[field]; } } } if (has(node, "loc")) { newNode.loc = node.loc; } if (has(node, "leadingComments")) { newNode.leadingComments = node.leadingComments; } if (has(node, "innerComments")) { newNode.innerComments = node.innerComments; } if (has(node, "trailingComments")) { newNode.trailingComments = node.trailingComments; } if (has(node, "extra")) { newNode.extra = Object.assign({}, node.extra); } return newNode; } },{"../definitions":136}],111:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = cloneWithoutLoc; var _clone = _interopRequireDefault(require("./clone")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function cloneWithoutLoc(node) { const newNode = (0, _clone.default)(node); newNode.loc = null; return newNode; } },{"./clone":108}],112:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = addComment; var _addComments = _interopRequireDefault(require("./addComments")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function addComment(node, type, content, line) { return (0, _addComments.default)(node, type, [{ type: line ? "CommentLine" : "CommentBlock", value: content }]); } },{"./addComments":113}],113:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = addComments; function addComments(node, type, comments) { if (!comments || !node) return node; const key = `${type}Comments`; if (node[key]) { if (type === "leading") { node[key] = comments.concat(node[key]); } else { node[key] = node[key].concat(comments); } } else { node[key] = comments; } return node; } },{}],114:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = inheritInnerComments; var _inherit = _interopRequireDefault(require("../utils/inherit")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function inheritInnerComments(child, parent) { (0, _inherit.default)("innerComments", child, parent); } },{"../utils/inherit":153}],115:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = inheritLeadingComments; var _inherit = _interopRequireDefault(require("../utils/inherit")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function inheritLeadingComments(child, parent) { (0, _inherit.default)("leadingComments", child, parent); } },{"../utils/inherit":153}],116:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = inheritTrailingComments; var _inherit = _interopRequireDefault(require("../utils/inherit")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function inheritTrailingComments(child, parent) { (0, _inherit.default)("trailingComments", child, parent); } },{"../utils/inherit":153}],117:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = inheritsComments; var _inheritTrailingComments = _interopRequireDefault(require("./inheritTrailingComments")); var _inheritLeadingComments = _interopRequireDefault(require("./inheritLeadingComments")); var _inheritInnerComments = _interopRequireDefault(require("./inheritInnerComments")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function inheritsComments(child, parent) { (0, _inheritTrailingComments.default)(child, parent); (0, _inheritLeadingComments.default)(child, parent); (0, _inheritInnerComments.default)(child, parent); return child; } },{"./inheritInnerComments":114,"./inheritLeadingComments":115,"./inheritTrailingComments":116}],118:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = removeComments; var _constants = require("../constants"); function removeComments(node) { _constants.COMMENT_KEYS.forEach(key => { node[key] = null; }); return node; } },{"../constants":120}],119:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TSTYPE_TYPES = exports.TSTYPEELEMENT_TYPES = exports.PRIVATE_TYPES = exports.JSX_TYPES = exports.FLOWPREDICATE_TYPES = exports.FLOWDECLARATION_TYPES = exports.FLOWBASEANNOTATION_TYPES = exports.FLOWTYPE_TYPES = exports.FLOW_TYPES = exports.MODULESPECIFIER_TYPES = exports.EXPORTDECLARATION_TYPES = exports.MODULEDECLARATION_TYPES = exports.CLASS_TYPES = exports.PATTERN_TYPES = exports.UNARYLIKE_TYPES = exports.PROPERTY_TYPES = exports.OBJECTMEMBER_TYPES = exports.METHOD_TYPES = exports.USERWHITESPACABLE_TYPES = exports.IMMUTABLE_TYPES = exports.LITERAL_TYPES = exports.TSENTITYNAME_TYPES = exports.LVAL_TYPES = exports.PATTERNLIKE_TYPES = exports.DECLARATION_TYPES = exports.PUREISH_TYPES = exports.FUNCTIONPARENT_TYPES = exports.FUNCTION_TYPES = exports.FORXSTATEMENT_TYPES = exports.FOR_TYPES = exports.EXPRESSIONWRAPPER_TYPES = exports.WHILE_TYPES = exports.LOOP_TYPES = exports.CONDITIONAL_TYPES = exports.COMPLETIONSTATEMENT_TYPES = exports.TERMINATORLESS_TYPES = exports.STATEMENT_TYPES = exports.BLOCK_TYPES = exports.BLOCKPARENT_TYPES = exports.SCOPABLE_TYPES = exports.BINARY_TYPES = exports.EXPRESSION_TYPES = void 0; var _definitions = require("../../definitions"); const EXPRESSION_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Expression"]; exports.EXPRESSION_TYPES = EXPRESSION_TYPES; const BINARY_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Binary"]; exports.BINARY_TYPES = BINARY_TYPES; const SCOPABLE_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Scopable"]; exports.SCOPABLE_TYPES = SCOPABLE_TYPES; const BLOCKPARENT_TYPES = _definitions.FLIPPED_ALIAS_KEYS["BlockParent"]; exports.BLOCKPARENT_TYPES = BLOCKPARENT_TYPES; const BLOCK_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Block"]; exports.BLOCK_TYPES = BLOCK_TYPES; const STATEMENT_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Statement"]; exports.STATEMENT_TYPES = STATEMENT_TYPES; const TERMINATORLESS_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Terminatorless"]; exports.TERMINATORLESS_TYPES = TERMINATORLESS_TYPES; const COMPLETIONSTATEMENT_TYPES = _definitions.FLIPPED_ALIAS_KEYS["CompletionStatement"]; exports.COMPLETIONSTATEMENT_TYPES = COMPLETIONSTATEMENT_TYPES; const CONDITIONAL_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Conditional"]; exports.CONDITIONAL_TYPES = CONDITIONAL_TYPES; const LOOP_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Loop"]; exports.LOOP_TYPES = LOOP_TYPES; const WHILE_TYPES = _definitions.FLIPPED_ALIAS_KEYS["While"]; exports.WHILE_TYPES = WHILE_TYPES; const EXPRESSIONWRAPPER_TYPES = _definitions.FLIPPED_ALIAS_KEYS["ExpressionWrapper"]; exports.EXPRESSIONWRAPPER_TYPES = EXPRESSIONWRAPPER_TYPES; const FOR_TYPES = _definitions.FLIPPED_ALIAS_KEYS["For"]; exports.FOR_TYPES = FOR_TYPES; const FORXSTATEMENT_TYPES = _definitions.FLIPPED_ALIAS_KEYS["ForXStatement"]; exports.FORXSTATEMENT_TYPES = FORXSTATEMENT_TYPES; const FUNCTION_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Function"]; exports.FUNCTION_TYPES = FUNCTION_TYPES; const FUNCTIONPARENT_TYPES = _definitions.FLIPPED_ALIAS_KEYS["FunctionParent"]; exports.FUNCTIONPARENT_TYPES = FUNCTIONPARENT_TYPES; const PUREISH_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Pureish"]; exports.PUREISH_TYPES = PUREISH_TYPES; const DECLARATION_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Declaration"]; exports.DECLARATION_TYPES = DECLARATION_TYPES; const PATTERNLIKE_TYPES = _definitions.FLIPPED_ALIAS_KEYS["PatternLike"]; exports.PATTERNLIKE_TYPES = PATTERNLIKE_TYPES; const LVAL_TYPES = _definitions.FLIPPED_ALIAS_KEYS["LVal"]; exports.LVAL_TYPES = LVAL_TYPES; const TSENTITYNAME_TYPES = _definitions.FLIPPED_ALIAS_KEYS["TSEntityName"]; exports.TSENTITYNAME_TYPES = TSENTITYNAME_TYPES; const LITERAL_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Literal"]; exports.LITERAL_TYPES = LITERAL_TYPES; const IMMUTABLE_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Immutable"]; exports.IMMUTABLE_TYPES = IMMUTABLE_TYPES; const USERWHITESPACABLE_TYPES = _definitions.FLIPPED_ALIAS_KEYS["UserWhitespacable"]; exports.USERWHITESPACABLE_TYPES = USERWHITESPACABLE_TYPES; const METHOD_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Method"]; exports.METHOD_TYPES = METHOD_TYPES; const OBJECTMEMBER_TYPES = _definitions.FLIPPED_ALIAS_KEYS["ObjectMember"]; exports.OBJECTMEMBER_TYPES = OBJECTMEMBER_TYPES; const PROPERTY_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Property"]; exports.PROPERTY_TYPES = PROPERTY_TYPES; const UNARYLIKE_TYPES = _definitions.FLIPPED_ALIAS_KEYS["UnaryLike"]; exports.UNARYLIKE_TYPES = UNARYLIKE_TYPES; const PATTERN_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Pattern"]; exports.PATTERN_TYPES = PATTERN_TYPES; const CLASS_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Class"]; exports.CLASS_TYPES = CLASS_TYPES; const MODULEDECLARATION_TYPES = _definitions.FLIPPED_ALIAS_KEYS["ModuleDeclaration"]; exports.MODULEDECLARATION_TYPES = MODULEDECLARATION_TYPES; const EXPORTDECLARATION_TYPES = _definitions.FLIPPED_ALIAS_KEYS["ExportDeclaration"]; exports.EXPORTDECLARATION_TYPES = EXPORTDECLARATION_TYPES; const MODULESPECIFIER_TYPES = _definitions.FLIPPED_ALIAS_KEYS["ModuleSpecifier"]; exports.MODULESPECIFIER_TYPES = MODULESPECIFIER_TYPES; const FLOW_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Flow"]; exports.FLOW_TYPES = FLOW_TYPES; const FLOWTYPE_TYPES = _definitions.FLIPPED_ALIAS_KEYS["FlowType"]; exports.FLOWTYPE_TYPES = FLOWTYPE_TYPES; const FLOWBASEANNOTATION_TYPES = _definitions.FLIPPED_ALIAS_KEYS["FlowBaseAnnotation"]; exports.FLOWBASEANNOTATION_TYPES = FLOWBASEANNOTATION_TYPES; const FLOWDECLARATION_TYPES = _definitions.FLIPPED_ALIAS_KEYS["FlowDeclaration"]; exports.FLOWDECLARATION_TYPES = FLOWDECLARATION_TYPES; const FLOWPREDICATE_TYPES = _definitions.FLIPPED_ALIAS_KEYS["FlowPredicate"]; exports.FLOWPREDICATE_TYPES = FLOWPREDICATE_TYPES; const JSX_TYPES = _definitions.FLIPPED_ALIAS_KEYS["JSX"]; exports.JSX_TYPES = JSX_TYPES; const PRIVATE_TYPES = _definitions.FLIPPED_ALIAS_KEYS["Private"]; exports.PRIVATE_TYPES = PRIVATE_TYPES; const TSTYPEELEMENT_TYPES = _definitions.FLIPPED_ALIAS_KEYS["TSTypeElement"]; exports.TSTYPEELEMENT_TYPES = TSTYPEELEMENT_TYPES; const TSTYPE_TYPES = _definitions.FLIPPED_ALIAS_KEYS["TSType"]; exports.TSTYPE_TYPES = TSTYPE_TYPES; },{"../../definitions":136}],120:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.NOT_LOCAL_BINDING = exports.BLOCK_SCOPED_SYMBOL = exports.INHERIT_KEYS = exports.UNARY_OPERATORS = exports.STRING_UNARY_OPERATORS = exports.NUMBER_UNARY_OPERATORS = exports.BOOLEAN_UNARY_OPERATORS = exports.BINARY_OPERATORS = exports.NUMBER_BINARY_OPERATORS = exports.BOOLEAN_BINARY_OPERATORS = exports.COMPARISON_BINARY_OPERATORS = exports.EQUALITY_BINARY_OPERATORS = exports.BOOLEAN_NUMBER_BINARY_OPERATORS = exports.UPDATE_OPERATORS = exports.LOGICAL_OPERATORS = exports.COMMENT_KEYS = exports.FOR_INIT_KEYS = exports.FLATTENABLE_KEYS = exports.STATEMENT_OR_BLOCK_KEYS = void 0; const STATEMENT_OR_BLOCK_KEYS = ["consequent", "body", "alternate"]; exports.STATEMENT_OR_BLOCK_KEYS = STATEMENT_OR_BLOCK_KEYS; const FLATTENABLE_KEYS = ["body", "expressions"]; exports.FLATTENABLE_KEYS = FLATTENABLE_KEYS; const FOR_INIT_KEYS = ["left", "init"]; exports.FOR_INIT_KEYS = FOR_INIT_KEYS; const COMMENT_KEYS = ["leadingComments", "trailingComments", "innerComments"]; exports.COMMENT_KEYS = COMMENT_KEYS; const LOGICAL_OPERATORS = ["||", "&&", "??"]; exports.LOGICAL_OPERATORS = LOGICAL_OPERATORS; const UPDATE_OPERATORS = ["++", "--"]; exports.UPDATE_OPERATORS = UPDATE_OPERATORS; const BOOLEAN_NUMBER_BINARY_OPERATORS = [">", "<", ">=", "<="]; exports.BOOLEAN_NUMBER_BINARY_OPERATORS = BOOLEAN_NUMBER_BINARY_OPERATORS; const EQUALITY_BINARY_OPERATORS = ["==", "===", "!=", "!=="]; exports.EQUALITY_BINARY_OPERATORS = EQUALITY_BINARY_OPERATORS; const COMPARISON_BINARY_OPERATORS = [...EQUALITY_BINARY_OPERATORS, "in", "instanceof"]; exports.COMPARISON_BINARY_OPERATORS = COMPARISON_BINARY_OPERATORS; const BOOLEAN_BINARY_OPERATORS = [...COMPARISON_BINARY_OPERATORS, ...BOOLEAN_NUMBER_BINARY_OPERATORS]; exports.BOOLEAN_BINARY_OPERATORS = BOOLEAN_BINARY_OPERATORS; const NUMBER_BINARY_OPERATORS = ["-", "/", "%", "*", "**", "&", "|", ">>", ">>>", "<<", "^"]; exports.NUMBER_BINARY_OPERATORS = NUMBER_BINARY_OPERATORS; const BINARY_OPERATORS = ["+", ...NUMBER_BINARY_OPERATORS, ...BOOLEAN_BINARY_OPERATORS]; exports.BINARY_OPERATORS = BINARY_OPERATORS; const BOOLEAN_UNARY_OPERATORS = ["delete", "!"]; exports.BOOLEAN_UNARY_OPERATORS = BOOLEAN_UNARY_OPERATORS; const NUMBER_UNARY_OPERATORS = ["+", "-", "~"]; exports.NUMBER_UNARY_OPERATORS = NUMBER_UNARY_OPERATORS; const STRING_UNARY_OPERATORS = ["typeof"]; exports.STRING_UNARY_OPERATORS = STRING_UNARY_OPERATORS; const UNARY_OPERATORS = ["void", "throw", ...BOOLEAN_UNARY_OPERATORS, ...NUMBER_UNARY_OPERATORS, ...STRING_UNARY_OPERATORS]; exports.UNARY_OPERATORS = UNARY_OPERATORS; const INHERIT_KEYS = { optional: ["typeAnnotation", "typeParameters", "returnType"], force: ["start", "loc", "end"] }; exports.INHERIT_KEYS = INHERIT_KEYS; const BLOCK_SCOPED_SYMBOL = Symbol.for("var used to be block scoped"); exports.BLOCK_SCOPED_SYMBOL = BLOCK_SCOPED_SYMBOL; const NOT_LOCAL_BINDING = Symbol.for("should not be considered a local binding"); exports.NOT_LOCAL_BINDING = NOT_LOCAL_BINDING; },{}],121:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = ensureBlock; var _toBlock = _interopRequireDefault(require("./toBlock")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function ensureBlock(node, key = "body") { return node[key] = (0, _toBlock.default)(node[key], node); } },{"./toBlock":124}],122:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = gatherSequenceExpressions; var _getBindingIdentifiers = _interopRequireDefault(require("../retrievers/getBindingIdentifiers")); var _generated = require("../validators/generated"); var _generated2 = require("../builders/generated"); var _cloneNode = _interopRequireDefault(require("../clone/cloneNode")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function gatherSequenceExpressions(nodes, scope, declars) { const exprs = []; let ensureLastUndefined = true; for (const node of nodes) { ensureLastUndefined = false; if ((0, _generated.isExpression)(node)) { exprs.push(node); } else if ((0, _generated.isExpressionStatement)(node)) { exprs.push(node.expression); } else if ((0, _generated.isVariableDeclaration)(node)) { if (node.kind !== "var") return; for (const declar of node.declarations) { const bindings = (0, _getBindingIdentifiers.default)(declar); for (const key of Object.keys(bindings)) { declars.push({ kind: node.kind, id: (0, _cloneNode.default)(bindings[key]) }); } if (declar.init) { exprs.push((0, _generated2.assignmentExpression)("=", declar.id, declar.init)); } } ensureLastUndefined = true; } else if ((0, _generated.isIfStatement)(node)) { const consequent = node.consequent ? gatherSequenceExpressions([node.consequent], scope, declars) : scope.buildUndefinedNode(); const alternate = node.alternate ? gatherSequenceExpressions([node.alternate], scope, declars) : scope.buildUndefinedNode(); if (!consequent || !alternate) return; exprs.push((0, _generated2.conditionalExpression)(node.test, consequent, alternate)); } else if ((0, _generated.isBlockStatement)(node)) { const body = gatherSequenceExpressions(node.body, scope, declars); if (!body) return; exprs.push(body); } else if ((0, _generated.isEmptyStatement)(node)) { ensureLastUndefined = true; } else { return; } } if (ensureLastUndefined) { exprs.push(scope.buildUndefinedNode()); } if (exprs.length === 1) { return exprs[0]; } else { return (0, _generated2.sequenceExpression)(exprs); } } },{"../builders/generated":106,"../clone/cloneNode":110,"../retrievers/getBindingIdentifiers":149,"../validators/generated":157}],123:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = toBindingIdentifierName; var _toIdentifier = _interopRequireDefault(require("./toIdentifier")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function toBindingIdentifierName(name) { name = (0, _toIdentifier.default)(name); if (name === "eval" || name === "arguments") name = "_" + name; return name; } },{"./toIdentifier":127}],124:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = toBlock; var _generated = require("../validators/generated"); var _generated2 = require("../builders/generated"); function toBlock(node, parent) { if ((0, _generated.isBlockStatement)(node)) { return node; } let blockNodes = []; if ((0, _generated.isEmptyStatement)(node)) { blockNodes = []; } else { if (!(0, _generated.isStatement)(node)) { if ((0, _generated.isFunction)(parent)) { node = (0, _generated2.returnStatement)(node); } else { node = (0, _generated2.expressionStatement)(node); } } blockNodes = [node]; } return (0, _generated2.blockStatement)(blockNodes); } },{"../builders/generated":106,"../validators/generated":157}],125:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = toComputedKey; var _generated = require("../validators/generated"); var _generated2 = require("../builders/generated"); function toComputedKey(node, key = node.key || node.property) { if (!node.computed && (0, _generated.isIdentifier)(key)) key = (0, _generated2.stringLiteral)(key.name); return key; } },{"../builders/generated":106,"../validators/generated":157}],126:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = toExpression; var _generated = require("../validators/generated"); function toExpression(node) { if ((0, _generated.isExpressionStatement)(node)) { node = node.expression; } if ((0, _generated.isExpression)(node)) { return node; } if ((0, _generated.isClass)(node)) { node.type = "ClassExpression"; } else if ((0, _generated.isFunction)(node)) { node.type = "FunctionExpression"; } if (!(0, _generated.isExpression)(node)) { throw new Error(`cannot turn ${node.type} to an expression`); } return node; } },{"../validators/generated":157}],127:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = toIdentifier; var _isValidIdentifier = _interopRequireDefault(require("../validators/isValidIdentifier")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function toIdentifier(name) { name = name + ""; name = name.replace(/[^a-zA-Z0-9$_]/g, "-"); name = name.replace(/^[-0-9]+/, ""); name = name.replace(/[-\s]+(.)?/g, function (match, c) { return c ? c.toUpperCase() : ""; }); if (!(0, _isValidIdentifier.default)(name)) { name = `_${name}`; } return name || "_"; } },{"../validators/isValidIdentifier":171}],128:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = toKeyAlias; var _generated = require("../validators/generated"); var _cloneNode = _interopRequireDefault(require("../clone/cloneNode")); var _removePropertiesDeep = _interopRequireDefault(require("../modifications/removePropertiesDeep")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function toKeyAlias(node, key = node.key) { let alias; if (node.kind === "method") { return toKeyAlias.increment() + ""; } else if ((0, _generated.isIdentifier)(key)) { alias = key.name; } else if ((0, _generated.isStringLiteral)(key)) { alias = JSON.stringify(key.value); } else { alias = JSON.stringify((0, _removePropertiesDeep.default)((0, _cloneNode.default)(key))); } if (node.computed) { alias = `[${alias}]`; } if (node.static) { alias = `static:${alias}`; } return alias; } toKeyAlias.uid = 0; toKeyAlias.increment = function () { if (toKeyAlias.uid >= Number.MAX_SAFE_INTEGER) { return toKeyAlias.uid = 0; } else { return toKeyAlias.uid++; } }; },{"../clone/cloneNode":110,"../modifications/removePropertiesDeep":148,"../validators/generated":157}],129:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = toSequenceExpression; var _gatherSequenceExpressions = _interopRequireDefault(require("./gatherSequenceExpressions")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function toSequenceExpression(nodes, scope) { if (!nodes || !nodes.length) return; const declars = []; const result = (0, _gatherSequenceExpressions.default)(nodes, scope, declars); if (!result) return; for (const declar of declars) { scope.push(declar); } return result; } },{"./gatherSequenceExpressions":122}],130:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = toStatement; var _generated = require("../validators/generated"); var _generated2 = require("../builders/generated"); function toStatement(node, ignore) { if ((0, _generated.isStatement)(node)) { return node; } let mustHaveId = false; let newType; if ((0, _generated.isClass)(node)) { mustHaveId = true; newType = "ClassDeclaration"; } else if ((0, _generated.isFunction)(node)) { mustHaveId = true; newType = "FunctionDeclaration"; } else if ((0, _generated.isAssignmentExpression)(node)) { return (0, _generated2.expressionStatement)(node); } if (mustHaveId && !node.id) { newType = false; } if (!newType) { if (ignore) { return false; } else { throw new Error(`cannot turn ${node.type} to a statement`); } } node.type = newType; return node; } },{"../builders/generated":106,"../validators/generated":157}],131:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = valueToNode; function _isPlainObject() { const data = _interopRequireDefault(require("lodash/isPlainObject")); _isPlainObject = function () { return data; }; return data; } function _isRegExp() { const data = _interopRequireDefault(require("lodash/isRegExp")); _isRegExp = function () { return data; }; return data; } var _isValidIdentifier = _interopRequireDefault(require("../validators/isValidIdentifier")); var _generated = require("../builders/generated"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function valueToNode(value) { if (value === undefined) { return (0, _generated.identifier)("undefined"); } if (value === true || value === false) { return (0, _generated.booleanLiteral)(value); } if (value === null) { return (0, _generated.nullLiteral)(); } if (typeof value === "string") { return (0, _generated.stringLiteral)(value); } if (typeof value === "number") { let result; if (Number.isFinite(value)) { result = (0, _generated.numericLiteral)(Math.abs(value)); } else { let numerator; if (Number.isNaN(value)) { numerator = (0, _generated.numericLiteral)(0); } else { numerator = (0, _generated.numericLiteral)(1); } result = (0, _generated.binaryExpression)("/", numerator, (0, _generated.numericLiteral)(0)); } if (value < 0 || Object.is(value, -0)) { result = (0, _generated.unaryExpression)("-", result); } return result; } if ((0, _isRegExp().default)(value)) { const pattern = value.source; const flags = value.toString().match(/\/([a-z]+|)$/)[1]; return (0, _generated.regExpLiteral)(pattern, flags); } if (Array.isArray(value)) { return (0, _generated.arrayExpression)(value.map(valueToNode)); } if ((0, _isPlainObject().default)(value)) { const props = []; for (const key of Object.keys(value)) { let nodeKey; if ((0, _isValidIdentifier.default)(key)) { nodeKey = (0, _generated.identifier)(key); } else { nodeKey = (0, _generated.stringLiteral)(key); } props.push((0, _generated.objectProperty)(nodeKey, valueToNode(value[key]))); } return (0, _generated.objectExpression)(props); } throw new Error("don't know how to turn this value into a node"); } },{"../builders/generated":106,"../validators/isValidIdentifier":171,"lodash/isPlainObject":380,"lodash/isRegExp":381}],132:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.patternLikeCommon = exports.functionDeclarationCommon = exports.functionTypeAnnotationCommon = exports.functionCommon = void 0; var _isValidIdentifier = _interopRequireDefault(require("../validators/isValidIdentifier")); var _constants = require("../constants"); var _utils = _interopRequireWildcard(require("./utils")); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (0, _utils.default)("ArrayExpression", { fields: { elements: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeOrValueType)("null", "Expression", "SpreadElement"))), default: [] } }, visitor: ["elements"], aliases: ["Expression"] }); (0, _utils.default)("AssignmentExpression", { fields: { operator: { validate: (0, _utils.assertValueType)("string") }, left: { validate: (0, _utils.assertNodeType)("LVal") }, right: { validate: (0, _utils.assertNodeType)("Expression") } }, builder: ["operator", "left", "right"], visitor: ["left", "right"], aliases: ["Expression"] }); (0, _utils.default)("BinaryExpression", { builder: ["operator", "left", "right"], fields: { operator: { validate: (0, _utils.assertOneOf)(..._constants.BINARY_OPERATORS) }, left: { validate: (0, _utils.assertNodeType)("Expression") }, right: { validate: (0, _utils.assertNodeType)("Expression") } }, visitor: ["left", "right"], aliases: ["Binary", "Expression"] }); (0, _utils.default)("InterpreterDirective", { builder: ["value"], fields: { value: { validate: (0, _utils.assertValueType)("string") } } }); (0, _utils.default)("Directive", { visitor: ["value"], fields: { value: { validate: (0, _utils.assertNodeType)("DirectiveLiteral") } } }); (0, _utils.default)("DirectiveLiteral", { builder: ["value"], fields: { value: { validate: (0, _utils.assertValueType)("string") } } }); (0, _utils.default)("BlockStatement", { builder: ["body", "directives"], visitor: ["directives", "body"], fields: { directives: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Directive"))), default: [] }, body: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Statement"))) } }, aliases: ["Scopable", "BlockParent", "Block", "Statement"] }); (0, _utils.default)("BreakStatement", { visitor: ["label"], fields: { label: { validate: (0, _utils.assertNodeType)("Identifier"), optional: true } }, aliases: ["Statement", "Terminatorless", "CompletionStatement"] }); (0, _utils.default)("CallExpression", { visitor: ["callee", "arguments", "typeParameters", "typeArguments"], builder: ["callee", "arguments"], aliases: ["Expression"], fields: { callee: { validate: (0, _utils.assertNodeType)("Expression") }, arguments: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Expression", "SpreadElement", "JSXNamespacedName", "ArgumentPlaceholder"))) }, optional: { validate: (0, _utils.assertOneOf)(true, false), optional: true }, typeArguments: { validate: (0, _utils.assertNodeType)("TypeParameterInstantiation"), optional: true }, typeParameters: { validate: (0, _utils.assertNodeType)("TSTypeParameterInstantiation"), optional: true } } }); (0, _utils.default)("CatchClause", { visitor: ["param", "body"], fields: { param: { validate: (0, _utils.assertNodeType)("Identifier"), optional: true }, body: { validate: (0, _utils.assertNodeType)("BlockStatement") } }, aliases: ["Scopable", "BlockParent"] }); (0, _utils.default)("ConditionalExpression", { visitor: ["test", "consequent", "alternate"], fields: { test: { validate: (0, _utils.assertNodeType)("Expression") }, consequent: { validate: (0, _utils.assertNodeType)("Expression") }, alternate: { validate: (0, _utils.assertNodeType)("Expression") } }, aliases: ["Expression", "Conditional"] }); (0, _utils.default)("ContinueStatement", { visitor: ["label"], fields: { label: { validate: (0, _utils.assertNodeType)("Identifier"), optional: true } }, aliases: ["Statement", "Terminatorless", "CompletionStatement"] }); (0, _utils.default)("DebuggerStatement", { aliases: ["Statement"] }); (0, _utils.default)("DoWhileStatement", { visitor: ["test", "body"], fields: { test: { validate: (0, _utils.assertNodeType)("Expression") }, body: { validate: (0, _utils.assertNodeType)("Statement") } }, aliases: ["Statement", "BlockParent", "Loop", "While", "Scopable"] }); (0, _utils.default)("EmptyStatement", { aliases: ["Statement"] }); (0, _utils.default)("ExpressionStatement", { visitor: ["expression"], fields: { expression: { validate: (0, _utils.assertNodeType)("Expression") } }, aliases: ["Statement", "ExpressionWrapper"] }); (0, _utils.default)("File", { builder: ["program", "comments", "tokens"], visitor: ["program"], fields: { program: { validate: (0, _utils.assertNodeType)("Program") } } }); (0, _utils.default)("ForInStatement", { visitor: ["left", "right", "body"], aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"], fields: { left: { validate: (0, _utils.assertNodeType)("VariableDeclaration", "LVal") }, right: { validate: (0, _utils.assertNodeType)("Expression") }, body: { validate: (0, _utils.assertNodeType)("Statement") } } }); (0, _utils.default)("ForStatement", { visitor: ["init", "test", "update", "body"], aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop"], fields: { init: { validate: (0, _utils.assertNodeType)("VariableDeclaration", "Expression"), optional: true }, test: { validate: (0, _utils.assertNodeType)("Expression"), optional: true }, update: { validate: (0, _utils.assertNodeType)("Expression"), optional: true }, body: { validate: (0, _utils.assertNodeType)("Statement") } } }); const functionCommon = { params: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Identifier", "Pattern", "RestElement", "TSParameterProperty"))) }, generator: { default: false, validate: (0, _utils.assertValueType)("boolean") }, async: { validate: (0, _utils.assertValueType)("boolean"), default: false } }; exports.functionCommon = functionCommon; const functionTypeAnnotationCommon = { returnType: { validate: (0, _utils.assertNodeType)("TypeAnnotation", "TSTypeAnnotation", "Noop"), optional: true }, typeParameters: { validate: (0, _utils.assertNodeType)("TypeParameterDeclaration", "TSTypeParameterDeclaration", "Noop"), optional: true } }; exports.functionTypeAnnotationCommon = functionTypeAnnotationCommon; const functionDeclarationCommon = Object.assign({}, functionCommon, { declare: { validate: (0, _utils.assertValueType)("boolean"), optional: true }, id: { validate: (0, _utils.assertNodeType)("Identifier"), optional: true } }); exports.functionDeclarationCommon = functionDeclarationCommon; (0, _utils.default)("FunctionDeclaration", { builder: ["id", "params", "body", "generator", "async"], visitor: ["id", "params", "body", "returnType", "typeParameters"], fields: Object.assign({}, functionDeclarationCommon, functionTypeAnnotationCommon, { body: { validate: (0, _utils.assertNodeType)("BlockStatement") } }), aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Statement", "Pureish", "Declaration"] }); (0, _utils.default)("FunctionExpression", { inherits: "FunctionDeclaration", aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Expression", "Pureish"], fields: Object.assign({}, functionCommon, functionTypeAnnotationCommon, { id: { validate: (0, _utils.assertNodeType)("Identifier"), optional: true }, body: { validate: (0, _utils.assertNodeType)("BlockStatement") } }) }); const patternLikeCommon = { typeAnnotation: { validate: (0, _utils.assertNodeType)("TypeAnnotation", "TSTypeAnnotation", "Noop"), optional: true }, decorators: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))) } }; exports.patternLikeCommon = patternLikeCommon; (0, _utils.default)("Identifier", { builder: ["name"], visitor: ["typeAnnotation", "decorators"], aliases: ["Expression", "PatternLike", "LVal", "TSEntityName"], fields: Object.assign({}, patternLikeCommon, { name: { validate: (0, _utils.chain)(function (node, key, val) { if (!(0, _isValidIdentifier.default)(val)) {} }, (0, _utils.assertValueType)("string")) }, optional: { validate: (0, _utils.assertValueType)("boolean"), optional: true } }) }); (0, _utils.default)("IfStatement", { visitor: ["test", "consequent", "alternate"], aliases: ["Statement", "Conditional"], fields: { test: { validate: (0, _utils.assertNodeType)("Expression") }, consequent: { validate: (0, _utils.assertNodeType)("Statement") }, alternate: { optional: true, validate: (0, _utils.assertNodeType)("Statement") } } }); (0, _utils.default)("LabeledStatement", { visitor: ["label", "body"], aliases: ["Statement"], fields: { label: { validate: (0, _utils.assertNodeType)("Identifier") }, body: { validate: (0, _utils.assertNodeType)("Statement") } } }); (0, _utils.default)("StringLiteral", { builder: ["value"], fields: { value: { validate: (0, _utils.assertValueType)("string") } }, aliases: ["Expression", "Pureish", "Literal", "Immutable"] }); (0, _utils.default)("NumericLiteral", { builder: ["value"], deprecatedAlias: "NumberLiteral", fields: { value: { validate: (0, _utils.assertValueType)("number") } }, aliases: ["Expression", "Pureish", "Literal", "Immutable"] }); (0, _utils.default)("NullLiteral", { aliases: ["Expression", "Pureish", "Literal", "Immutable"] }); (0, _utils.default)("BooleanLiteral", { builder: ["value"], fields: { value: { validate: (0, _utils.assertValueType)("boolean") } }, aliases: ["Expression", "Pureish", "Literal", "Immutable"] }); (0, _utils.default)("RegExpLiteral", { builder: ["pattern", "flags"], deprecatedAlias: "RegexLiteral", aliases: ["Expression", "Literal"], fields: { pattern: { validate: (0, _utils.assertValueType)("string") }, flags: { validate: (0, _utils.assertValueType)("string"), default: "" } } }); (0, _utils.default)("LogicalExpression", { builder: ["operator", "left", "right"], visitor: ["left", "right"], aliases: ["Binary", "Expression"], fields: { operator: { validate: (0, _utils.assertOneOf)(..._constants.LOGICAL_OPERATORS) }, left: { validate: (0, _utils.assertNodeType)("Expression") }, right: { validate: (0, _utils.assertNodeType)("Expression") } } }); (0, _utils.default)("MemberExpression", { builder: ["object", "property", "computed", "optional"], visitor: ["object", "property"], aliases: ["Expression", "LVal"], fields: { object: { validate: (0, _utils.assertNodeType)("Expression") }, property: { validate: function () { const normal = (0, _utils.assertNodeType)("Identifier", "PrivateName"); const computed = (0, _utils.assertNodeType)("Expression"); return function (node, key, val) { const validator = node.computed ? computed : normal; validator(node, key, val); }; }() }, computed: { default: false }, optional: { validate: (0, _utils.assertOneOf)(true, false), optional: true } } }); (0, _utils.default)("NewExpression", { inherits: "CallExpression" }); (0, _utils.default)("Program", { visitor: ["directives", "body"], builder: ["body", "directives", "sourceType", "interpreter"], fields: { sourceFile: { validate: (0, _utils.assertValueType)("string") }, sourceType: { validate: (0, _utils.assertOneOf)("script", "module"), default: "script" }, interpreter: { validate: (0, _utils.assertNodeType)("InterpreterDirective"), default: null, optional: true }, directives: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Directive"))), default: [] }, body: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Statement"))) } }, aliases: ["Scopable", "BlockParent", "Block"] }); (0, _utils.default)("ObjectExpression", { visitor: ["properties"], aliases: ["Expression"], fields: { properties: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("ObjectMethod", "ObjectProperty", "SpreadElement"))) } } }); (0, _utils.default)("ObjectMethod", { builder: ["kind", "key", "params", "body", "computed"], fields: Object.assign({}, functionCommon, functionTypeAnnotationCommon, { kind: { validate: (0, _utils.chain)((0, _utils.assertValueType)("string"), (0, _utils.assertOneOf)("method", "get", "set")), default: "method" }, computed: { validate: (0, _utils.assertValueType)("boolean"), default: false }, key: { validate: function () { const normal = (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral"); const computed = (0, _utils.assertNodeType)("Expression"); return function (node, key, val) { const validator = node.computed ? computed : normal; validator(node, key, val); }; }() }, decorators: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))) }, body: { validate: (0, _utils.assertNodeType)("BlockStatement") } }), visitor: ["key", "params", "body", "decorators", "returnType", "typeParameters"], aliases: ["UserWhitespacable", "Function", "Scopable", "BlockParent", "FunctionParent", "Method", "ObjectMember"] }); (0, _utils.default)("ObjectProperty", { builder: ["key", "value", "computed", "shorthand", "decorators"], fields: { computed: { validate: (0, _utils.assertValueType)("boolean"), default: false }, key: { validate: function () { const normal = (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral"); const computed = (0, _utils.assertNodeType)("Expression"); return function (node, key, val) { const validator = node.computed ? computed : normal; validator(node, key, val); }; }() }, value: { validate: (0, _utils.assertNodeType)("Expression", "PatternLike") }, shorthand: { validate: (0, _utils.assertValueType)("boolean"), default: false }, decorators: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))), optional: true } }, visitor: ["key", "value", "decorators"], aliases: ["UserWhitespacable", "Property", "ObjectMember"] }); (0, _utils.default)("RestElement", { visitor: ["argument", "typeAnnotation"], builder: ["argument"], aliases: ["LVal", "PatternLike"], deprecatedAlias: "RestProperty", fields: Object.assign({}, patternLikeCommon, { argument: { validate: (0, _utils.assertNodeType)("LVal") } }) }); (0, _utils.default)("ReturnStatement", { visitor: ["argument"], aliases: ["Statement", "Terminatorless", "CompletionStatement"], fields: { argument: { validate: (0, _utils.assertNodeType)("Expression"), optional: true } } }); (0, _utils.default)("SequenceExpression", { visitor: ["expressions"], fields: { expressions: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Expression"))) } }, aliases: ["Expression"] }); (0, _utils.default)("ParenthesizedExpression", { visitor: ["expression"], aliases: ["Expression", "ExpressionWrapper"], fields: { expression: { validate: (0, _utils.assertNodeType)("Expression") } } }); (0, _utils.default)("SwitchCase", { visitor: ["test", "consequent"], fields: { test: { validate: (0, _utils.assertNodeType)("Expression"), optional: true }, consequent: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Statement"))) } } }); (0, _utils.default)("SwitchStatement", { visitor: ["discriminant", "cases"], aliases: ["Statement", "BlockParent", "Scopable"], fields: { discriminant: { validate: (0, _utils.assertNodeType)("Expression") }, cases: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("SwitchCase"))) } } }); (0, _utils.default)("ThisExpression", { aliases: ["Expression"] }); (0, _utils.default)("ThrowStatement", { visitor: ["argument"], aliases: ["Statement", "Terminatorless", "CompletionStatement"], fields: { argument: { validate: (0, _utils.assertNodeType)("Expression") } } }); (0, _utils.default)("TryStatement", { visitor: ["block", "handler", "finalizer"], aliases: ["Statement"], fields: { block: { validate: (0, _utils.assertNodeType)("BlockStatement") }, handler: { optional: true, validate: (0, _utils.assertNodeType)("CatchClause") }, finalizer: { optional: true, validate: (0, _utils.assertNodeType)("BlockStatement") } } }); (0, _utils.default)("UnaryExpression", { builder: ["operator", "argument", "prefix"], fields: { prefix: { default: true }, argument: { validate: (0, _utils.assertNodeType)("Expression") }, operator: { validate: (0, _utils.assertOneOf)(..._constants.UNARY_OPERATORS) } }, visitor: ["argument"], aliases: ["UnaryLike", "Expression"] }); (0, _utils.default)("UpdateExpression", { builder: ["operator", "argument", "prefix"], fields: { prefix: { default: false }, argument: { validate: (0, _utils.assertNodeType)("Expression") }, operator: { validate: (0, _utils.assertOneOf)(..._constants.UPDATE_OPERATORS) } }, visitor: ["argument"], aliases: ["Expression"] }); (0, _utils.default)("VariableDeclaration", { builder: ["kind", "declarations"], visitor: ["declarations"], aliases: ["Statement", "Declaration"], fields: { declare: { validate: (0, _utils.assertValueType)("boolean"), optional: true }, kind: { validate: (0, _utils.chain)((0, _utils.assertValueType)("string"), (0, _utils.assertOneOf)("var", "let", "const")) }, declarations: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("VariableDeclarator"))) } } }); (0, _utils.default)("VariableDeclarator", { visitor: ["id", "init"], fields: { id: { validate: (0, _utils.assertNodeType)("LVal") }, definite: { optional: true, validate: (0, _utils.assertValueType)("boolean") }, init: { optional: true, validate: (0, _utils.assertNodeType)("Expression") } } }); (0, _utils.default)("WhileStatement", { visitor: ["test", "body"], aliases: ["Statement", "BlockParent", "Loop", "While", "Scopable"], fields: { test: { validate: (0, _utils.assertNodeType)("Expression") }, body: { validate: (0, _utils.assertNodeType)("BlockStatement", "Statement") } } }); (0, _utils.default)("WithStatement", { visitor: ["object", "body"], aliases: ["Statement"], fields: { object: { validate: (0, _utils.assertNodeType)("Expression") }, body: { validate: (0, _utils.assertNodeType)("BlockStatement", "Statement") } } }); },{"../constants":120,"../validators/isValidIdentifier":171,"./utils":141}],133:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.classMethodOrDeclareMethodCommon = exports.classMethodOrPropertyCommon = void 0; var _utils = _interopRequireWildcard(require("./utils")); var _core = require("./core"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } (0, _utils.default)("AssignmentPattern", { visitor: ["left", "right", "decorators"], builder: ["left", "right"], aliases: ["Pattern", "PatternLike", "LVal"], fields: Object.assign({}, _core.patternLikeCommon, { left: { validate: (0, _utils.assertNodeType)("Identifier", "ObjectPattern", "ArrayPattern") }, right: { validate: (0, _utils.assertNodeType)("Expression") }, decorators: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))) } }) }); (0, _utils.default)("ArrayPattern", { visitor: ["elements", "typeAnnotation"], builder: ["elements"], aliases: ["Pattern", "PatternLike", "LVal"], fields: Object.assign({}, _core.patternLikeCommon, { elements: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("PatternLike"))) }, decorators: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))) } }) }); (0, _utils.default)("ArrowFunctionExpression", { builder: ["params", "body", "async"], visitor: ["params", "body", "returnType", "typeParameters"], aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Expression", "Pureish"], fields: Object.assign({}, _core.functionCommon, _core.functionTypeAnnotationCommon, { expression: { validate: (0, _utils.assertValueType)("boolean") }, body: { validate: (0, _utils.assertNodeType)("BlockStatement", "Expression") } }) }); (0, _utils.default)("ClassBody", { visitor: ["body"], fields: { body: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("ClassMethod", "ClassPrivateMethod", "ClassProperty", "ClassPrivateProperty", "TSDeclareMethod", "TSIndexSignature"))) } } }); const classCommon = { typeParameters: { validate: (0, _utils.assertNodeType)("TypeParameterDeclaration", "TSTypeParameterDeclaration", "Noop"), optional: true }, body: { validate: (0, _utils.assertNodeType)("ClassBody") }, superClass: { optional: true, validate: (0, _utils.assertNodeType)("Expression") }, superTypeParameters: { validate: (0, _utils.assertNodeType)("TypeParameterInstantiation", "TSTypeParameterInstantiation"), optional: true }, implements: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("TSExpressionWithTypeArguments", "ClassImplements"))), optional: true } }; (0, _utils.default)("ClassDeclaration", { builder: ["id", "superClass", "body", "decorators"], visitor: ["id", "body", "superClass", "mixins", "typeParameters", "superTypeParameters", "implements", "decorators"], aliases: ["Scopable", "Class", "Statement", "Declaration", "Pureish"], fields: Object.assign({}, classCommon, { declare: { validate: (0, _utils.assertValueType)("boolean"), optional: true }, abstract: { validate: (0, _utils.assertValueType)("boolean"), optional: true }, id: { validate: (0, _utils.assertNodeType)("Identifier"), optional: true }, decorators: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))), optional: true } }) }); (0, _utils.default)("ClassExpression", { inherits: "ClassDeclaration", aliases: ["Scopable", "Class", "Expression", "Pureish"], fields: Object.assign({}, classCommon, { id: { optional: true, validate: (0, _utils.assertNodeType)("Identifier") }, body: { validate: (0, _utils.assertNodeType)("ClassBody") }, superClass: { optional: true, validate: (0, _utils.assertNodeType)("Expression") }, decorators: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))), optional: true } }) }); (0, _utils.default)("ExportAllDeclaration", { visitor: ["source"], aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"], fields: { source: { validate: (0, _utils.assertNodeType)("StringLiteral") } } }); (0, _utils.default)("ExportDefaultDeclaration", { visitor: ["declaration"], aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"], fields: { declaration: { validate: (0, _utils.assertNodeType)("FunctionDeclaration", "TSDeclareFunction", "ClassDeclaration", "Expression") } } }); (0, _utils.default)("ExportNamedDeclaration", { visitor: ["declaration", "specifiers", "source"], aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"], fields: { declaration: { validate: (0, _utils.assertNodeType)("Declaration"), optional: true }, specifiers: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("ExportSpecifier", "ExportDefaultSpecifier", "ExportNamespaceSpecifier"))) }, source: { validate: (0, _utils.assertNodeType)("StringLiteral"), optional: true } } }); (0, _utils.default)("ExportSpecifier", { visitor: ["local", "exported"], aliases: ["ModuleSpecifier"], fields: { local: { validate: (0, _utils.assertNodeType)("Identifier") }, exported: { validate: (0, _utils.assertNodeType)("Identifier") } } }); (0, _utils.default)("ForOfStatement", { visitor: ["left", "right", "body"], aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"], fields: { left: { validate: (0, _utils.assertNodeType)("VariableDeclaration", "LVal") }, right: { validate: (0, _utils.assertNodeType)("Expression") }, body: { validate: (0, _utils.assertNodeType)("Statement") }, await: { default: false, validate: (0, _utils.assertValueType)("boolean") } } }); (0, _utils.default)("ImportDeclaration", { visitor: ["specifiers", "source"], aliases: ["Statement", "Declaration", "ModuleDeclaration"], fields: { specifiers: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("ImportSpecifier", "ImportDefaultSpecifier", "ImportNamespaceSpecifier"))) }, source: { validate: (0, _utils.assertNodeType)("StringLiteral") }, importKind: { validate: (0, _utils.assertOneOf)("type", "typeof", "value"), optional: true } } }); (0, _utils.default)("ImportDefaultSpecifier", { visitor: ["local"], aliases: ["ModuleSpecifier"], fields: { local: { validate: (0, _utils.assertNodeType)("Identifier") } } }); (0, _utils.default)("ImportNamespaceSpecifier", { visitor: ["local"], aliases: ["ModuleSpecifier"], fields: { local: { validate: (0, _utils.assertNodeType)("Identifier") } } }); (0, _utils.default)("ImportSpecifier", { visitor: ["local", "imported"], aliases: ["ModuleSpecifier"], fields: { local: { validate: (0, _utils.assertNodeType)("Identifier") }, imported: { validate: (0, _utils.assertNodeType)("Identifier") }, importKind: { validate: (0, _utils.assertOneOf)("type", "typeof"), optional: true } } }); (0, _utils.default)("MetaProperty", { visitor: ["meta", "property"], aliases: ["Expression"], fields: { meta: { validate: (0, _utils.assertNodeType)("Identifier") }, property: { validate: (0, _utils.assertNodeType)("Identifier") } } }); const classMethodOrPropertyCommon = { abstract: { validate: (0, _utils.assertValueType)("boolean"), optional: true }, accessibility: { validate: (0, _utils.chain)((0, _utils.assertValueType)("string"), (0, _utils.assertOneOf)("public", "private", "protected")), optional: true }, static: { validate: (0, _utils.assertValueType)("boolean"), optional: true }, computed: { default: false, validate: (0, _utils.assertValueType)("boolean") }, optional: { validate: (0, _utils.assertValueType)("boolean"), optional: true }, key: { validate: (0, _utils.chain)(function () { const normal = (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral"); const computed = (0, _utils.assertNodeType)("Expression"); return function (node, key, val) { const validator = node.computed ? computed : normal; validator(node, key, val); }; }(), (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral", "Expression")) } }; exports.classMethodOrPropertyCommon = classMethodOrPropertyCommon; const classMethodOrDeclareMethodCommon = Object.assign({}, _core.functionCommon, classMethodOrPropertyCommon, { kind: { validate: (0, _utils.chain)((0, _utils.assertValueType)("string"), (0, _utils.assertOneOf)("get", "set", "method", "constructor")), default: "method" }, access: { validate: (0, _utils.chain)((0, _utils.assertValueType)("string"), (0, _utils.assertOneOf)("public", "private", "protected")), optional: true }, decorators: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))), optional: true } }); exports.classMethodOrDeclareMethodCommon = classMethodOrDeclareMethodCommon; (0, _utils.default)("ClassMethod", { aliases: ["Function", "Scopable", "BlockParent", "FunctionParent", "Method"], builder: ["kind", "key", "params", "body", "computed", "static"], visitor: ["key", "params", "body", "decorators", "returnType", "typeParameters"], fields: Object.assign({}, classMethodOrDeclareMethodCommon, _core.functionTypeAnnotationCommon, { body: { validate: (0, _utils.assertNodeType)("BlockStatement") } }) }); (0, _utils.default)("ObjectPattern", { visitor: ["properties", "typeAnnotation", "decorators"], builder: ["properties"], aliases: ["Pattern", "PatternLike", "LVal"], fields: Object.assign({}, _core.patternLikeCommon, { properties: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("RestElement", "ObjectProperty"))) } }) }); (0, _utils.default)("SpreadElement", { visitor: ["argument"], aliases: ["UnaryLike"], deprecatedAlias: "SpreadProperty", fields: { argument: { validate: (0, _utils.assertNodeType)("Expression") } } }); (0, _utils.default)("Super", { aliases: ["Expression"] }); (0, _utils.default)("TaggedTemplateExpression", { visitor: ["tag", "quasi"], aliases: ["Expression"], fields: { tag: { validate: (0, _utils.assertNodeType)("Expression") }, quasi: { validate: (0, _utils.assertNodeType)("TemplateLiteral") }, typeParameters: { validate: (0, _utils.assertNodeType)("TypeParameterInstantiation", "TSTypeParameterInstantiation"), optional: true } } }); (0, _utils.default)("TemplateElement", { builder: ["value", "tail"], fields: { value: {}, tail: { validate: (0, _utils.assertValueType)("boolean"), default: false } } }); (0, _utils.default)("TemplateLiteral", { visitor: ["quasis", "expressions"], aliases: ["Expression", "Literal"], fields: { quasis: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("TemplateElement"))) }, expressions: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Expression"))) } } }); (0, _utils.default)("YieldExpression", { builder: ["argument", "delegate"], visitor: ["argument"], aliases: ["Expression", "Terminatorless"], fields: { delegate: { validate: (0, _utils.assertValueType)("boolean"), default: false }, argument: { optional: true, validate: (0, _utils.assertNodeType)("Expression") } } }); },{"./core":132,"./utils":141}],134:[function(require,module,exports){ "use strict"; var _utils = _interopRequireWildcard(require("./utils")); var _es = require("./es2015"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } (0, _utils.default)("ArgumentPlaceholder", {}); (0, _utils.default)("AwaitExpression", { builder: ["argument"], visitor: ["argument"], aliases: ["Expression", "Terminatorless"], fields: { argument: { validate: (0, _utils.assertNodeType)("Expression") } } }); (0, _utils.default)("BindExpression", { visitor: ["object", "callee"], aliases: ["Expression"], fields: {} }); (0, _utils.default)("ClassProperty", { visitor: ["key", "value", "typeAnnotation", "decorators"], builder: ["key", "value", "typeAnnotation", "decorators", "computed"], aliases: ["Property"], fields: Object.assign({}, _es.classMethodOrPropertyCommon, { value: { validate: (0, _utils.assertNodeType)("Expression"), optional: true }, definite: { validate: (0, _utils.assertValueType)("boolean"), optional: true }, typeAnnotation: { validate: (0, _utils.assertNodeType)("TypeAnnotation", "TSTypeAnnotation", "Noop"), optional: true }, decorators: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))), optional: true }, readonly: { validate: (0, _utils.assertValueType)("boolean"), optional: true } }) }); (0, _utils.default)("OptionalMemberExpression", { builder: ["object", "property", "computed", "optional"], visitor: ["object", "property"], aliases: ["Expression"], fields: { object: { validate: (0, _utils.assertNodeType)("Expression") }, property: { validate: function () { const normal = (0, _utils.assertNodeType)("Identifier"); const computed = (0, _utils.assertNodeType)("Expression"); return function (node, key, val) { const validator = node.computed ? computed : normal; validator(node, key, val); }; }() }, computed: { default: false }, optional: { validate: (0, _utils.assertValueType)("boolean") } } }); (0, _utils.default)("PipelineTopicExpression", { builder: ["expression"], visitor: ["expression"], fields: { expression: { validate: (0, _utils.assertNodeType)("Expression") } } }); (0, _utils.default)("PipelineBareFunction", { builder: ["callee"], visitor: ["callee"], fields: { callee: { validate: (0, _utils.assertNodeType)("Expression") } } }); (0, _utils.default)("PipelinePrimaryTopicReference", { aliases: ["Expression"] }); (0, _utils.default)("OptionalCallExpression", { visitor: ["callee", "arguments", "typeParameters", "typeArguments"], builder: ["callee", "arguments", "optional"], aliases: ["Expression"], fields: { callee: { validate: (0, _utils.assertNodeType)("Expression") }, arguments: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Expression", "SpreadElement", "JSXNamespacedName"))) }, optional: { validate: (0, _utils.assertValueType)("boolean") }, typeArguments: { validate: (0, _utils.assertNodeType)("TypeParameterInstantiation"), optional: true }, typeParameters: { validate: (0, _utils.assertNodeType)("TSTypeParameterInstantiation"), optional: true } } }); (0, _utils.default)("ClassPrivateProperty", { visitor: ["key", "value"], builder: ["key", "value"], aliases: ["Property", "Private"], fields: { key: { validate: (0, _utils.assertNodeType)("PrivateName") }, value: { validate: (0, _utils.assertNodeType)("Expression"), optional: true } } }); (0, _utils.default)("ClassPrivateMethod", { builder: ["kind", "key", "params", "body", "static"], visitor: ["key", "params", "body", "decorators", "returnType", "typeParameters"], aliases: ["Function", "Scopable", "BlockParent", "FunctionParent", "Method", "Private"], fields: Object.assign({}, _es.classMethodOrDeclareMethodCommon, { key: { validate: (0, _utils.assertNodeType)("PrivateName") }, body: { validate: (0, _utils.assertNodeType)("BlockStatement") } }) }); (0, _utils.default)("Import", { aliases: ["Expression"] }); (0, _utils.default)("Decorator", { visitor: ["expression"], fields: { expression: { validate: (0, _utils.assertNodeType)("Expression") } } }); (0, _utils.default)("DoExpression", { visitor: ["body"], aliases: ["Expression"], fields: { body: { validate: (0, _utils.assertNodeType)("BlockStatement") } } }); (0, _utils.default)("ExportDefaultSpecifier", { visitor: ["exported"], aliases: ["ModuleSpecifier"], fields: { exported: { validate: (0, _utils.assertNodeType)("Identifier") } } }); (0, _utils.default)("ExportNamespaceSpecifier", { visitor: ["exported"], aliases: ["ModuleSpecifier"], fields: { exported: { validate: (0, _utils.assertNodeType)("Identifier") } } }); (0, _utils.default)("PrivateName", { visitor: ["id"], aliases: ["Private"], fields: { id: { validate: (0, _utils.assertNodeType)("Identifier") } } }); (0, _utils.default)("BigIntLiteral", { builder: ["value"], fields: { value: { validate: (0, _utils.assertValueType)("string") } }, aliases: ["Expression", "Pureish", "Literal", "Immutable"] }); },{"./es2015":133,"./utils":141}],135:[function(require,module,exports){ "use strict"; var _utils = _interopRequireWildcard(require("./utils")); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } const defineInterfaceishType = (name, typeParameterType = "TypeParameterDeclaration") => { (0, _utils.default)(name, { builder: ["id", "typeParameters", "extends", "body"], visitor: ["id", "typeParameters", "extends", "mixins", "implements", "body"], aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], fields: { id: (0, _utils.validateType)("Identifier"), typeParameters: (0, _utils.validateOptionalType)(typeParameterType), extends: (0, _utils.validateOptional)((0, _utils.arrayOfType)("InterfaceExtends")), mixins: (0, _utils.validateOptional)((0, _utils.arrayOfType)("InterfaceExtends")), implements: (0, _utils.validateOptional)((0, _utils.arrayOfType)("ClassImplements")), body: (0, _utils.validateType)("ObjectTypeAnnotation") } }); }; (0, _utils.default)("AnyTypeAnnotation", { aliases: ["Flow", "FlowType", "FlowBaseAnnotation"] }); (0, _utils.default)("ArrayTypeAnnotation", { visitor: ["elementType"], aliases: ["Flow", "FlowType"], fields: { elementType: (0, _utils.validateType)("FlowType") } }); (0, _utils.default)("BooleanTypeAnnotation", { aliases: ["Flow", "FlowType", "FlowBaseAnnotation"] }); (0, _utils.default)("BooleanLiteralTypeAnnotation", { builder: ["value"], aliases: ["Flow", "FlowType"], fields: { value: (0, _utils.validate)((0, _utils.assertValueType)("boolean")) } }); (0, _utils.default)("NullLiteralTypeAnnotation", { aliases: ["Flow", "FlowType", "FlowBaseAnnotation"] }); (0, _utils.default)("ClassImplements", { visitor: ["id", "typeParameters"], aliases: ["Flow"], fields: { id: (0, _utils.validateType)("Identifier"), typeParameters: (0, _utils.validateOptionalType)("TypeParameterInstantiation") } }); defineInterfaceishType("DeclareClass"); (0, _utils.default)("DeclareFunction", { visitor: ["id"], aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], fields: { id: (0, _utils.validateType)("Identifier"), predicate: (0, _utils.validateOptionalType)("DeclaredPredicate") } }); defineInterfaceishType("DeclareInterface"); (0, _utils.default)("DeclareModule", { builder: ["id", "body", "kind"], visitor: ["id", "body"], aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], fields: { id: (0, _utils.validateType)(["Identifier", "StringLiteral"]), body: (0, _utils.validateType)("BlockStatement"), kind: (0, _utils.validateOptional)((0, _utils.assertOneOf)("CommonJS", "ES")) } }); (0, _utils.default)("DeclareModuleExports", { visitor: ["typeAnnotation"], aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], fields: { typeAnnotation: (0, _utils.validateType)("TypeAnnotation") } }); (0, _utils.default)("DeclareTypeAlias", { visitor: ["id", "typeParameters", "right"], aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], fields: { id: (0, _utils.validateType)("Identifier"), typeParameters: (0, _utils.validateOptionalType)("TypeParameterDeclaration"), right: (0, _utils.validateType)("FlowType") } }); (0, _utils.default)("DeclareOpaqueType", { visitor: ["id", "typeParameters", "supertype"], aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], fields: { id: (0, _utils.validateType)("Identifier"), typeParameters: (0, _utils.validateOptionalType)("TypeParameterDeclaration"), supertype: (0, _utils.validateOptionalType)("FlowType") } }); (0, _utils.default)("DeclareVariable", { visitor: ["id"], aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], fields: { id: (0, _utils.validateType)("Identifier") } }); (0, _utils.default)("DeclareExportDeclaration", { visitor: ["declaration", "specifiers", "source"], aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], fields: { declaration: (0, _utils.validateOptionalType)("Flow"), specifiers: (0, _utils.validateOptional)((0, _utils.arrayOfType)(["ExportSpecifier", "ExportNamespaceSpecifier"])), source: (0, _utils.validateOptionalType)("StringLiteral"), default: (0, _utils.validateOptional)((0, _utils.assertValueType)("boolean")) } }); (0, _utils.default)("DeclareExportAllDeclaration", { visitor: ["source"], aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], fields: { source: (0, _utils.validateType)("StringLiteral"), exportKind: (0, _utils.validateOptional)((0, _utils.assertOneOf)(["type", "value"])) } }); (0, _utils.default)("DeclaredPredicate", { visitor: ["value"], aliases: ["Flow", "FlowPredicate"], fields: { value: (0, _utils.validateType)("Flow") } }); (0, _utils.default)("ExistsTypeAnnotation", { aliases: ["Flow", "FlowType"] }); (0, _utils.default)("FunctionTypeAnnotation", { visitor: ["typeParameters", "params", "rest", "returnType"], aliases: ["Flow", "FlowType"], fields: { typeParameters: (0, _utils.validateOptionalType)("TypeParameterDeclaration"), params: (0, _utils.validate)((0, _utils.arrayOfType)("FunctionTypeParam")), rest: (0, _utils.validateOptionalType)("FunctionTypeParam"), returnType: (0, _utils.validateType)("FlowType") } }); (0, _utils.default)("FunctionTypeParam", { visitor: ["name", "typeAnnotation"], aliases: ["Flow"], fields: { name: (0, _utils.validateOptionalType)("Identifier"), typeAnnotation: (0, _utils.validateType)("FlowType"), optional: (0, _utils.validateOptional)((0, _utils.assertValueType)("boolean")) } }); (0, _utils.default)("GenericTypeAnnotation", { visitor: ["id", "typeParameters"], aliases: ["Flow", "FlowType"], fields: { id: (0, _utils.validateType)(["Identifier", "QualifiedTypeIdentifier"]), typeParameters: (0, _utils.validateOptionalType)("TypeParameterInstantiation") } }); (0, _utils.default)("InferredPredicate", { aliases: ["Flow", "FlowPredicate"] }); (0, _utils.default)("InterfaceExtends", { visitor: ["id", "typeParameters"], aliases: ["Flow"], fields: { id: (0, _utils.validateType)(["Identifier", "QualifiedTypeIdentifier"]), typeParameters: (0, _utils.validateOptionalType)("TypeParameterInstantiation") } }); defineInterfaceishType("InterfaceDeclaration"); (0, _utils.default)("InterfaceTypeAnnotation", { visitor: ["extends", "body"], aliases: ["Flow", "FlowType"], fields: { extends: (0, _utils.validateOptional)((0, _utils.arrayOfType)("InterfaceExtends")), body: (0, _utils.validateType)("ObjectTypeAnnotation") } }); (0, _utils.default)("IntersectionTypeAnnotation", { visitor: ["types"], aliases: ["Flow", "FlowType"], fields: { types: (0, _utils.validate)((0, _utils.arrayOfType)("FlowType")) } }); (0, _utils.default)("MixedTypeAnnotation", { aliases: ["Flow", "FlowType", "FlowBaseAnnotation"] }); (0, _utils.default)("EmptyTypeAnnotation", { aliases: ["Flow", "FlowType", "FlowBaseAnnotation"] }); (0, _utils.default)("NullableTypeAnnotation", { visitor: ["typeAnnotation"], aliases: ["Flow", "FlowType"], fields: { typeAnnotation: (0, _utils.validateType)("FlowType") } }); (0, _utils.default)("NumberLiteralTypeAnnotation", { builder: ["value"], aliases: ["Flow", "FlowType"], fields: { value: (0, _utils.validate)((0, _utils.assertValueType)("number")) } }); (0, _utils.default)("NumberTypeAnnotation", { aliases: ["Flow", "FlowType", "FlowBaseAnnotation"] }); (0, _utils.default)("ObjectTypeAnnotation", { visitor: ["properties", "indexers", "callProperties", "internalSlots"], aliases: ["Flow", "FlowType"], builder: ["properties", "indexers", "callProperties", "internalSlots", "exact"], fields: { properties: (0, _utils.validate)((0, _utils.arrayOfType)(["ObjectTypeProperty", "ObjectTypeSpreadProperty"])), indexers: (0, _utils.validateOptional)((0, _utils.arrayOfType)("ObjectTypeIndexer")), callProperties: (0, _utils.validateOptional)((0, _utils.arrayOfType)("ObjectTypeCallProperty")), internalSlots: (0, _utils.validateOptional)((0, _utils.arrayOfType)("ObjectTypeInternalSlot")), exact: { validate: (0, _utils.assertValueType)("boolean"), default: false }, inexact: (0, _utils.validateOptional)((0, _utils.assertValueType)("boolean")) } }); (0, _utils.default)("ObjectTypeInternalSlot", { visitor: ["id", "value", "optional", "static", "method"], aliases: ["Flow", "UserWhitespacable"], fields: { id: (0, _utils.validateType)("Identifier"), value: (0, _utils.validateType)("FlowType"), optional: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), static: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), method: (0, _utils.validate)((0, _utils.assertValueType)("boolean")) } }); (0, _utils.default)("ObjectTypeCallProperty", { visitor: ["value"], aliases: ["Flow", "UserWhitespacable"], fields: { value: (0, _utils.validateType)("FlowType"), static: (0, _utils.validate)((0, _utils.assertValueType)("boolean")) } }); (0, _utils.default)("ObjectTypeIndexer", { visitor: ["id", "key", "value", "variance"], aliases: ["Flow", "UserWhitespacable"], fields: { id: (0, _utils.validateOptionalType)("Identifier"), key: (0, _utils.validateType)("FlowType"), value: (0, _utils.validateType)("FlowType"), static: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), variance: (0, _utils.validateOptionalType)("Variance") } }); (0, _utils.default)("ObjectTypeProperty", { visitor: ["key", "value", "variance"], aliases: ["Flow", "UserWhitespacable"], fields: { key: (0, _utils.validateType)(["Identifier", "StringLiteral"]), value: (0, _utils.validateType)("FlowType"), kind: (0, _utils.validate)((0, _utils.assertOneOf)("init", "get", "set")), static: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), proto: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), optional: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), variance: (0, _utils.validateOptionalType)("Variance") } }); (0, _utils.default)("ObjectTypeSpreadProperty", { visitor: ["argument"], aliases: ["Flow", "UserWhitespacable"], fields: { argument: (0, _utils.validateType)("FlowType") } }); (0, _utils.default)("OpaqueType", { visitor: ["id", "typeParameters", "supertype", "impltype"], aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], fields: { id: (0, _utils.validateType)("Identifier"), typeParameters: (0, _utils.validateOptionalType)("TypeParameterDeclaration"), supertype: (0, _utils.validateOptionalType)("FlowType"), impltype: (0, _utils.validateType)("FlowType") } }); (0, _utils.default)("QualifiedTypeIdentifier", { visitor: ["id", "qualification"], aliases: ["Flow"], fields: { id: (0, _utils.validateType)("Identifier"), qualification: (0, _utils.validateType)(["Identifier", "QualifiedTypeIdentifier"]) } }); (0, _utils.default)("StringLiteralTypeAnnotation", { builder: ["value"], aliases: ["Flow", "FlowType"], fields: { value: (0, _utils.validate)((0, _utils.assertValueType)("string")) } }); (0, _utils.default)("StringTypeAnnotation", { aliases: ["Flow", "FlowType", "FlowBaseAnnotation"] }); (0, _utils.default)("ThisTypeAnnotation", { aliases: ["Flow", "FlowType", "FlowBaseAnnotation"] }); (0, _utils.default)("TupleTypeAnnotation", { visitor: ["types"], aliases: ["Flow", "FlowType"], fields: { types: (0, _utils.validate)((0, _utils.arrayOfType)("FlowType")) } }); (0, _utils.default)("TypeofTypeAnnotation", { visitor: ["argument"], aliases: ["Flow", "FlowType"], fields: { argument: (0, _utils.validateType)("FlowType") } }); (0, _utils.default)("TypeAlias", { visitor: ["id", "typeParameters", "right"], aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], fields: { id: (0, _utils.validateType)("Identifier"), typeParameters: (0, _utils.validateOptionalType)("TypeParameterDeclaration"), right: (0, _utils.validateType)("FlowType") } }); (0, _utils.default)("TypeAnnotation", { aliases: ["Flow"], visitor: ["typeAnnotation"], fields: { typeAnnotation: (0, _utils.validateType)("FlowType") } }); (0, _utils.default)("TypeCastExpression", { visitor: ["expression", "typeAnnotation"], aliases: ["Flow", "ExpressionWrapper", "Expression"], fields: { expression: (0, _utils.validateType)("Expression"), typeAnnotation: (0, _utils.validateType)("TypeAnnotation") } }); (0, _utils.default)("TypeParameter", { aliases: ["Flow"], visitor: ["bound", "default", "variance"], fields: { name: (0, _utils.validate)((0, _utils.assertValueType)("string")), bound: (0, _utils.validateOptionalType)("TypeAnnotation"), default: (0, _utils.validateOptionalType)("FlowType"), variance: (0, _utils.validateOptionalType)("Variance") } }); (0, _utils.default)("TypeParameterDeclaration", { aliases: ["Flow"], visitor: ["params"], fields: { params: (0, _utils.validate)((0, _utils.arrayOfType)("TypeParameter")) } }); (0, _utils.default)("TypeParameterInstantiation", { aliases: ["Flow"], visitor: ["params"], fields: { params: (0, _utils.validate)((0, _utils.arrayOfType)("FlowType")) } }); (0, _utils.default)("UnionTypeAnnotation", { visitor: ["types"], aliases: ["Flow", "FlowType"], fields: { types: (0, _utils.validate)((0, _utils.arrayOfType)("FlowType")) } }); (0, _utils.default)("Variance", { aliases: ["Flow"], builder: ["kind"], fields: { kind: (0, _utils.validate)((0, _utils.assertOneOf)("minus", "plus")) } }); (0, _utils.default)("VoidTypeAnnotation", { aliases: ["Flow", "FlowType", "FlowBaseAnnotation"] }); },{"./utils":141}],136:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "VISITOR_KEYS", { enumerable: true, get: function () { return _utils.VISITOR_KEYS; } }); Object.defineProperty(exports, "ALIAS_KEYS", { enumerable: true, get: function () { return _utils.ALIAS_KEYS; } }); Object.defineProperty(exports, "FLIPPED_ALIAS_KEYS", { enumerable: true, get: function () { return _utils.FLIPPED_ALIAS_KEYS; } }); Object.defineProperty(exports, "NODE_FIELDS", { enumerable: true, get: function () { return _utils.NODE_FIELDS; } }); Object.defineProperty(exports, "BUILDER_KEYS", { enumerable: true, get: function () { return _utils.BUILDER_KEYS; } }); Object.defineProperty(exports, "DEPRECATED_KEYS", { enumerable: true, get: function () { return _utils.DEPRECATED_KEYS; } }); Object.defineProperty(exports, "PLACEHOLDERS", { enumerable: true, get: function () { return _placeholders.PLACEHOLDERS; } }); Object.defineProperty(exports, "PLACEHOLDERS_ALIAS", { enumerable: true, get: function () { return _placeholders.PLACEHOLDERS_ALIAS; } }); Object.defineProperty(exports, "PLACEHOLDERS_FLIPPED_ALIAS", { enumerable: true, get: function () { return _placeholders.PLACEHOLDERS_FLIPPED_ALIAS; } }); exports.TYPES = void 0; function _toFastProperties() { const data = _interopRequireDefault(require("to-fast-properties")); _toFastProperties = function () { return data; }; return data; } require("./core"); require("./es2015"); require("./flow"); require("./jsx"); require("./misc"); require("./experimental"); require("./typescript"); var _utils = require("./utils"); var _placeholders = require("./placeholders"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } (0, _toFastProperties().default)(_utils.VISITOR_KEYS); (0, _toFastProperties().default)(_utils.ALIAS_KEYS); (0, _toFastProperties().default)(_utils.FLIPPED_ALIAS_KEYS); (0, _toFastProperties().default)(_utils.NODE_FIELDS); (0, _toFastProperties().default)(_utils.BUILDER_KEYS); (0, _toFastProperties().default)(_utils.DEPRECATED_KEYS); (0, _toFastProperties().default)(_placeholders.PLACEHOLDERS_ALIAS); (0, _toFastProperties().default)(_placeholders.PLACEHOLDERS_FLIPPED_ALIAS); const TYPES = Object.keys(_utils.VISITOR_KEYS).concat(Object.keys(_utils.FLIPPED_ALIAS_KEYS)).concat(Object.keys(_utils.DEPRECATED_KEYS)); exports.TYPES = TYPES; },{"./core":132,"./es2015":133,"./experimental":134,"./flow":135,"./jsx":137,"./misc":138,"./placeholders":139,"./typescript":140,"./utils":141,"to-fast-properties":456}],137:[function(require,module,exports){ "use strict"; var _utils = _interopRequireWildcard(require("./utils")); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } (0, _utils.default)("JSXAttribute", { visitor: ["name", "value"], aliases: ["JSX", "Immutable"], fields: { name: { validate: (0, _utils.assertNodeType)("JSXIdentifier", "JSXNamespacedName") }, value: { optional: true, validate: (0, _utils.assertNodeType)("JSXElement", "JSXFragment", "StringLiteral", "JSXExpressionContainer") } } }); (0, _utils.default)("JSXClosingElement", { visitor: ["name"], aliases: ["JSX", "Immutable"], fields: { name: { validate: (0, _utils.assertNodeType)("JSXIdentifier", "JSXMemberExpression") } } }); (0, _utils.default)("JSXElement", { builder: ["openingElement", "closingElement", "children", "selfClosing"], visitor: ["openingElement", "children", "closingElement"], aliases: ["JSX", "Immutable", "Expression"], fields: { openingElement: { validate: (0, _utils.assertNodeType)("JSXOpeningElement") }, closingElement: { optional: true, validate: (0, _utils.assertNodeType)("JSXClosingElement") }, children: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("JSXText", "JSXExpressionContainer", "JSXSpreadChild", "JSXElement", "JSXFragment"))) } } }); (0, _utils.default)("JSXEmptyExpression", { aliases: ["JSX"] }); (0, _utils.default)("JSXExpressionContainer", { visitor: ["expression"], aliases: ["JSX", "Immutable"], fields: { expression: { validate: (0, _utils.assertNodeType)("Expression", "JSXEmptyExpression") } } }); (0, _utils.default)("JSXSpreadChild", { visitor: ["expression"], aliases: ["JSX", "Immutable"], fields: { expression: { validate: (0, _utils.assertNodeType)("Expression") } } }); (0, _utils.default)("JSXIdentifier", { builder: ["name"], aliases: ["JSX"], fields: { name: { validate: (0, _utils.assertValueType)("string") } } }); (0, _utils.default)("JSXMemberExpression", { visitor: ["object", "property"], aliases: ["JSX"], fields: { object: { validate: (0, _utils.assertNodeType)("JSXMemberExpression", "JSXIdentifier") }, property: { validate: (0, _utils.assertNodeType)("JSXIdentifier") } } }); (0, _utils.default)("JSXNamespacedName", { visitor: ["namespace", "name"], aliases: ["JSX"], fields: { namespace: { validate: (0, _utils.assertNodeType)("JSXIdentifier") }, name: { validate: (0, _utils.assertNodeType)("JSXIdentifier") } } }); (0, _utils.default)("JSXOpeningElement", { builder: ["name", "attributes", "selfClosing"], visitor: ["name", "attributes"], aliases: ["JSX", "Immutable"], fields: { name: { validate: (0, _utils.assertNodeType)("JSXIdentifier", "JSXMemberExpression") }, selfClosing: { default: false, validate: (0, _utils.assertValueType)("boolean") }, attributes: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("JSXAttribute", "JSXSpreadAttribute"))) }, typeParameters: { validate: (0, _utils.assertNodeType)("TypeParameterInstantiation", "TSTypeParameterInstantiation"), optional: true } } }); (0, _utils.default)("JSXSpreadAttribute", { visitor: ["argument"], aliases: ["JSX"], fields: { argument: { validate: (0, _utils.assertNodeType)("Expression") } } }); (0, _utils.default)("JSXText", { aliases: ["JSX", "Immutable"], builder: ["value"], fields: { value: { validate: (0, _utils.assertValueType)("string") } } }); (0, _utils.default)("JSXFragment", { builder: ["openingFragment", "closingFragment", "children"], visitor: ["openingFragment", "children", "closingFragment"], aliases: ["JSX", "Immutable", "Expression"], fields: { openingFragment: { validate: (0, _utils.assertNodeType)("JSXOpeningFragment") }, closingFragment: { validate: (0, _utils.assertNodeType)("JSXClosingFragment") }, children: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("JSXText", "JSXExpressionContainer", "JSXSpreadChild", "JSXElement", "JSXFragment"))) } } }); (0, _utils.default)("JSXOpeningFragment", { aliases: ["JSX", "Immutable"] }); (0, _utils.default)("JSXClosingFragment", { aliases: ["JSX", "Immutable"] }); },{"./utils":141}],138:[function(require,module,exports){ "use strict"; var _utils = _interopRequireWildcard(require("./utils")); var _placeholders = require("./placeholders"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } (0, _utils.default)("Noop", { visitor: [] }); (0, _utils.default)("Placeholder", { visitor: [], builder: ["expectedNode", "name"], fields: { name: { validate: (0, _utils.assertNodeType)("Identifier") }, expectedNode: { validate: (0, _utils.assertOneOf)(..._placeholders.PLACEHOLDERS) } } }); },{"./placeholders":139,"./utils":141}],139:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PLACEHOLDERS_FLIPPED_ALIAS = exports.PLACEHOLDERS_ALIAS = exports.PLACEHOLDERS = void 0; var _utils = require("./utils"); const PLACEHOLDERS = ["Identifier", "StringLiteral", "Expression", "Statement", "Declaration", "BlockStatement", "ClassBody", "Pattern"]; exports.PLACEHOLDERS = PLACEHOLDERS; const PLACEHOLDERS_ALIAS = { Declaration: ["Statement"], Pattern: ["PatternLike", "LVal"] }; exports.PLACEHOLDERS_ALIAS = PLACEHOLDERS_ALIAS; for (const type of PLACEHOLDERS) { const alias = _utils.ALIAS_KEYS[type]; if (alias && alias.length) PLACEHOLDERS_ALIAS[type] = alias; } const PLACEHOLDERS_FLIPPED_ALIAS = {}; exports.PLACEHOLDERS_FLIPPED_ALIAS = PLACEHOLDERS_FLIPPED_ALIAS; Object.keys(PLACEHOLDERS_ALIAS).forEach(type => { PLACEHOLDERS_ALIAS[type].forEach(alias => { if (!Object.hasOwnProperty.call(PLACEHOLDERS_FLIPPED_ALIAS, alias)) { PLACEHOLDERS_FLIPPED_ALIAS[alias] = []; } PLACEHOLDERS_FLIPPED_ALIAS[alias].push(type); }); }); },{"./utils":141}],140:[function(require,module,exports){ "use strict"; var _utils = _interopRequireWildcard(require("./utils")); var _core = require("./core"); var _es = require("./es2015"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } const bool = (0, _utils.assertValueType)("boolean"); const tSFunctionTypeAnnotationCommon = { returnType: { validate: (0, _utils.assertNodeType)("TSTypeAnnotation", "Noop"), optional: true }, typeParameters: { validate: (0, _utils.assertNodeType)("TSTypeParameterDeclaration", "Noop"), optional: true } }; (0, _utils.default)("TSParameterProperty", { aliases: ["LVal"], visitor: ["parameter"], fields: { accessibility: { validate: (0, _utils.assertOneOf)("public", "private", "protected"), optional: true }, readonly: { validate: (0, _utils.assertValueType)("boolean"), optional: true }, parameter: { validate: (0, _utils.assertNodeType)("Identifier", "AssignmentPattern") } } }); (0, _utils.default)("TSDeclareFunction", { aliases: ["Statement", "Declaration"], visitor: ["id", "typeParameters", "params", "returnType"], fields: Object.assign({}, _core.functionDeclarationCommon, tSFunctionTypeAnnotationCommon) }); (0, _utils.default)("TSDeclareMethod", { visitor: ["decorators", "key", "typeParameters", "params", "returnType"], fields: Object.assign({}, _es.classMethodOrDeclareMethodCommon, tSFunctionTypeAnnotationCommon) }); (0, _utils.default)("TSQualifiedName", { aliases: ["TSEntityName"], visitor: ["left", "right"], fields: { left: (0, _utils.validateType)("TSEntityName"), right: (0, _utils.validateType)("Identifier") } }); const signatureDeclarationCommon = { typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterDeclaration"), parameters: (0, _utils.validateArrayOfType)(["Identifier", "RestElement"]), typeAnnotation: (0, _utils.validateOptionalType)("TSTypeAnnotation") }; const callConstructSignatureDeclaration = { aliases: ["TSTypeElement"], visitor: ["typeParameters", "parameters", "typeAnnotation"], fields: signatureDeclarationCommon }; (0, _utils.default)("TSCallSignatureDeclaration", callConstructSignatureDeclaration); (0, _utils.default)("TSConstructSignatureDeclaration", callConstructSignatureDeclaration); const namedTypeElementCommon = { key: (0, _utils.validateType)("Expression"), computed: (0, _utils.validate)(bool), optional: (0, _utils.validateOptional)(bool) }; (0, _utils.default)("TSPropertySignature", { aliases: ["TSTypeElement"], visitor: ["key", "typeAnnotation", "initializer"], fields: Object.assign({}, namedTypeElementCommon, { readonly: (0, _utils.validateOptional)(bool), typeAnnotation: (0, _utils.validateOptionalType)("TSTypeAnnotation"), initializer: (0, _utils.validateOptionalType)("Expression") }) }); (0, _utils.default)("TSMethodSignature", { aliases: ["TSTypeElement"], visitor: ["key", "typeParameters", "parameters", "typeAnnotation"], fields: Object.assign({}, signatureDeclarationCommon, namedTypeElementCommon) }); (0, _utils.default)("TSIndexSignature", { aliases: ["TSTypeElement"], visitor: ["parameters", "typeAnnotation"], fields: { readonly: (0, _utils.validateOptional)(bool), parameters: (0, _utils.validateArrayOfType)("Identifier"), typeAnnotation: (0, _utils.validateOptionalType)("TSTypeAnnotation") } }); const tsKeywordTypes = ["TSAnyKeyword", "TSUnknownKeyword", "TSNumberKeyword", "TSObjectKeyword", "TSBooleanKeyword", "TSStringKeyword", "TSSymbolKeyword", "TSVoidKeyword", "TSUndefinedKeyword", "TSNullKeyword", "TSNeverKeyword"]; for (const type of tsKeywordTypes) { (0, _utils.default)(type, { aliases: ["TSType"], visitor: [], fields: {} }); } (0, _utils.default)("TSThisType", { aliases: ["TSType"], visitor: [], fields: {} }); const fnOrCtr = { aliases: ["TSType"], visitor: ["typeParameters", "parameters", "typeAnnotation"], fields: signatureDeclarationCommon }; (0, _utils.default)("TSFunctionType", fnOrCtr); (0, _utils.default)("TSConstructorType", fnOrCtr); (0, _utils.default)("TSTypeReference", { aliases: ["TSType"], visitor: ["typeName", "typeParameters"], fields: { typeName: (0, _utils.validateType)("TSEntityName"), typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterInstantiation") } }); (0, _utils.default)("TSTypePredicate", { aliases: ["TSType"], visitor: ["parameterName", "typeAnnotation"], fields: { parameterName: (0, _utils.validateType)(["Identifier", "TSThisType"]), typeAnnotation: (0, _utils.validateType)("TSTypeAnnotation") } }); (0, _utils.default)("TSTypeQuery", { aliases: ["TSType"], visitor: ["exprName"], fields: { exprName: (0, _utils.validateType)(["TSEntityName", "TSImportType"]) } }); (0, _utils.default)("TSTypeLiteral", { aliases: ["TSType"], visitor: ["members"], fields: { members: (0, _utils.validateArrayOfType)("TSTypeElement") } }); (0, _utils.default)("TSArrayType", { aliases: ["TSType"], visitor: ["elementType"], fields: { elementType: (0, _utils.validateType)("TSType") } }); (0, _utils.default)("TSTupleType", { aliases: ["TSType"], visitor: ["elementTypes"], fields: { elementTypes: (0, _utils.validateArrayOfType)("TSType") } }); (0, _utils.default)("TSOptionalType", { aliases: ["TSType"], visitor: ["typeAnnotation"], fields: { typeAnnotation: (0, _utils.validateType)("TSType") } }); (0, _utils.default)("TSRestType", { aliases: ["TSType"], visitor: ["typeAnnotation"], fields: { typeAnnotation: (0, _utils.validateType)("TSType") } }); const unionOrIntersection = { aliases: ["TSType"], visitor: ["types"], fields: { types: (0, _utils.validateArrayOfType)("TSType") } }; (0, _utils.default)("TSUnionType", unionOrIntersection); (0, _utils.default)("TSIntersectionType", unionOrIntersection); (0, _utils.default)("TSConditionalType", { aliases: ["TSType"], visitor: ["checkType", "extendsType", "trueType", "falseType"], fields: { checkType: (0, _utils.validateType)("TSType"), extendsType: (0, _utils.validateType)("TSType"), trueType: (0, _utils.validateType)("TSType"), falseType: (0, _utils.validateType)("TSType") } }); (0, _utils.default)("TSInferType", { aliases: ["TSType"], visitor: ["typeParameter"], fields: { typeParameter: (0, _utils.validateType)("TSTypeParameter") } }); (0, _utils.default)("TSParenthesizedType", { aliases: ["TSType"], visitor: ["typeAnnotation"], fields: { typeAnnotation: (0, _utils.validateType)("TSType") } }); (0, _utils.default)("TSTypeOperator", { aliases: ["TSType"], visitor: ["typeAnnotation"], fields: { operator: (0, _utils.validate)((0, _utils.assertValueType)("string")), typeAnnotation: (0, _utils.validateType)("TSType") } }); (0, _utils.default)("TSIndexedAccessType", { aliases: ["TSType"], visitor: ["objectType", "indexType"], fields: { objectType: (0, _utils.validateType)("TSType"), indexType: (0, _utils.validateType)("TSType") } }); (0, _utils.default)("TSMappedType", { aliases: ["TSType"], visitor: ["typeParameter", "typeAnnotation"], fields: { readonly: (0, _utils.validateOptional)(bool), typeParameter: (0, _utils.validateType)("TSTypeParameter"), optional: (0, _utils.validateOptional)(bool), typeAnnotation: (0, _utils.validateOptionalType)("TSType") } }); (0, _utils.default)("TSLiteralType", { aliases: ["TSType"], visitor: ["literal"], fields: { literal: (0, _utils.validateType)(["NumericLiteral", "StringLiteral", "BooleanLiteral"]) } }); (0, _utils.default)("TSExpressionWithTypeArguments", { aliases: ["TSType"], visitor: ["expression", "typeParameters"], fields: { expression: (0, _utils.validateType)("TSEntityName"), typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterInstantiation") } }); (0, _utils.default)("TSInterfaceDeclaration", { aliases: ["Statement", "Declaration"], visitor: ["id", "typeParameters", "extends", "body"], fields: { declare: (0, _utils.validateOptional)(bool), id: (0, _utils.validateType)("Identifier"), typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterDeclaration"), extends: (0, _utils.validateOptional)((0, _utils.arrayOfType)("TSExpressionWithTypeArguments")), body: (0, _utils.validateType)("TSInterfaceBody") } }); (0, _utils.default)("TSInterfaceBody", { visitor: ["body"], fields: { body: (0, _utils.validateArrayOfType)("TSTypeElement") } }); (0, _utils.default)("TSTypeAliasDeclaration", { aliases: ["Statement", "Declaration"], visitor: ["id", "typeParameters", "typeAnnotation"], fields: { declare: (0, _utils.validateOptional)(bool), id: (0, _utils.validateType)("Identifier"), typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterDeclaration"), typeAnnotation: (0, _utils.validateType)("TSType") } }); (0, _utils.default)("TSAsExpression", { aliases: ["Expression"], visitor: ["expression", "typeAnnotation"], fields: { expression: (0, _utils.validateType)("Expression"), typeAnnotation: (0, _utils.validateType)("TSType") } }); (0, _utils.default)("TSTypeAssertion", { aliases: ["Expression"], visitor: ["typeAnnotation", "expression"], fields: { typeAnnotation: (0, _utils.validateType)("TSType"), expression: (0, _utils.validateType)("Expression") } }); (0, _utils.default)("TSEnumDeclaration", { aliases: ["Statement", "Declaration"], visitor: ["id", "members"], fields: { declare: (0, _utils.validateOptional)(bool), const: (0, _utils.validateOptional)(bool), id: (0, _utils.validateType)("Identifier"), members: (0, _utils.validateArrayOfType)("TSEnumMember"), initializer: (0, _utils.validateOptionalType)("Expression") } }); (0, _utils.default)("TSEnumMember", { visitor: ["id", "initializer"], fields: { id: (0, _utils.validateType)(["Identifier", "StringLiteral"]), initializer: (0, _utils.validateOptionalType)("Expression") } }); (0, _utils.default)("TSModuleDeclaration", { aliases: ["Statement", "Declaration"], visitor: ["id", "body"], fields: { declare: (0, _utils.validateOptional)(bool), global: (0, _utils.validateOptional)(bool), id: (0, _utils.validateType)(["Identifier", "StringLiteral"]), body: (0, _utils.validateType)(["TSModuleBlock", "TSModuleDeclaration"]) } }); (0, _utils.default)("TSModuleBlock", { visitor: ["body"], fields: { body: (0, _utils.validateArrayOfType)("Statement") } }); (0, _utils.default)("TSImportType", { aliases: ["TSType"], visitor: ["argument", "qualifier", "typeParameters"], fields: { argument: (0, _utils.validateType)("StringLiteral"), qualifier: (0, _utils.validateOptionalType)("TSEntityName"), typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterInstantiation") } }); (0, _utils.default)("TSImportEqualsDeclaration", { aliases: ["Statement"], visitor: ["id", "moduleReference"], fields: { isExport: (0, _utils.validate)(bool), id: (0, _utils.validateType)("Identifier"), moduleReference: (0, _utils.validateType)(["TSEntityName", "TSExternalModuleReference"]) } }); (0, _utils.default)("TSExternalModuleReference", { visitor: ["expression"], fields: { expression: (0, _utils.validateType)("StringLiteral") } }); (0, _utils.default)("TSNonNullExpression", { aliases: ["Expression"], visitor: ["expression"], fields: { expression: (0, _utils.validateType)("Expression") } }); (0, _utils.default)("TSExportAssignment", { aliases: ["Statement"], visitor: ["expression"], fields: { expression: (0, _utils.validateType)("Expression") } }); (0, _utils.default)("TSNamespaceExportDeclaration", { aliases: ["Statement"], visitor: ["id"], fields: { id: (0, _utils.validateType)("Identifier") } }); (0, _utils.default)("TSTypeAnnotation", { visitor: ["typeAnnotation"], fields: { typeAnnotation: { validate: (0, _utils.assertNodeType)("TSType") } } }); (0, _utils.default)("TSTypeParameterInstantiation", { visitor: ["params"], fields: { params: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("TSType"))) } } }); (0, _utils.default)("TSTypeParameterDeclaration", { visitor: ["params"], fields: { params: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("TSTypeParameter"))) } } }); (0, _utils.default)("TSTypeParameter", { visitor: ["constraint", "default"], fields: { name: { validate: (0, _utils.assertValueType)("string") }, constraint: { validate: (0, _utils.assertNodeType)("TSType"), optional: true }, default: { validate: (0, _utils.assertNodeType)("TSType"), optional: true } } }); },{"./core":132,"./es2015":133,"./utils":141}],141:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validate = validate; exports.typeIs = typeIs; exports.validateType = validateType; exports.validateOptional = validateOptional; exports.validateOptionalType = validateOptionalType; exports.arrayOf = arrayOf; exports.arrayOfType = arrayOfType; exports.validateArrayOfType = validateArrayOfType; exports.assertEach = assertEach; exports.assertOneOf = assertOneOf; exports.assertNodeType = assertNodeType; exports.assertNodeOrValueType = assertNodeOrValueType; exports.assertValueType = assertValueType; exports.chain = chain; exports.default = defineType; exports.DEPRECATED_KEYS = exports.BUILDER_KEYS = exports.NODE_FIELDS = exports.FLIPPED_ALIAS_KEYS = exports.ALIAS_KEYS = exports.VISITOR_KEYS = void 0; var _is = _interopRequireDefault(require("../validators/is")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const VISITOR_KEYS = {}; exports.VISITOR_KEYS = VISITOR_KEYS; const ALIAS_KEYS = {}; exports.ALIAS_KEYS = ALIAS_KEYS; const FLIPPED_ALIAS_KEYS = {}; exports.FLIPPED_ALIAS_KEYS = FLIPPED_ALIAS_KEYS; const NODE_FIELDS = {}; exports.NODE_FIELDS = NODE_FIELDS; const BUILDER_KEYS = {}; exports.BUILDER_KEYS = BUILDER_KEYS; const DEPRECATED_KEYS = {}; exports.DEPRECATED_KEYS = DEPRECATED_KEYS; function getType(val) { if (Array.isArray(val)) { return "array"; } else if (val === null) { return "null"; } else if (val === undefined) { return "undefined"; } else { return typeof val; } } function validate(validate) { return { validate }; } function typeIs(typeName) { return typeof typeName === "string" ? assertNodeType(typeName) : assertNodeType(...typeName); } function validateType(typeName) { return validate(typeIs(typeName)); } function validateOptional(validate) { return { validate, optional: true }; } function validateOptionalType(typeName) { return { validate: typeIs(typeName), optional: true }; } function arrayOf(elementType) { return chain(assertValueType("array"), assertEach(elementType)); } function arrayOfType(typeName) { return arrayOf(typeIs(typeName)); } function validateArrayOfType(typeName) { return validate(arrayOfType(typeName)); } function assertEach(callback) { function validator(node, key, val) { if (!Array.isArray(val)) return; for (let i = 0; i < val.length; i++) { callback(node, `${key}[${i}]`, val[i]); } } validator.each = callback; return validator; } function assertOneOf(...values) { function validate(node, key, val) { if (values.indexOf(val) < 0) { throw new TypeError(`Property ${key} expected value to be one of ${JSON.stringify(values)} but got ${JSON.stringify(val)}`); } } validate.oneOf = values; return validate; } function assertNodeType(...types) { function validate(node, key, val) { let valid = false; for (const type of types) { if ((0, _is.default)(type, val)) { valid = true; break; } } if (!valid) { throw new TypeError(`Property ${key} of ${node.type} expected node to be of a type ${JSON.stringify(types)} ` + `but instead got ${JSON.stringify(val && val.type)}`); } } validate.oneOfNodeTypes = types; return validate; } function assertNodeOrValueType(...types) { function validate(node, key, val) { let valid = false; for (const type of types) { if (getType(val) === type || (0, _is.default)(type, val)) { valid = true; break; } } if (!valid) { throw new TypeError(`Property ${key} of ${node.type} expected node to be of a type ${JSON.stringify(types)} ` + `but instead got ${JSON.stringify(val && val.type)}`); } } validate.oneOfNodeOrValueTypes = types; return validate; } function assertValueType(type) { function validate(node, key, val) { const valid = getType(val) === type; if (!valid) { throw new TypeError(`Property ${key} expected type of ${type} but got ${getType(val)}`); } } validate.type = type; return validate; } function chain(...fns) { function validate(...args) { for (const fn of fns) { fn(...args); } } validate.chainOf = fns; return validate; } function defineType(type, opts = {}) { const inherits = opts.inherits && store[opts.inherits] || {}; const fields = opts.fields || inherits.fields || {}; const visitor = opts.visitor || inherits.visitor || []; const aliases = opts.aliases || inherits.aliases || []; const builder = opts.builder || inherits.builder || opts.visitor || []; if (opts.deprecatedAlias) { DEPRECATED_KEYS[opts.deprecatedAlias] = type; } for (const key of visitor.concat(builder)) { fields[key] = fields[key] || {}; } for (const key of Object.keys(fields)) { const field = fields[key]; if (builder.indexOf(key) === -1) { field.optional = true; } if (field.default === undefined) { field.default = null; } else if (!field.validate) { field.validate = assertValueType(getType(field.default)); } } VISITOR_KEYS[type] = opts.visitor = visitor; BUILDER_KEYS[type] = opts.builder = builder; NODE_FIELDS[type] = opts.fields = fields; ALIAS_KEYS[type] = opts.aliases = aliases; aliases.forEach(alias => { FLIPPED_ALIAS_KEYS[alias] = FLIPPED_ALIAS_KEYS[alias] || []; FLIPPED_ALIAS_KEYS[alias].push(type); }); store[type] = opts; } const store = {}; },{"../validators/is":158}],142:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _exportNames = { react: true, assertNode: true, createTypeAnnotationBasedOnTypeof: true, createUnionTypeAnnotation: true, cloneNode: true, clone: true, cloneDeep: true, cloneWithoutLoc: true, addComment: true, addComments: true, inheritInnerComments: true, inheritLeadingComments: true, inheritsComments: true, inheritTrailingComments: true, removeComments: true, ensureBlock: true, toBindingIdentifierName: true, toBlock: true, toComputedKey: true, toExpression: true, toIdentifier: true, toKeyAlias: true, toSequenceExpression: true, toStatement: true, valueToNode: true, appendToMemberExpression: true, inherits: true, prependToMemberExpression: true, removeProperties: true, removePropertiesDeep: true, removeTypeDuplicates: true, getBindingIdentifiers: true, getOuterBindingIdentifiers: true, traverse: true, traverseFast: true, shallowEqual: true, is: true, isBinding: true, isBlockScoped: true, isImmutable: true, isLet: true, isNode: true, isNodesEquivalent: true, isPlaceholderType: true, isReferenced: true, isScope: true, isSpecifierDefault: true, isType: true, isValidES3Identifier: true, isValidIdentifier: true, isVar: true, matchesPattern: true, validate: true, buildMatchMemberExpression: true }; Object.defineProperty(exports, "assertNode", { enumerable: true, get: function () { return _assertNode.default; } }); Object.defineProperty(exports, "createTypeAnnotationBasedOnTypeof", { enumerable: true, get: function () { return _createTypeAnnotationBasedOnTypeof.default; } }); Object.defineProperty(exports, "createUnionTypeAnnotation", { enumerable: true, get: function () { return _createUnionTypeAnnotation.default; } }); Object.defineProperty(exports, "cloneNode", { enumerable: true, get: function () { return _cloneNode.default; } }); Object.defineProperty(exports, "clone", { enumerable: true, get: function () { return _clone.default; } }); Object.defineProperty(exports, "cloneDeep", { enumerable: true, get: function () { return _cloneDeep.default; } }); Object.defineProperty(exports, "cloneWithoutLoc", { enumerable: true, get: function () { return _cloneWithoutLoc.default; } }); Object.defineProperty(exports, "addComment", { enumerable: true, get: function () { return _addComment.default; } }); Object.defineProperty(exports, "addComments", { enumerable: true, get: function () { return _addComments.default; } }); Object.defineProperty(exports, "inheritInnerComments", { enumerable: true, get: function () { return _inheritInnerComments.default; } }); Object.defineProperty(exports, "inheritLeadingComments", { enumerable: true, get: function () { return _inheritLeadingComments.default; } }); Object.defineProperty(exports, "inheritsComments", { enumerable: true, get: function () { return _inheritsComments.default; } }); Object.defineProperty(exports, "inheritTrailingComments", { enumerable: true, get: function () { return _inheritTrailingComments.default; } }); Object.defineProperty(exports, "removeComments", { enumerable: true, get: function () { return _removeComments.default; } }); Object.defineProperty(exports, "ensureBlock", { enumerable: true, get: function () { return _ensureBlock.default; } }); Object.defineProperty(exports, "toBindingIdentifierName", { enumerable: true, get: function () { return _toBindingIdentifierName.default; } }); Object.defineProperty(exports, "toBlock", { enumerable: true, get: function () { return _toBlock.default; } }); Object.defineProperty(exports, "toComputedKey", { enumerable: true, get: function () { return _toComputedKey.default; } }); Object.defineProperty(exports, "toExpression", { enumerable: true, get: function () { return _toExpression.default; } }); Object.defineProperty(exports, "toIdentifier", { enumerable: true, get: function () { return _toIdentifier.default; } }); Object.defineProperty(exports, "toKeyAlias", { enumerable: true, get: function () { return _toKeyAlias.default; } }); Object.defineProperty(exports, "toSequenceExpression", { enumerable: true, get: function () { return _toSequenceExpression.default; } }); Object.defineProperty(exports, "toStatement", { enumerable: true, get: function () { return _toStatement.default; } }); Object.defineProperty(exports, "valueToNode", { enumerable: true, get: function () { return _valueToNode.default; } }); Object.defineProperty(exports, "appendToMemberExpression", { enumerable: true, get: function () { return _appendToMemberExpression.default; } }); Object.defineProperty(exports, "inherits", { enumerable: true, get: function () { return _inherits.default; } }); Object.defineProperty(exports, "prependToMemberExpression", { enumerable: true, get: function () { return _prependToMemberExpression.default; } }); Object.defineProperty(exports, "removeProperties", { enumerable: true, get: function () { return _removeProperties.default; } }); Object.defineProperty(exports, "removePropertiesDeep", { enumerable: true, get: function () { return _removePropertiesDeep.default; } }); Object.defineProperty(exports, "removeTypeDuplicates", { enumerable: true, get: function () { return _removeTypeDuplicates.default; } }); Object.defineProperty(exports, "getBindingIdentifiers", { enumerable: true, get: function () { return _getBindingIdentifiers.default; } }); Object.defineProperty(exports, "getOuterBindingIdentifiers", { enumerable: true, get: function () { return _getOuterBindingIdentifiers.default; } }); Object.defineProperty(exports, "traverse", { enumerable: true, get: function () { return _traverse.default; } }); Object.defineProperty(exports, "traverseFast", { enumerable: true, get: function () { return _traverseFast.default; } }); Object.defineProperty(exports, "shallowEqual", { enumerable: true, get: function () { return _shallowEqual.default; } }); Object.defineProperty(exports, "is", { enumerable: true, get: function () { return _is.default; } }); Object.defineProperty(exports, "isBinding", { enumerable: true, get: function () { return _isBinding.default; } }); Object.defineProperty(exports, "isBlockScoped", { enumerable: true, get: function () { return _isBlockScoped.default; } }); Object.defineProperty(exports, "isImmutable", { enumerable: true, get: function () { return _isImmutable.default; } }); Object.defineProperty(exports, "isLet", { enumerable: true, get: function () { return _isLet.default; } }); Object.defineProperty(exports, "isNode", { enumerable: true, get: function () { return _isNode.default; } }); Object.defineProperty(exports, "isNodesEquivalent", { enumerable: true, get: function () { return _isNodesEquivalent.default; } }); Object.defineProperty(exports, "isPlaceholderType", { enumerable: true, get: function () { return _isPlaceholderType.default; } }); Object.defineProperty(exports, "isReferenced", { enumerable: true, get: function () { return _isReferenced.default; } }); Object.defineProperty(exports, "isScope", { enumerable: true, get: function () { return _isScope.default; } }); Object.defineProperty(exports, "isSpecifierDefault", { enumerable: true, get: function () { return _isSpecifierDefault.default; } }); Object.defineProperty(exports, "isType", { enumerable: true, get: function () { return _isType.default; } }); Object.defineProperty(exports, "isValidES3Identifier", { enumerable: true, get: function () { return _isValidES3Identifier.default; } }); Object.defineProperty(exports, "isValidIdentifier", { enumerable: true, get: function () { return _isValidIdentifier.default; } }); Object.defineProperty(exports, "isVar", { enumerable: true, get: function () { return _isVar.default; } }); Object.defineProperty(exports, "matchesPattern", { enumerable: true, get: function () { return _matchesPattern.default; } }); Object.defineProperty(exports, "validate", { enumerable: true, get: function () { return _validate.default; } }); Object.defineProperty(exports, "buildMatchMemberExpression", { enumerable: true, get: function () { return _buildMatchMemberExpression.default; } }); exports.react = void 0; var _isReactComponent = _interopRequireDefault(require("./validators/react/isReactComponent")); var _isCompatTag = _interopRequireDefault(require("./validators/react/isCompatTag")); var _buildChildren = _interopRequireDefault(require("./builders/react/buildChildren")); var _assertNode = _interopRequireDefault(require("./asserts/assertNode")); var _generated = require("./asserts/generated"); Object.keys(_generated).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _generated[key]; } }); }); var _createTypeAnnotationBasedOnTypeof = _interopRequireDefault(require("./builders/flow/createTypeAnnotationBasedOnTypeof")); var _createUnionTypeAnnotation = _interopRequireDefault(require("./builders/flow/createUnionTypeAnnotation")); var _generated2 = require("./builders/generated"); Object.keys(_generated2).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _generated2[key]; } }); }); var _cloneNode = _interopRequireDefault(require("./clone/cloneNode")); var _clone = _interopRequireDefault(require("./clone/clone")); var _cloneDeep = _interopRequireDefault(require("./clone/cloneDeep")); var _cloneWithoutLoc = _interopRequireDefault(require("./clone/cloneWithoutLoc")); var _addComment = _interopRequireDefault(require("./comments/addComment")); var _addComments = _interopRequireDefault(require("./comments/addComments")); var _inheritInnerComments = _interopRequireDefault(require("./comments/inheritInnerComments")); var _inheritLeadingComments = _interopRequireDefault(require("./comments/inheritLeadingComments")); var _inheritsComments = _interopRequireDefault(require("./comments/inheritsComments")); var _inheritTrailingComments = _interopRequireDefault(require("./comments/inheritTrailingComments")); var _removeComments = _interopRequireDefault(require("./comments/removeComments")); var _generated3 = require("./constants/generated"); Object.keys(_generated3).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _generated3[key]; } }); }); var _constants = require("./constants"); Object.keys(_constants).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _constants[key]; } }); }); var _ensureBlock = _interopRequireDefault(require("./converters/ensureBlock")); var _toBindingIdentifierName = _interopRequireDefault(require("./converters/toBindingIdentifierName")); var _toBlock = _interopRequireDefault(require("./converters/toBlock")); var _toComputedKey = _interopRequireDefault(require("./converters/toComputedKey")); var _toExpression = _interopRequireDefault(require("./converters/toExpression")); var _toIdentifier = _interopRequireDefault(require("./converters/toIdentifier")); var _toKeyAlias = _interopRequireDefault(require("./converters/toKeyAlias")); var _toSequenceExpression = _interopRequireDefault(require("./converters/toSequenceExpression")); var _toStatement = _interopRequireDefault(require("./converters/toStatement")); var _valueToNode = _interopRequireDefault(require("./converters/valueToNode")); var _definitions = require("./definitions"); Object.keys(_definitions).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _definitions[key]; } }); }); var _appendToMemberExpression = _interopRequireDefault(require("./modifications/appendToMemberExpression")); var _inherits = _interopRequireDefault(require("./modifications/inherits")); var _prependToMemberExpression = _interopRequireDefault(require("./modifications/prependToMemberExpression")); var _removeProperties = _interopRequireDefault(require("./modifications/removeProperties")); var _removePropertiesDeep = _interopRequireDefault(require("./modifications/removePropertiesDeep")); var _removeTypeDuplicates = _interopRequireDefault(require("./modifications/flow/removeTypeDuplicates")); var _getBindingIdentifiers = _interopRequireDefault(require("./retrievers/getBindingIdentifiers")); var _getOuterBindingIdentifiers = _interopRequireDefault(require("./retrievers/getOuterBindingIdentifiers")); var _traverse = _interopRequireDefault(require("./traverse/traverse")); var _traverseFast = _interopRequireDefault(require("./traverse/traverseFast")); var _shallowEqual = _interopRequireDefault(require("./utils/shallowEqual")); var _is = _interopRequireDefault(require("./validators/is")); var _isBinding = _interopRequireDefault(require("./validators/isBinding")); var _isBlockScoped = _interopRequireDefault(require("./validators/isBlockScoped")); var _isImmutable = _interopRequireDefault(require("./validators/isImmutable")); var _isLet = _interopRequireDefault(require("./validators/isLet")); var _isNode = _interopRequireDefault(require("./validators/isNode")); var _isNodesEquivalent = _interopRequireDefault(require("./validators/isNodesEquivalent")); var _isPlaceholderType = _interopRequireDefault(require("./validators/isPlaceholderType")); var _isReferenced = _interopRequireDefault(require("./validators/isReferenced")); var _isScope = _interopRequireDefault(require("./validators/isScope")); var _isSpecifierDefault = _interopRequireDefault(require("./validators/isSpecifierDefault")); var _isType = _interopRequireDefault(require("./validators/isType")); var _isValidES3Identifier = _interopRequireDefault(require("./validators/isValidES3Identifier")); var _isValidIdentifier = _interopRequireDefault(require("./validators/isValidIdentifier")); var _isVar = _interopRequireDefault(require("./validators/isVar")); var _matchesPattern = _interopRequireDefault(require("./validators/matchesPattern")); var _validate = _interopRequireDefault(require("./validators/validate")); var _buildMatchMemberExpression = _interopRequireDefault(require("./validators/buildMatchMemberExpression")); var _generated4 = require("./validators/generated"); Object.keys(_generated4).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _generated4[key]; } }); }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const react = { isReactComponent: _isReactComponent.default, isCompatTag: _isCompatTag.default, buildChildren: _buildChildren.default }; exports.react = react; },{"./asserts/assertNode":101,"./asserts/generated":102,"./builders/flow/createTypeAnnotationBasedOnTypeof":104,"./builders/flow/createUnionTypeAnnotation":105,"./builders/generated":106,"./builders/react/buildChildren":107,"./clone/clone":108,"./clone/cloneDeep":109,"./clone/cloneNode":110,"./clone/cloneWithoutLoc":111,"./comments/addComment":112,"./comments/addComments":113,"./comments/inheritInnerComments":114,"./comments/inheritLeadingComments":115,"./comments/inheritTrailingComments":116,"./comments/inheritsComments":117,"./comments/removeComments":118,"./constants":120,"./constants/generated":119,"./converters/ensureBlock":121,"./converters/toBindingIdentifierName":123,"./converters/toBlock":124,"./converters/toComputedKey":125,"./converters/toExpression":126,"./converters/toIdentifier":127,"./converters/toKeyAlias":128,"./converters/toSequenceExpression":129,"./converters/toStatement":130,"./converters/valueToNode":131,"./definitions":136,"./modifications/appendToMemberExpression":143,"./modifications/flow/removeTypeDuplicates":144,"./modifications/inherits":145,"./modifications/prependToMemberExpression":146,"./modifications/removeProperties":147,"./modifications/removePropertiesDeep":148,"./retrievers/getBindingIdentifiers":149,"./retrievers/getOuterBindingIdentifiers":150,"./traverse/traverse":151,"./traverse/traverseFast":152,"./utils/shallowEqual":155,"./validators/buildMatchMemberExpression":156,"./validators/generated":157,"./validators/is":158,"./validators/isBinding":159,"./validators/isBlockScoped":160,"./validators/isImmutable":161,"./validators/isLet":162,"./validators/isNode":163,"./validators/isNodesEquivalent":164,"./validators/isPlaceholderType":165,"./validators/isReferenced":166,"./validators/isScope":167,"./validators/isSpecifierDefault":168,"./validators/isType":169,"./validators/isValidES3Identifier":170,"./validators/isValidIdentifier":171,"./validators/isVar":172,"./validators/matchesPattern":173,"./validators/react/isCompatTag":174,"./validators/react/isReactComponent":175,"./validators/validate":176}],143:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = appendToMemberExpression; var _generated = require("../builders/generated"); function appendToMemberExpression(member, append, computed = false) { member.object = (0, _generated.memberExpression)(member.object, member.property, member.computed); member.property = append; member.computed = !!computed; return member; } },{"../builders/generated":106}],144:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = removeTypeDuplicates; var _generated = require("../../validators/generated"); function removeTypeDuplicates(nodes) { const generics = {}; const bases = {}; const typeGroups = []; const types = []; for (let i = 0; i < nodes.length; i++) { const node = nodes[i]; if (!node) continue; if (types.indexOf(node) >= 0) { continue; } if ((0, _generated.isAnyTypeAnnotation)(node)) { return [node]; } if ((0, _generated.isFlowBaseAnnotation)(node)) { bases[node.type] = node; continue; } if ((0, _generated.isUnionTypeAnnotation)(node)) { if (typeGroups.indexOf(node.types) < 0) { nodes = nodes.concat(node.types); typeGroups.push(node.types); } continue; } if ((0, _generated.isGenericTypeAnnotation)(node)) { const name = node.id.name; if (generics[name]) { let existing = generics[name]; if (existing.typeParameters) { if (node.typeParameters) { existing.typeParameters.params = removeTypeDuplicates(existing.typeParameters.params.concat(node.typeParameters.params)); } } else { existing = node.typeParameters; } } else { generics[name] = node; } continue; } types.push(node); } for (const type of Object.keys(bases)) { types.push(bases[type]); } for (const name of Object.keys(generics)) { types.push(generics[name]); } return types; } },{"../../validators/generated":157}],145:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = inherits; var _constants = require("../constants"); var _inheritsComments = _interopRequireDefault(require("../comments/inheritsComments")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function inherits(child, parent) { if (!child || !parent) return child; for (const key of _constants.INHERIT_KEYS.optional) { if (child[key] == null) { child[key] = parent[key]; } } for (const key of Object.keys(parent)) { if (key[0] === "_" && key !== "__clone") child[key] = parent[key]; } for (const key of _constants.INHERIT_KEYS.force) { child[key] = parent[key]; } (0, _inheritsComments.default)(child, parent); return child; } },{"../comments/inheritsComments":117,"../constants":120}],146:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = prependToMemberExpression; var _generated = require("../builders/generated"); function prependToMemberExpression(member, prepend) { member.object = (0, _generated.memberExpression)(prepend, member.object); return member; } },{"../builders/generated":106}],147:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = removeProperties; var _constants = require("../constants"); const CLEAR_KEYS = ["tokens", "start", "end", "loc", "raw", "rawValue"]; const CLEAR_KEYS_PLUS_COMMENTS = _constants.COMMENT_KEYS.concat(["comments"]).concat(CLEAR_KEYS); function removeProperties(node, opts = {}) { const map = opts.preserveComments ? CLEAR_KEYS : CLEAR_KEYS_PLUS_COMMENTS; for (const key of map) { if (node[key] != null) node[key] = undefined; } for (const key of Object.keys(node)) { if (key[0] === "_" && node[key] != null) node[key] = undefined; } const symbols = Object.getOwnPropertySymbols(node); for (const sym of symbols) { node[sym] = null; } } },{"../constants":120}],148:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = removePropertiesDeep; var _traverseFast = _interopRequireDefault(require("../traverse/traverseFast")); var _removeProperties = _interopRequireDefault(require("./removeProperties")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function removePropertiesDeep(tree, opts) { (0, _traverseFast.default)(tree, _removeProperties.default, opts); return tree; } },{"../traverse/traverseFast":152,"./removeProperties":147}],149:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = getBindingIdentifiers; var _generated = require("../validators/generated"); function getBindingIdentifiers(node, duplicates, outerOnly) { let search = [].concat(node); const ids = Object.create(null); while (search.length) { const id = search.shift(); if (!id) continue; const keys = getBindingIdentifiers.keys[id.type]; if ((0, _generated.isIdentifier)(id)) { if (duplicates) { const _ids = ids[id.name] = ids[id.name] || []; _ids.push(id); } else { ids[id.name] = id; } continue; } if ((0, _generated.isExportDeclaration)(id)) { if ((0, _generated.isDeclaration)(id.declaration)) { search.push(id.declaration); } continue; } if (outerOnly) { if ((0, _generated.isFunctionDeclaration)(id)) { search.push(id.id); continue; } if ((0, _generated.isFunctionExpression)(id)) { continue; } } if (keys) { for (let i = 0; i < keys.length; i++) { const key = keys[i]; if (id[key]) { search = search.concat(id[key]); } } } } return ids; } getBindingIdentifiers.keys = { DeclareClass: ["id"], DeclareFunction: ["id"], DeclareModule: ["id"], DeclareVariable: ["id"], DeclareInterface: ["id"], DeclareTypeAlias: ["id"], DeclareOpaqueType: ["id"], InterfaceDeclaration: ["id"], TypeAlias: ["id"], OpaqueType: ["id"], CatchClause: ["param"], LabeledStatement: ["label"], UnaryExpression: ["argument"], AssignmentExpression: ["left"], ImportSpecifier: ["local"], ImportNamespaceSpecifier: ["local"], ImportDefaultSpecifier: ["local"], ImportDeclaration: ["specifiers"], ExportSpecifier: ["exported"], ExportNamespaceSpecifier: ["exported"], ExportDefaultSpecifier: ["exported"], FunctionDeclaration: ["id", "params"], FunctionExpression: ["id", "params"], ArrowFunctionExpression: ["params"], ObjectMethod: ["params"], ClassMethod: ["params"], ForInStatement: ["left"], ForOfStatement: ["left"], ClassDeclaration: ["id"], ClassExpression: ["id"], RestElement: ["argument"], UpdateExpression: ["argument"], ObjectProperty: ["value"], AssignmentPattern: ["left"], ArrayPattern: ["elements"], ObjectPattern: ["properties"], VariableDeclaration: ["declarations"], VariableDeclarator: ["id"] }; },{"../validators/generated":157}],150:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = getOuterBindingIdentifiers; var _getBindingIdentifiers = _interopRequireDefault(require("./getBindingIdentifiers")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function getOuterBindingIdentifiers(node, duplicates) { return (0, _getBindingIdentifiers.default)(node, duplicates, true); } },{"./getBindingIdentifiers":149}],151:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = traverse; var _definitions = require("../definitions"); function traverse(node, handlers, state) { if (typeof handlers === "function") { handlers = { enter: handlers }; } const { enter, exit } = handlers; traverseSimpleImpl(node, enter, exit, state, []); } function traverseSimpleImpl(node, enter, exit, state, ancestors) { const keys = _definitions.VISITOR_KEYS[node.type]; if (!keys) return; if (enter) enter(node, ancestors, state); for (const key of keys) { const subNode = node[key]; if (Array.isArray(subNode)) { for (let i = 0; i < subNode.length; i++) { const child = subNode[i]; if (!child) continue; ancestors.push({ node, key, index: i }); traverseSimpleImpl(child, enter, exit, state, ancestors); ancestors.pop(); } } else if (subNode) { ancestors.push({ node, key }); traverseSimpleImpl(subNode, enter, exit, state, ancestors); ancestors.pop(); } } if (exit) exit(node, ancestors, state); } },{"../definitions":136}],152:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = traverseFast; var _definitions = require("../definitions"); function traverseFast(node, enter, opts) { if (!node) return; const keys = _definitions.VISITOR_KEYS[node.type]; if (!keys) return; opts = opts || {}; enter(node, opts); for (const key of keys) { const subNode = node[key]; if (Array.isArray(subNode)) { for (const node of subNode) { traverseFast(node, enter, opts); } } else { traverseFast(subNode, enter, opts); } } } },{"../definitions":136}],153:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = inherit; function _uniq() { const data = _interopRequireDefault(require("lodash/uniq")); _uniq = function () { return data; }; return data; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function inherit(key, child, parent) { if (child && parent) { child[key] = (0, _uniq().default)([].concat(child[key], parent[key]).filter(Boolean)); } } },{"lodash/uniq":399}],154:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = cleanJSXElementLiteralChild; var _generated = require("../../builders/generated"); function cleanJSXElementLiteralChild(child, args) { const lines = child.value.split(/\r\n|\n|\r/); let lastNonEmptyLine = 0; for (let i = 0; i < lines.length; i++) { if (lines[i].match(/[^ \t]/)) { lastNonEmptyLine = i; } } let str = ""; for (let i = 0; i < lines.length; i++) { const line = lines[i]; const isFirstLine = i === 0; const isLastLine = i === lines.length - 1; const isLastNonEmptyLine = i === lastNonEmptyLine; let trimmedLine = line.replace(/\t/g, " "); if (!isFirstLine) { trimmedLine = trimmedLine.replace(/^[ ]+/, ""); } if (!isLastLine) { trimmedLine = trimmedLine.replace(/[ ]+$/, ""); } if (trimmedLine) { if (!isLastNonEmptyLine) { trimmedLine += " "; } str += trimmedLine; } } if (str) args.push((0, _generated.stringLiteral)(str)); } },{"../../builders/generated":106}],155:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = shallowEqual; function shallowEqual(actual, expected) { const keys = Object.keys(expected); for (const key of keys) { if (actual[key] !== expected[key]) { return false; } } return true; } },{}],156:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = buildMatchMemberExpression; var _matchesPattern = _interopRequireDefault(require("./matchesPattern")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function buildMatchMemberExpression(match, allowPartial) { const parts = match.split("."); return member => (0, _matchesPattern.default)(member, parts, allowPartial); } },{"./matchesPattern":173}],157:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isArrayExpression = isArrayExpression; exports.isAssignmentExpression = isAssignmentExpression; exports.isBinaryExpression = isBinaryExpression; exports.isInterpreterDirective = isInterpreterDirective; exports.isDirective = isDirective; exports.isDirectiveLiteral = isDirectiveLiteral; exports.isBlockStatement = isBlockStatement; exports.isBreakStatement = isBreakStatement; exports.isCallExpression = isCallExpression; exports.isCatchClause = isCatchClause; exports.isConditionalExpression = isConditionalExpression; exports.isContinueStatement = isContinueStatement; exports.isDebuggerStatement = isDebuggerStatement; exports.isDoWhileStatement = isDoWhileStatement; exports.isEmptyStatement = isEmptyStatement; exports.isExpressionStatement = isExpressionStatement; exports.isFile = isFile; exports.isForInStatement = isForInStatement; exports.isForStatement = isForStatement; exports.isFunctionDeclaration = isFunctionDeclaration; exports.isFunctionExpression = isFunctionExpression; exports.isIdentifier = isIdentifier; exports.isIfStatement = isIfStatement; exports.isLabeledStatement = isLabeledStatement; exports.isStringLiteral = isStringLiteral; exports.isNumericLiteral = isNumericLiteral; exports.isNullLiteral = isNullLiteral; exports.isBooleanLiteral = isBooleanLiteral; exports.isRegExpLiteral = isRegExpLiteral; exports.isLogicalExpression = isLogicalExpression; exports.isMemberExpression = isMemberExpression; exports.isNewExpression = isNewExpression; exports.isProgram = isProgram; exports.isObjectExpression = isObjectExpression; exports.isObjectMethod = isObjectMethod; exports.isObjectProperty = isObjectProperty; exports.isRestElement = isRestElement; exports.isReturnStatement = isReturnStatement; exports.isSequenceExpression = isSequenceExpression; exports.isParenthesizedExpression = isParenthesizedExpression; exports.isSwitchCase = isSwitchCase; exports.isSwitchStatement = isSwitchStatement; exports.isThisExpression = isThisExpression; exports.isThrowStatement = isThrowStatement; exports.isTryStatement = isTryStatement; exports.isUnaryExpression = isUnaryExpression; exports.isUpdateExpression = isUpdateExpression; exports.isVariableDeclaration = isVariableDeclaration; exports.isVariableDeclarator = isVariableDeclarator; exports.isWhileStatement = isWhileStatement; exports.isWithStatement = isWithStatement; exports.isAssignmentPattern = isAssignmentPattern; exports.isArrayPattern = isArrayPattern; exports.isArrowFunctionExpression = isArrowFunctionExpression; exports.isClassBody = isClassBody; exports.isClassDeclaration = isClassDeclaration; exports.isClassExpression = isClassExpression; exports.isExportAllDeclaration = isExportAllDeclaration; exports.isExportDefaultDeclaration = isExportDefaultDeclaration; exports.isExportNamedDeclaration = isExportNamedDeclaration; exports.isExportSpecifier = isExportSpecifier; exports.isForOfStatement = isForOfStatement; exports.isImportDeclaration = isImportDeclaration; exports.isImportDefaultSpecifier = isImportDefaultSpecifier; exports.isImportNamespaceSpecifier = isImportNamespaceSpecifier; exports.isImportSpecifier = isImportSpecifier; exports.isMetaProperty = isMetaProperty; exports.isClassMethod = isClassMethod; exports.isObjectPattern = isObjectPattern; exports.isSpreadElement = isSpreadElement; exports.isSuper = isSuper; exports.isTaggedTemplateExpression = isTaggedTemplateExpression; exports.isTemplateElement = isTemplateElement; exports.isTemplateLiteral = isTemplateLiteral; exports.isYieldExpression = isYieldExpression; exports.isAnyTypeAnnotation = isAnyTypeAnnotation; exports.isArrayTypeAnnotation = isArrayTypeAnnotation; exports.isBooleanTypeAnnotation = isBooleanTypeAnnotation; exports.isBooleanLiteralTypeAnnotation = isBooleanLiteralTypeAnnotation; exports.isNullLiteralTypeAnnotation = isNullLiteralTypeAnnotation; exports.isClassImplements = isClassImplements; exports.isDeclareClass = isDeclareClass; exports.isDeclareFunction = isDeclareFunction; exports.isDeclareInterface = isDeclareInterface; exports.isDeclareModule = isDeclareModule; exports.isDeclareModuleExports = isDeclareModuleExports; exports.isDeclareTypeAlias = isDeclareTypeAlias; exports.isDeclareOpaqueType = isDeclareOpaqueType; exports.isDeclareVariable = isDeclareVariable; exports.isDeclareExportDeclaration = isDeclareExportDeclaration; exports.isDeclareExportAllDeclaration = isDeclareExportAllDeclaration; exports.isDeclaredPredicate = isDeclaredPredicate; exports.isExistsTypeAnnotation = isExistsTypeAnnotation; exports.isFunctionTypeAnnotation = isFunctionTypeAnnotation; exports.isFunctionTypeParam = isFunctionTypeParam; exports.isGenericTypeAnnotation = isGenericTypeAnnotation; exports.isInferredPredicate = isInferredPredicate; exports.isInterfaceExtends = isInterfaceExtends; exports.isInterfaceDeclaration = isInterfaceDeclaration; exports.isInterfaceTypeAnnotation = isInterfaceTypeAnnotation; exports.isIntersectionTypeAnnotation = isIntersectionTypeAnnotation; exports.isMixedTypeAnnotation = isMixedTypeAnnotation; exports.isEmptyTypeAnnotation = isEmptyTypeAnnotation; exports.isNullableTypeAnnotation = isNullableTypeAnnotation; exports.isNumberLiteralTypeAnnotation = isNumberLiteralTypeAnnotation; exports.isNumberTypeAnnotation = isNumberTypeAnnotation; exports.isObjectTypeAnnotation = isObjectTypeAnnotation; exports.isObjectTypeInternalSlot = isObjectTypeInternalSlot; exports.isObjectTypeCallProperty = isObjectTypeCallProperty; exports.isObjectTypeIndexer = isObjectTypeIndexer; exports.isObjectTypeProperty = isObjectTypeProperty; exports.isObjectTypeSpreadProperty = isObjectTypeSpreadProperty; exports.isOpaqueType = isOpaqueType; exports.isQualifiedTypeIdentifier = isQualifiedTypeIdentifier; exports.isStringLiteralTypeAnnotation = isStringLiteralTypeAnnotation; exports.isStringTypeAnnotation = isStringTypeAnnotation; exports.isThisTypeAnnotation = isThisTypeAnnotation; exports.isTupleTypeAnnotation = isTupleTypeAnnotation; exports.isTypeofTypeAnnotation = isTypeofTypeAnnotation; exports.isTypeAlias = isTypeAlias; exports.isTypeAnnotation = isTypeAnnotation; exports.isTypeCastExpression = isTypeCastExpression; exports.isTypeParameter = isTypeParameter; exports.isTypeParameterDeclaration = isTypeParameterDeclaration; exports.isTypeParameterInstantiation = isTypeParameterInstantiation; exports.isUnionTypeAnnotation = isUnionTypeAnnotation; exports.isVariance = isVariance; exports.isVoidTypeAnnotation = isVoidTypeAnnotation; exports.isJSXAttribute = isJSXAttribute; exports.isJSXClosingElement = isJSXClosingElement; exports.isJSXElement = isJSXElement; exports.isJSXEmptyExpression = isJSXEmptyExpression; exports.isJSXExpressionContainer = isJSXExpressionContainer; exports.isJSXSpreadChild = isJSXSpreadChild; exports.isJSXIdentifier = isJSXIdentifier; exports.isJSXMemberExpression = isJSXMemberExpression; exports.isJSXNamespacedName = isJSXNamespacedName; exports.isJSXOpeningElement = isJSXOpeningElement; exports.isJSXSpreadAttribute = isJSXSpreadAttribute; exports.isJSXText = isJSXText; exports.isJSXFragment = isJSXFragment; exports.isJSXOpeningFragment = isJSXOpeningFragment; exports.isJSXClosingFragment = isJSXClosingFragment; exports.isNoop = isNoop; exports.isPlaceholder = isPlaceholder; exports.isArgumentPlaceholder = isArgumentPlaceholder; exports.isAwaitExpression = isAwaitExpression; exports.isBindExpression = isBindExpression; exports.isClassProperty = isClassProperty; exports.isOptionalMemberExpression = isOptionalMemberExpression; exports.isPipelineTopicExpression = isPipelineTopicExpression; exports.isPipelineBareFunction = isPipelineBareFunction; exports.isPipelinePrimaryTopicReference = isPipelinePrimaryTopicReference; exports.isOptionalCallExpression = isOptionalCallExpression; exports.isClassPrivateProperty = isClassPrivateProperty; exports.isClassPrivateMethod = isClassPrivateMethod; exports.isImport = isImport; exports.isDecorator = isDecorator; exports.isDoExpression = isDoExpression; exports.isExportDefaultSpecifier = isExportDefaultSpecifier; exports.isExportNamespaceSpecifier = isExportNamespaceSpecifier; exports.isPrivateName = isPrivateName; exports.isBigIntLiteral = isBigIntLiteral; exports.isTSParameterProperty = isTSParameterProperty; exports.isTSDeclareFunction = isTSDeclareFunction; exports.isTSDeclareMethod = isTSDeclareMethod; exports.isTSQualifiedName = isTSQualifiedName; exports.isTSCallSignatureDeclaration = isTSCallSignatureDeclaration; exports.isTSConstructSignatureDeclaration = isTSConstructSignatureDeclaration; exports.isTSPropertySignature = isTSPropertySignature; exports.isTSMethodSignature = isTSMethodSignature; exports.isTSIndexSignature = isTSIndexSignature; exports.isTSAnyKeyword = isTSAnyKeyword; exports.isTSUnknownKeyword = isTSUnknownKeyword; exports.isTSNumberKeyword = isTSNumberKeyword; exports.isTSObjectKeyword = isTSObjectKeyword; exports.isTSBooleanKeyword = isTSBooleanKeyword; exports.isTSStringKeyword = isTSStringKeyword; exports.isTSSymbolKeyword = isTSSymbolKeyword; exports.isTSVoidKeyword = isTSVoidKeyword; exports.isTSUndefinedKeyword = isTSUndefinedKeyword; exports.isTSNullKeyword = isTSNullKeyword; exports.isTSNeverKeyword = isTSNeverKeyword; exports.isTSThisType = isTSThisType; exports.isTSFunctionType = isTSFunctionType; exports.isTSConstructorType = isTSConstructorType; exports.isTSTypeReference = isTSTypeReference; exports.isTSTypePredicate = isTSTypePredicate; exports.isTSTypeQuery = isTSTypeQuery; exports.isTSTypeLiteral = isTSTypeLiteral; exports.isTSArrayType = isTSArrayType; exports.isTSTupleType = isTSTupleType; exports.isTSOptionalType = isTSOptionalType; exports.isTSRestType = isTSRestType; exports.isTSUnionType = isTSUnionType; exports.isTSIntersectionType = isTSIntersectionType; exports.isTSConditionalType = isTSConditionalType; exports.isTSInferType = isTSInferType; exports.isTSParenthesizedType = isTSParenthesizedType; exports.isTSTypeOperator = isTSTypeOperator; exports.isTSIndexedAccessType = isTSIndexedAccessType; exports.isTSMappedType = isTSMappedType; exports.isTSLiteralType = isTSLiteralType; exports.isTSExpressionWithTypeArguments = isTSExpressionWithTypeArguments; exports.isTSInterfaceDeclaration = isTSInterfaceDeclaration; exports.isTSInterfaceBody = isTSInterfaceBody; exports.isTSTypeAliasDeclaration = isTSTypeAliasDeclaration; exports.isTSAsExpression = isTSAsExpression; exports.isTSTypeAssertion = isTSTypeAssertion; exports.isTSEnumDeclaration = isTSEnumDeclaration; exports.isTSEnumMember = isTSEnumMember; exports.isTSModuleDeclaration = isTSModuleDeclaration; exports.isTSModuleBlock = isTSModuleBlock; exports.isTSImportType = isTSImportType; exports.isTSImportEqualsDeclaration = isTSImportEqualsDeclaration; exports.isTSExternalModuleReference = isTSExternalModuleReference; exports.isTSNonNullExpression = isTSNonNullExpression; exports.isTSExportAssignment = isTSExportAssignment; exports.isTSNamespaceExportDeclaration = isTSNamespaceExportDeclaration; exports.isTSTypeAnnotation = isTSTypeAnnotation; exports.isTSTypeParameterInstantiation = isTSTypeParameterInstantiation; exports.isTSTypeParameterDeclaration = isTSTypeParameterDeclaration; exports.isTSTypeParameter = isTSTypeParameter; exports.isExpression = isExpression; exports.isBinary = isBinary; exports.isScopable = isScopable; exports.isBlockParent = isBlockParent; exports.isBlock = isBlock; exports.isStatement = isStatement; exports.isTerminatorless = isTerminatorless; exports.isCompletionStatement = isCompletionStatement; exports.isConditional = isConditional; exports.isLoop = isLoop; exports.isWhile = isWhile; exports.isExpressionWrapper = isExpressionWrapper; exports.isFor = isFor; exports.isForXStatement = isForXStatement; exports.isFunction = isFunction; exports.isFunctionParent = isFunctionParent; exports.isPureish = isPureish; exports.isDeclaration = isDeclaration; exports.isPatternLike = isPatternLike; exports.isLVal = isLVal; exports.isTSEntityName = isTSEntityName; exports.isLiteral = isLiteral; exports.isImmutable = isImmutable; exports.isUserWhitespacable = isUserWhitespacable; exports.isMethod = isMethod; exports.isObjectMember = isObjectMember; exports.isProperty = isProperty; exports.isUnaryLike = isUnaryLike; exports.isPattern = isPattern; exports.isClass = isClass; exports.isModuleDeclaration = isModuleDeclaration; exports.isExportDeclaration = isExportDeclaration; exports.isModuleSpecifier = isModuleSpecifier; exports.isFlow = isFlow; exports.isFlowType = isFlowType; exports.isFlowBaseAnnotation = isFlowBaseAnnotation; exports.isFlowDeclaration = isFlowDeclaration; exports.isFlowPredicate = isFlowPredicate; exports.isJSX = isJSX; exports.isPrivate = isPrivate; exports.isTSTypeElement = isTSTypeElement; exports.isTSType = isTSType; exports.isNumberLiteral = isNumberLiteral; exports.isRegexLiteral = isRegexLiteral; exports.isRestProperty = isRestProperty; exports.isSpreadProperty = isSpreadProperty; var _shallowEqual = _interopRequireDefault(require("../../utils/shallowEqual")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function isArrayExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ArrayExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isAssignmentExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "AssignmentExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isBinaryExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "BinaryExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isInterpreterDirective(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "InterpreterDirective") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDirective(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Directive") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDirectiveLiteral(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DirectiveLiteral") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isBlockStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "BlockStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isBreakStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "BreakStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isCallExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "CallExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isCatchClause(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "CatchClause") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isConditionalExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ConditionalExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isContinueStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ContinueStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDebuggerStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DebuggerStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDoWhileStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DoWhileStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isEmptyStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "EmptyStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isExpressionStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ExpressionStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isFile(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "File") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isForInStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ForInStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isForStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ForStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isFunctionDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "FunctionDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isFunctionExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "FunctionExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isIdentifier(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Identifier") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isIfStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "IfStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isLabeledStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "LabeledStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isStringLiteral(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "StringLiteral") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isNumericLiteral(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "NumericLiteral") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isNullLiteral(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "NullLiteral") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isBooleanLiteral(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "BooleanLiteral") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isRegExpLiteral(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "RegExpLiteral") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isLogicalExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "LogicalExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isMemberExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "MemberExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isNewExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "NewExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isProgram(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Program") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isObjectExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ObjectExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isObjectMethod(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ObjectMethod") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isObjectProperty(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ObjectProperty") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isRestElement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "RestElement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isReturnStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ReturnStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isSequenceExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "SequenceExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isParenthesizedExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ParenthesizedExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isSwitchCase(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "SwitchCase") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isSwitchStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "SwitchStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isThisExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ThisExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isThrowStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ThrowStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTryStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TryStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isUnaryExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "UnaryExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isUpdateExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "UpdateExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isVariableDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "VariableDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isVariableDeclarator(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "VariableDeclarator") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isWhileStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "WhileStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isWithStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "WithStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isAssignmentPattern(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "AssignmentPattern") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isArrayPattern(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ArrayPattern") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isArrowFunctionExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ArrowFunctionExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isClassBody(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ClassBody") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isClassDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ClassDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isClassExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ClassExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isExportAllDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ExportAllDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isExportDefaultDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ExportDefaultDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isExportNamedDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ExportNamedDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isExportSpecifier(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ExportSpecifier") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isForOfStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ForOfStatement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isImportDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ImportDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isImportDefaultSpecifier(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ImportDefaultSpecifier") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isImportNamespaceSpecifier(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ImportNamespaceSpecifier") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isImportSpecifier(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ImportSpecifier") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isMetaProperty(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "MetaProperty") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isClassMethod(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ClassMethod") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isObjectPattern(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ObjectPattern") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isSpreadElement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "SpreadElement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isSuper(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Super") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTaggedTemplateExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TaggedTemplateExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTemplateElement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TemplateElement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTemplateLiteral(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TemplateLiteral") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isYieldExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "YieldExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isAnyTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "AnyTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isArrayTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ArrayTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isBooleanTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "BooleanTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isBooleanLiteralTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "BooleanLiteralTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isNullLiteralTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "NullLiteralTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isClassImplements(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ClassImplements") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDeclareClass(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DeclareClass") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDeclareFunction(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DeclareFunction") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDeclareInterface(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DeclareInterface") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDeclareModule(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DeclareModule") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDeclareModuleExports(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DeclareModuleExports") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDeclareTypeAlias(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DeclareTypeAlias") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDeclareOpaqueType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DeclareOpaqueType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDeclareVariable(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DeclareVariable") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDeclareExportDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DeclareExportDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDeclareExportAllDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DeclareExportAllDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDeclaredPredicate(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DeclaredPredicate") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isExistsTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ExistsTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isFunctionTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "FunctionTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isFunctionTypeParam(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "FunctionTypeParam") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isGenericTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "GenericTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isInferredPredicate(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "InferredPredicate") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isInterfaceExtends(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "InterfaceExtends") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isInterfaceDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "InterfaceDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isInterfaceTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "InterfaceTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isIntersectionTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "IntersectionTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isMixedTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "MixedTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isEmptyTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "EmptyTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isNullableTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "NullableTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isNumberLiteralTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "NumberLiteralTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isNumberTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "NumberTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isObjectTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ObjectTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isObjectTypeInternalSlot(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ObjectTypeInternalSlot") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isObjectTypeCallProperty(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ObjectTypeCallProperty") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isObjectTypeIndexer(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ObjectTypeIndexer") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isObjectTypeProperty(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ObjectTypeProperty") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isObjectTypeSpreadProperty(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ObjectTypeSpreadProperty") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isOpaqueType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "OpaqueType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isQualifiedTypeIdentifier(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "QualifiedTypeIdentifier") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isStringLiteralTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "StringLiteralTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isStringTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "StringTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isThisTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ThisTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTupleTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TupleTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTypeofTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TypeofTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTypeAlias(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TypeAlias") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTypeCastExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TypeCastExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTypeParameter(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TypeParameter") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTypeParameterDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TypeParameterDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTypeParameterInstantiation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TypeParameterInstantiation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isUnionTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "UnionTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isVariance(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Variance") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isVoidTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "VoidTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXAttribute(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXAttribute") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXClosingElement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXClosingElement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXElement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXElement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXEmptyExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXEmptyExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXExpressionContainer(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXExpressionContainer") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXSpreadChild(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXSpreadChild") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXIdentifier(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXIdentifier") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXMemberExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXMemberExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXNamespacedName(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXNamespacedName") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXOpeningElement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXOpeningElement") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXSpreadAttribute(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXSpreadAttribute") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXText(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXText") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXFragment(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXFragment") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXOpeningFragment(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXOpeningFragment") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSXClosingFragment(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSXClosingFragment") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isNoop(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Noop") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isPlaceholder(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Placeholder") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isArgumentPlaceholder(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ArgumentPlaceholder") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isAwaitExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "AwaitExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isBindExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "BindExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isClassProperty(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ClassProperty") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isOptionalMemberExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "OptionalMemberExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isPipelineTopicExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "PipelineTopicExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isPipelineBareFunction(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "PipelineBareFunction") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isPipelinePrimaryTopicReference(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "PipelinePrimaryTopicReference") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isOptionalCallExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "OptionalCallExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isClassPrivateProperty(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ClassPrivateProperty") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isClassPrivateMethod(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ClassPrivateMethod") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isImport(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Import") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDecorator(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Decorator") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDoExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DoExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isExportDefaultSpecifier(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ExportDefaultSpecifier") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isExportNamespaceSpecifier(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ExportNamespaceSpecifier") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isPrivateName(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "PrivateName") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isBigIntLiteral(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "BigIntLiteral") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSParameterProperty(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSParameterProperty") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSDeclareFunction(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSDeclareFunction") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSDeclareMethod(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSDeclareMethod") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSQualifiedName(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSQualifiedName") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSCallSignatureDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSCallSignatureDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSConstructSignatureDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSConstructSignatureDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSPropertySignature(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSPropertySignature") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSMethodSignature(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSMethodSignature") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSIndexSignature(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSIndexSignature") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSAnyKeyword(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSAnyKeyword") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSUnknownKeyword(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSUnknownKeyword") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSNumberKeyword(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSNumberKeyword") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSObjectKeyword(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSObjectKeyword") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSBooleanKeyword(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSBooleanKeyword") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSStringKeyword(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSStringKeyword") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSSymbolKeyword(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSSymbolKeyword") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSVoidKeyword(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSVoidKeyword") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSUndefinedKeyword(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSUndefinedKeyword") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSNullKeyword(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSNullKeyword") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSNeverKeyword(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSNeverKeyword") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSThisType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSThisType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSFunctionType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSFunctionType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSConstructorType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSConstructorType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSTypeReference(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSTypeReference") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSTypePredicate(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSTypePredicate") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSTypeQuery(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSTypeQuery") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSTypeLiteral(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSTypeLiteral") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSArrayType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSArrayType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSTupleType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSTupleType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSOptionalType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSOptionalType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSRestType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSRestType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSUnionType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSUnionType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSIntersectionType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSIntersectionType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSConditionalType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSConditionalType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSInferType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSInferType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSParenthesizedType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSParenthesizedType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSTypeOperator(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSTypeOperator") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSIndexedAccessType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSIndexedAccessType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSMappedType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSMappedType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSLiteralType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSLiteralType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSExpressionWithTypeArguments(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSExpressionWithTypeArguments") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSInterfaceDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSInterfaceDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSInterfaceBody(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSInterfaceBody") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSTypeAliasDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSTypeAliasDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSAsExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSAsExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSTypeAssertion(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSTypeAssertion") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSEnumDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSEnumDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSEnumMember(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSEnumMember") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSModuleDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSModuleDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSModuleBlock(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSModuleBlock") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSImportType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSImportType") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSImportEqualsDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSImportEqualsDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSExternalModuleReference(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSExternalModuleReference") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSNonNullExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSNonNullExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSExportAssignment(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSExportAssignment") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSNamespaceExportDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSNamespaceExportDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSTypeAnnotation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSTypeParameterInstantiation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSTypeParameterInstantiation") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSTypeParameterDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSTypeParameterDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSTypeParameter(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSTypeParameter") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Expression" || "ArrayExpression" === nodeType || "AssignmentExpression" === nodeType || "BinaryExpression" === nodeType || "CallExpression" === nodeType || "ConditionalExpression" === nodeType || "FunctionExpression" === nodeType || "Identifier" === nodeType || "StringLiteral" === nodeType || "NumericLiteral" === nodeType || "NullLiteral" === nodeType || "BooleanLiteral" === nodeType || "RegExpLiteral" === nodeType || "LogicalExpression" === nodeType || "MemberExpression" === nodeType || "NewExpression" === nodeType || "ObjectExpression" === nodeType || "SequenceExpression" === nodeType || "ParenthesizedExpression" === nodeType || "ThisExpression" === nodeType || "UnaryExpression" === nodeType || "UpdateExpression" === nodeType || "ArrowFunctionExpression" === nodeType || "ClassExpression" === nodeType || "MetaProperty" === nodeType || "Super" === nodeType || "TaggedTemplateExpression" === nodeType || "TemplateLiteral" === nodeType || "YieldExpression" === nodeType || "TypeCastExpression" === nodeType || "JSXElement" === nodeType || "JSXFragment" === nodeType || "AwaitExpression" === nodeType || "BindExpression" === nodeType || "OptionalMemberExpression" === nodeType || "PipelinePrimaryTopicReference" === nodeType || "OptionalCallExpression" === nodeType || "Import" === nodeType || "DoExpression" === nodeType || "BigIntLiteral" === nodeType || "TSAsExpression" === nodeType || "TSTypeAssertion" === nodeType || "TSNonNullExpression" === nodeType || nodeType === "Placeholder" && ("Expression" === node.expectedNode || "Identifier" === node.expectedNode || "StringLiteral" === node.expectedNode)) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isBinary(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Binary" || "BinaryExpression" === nodeType || "LogicalExpression" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isScopable(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Scopable" || "BlockStatement" === nodeType || "CatchClause" === nodeType || "DoWhileStatement" === nodeType || "ForInStatement" === nodeType || "ForStatement" === nodeType || "FunctionDeclaration" === nodeType || "FunctionExpression" === nodeType || "Program" === nodeType || "ObjectMethod" === nodeType || "SwitchStatement" === nodeType || "WhileStatement" === nodeType || "ArrowFunctionExpression" === nodeType || "ClassDeclaration" === nodeType || "ClassExpression" === nodeType || "ForOfStatement" === nodeType || "ClassMethod" === nodeType || "ClassPrivateMethod" === nodeType || nodeType === "Placeholder" && "BlockStatement" === node.expectedNode) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isBlockParent(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "BlockParent" || "BlockStatement" === nodeType || "CatchClause" === nodeType || "DoWhileStatement" === nodeType || "ForInStatement" === nodeType || "ForStatement" === nodeType || "FunctionDeclaration" === nodeType || "FunctionExpression" === nodeType || "Program" === nodeType || "ObjectMethod" === nodeType || "SwitchStatement" === nodeType || "WhileStatement" === nodeType || "ArrowFunctionExpression" === nodeType || "ForOfStatement" === nodeType || "ClassMethod" === nodeType || "ClassPrivateMethod" === nodeType || nodeType === "Placeholder" && "BlockStatement" === node.expectedNode) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isBlock(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Block" || "BlockStatement" === nodeType || "Program" === nodeType || nodeType === "Placeholder" && "BlockStatement" === node.expectedNode) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Statement" || "BlockStatement" === nodeType || "BreakStatement" === nodeType || "ContinueStatement" === nodeType || "DebuggerStatement" === nodeType || "DoWhileStatement" === nodeType || "EmptyStatement" === nodeType || "ExpressionStatement" === nodeType || "ForInStatement" === nodeType || "ForStatement" === nodeType || "FunctionDeclaration" === nodeType || "IfStatement" === nodeType || "LabeledStatement" === nodeType || "ReturnStatement" === nodeType || "SwitchStatement" === nodeType || "ThrowStatement" === nodeType || "TryStatement" === nodeType || "VariableDeclaration" === nodeType || "WhileStatement" === nodeType || "WithStatement" === nodeType || "ClassDeclaration" === nodeType || "ExportAllDeclaration" === nodeType || "ExportDefaultDeclaration" === nodeType || "ExportNamedDeclaration" === nodeType || "ForOfStatement" === nodeType || "ImportDeclaration" === nodeType || "DeclareClass" === nodeType || "DeclareFunction" === nodeType || "DeclareInterface" === nodeType || "DeclareModule" === nodeType || "DeclareModuleExports" === nodeType || "DeclareTypeAlias" === nodeType || "DeclareOpaqueType" === nodeType || "DeclareVariable" === nodeType || "DeclareExportDeclaration" === nodeType || "DeclareExportAllDeclaration" === nodeType || "InterfaceDeclaration" === nodeType || "OpaqueType" === nodeType || "TypeAlias" === nodeType || "TSDeclareFunction" === nodeType || "TSInterfaceDeclaration" === nodeType || "TSTypeAliasDeclaration" === nodeType || "TSEnumDeclaration" === nodeType || "TSModuleDeclaration" === nodeType || "TSImportEqualsDeclaration" === nodeType || "TSExportAssignment" === nodeType || "TSNamespaceExportDeclaration" === nodeType || nodeType === "Placeholder" && ("Statement" === node.expectedNode || "Declaration" === node.expectedNode || "BlockStatement" === node.expectedNode)) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTerminatorless(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Terminatorless" || "BreakStatement" === nodeType || "ContinueStatement" === nodeType || "ReturnStatement" === nodeType || "ThrowStatement" === nodeType || "YieldExpression" === nodeType || "AwaitExpression" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isCompletionStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "CompletionStatement" || "BreakStatement" === nodeType || "ContinueStatement" === nodeType || "ReturnStatement" === nodeType || "ThrowStatement" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isConditional(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Conditional" || "ConditionalExpression" === nodeType || "IfStatement" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isLoop(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Loop" || "DoWhileStatement" === nodeType || "ForInStatement" === nodeType || "ForStatement" === nodeType || "WhileStatement" === nodeType || "ForOfStatement" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isWhile(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "While" || "DoWhileStatement" === nodeType || "WhileStatement" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isExpressionWrapper(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ExpressionWrapper" || "ExpressionStatement" === nodeType || "ParenthesizedExpression" === nodeType || "TypeCastExpression" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isFor(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "For" || "ForInStatement" === nodeType || "ForStatement" === nodeType || "ForOfStatement" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isForXStatement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ForXStatement" || "ForInStatement" === nodeType || "ForOfStatement" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isFunction(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Function" || "FunctionDeclaration" === nodeType || "FunctionExpression" === nodeType || "ObjectMethod" === nodeType || "ArrowFunctionExpression" === nodeType || "ClassMethod" === nodeType || "ClassPrivateMethod" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isFunctionParent(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "FunctionParent" || "FunctionDeclaration" === nodeType || "FunctionExpression" === nodeType || "ObjectMethod" === nodeType || "ArrowFunctionExpression" === nodeType || "ClassMethod" === nodeType || "ClassPrivateMethod" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isPureish(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Pureish" || "FunctionDeclaration" === nodeType || "FunctionExpression" === nodeType || "StringLiteral" === nodeType || "NumericLiteral" === nodeType || "NullLiteral" === nodeType || "BooleanLiteral" === nodeType || "ArrowFunctionExpression" === nodeType || "ClassDeclaration" === nodeType || "ClassExpression" === nodeType || "BigIntLiteral" === nodeType || nodeType === "Placeholder" && "StringLiteral" === node.expectedNode) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Declaration" || "FunctionDeclaration" === nodeType || "VariableDeclaration" === nodeType || "ClassDeclaration" === nodeType || "ExportAllDeclaration" === nodeType || "ExportDefaultDeclaration" === nodeType || "ExportNamedDeclaration" === nodeType || "ImportDeclaration" === nodeType || "DeclareClass" === nodeType || "DeclareFunction" === nodeType || "DeclareInterface" === nodeType || "DeclareModule" === nodeType || "DeclareModuleExports" === nodeType || "DeclareTypeAlias" === nodeType || "DeclareOpaqueType" === nodeType || "DeclareVariable" === nodeType || "DeclareExportDeclaration" === nodeType || "DeclareExportAllDeclaration" === nodeType || "InterfaceDeclaration" === nodeType || "OpaqueType" === nodeType || "TypeAlias" === nodeType || "TSDeclareFunction" === nodeType || "TSInterfaceDeclaration" === nodeType || "TSTypeAliasDeclaration" === nodeType || "TSEnumDeclaration" === nodeType || "TSModuleDeclaration" === nodeType || nodeType === "Placeholder" && "Declaration" === node.expectedNode) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isPatternLike(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "PatternLike" || "Identifier" === nodeType || "RestElement" === nodeType || "AssignmentPattern" === nodeType || "ArrayPattern" === nodeType || "ObjectPattern" === nodeType || nodeType === "Placeholder" && ("Pattern" === node.expectedNode || "Identifier" === node.expectedNode)) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isLVal(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "LVal" || "Identifier" === nodeType || "MemberExpression" === nodeType || "RestElement" === nodeType || "AssignmentPattern" === nodeType || "ArrayPattern" === nodeType || "ObjectPattern" === nodeType || "TSParameterProperty" === nodeType || nodeType === "Placeholder" && ("Pattern" === node.expectedNode || "Identifier" === node.expectedNode)) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSEntityName(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSEntityName" || "Identifier" === nodeType || "TSQualifiedName" === nodeType || nodeType === "Placeholder" && "Identifier" === node.expectedNode) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isLiteral(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Literal" || "StringLiteral" === nodeType || "NumericLiteral" === nodeType || "NullLiteral" === nodeType || "BooleanLiteral" === nodeType || "RegExpLiteral" === nodeType || "TemplateLiteral" === nodeType || "BigIntLiteral" === nodeType || nodeType === "Placeholder" && "StringLiteral" === node.expectedNode) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isImmutable(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Immutable" || "StringLiteral" === nodeType || "NumericLiteral" === nodeType || "NullLiteral" === nodeType || "BooleanLiteral" === nodeType || "JSXAttribute" === nodeType || "JSXClosingElement" === nodeType || "JSXElement" === nodeType || "JSXExpressionContainer" === nodeType || "JSXSpreadChild" === nodeType || "JSXOpeningElement" === nodeType || "JSXText" === nodeType || "JSXFragment" === nodeType || "JSXOpeningFragment" === nodeType || "JSXClosingFragment" === nodeType || "BigIntLiteral" === nodeType || nodeType === "Placeholder" && "StringLiteral" === node.expectedNode) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isUserWhitespacable(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "UserWhitespacable" || "ObjectMethod" === nodeType || "ObjectProperty" === nodeType || "ObjectTypeInternalSlot" === nodeType || "ObjectTypeCallProperty" === nodeType || "ObjectTypeIndexer" === nodeType || "ObjectTypeProperty" === nodeType || "ObjectTypeSpreadProperty" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isMethod(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Method" || "ObjectMethod" === nodeType || "ClassMethod" === nodeType || "ClassPrivateMethod" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isObjectMember(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ObjectMember" || "ObjectMethod" === nodeType || "ObjectProperty" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isProperty(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Property" || "ObjectProperty" === nodeType || "ClassProperty" === nodeType || "ClassPrivateProperty" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isUnaryLike(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "UnaryLike" || "UnaryExpression" === nodeType || "SpreadElement" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isPattern(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Pattern" || "AssignmentPattern" === nodeType || "ArrayPattern" === nodeType || "ObjectPattern" === nodeType || nodeType === "Placeholder" && "Pattern" === node.expectedNode) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isClass(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Class" || "ClassDeclaration" === nodeType || "ClassExpression" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isModuleDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ModuleDeclaration" || "ExportAllDeclaration" === nodeType || "ExportDefaultDeclaration" === nodeType || "ExportNamedDeclaration" === nodeType || "ImportDeclaration" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isExportDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ExportDeclaration" || "ExportAllDeclaration" === nodeType || "ExportDefaultDeclaration" === nodeType || "ExportNamedDeclaration" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isModuleSpecifier(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ModuleSpecifier" || "ExportSpecifier" === nodeType || "ImportDefaultSpecifier" === nodeType || "ImportNamespaceSpecifier" === nodeType || "ImportSpecifier" === nodeType || "ExportDefaultSpecifier" === nodeType || "ExportNamespaceSpecifier" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isFlow(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Flow" || "AnyTypeAnnotation" === nodeType || "ArrayTypeAnnotation" === nodeType || "BooleanTypeAnnotation" === nodeType || "BooleanLiteralTypeAnnotation" === nodeType || "NullLiteralTypeAnnotation" === nodeType || "ClassImplements" === nodeType || "DeclareClass" === nodeType || "DeclareFunction" === nodeType || "DeclareInterface" === nodeType || "DeclareModule" === nodeType || "DeclareModuleExports" === nodeType || "DeclareTypeAlias" === nodeType || "DeclareOpaqueType" === nodeType || "DeclareVariable" === nodeType || "DeclareExportDeclaration" === nodeType || "DeclareExportAllDeclaration" === nodeType || "DeclaredPredicate" === nodeType || "ExistsTypeAnnotation" === nodeType || "FunctionTypeAnnotation" === nodeType || "FunctionTypeParam" === nodeType || "GenericTypeAnnotation" === nodeType || "InferredPredicate" === nodeType || "InterfaceExtends" === nodeType || "InterfaceDeclaration" === nodeType || "InterfaceTypeAnnotation" === nodeType || "IntersectionTypeAnnotation" === nodeType || "MixedTypeAnnotation" === nodeType || "EmptyTypeAnnotation" === nodeType || "NullableTypeAnnotation" === nodeType || "NumberLiteralTypeAnnotation" === nodeType || "NumberTypeAnnotation" === nodeType || "ObjectTypeAnnotation" === nodeType || "ObjectTypeInternalSlot" === nodeType || "ObjectTypeCallProperty" === nodeType || "ObjectTypeIndexer" === nodeType || "ObjectTypeProperty" === nodeType || "ObjectTypeSpreadProperty" === nodeType || "OpaqueType" === nodeType || "QualifiedTypeIdentifier" === nodeType || "StringLiteralTypeAnnotation" === nodeType || "StringTypeAnnotation" === nodeType || "ThisTypeAnnotation" === nodeType || "TupleTypeAnnotation" === nodeType || "TypeofTypeAnnotation" === nodeType || "TypeAlias" === nodeType || "TypeAnnotation" === nodeType || "TypeCastExpression" === nodeType || "TypeParameter" === nodeType || "TypeParameterDeclaration" === nodeType || "TypeParameterInstantiation" === nodeType || "UnionTypeAnnotation" === nodeType || "Variance" === nodeType || "VoidTypeAnnotation" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isFlowType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "FlowType" || "AnyTypeAnnotation" === nodeType || "ArrayTypeAnnotation" === nodeType || "BooleanTypeAnnotation" === nodeType || "BooleanLiteralTypeAnnotation" === nodeType || "NullLiteralTypeAnnotation" === nodeType || "ExistsTypeAnnotation" === nodeType || "FunctionTypeAnnotation" === nodeType || "GenericTypeAnnotation" === nodeType || "InterfaceTypeAnnotation" === nodeType || "IntersectionTypeAnnotation" === nodeType || "MixedTypeAnnotation" === nodeType || "EmptyTypeAnnotation" === nodeType || "NullableTypeAnnotation" === nodeType || "NumberLiteralTypeAnnotation" === nodeType || "NumberTypeAnnotation" === nodeType || "ObjectTypeAnnotation" === nodeType || "StringLiteralTypeAnnotation" === nodeType || "StringTypeAnnotation" === nodeType || "ThisTypeAnnotation" === nodeType || "TupleTypeAnnotation" === nodeType || "TypeofTypeAnnotation" === nodeType || "UnionTypeAnnotation" === nodeType || "VoidTypeAnnotation" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isFlowBaseAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "FlowBaseAnnotation" || "AnyTypeAnnotation" === nodeType || "BooleanTypeAnnotation" === nodeType || "NullLiteralTypeAnnotation" === nodeType || "MixedTypeAnnotation" === nodeType || "EmptyTypeAnnotation" === nodeType || "NumberTypeAnnotation" === nodeType || "StringTypeAnnotation" === nodeType || "ThisTypeAnnotation" === nodeType || "VoidTypeAnnotation" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isFlowDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "FlowDeclaration" || "DeclareClass" === nodeType || "DeclareFunction" === nodeType || "DeclareInterface" === nodeType || "DeclareModule" === nodeType || "DeclareModuleExports" === nodeType || "DeclareTypeAlias" === nodeType || "DeclareOpaqueType" === nodeType || "DeclareVariable" === nodeType || "DeclareExportDeclaration" === nodeType || "DeclareExportAllDeclaration" === nodeType || "InterfaceDeclaration" === nodeType || "OpaqueType" === nodeType || "TypeAlias" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isFlowPredicate(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "FlowPredicate" || "DeclaredPredicate" === nodeType || "InferredPredicate" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isJSX(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "JSX" || "JSXAttribute" === nodeType || "JSXClosingElement" === nodeType || "JSXElement" === nodeType || "JSXEmptyExpression" === nodeType || "JSXExpressionContainer" === nodeType || "JSXSpreadChild" === nodeType || "JSXIdentifier" === nodeType || "JSXMemberExpression" === nodeType || "JSXNamespacedName" === nodeType || "JSXOpeningElement" === nodeType || "JSXSpreadAttribute" === nodeType || "JSXText" === nodeType || "JSXFragment" === nodeType || "JSXOpeningFragment" === nodeType || "JSXClosingFragment" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isPrivate(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "Private" || "ClassPrivateProperty" === nodeType || "ClassPrivateMethod" === nodeType || "PrivateName" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSTypeElement(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSTypeElement" || "TSCallSignatureDeclaration" === nodeType || "TSConstructSignatureDeclaration" === nodeType || "TSPropertySignature" === nodeType || "TSMethodSignature" === nodeType || "TSIndexSignature" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSType" || "TSAnyKeyword" === nodeType || "TSUnknownKeyword" === nodeType || "TSNumberKeyword" === nodeType || "TSObjectKeyword" === nodeType || "TSBooleanKeyword" === nodeType || "TSStringKeyword" === nodeType || "TSSymbolKeyword" === nodeType || "TSVoidKeyword" === nodeType || "TSUndefinedKeyword" === nodeType || "TSNullKeyword" === nodeType || "TSNeverKeyword" === nodeType || "TSThisType" === nodeType || "TSFunctionType" === nodeType || "TSConstructorType" === nodeType || "TSTypeReference" === nodeType || "TSTypePredicate" === nodeType || "TSTypeQuery" === nodeType || "TSTypeLiteral" === nodeType || "TSArrayType" === nodeType || "TSTupleType" === nodeType || "TSOptionalType" === nodeType || "TSRestType" === nodeType || "TSUnionType" === nodeType || "TSIntersectionType" === nodeType || "TSConditionalType" === nodeType || "TSInferType" === nodeType || "TSParenthesizedType" === nodeType || "TSTypeOperator" === nodeType || "TSIndexedAccessType" === nodeType || "TSMappedType" === nodeType || "TSLiteralType" === nodeType || "TSExpressionWithTypeArguments" === nodeType || "TSImportType" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isNumberLiteral(node, opts) { console.trace("The node type NumberLiteral has been renamed to NumericLiteral"); if (!node) return false; const nodeType = node.type; if (nodeType === "NumberLiteral") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isRegexLiteral(node, opts) { console.trace("The node type RegexLiteral has been renamed to RegExpLiteral"); if (!node) return false; const nodeType = node.type; if (nodeType === "RegexLiteral") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isRestProperty(node, opts) { console.trace("The node type RestProperty has been renamed to RestElement"); if (!node) return false; const nodeType = node.type; if (nodeType === "RestProperty") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isSpreadProperty(node, opts) { console.trace("The node type SpreadProperty has been renamed to SpreadElement"); if (!node) return false; const nodeType = node.type; if (nodeType === "SpreadProperty") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } },{"../../utils/shallowEqual":155}],158:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = is; var _shallowEqual = _interopRequireDefault(require("../utils/shallowEqual")); var _isType = _interopRequireDefault(require("./isType")); var _isPlaceholderType = _interopRequireDefault(require("./isPlaceholderType")); var _definitions = require("../definitions"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function is(type, node, opts) { if (!node) return false; const matches = (0, _isType.default)(node.type, type); if (!matches) { if (!opts && node.type === "Placeholder" && type in _definitions.FLIPPED_ALIAS_KEYS) { return (0, _isPlaceholderType.default)(node.expectedNode, type); } return false; } if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } },{"../definitions":136,"../utils/shallowEqual":155,"./isPlaceholderType":165,"./isType":169}],159:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isBinding; var _getBindingIdentifiers = _interopRequireDefault(require("../retrievers/getBindingIdentifiers")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function isBinding(node, parent, grandparent) { if (grandparent && node.type === "Identifier" && parent.type === "ObjectProperty" && grandparent.type === "ObjectExpression") { return false; } const keys = _getBindingIdentifiers.default.keys[parent.type]; if (keys) { for (let i = 0; i < keys.length; i++) { const key = keys[i]; const val = parent[key]; if (Array.isArray(val)) { if (val.indexOf(node) >= 0) return true; } else { if (val === node) return true; } } } return false; } },{"../retrievers/getBindingIdentifiers":149}],160:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isBlockScoped; var _generated = require("./generated"); var _isLet = _interopRequireDefault(require("./isLet")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function isBlockScoped(node) { return (0, _generated.isFunctionDeclaration)(node) || (0, _generated.isClassDeclaration)(node) || (0, _isLet.default)(node); } },{"./generated":157,"./isLet":162}],161:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isImmutable; var _isType = _interopRequireDefault(require("./isType")); var _generated = require("./generated"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function isImmutable(node) { if ((0, _isType.default)(node.type, "Immutable")) return true; if ((0, _generated.isIdentifier)(node)) { if (node.name === "undefined") { return true; } else { return false; } } return false; } },{"./generated":157,"./isType":169}],162:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isLet; var _generated = require("./generated"); var _constants = require("../constants"); function isLet(node) { return (0, _generated.isVariableDeclaration)(node) && (node.kind !== "var" || node[_constants.BLOCK_SCOPED_SYMBOL]); } },{"../constants":120,"./generated":157}],163:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isNode; var _definitions = require("../definitions"); function isNode(node) { return !!(node && _definitions.VISITOR_KEYS[node.type]); } },{"../definitions":136}],164:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isNodesEquivalent; var _definitions = require("../definitions"); function isNodesEquivalent(a, b) { if (typeof a !== "object" || typeof b !== "object" || a == null || b == null) { return a === b; } if (a.type !== b.type) { return false; } const fields = Object.keys(_definitions.NODE_FIELDS[a.type] || a.type); const visitorKeys = _definitions.VISITOR_KEYS[a.type]; for (const field of fields) { if (typeof a[field] !== typeof b[field]) { return false; } if (a[field] == null && b[field] == null) { continue; } else if (a[field] == null || b[field] == null) { return false; } if (Array.isArray(a[field])) { if (!Array.isArray(b[field])) { return false; } if (a[field].length !== b[field].length) { return false; } for (let i = 0; i < a[field].length; i++) { if (!isNodesEquivalent(a[field][i], b[field][i])) { return false; } } continue; } if (typeof a[field] === "object" && (!visitorKeys || !visitorKeys.includes(field))) { for (const key of Object.keys(a[field])) { if (a[field][key] !== b[field][key]) { return false; } } continue; } if (!isNodesEquivalent(a[field], b[field])) { return false; } } return true; } },{"../definitions":136}],165:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isPlaceholderType; var _definitions = require("../definitions"); function isPlaceholderType(placeholderType, targetType) { if (placeholderType === targetType) return true; const aliases = _definitions.PLACEHOLDERS_ALIAS[placeholderType]; if (aliases) { for (const alias of aliases) { if (targetType === alias) return true; } } return false; } },{"../definitions":136}],166:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isReferenced; function isReferenced(node, parent, grandparent) { switch (parent.type) { case "MemberExpression": case "JSXMemberExpression": case "OptionalMemberExpression": if (parent.property === node) { return !!parent.computed; } return parent.object === node; case "VariableDeclarator": return parent.init === node; case "ArrowFunctionExpression": return parent.body === node; case "ExportSpecifier": if (parent.source) { return false; } return parent.local === node; case "PrivateName": return false; case "ObjectProperty": case "ClassProperty": case "ClassPrivateProperty": case "ClassMethod": case "ClassPrivateMethod": case "ObjectMethod": if (parent.key === node) { return !!parent.computed; } if (parent.value === node) { return !grandparent || grandparent.type !== "ObjectPattern"; } return true; case "ClassDeclaration": case "ClassExpression": return parent.superClass === node; case "AssignmentExpression": return parent.right === node; case "AssignmentPattern": return parent.right === node; case "LabeledStatement": return false; case "CatchClause": return false; case "RestElement": return false; case "BreakStatement": case "ContinueStatement": return false; case "FunctionDeclaration": case "FunctionExpression": return false; case "ExportNamespaceSpecifier": case "ExportDefaultSpecifier": return false; case "ImportDefaultSpecifier": case "ImportNamespaceSpecifier": case "ImportSpecifier": return false; case "JSXAttribute": return false; case "ObjectPattern": case "ArrayPattern": return false; case "MetaProperty": return false; case "ObjectTypeProperty": return parent.key !== node; case "TSEnumMember": return parent.id !== node; case "TSPropertySignature": if (parent.key === node) { return !!parent.computed; } return true; } return true; } },{}],167:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isScope; var _generated = require("./generated"); function isScope(node, parent) { if ((0, _generated.isBlockStatement)(node) && (0, _generated.isFunction)(parent, { body: node })) { return false; } if ((0, _generated.isBlockStatement)(node) && (0, _generated.isCatchClause)(parent, { body: node })) { return false; } return (0, _generated.isScopable)(node); } },{"./generated":157}],168:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isSpecifierDefault; var _generated = require("./generated"); function isSpecifierDefault(specifier) { return (0, _generated.isImportDefaultSpecifier)(specifier) || (0, _generated.isIdentifier)(specifier.imported || specifier.exported, { name: "default" }); } },{"./generated":157}],169:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isType; var _definitions = require("../definitions"); function isType(nodeType, targetType) { if (nodeType === targetType) return true; if (_definitions.ALIAS_KEYS[targetType]) return false; const aliases = _definitions.FLIPPED_ALIAS_KEYS[targetType]; if (aliases) { if (aliases[0] === nodeType) return true; for (const alias of aliases) { if (nodeType === alias) return true; } } return false; } },{"../definitions":136}],170:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isValidES3Identifier; var _isValidIdentifier = _interopRequireDefault(require("./isValidIdentifier")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const RESERVED_WORDS_ES3_ONLY = new Set(["abstract", "boolean", "byte", "char", "double", "enum", "final", "float", "goto", "implements", "int", "interface", "long", "native", "package", "private", "protected", "public", "short", "static", "synchronized", "throws", "transient", "volatile"]); function isValidES3Identifier(name) { return (0, _isValidIdentifier.default)(name) && !RESERVED_WORDS_ES3_ONLY.has(name); } },{"./isValidIdentifier":171}],171:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isValidIdentifier; function _esutils() { const data = _interopRequireDefault(require("esutils")); _esutils = function () { return data; }; return data; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function isValidIdentifier(name) { if (typeof name !== "string" || _esutils().default.keyword.isReservedWordES6(name, true)) { return false; } else if (name === "await") { return false; } else { return _esutils().default.keyword.isIdentifierNameES6(name); } } },{"esutils":198}],172:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isVar; var _generated = require("./generated"); var _constants = require("../constants"); function isVar(node) { return (0, _generated.isVariableDeclaration)(node, { kind: "var" }) && !node[_constants.BLOCK_SCOPED_SYMBOL]; } },{"../constants":120,"./generated":157}],173:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = matchesPattern; var _generated = require("./generated"); function matchesPattern(member, match, allowPartial) { if (!(0, _generated.isMemberExpression)(member)) return false; const parts = Array.isArray(match) ? match : match.split("."); const nodes = []; let node; for (node = member; (0, _generated.isMemberExpression)(node); node = node.object) { nodes.push(node.property); } nodes.push(node); if (nodes.length < parts.length) return false; if (!allowPartial && nodes.length > parts.length) return false; for (let i = 0, j = nodes.length - 1; i < parts.length; i++, j--) { const node = nodes[j]; let value; if ((0, _generated.isIdentifier)(node)) { value = node.name; } else if ((0, _generated.isStringLiteral)(node)) { value = node.value; } else { return false; } if (parts[i] !== value) return false; } return true; } },{"./generated":157}],174:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isCompatTag; function isCompatTag(tagName) { return !!tagName && /^[a-z]/.test(tagName); } },{}],175:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _buildMatchMemberExpression = _interopRequireDefault(require("../buildMatchMemberExpression")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const isReactComponent = (0, _buildMatchMemberExpression.default)("React.Component"); var _default = isReactComponent; exports.default = _default; },{"../buildMatchMemberExpression":156}],176:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = validate; var _definitions = require("../definitions"); function validate(node, key, val) { if (!node) return; const fields = _definitions.NODE_FIELDS[node.type]; if (!fields) return; const field = fields[key]; if (!field || !field.validate) return; if (field.optional && val == null) return; field.validate(node, key, val); } },{"../definitions":136}],177:[function(require,module,exports){ 'use strict'; const colorConvert = require('color-convert'); const wrapAnsi16 = (fn, offset) => function () { const code = fn.apply(colorConvert, arguments); return `\u001B[${code + offset}m`; }; const wrapAnsi256 = (fn, offset) => function () { const code = fn.apply(colorConvert, arguments); return `\u001B[${38 + offset};5;${code}m`; }; const wrapAnsi16m = (fn, offset) => function () { const rgb = fn.apply(colorConvert, arguments); return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; }; function assembleStyles() { const codes = new Map(); const styles = { modifier: { reset: [0, 0], // 21 isn't widely supported and 22 does the same thing bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29] }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], // Bright color redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39] }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], // Bright color bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49] } }; // Fix humans styles.color.grey = styles.color.gray; for (const groupName of Object.keys(styles)) { const group = styles[groupName]; for (const styleName of Object.keys(group)) { const style = group[styleName]; styles[styleName] = { open: `\u001B[${style[0]}m`, close: `\u001B[${style[1]}m` }; group[styleName] = styles[styleName]; codes.set(style[0], style[1]); } Object.defineProperty(styles, groupName, { value: group, enumerable: false }); Object.defineProperty(styles, 'codes', { value: codes, enumerable: false }); } const ansi2ansi = n => n; const rgb2rgb = (r, g, b) => [r, g, b]; styles.color.close = '\u001B[39m'; styles.bgColor.close = '\u001B[49m'; styles.color.ansi = { ansi: wrapAnsi16(ansi2ansi, 0) }; styles.color.ansi256 = { ansi256: wrapAnsi256(ansi2ansi, 0) }; styles.color.ansi16m = { rgb: wrapAnsi16m(rgb2rgb, 0) }; styles.bgColor.ansi = { ansi: wrapAnsi16(ansi2ansi, 10) }; styles.bgColor.ansi256 = { ansi256: wrapAnsi256(ansi2ansi, 10) }; styles.bgColor.ansi16m = { rgb: wrapAnsi16m(rgb2rgb, 10) }; for (let key of Object.keys(colorConvert)) { if (typeof colorConvert[key] !== 'object') { continue; } const suite = colorConvert[key]; if (key === 'ansi16') { key = 'ansi'; } if ('ansi16' in suite) { styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); } if ('ansi256' in suite) { styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); } if ('rgb' in suite) { styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); } } return styles; } // Make the export immutable Object.defineProperty(module, 'exports', { enumerable: true, get: assembleStyles }); },{"color-convert":186}],178:[function(require,module,exports){ (function (Buffer){ "use strict"; var stream = require("stream"); var util = require("util"); var path = require("path"); let babel; try { babel = require("@babel/core"); } catch (err) { if (err.code === "MODULE_NOT_FOUND") { err.message += "\n babelify@10 requires Babel 7.x (the package '@babel/core'). " + "If you'd like to use Babel 6.x ('babel-core'), you should install 'babelify@8'."; } throw err; } // Since we've got the reverse bridge package at @babel/core@6.x, give // people useful feedback if they try to use it alongside babel-loader. if (/^6\./.test(babel.version)) { throw new Error( "\n babelify@10 will not work with the '@babel/core@6' bridge package. " + "If you want to use Babel 6.x, install 'babelify@8'." ); } module.exports = buildTransform(); module.exports.configure = buildTransform; // Allow projects to import this module and check `foo instanceof babelify` // to see if the current stream they are working with is one created // by Babelify. Object.defineProperty(module.exports, Symbol.hasInstance, { value: function hasInstance(obj) { return obj instanceof BabelifyStream; }, }); function buildTransform(opts) { return function (filename, transformOpts) { const babelOpts = normalizeOptions(opts, transformOpts, filename); if (babelOpts === null) { return stream.PassThrough(); } return new BabelifyStream(babelOpts); }; } function normalizeOptions(preconfiguredOpts, transformOpts, filename) { const basedir = normalizeTransformBasedir(transformOpts); const opts = normalizeTransformOpts(transformOpts); // Transform options override preconfigured options unless they are undefined. if (preconfiguredOpts) { for (const key of Object.keys(preconfiguredOpts)) { if (opts[key] === undefined) { opts[key] = preconfiguredOpts[key]; } } } // babelify specific options var extensions = opts.extensions || babel.DEFAULT_EXTENSIONS; var sourceMapsAbsolute = opts.sourceMapsAbsolute; delete opts.sourceMapsAbsolute; delete opts.extensions; var extname = path.extname(filename); if (extensions.indexOf(extname) === -1) { return null; } // Browserify doesn't actually always normalize the filename passed // to transforms, so we manually ensure that the filename is relative const absoluteFilename = path.resolve(basedir, filename); Object.assign(opts, { cwd: opts.cwd === undefined ? basedir : opts.cwd, caller: Object.assign( { name: "babelify", }, opts.caller ), filename: absoluteFilename, sourceFileName: sourceMapsAbsolute ? absoluteFilename : undefined, }); return opts; } function normalizeTransformBasedir(opts) { return path.resolve(opts._flags && opts._flags.basedir || "."); } function normalizeTransformOpts(opts) { opts = Object.assign({}, opts); // browserify cli options delete opts._; // "--opt [ a b ]" and "--opt a --opt b" are allowed: if (opts.ignore && opts.ignore._) opts.ignore = opts.ignore._; if (opts.only && opts.only._) opts.only = opts.only._; if (opts.plugins && opts.plugins._) opts.plugins = opts.plugins._; if (opts.presets && opts.presets._) opts.presets = opts.presets._; // browserify specific options delete opts._flags; delete opts.basedir; delete opts.global; return opts; } class BabelifyStream extends stream.Transform { constructor(opts) { super(); this._data = []; this._opts = opts; } _transform(buf, enc, callback) { this._data.push(buf); callback(); } _flush(callback) { // Merge the buffer pieces after all are available, instead of one at a time, // to avoid corrupting multibyte characters. const data = Buffer.concat(this._data).toString(); transform(data, this._opts, (err, result) => { if (err) { callback(err); } else { this.emit("babelify", result, this._opts.filename); var code = result !== null ? result.code : data; // Note: Node 8.x allows passing 'code' to the callback instead of // manually pushing, but we need to support Node 6.x. this.push(code); callback(); } }); } } function transform(data, inputOpts, done) { let cfg; try { cfg = babel.loadPartialConfig(inputOpts); if (!cfg) return done(null, null); } catch (err) { return done(err); } const opts = cfg.options; // Since Browserify can only handle inline sourcemaps, we override any other // values to force inline sourcemaps unless they've been disabled. if (opts.sourceMaps !== false) { opts.sourceMaps = "inline"; } babel.transform(data, opts, done); } }).call(this,require("buffer").Buffer) },{"@babel/core":26,"buffer":182,"path":403,"stream":451,"util":461}],179:[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 for (var 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('') } },{}],180:[function(require,module,exports){ },{}],181:[function(require,module,exports){ arguments[4][180][0].apply(exports,arguments) },{"dup":180}],182:[function(require,module,exports){ (function (Buffer){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ /* eslint-disable no-proto */ 'use strict' var base64 = require('base64-js') var ieee754 = require('ieee754') exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 var K_MAX_LENGTH = 0x7fffffff exports.kMaxLength = K_MAX_LENGTH /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Print warning and recommend using `buffer` v4.x which has an 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+. * * We report that the browser does not support typed arrays if the are not subclassable * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support * for __proto__ and has a buggy typed array implementation. */ Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && typeof console.error === 'function') { console.error( 'This browser lacks typed array (Uint8Array) support which is required by ' + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' ) } function typedArraySupport () { // Can typed array instances can be augmented? try { var arr = new Uint8Array(1) arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } return arr.foo() === 42 } catch (e) { return false } } Object.defineProperty(Buffer.prototype, 'parent', { enumerable: true, get: function () { if (!Buffer.isBuffer(this)) return undefined return this.buffer } }) Object.defineProperty(Buffer.prototype, 'offset', { enumerable: true, get: function () { if (!Buffer.isBuffer(this)) return undefined return this.byteOffset } }) function createBuffer (length) { if (length > K_MAX_LENGTH) { throw new RangeError('The value "' + length + '" is invalid for option "size"') } // Return an augmented `Uint8Array` instance var buf = new Uint8Array(length) buf.__proto__ = Buffer.prototype return buf } /** * 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) { // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new TypeError( 'The "string" argument must be of type string. Received type number' ) } return allocUnsafe(arg) } return from(arg, encodingOrOffset, length) } // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 if (typeof Symbol !== 'undefined' && Symbol.species != null && Buffer[Symbol.species] === Buffer) { Object.defineProperty(Buffer, Symbol.species, { value: null, configurable: true, enumerable: false, writable: false }) } Buffer.poolSize = 8192 // not used by this implementation function from (value, encodingOrOffset, length) { if (typeof value === 'string') { return fromString(value, encodingOrOffset) } if (ArrayBuffer.isView(value)) { return fromArrayLike(value) } if (value == null) { throw TypeError( 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + (typeof value) ) } if (isInstance(value, ArrayBuffer) || (value && isInstance(value.buffer, ArrayBuffer))) { return fromArrayBuffer(value, encodingOrOffset, length) } if (typeof value === 'number') { throw new TypeError( 'The "value" argument must not be of type number. Received type number' ) } var valueOf = value.valueOf && value.valueOf() if (valueOf != null && valueOf !== value) { return Buffer.from(valueOf, encodingOrOffset, length) } var b = fromObject(value) if (b) return b if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === 'function') { return Buffer.from( value[Symbol.toPrimitive]('string'), encodingOrOffset, length ) } throw new TypeError( 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + (typeof 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(value, encodingOrOffset, length) } // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: // https://github.com/feross/buffer/pull/148 Buffer.prototype.__proto__ = Uint8Array.prototype Buffer.__proto__ = Uint8Array function assertSize (size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be of type number') } else if (size < 0) { throw new RangeError('The value "' + size + '" is invalid for option "size"') } } function alloc (size, fill, encoding) { assertSize(size) if (size <= 0) { return createBuffer(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(size).fill(fill, encoding) : createBuffer(size).fill(fill) } return createBuffer(size) } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function (size, fill, encoding) { return alloc(size, fill, encoding) } function allocUnsafe (size) { assertSize(size) return createBuffer(size < 0 ? 0 : checked(size) | 0) } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function (size) { return allocUnsafe(size) } /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function (size) { return allocUnsafe(size) } function fromString (string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8' } if (!Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } var length = byteLength(string, encoding) | 0 var buf = createBuffer(length) var actual = buf.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') buf = buf.slice(0, actual) } return buf } function fromArrayLike (array) { var length = array.length < 0 ? 0 : checked(array.length) | 0 var buf = createBuffer(length) for (var i = 0; i < length; i += 1) { buf[i] = array[i] & 255 } return buf } function fromArrayBuffer (array, byteOffset, length) { if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('"offset" is outside of buffer bounds') } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('"length" is outside of buffer bounds') } var buf if (byteOffset === undefined && length === undefined) { buf = new Uint8Array(array) } else if (length === undefined) { buf = new Uint8Array(array, byteOffset) } else { buf = new Uint8Array(array, byteOffset, length) } // Return an augmented `Uint8Array` instance buf.__proto__ = Buffer.prototype return buf } function fromObject (obj) { if (Buffer.isBuffer(obj)) { var len = checked(obj.length) | 0 var buf = createBuffer(len) if (buf.length === 0) { return buf } obj.copy(buf, 0, 0, len) return buf } if (obj.length !== undefined) { if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { return createBuffer(0) } return fromArrayLike(obj) } if (obj.type === 'Buffer' && Array.isArray(obj.data)) { return fromArrayLike(obj.data) } } function checked (length) { // Note: cannot use `length < K_MAX_LENGTH` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= K_MAX_LENGTH) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + K_MAX_LENGTH.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 === true && b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false } Buffer.compare = function compare (a, b) { if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError( 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' ) } 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 (!Array.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 (isInstance(buf, Uint8Array)) { buf = Buffer.from(buf) } 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 (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { return string.byteLength } if (typeof string !== 'string') { throw new TypeError( 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + 'Received type ' + typeof string ) } var len = string.length var mustMatch = (arguments.length > 2 && arguments[2] === true) if (!mustMatch && 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': 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 mustMatch ? -1 : 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 } } } // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) // to detect a Buffer instance. It's not possible to use `instanceof Buffer` // reliably in a browserify context because there could be multiple different // copies of the 'buffer' package in use. This method works even for Buffer // instances that were created from another copy of the `buffer` package. // See: https://github.com/feross/buffer/issues/154 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 if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) } Buffer.prototype.toLocaleString = Buffer.prototype.toString 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 str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() if (this.length > max) str += ' ... ' return '' } Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (isInstance(target, Uint8Array)) { target = Buffer.from(target, target.offset, target.byteLength) } if (!Buffer.isBuffer(target)) { throw new TypeError( 'The "target" argument must be one of type Buffer or Uint8Array. ' + 'Received type ' + (typeof target) ) } 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 (numberIsNaN(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 (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 } } var strLen = string.length if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16) if (numberIsNaN(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 } } 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 = this.subarray(start, end) // Return an augmented `Uint8Array` instance newBuf.__proto__ = Buffer.prototype 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) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { offset = offset >>> 0 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) { offset = offset >>> 0 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) { offset = offset >>> 0 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) { offset = offset >>> 0 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) { offset = offset >>> 0 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) { offset = offset >>> 0 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) { offset = offset >>> 0 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) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { offset = offset >>> 0 if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { offset = offset >>> 0 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) this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) 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) this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) return offset + 2 } Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) this[offset + 3] = (value >>> 24) this[offset + 2] = (value >>> 16) this[offset + 1] = (value >>> 8) this[offset] = (value & 0xff) 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) this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) 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 (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) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) 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) this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) 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) this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) this[offset + 2] = (value >>> 16) this[offset + 3] = (value >>> 24) 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 this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) 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) { value = +value offset = offset >>> 0 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) { value = +value offset = offset >>> 0 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 (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') 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('Index out of range') 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 if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { // Use built-in when available, missing from IE11 this.copyWithin(targetStart, start, end) } else if (this === target && start < targetStart && targetStart < end) { // descending copy from end for (var i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start] } } else { Uint8Array.prototype.set.call( target, this.subarray(start, end), 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 (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) } if (val.length === 1) { var code = val.charCodeAt(0) if ((encoding === 'utf8' && code < 128) || encoding === 'latin1') { // Fast path: If `val` fits into a single byte, use that numeric value. val = code } } } 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 : Buffer.from(val, encoding) var len = bytes.length if (len === 0) { throw new TypeError('The value "' + val + '" is invalid for argument "value"') } 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 takes equal signs as end of the Base64 encoding str = str.split('=')[0] // Node strips out invalid characters like \n and \t from the string, base64-js does not str = str.trim().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 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 } // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass // the `instanceof` check but they should be treated as of that type. // See: https://github.com/feross/buffer/issues/166 function isInstance (obj, type) { return obj instanceof type || (obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name) } function numberIsNaN (obj) { // For IE11 support return obj !== obj // eslint-disable-line no-self-compare } }).call(this,require("buffer").Buffer) },{"base64-js":179,"buffer":182,"ieee754":202}],183:[function(require,module,exports){ (function (process){ 'use strict'; const escapeStringRegexp = require('escape-string-regexp'); const ansiStyles = require('ansi-styles'); const stdoutColor = require('supports-color').stdout; const template = require('./templates.js'); const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such const skipModels = new Set(['gray']); const styles = Object.create(null); function applyOptions(obj, options) { options = options || {}; // Detect level if not set manually const scLevel = stdoutColor ? stdoutColor.level : 0; obj.level = options.level === undefined ? scLevel : options.level; obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; } function Chalk(options) { // We check for this.template here since calling `chalk.constructor()` // by itself will have a `this` of a previously constructed chalk object if (!this || !(this instanceof Chalk) || this.template) { const chalk = {}; applyOptions(chalk, options); chalk.template = function () { const args = [].slice.call(arguments); return chalkTag.apply(null, [chalk.template].concat(args)); }; Object.setPrototypeOf(chalk, Chalk.prototype); Object.setPrototypeOf(chalk.template, chalk); chalk.template.constructor = Chalk; return chalk.template; } applyOptions(this, options); } // Use bright blue on Windows as the normal blue color is illegible if (isSimpleWindowsTerm) { ansiStyles.blue.open = '\u001B[94m'; } for (const key of Object.keys(ansiStyles)) { ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); styles[key] = { get() { const codes = ansiStyles[key]; return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); } }; } styles.visible = { get() { return build.call(this, this._styles || [], true, 'visible'); } }; ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); for (const model of Object.keys(ansiStyles.color.ansi)) { if (skipModels.has(model)) { continue; } styles[model] = { get() { const level = this.level; return function () { const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); const codes = { open, close: ansiStyles.color.close, closeRe: ansiStyles.color.closeRe }; return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); }; } }; } ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); for (const model of Object.keys(ansiStyles.bgColor.ansi)) { if (skipModels.has(model)) { continue; } const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); styles[bgModel] = { get() { const level = this.level; return function () { const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); const codes = { open, close: ansiStyles.bgColor.close, closeRe: ansiStyles.bgColor.closeRe }; return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); }; } }; } const proto = Object.defineProperties(() => {}, styles); function build(_styles, _empty, key) { const builder = function () { return applyStyle.apply(builder, arguments); }; builder._styles = _styles; builder._empty = _empty; const self = this; Object.defineProperty(builder, 'level', { enumerable: true, get() { return self.level; }, set(level) { self.level = level; } }); Object.defineProperty(builder, 'enabled', { enumerable: true, get() { return self.enabled; }, set(enabled) { self.enabled = enabled; } }); // See below for fix regarding invisible grey/dim combination on Windows builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is // no way to create a function with a different prototype builder.__proto__ = proto; // eslint-disable-line no-proto return builder; } function applyStyle() { // Support varags, but simply cast to string in case there's only one arg const args = arguments; const argsLen = args.length; let str = String(arguments[0]); if (argsLen === 0) { return ''; } if (argsLen > 1) { // Don't slice `arguments`, it prevents V8 optimizations for (let a = 1; a < argsLen; a++) { str += ' ' + args[a]; } } if (!this.enabled || this.level <= 0 || !str) { return this._empty ? '' : str; } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, // see https://github.com/chalk/chalk/issues/58 // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. const originalDim = ansiStyles.dim.open; if (isSimpleWindowsTerm && this.hasGrey) { ansiStyles.dim.open = ''; } for (const code of this._styles.slice().reverse()) { // Replace any instances already present with a re-opening code // otherwise only the part of the string until said closing code // will be colored, and the rest will simply be 'plain'. str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen // after next line to fix a bleed issue on macOS // https://github.com/chalk/chalk/pull/92 str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue ansiStyles.dim.open = originalDim; return str; } function chalkTag(chalk, strings) { if (!Array.isArray(strings)) { // If chalk() was called by itself or with a string, // return the string itself as a string. return [].slice.call(arguments, 1).join(' '); } const args = [].slice.call(arguments, 2); const parts = [strings.raw[0]]; for (let i = 1; i < strings.length; i++) { parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); parts.push(String(strings.raw[i])); } return template(chalk, parts.join('')); } Object.defineProperties(Chalk.prototype, styles); module.exports = Chalk(); // eslint-disable-line new-cap module.exports.supportsColor = stdoutColor; module.exports.default = module.exports; // For TypeScript }).call(this,require('_process')) },{"./templates.js":184,"_process":405,"ansi-styles":177,"escape-string-regexp":194,"supports-color":454}],184:[function(require,module,exports){ 'use strict'; const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; const ESCAPES = new Map([ ['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007'] ]); function unescape(c) { if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) { return String.fromCharCode(parseInt(c.slice(1), 16)); } return ESCAPES.get(c) || c; } function parseArguments(name, args) { const results = []; const chunks = args.trim().split(/\s*,\s*/g); let matches; for (const chunk of chunks) { if (!isNaN(chunk)) { results.push(Number(chunk)); } else if ((matches = chunk.match(STRING_REGEX))) { results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr)); } else { throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); } } return results; } function parseStyle(style) { STYLE_REGEX.lastIndex = 0; const results = []; let matches; while ((matches = STYLE_REGEX.exec(style)) !== null) { const name = matches[1]; if (matches[2]) { const args = parseArguments(name, matches[2]); results.push([name].concat(args)); } else { results.push([name]); } } return results; } function buildStyle(chalk, styles) { const enabled = {}; for (const layer of styles) { for (const style of layer.styles) { enabled[style[0]] = layer.inverse ? null : style.slice(1); } } let current = chalk; for (const styleName of Object.keys(enabled)) { if (Array.isArray(enabled[styleName])) { if (!(styleName in current)) { throw new Error(`Unknown Chalk style: ${styleName}`); } if (enabled[styleName].length > 0) { current = current[styleName].apply(current, enabled[styleName]); } else { current = current[styleName]; } } } return current; } module.exports = (chalk, tmp) => { const styles = []; const chunks = []; let chunk = []; // eslint-disable-next-line max-params tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => { if (escapeChar) { chunk.push(unescape(escapeChar)); } else if (style) { const str = chunk.join(''); chunk = []; chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); styles.push({inverse, styles: parseStyle(style)}); } else if (close) { if (styles.length === 0) { throw new Error('Found extraneous } in Chalk template literal'); } chunks.push(buildStyle(chalk, styles)(chunk.join(''))); chunk = []; styles.pop(); } else { chunk.push(chr); } }); chunks.push(chunk.join('')); if (styles.length > 0) { const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; throw new Error(errMsg); } return chunks.join(''); }; },{}],185:[function(require,module,exports){ /* MIT license */ var cssKeywords = require('color-name'); // NOTE: conversions should only return primitive values (i.e. arrays, or // values that give correct `typeof` results). // do not use box values types (i.e. Number(), String(), etc.) var reverseKeywords = {}; for (var key in cssKeywords) { if (cssKeywords.hasOwnProperty(key)) { reverseKeywords[cssKeywords[key]] = key; } } var convert = module.exports = { rgb: {channels: 3, labels: 'rgb'}, hsl: {channels: 3, labels: 'hsl'}, hsv: {channels: 3, labels: 'hsv'}, hwb: {channels: 3, labels: 'hwb'}, cmyk: {channels: 4, labels: 'cmyk'}, xyz: {channels: 3, labels: 'xyz'}, lab: {channels: 3, labels: 'lab'}, lch: {channels: 3, labels: 'lch'}, hex: {channels: 1, labels: ['hex']}, keyword: {channels: 1, labels: ['keyword']}, ansi16: {channels: 1, labels: ['ansi16']}, ansi256: {channels: 1, labels: ['ansi256']}, hcg: {channels: 3, labels: ['h', 'c', 'g']}, apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, gray: {channels: 1, labels: ['gray']} }; // hide .channels and .labels properties for (var model in convert) { if (convert.hasOwnProperty(model)) { if (!('channels' in convert[model])) { throw new Error('missing channels property: ' + model); } if (!('labels' in convert[model])) { throw new Error('missing channel labels property: ' + model); } if (convert[model].labels.length !== convert[model].channels) { throw new Error('channel and label counts mismatch: ' + model); } var channels = convert[model].channels; var labels = convert[model].labels; delete convert[model].channels; delete convert[model].labels; Object.defineProperty(convert[model], 'channels', {value: channels}); Object.defineProperty(convert[model], 'labels', {value: labels}); } } convert.rgb.hsl = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var min = Math.min(r, g, b); var max = Math.max(r, g, b); var delta = max - min; var h; var s; var l; if (max === min) { h = 0; } else if (r === max) { h = (g - b) / delta; } else if (g === max) { h = 2 + (b - r) / delta; } else if (b === max) { h = 4 + (r - g) / delta; } h = Math.min(h * 60, 360); if (h < 0) { h += 360; } l = (min + max) / 2; if (max === min) { s = 0; } else if (l <= 0.5) { s = delta / (max + min); } else { s = delta / (2 - max - min); } return [h, s * 100, l * 100]; }; convert.rgb.hsv = function (rgb) { var rdif; var gdif; var bdif; var h; var s; var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var v = Math.max(r, g, b); var diff = v - Math.min(r, g, b); var diffc = function (c) { return (v - c) / 6 / diff + 1 / 2; }; if (diff === 0) { h = s = 0; } else { s = diff / v; rdif = diffc(r); gdif = diffc(g); bdif = diffc(b); if (r === v) { h = bdif - gdif; } else if (g === v) { h = (1 / 3) + rdif - bdif; } else if (b === v) { h = (2 / 3) + gdif - rdif; } if (h < 0) { h += 1; } else if (h > 1) { h -= 1; } } return [ h * 360, s * 100, v * 100 ]; }; convert.rgb.hwb = function (rgb) { var r = rgb[0]; var g = rgb[1]; var b = rgb[2]; var h = convert.rgb.hsl(rgb)[0]; var w = 1 / 255 * Math.min(r, Math.min(g, b)); b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); return [h, w * 100, b * 100]; }; convert.rgb.cmyk = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var c; var m; var y; var k; k = Math.min(1 - r, 1 - g, 1 - b); c = (1 - r - k) / (1 - k) || 0; m = (1 - g - k) / (1 - k) || 0; y = (1 - b - k) / (1 - k) || 0; return [c * 100, m * 100, y * 100, k * 100]; }; /** * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance * */ function comparativeDistance(x, y) { return ( Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2) ); } convert.rgb.keyword = function (rgb) { var reversed = reverseKeywords[rgb]; if (reversed) { return reversed; } var currentClosestDistance = Infinity; var currentClosestKeyword; for (var keyword in cssKeywords) { if (cssKeywords.hasOwnProperty(keyword)) { var value = cssKeywords[keyword]; // Compute comparative distance var distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest if (distance < currentClosestDistance) { currentClosestDistance = distance; currentClosestKeyword = keyword; } } } return currentClosestKeyword; }; convert.keyword.rgb = function (keyword) { return cssKeywords[keyword]; }; convert.rgb.xyz = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; // assume sRGB r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92); g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92); b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92); var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); return [x * 100, y * 100, z * 100]; }; convert.rgb.lab = function (rgb) { var xyz = convert.rgb.xyz(rgb); var x = xyz[0]; var y = xyz[1]; var z = xyz[2]; var l; var a; var b; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); l = (116 * y) - 16; a = 500 * (x - y); b = 200 * (y - z); return [l, a, b]; }; convert.hsl.rgb = function (hsl) { var h = hsl[0] / 360; var s = hsl[1] / 100; var l = hsl[2] / 100; var t1; var t2; var t3; var rgb; var val; if (s === 0) { val = l * 255; return [val, val, val]; } if (l < 0.5) { t2 = l * (1 + s); } else { t2 = l + s - l * s; } t1 = 2 * l - t2; rgb = [0, 0, 0]; for (var i = 0; i < 3; i++) { t3 = h + 1 / 3 * -(i - 1); if (t3 < 0) { t3++; } if (t3 > 1) { t3--; } if (6 * t3 < 1) { val = t1 + (t2 - t1) * 6 * t3; } else if (2 * t3 < 1) { val = t2; } else if (3 * t3 < 2) { val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; } else { val = t1; } rgb[i] = val * 255; } return rgb; }; convert.hsl.hsv = function (hsl) { var h = hsl[0]; var s = hsl[1] / 100; var l = hsl[2] / 100; var smin = s; var lmin = Math.max(l, 0.01); var sv; var v; l *= 2; s *= (l <= 1) ? l : 2 - l; smin *= lmin <= 1 ? lmin : 2 - lmin; v = (l + s) / 2; sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); return [h, sv * 100, v * 100]; }; convert.hsv.rgb = function (hsv) { var h = hsv[0] / 60; var s = hsv[1] / 100; var v = hsv[2] / 100; var hi = Math.floor(h) % 6; var f = h - Math.floor(h); var p = 255 * v * (1 - s); var q = 255 * v * (1 - (s * f)); var t = 255 * v * (1 - (s * (1 - f))); v *= 255; switch (hi) { case 0: return [v, t, p]; case 1: return [q, v, p]; case 2: return [p, v, t]; case 3: return [p, q, v]; case 4: return [t, p, v]; case 5: return [v, p, q]; } }; convert.hsv.hsl = function (hsv) { var h = hsv[0]; var s = hsv[1] / 100; var v = hsv[2] / 100; var vmin = Math.max(v, 0.01); var lmin; var sl; var l; l = (2 - s) * v; lmin = (2 - s) * vmin; sl = s * vmin; sl /= (lmin <= 1) ? lmin : 2 - lmin; sl = sl || 0; l /= 2; return [h, sl * 100, l * 100]; }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb convert.hwb.rgb = function (hwb) { var h = hwb[0] / 360; var wh = hwb[1] / 100; var bl = hwb[2] / 100; var ratio = wh + bl; var i; var v; var f; var n; // wh + bl cant be > 1 if (ratio > 1) { wh /= ratio; bl /= ratio; } i = Math.floor(6 * h); v = 1 - bl; f = 6 * h - i; if ((i & 0x01) !== 0) { f = 1 - f; } n = wh + f * (v - wh); // linear interpolation var r; var g; var b; switch (i) { default: case 6: case 0: r = v; g = n; b = wh; break; case 1: r = n; g = v; b = wh; break; case 2: r = wh; g = v; b = n; break; case 3: r = wh; g = n; b = v; break; case 4: r = n; g = wh; b = v; break; case 5: r = v; g = wh; b = n; break; } return [r * 255, g * 255, b * 255]; }; convert.cmyk.rgb = function (cmyk) { var c = cmyk[0] / 100; var m = cmyk[1] / 100; var y = cmyk[2] / 100; var k = cmyk[3] / 100; var r; var g; var b; r = 1 - Math.min(1, c * (1 - k) + k); g = 1 - Math.min(1, m * (1 - k) + k); b = 1 - Math.min(1, y * (1 - k) + k); return [r * 255, g * 255, b * 255]; }; convert.xyz.rgb = function (xyz) { var x = xyz[0] / 100; var y = xyz[1] / 100; var z = xyz[2] / 100; var r; var g; var b; r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); // assume sRGB r = r > 0.0031308 ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055) : r * 12.92; g = g > 0.0031308 ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055) : g * 12.92; b = b > 0.0031308 ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055) : b * 12.92; r = Math.min(Math.max(0, r), 1); g = Math.min(Math.max(0, g), 1); b = Math.min(Math.max(0, b), 1); return [r * 255, g * 255, b * 255]; }; convert.xyz.lab = function (xyz) { var x = xyz[0]; var y = xyz[1]; var z = xyz[2]; var l; var a; var b; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); l = (116 * y) - 16; a = 500 * (x - y); b = 200 * (y - z); return [l, a, b]; }; convert.lab.xyz = function (lab) { var l = lab[0]; var a = lab[1]; var b = lab[2]; var x; var y; var z; y = (l + 16) / 116; x = a / 500 + y; z = y - b / 200; var y2 = Math.pow(y, 3); var x2 = Math.pow(x, 3); var z2 = Math.pow(z, 3); y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; x *= 95.047; y *= 100; z *= 108.883; return [x, y, z]; }; convert.lab.lch = function (lab) { var l = lab[0]; var a = lab[1]; var b = lab[2]; var hr; var h; var c; hr = Math.atan2(b, a); h = hr * 360 / 2 / Math.PI; if (h < 0) { h += 360; } c = Math.sqrt(a * a + b * b); return [l, c, h]; }; convert.lch.lab = function (lch) { var l = lch[0]; var c = lch[1]; var h = lch[2]; var a; var b; var hr; hr = h / 360 * 2 * Math.PI; a = c * Math.cos(hr); b = c * Math.sin(hr); return [l, a, b]; }; convert.rgb.ansi16 = function (args) { var r = args[0]; var g = args[1]; var b = args[2]; var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization value = Math.round(value / 50); if (value === 0) { return 30; } var ansi = 30 + ((Math.round(b / 255) << 2) | (Math.round(g / 255) << 1) | Math.round(r / 255)); if (value === 2) { ansi += 60; } return ansi; }; convert.hsv.ansi16 = function (args) { // optimization here; we already know the value and don't need to get // it converted for us. return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); }; convert.rgb.ansi256 = function (args) { var r = args[0]; var g = args[1]; var b = args[2]; // we use the extended greyscale palette here, with the exception of // black and white. normal palette only has 4 greyscale shades. if (r === g && g === b) { if (r < 8) { return 16; } if (r > 248) { return 231; } return Math.round(((r - 8) / 247) * 24) + 232; } var ansi = 16 + (36 * Math.round(r / 255 * 5)) + (6 * Math.round(g / 255 * 5)) + Math.round(b / 255 * 5); return ansi; }; convert.ansi16.rgb = function (args) { var color = args % 10; // handle greyscale if (color === 0 || color === 7) { if (args > 50) { color += 3.5; } color = color / 10.5 * 255; return [color, color, color]; } var mult = (~~(args > 50) + 1) * 0.5; var r = ((color & 1) * mult) * 255; var g = (((color >> 1) & 1) * mult) * 255; var b = (((color >> 2) & 1) * mult) * 255; return [r, g, b]; }; convert.ansi256.rgb = function (args) { // handle greyscale if (args >= 232) { var c = (args - 232) * 10 + 8; return [c, c, c]; } args -= 16; var rem; var r = Math.floor(args / 36) / 5 * 255; var g = Math.floor((rem = args % 36) / 6) / 5 * 255; var b = (rem % 6) / 5 * 255; return [r, g, b]; }; convert.rgb.hex = function (args) { var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF); var string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert.hex.rgb = function (args) { var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); if (!match) { return [0, 0, 0]; } var colorString = match[0]; if (match[0].length === 3) { colorString = colorString.split('').map(function (char) { return char + char; }).join(''); } var integer = parseInt(colorString, 16); var r = (integer >> 16) & 0xFF; var g = (integer >> 8) & 0xFF; var b = integer & 0xFF; return [r, g, b]; }; convert.rgb.hcg = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var max = Math.max(Math.max(r, g), b); var min = Math.min(Math.min(r, g), b); var chroma = (max - min); var grayscale; var hue; if (chroma < 1) { grayscale = min / (1 - chroma); } else { grayscale = 0; } if (chroma <= 0) { hue = 0; } else if (max === r) { hue = ((g - b) / chroma) % 6; } else if (max === g) { hue = 2 + (b - r) / chroma; } else { hue = 4 + (r - g) / chroma + 4; } hue /= 6; hue %= 1; return [hue * 360, chroma * 100, grayscale * 100]; }; convert.hsl.hcg = function (hsl) { var s = hsl[1] / 100; var l = hsl[2] / 100; var c = 1; var f = 0; if (l < 0.5) { c = 2.0 * s * l; } else { c = 2.0 * s * (1.0 - l); } if (c < 1.0) { f = (l - 0.5 * c) / (1.0 - c); } return [hsl[0], c * 100, f * 100]; }; convert.hsv.hcg = function (hsv) { var s = hsv[1] / 100; var v = hsv[2] / 100; var c = s * v; var f = 0; if (c < 1.0) { f = (v - c) / (1 - c); } return [hsv[0], c * 100, f * 100]; }; convert.hcg.rgb = function (hcg) { var h = hcg[0] / 360; var c = hcg[1] / 100; var g = hcg[2] / 100; if (c === 0.0) { return [g * 255, g * 255, g * 255]; } var pure = [0, 0, 0]; var hi = (h % 1) * 6; var v = hi % 1; var w = 1 - v; var mg = 0; switch (Math.floor(hi)) { case 0: pure[0] = 1; pure[1] = v; pure[2] = 0; break; case 1: pure[0] = w; pure[1] = 1; pure[2] = 0; break; case 2: pure[0] = 0; pure[1] = 1; pure[2] = v; break; case 3: pure[0] = 0; pure[1] = w; pure[2] = 1; break; case 4: pure[0] = v; pure[1] = 0; pure[2] = 1; break; default: pure[0] = 1; pure[1] = 0; pure[2] = w; } mg = (1.0 - c) * g; return [ (c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255 ]; }; convert.hcg.hsv = function (hcg) { var c = hcg[1] / 100; var g = hcg[2] / 100; var v = c + g * (1.0 - c); var f = 0; if (v > 0.0) { f = c / v; } return [hcg[0], f * 100, v * 100]; }; convert.hcg.hsl = function (hcg) { var c = hcg[1] / 100; var g = hcg[2] / 100; var l = g * (1.0 - c) + 0.5 * c; var s = 0; if (l > 0.0 && l < 0.5) { s = c / (2 * l); } else if (l >= 0.5 && l < 1.0) { s = c / (2 * (1 - l)); } return [hcg[0], s * 100, l * 100]; }; convert.hcg.hwb = function (hcg) { var c = hcg[1] / 100; var g = hcg[2] / 100; var v = c + g * (1.0 - c); return [hcg[0], (v - c) * 100, (1 - v) * 100]; }; convert.hwb.hcg = function (hwb) { var w = hwb[1] / 100; var b = hwb[2] / 100; var v = 1 - b; var c = v - w; var g = 0; if (c < 1) { g = (v - c) / (1 - c); } return [hwb[0], c * 100, g * 100]; }; convert.apple.rgb = function (apple) { return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; }; convert.rgb.apple = function (rgb) { return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; }; convert.gray.rgb = function (args) { return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; }; convert.gray.hsl = convert.gray.hsv = function (args) { return [0, 0, args[0]]; }; convert.gray.hwb = function (gray) { return [0, 100, gray[0]]; }; convert.gray.cmyk = function (gray) { return [0, 0, 0, gray[0]]; }; convert.gray.lab = function (gray) { return [gray[0], 0, 0]; }; convert.gray.hex = function (gray) { var val = Math.round(gray[0] / 100 * 255) & 0xFF; var integer = (val << 16) + (val << 8) + val; var string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert.rgb.gray = function (rgb) { var val = (rgb[0] + rgb[1] + rgb[2]) / 3; return [val / 255 * 100]; }; },{"color-name":188}],186:[function(require,module,exports){ var conversions = require('./conversions'); var route = require('./route'); var convert = {}; var models = Object.keys(conversions); function wrapRaw(fn) { var wrappedFn = function (args) { if (args === undefined || args === null) { return args; } if (arguments.length > 1) { args = Array.prototype.slice.call(arguments); } return fn(args); }; // preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } function wrapRounded(fn) { var wrappedFn = function (args) { if (args === undefined || args === null) { return args; } if (arguments.length > 1) { args = Array.prototype.slice.call(arguments); } var result = fn(args); // we're assuming the result is an array here. // see notice in conversions.js; don't use box types // in conversion functions. if (typeof result === 'object') { for (var len = result.length, i = 0; i < len; i++) { result[i] = Math.round(result[i]); } } return result; }; // preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } models.forEach(function (fromModel) { convert[fromModel] = {}; Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); var routes = route(fromModel); var routeModels = Object.keys(routes); routeModels.forEach(function (toModel) { var fn = routes[toModel]; convert[fromModel][toModel] = wrapRounded(fn); convert[fromModel][toModel].raw = wrapRaw(fn); }); }); module.exports = convert; },{"./conversions":185,"./route":187}],187:[function(require,module,exports){ var conversions = require('./conversions'); /* this function routes a model to all other models. all functions that are routed have a property `.conversion` attached to the returned synthetic function. This property is an array of strings, each with the steps in between the 'from' and 'to' color models (inclusive). conversions that are not possible simply are not included. */ function buildGraph() { var graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3 var models = Object.keys(conversions); for (var len = models.length, i = 0; i < len; i++) { graph[models[i]] = { // http://jsperf.com/1-vs-infinity // micro-opt, but this is simple. distance: -1, parent: null }; } return graph; } // https://en.wikipedia.org/wiki/Breadth-first_search function deriveBFS(fromModel) { var graph = buildGraph(); var queue = [fromModel]; // unshift -> queue -> pop graph[fromModel].distance = 0; while (queue.length) { var current = queue.pop(); var adjacents = Object.keys(conversions[current]); for (var len = adjacents.length, i = 0; i < len; i++) { var adjacent = adjacents[i]; var node = graph[adjacent]; if (node.distance === -1) { node.distance = graph[current].distance + 1; node.parent = current; queue.unshift(adjacent); } } } return graph; } function link(from, to) { return function (args) { return to(from(args)); }; } function wrapConversion(toModel, graph) { var path = [graph[toModel].parent, toModel]; var fn = conversions[graph[toModel].parent][toModel]; var cur = graph[toModel].parent; while (graph[cur].parent) { path.unshift(graph[cur].parent); fn = link(conversions[graph[cur].parent][cur], fn); cur = graph[cur].parent; } fn.conversion = path; return fn; } module.exports = function (fromModel) { var graph = deriveBFS(fromModel); var conversion = {}; var models = Object.keys(graph); for (var len = models.length, i = 0; i < len; i++) { var toModel = models[i]; var node = graph[toModel]; if (node.parent === null) { // no possible conversion, or this node is the source model. continue; } conversion[toModel] = wrapConversion(toModel, graph); } return conversion; }; },{"./conversions":185}],188:[function(require,module,exports){ 'use strict' module.exports = { "aliceblue": [240, 248, 255], "antiquewhite": [250, 235, 215], "aqua": [0, 255, 255], "aquamarine": [127, 255, 212], "azure": [240, 255, 255], "beige": [245, 245, 220], "bisque": [255, 228, 196], "black": [0, 0, 0], "blanchedalmond": [255, 235, 205], "blue": [0, 0, 255], "blueviolet": [138, 43, 226], "brown": [165, 42, 42], "burlywood": [222, 184, 135], "cadetblue": [95, 158, 160], "chartreuse": [127, 255, 0], "chocolate": [210, 105, 30], "coral": [255, 127, 80], "cornflowerblue": [100, 149, 237], "cornsilk": [255, 248, 220], "crimson": [220, 20, 60], "cyan": [0, 255, 255], "darkblue": [0, 0, 139], "darkcyan": [0, 139, 139], "darkgoldenrod": [184, 134, 11], "darkgray": [169, 169, 169], "darkgreen": [0, 100, 0], "darkgrey": [169, 169, 169], "darkkhaki": [189, 183, 107], "darkmagenta": [139, 0, 139], "darkolivegreen": [85, 107, 47], "darkorange": [255, 140, 0], "darkorchid": [153, 50, 204], "darkred": [139, 0, 0], "darksalmon": [233, 150, 122], "darkseagreen": [143, 188, 143], "darkslateblue": [72, 61, 139], "darkslategray": [47, 79, 79], "darkslategrey": [47, 79, 79], "darkturquoise": [0, 206, 209], "darkviolet": [148, 0, 211], "deeppink": [255, 20, 147], "deepskyblue": [0, 191, 255], "dimgray": [105, 105, 105], "dimgrey": [105, 105, 105], "dodgerblue": [30, 144, 255], "firebrick": [178, 34, 34], "floralwhite": [255, 250, 240], "forestgreen": [34, 139, 34], "fuchsia": [255, 0, 255], "gainsboro": [220, 220, 220], "ghostwhite": [248, 248, 255], "gold": [255, 215, 0], "goldenrod": [218, 165, 32], "gray": [128, 128, 128], "green": [0, 128, 0], "greenyellow": [173, 255, 47], "grey": [128, 128, 128], "honeydew": [240, 255, 240], "hotpink": [255, 105, 180], "indianred": [205, 92, 92], "indigo": [75, 0, 130], "ivory": [255, 255, 240], "khaki": [240, 230, 140], "lavender": [230, 230, 250], "lavenderblush": [255, 240, 245], "lawngreen": [124, 252, 0], "lemonchiffon": [255, 250, 205], "lightblue": [173, 216, 230], "lightcoral": [240, 128, 128], "lightcyan": [224, 255, 255], "lightgoldenrodyellow": [250, 250, 210], "lightgray": [211, 211, 211], "lightgreen": [144, 238, 144], "lightgrey": [211, 211, 211], "lightpink": [255, 182, 193], "lightsalmon": [255, 160, 122], "lightseagreen": [32, 178, 170], "lightskyblue": [135, 206, 250], "lightslategray": [119, 136, 153], "lightslategrey": [119, 136, 153], "lightsteelblue": [176, 196, 222], "lightyellow": [255, 255, 224], "lime": [0, 255, 0], "limegreen": [50, 205, 50], "linen": [250, 240, 230], "magenta": [255, 0, 255], "maroon": [128, 0, 0], "mediumaquamarine": [102, 205, 170], "mediumblue": [0, 0, 205], "mediumorchid": [186, 85, 211], "mediumpurple": [147, 112, 219], "mediumseagreen": [60, 179, 113], "mediumslateblue": [123, 104, 238], "mediumspringgreen": [0, 250, 154], "mediumturquoise": [72, 209, 204], "mediumvioletred": [199, 21, 133], "midnightblue": [25, 25, 112], "mintcream": [245, 255, 250], "mistyrose": [255, 228, 225], "moccasin": [255, 228, 181], "navajowhite": [255, 222, 173], "navy": [0, 0, 128], "oldlace": [253, 245, 230], "olive": [128, 128, 0], "olivedrab": [107, 142, 35], "orange": [255, 165, 0], "orangered": [255, 69, 0], "orchid": [218, 112, 214], "palegoldenrod": [238, 232, 170], "palegreen": [152, 251, 152], "paleturquoise": [175, 238, 238], "palevioletred": [219, 112, 147], "papayawhip": [255, 239, 213], "peachpuff": [255, 218, 185], "peru": [205, 133, 63], "pink": [255, 192, 203], "plum": [221, 160, 221], "powderblue": [176, 224, 230], "purple": [128, 0, 128], "rebeccapurple": [102, 51, 153], "red": [255, 0, 0], "rosybrown": [188, 143, 143], "royalblue": [65, 105, 225], "saddlebrown": [139, 69, 19], "salmon": [250, 128, 114], "sandybrown": [244, 164, 96], "seagreen": [46, 139, 87], "seashell": [255, 245, 238], "sienna": [160, 82, 45], "silver": [192, 192, 192], "skyblue": [135, 206, 235], "slateblue": [106, 90, 205], "slategray": [112, 128, 144], "slategrey": [112, 128, 144], "snow": [255, 250, 250], "springgreen": [0, 255, 127], "steelblue": [70, 130, 180], "tan": [210, 180, 140], "teal": [0, 128, 128], "thistle": [216, 191, 216], "tomato": [255, 99, 71], "turquoise": [64, 224, 208], "violet": [238, 130, 238], "wheat": [245, 222, 179], "white": [255, 255, 255], "whitesmoke": [245, 245, 245], "yellow": [255, 255, 0], "yellowgreen": [154, 205, 50] }; },{}],189:[function(require,module,exports){ 'use strict'; var fs = require('fs'); var path = require('path'); var SafeBuffer = require('safe-buffer'); Object.defineProperty(exports, 'commentRegex', { get: function getCommentRegex () { return /^\s*\/(?:\/|\*)[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,(?:.*)$/mg; } }); Object.defineProperty(exports, 'mapFileCommentRegex', { get: function getMapFileCommentRegex () { // Matches sourceMappingURL in either // or /* comment styles. return /(?:\/\/[@#][ \t]+sourceMappingURL=([^\s'"`]+?)[ \t]*$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^\*]+?)[ \t]*(?:\*\/){1}[ \t]*$)/mg; } }); function decodeBase64(base64) { return SafeBuffer.Buffer.from(base64, 'base64').toString(); } function stripComment(sm) { return sm.split(',').pop(); } function readFromFileMap(sm, dir) { // NOTE: this will only work on the server since it attempts to read the map file var r = exports.mapFileCommentRegex.exec(sm); // for some odd reason //# .. captures in 1 and /* .. */ in 2 var filename = r[1] || r[2]; var filepath = path.resolve(dir, filename); try { return fs.readFileSync(filepath, 'utf8'); } catch (e) { throw new Error('An error occurred while trying to read the map file at ' + filepath + '\n' + e); } } function Converter (sm, opts) { opts = opts || {}; if (opts.isFileComment) sm = readFromFileMap(sm, opts.commentFileDir); if (opts.hasComment) sm = stripComment(sm); if (opts.isEncoded) sm = decodeBase64(sm); if (opts.isJSON || opts.isEncoded) sm = JSON.parse(sm); this.sourcemap = sm; } Converter.prototype.toJSON = function (space) { return JSON.stringify(this.sourcemap, null, space); }; Converter.prototype.toBase64 = function () { var json = this.toJSON(); return SafeBuffer.Buffer.from(json, 'utf8').toString('base64'); }; Converter.prototype.toComment = function (options) { var base64 = this.toBase64(); var data = 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + base64; return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data; }; // returns copy instead of original Converter.prototype.toObject = function () { return JSON.parse(this.toJSON()); }; Converter.prototype.addProperty = function (key, value) { if (this.sourcemap.hasOwnProperty(key)) throw new Error('property "' + key + '" already exists on the sourcemap, use set property instead'); return this.setProperty(key, value); }; Converter.prototype.setProperty = function (key, value) { this.sourcemap[key] = value; return this; }; Converter.prototype.getProperty = function (key) { return this.sourcemap[key]; }; exports.fromObject = function (obj) { return new Converter(obj); }; exports.fromJSON = function (json) { return new Converter(json, { isJSON: true }); }; exports.fromBase64 = function (base64) { return new Converter(base64, { isEncoded: true }); }; exports.fromComment = function (comment) { comment = comment .replace(/^\/\*/g, '//') .replace(/\*\/$/g, ''); return new Converter(comment, { isEncoded: true, hasComment: true }); }; exports.fromMapFileComment = function (comment, dir) { return new Converter(comment, { commentFileDir: dir, isFileComment: true, isJSON: true }); }; // Finds last sourcemap comment in file or returns null if none was found exports.fromSource = function (content) { var m = content.match(exports.commentRegex); return m ? exports.fromComment(m.pop()) : null; }; // Finds last sourcemap comment in file or returns null if none was found exports.fromMapFileSource = function (content, dir) { var m = content.match(exports.mapFileCommentRegex); return m ? exports.fromMapFileComment(m.pop(), dir) : null; }; exports.removeComments = function (src) { return src.replace(exports.commentRegex, ''); }; exports.removeMapFileComments = function (src) { return src.replace(exports.mapFileCommentRegex, ''); }; exports.generateMapFileComment = function (file, options) { var data = 'sourceMappingURL=' + file; return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data; }; },{"fs":181,"path":403,"safe-buffer":431}],190:[function(require,module,exports){ (function (Buffer){ // 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 === '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 === '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 === '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":204}],191:[function(require,module,exports){ (function (process){ /* eslint-env browser */ /** * This is the web browser implementation of `debug()`. */ exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = localstorage(); /** * Colors. */ exports.colors = [ '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ // eslint-disable-next-line complexity function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { return true; } // Internet Explorer and Edge do not support colors. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { return false; } // Is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || // Is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // Is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || // Double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff); if (!this.useColors) { return; } const c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into let index = 0; let lastC = 0; args[0].replace(/%[a-zA-Z%]/g, match => { if (match === '%%') { return; } index++; if (match === '%c') { // We only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.log()` when available. * No-op when `console.log` is not a "function". * * @api public */ function log(...args) { // This hackery is required for IE8/9, where // the `console.log` function doesn't have 'apply' return typeof console === 'object' && console.log && console.log(...args); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (namespaces) { exports.storage.setItem('debug', namespaces); } else { exports.storage.removeItem('debug'); } } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { let r; try { r = exports.storage.getItem('debug'); } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; } /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage() { try { // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context // The Browser also has localStorage in the global context. return localStorage; } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? } } module.exports = require('./common')(exports); const {formatters} = module.exports; /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ formatters.j = function (v) { try { return JSON.stringify(v); } catch (error) { return '[UnexpectedJSONParseError]: ' + error.message; } }; }).call(this,require('_process')) },{"./common":192,"_process":405}],192:[function(require,module,exports){ /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. */ function setup(env) { createDebug.debug = createDebug; createDebug.default = createDebug; createDebug.coerce = coerce; createDebug.disable = disable; createDebug.enable = enable; createDebug.enabled = enabled; createDebug.humanize = require('ms'); Object.keys(env).forEach(key => { createDebug[key] = env[key]; }); /** * Active `debug` instances. */ createDebug.instances = []; /** * The currently active debug mode names, and names to skip. */ createDebug.names = []; createDebug.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ createDebug.formatters = {}; /** * Selects a color for a debug namespace * @param {String} namespace The namespace string for the for the debug instance to be colored * @return {Number|String} An ANSI color code for the given namespace * @api private */ function selectColor(namespace) { let hash = 0; for (let i = 0; i < namespace.length; i++) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; } createDebug.selectColor = selectColor; /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { let prevTime; function debug(...args) { // Disabled? if (!debug.enabled) { return; } const self = debug; // Set `diff` timestamp const curr = Number(new Date()); const ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; args[0] = createDebug.coerce(args[0]); if (typeof args[0] !== 'string') { // Anything else let's inspect with %O args.unshift('%O'); } // Apply any `formatters` transformations let index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { // If we encounter an escaped % then don't increase the array index if (match === '%%') { return match; } index++; const formatter = createDebug.formatters[format]; if (typeof formatter === 'function') { const val = args[index]; match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // Apply env-specific formatting (colors, etc.) createDebug.formatArgs.call(self, args); const logFn = self.log || createDebug.log; logFn.apply(self, args); } debug.namespace = namespace; debug.enabled = createDebug.enabled(namespace); debug.useColors = createDebug.useColors(); debug.color = selectColor(namespace); debug.destroy = destroy; debug.extend = extend; // Debug.formatArgs = formatArgs; // debug.rawLog = rawLog; // env-specific initialization logic for debug instances if (typeof createDebug.init === 'function') { createDebug.init(debug); } createDebug.instances.push(debug); return debug; } function destroy() { const index = createDebug.instances.indexOf(this); if (index !== -1) { createDebug.instances.splice(index, 1); return true; } return false; } function extend(namespace, delimiter) { const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); newDebug.log = this.log; return newDebug; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { createDebug.save(namespaces); createDebug.names = []; createDebug.skips = []; let i; const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); const len = split.length; for (i = 0; i < len; i++) { if (!split[i]) { // ignore empty strings continue; } namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); } else { createDebug.names.push(new RegExp('^' + namespaces + '$')); } } for (i = 0; i < createDebug.instances.length; i++) { const instance = createDebug.instances[i]; instance.enabled = createDebug.enabled(instance.namespace); } } /** * Disable debug output. * * @return {String} namespaces * @api public */ function disable() { const namespaces = [ ...createDebug.names.map(toNamespace), ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) ].join(','); createDebug.enable(''); return namespaces; } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { if (name[name.length - 1] === '*') { return true; } let i; let len; for (i = 0, len = createDebug.skips.length; i < len; i++) { if (createDebug.skips[i].test(name)) { return false; } } for (i = 0, len = createDebug.names.length; i < len; i++) { if (createDebug.names[i].test(name)) { return true; } } return false; } /** * Convert regexp to namespace * * @param {RegExp} regxep * @return {String} namespace * @api private */ function toNamespace(regexp) { return regexp.toString() .substring(2, regexp.toString().length - 2) .replace(/\.\*\?$/, '*'); } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) { return val.stack || val.message; } return val; } createDebug.enable(createDebug.load()); return createDebug; } module.exports = setup; },{"ms":401}],193:[function(require,module,exports){ 'use strict'; var token = '%[a-f0-9]{2}'; var singleMatcher = new RegExp(token, 'gi'); var multiMatcher = new RegExp('(' + token + ')+', 'gi'); function decodeComponents(components, split) { try { // Try to decode the entire string first return decodeURIComponent(components.join('')); } catch (err) { // Do nothing } if (components.length === 1) { return components; } split = split || 1; // Split the array in 2 parts var left = components.slice(0, split); var right = components.slice(split); return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right)); } function decode(input) { try { return decodeURIComponent(input); } catch (err) { var tokens = input.match(singleMatcher); for (var i = 1; i < tokens.length; i++) { input = decodeComponents(tokens, i).join(''); tokens = input.match(singleMatcher); } return input; } } function customDecodeURIComponent(input) { // Keep track of all the replacements and prefill the map with the `BOM` var replaceMap = { '%FE%FF': '\uFFFD\uFFFD', '%FF%FE': '\uFFFD\uFFFD' }; var match = multiMatcher.exec(input); while (match) { try { // Decode as big chunks as possible replaceMap[match[0]] = decodeURIComponent(match[0]); } catch (err) { var result = decode(match[0]); if (result !== match[0]) { replaceMap[match[0]] = result; } } match = multiMatcher.exec(input); } // Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else replaceMap['%C2'] = '\uFFFD'; var entries = Object.keys(replaceMap); for (var i = 0; i < entries.length; i++) { // Replace all decoded components var key = entries[i]; input = input.replace(new RegExp(key, 'g'), replaceMap[key]); } return input; } module.exports = function (encodedURI) { if (typeof encodedURI !== 'string') { throw new TypeError('Expected `encodedURI` to be of type `string`, got `' + typeof encodedURI + '`'); } try { encodedURI = encodedURI.replace(/\+/g, ' '); // Try the built in decoder first return decodeURIComponent(encodedURI); } catch (err) { // Fallback to a more advanced decoder return customDecodeURIComponent(encodedURI); } }; },{}],194:[function(require,module,exports){ 'use strict'; var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; module.exports = function (str) { if (typeof str !== 'string') { throw new TypeError('Expected a string'); } return str.replace(matchOperatorsRe, '\\$&'); }; },{}],195:[function(require,module,exports){ /* Copyright (C) 2013 Yusuke Suzuki 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 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 () { 'use strict'; function isExpression(node) { if (node == null) { return false; } switch (node.type) { case 'ArrayExpression': case 'AssignmentExpression': case 'BinaryExpression': case 'CallExpression': case 'ConditionalExpression': case 'FunctionExpression': case 'Identifier': case 'Literal': case 'LogicalExpression': case 'MemberExpression': case 'NewExpression': case 'ObjectExpression': case 'SequenceExpression': case 'ThisExpression': case 'UnaryExpression': case 'UpdateExpression': return true; } return false; } function isIterationStatement(node) { if (node == null) { return false; } switch (node.type) { case 'DoWhileStatement': case 'ForInStatement': case 'ForStatement': case 'WhileStatement': return true; } return false; } function isStatement(node) { if (node == null) { return false; } switch (node.type) { case 'BlockStatement': case 'BreakStatement': case 'ContinueStatement': case 'DebuggerStatement': case 'DoWhileStatement': case 'EmptyStatement': case 'ExpressionStatement': case 'ForInStatement': case 'ForStatement': case 'IfStatement': case 'LabeledStatement': case 'ReturnStatement': case 'SwitchStatement': case 'ThrowStatement': case 'TryStatement': case 'VariableDeclaration': case 'WhileStatement': case 'WithStatement': return true; } return false; } function isSourceElement(node) { return isStatement(node) || node != null && node.type === 'FunctionDeclaration'; } function trailingStatement(node) { switch (node.type) { case 'IfStatement': if (node.alternate != null) { return node.alternate; } return node.consequent; case 'LabeledStatement': case 'ForStatement': case 'ForInStatement': case 'WhileStatement': case 'WithStatement': return node.body; } return null; } function isProblematicIfStatement(node) { var current; if (node.type !== 'IfStatement') { return false; } if (node.alternate == null) { return false; } current = node.consequent; do { if (current.type === 'IfStatement') { if (current.alternate == null) { return true; } } current = trailingStatement(current); } while (current); return false; } module.exports = { isExpression: isExpression, isStatement: isStatement, isIterationStatement: isIterationStatement, isSourceElement: isSourceElement, isProblematicIfStatement: isProblematicIfStatement, trailingStatement: trailingStatement }; }()); /* vim: set sw=4 ts=4 et tw=80 : */ },{}],196:[function(require,module,exports){ /* Copyright (C) 2013-2014 Yusuke Suzuki Copyright (C) 2014 Ivan Nikulin 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 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 () { 'use strict'; var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch; // See `tools/generate-identifier-regex.js`. ES5Regex = { // ECMAScript 5.1/Unicode v7.0.0 NonAsciiIdentifierStart: NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/, // ECMAScript 5.1/Unicode v7.0.0 NonAsciiIdentifierPart: NonAsciiIdentifierPart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/ }; ES6Regex = { // ECMAScript 6/Unicode v7.0.0 NonAsciiIdentifierStart: NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDE00-\uDE11\uDE13-\uDE2B\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDE00-\uDE2F\uDE44\uDE80-\uDEAA]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]/, // ECMAScript 6/Unicode v7.0.0 NonAsciiIdentifierPart: NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDD0-\uDDDA\uDE00-\uDE11\uDE13-\uDE37\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF01-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/ }; function isDecimalDigit(ch) { return 0x30 <= ch && ch <= 0x39; // 0..9 } function isHexDigit(ch) { return 0x30 <= ch && ch <= 0x39 || // 0..9 0x61 <= ch && ch <= 0x66 || // a..f 0x41 <= ch && ch <= 0x46; // A..F } function isOctalDigit(ch) { return ch >= 0x30 && ch <= 0x37; // 0..7 } // 7.2 White Space NON_ASCII_WHITESPACES = [ 0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF ]; function isWhiteSpace(ch) { return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0; } // 7.3 Line Terminators function isLineTerminator(ch) { return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029; } // 7.6 Identifier Names and Identifiers function fromCodePoint(cp) { if (cp <= 0xFFFF) { return String.fromCharCode(cp); } var cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800); var cu2 = String.fromCharCode(((cp - 0x10000) % 0x400) + 0xDC00); return cu1 + cu2; } IDENTIFIER_START = new Array(0x80); for(ch = 0; ch < 0x80; ++ch) { IDENTIFIER_START[ch] = ch >= 0x61 && ch <= 0x7A || // a..z ch >= 0x41 && ch <= 0x5A || // A..Z ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) } IDENTIFIER_PART = new Array(0x80); for(ch = 0; ch < 0x80; ++ch) { IDENTIFIER_PART[ch] = ch >= 0x61 && ch <= 0x7A || // a..z ch >= 0x41 && ch <= 0x5A || // A..Z ch >= 0x30 && ch <= 0x39 || // 0..9 ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) } function isIdentifierStartES5(ch) { return ch < 0x80 ? IDENTIFIER_START[ch] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); } function isIdentifierPartES5(ch) { return ch < 0x80 ? IDENTIFIER_PART[ch] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); } function isIdentifierStartES6(ch) { return ch < 0x80 ? IDENTIFIER_START[ch] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); } function isIdentifierPartES6(ch) { return ch < 0x80 ? IDENTIFIER_PART[ch] : ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); } module.exports = { isDecimalDigit: isDecimalDigit, isHexDigit: isHexDigit, isOctalDigit: isOctalDigit, isWhiteSpace: isWhiteSpace, isLineTerminator: isLineTerminator, isIdentifierStartES5: isIdentifierStartES5, isIdentifierPartES5: isIdentifierPartES5, isIdentifierStartES6: isIdentifierStartES6, isIdentifierPartES6: isIdentifierPartES6 }; }()); /* vim: set sw=4 ts=4 et tw=80 : */ },{}],197:[function(require,module,exports){ /* Copyright (C) 2013 Yusuke Suzuki 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 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 () { 'use strict'; var code = require('./code'); function isStrictModeReservedWordES6(id) { switch (id) { case 'implements': case 'interface': case 'package': case 'private': case 'protected': case 'public': case 'static': case 'let': return true; default: return false; } } function isKeywordES5(id, strict) { // yield should not be treated as keyword under non-strict mode. if (!strict && id === 'yield') { return false; } return isKeywordES6(id, strict); } function isKeywordES6(id, strict) { if (strict && isStrictModeReservedWordES6(id)) { return true; } switch (id.length) { case 2: return (id === 'if') || (id === 'in') || (id === 'do'); case 3: return (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try'); case 4: return (id === 'this') || (id === 'else') || (id === 'case') || (id === 'void') || (id === 'with') || (id === 'enum'); case 5: return (id === 'while') || (id === 'break') || (id === 'catch') || (id === 'throw') || (id === 'const') || (id === 'yield') || (id === 'class') || (id === 'super'); case 6: return (id === 'return') || (id === 'typeof') || (id === 'delete') || (id === 'switch') || (id === 'export') || (id === 'import'); case 7: return (id === 'default') || (id === 'finally') || (id === 'extends'); case 8: return (id === 'function') || (id === 'continue') || (id === 'debugger'); case 10: return (id === 'instanceof'); default: return false; } } function isReservedWordES5(id, strict) { return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict); } function isReservedWordES6(id, strict) { return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict); } function isRestrictedWord(id) { return id === 'eval' || id === 'arguments'; } function isIdentifierNameES5(id) { var i, iz, ch; if (id.length === 0) { return false; } ch = id.charCodeAt(0); if (!code.isIdentifierStartES5(ch)) { return false; } for (i = 1, iz = id.length; i < iz; ++i) { ch = id.charCodeAt(i); if (!code.isIdentifierPartES5(ch)) { return false; } } return true; } function decodeUtf16(lead, trail) { return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; } function isIdentifierNameES6(id) { var i, iz, ch, lowCh, check; if (id.length === 0) { return false; } check = code.isIdentifierStartES6; for (i = 0, iz = id.length; i < iz; ++i) { ch = id.charCodeAt(i); if (0xD800 <= ch && ch <= 0xDBFF) { ++i; if (i >= iz) { return false; } lowCh = id.charCodeAt(i); if (!(0xDC00 <= lowCh && lowCh <= 0xDFFF)) { return false; } ch = decodeUtf16(ch, lowCh); } if (!check(ch)) { return false; } check = code.isIdentifierPartES6; } return true; } function isIdentifierES5(id, strict) { return isIdentifierNameES5(id) && !isReservedWordES5(id, strict); } function isIdentifierES6(id, strict) { return isIdentifierNameES6(id) && !isReservedWordES6(id, strict); } module.exports = { isKeywordES5: isKeywordES5, isKeywordES6: isKeywordES6, isReservedWordES5: isReservedWordES5, isReservedWordES6: isReservedWordES6, isRestrictedWord: isRestrictedWord, isIdentifierNameES5: isIdentifierNameES5, isIdentifierNameES6: isIdentifierNameES6, isIdentifierES5: isIdentifierES5, isIdentifierES6: isIdentifierES6 }; }()); /* vim: set sw=4 ts=4 et tw=80 : */ },{"./code":196}],198:[function(require,module,exports){ /* Copyright (C) 2013 Yusuke Suzuki 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 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 () { 'use strict'; exports.ast = require('./ast'); exports.code = require('./code'); exports.keyword = require('./keyword'); }()); /* vim: set sw=4 ts=4 et tw=80 : */ },{"./ast":195,"./code":196,"./keyword":197}],199:[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 objectCreate = Object.create || objectCreatePolyfill var objectKeys = Object.keys || objectKeysPolyfill var bind = Function.prototype.bind || functionBindPolyfill function EventEmitter() { if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) { this._events = objectCreate(null); this._eventsCount = 0; } 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. var defaultMaxListeners = 10; var hasDefineProperty; try { var o = {}; if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 }); hasDefineProperty = o.x === 0; } catch (err) { hasDefineProperty = false } if (hasDefineProperty) { Object.defineProperty(EventEmitter, 'defaultMaxListeners', { enumerable: true, get: function() { return defaultMaxListeners; }, set: function(arg) { // check whether the input is a positive number (whose value is zero or // greater and not a NaN). if (typeof arg !== 'number' || arg < 0 || arg !== arg) throw new TypeError('"defaultMaxListeners" must be a positive number'); defaultMaxListeners = arg; } }); } else { EventEmitter.defaultMaxListeners = defaultMaxListeners; } // 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 setMaxListeners(n) { if (typeof n !== 'number' || n < 0 || isNaN(n)) throw new TypeError('"n" argument must be a positive number'); this._maxListeners = n; return this; }; function $getMaxListeners(that) { if (that._maxListeners === undefined) return EventEmitter.defaultMaxListeners; return that._maxListeners; } EventEmitter.prototype.getMaxListeners = function getMaxListeners() { return $getMaxListeners(this); }; // These standalone emit* functions are used to optimize calling of event // handlers for fast cases because emit() itself often has a variable number of // arguments and can be deoptimized because of that. These functions always have // the same number of arguments and thus do not get deoptimized, so the code // inside them can execute faster. function emitNone(handler, isFn, self) { if (isFn) handler.call(self); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self); } } function emitOne(handler, isFn, self, arg1) { if (isFn) handler.call(self, arg1); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self, arg1); } } function emitTwo(handler, isFn, self, arg1, arg2) { if (isFn) handler.call(self, arg1, arg2); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self, arg1, arg2); } } function emitThree(handler, isFn, self, arg1, arg2, arg3) { if (isFn) handler.call(self, arg1, arg2, arg3); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self, arg1, arg2, arg3); } } function emitMany(handler, isFn, self, args) { if (isFn) handler.apply(self, args); else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].apply(self, args); } } EventEmitter.prototype.emit = function emit(type) { var er, handler, len, args, i, events; var doError = (type === 'error'); events = this._events; if (events) doError = (doError && events.error == null); else if (!doError) return false; // If there is no 'error' event listener then throw. if (doError) { if (arguments.length > 1) 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('Unhandled "error" event. (' + er + ')'); err.context = er; throw err; } return false; } handler = events[type]; if (!handler) return false; var isFn = typeof handler === 'function'; len = arguments.length; switch (len) { // fast cases case 1: emitNone(handler, isFn, this); break; case 2: emitOne(handler, isFn, this, arguments[1]); break; case 3: emitTwo(handler, isFn, this, arguments[1], arguments[2]); break; case 4: emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); break; // slower default: args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; emitMany(handler, isFn, this, args); } return true; }; function _addListener(target, type, listener, prepend) { var m; var events; var existing; if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); events = target._events; if (!events) { events = target._events = objectCreate(null); target._eventsCount = 0; } else { // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (events.newListener) { target.emit('newListener', type, listener.listener ? listener.listener : listener); // Re-assign `events` because a newListener handler could have caused the // this._events to be assigned to a new object events = target._events; } existing = events[type]; } if (!existing) { // Optimize the case of one listener. Don't need the extra array object. existing = events[type] = listener; ++target._eventsCount; } else { if (typeof existing === 'function') { // Adding the second element, need to change to array. existing = events[type] = prepend ? [listener, existing] : [existing, listener]; } else { // If we've already got an array, just append. if (prepend) { existing.unshift(listener); } else { existing.push(listener); } } // Check for listener leak if (!existing.warned) { m = $getMaxListeners(target); if (m && m > 0 && existing.length > m) { existing.warned = true; var w = new Error('Possible EventEmitter memory leak detected. ' + existing.length + ' "' + String(type) + '" listeners ' + 'added. Use emitter.setMaxListeners() to ' + 'increase limit.'); w.name = 'MaxListenersExceededWarning'; w.emitter = target; w.type = type; w.count = existing.length; if (typeof console === 'object' && console.warn) { console.warn('%s: %s', w.name, w.message); } } } } return target; } EventEmitter.prototype.addListener = function addListener(type, listener) { return _addListener(this, type, listener, false); }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.prependListener = function prependListener(type, listener) { return _addListener(this, type, listener, true); }; function onceWrapper() { if (!this.fired) { this.target.removeListener(this.type, this.wrapFn); this.fired = true; switch (arguments.length) { case 0: return this.listener.call(this.target); case 1: return this.listener.call(this.target, arguments[0]); case 2: return this.listener.call(this.target, arguments[0], arguments[1]); case 3: return this.listener.call(this.target, arguments[0], arguments[1], arguments[2]); default: var args = new Array(arguments.length); for (var i = 0; i < args.length; ++i) args[i] = arguments[i]; this.listener.apply(this.target, args); } } } function _onceWrap(target, type, listener) { var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; var wrapped = bind.call(onceWrapper, state); wrapped.listener = listener; state.wrapFn = wrapped; return wrapped; } EventEmitter.prototype.once = function once(type, listener) { if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); this.on(type, _onceWrap(this, type, listener)); return this; }; EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) { if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); this.prependListener(type, _onceWrap(this, type, listener)); return this; }; // Emits a 'removeListener' event if and only if the listener was removed. EventEmitter.prototype.removeListener = function removeListener(type, listener) { var list, events, position, i, originalListener; if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); events = this._events; if (!events) return this; list = events[type]; if (!list) return this; if (list === listener || list.listener === listener) { if (--this._eventsCount === 0) this._events = objectCreate(null); else { delete events[type]; if (events.removeListener) this.emit('removeListener', type, list.listener || listener); } } else if (typeof list !== 'function') { position = -1; for (i = list.length - 1; i >= 0; i--) { if (list[i] === listener || list[i].listener === listener) { originalListener = list[i].listener; position = i; break; } } if (position < 0) return this; if (position === 0) list.shift(); else spliceOne(list, position); if (list.length === 1) events[type] = list[0]; if (events.removeListener) this.emit('removeListener', type, originalListener || listener); } return this; }; EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) { var listeners, events, i; events = this._events; if (!events) return this; // not listening for removeListener, no need to emit if (!events.removeListener) { if (arguments.length === 0) { this._events = objectCreate(null); this._eventsCount = 0; } else if (events[type]) { if (--this._eventsCount === 0) this._events = objectCreate(null); else delete events[type]; } return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { var keys = objectKeys(events); var key; for (i = 0; i < keys.length; ++i) { key = keys[i]; if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = objectCreate(null); this._eventsCount = 0; return this; } listeners = events[type]; if (typeof listeners === 'function') { this.removeListener(type, listeners); } else if (listeners) { // LIFO order for (i = listeners.length - 1; i >= 0; i--) { this.removeListener(type, listeners[i]); } } return this; }; function _listeners(target, type, unwrap) { var events = target._events; if (!events) return []; var evlistener = events[type]; if (!evlistener) return []; if (typeof evlistener === 'function') return unwrap ? [evlistener.listener || evlistener] : [evlistener]; return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); } EventEmitter.prototype.listeners = function listeners(type) { return _listeners(this, type, true); }; EventEmitter.prototype.rawListeners = function rawListeners(type) { return _listeners(this, type, false); }; EventEmitter.listenerCount = function(emitter, type) { if (typeof emitter.listenerCount === 'function') { return emitter.listenerCount(type); } else { return listenerCount.call(emitter, type); } }; EventEmitter.prototype.listenerCount = listenerCount; function listenerCount(type) { var events = this._events; if (events) { var evlistener = events[type]; if (typeof evlistener === 'function') { return 1; } else if (evlistener) { return evlistener.length; } } return 0; } EventEmitter.prototype.eventNames = function eventNames() { return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; }; // About 1.5x faster than the two-arg version of Array#splice(). function spliceOne(list, index) { for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) list[i] = list[k]; list.pop(); } function arrayClone(arr, n) { var copy = new Array(n); for (var i = 0; i < n; ++i) copy[i] = arr[i]; return copy; } function unwrapListeners(arr) { var ret = new Array(arr.length); for (var i = 0; i < ret.length; ++i) { ret[i] = arr[i].listener || arr[i]; } return ret; } function objectCreatePolyfill(proto) { var F = function() {}; F.prototype = proto; return new F; } function objectKeysPolyfill(obj) { var keys = []; for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) { keys.push(k); } return k; } function functionBindPolyfill(context) { var fn = this; return function () { return fn.apply(context, arguments); }; } },{}],200:[function(require,module,exports){ module.exports={ "builtin": { "Array": false, "ArrayBuffer": false, "Atomics": false, "BigInt": false, "BigInt64Array": false, "BigUint64Array": false, "Boolean": false, "constructor": false, "DataView": false, "Date": false, "decodeURI": false, "decodeURIComponent": false, "encodeURI": false, "encodeURIComponent": false, "Error": false, "escape": false, "eval": false, "EvalError": false, "Float32Array": false, "Float64Array": false, "Function": false, "globalThis": false, "hasOwnProperty": false, "Infinity": false, "Int16Array": false, "Int32Array": false, "Int8Array": false, "isFinite": false, "isNaN": false, "isPrototypeOf": false, "JSON": false, "Map": false, "Math": false, "NaN": false, "Number": false, "Object": false, "parseFloat": false, "parseInt": false, "Promise": false, "propertyIsEnumerable": false, "Proxy": false, "RangeError": false, "ReferenceError": false, "Reflect": false, "RegExp": false, "Set": false, "SharedArrayBuffer": false, "String": false, "Symbol": false, "SyntaxError": false, "toLocaleString": false, "toString": false, "TypeError": false, "Uint16Array": false, "Uint32Array": false, "Uint8Array": false, "Uint8ClampedArray": false, "undefined": false, "unescape": false, "URIError": false, "valueOf": false, "WeakMap": false, "WeakSet": false }, "es5": { "Array": false, "Boolean": false, "constructor": false, "Date": false, "decodeURI": false, "decodeURIComponent": false, "encodeURI": false, "encodeURIComponent": false, "Error": false, "escape": false, "eval": false, "EvalError": false, "Function": false, "hasOwnProperty": false, "Infinity": false, "isFinite": false, "isNaN": false, "isPrototypeOf": false, "JSON": false, "Math": false, "NaN": false, "Number": false, "Object": false, "parseFloat": false, "parseInt": false, "propertyIsEnumerable": false, "RangeError": false, "ReferenceError": false, "RegExp": false, "String": false, "SyntaxError": false, "toLocaleString": false, "toString": false, "TypeError": false, "undefined": false, "unescape": false, "URIError": false, "valueOf": false }, "es2015": { "Array": false, "ArrayBuffer": false, "Boolean": false, "constructor": false, "DataView": false, "Date": false, "decodeURI": false, "decodeURIComponent": false, "encodeURI": false, "encodeURIComponent": false, "Error": false, "escape": false, "eval": false, "EvalError": false, "Float32Array": false, "Float64Array": false, "Function": false, "hasOwnProperty": false, "Infinity": false, "Int16Array": false, "Int32Array": false, "Int8Array": false, "isFinite": false, "isNaN": false, "isPrototypeOf": false, "JSON": false, "Map": false, "Math": false, "NaN": false, "Number": false, "Object": false, "parseFloat": false, "parseInt": false, "Promise": false, "propertyIsEnumerable": false, "Proxy": false, "RangeError": false, "ReferenceError": false, "Reflect": false, "RegExp": false, "Set": false, "String": false, "Symbol": false, "SyntaxError": false, "toLocaleString": false, "toString": false, "TypeError": false, "Uint16Array": false, "Uint32Array": false, "Uint8Array": false, "Uint8ClampedArray": false, "undefined": false, "unescape": false, "URIError": false, "valueOf": false, "WeakMap": false, "WeakSet": false }, "es2017": { "Array": false, "ArrayBuffer": false, "Atomics": false, "Boolean": false, "constructor": false, "DataView": false, "Date": false, "decodeURI": false, "decodeURIComponent": false, "encodeURI": false, "encodeURIComponent": false, "Error": false, "escape": false, "eval": false, "EvalError": false, "Float32Array": false, "Float64Array": false, "Function": false, "hasOwnProperty": false, "Infinity": false, "Int16Array": false, "Int32Array": false, "Int8Array": false, "isFinite": false, "isNaN": false, "isPrototypeOf": false, "JSON": false, "Map": false, "Math": false, "NaN": false, "Number": false, "Object": false, "parseFloat": false, "parseInt": false, "Promise": false, "propertyIsEnumerable": false, "Proxy": false, "RangeError": false, "ReferenceError": false, "Reflect": false, "RegExp": false, "Set": false, "SharedArrayBuffer": false, "String": false, "Symbol": false, "SyntaxError": false, "toLocaleString": false, "toString": false, "TypeError": false, "Uint16Array": false, "Uint32Array": false, "Uint8Array": false, "Uint8ClampedArray": false, "undefined": false, "unescape": false, "URIError": false, "valueOf": false, "WeakMap": false, "WeakSet": false }, "browser": { "AbortController": false, "AbortSignal": false, "addEventListener": false, "alert": false, "AnalyserNode": false, "Animation": false, "AnimationEffectReadOnly": false, "AnimationEffectTiming": false, "AnimationEffectTimingReadOnly": false, "AnimationEvent": false, "AnimationPlaybackEvent": false, "AnimationTimeline": false, "applicationCache": false, "ApplicationCache": false, "ApplicationCacheErrorEvent": false, "atob": false, "Attr": false, "Audio": false, "AudioBuffer": false, "AudioBufferSourceNode": false, "AudioContext": false, "AudioDestinationNode": false, "AudioListener": false, "AudioNode": false, "AudioParam": false, "AudioProcessingEvent": false, "AudioScheduledSourceNode": false, "AudioWorkletGlobalScope ": false, "AudioWorkletNode": false, "AudioWorkletProcessor": false, "BarProp": false, "BaseAudioContext": false, "BatteryManager": false, "BeforeUnloadEvent": false, "BiquadFilterNode": false, "Blob": false, "BlobEvent": false, "blur": false, "BroadcastChannel": false, "btoa": false, "BudgetService": false, "ByteLengthQueuingStrategy": false, "Cache": false, "caches": false, "CacheStorage": false, "cancelAnimationFrame": false, "cancelIdleCallback": false, "CanvasCaptureMediaStreamTrack": false, "CanvasGradient": false, "CanvasPattern": false, "CanvasRenderingContext2D": false, "ChannelMergerNode": false, "ChannelSplitterNode": false, "CharacterData": false, "clearInterval": false, "clearTimeout": false, "clientInformation": false, "ClipboardEvent": false, "close": false, "closed": false, "CloseEvent": false, "Comment": false, "CompositionEvent": false, "confirm": false, "console": false, "ConstantSourceNode": false, "ConvolverNode": false, "CountQueuingStrategy": false, "createImageBitmap": false, "Credential": false, "CredentialsContainer": false, "crypto": false, "Crypto": false, "CryptoKey": false, "CSS": false, "CSSConditionRule": false, "CSSFontFaceRule": false, "CSSGroupingRule": false, "CSSImportRule": false, "CSSKeyframeRule": false, "CSSKeyframesRule": false, "CSSMediaRule": false, "CSSNamespaceRule": false, "CSSPageRule": false, "CSSRule": false, "CSSRuleList": false, "CSSStyleDeclaration": false, "CSSStyleRule": false, "CSSStyleSheet": false, "CSSSupportsRule": false, "CustomElementRegistry": false, "customElements": false, "CustomEvent": false, "DataTransfer": false, "DataTransferItem": false, "DataTransferItemList": false, "defaultstatus": false, "defaultStatus": false, "DelayNode": false, "DeviceMotionEvent": false, "DeviceOrientationEvent": false, "devicePixelRatio": false, "dispatchEvent": false, "document": false, "Document": false, "DocumentFragment": false, "DocumentType": false, "DOMError": false, "DOMException": false, "DOMImplementation": false, "DOMMatrix": false, "DOMMatrixReadOnly": false, "DOMParser": false, "DOMPoint": false, "DOMPointReadOnly": false, "DOMQuad": false, "DOMRect": false, "DOMRectReadOnly": false, "DOMStringList": false, "DOMStringMap": false, "DOMTokenList": false, "DragEvent": false, "DynamicsCompressorNode": false, "Element": false, "ErrorEvent": false, "event": false, "Event": false, "EventSource": false, "EventTarget": false, "external": false, "fetch": false, "File": false, "FileList": false, "FileReader": false, "find": false, "focus": false, "FocusEvent": false, "FontFace": false, "FontFaceSetLoadEvent": false, "FormData": false, "frameElement": false, "frames": false, "GainNode": false, "Gamepad": false, "GamepadButton": false, "GamepadEvent": false, "getComputedStyle": false, "getSelection": false, "HashChangeEvent": false, "Headers": false, "history": false, "History": false, "HTMLAllCollection": false, "HTMLAnchorElement": false, "HTMLAreaElement": false, "HTMLAudioElement": false, "HTMLBaseElement": false, "HTMLBodyElement": false, "HTMLBRElement": false, "HTMLButtonElement": false, "HTMLCanvasElement": false, "HTMLCollection": false, "HTMLContentElement": false, "HTMLDataElement": false, "HTMLDataListElement": false, "HTMLDetailsElement": false, "HTMLDialogElement": false, "HTMLDirectoryElement": false, "HTMLDivElement": false, "HTMLDListElement": false, "HTMLDocument": false, "HTMLElement": false, "HTMLEmbedElement": false, "HTMLFieldSetElement": false, "HTMLFontElement": false, "HTMLFormControlsCollection": false, "HTMLFormElement": false, "HTMLFrameElement": false, "HTMLFrameSetElement": false, "HTMLHeadElement": false, "HTMLHeadingElement": false, "HTMLHRElement": false, "HTMLHtmlElement": false, "HTMLIFrameElement": false, "HTMLImageElement": false, "HTMLInputElement": false, "HTMLLabelElement": false, "HTMLLegendElement": false, "HTMLLIElement": false, "HTMLLinkElement": false, "HTMLMapElement": false, "HTMLMarqueeElement": false, "HTMLMediaElement": false, "HTMLMenuElement": false, "HTMLMetaElement": false, "HTMLMeterElement": false, "HTMLModElement": false, "HTMLObjectElement": false, "HTMLOListElement": false, "HTMLOptGroupElement": false, "HTMLOptionElement": false, "HTMLOptionsCollection": false, "HTMLOutputElement": false, "HTMLParagraphElement": false, "HTMLParamElement": false, "HTMLPictureElement": false, "HTMLPreElement": false, "HTMLProgressElement": false, "HTMLQuoteElement": false, "HTMLScriptElement": false, "HTMLSelectElement": false, "HTMLShadowElement": false, "HTMLSlotElement": false, "HTMLSourceElement": false, "HTMLSpanElement": false, "HTMLStyleElement": false, "HTMLTableCaptionElement": false, "HTMLTableCellElement": false, "HTMLTableColElement": false, "HTMLTableElement": false, "HTMLTableRowElement": false, "HTMLTableSectionElement": false, "HTMLTemplateElement": false, "HTMLTextAreaElement": false, "HTMLTimeElement": false, "HTMLTitleElement": false, "HTMLTrackElement": false, "HTMLUListElement": false, "HTMLUnknownElement": false, "HTMLVideoElement": false, "IDBCursor": false, "IDBCursorWithValue": false, "IDBDatabase": false, "IDBFactory": false, "IDBIndex": false, "IDBKeyRange": false, "IDBObjectStore": false, "IDBOpenDBRequest": false, "IDBRequest": false, "IDBTransaction": false, "IDBVersionChangeEvent": false, "IdleDeadline": false, "IIRFilterNode": false, "Image": false, "ImageBitmap": false, "ImageBitmapRenderingContext": false, "ImageCapture": false, "ImageData": false, "indexedDB": false, "innerHeight": false, "innerWidth": false, "InputEvent": false, "IntersectionObserver": false, "IntersectionObserverEntry": false, "Intl": false, "isSecureContext": false, "KeyboardEvent": false, "KeyframeEffect": false, "KeyframeEffectReadOnly": false, "length": false, "localStorage": false, "location": true, "Location": false, "locationbar": false, "matchMedia": false, "MediaDeviceInfo": false, "MediaDevices": false, "MediaElementAudioSourceNode": false, "MediaEncryptedEvent": false, "MediaError": false, "MediaKeyMessageEvent": false, "MediaKeySession": false, "MediaKeyStatusMap": false, "MediaKeySystemAccess": false, "MediaList": false, "MediaQueryList": false, "MediaQueryListEvent": false, "MediaRecorder": false, "MediaSettingsRange": false, "MediaSource": false, "MediaStream": false, "MediaStreamAudioDestinationNode": false, "MediaStreamAudioSourceNode": false, "MediaStreamEvent": false, "MediaStreamTrack": false, "MediaStreamTrackEvent": false, "menubar": false, "MessageChannel": false, "MessageEvent": false, "MessagePort": false, "MIDIAccess": false, "MIDIConnectionEvent": false, "MIDIInput": false, "MIDIInputMap": false, "MIDIMessageEvent": false, "MIDIOutput": false, "MIDIOutputMap": false, "MIDIPort": false, "MimeType": false, "MimeTypeArray": false, "MouseEvent": false, "moveBy": false, "moveTo": false, "MutationEvent": false, "MutationObserver": false, "MutationRecord": false, "name": false, "NamedNodeMap": false, "NavigationPreloadManager": false, "navigator": false, "Navigator": false, "NetworkInformation": false, "Node": false, "NodeFilter": false, "NodeIterator": false, "NodeList": false, "Notification": false, "OfflineAudioCompletionEvent": false, "OfflineAudioContext": false, "offscreenBuffering": false, "OffscreenCanvas": true, "onabort": true, "onafterprint": true, "onanimationend": true, "onanimationiteration": true, "onanimationstart": true, "onappinstalled": true, "onauxclick": true, "onbeforeinstallprompt": true, "onbeforeprint": true, "onbeforeunload": true, "onblur": true, "oncancel": true, "oncanplay": true, "oncanplaythrough": true, "onchange": true, "onclick": true, "onclose": true, "oncontextmenu": true, "oncuechange": true, "ondblclick": true, "ondevicemotion": true, "ondeviceorientation": true, "ondeviceorientationabsolute": true, "ondrag": true, "ondragend": true, "ondragenter": true, "ondragleave": true, "ondragover": true, "ondragstart": true, "ondrop": true, "ondurationchange": true, "onemptied": true, "onended": true, "onerror": true, "onfocus": true, "ongotpointercapture": true, "onhashchange": true, "oninput": true, "oninvalid": true, "onkeydown": true, "onkeypress": true, "onkeyup": true, "onlanguagechange": true, "onload": true, "onloadeddata": true, "onloadedmetadata": true, "onloadstart": true, "onlostpointercapture": true, "onmessage": true, "onmessageerror": true, "onmousedown": true, "onmouseenter": true, "onmouseleave": true, "onmousemove": true, "onmouseout": true, "onmouseover": true, "onmouseup": true, "onmousewheel": true, "onoffline": true, "ononline": true, "onpagehide": true, "onpageshow": true, "onpause": true, "onplay": true, "onplaying": true, "onpointercancel": true, "onpointerdown": true, "onpointerenter": true, "onpointerleave": true, "onpointermove": true, "onpointerout": true, "onpointerover": true, "onpointerup": true, "onpopstate": true, "onprogress": true, "onratechange": true, "onrejectionhandled": true, "onreset": true, "onresize": true, "onscroll": true, "onsearch": true, "onseeked": true, "onseeking": true, "onselect": true, "onstalled": true, "onstorage": true, "onsubmit": true, "onsuspend": true, "ontimeupdate": true, "ontoggle": true, "ontransitionend": true, "onunhandledrejection": true, "onunload": true, "onvolumechange": true, "onwaiting": true, "onwheel": true, "open": false, "openDatabase": false, "opener": false, "Option": false, "origin": false, "OscillatorNode": false, "outerHeight": false, "outerWidth": false, "PageTransitionEvent": false, "pageXOffset": false, "pageYOffset": false, "PannerNode": false, "parent": false, "Path2D": false, "PaymentAddress": false, "PaymentRequest": false, "PaymentRequestUpdateEvent": false, "PaymentResponse": false, "performance": false, "Performance": false, "PerformanceEntry": false, "PerformanceLongTaskTiming": false, "PerformanceMark": false, "PerformanceMeasure": false, "PerformanceNavigation": false, "PerformanceNavigationTiming": false, "PerformanceObserver": false, "PerformanceObserverEntryList": false, "PerformancePaintTiming": false, "PerformanceResourceTiming": false, "PerformanceTiming": false, "PeriodicWave": false, "Permissions": false, "PermissionStatus": false, "personalbar": false, "PhotoCapabilities": false, "Plugin": false, "PluginArray": false, "PointerEvent": false, "PopStateEvent": false, "postMessage": false, "Presentation": false, "PresentationAvailability": false, "PresentationConnection": false, "PresentationConnectionAvailableEvent": false, "PresentationConnectionCloseEvent": false, "PresentationConnectionList": false, "PresentationReceiver": false, "PresentationRequest": false, "print": false, "ProcessingInstruction": false, "ProgressEvent": false, "PromiseRejectionEvent": false, "prompt": false, "PushManager": false, "PushSubscription": false, "PushSubscriptionOptions": false, "queueMicrotask": false, "RadioNodeList": false, "Range": false, "ReadableStream": false, "registerProcessor": false, "RemotePlayback": false, "removeEventListener": false, "Request": false, "requestAnimationFrame": false, "requestIdleCallback": false, "resizeBy": false, "ResizeObserver": false, "ResizeObserverEntry": false, "resizeTo": false, "Response": false, "RTCCertificate": false, "RTCDataChannel": false, "RTCDataChannelEvent": false, "RTCDtlsTransport": false, "RTCIceCandidate": false, "RTCIceGatherer": false, "RTCIceTransport": false, "RTCPeerConnection": false, "RTCPeerConnectionIceEvent": false, "RTCRtpContributingSource": false, "RTCRtpReceiver": false, "RTCRtpSender": false, "RTCSctpTransport": false, "RTCSessionDescription": false, "RTCStatsReport": false, "RTCTrackEvent": false, "screen": false, "Screen": false, "screenLeft": false, "ScreenOrientation": false, "screenTop": false, "screenX": false, "screenY": false, "ScriptProcessorNode": false, "scroll": false, "scrollbars": false, "scrollBy": false, "scrollTo": false, "scrollX": false, "scrollY": false, "SecurityPolicyViolationEvent": false, "Selection": false, "self": false, "ServiceWorker": false, "ServiceWorkerContainer": false, "ServiceWorkerRegistration": false, "sessionStorage": false, "setInterval": false, "setTimeout": false, "ShadowRoot": false, "SharedWorker": false, "SourceBuffer": false, "SourceBufferList": false, "speechSynthesis": false, "SpeechSynthesisEvent": false, "SpeechSynthesisUtterance": false, "StaticRange": false, "status": false, "statusbar": false, "StereoPannerNode": false, "stop": false, "Storage": false, "StorageEvent": false, "StorageManager": false, "styleMedia": false, "StyleSheet": false, "StyleSheetList": false, "SubtleCrypto": false, "SVGAElement": false, "SVGAngle": false, "SVGAnimatedAngle": false, "SVGAnimatedBoolean": false, "SVGAnimatedEnumeration": false, "SVGAnimatedInteger": false, "SVGAnimatedLength": false, "SVGAnimatedLengthList": false, "SVGAnimatedNumber": false, "SVGAnimatedNumberList": false, "SVGAnimatedPreserveAspectRatio": false, "SVGAnimatedRect": false, "SVGAnimatedString": false, "SVGAnimatedTransformList": false, "SVGAnimateElement": false, "SVGAnimateMotionElement": false, "SVGAnimateTransformElement": false, "SVGAnimationElement": false, "SVGCircleElement": false, "SVGClipPathElement": false, "SVGComponentTransferFunctionElement": false, "SVGDefsElement": false, "SVGDescElement": false, "SVGDiscardElement": false, "SVGElement": false, "SVGEllipseElement": false, "SVGFEBlendElement": false, "SVGFEColorMatrixElement": false, "SVGFEComponentTransferElement": false, "SVGFECompositeElement": false, "SVGFEConvolveMatrixElement": false, "SVGFEDiffuseLightingElement": false, "SVGFEDisplacementMapElement": false, "SVGFEDistantLightElement": false, "SVGFEDropShadowElement": false, "SVGFEFloodElement": false, "SVGFEFuncAElement": false, "SVGFEFuncBElement": false, "SVGFEFuncGElement": false, "SVGFEFuncRElement": false, "SVGFEGaussianBlurElement": false, "SVGFEImageElement": false, "SVGFEMergeElement": false, "SVGFEMergeNodeElement": false, "SVGFEMorphologyElement": false, "SVGFEOffsetElement": false, "SVGFEPointLightElement": false, "SVGFESpecularLightingElement": false, "SVGFESpotLightElement": false, "SVGFETileElement": false, "SVGFETurbulenceElement": false, "SVGFilterElement": false, "SVGForeignObjectElement": false, "SVGGElement": false, "SVGGeometryElement": false, "SVGGradientElement": false, "SVGGraphicsElement": false, "SVGImageElement": false, "SVGLength": false, "SVGLengthList": false, "SVGLinearGradientElement": false, "SVGLineElement": false, "SVGMarkerElement": false, "SVGMaskElement": false, "SVGMatrix": false, "SVGMetadataElement": false, "SVGMPathElement": false, "SVGNumber": false, "SVGNumberList": false, "SVGPathElement": false, "SVGPatternElement": false, "SVGPoint": false, "SVGPointList": false, "SVGPolygonElement": false, "SVGPolylineElement": false, "SVGPreserveAspectRatio": false, "SVGRadialGradientElement": false, "SVGRect": false, "SVGRectElement": false, "SVGScriptElement": false, "SVGSetElement": false, "SVGStopElement": false, "SVGStringList": false, "SVGStyleElement": false, "SVGSVGElement": false, "SVGSwitchElement": false, "SVGSymbolElement": false, "SVGTextContentElement": false, "SVGTextElement": false, "SVGTextPathElement": false, "SVGTextPositioningElement": false, "SVGTitleElement": false, "SVGTransform": false, "SVGTransformList": false, "SVGTSpanElement": false, "SVGUnitTypes": false, "SVGUseElement": false, "SVGViewElement": false, "TaskAttributionTiming": false, "Text": false, "TextDecoder": false, "TextEncoder": false, "TextEvent": false, "TextMetrics": false, "TextTrack": false, "TextTrackCue": false, "TextTrackCueList": false, "TextTrackList": false, "TimeRanges": false, "toolbar": false, "top": false, "Touch": false, "TouchEvent": false, "TouchList": false, "TrackEvent": false, "TransitionEvent": false, "TreeWalker": false, "UIEvent": false, "URL": false, "URLSearchParams": false, "ValidityState": false, "visualViewport": false, "VisualViewport": false, "VTTCue": false, "WaveShaperNode": false, "WebAssembly": false, "WebGL2RenderingContext": false, "WebGLActiveInfo": false, "WebGLBuffer": false, "WebGLContextEvent": false, "WebGLFramebuffer": false, "WebGLProgram": false, "WebGLQuery": false, "WebGLRenderbuffer": false, "WebGLRenderingContext": false, "WebGLSampler": false, "WebGLShader": false, "WebGLShaderPrecisionFormat": false, "WebGLSync": false, "WebGLTexture": false, "WebGLTransformFeedback": false, "WebGLUniformLocation": false, "WebGLVertexArrayObject": false, "WebSocket": false, "WheelEvent": false, "window": false, "Window": false, "Worker": false, "WritableStream": false, "XMLDocument": false, "XMLHttpRequest": false, "XMLHttpRequestEventTarget": false, "XMLHttpRequestUpload": false, "XMLSerializer": false, "XPathEvaluator": false, "XPathExpression": false, "XPathResult": false, "XSLTProcessor": false }, "worker": { "addEventListener": false, "applicationCache": false, "atob": false, "Blob": false, "BroadcastChannel": false, "btoa": false, "Cache": false, "caches": false, "clearInterval": false, "clearTimeout": false, "close": true, "console": false, "fetch": false, "FileReaderSync": false, "FormData": false, "Headers": false, "IDBCursor": false, "IDBCursorWithValue": false, "IDBDatabase": false, "IDBFactory": false, "IDBIndex": false, "IDBKeyRange": false, "IDBObjectStore": false, "IDBOpenDBRequest": false, "IDBRequest": false, "IDBTransaction": false, "IDBVersionChangeEvent": false, "ImageData": false, "importScripts": true, "indexedDB": false, "location": false, "MessageChannel": false, "MessagePort": false, "name": false, "navigator": false, "Notification": false, "onclose": true, "onconnect": true, "onerror": true, "onlanguagechange": true, "onmessage": true, "onoffline": true, "ononline": true, "onrejectionhandled": true, "onunhandledrejection": true, "performance": false, "Performance": false, "PerformanceEntry": false, "PerformanceMark": false, "PerformanceMeasure": false, "PerformanceNavigation": false, "PerformanceResourceTiming": false, "PerformanceTiming": false, "postMessage": true, "Promise": false, "queueMicrotask": false, "removeEventListener": false, "Request": false, "Response": false, "self": true, "ServiceWorkerRegistration": false, "setInterval": false, "setTimeout": false, "TextDecoder": false, "TextEncoder": false, "URL": false, "URLSearchParams": false, "WebSocket": false, "Worker": false, "WorkerGlobalScope": false, "XMLHttpRequest": false }, "node": { "__dirname": false, "__filename": false, "Buffer": false, "clearImmediate": false, "clearInterval": false, "clearTimeout": false, "console": false, "exports": true, "global": false, "Intl": false, "module": false, "process": false, "queueMicrotask": false, "require": false, "setImmediate": false, "setInterval": false, "setTimeout": false, "TextDecoder": false, "TextEncoder": false, "URL": false, "URLSearchParams": false }, "commonjs": { "exports": true, "global": false, "module": false, "require": false }, "amd": { "define": false, "require": false }, "mocha": { "after": false, "afterEach": false, "before": false, "beforeEach": false, "context": false, "describe": false, "it": false, "mocha": false, "run": false, "setup": false, "specify": false, "suite": false, "suiteSetup": false, "suiteTeardown": false, "teardown": false, "test": false, "xcontext": false, "xdescribe": false, "xit": false, "xspecify": false }, "jasmine": { "afterAll": false, "afterEach": false, "beforeAll": false, "beforeEach": false, "describe": false, "expect": false, "fail": false, "fdescribe": false, "fit": false, "it": false, "jasmine": false, "pending": false, "runs": false, "spyOn": false, "spyOnProperty": false, "waits": false, "waitsFor": false, "xdescribe": false, "xit": false }, "jest": { "afterAll": false, "afterEach": false, "beforeAll": false, "beforeEach": false, "describe": false, "expect": false, "fdescribe": false, "fit": false, "it": false, "jest": false, "pit": false, "require": false, "test": false, "xdescribe": false, "xit": false, "xtest": false }, "qunit": { "asyncTest": false, "deepEqual": false, "equal": false, "expect": false, "module": false, "notDeepEqual": false, "notEqual": false, "notOk": false, "notPropEqual": false, "notStrictEqual": false, "ok": false, "propEqual": false, "QUnit": false, "raises": false, "start": false, "stop": false, "strictEqual": false, "test": false, "throws": false }, "phantomjs": { "console": true, "exports": true, "phantom": true, "require": true, "WebPage": true }, "couch": { "emit": false, "exports": false, "getRow": false, "log": false, "module": false, "provides": false, "require": false, "respond": false, "send": false, "start": false, "sum": false }, "rhino": { "defineClass": false, "deserialize": false, "gc": false, "help": false, "importClass": false, "importPackage": false, "java": false, "load": false, "loadClass": false, "Packages": false, "print": false, "quit": false, "readFile": false, "readUrl": false, "runCommand": false, "seal": false, "serialize": false, "spawn": false, "sync": false, "toint32": false, "version": false }, "nashorn": { "__DIR__": false, "__FILE__": false, "__LINE__": false, "com": false, "edu": false, "exit": false, "java": false, "Java": false, "javafx": false, "JavaImporter": false, "javax": false, "JSAdapter": false, "load": false, "loadWithNewGlobal": false, "org": false, "Packages": false, "print": false, "quit": false }, "wsh": { "ActiveXObject": true, "Enumerator": true, "GetObject": true, "ScriptEngine": true, "ScriptEngineBuildVersion": true, "ScriptEngineMajorVersion": true, "ScriptEngineMinorVersion": true, "VBArray": true, "WScript": true, "WSH": true, "XDomainRequest": true }, "jquery": { "$": false, "jQuery": false }, "yui": { "YAHOO": false, "YAHOO_config": false, "YUI": false, "YUI_config": false }, "shelljs": { "cat": false, "cd": false, "chmod": false, "config": false, "cp": false, "dirs": false, "echo": false, "env": false, "error": false, "exec": false, "exit": false, "find": false, "grep": false, "ln": false, "ls": false, "mkdir": false, "mv": false, "popd": false, "pushd": false, "pwd": false, "rm": false, "sed": false, "set": false, "target": false, "tempdir": false, "test": false, "touch": false, "which": false }, "prototypejs": { "$": false, "$$": false, "$A": false, "$break": false, "$continue": false, "$F": false, "$H": false, "$R": false, "$w": false, "Abstract": false, "Ajax": false, "Autocompleter": false, "Builder": false, "Class": false, "Control": false, "Draggable": false, "Draggables": false, "Droppables": false, "Effect": false, "Element": false, "Enumerable": false, "Event": false, "Field": false, "Form": false, "Hash": false, "Insertion": false, "ObjectRange": false, "PeriodicalExecuter": false, "Position": false, "Prototype": false, "Scriptaculous": false, "Selector": false, "Sortable": false, "SortableObserver": false, "Sound": false, "Template": false, "Toggle": false, "Try": false }, "meteor": { "_": false, "$": false, "Accounts": false, "AccountsClient": false, "AccountsCommon": false, "AccountsServer": false, "App": false, "Assets": false, "Blaze": false, "check": false, "Cordova": false, "DDP": false, "DDPRateLimiter": false, "DDPServer": false, "Deps": false, "EJSON": false, "Email": false, "HTTP": false, "Log": false, "Match": false, "Meteor": false, "Mongo": false, "MongoInternals": false, "Npm": false, "Package": false, "Plugin": false, "process": false, "Random": false, "ReactiveDict": false, "ReactiveVar": false, "Router": false, "ServiceConfiguration": false, "Session": false, "share": false, "Spacebars": false, "Template": false, "Tinytest": false, "Tracker": false, "UI": false, "Utils": false, "WebApp": false, "WebAppInternals": false }, "mongo": { "_isWindows": false, "_rand": false, "BulkWriteResult": false, "cat": false, "cd": false, "connect": false, "db": false, "getHostName": false, "getMemInfo": false, "hostname": false, "ISODate": false, "listFiles": false, "load": false, "ls": false, "md5sumFile": false, "mkdir": false, "Mongo": false, "NumberInt": false, "NumberLong": false, "ObjectId": false, "PlanCache": false, "print": false, "printjson": false, "pwd": false, "quit": false, "removeFile": false, "rs": false, "sh": false, "UUID": false, "version": false, "WriteResult": false }, "applescript": { "$": false, "Application": false, "Automation": false, "console": false, "delay": false, "Library": false, "ObjC": false, "ObjectSpecifier": false, "Path": false, "Progress": false, "Ref": false }, "serviceworker": { "addEventListener": false, "applicationCache": false, "atob": false, "Blob": false, "BroadcastChannel": false, "btoa": false, "Cache": false, "caches": false, "CacheStorage": false, "clearInterval": false, "clearTimeout": false, "Client": false, "clients": false, "Clients": false, "close": true, "console": false, "ExtendableEvent": false, "ExtendableMessageEvent": false, "fetch": false, "FetchEvent": false, "FileReaderSync": false, "FormData": false, "Headers": false, "IDBCursor": false, "IDBCursorWithValue": false, "IDBDatabase": false, "IDBFactory": false, "IDBIndex": false, "IDBKeyRange": false, "IDBObjectStore": false, "IDBOpenDBRequest": false, "IDBRequest": false, "IDBTransaction": false, "IDBVersionChangeEvent": false, "ImageData": false, "importScripts": false, "indexedDB": false, "location": false, "MessageChannel": false, "MessagePort": false, "name": false, "navigator": false, "Notification": false, "onclose": true, "onconnect": true, "onerror": true, "onfetch": true, "oninstall": true, "onlanguagechange": true, "onmessage": true, "onmessageerror": true, "onnotificationclick": true, "onnotificationclose": true, "onoffline": true, "ononline": true, "onpush": true, "onpushsubscriptionchange": true, "onrejectionhandled": true, "onsync": true, "onunhandledrejection": true, "performance": false, "Performance": false, "PerformanceEntry": false, "PerformanceMark": false, "PerformanceMeasure": false, "PerformanceNavigation": false, "PerformanceResourceTiming": false, "PerformanceTiming": false, "postMessage": true, "Promise": false, "queueMicrotask": false, "registration": false, "removeEventListener": false, "Request": false, "Response": false, "self": false, "ServiceWorker": false, "ServiceWorkerContainer": false, "ServiceWorkerGlobalScope": false, "ServiceWorkerMessageEvent": false, "ServiceWorkerRegistration": false, "setInterval": false, "setTimeout": false, "skipWaiting": false, "TextDecoder": false, "TextEncoder": false, "URL": false, "URLSearchParams": false, "WebSocket": false, "WindowClient": false, "Worker": false, "WorkerGlobalScope": false, "XMLHttpRequest": false }, "atomtest": { "advanceClock": false, "fakeClearInterval": false, "fakeClearTimeout": false, "fakeSetInterval": false, "fakeSetTimeout": false, "resetTimeouts": false, "waitsForPromise": false }, "embertest": { "andThen": false, "click": false, "currentPath": false, "currentRouteName": false, "currentURL": false, "fillIn": false, "find": false, "findAll": false, "findWithAssert": false, "keyEvent": false, "pauseTest": false, "resumeTest": false, "triggerEvent": false, "visit": false, "wait": false }, "protractor": { "$": false, "$$": false, "browser": false, "by": false, "By": false, "DartObject": false, "element": false, "protractor": false }, "shared-node-browser": { "clearInterval": false, "clearTimeout": false, "console": false, "setInterval": false, "setTimeout": false, "URL": false, "URLSearchParams": false }, "webextensions": { "browser": false, "chrome": false, "opr": false }, "greasemonkey": { "cloneInto": false, "createObjectIn": false, "exportFunction": false, "GM": false, "GM_addStyle": false, "GM_deleteValue": false, "GM_getResourceText": false, "GM_getResourceURL": false, "GM_getValue": false, "GM_info": false, "GM_listValues": false, "GM_log": false, "GM_openInTab": false, "GM_registerMenuCommand": false, "GM_setClipboard": false, "GM_setValue": false, "GM_xmlhttpRequest": false, "unsafeWindow": false }, "devtools": { "$": false, "$_": false, "$$": false, "$0": false, "$1": false, "$2": false, "$3": false, "$4": false, "$x": false, "chrome": false, "clear": false, "copy": false, "debug": false, "dir": false, "dirxml": false, "getEventListeners": false, "inspect": false, "keys": false, "monitor": false, "monitorEvents": false, "profile": false, "profileEnd": false, "queryObjects": false, "table": false, "undebug": false, "unmonitor": false, "unmonitorEvents": false, "values": false } } },{}],201:[function(require,module,exports){ 'use strict'; module.exports = require('./globals.json'); },{"./globals.json":200}],202:[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 } },{}],203:[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 } } } },{}],204:[function(require,module,exports){ /*! * Determine if an object is a Buffer * * @author Feross Aboukhadijeh * @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)) } },{}],205:[function(require,module,exports){ var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; },{}],206:[function(require,module,exports){ // Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell // License: MIT. (See LICENSE.) Object.defineProperty(exports, "__esModule", { value: true }) // This regex comes from regex.coffee, and is inserted here by generate-index.js // (run `npm run build`). exports.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyus]{1,6}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g exports.matchToToken = function(match) { var token = {type: "invalid", value: match[0], closed: undefined} if (match[ 1]) token.type = "string" , token.closed = !!(match[3] || match[4]) else if (match[ 5]) token.type = "comment" else if (match[ 6]) token.type = "comment", token.closed = !!match[7] else if (match[ 8]) token.type = "regex" else if (match[ 9]) token.type = "number" else if (match[10]) token.type = "name" else if (match[11]) token.type = "punctuator" else if (match[12]) token.type = "whitespace" return token } },{}],207:[function(require,module,exports){ (function (Buffer){ 'use strict'; const object = {}; const hasOwnProperty = object.hasOwnProperty; const forOwn = (object, callback) => { for (const key in object) { if (hasOwnProperty.call(object, key)) { callback(key, object[key]); } } }; const extend = (destination, source) => { if (!source) { return destination; } forOwn(source, (key, value) => { destination[key] = value; }); return destination; }; const forEach = (array, callback) => { const length = array.length; let index = -1; while (++index < length) { callback(array[index]); } }; const toString = object.toString; const isArray = Array.isArray; const isBuffer = Buffer.isBuffer; const isObject = (value) => { // This is a very simple check, but it’s good enough for what we need. return toString.call(value) == '[object Object]'; }; const isString = (value) => { return typeof value == 'string' || toString.call(value) == '[object String]'; }; const isNumber = (value) => { return typeof value == 'number' || toString.call(value) == '[object Number]'; }; const isFunction = (value) => { return typeof value == 'function'; }; const isMap = (value) => { return toString.call(value) == '[object Map]'; }; const isSet = (value) => { return toString.call(value) == '[object Set]'; }; /*--------------------------------------------------------------------------*/ // https://mathiasbynens.be/notes/javascript-escapes#single const singleEscapes = { '"': '\\"', '\'': '\\\'', '\\': '\\\\', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t' // `\v` is omitted intentionally, because in IE < 9, '\v' == 'v'. // '\v': '\\x0B' }; const regexSingleEscape = /["'\\\b\f\n\r\t]/; const regexDigit = /[0-9]/; const regexWhitelist = /[ !#-&\(-\[\]-_a-~]/; const jsesc = (argument, options) => { const increaseIndentation = () => { oldIndent = indent; ++options.indentLevel; indent = options.indent.repeat(options.indentLevel) }; // Handle options const defaults = { 'escapeEverything': false, 'minimal': false, 'isScriptContext': false, 'quotes': 'single', 'wrap': false, 'es6': false, 'json': false, 'compact': true, 'lowercaseHex': false, 'numbers': 'decimal', 'indent': '\t', 'indentLevel': 0, '__inline1__': false, '__inline2__': false }; const json = options && options.json; if (json) { defaults.quotes = 'double'; defaults.wrap = true; } options = extend(defaults, options); if ( options.quotes != 'single' && options.quotes != 'double' && options.quotes != 'backtick' ) { options.quotes = 'single'; } const quote = options.quotes == 'double' ? '"' : (options.quotes == 'backtick' ? '`' : '\'' ); const compact = options.compact; const lowercaseHex = options.lowercaseHex; let indent = options.indent.repeat(options.indentLevel); let oldIndent = ''; const inline1 = options.__inline1__; const inline2 = options.__inline2__; const newLine = compact ? '' : '\n'; let result; let isEmpty = true; const useBinNumbers = options.numbers == 'binary'; const useOctNumbers = options.numbers == 'octal'; const useDecNumbers = options.numbers == 'decimal'; const useHexNumbers = options.numbers == 'hexadecimal'; if (json && argument && isFunction(argument.toJSON)) { argument = argument.toJSON(); } if (!isString(argument)) { if (isMap(argument)) { if (argument.size == 0) { return 'new Map()'; } if (!compact) { options.__inline1__ = true; options.__inline2__ = false; } return 'new Map(' + jsesc(Array.from(argument), options) + ')'; } if (isSet(argument)) { if (argument.size == 0) { return 'new Set()'; } return 'new Set(' + jsesc(Array.from(argument), options) + ')'; } if (isBuffer(argument)) { if (argument.length == 0) { return 'Buffer.from([])'; } return 'Buffer.from(' + jsesc(Array.from(argument), options) + ')'; } if (isArray(argument)) { result = []; options.wrap = true; if (inline1) { options.__inline1__ = false; options.__inline2__ = true; } if (!inline2) { increaseIndentation(); } forEach(argument, (value) => { isEmpty = false; if (inline2) { options.__inline2__ = false; } result.push( (compact || inline2 ? '' : indent) + jsesc(value, options) ); }); if (isEmpty) { return '[]'; } if (inline2) { return '[' + result.join(', ') + ']'; } return '[' + newLine + result.join(',' + newLine) + newLine + (compact ? '' : oldIndent) + ']'; } else if (isNumber(argument)) { if (json) { // Some number values (e.g. `Infinity`) cannot be represented in JSON. return JSON.stringify(argument); } if (useDecNumbers) { return String(argument); } if (useHexNumbers) { let hexadecimal = argument.toString(16); if (!lowercaseHex) { hexadecimal = hexadecimal.toUpperCase(); } return '0x' + hexadecimal; } if (useBinNumbers) { return '0b' + argument.toString(2); } if (useOctNumbers) { return '0o' + argument.toString(8); } } else if (!isObject(argument)) { if (json) { // For some values (e.g. `undefined`, `function` objects), // `JSON.stringify(value)` returns `undefined` (which isn’t valid // JSON) instead of `'null'`. return JSON.stringify(argument) || 'null'; } return String(argument); } else { // it’s an object result = []; options.wrap = true; increaseIndentation(); forOwn(argument, (key, value) => { isEmpty = false; result.push( (compact ? '' : indent) + jsesc(key, options) + ':' + (compact ? '' : ' ') + jsesc(value, options) ); }); if (isEmpty) { return '{}'; } return '{' + newLine + result.join(',' + newLine) + newLine + (compact ? '' : oldIndent) + '}'; } } const string = argument; // Loop over each code unit in the string and escape it let index = -1; const length = string.length; result = ''; while (++index < length) { const character = string.charAt(index); if (options.es6) { const first = string.charCodeAt(index); if ( // check if it’s the start of a surrogate pair first >= 0xD800 && first <= 0xDBFF && // high surrogate length > index + 1 // there is a next code unit ) { const second = string.charCodeAt(index + 1); if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae const codePoint = (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; let hexadecimal = codePoint.toString(16); if (!lowercaseHex) { hexadecimal = hexadecimal.toUpperCase(); } result += '\\u{' + hexadecimal + '}'; ++index; continue; } } } if (!options.escapeEverything) { if (regexWhitelist.test(character)) { // It’s a printable ASCII character that is not `"`, `'` or `\`, // so don’t escape it. result += character; continue; } if (character == '"') { result += quote == character ? '\\"' : character; continue; } if (character == '`') { result += quote == character ? '\\`' : character; continue; } if (character == '\'') { result += quote == character ? '\\\'' : character; continue; } } if ( character == '\0' && !json && !regexDigit.test(string.charAt(index + 1)) ) { result += '\\0'; continue; } if (regexSingleEscape.test(character)) { // no need for a `hasOwnProperty` check here result += singleEscapes[character]; continue; } const charCode = character.charCodeAt(0); if (options.minimal && charCode != 0x2028 && charCode != 0x2029) { result += character; continue; } let hexadecimal = charCode.toString(16); if (!lowercaseHex) { hexadecimal = hexadecimal.toUpperCase(); } const longhand = hexadecimal.length > 2 || json; const escaped = '\\' + (longhand ? 'u' : 'x') + ('0000' + hexadecimal).slice(longhand ? -4 : -2); result += escaped; continue; } if (options.wrap) { result = quote + result + quote; } if (quote == '`') { result = result.replace(/\$\{/g, '\\\$\{'); } if (options.isScriptContext) { // https://mathiasbynens.be/notes/etago return result .replace(/<\/(script|style)/gi, '<\\/$1') .replace(/' + escapeTextForBrowser(text); } this.previousWasTextNode = true; return escapeTextForBrowser(text); } else { var nextChild = void 0; var _resolve = resolve(child, context, this.threadID); nextChild = _resolve.child; context = _resolve.context; if (nextChild === null || nextChild === false) { return ''; } else if (!React.isValidElement(nextChild)) { if (nextChild != null && nextChild.$$typeof != null) { // Catch unexpected special types early. var $$typeof = nextChild.$$typeof; !($$typeof !== REACT_PORTAL_TYPE) ? invariant(false, 'Portals are not currently supported by the server renderer. Render them conditionally so that they only appear on the client render.') : void 0; // Catch-all to prevent an infinite loop if React.Children.toArray() supports some new type. invariant(false, 'Unknown element-like object type: %s. This is likely a bug in React. Please file an issue.', $$typeof.toString()); } var nextChildren = toArray(nextChild); var frame = { type: null, domNamespace: parentNamespace, children: nextChildren, childIndex: 0, context: context, footer: '' }; { frame.debugElementStack = []; } this.stack.push(frame); return ''; } // Safe because we just checked it's an element. var nextElement = nextChild; var elementType = nextElement.type; if (typeof elementType === 'string') { return this.renderDOM(nextElement, context, parentNamespace); } switch (elementType) { case REACT_STRICT_MODE_TYPE: case REACT_CONCURRENT_MODE_TYPE: case REACT_PROFILER_TYPE: case REACT_FRAGMENT_TYPE: { var _nextChildren = toArray(nextChild.props.children); var _frame = { type: null, domNamespace: parentNamespace, children: _nextChildren, childIndex: 0, context: context, footer: '' }; { _frame.debugElementStack = []; } this.stack.push(_frame); return ''; } case REACT_SUSPENSE_TYPE: { if (enableSuspenseServerRenderer) { var fallback = nextChild.props.fallback; if (fallback === undefined) { // If there is no fallback, then this just behaves as a fragment. var _nextChildren3 = toArray(nextChild.props.children); var _frame3 = { type: null, domNamespace: parentNamespace, children: _nextChildren3, childIndex: 0, context: context, footer: '' }; { _frame3.debugElementStack = []; } this.stack.push(_frame3); return ''; } var fallbackChildren = toArray(fallback); var _nextChildren2 = toArray(nextChild.props.children); var _fallbackFrame2 = { type: null, domNamespace: parentNamespace, children: fallbackChildren, childIndex: 0, context: context, footer: '', out: '' }; var _frame2 = { fallbackFrame: _fallbackFrame2, type: REACT_SUSPENSE_TYPE, domNamespace: parentNamespace, children: _nextChildren2, childIndex: 0, context: context, footer: '' }; { _frame2.debugElementStack = []; _fallbackFrame2.debugElementStack = []; } this.stack.push(_frame2); this.suspenseDepth++; return ''; } else { invariant(false, 'ReactDOMServer does not yet support Suspense.'); } } // eslint-disable-next-line-no-fallthrough default: break; } if (typeof elementType === 'object' && elementType !== null) { switch (elementType.$$typeof) { case REACT_FORWARD_REF_TYPE: { var element = nextChild; var _nextChildren4 = void 0; var componentIdentity = {}; prepareToUseHooks(componentIdentity); _nextChildren4 = elementType.render(element.props, element.ref); _nextChildren4 = finishHooks(elementType.render, element.props, _nextChildren4, element.ref); _nextChildren4 = toArray(_nextChildren4); var _frame4 = { type: null, domNamespace: parentNamespace, children: _nextChildren4, childIndex: 0, context: context, footer: '' }; { _frame4.debugElementStack = []; } this.stack.push(_frame4); return ''; } case REACT_MEMO_TYPE: { var _element = nextChild; var _nextChildren5 = [React.createElement(elementType.type, _assign({ ref: _element.ref }, _element.props))]; var _frame5 = { type: null, domNamespace: parentNamespace, children: _nextChildren5, childIndex: 0, context: context, footer: '' }; { _frame5.debugElementStack = []; } this.stack.push(_frame5); return ''; } case REACT_PROVIDER_TYPE: { var provider = nextChild; var nextProps = provider.props; var _nextChildren6 = toArray(nextProps.children); var _frame6 = { type: provider, domNamespace: parentNamespace, children: _nextChildren6, childIndex: 0, context: context, footer: '' }; { _frame6.debugElementStack = []; } this.pushProvider(provider); this.stack.push(_frame6); return ''; } case REACT_CONTEXT_TYPE: { var reactContext = nextChild.type; // The logic below for Context differs depending on PROD or DEV mode. In // DEV mode, we create a separate object for Context.Consumer that acts // like a proxy to Context. This proxy object adds unnecessary code in PROD // so we use the old behaviour (Context.Consumer references Context) to // reduce size and overhead. The separate object references context via // a property called "_context", which also gives us the ability to check // in DEV mode if this property exists or not and warn if it does not. { if (reactContext._context === undefined) { // This may be because it's a Context (rather than a Consumer). // Or it may be because it's older React where they're the same thing. // We only want to warn if we're sure it's a new React. if (reactContext !== reactContext.Consumer) { if (!hasWarnedAboutUsingContextAsConsumer) { hasWarnedAboutUsingContextAsConsumer = true; warning$1(false, 'Rendering directly is not supported and will be removed in ' + 'a future major release. Did you mean to render instead?'); } } } else { reactContext = reactContext._context; } } var _nextProps = nextChild.props; var threadID = this.threadID; validateContextBounds(reactContext, threadID); var nextValue = reactContext[threadID]; var _nextChildren7 = toArray(_nextProps.children(nextValue)); var _frame7 = { type: nextChild, domNamespace: parentNamespace, children: _nextChildren7, childIndex: 0, context: context, footer: '' }; { _frame7.debugElementStack = []; } this.stack.push(_frame7); return ''; } case REACT_LAZY_TYPE: invariant(false, 'ReactDOMServer does not yet support lazy-loaded components.'); } } var info = ''; { var owner = nextElement._owner; if (elementType === undefined || typeof elementType === 'object' && elementType !== null && Object.keys(elementType).length === 0) { info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.'; } var ownerName = owner ? getComponentName(owner) : null; if (ownerName) { info += '\n\nCheck the render method of `' + ownerName + '`.'; } } invariant(false, 'Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s', elementType == null ? elementType : typeof elementType, info); } }; ReactDOMServerRenderer.prototype.renderDOM = function renderDOM(element, context, parentNamespace) { var tag = element.type.toLowerCase(); var namespace = parentNamespace; if (parentNamespace === Namespaces.html) { namespace = getIntrinsicNamespace(tag); } { if (namespace === Namespaces.html) { // Should this check be gated by parent namespace? Not sure we want to // allow or . !(tag === element.type) ? warning$1(false, '<%s /> is using incorrect casing. ' + 'Use PascalCase for React components, ' + 'or lowercase for HTML elements.', element.type) : void 0; } } validateDangerousTag(tag); var props = element.props; if (tag === 'input') { { ReactControlledValuePropTypes.checkPropTypes('input', props); if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnDefaultChecked) { warning$1(false, '%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', 'A component', props.type); didWarnDefaultChecked = true; } if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultInputValue) { warning$1(false, '%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', 'A component', props.type); didWarnDefaultInputValue = true; } } props = _assign({ type: undefined }, props, { defaultChecked: undefined, defaultValue: undefined, value: props.value != null ? props.value : props.defaultValue, checked: props.checked != null ? props.checked : props.defaultChecked }); } else if (tag === 'textarea') { { ReactControlledValuePropTypes.checkPropTypes('textarea', props); if (props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultTextareaValue) { warning$1(false, 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components'); didWarnDefaultTextareaValue = true; } } var initialValue = props.value; if (initialValue == null) { var defaultValue = props.defaultValue; // TODO (yungsters): Remove support for children content in oo" but that still // satisfies our requirement. Our requirement is not to produce perfect // HTML and attributes. Ideally we should preserve structure but it's // ok not to if the visible content is still enough to indicate what // even listeners these nodes might be wired up to. // TODO: Warn if there is more than a single textNode as a child. // TODO: Should we use domElement.firstChild.nodeValue to compare? if (typeof nextProp === 'string') { if (domElement.textContent !== nextProp) { if (true && !suppressHydrationWarning) { warnForTextDifference(domElement.textContent, nextProp); } updatePayload = [CHILDREN, nextProp]; } } else if (typeof nextProp === 'number') { if (domElement.textContent !== '' + nextProp) { if (true && !suppressHydrationWarning) { warnForTextDifference(domElement.textContent, nextProp); } updatePayload = [CHILDREN, '' + nextProp]; } } } else if (registrationNameModules.hasOwnProperty(propKey)) { if (nextProp != null) { if (true && typeof nextProp !== 'function') { warnForInvalidEventListener(propKey, nextProp); } ensureListeningTo(rootContainerElement, propKey); } } else if (true && // Convince Flow we've calculated it (it's DEV-only in this method.) typeof isCustomComponentTag === 'boolean') { // Validate that the properties correspond to their expected values. var serverValue = void 0; var propertyInfo = getPropertyInfo(propKey); if (suppressHydrationWarning) { // Don't bother comparing. We're ignoring all these warnings. } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING$1 || // Controlled attributes are not validated // TODO: Only ignore them on controlled tags. propKey === 'value' || propKey === 'checked' || propKey === 'selected') { // Noop } else if (propKey === DANGEROUSLY_SET_INNER_HTML) { var serverHTML = domElement.innerHTML; var nextHtml = nextProp ? nextProp[HTML] : undefined; var expectedHTML = normalizeHTML(domElement, nextHtml != null ? nextHtml : ''); if (expectedHTML !== serverHTML) { warnForPropDifference(propKey, serverHTML, expectedHTML); } } else if (propKey === STYLE$1) { // $FlowFixMe - Should be inferred as not undefined. extraAttributeNames.delete(propKey); if (canDiffStyleForHydrationWarning) { var expectedStyle = createDangerousStringForStyles(nextProp); serverValue = domElement.getAttribute('style'); if (expectedStyle !== serverValue) { warnForPropDifference(propKey, serverValue, expectedStyle); } } } else if (isCustomComponentTag) { // $FlowFixMe - Should be inferred as not undefined. extraAttributeNames.delete(propKey.toLowerCase()); serverValue = getValueForAttribute(domElement, propKey, nextProp); if (nextProp !== serverValue) { warnForPropDifference(propKey, serverValue, nextProp); } } else if (!shouldIgnoreAttribute(propKey, propertyInfo, isCustomComponentTag) && !shouldRemoveAttribute(propKey, nextProp, propertyInfo, isCustomComponentTag)) { var isMismatchDueToBadCasing = false; if (propertyInfo !== null) { // $FlowFixMe - Should be inferred as not undefined. extraAttributeNames.delete(propertyInfo.attributeName); serverValue = getValueForProperty(domElement, propKey, nextProp, propertyInfo); } else { var ownNamespace = parentNamespace; if (ownNamespace === HTML_NAMESPACE) { ownNamespace = getIntrinsicNamespace(tag); } if (ownNamespace === HTML_NAMESPACE) { // $FlowFixMe - Should be inferred as not undefined. extraAttributeNames.delete(propKey.toLowerCase()); } else { var standardName = getPossibleStandardName(propKey); if (standardName !== null && standardName !== propKey) { // If an SVG prop is supplied with bad casing, it will // be successfully parsed from HTML, but will produce a mismatch // (and would be incorrectly rendered on the client). // However, we already warn about bad casing elsewhere. // So we'll skip the misleading extra mismatch warning in this case. isMismatchDueToBadCasing = true; // $FlowFixMe - Should be inferred as not undefined. extraAttributeNames.delete(standardName); } // $FlowFixMe - Should be inferred as not undefined. extraAttributeNames.delete(propKey); } serverValue = getValueForAttribute(domElement, propKey, nextProp); } if (nextProp !== serverValue && !isMismatchDueToBadCasing) { warnForPropDifference(propKey, serverValue, nextProp); } } } } { // $FlowFixMe - Should be inferred as not undefined. if (extraAttributeNames.size > 0 && !suppressHydrationWarning) { // $FlowFixMe - Should be inferred as not undefined. warnForExtraAttributes(extraAttributeNames); } } switch (tag) { case 'input': // TODO: Make sure we check if this is still unmounted or do any clean // up necessary since we never stop tracking anymore. track(domElement); postMountWrapper(domElement, rawProps, true); break; case 'textarea': // TODO: Make sure we check if this is still unmounted or do any clean // up necessary since we never stop tracking anymore. track(domElement); postMountWrapper$3(domElement, rawProps); break; case 'select': case 'option': // For input and textarea we current always set the value property at // post mount to force it to diverge from attributes. However, for // option and select we don't quite do the same thing and select // is not resilient to the DOM state changing so we don't do that here. // TODO: Consider not doing this for input and textarea. break; default: if (typeof rawProps.onClick === 'function') { // TODO: This cast may not be sound for SVG, MathML or custom elements. trapClickOnNonInteractiveElement(domElement); } break; } return updatePayload; } function diffHydratedText(textNode, text) { var isDifferent = textNode.nodeValue !== text; return isDifferent; } function warnForUnmatchedText(textNode, text) { { warnForTextDifference(textNode.nodeValue, text); } } function warnForDeletedHydratableElement(parentNode, child) { { if (didWarnInvalidHydration) { return; } didWarnInvalidHydration = true; warningWithoutStack$1(false, 'Did not expect server HTML to contain a <%s> in <%s>.', child.nodeName.toLowerCase(), parentNode.nodeName.toLowerCase()); } } function warnForDeletedHydratableText(parentNode, child) { { if (didWarnInvalidHydration) { return; } didWarnInvalidHydration = true; warningWithoutStack$1(false, 'Did not expect server HTML to contain the text node "%s" in <%s>.', child.nodeValue, parentNode.nodeName.toLowerCase()); } } function warnForInsertedHydratedElement(parentNode, tag, props) { { if (didWarnInvalidHydration) { return; } didWarnInvalidHydration = true; warningWithoutStack$1(false, 'Expected server HTML to contain a matching <%s> in <%s>.', tag, parentNode.nodeName.toLowerCase()); } } function warnForInsertedHydratedText(parentNode, text) { { if (text === '') { // We expect to insert empty text nodes since they're not represented in // the HTML. // TODO: Remove this special case if we can just avoid inserting empty // text nodes. return; } if (didWarnInvalidHydration) { return; } didWarnInvalidHydration = true; warningWithoutStack$1(false, 'Expected server HTML to contain a matching text node for "%s" in <%s>.', text, parentNode.nodeName.toLowerCase()); } } function restoreControlledState$1(domElement, tag, props) { switch (tag) { case 'input': restoreControlledState(domElement, props); return; case 'textarea': restoreControlledState$3(domElement, props); return; case 'select': restoreControlledState$2(domElement, props); return; } } // TODO: direct imports like some-package/src/* are bad. Fix me. var validateDOMNesting = function () {}; var updatedAncestorInfo = function () {}; { // This validation code was written based on the HTML5 parsing spec: // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope // // Note: this does not catch all invalid nesting, nor does it try to (as it's // not clear what practical benefit doing so provides); instead, we warn only // for cases where the parser will give a parse tree differing from what React // intended. For example,
is invalid but we don't warn // because it still parses correctly; we do warn for other cases like nested //

tags where the beginning of the second element implicitly closes the // first, causing a confusing mess. // https://html.spec.whatwg.org/multipage/syntax.html#special var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point // TODO: Distinguish by namespace here -- for , including it here // errs on the side of fewer warnings 'foreignObject', 'desc', 'title']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope var buttonScopeTags = inScopeTags.concat(['button']); // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt']; var emptyAncestorInfo = { current: null, formTag: null, aTagInScope: null, buttonTagInScope: null, nobrTagInScope: null, pTagInButtonScope: null, listItemTagAutoclosing: null, dlItemTagAutoclosing: null }; updatedAncestorInfo = function (oldInfo, tag) { var ancestorInfo = _assign({}, oldInfo || emptyAncestorInfo); var info = { tag: tag }; if (inScopeTags.indexOf(tag) !== -1) { ancestorInfo.aTagInScope = null; ancestorInfo.buttonTagInScope = null; ancestorInfo.nobrTagInScope = null; } if (buttonScopeTags.indexOf(tag) !== -1) { ancestorInfo.pTagInButtonScope = null; } // See rules for 'li', 'dd', 'dt' start tags in // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') { ancestorInfo.listItemTagAutoclosing = null; ancestorInfo.dlItemTagAutoclosing = null; } ancestorInfo.current = info; if (tag === 'form') { ancestorInfo.formTag = info; } if (tag === 'a') { ancestorInfo.aTagInScope = info; } if (tag === 'button') { ancestorInfo.buttonTagInScope = info; } if (tag === 'nobr') { ancestorInfo.nobrTagInScope = info; } if (tag === 'p') { ancestorInfo.pTagInButtonScope = info; } if (tag === 'li') { ancestorInfo.listItemTagAutoclosing = info; } if (tag === 'dd' || tag === 'dt') { ancestorInfo.dlItemTagAutoclosing = info; } return ancestorInfo; }; /** * Returns whether */ var isTagValidWithParent = function (tag, parentTag) { // First, let's check if we're in an unusual parsing mode... switch (parentTag) { // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect case 'select': return tag === 'option' || tag === 'optgroup' || tag === '#text'; case 'optgroup': return tag === 'option' || tag === '#text'; // Strictly speaking, seeing an <option> doesn't mean we're in a <select> // but case 'option': return tag === '#text'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption // No special behavior since these rules fall back to "in body" mode for // all except special table nodes which cause bad parsing behavior anyway. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr case 'tr': return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody case 'tbody': case 'thead': case 'tfoot': return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup case 'colgroup': return tag === 'col' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable case 'table': return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead case 'head': return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element case 'html': return tag === 'head' || tag === 'body'; case '#document': return tag === 'html'; } // Probably in the "in body" parsing mode, so we outlaw only tag combos // where the parsing rules cause implicit opens or closes to be added. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody switch (tag) { case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6'; case 'rp': case 'rt': return impliedEndTags.indexOf(parentTag) === -1; case 'body': case 'caption': case 'col': case 'colgroup': case 'frame': case 'head': case 'html': case 'tbody': case 'td': case 'tfoot': case 'th': case 'thead': case 'tr': // These tags are only valid with a few parents that have special child // parsing rules -- if we're down here, then none of those matched and // so we allow it only if we don't know what the parent is, as all other // cases are invalid. return parentTag == null; } return true; }; /** * Returns whether */ var findInvalidAncestorForTag = function (tag, ancestorInfo) { switch (tag) { case 'address': case 'article': case 'aside': case 'blockquote': case 'center': case 'details': case 'dialog': case 'dir': case 'div': case 'dl': case 'fieldset': case 'figcaption': case 'figure': case 'footer': case 'header': case 'hgroup': case 'main': case 'menu': case 'nav': case 'ol': case 'p': case 'section': case 'summary': case 'ul': case 'pre': case 'listing': case 'table': case 'hr': case 'xmp': case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return ancestorInfo.pTagInButtonScope; case 'form': return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope; case 'li': return ancestorInfo.listItemTagAutoclosing; case 'dd': case 'dt': return ancestorInfo.dlItemTagAutoclosing; case 'button': return ancestorInfo.buttonTagInScope; case 'a': // Spec says something about storing a list of markers, but it sounds // equivalent to this check. return ancestorInfo.aTagInScope; case 'nobr': return ancestorInfo.nobrTagInScope; } return null; }; var didWarn = {}; validateDOMNesting = function (childTag, childText, ancestorInfo) { ancestorInfo = ancestorInfo || emptyAncestorInfo; var parentInfo = ancestorInfo.current; var parentTag = parentInfo && parentInfo.tag; if (childText != null) { !(childTag == null) ? warningWithoutStack$1(false, 'validateDOMNesting: when childText is passed, childTag should be null') : void 0; childTag = '#text'; } var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo; var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo); var invalidParentOrAncestor = invalidParent || invalidAncestor; if (!invalidParentOrAncestor) { return; } var ancestorTag = invalidParentOrAncestor.tag; var addendum = getCurrentFiberStackInDev(); var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + addendum; if (didWarn[warnKey]) { return; } didWarn[warnKey] = true; var tagDisplayName = childTag; var whitespaceInfo = ''; if (childTag === '#text') { if (/\S/.test(childText)) { tagDisplayName = 'Text nodes'; } else { tagDisplayName = 'Whitespace text nodes'; whitespaceInfo = " Make sure you don't have any extra whitespace between tags on " + 'each line of your source code.'; } } else { tagDisplayName = '<' + childTag + '>'; } if (invalidParent) { var info = ''; if (ancestorTag === 'table' && childTag === 'tr') { info += ' Add a <tbody> to your code to match the DOM tree generated by ' + 'the browser.'; } warningWithoutStack$1(false, 'validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s%s', tagDisplayName, ancestorTag, whitespaceInfo, info, addendum); } else { warningWithoutStack$1(false, 'validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>.%s', tagDisplayName, ancestorTag, addendum); } }; } // Renderers that don't support persistence // can re-export everything from this module. function shim() { invariant(false, 'The current renderer does not support persistence. This error is likely caused by a bug in React. Please file an issue.'); } // Persistence (when unsupported) var supportsPersistence = false; var cloneInstance = shim; var createContainerChildSet = shim; var appendChildToContainerChildSet = shim; var finalizeContainerChildren = shim; var replaceContainerChildren = shim; var cloneHiddenInstance = shim; var cloneUnhiddenInstance = shim; var createHiddenTextInstance = shim; var SUPPRESS_HYDRATION_WARNING = void 0; { SUPPRESS_HYDRATION_WARNING = 'suppressHydrationWarning'; } var SUSPENSE_START_DATA = '$'; var SUSPENSE_END_DATA = '/$'; var STYLE = 'style'; var eventsEnabled = null; var selectionInformation = null; function shouldAutoFocusHostComponent(type, props) { switch (type) { case 'button': case 'input': case 'select': case 'textarea': return !!props.autoFocus; } return false; } function getRootHostContext(rootContainerInstance) { var type = void 0; var namespace = void 0; var nodeType = rootContainerInstance.nodeType; switch (nodeType) { case DOCUMENT_NODE: case DOCUMENT_FRAGMENT_NODE: { type = nodeType === DOCUMENT_NODE ? '#document' : '#fragment'; var root = rootContainerInstance.documentElement; namespace = root ? root.namespaceURI : getChildNamespace(null, ''); break; } default: { var container = nodeType === COMMENT_NODE ? rootContainerInstance.parentNode : rootContainerInstance; var ownNamespace = container.namespaceURI || null; type = container.tagName; namespace = getChildNamespace(ownNamespace, type); break; } } { var validatedTag = type.toLowerCase(); var _ancestorInfo = updatedAncestorInfo(null, validatedTag); return { namespace: namespace, ancestorInfo: _ancestorInfo }; } return namespace; } function getChildHostContext(parentHostContext, type, rootContainerInstance) { { var parentHostContextDev = parentHostContext; var _namespace = getChildNamespace(parentHostContextDev.namespace, type); var _ancestorInfo2 = updatedAncestorInfo(parentHostContextDev.ancestorInfo, type); return { namespace: _namespace, ancestorInfo: _ancestorInfo2 }; } var parentNamespace = parentHostContext; return getChildNamespace(parentNamespace, type); } function getPublicInstance(instance) { return instance; } function prepareForCommit(containerInfo) { eventsEnabled = isEnabled(); selectionInformation = getSelectionInformation(); setEnabled(false); } function resetAfterCommit(containerInfo) { restoreSelection(selectionInformation); selectionInformation = null; setEnabled(eventsEnabled); eventsEnabled = null; } function createInstance(type, props, rootContainerInstance, hostContext, internalInstanceHandle) { var parentNamespace = void 0; { // TODO: take namespace into account when validating. var hostContextDev = hostContext; validateDOMNesting(type, null, hostContextDev.ancestorInfo); if (typeof props.children === 'string' || typeof props.children === 'number') { var string = '' + props.children; var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type); validateDOMNesting(null, string, ownAncestorInfo); } parentNamespace = hostContextDev.namespace; } var domElement = createElement(type, props, rootContainerInstance, parentNamespace); precacheFiberNode(internalInstanceHandle, domElement); updateFiberProps(domElement, props); return domElement; } function appendInitialChild(parentInstance, child) { parentInstance.appendChild(child); } function finalizeInitialChildren(domElement, type, props, rootContainerInstance, hostContext) { setInitialProperties(domElement, type, props, rootContainerInstance); return shouldAutoFocusHostComponent(type, props); } function prepareUpdate(domElement, type, oldProps, newProps, rootContainerInstance, hostContext) { { var hostContextDev = hostContext; if (typeof newProps.children !== typeof oldProps.children && (typeof newProps.children === 'string' || typeof newProps.children === 'number')) { var string = '' + newProps.children; var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type); validateDOMNesting(null, string, ownAncestorInfo); } } return diffProperties(domElement, type, oldProps, newProps, rootContainerInstance); } function shouldSetTextContent(type, props) { return type === 'textarea' || type === 'option' || type === 'noscript' || typeof props.children === 'string' || typeof props.children === 'number' || typeof props.dangerouslySetInnerHTML === 'object' && props.dangerouslySetInnerHTML !== null && props.dangerouslySetInnerHTML.__html != null; } function shouldDeprioritizeSubtree(type, props) { return !!props.hidden; } function createTextInstance(text, rootContainerInstance, hostContext, internalInstanceHandle) { { var hostContextDev = hostContext; validateDOMNesting(null, text, hostContextDev.ancestorInfo); } var textNode = createTextNode(text, rootContainerInstance); precacheFiberNode(internalInstanceHandle, textNode); return textNode; } var isPrimaryRenderer = true; // This initialization code may run even on server environments // if a component just imports ReactDOM (e.g. for findDOMNode). // Some environments might not have setTimeout or clearTimeout. var scheduleTimeout = typeof setTimeout === 'function' ? setTimeout : undefined; var cancelTimeout = typeof clearTimeout === 'function' ? clearTimeout : undefined; var noTimeout = -1; var schedulePassiveEffects = scheduler.unstable_scheduleCallback; var cancelPassiveEffects = scheduler.unstable_cancelCallback; // ------------------- // Mutation // ------------------- var supportsMutation = true; function commitMount(domElement, type, newProps, internalInstanceHandle) { // Despite the naming that might imply otherwise, this method only // fires if there is an `Update` effect scheduled during mounting. // This happens if `finalizeInitialChildren` returns `true` (which it // does to implement the `autoFocus` attribute on the client). But // there are also other cases when this might happen (such as patching // up text content during hydration mismatch). So we'll check this again. if (shouldAutoFocusHostComponent(type, newProps)) { domElement.focus(); } } function commitUpdate(domElement, updatePayload, type, oldProps, newProps, internalInstanceHandle) { // Update the props handle so that we know which props are the ones with // with current event handlers. updateFiberProps(domElement, newProps); // Apply the diff to the DOM node. updateProperties(domElement, updatePayload, type, oldProps, newProps); } function resetTextContent(domElement) { setTextContent(domElement, ''); } function commitTextUpdate(textInstance, oldText, newText) { textInstance.nodeValue = newText; } function appendChild(parentInstance, child) { parentInstance.appendChild(child); } function appendChildToContainer(container, child) { var parentNode = void 0; if (container.nodeType === COMMENT_NODE) { parentNode = container.parentNode; parentNode.insertBefore(child, container); } else { parentNode = container; parentNode.appendChild(child); } // This container might be used for a portal. // If something inside a portal is clicked, that click should bubble // through the React tree. However, on Mobile Safari the click would // never bubble through the *DOM* tree unless an ancestor with onclick // event exists. So we wouldn't see it and dispatch it. // This is why we ensure that non React root containers have inline onclick // defined. // https://github.com/facebook/react/issues/11918 var reactRootContainer = container._reactRootContainer; if ((reactRootContainer === null || reactRootContainer === undefined) && parentNode.onclick === null) { // TODO: This cast may not be sound for SVG, MathML or custom elements. trapClickOnNonInteractiveElement(parentNode); } } function insertBefore(parentInstance, child, beforeChild) { parentInstance.insertBefore(child, beforeChild); } function insertInContainerBefore(container, child, beforeChild) { if (container.nodeType === COMMENT_NODE) { container.parentNode.insertBefore(child, beforeChild); } else { container.insertBefore(child, beforeChild); } } function removeChild(parentInstance, child) { parentInstance.removeChild(child); } function removeChildFromContainer(container, child) { if (container.nodeType === COMMENT_NODE) { container.parentNode.removeChild(child); } else { container.removeChild(child); } } function clearSuspenseBoundary(parentInstance, suspenseInstance) { var node = suspenseInstance; // Delete all nodes within this suspense boundary. // There might be nested nodes so we need to keep track of how // deep we are and only break out when we're back on top. var depth = 0; do { var nextNode = node.nextSibling; parentInstance.removeChild(node); if (nextNode && nextNode.nodeType === COMMENT_NODE) { var data = nextNode.data; if (data === SUSPENSE_END_DATA) { if (depth === 0) { parentInstance.removeChild(nextNode); return; } else { depth--; } } else if (data === SUSPENSE_START_DATA) { depth++; } } node = nextNode; } while (node); // TODO: Warn, we didn't find the end comment boundary. } function clearSuspenseBoundaryFromContainer(container, suspenseInstance) { if (container.nodeType === COMMENT_NODE) { clearSuspenseBoundary(container.parentNode, suspenseInstance); } else if (container.nodeType === ELEMENT_NODE) { clearSuspenseBoundary(container, suspenseInstance); } else { // Document nodes should never contain suspense boundaries. } } function hideInstance(instance) { // TODO: Does this work for all element types? What about MathML? Should we // pass host context to this method? instance = instance; instance.style.display = 'none'; } function hideTextInstance(textInstance) { textInstance.nodeValue = ''; } function unhideInstance(instance, props) { instance = instance; var styleProp = props[STYLE]; var display = styleProp !== undefined && styleProp !== null && styleProp.hasOwnProperty('display') ? styleProp.display : null; instance.style.display = dangerousStyleValue('display', display); } function unhideTextInstance(textInstance, text) { textInstance.nodeValue = text; } // ------------------- // Hydration // ------------------- var supportsHydration = true; function canHydrateInstance(instance, type, props) { if (instance.nodeType !== ELEMENT_NODE || type.toLowerCase() !== instance.nodeName.toLowerCase()) { return null; } // This has now been refined to an element node. return instance; } function canHydrateTextInstance(instance, text) { if (text === '' || instance.nodeType !== TEXT_NODE) { // Empty strings are not parsed by HTML so there won't be a correct match here. return null; } // This has now been refined to a text node. return instance; } function canHydrateSuspenseInstance(instance) { if (instance.nodeType !== COMMENT_NODE) { // Empty strings are not parsed by HTML so there won't be a correct match here. return null; } // This has now been refined to a suspense node. return instance; } function getNextHydratableSibling(instance) { var node = instance.nextSibling; // Skip non-hydratable nodes. while (node && node.nodeType !== ELEMENT_NODE && node.nodeType !== TEXT_NODE && (!enableSuspenseServerRenderer || node.nodeType !== COMMENT_NODE || node.data !== SUSPENSE_START_DATA)) { node = node.nextSibling; } return node; } function getFirstHydratableChild(parentInstance) { var next = parentInstance.firstChild; // Skip non-hydratable nodes. while (next && next.nodeType !== ELEMENT_NODE && next.nodeType !== TEXT_NODE && (!enableSuspenseServerRenderer || next.nodeType !== COMMENT_NODE || next.data !== SUSPENSE_START_DATA)) { next = next.nextSibling; } return next; } function hydrateInstance(instance, type, props, rootContainerInstance, hostContext, internalInstanceHandle) { precacheFiberNode(internalInstanceHandle, instance); // TODO: Possibly defer this until the commit phase where all the events // get attached. updateFiberProps(instance, props); var parentNamespace = void 0; { var hostContextDev = hostContext; parentNamespace = hostContextDev.namespace; } return diffHydratedProperties(instance, type, props, parentNamespace, rootContainerInstance); } function hydrateTextInstance(textInstance, text, internalInstanceHandle) { precacheFiberNode(internalInstanceHandle, textInstance); return diffHydratedText(textInstance, text); } function getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance) { var node = suspenseInstance.nextSibling; // Skip past all nodes within this suspense boundary. // There might be nested nodes so we need to keep track of how // deep we are and only break out when we're back on top. var depth = 0; while (node) { if (node.nodeType === COMMENT_NODE) { var data = node.data; if (data === SUSPENSE_END_DATA) { if (depth === 0) { return getNextHydratableSibling(node); } else { depth--; } } else if (data === SUSPENSE_START_DATA) { depth++; } } node = node.nextSibling; } // TODO: Warn, we didn't find the end comment boundary. return null; } function didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, text) { { warnForUnmatchedText(textInstance, text); } } function didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, text) { if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) { warnForUnmatchedText(textInstance, text); } } function didNotHydrateContainerInstance(parentContainer, instance) { { if (instance.nodeType === ELEMENT_NODE) { warnForDeletedHydratableElement(parentContainer, instance); } else if (instance.nodeType === COMMENT_NODE) { // TODO: warnForDeletedHydratableSuspenseBoundary } else { warnForDeletedHydratableText(parentContainer, instance); } } } function didNotHydrateInstance(parentType, parentProps, parentInstance, instance) { if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) { if (instance.nodeType === ELEMENT_NODE) { warnForDeletedHydratableElement(parentInstance, instance); } else if (instance.nodeType === COMMENT_NODE) { // TODO: warnForDeletedHydratableSuspenseBoundary } else { warnForDeletedHydratableText(parentInstance, instance); } } } function didNotFindHydratableContainerInstance(parentContainer, type, props) { { warnForInsertedHydratedElement(parentContainer, type, props); } } function didNotFindHydratableContainerTextInstance(parentContainer, text) { { warnForInsertedHydratedText(parentContainer, text); } } function didNotFindHydratableInstance(parentType, parentProps, parentInstance, type, props) { if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) { warnForInsertedHydratedElement(parentInstance, type, props); } } function didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, text) { if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) { warnForInsertedHydratedText(parentInstance, text); } } function didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance) { if (true && parentProps[SUPPRESS_HYDRATION_WARNING] !== true) { // TODO: warnForInsertedHydratedSuspense(parentInstance); } } // Prefix measurements so that it's possible to filter them. // Longer prefixes are hard to read in DevTools. var reactEmoji = '\u269B'; var warningEmoji = '\u26D4'; var supportsUserTiming = typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function'; // Keep track of current fiber so that we know the path to unwind on pause. // TODO: this looks the same as nextUnitOfWork in scheduler. Can we unify them? var currentFiber = null; // If we're in the middle of user code, which fiber and method is it? // Reusing `currentFiber` would be confusing for this because user code fiber // can change during commit phase too, but we don't need to unwind it (since // lifecycles in the commit phase don't resemble a tree). var currentPhase = null; var currentPhaseFiber = null; // Did lifecycle hook schedule an update? This is often a performance problem, // so we will keep track of it, and include it in the report. // Track commits caused by cascading updates. var isCommitting = false; var hasScheduledUpdateInCurrentCommit = false; var hasScheduledUpdateInCurrentPhase = false; var commitCountInCurrentWorkLoop = 0; var effectCountInCurrentCommit = 0; var isWaitingForCallback = false; // During commits, we only show a measurement once per method name // to avoid stretch the commit phase with measurement overhead. var labelsInCurrentCommit = new Set(); var formatMarkName = function (markName) { return reactEmoji + ' ' + markName; }; var formatLabel = function (label, warning) { var prefix = warning ? warningEmoji + ' ' : reactEmoji + ' '; var suffix = warning ? ' Warning: ' + warning : ''; return '' + prefix + label + suffix; }; var beginMark = function (markName) { performance.mark(formatMarkName(markName)); }; var clearMark = function (markName) { performance.clearMarks(formatMarkName(markName)); }; var endMark = function (label, markName, warning) { var formattedMarkName = formatMarkName(markName); var formattedLabel = formatLabel(label, warning); try { performance.measure(formattedLabel, formattedMarkName); } catch (err) {} // If previous mark was missing for some reason, this will throw. // This could only happen if React crashed in an unexpected place earlier. // Don't pile on with more errors. // Clear marks immediately to avoid growing buffer. performance.clearMarks(formattedMarkName); performance.clearMeasures(formattedLabel); }; var getFiberMarkName = function (label, debugID) { return label + ' (#' + debugID + ')'; }; var getFiberLabel = function (componentName, isMounted, phase) { if (phase === null) { // These are composite component total time measurements. return componentName + ' [' + (isMounted ? 'update' : 'mount') + ']'; } else { // Composite component methods. return componentName + '.' + phase; } }; var beginFiberMark = function (fiber, phase) { var componentName = getComponentName(fiber.type) || 'Unknown'; var debugID = fiber._debugID; var isMounted = fiber.alternate !== null; var label = getFiberLabel(componentName, isMounted, phase); if (isCommitting && labelsInCurrentCommit.has(label)) { // During the commit phase, we don't show duplicate labels because // there is a fixed overhead for every measurement, and we don't // want to stretch the commit phase beyond necessary. return false; } labelsInCurrentCommit.add(label); var markName = getFiberMarkName(label, debugID); beginMark(markName); return true; }; var clearFiberMark = function (fiber, phase) { var componentName = getComponentName(fiber.type) || 'Unknown'; var debugID = fiber._debugID; var isMounted = fiber.alternate !== null; var label = getFiberLabel(componentName, isMounted, phase); var markName = getFiberMarkName(label, debugID); clearMark(markName); }; var endFiberMark = function (fiber, phase, warning) { var componentName = getComponentName(fiber.type) || 'Unknown'; var debugID = fiber._debugID; var isMounted = fiber.alternate !== null; var label = getFiberLabel(componentName, isMounted, phase); var markName = getFiberMarkName(label, debugID); endMark(label, markName, warning); }; var shouldIgnoreFiber = function (fiber) { // Host components should be skipped in the timeline. // We could check typeof fiber.type, but does this work with RN? switch (fiber.tag) { case HostRoot: case HostComponent: case HostText: case HostPortal: case Fragment: case ContextProvider: case ContextConsumer: case Mode: return true; default: return false; } }; var clearPendingPhaseMeasurement = function () { if (currentPhase !== null && currentPhaseFiber !== null) { clearFiberMark(currentPhaseFiber, currentPhase); } currentPhaseFiber = null; currentPhase = null; hasScheduledUpdateInCurrentPhase = false; }; var pauseTimers = function () { // Stops all currently active measurements so that they can be resumed // if we continue in a later deferred loop from the same unit of work. var fiber = currentFiber; while (fiber) { if (fiber._debugIsCurrentlyTiming) { endFiberMark(fiber, null, null); } fiber = fiber.return; } }; var resumeTimersRecursively = function (fiber) { if (fiber.return !== null) { resumeTimersRecursively(fiber.return); } if (fiber._debugIsCurrentlyTiming) { beginFiberMark(fiber, null); } }; var resumeTimers = function () { // Resumes all measurements that were active during the last deferred loop. if (currentFiber !== null) { resumeTimersRecursively(currentFiber); } }; function recordEffect() { if (enableUserTimingAPI) { effectCountInCurrentCommit++; } } function recordScheduleUpdate() { if (enableUserTimingAPI) { if (isCommitting) { hasScheduledUpdateInCurrentCommit = true; } if (currentPhase !== null && currentPhase !== 'componentWillMount' && currentPhase !== 'componentWillReceiveProps') { hasScheduledUpdateInCurrentPhase = true; } } } function startRequestCallbackTimer() { if (enableUserTimingAPI) { if (supportsUserTiming && !isWaitingForCallback) { isWaitingForCallback = true; beginMark('(Waiting for async callback...)'); } } } function stopRequestCallbackTimer(didExpire, expirationTime) { if (enableUserTimingAPI) { if (supportsUserTiming) { isWaitingForCallback = false; var warning = didExpire ? 'React was blocked by main thread' : null; endMark('(Waiting for async callback... will force flush in ' + expirationTime + ' ms)', '(Waiting for async callback...)', warning); } } } function startWorkTimer(fiber) { if (enableUserTimingAPI) { if (!supportsUserTiming || shouldIgnoreFiber(fiber)) { return; } // If we pause, this is the fiber to unwind from. currentFiber = fiber; if (!beginFiberMark(fiber, null)) { return; } fiber._debugIsCurrentlyTiming = true; } } function cancelWorkTimer(fiber) { if (enableUserTimingAPI) { if (!supportsUserTiming || shouldIgnoreFiber(fiber)) { return; } // Remember we shouldn't complete measurement for this fiber. // Otherwise flamechart will be deep even for small updates. fiber._debugIsCurrentlyTiming = false; clearFiberMark(fiber, null); } } function stopWorkTimer(fiber) { if (enableUserTimingAPI) { if (!supportsUserTiming || shouldIgnoreFiber(fiber)) { return; } // If we pause, its parent is the fiber to unwind from. currentFiber = fiber.return; if (!fiber._debugIsCurrentlyTiming) { return; } fiber._debugIsCurrentlyTiming = false; endFiberMark(fiber, null, null); } } function stopFailedWorkTimer(fiber) { if (enableUserTimingAPI) { if (!supportsUserTiming || shouldIgnoreFiber(fiber)) { return; } // If we pause, its parent is the fiber to unwind from. currentFiber = fiber.return; if (!fiber._debugIsCurrentlyTiming) { return; } fiber._debugIsCurrentlyTiming = false; var warning = fiber.tag === SuspenseComponent || fiber.tag === DehydratedSuspenseComponent ? 'Rendering was suspended' : 'An error was thrown inside this error boundary'; endFiberMark(fiber, null, warning); } } function startPhaseTimer(fiber, phase) { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } clearPendingPhaseMeasurement(); if (!beginFiberMark(fiber, phase)) { return; } currentPhaseFiber = fiber; currentPhase = phase; } } function stopPhaseTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } if (currentPhase !== null && currentPhaseFiber !== null) { var warning = hasScheduledUpdateInCurrentPhase ? 'Scheduled a cascading update' : null; endFiberMark(currentPhaseFiber, currentPhase, warning); } currentPhase = null; currentPhaseFiber = null; } } function startWorkLoopTimer(nextUnitOfWork) { if (enableUserTimingAPI) { currentFiber = nextUnitOfWork; if (!supportsUserTiming) { return; } commitCountInCurrentWorkLoop = 0; // This is top level call. // Any other measurements are performed within. beginMark('(React Tree Reconciliation)'); // Resume any measurements that were in progress during the last loop. resumeTimers(); } } function stopWorkLoopTimer(interruptedBy, didCompleteRoot) { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } var warning = null; if (interruptedBy !== null) { if (interruptedBy.tag === HostRoot) { warning = 'A top-level update interrupted the previous render'; } else { var componentName = getComponentName(interruptedBy.type) || 'Unknown'; warning = 'An update to ' + componentName + ' interrupted the previous render'; } } else if (commitCountInCurrentWorkLoop > 1) { warning = 'There were cascading updates'; } commitCountInCurrentWorkLoop = 0; var label = didCompleteRoot ? '(React Tree Reconciliation: Completed Root)' : '(React Tree Reconciliation: Yielded)'; // Pause any measurements until the next loop. pauseTimers(); endMark(label, '(React Tree Reconciliation)', warning); } } function startCommitTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } isCommitting = true; hasScheduledUpdateInCurrentCommit = false; labelsInCurrentCommit.clear(); beginMark('(Committing Changes)'); } } function stopCommitTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } var warning = null; if (hasScheduledUpdateInCurrentCommit) { warning = 'Lifecycle hook scheduled a cascading update'; } else if (commitCountInCurrentWorkLoop > 0) { warning = 'Caused by a cascading update in earlier commit'; } hasScheduledUpdateInCurrentCommit = false; commitCountInCurrentWorkLoop++; isCommitting = false; labelsInCurrentCommit.clear(); endMark('(Committing Changes)', '(Committing Changes)', warning); } } function startCommitSnapshotEffectsTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } effectCountInCurrentCommit = 0; beginMark('(Committing Snapshot Effects)'); } } function stopCommitSnapshotEffectsTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } var count = effectCountInCurrentCommit; effectCountInCurrentCommit = 0; endMark('(Committing Snapshot Effects: ' + count + ' Total)', '(Committing Snapshot Effects)', null); } } function startCommitHostEffectsTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } effectCountInCurrentCommit = 0; beginMark('(Committing Host Effects)'); } } function stopCommitHostEffectsTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } var count = effectCountInCurrentCommit; effectCountInCurrentCommit = 0; endMark('(Committing Host Effects: ' + count + ' Total)', '(Committing Host Effects)', null); } } function startCommitLifeCyclesTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } effectCountInCurrentCommit = 0; beginMark('(Calling Lifecycle Methods)'); } } function stopCommitLifeCyclesTimer() { if (enableUserTimingAPI) { if (!supportsUserTiming) { return; } var count = effectCountInCurrentCommit; effectCountInCurrentCommit = 0; endMark('(Calling Lifecycle Methods: ' + count + ' Total)', '(Calling Lifecycle Methods)', null); } } var valueStack = []; var fiberStack = void 0; { fiberStack = []; } var index = -1; function createCursor(defaultValue) { return { current: defaultValue }; } function pop(cursor, fiber) { if (index < 0) { { warningWithoutStack$1(false, 'Unexpected pop.'); } return; } { if (fiber !== fiberStack[index]) { warningWithoutStack$1(false, 'Unexpected Fiber popped.'); } } cursor.current = valueStack[index]; valueStack[index] = null; { fiberStack[index] = null; } index--; } function push(cursor, value, fiber) { index++; valueStack[index] = cursor.current; { fiberStack[index] = fiber; } cursor.current = value; } function checkThatStackIsEmpty() { { if (index !== -1) { warningWithoutStack$1(false, 'Expected an empty stack. Something was not reset properly.'); } } } function resetStackAfterFatalErrorInDev() { { index = -1; valueStack.length = 0; fiberStack.length = 0; } } var warnedAboutMissingGetChildContext = void 0; { warnedAboutMissingGetChildContext = {}; } var emptyContextObject = {}; { Object.freeze(emptyContextObject); } // A cursor to the current merged context object on the stack. var contextStackCursor = createCursor(emptyContextObject); // A cursor to a boolean indicating whether the context has changed. var didPerformWorkStackCursor = createCursor(false); // Keep track of the previous context object that was on the stack. // We use this to get access to the parent context after we have already // pushed the next context provider, and now need to merge their contexts. var previousContext = emptyContextObject; function getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) { if (didPushOwnContextIfProvider && isContextProvider(Component)) { // If the fiber is a context provider itself, when we read its context // we may have already pushed its own child context on the stack. A context // provider should not "see" its own child context. Therefore we read the // previous (parent) context instead for a context provider. return previousContext; } return contextStackCursor.current; } function cacheContext(workInProgress, unmaskedContext, maskedContext) { var instance = workInProgress.stateNode; instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext; instance.__reactInternalMemoizedMaskedChildContext = maskedContext; } function getMaskedContext(workInProgress, unmaskedContext) { var type = workInProgress.type; var contextTypes = type.contextTypes; if (!contextTypes) { return emptyContextObject; } // Avoid recreating masked context unless unmasked context has changed. // Failing to do this will result in unnecessary calls to componentWillReceiveProps. // This may trigger infinite loops if componentWillReceiveProps calls setState. var instance = workInProgress.stateNode; if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) { return instance.__reactInternalMemoizedMaskedChildContext; } var context = {}; for (var key in contextTypes) { context[key] = unmaskedContext[key]; } { var name = getComponentName(type) || 'Unknown'; checkPropTypes(contextTypes, context, 'context', name, getCurrentFiberStackInDev); } // Cache unmasked context so we can avoid recreating masked context unless necessary. // Context is created before the class component is instantiated so check for instance. if (instance) { cacheContext(workInProgress, unmaskedContext, context); } return context; } function hasContextChanged() { return didPerformWorkStackCursor.current; } function isContextProvider(type) { var childContextTypes = type.childContextTypes; return childContextTypes !== null && childContextTypes !== undefined; } function popContext(fiber) { pop(didPerformWorkStackCursor, fiber); pop(contextStackCursor, fiber); } function popTopLevelContextObject(fiber) { pop(didPerformWorkStackCursor, fiber); pop(contextStackCursor, fiber); } function pushTopLevelContextObject(fiber, context, didChange) { !(contextStackCursor.current === emptyContextObject) ? invariant(false, 'Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue.') : void 0; push(contextStackCursor, context, fiber); push(didPerformWorkStackCursor, didChange, fiber); } function processChildContext(fiber, type, parentContext) { var instance = fiber.stateNode; var childContextTypes = type.childContextTypes; // TODO (bvaughn) Replace this behavior with an invariant() in the future. // It has only been added in Fiber to match the (unintentional) behavior in Stack. if (typeof instance.getChildContext !== 'function') { { var componentName = getComponentName(type) || 'Unknown'; if (!warnedAboutMissingGetChildContext[componentName]) { warnedAboutMissingGetChildContext[componentName] = true; warningWithoutStack$1(false, '%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName); } } return parentContext; } var childContext = void 0; { setCurrentPhase('getChildContext'); } startPhaseTimer(fiber, 'getChildContext'); childContext = instance.getChildContext(); stopPhaseTimer(); { setCurrentPhase(null); } for (var contextKey in childContext) { !(contextKey in childContextTypes) ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', getComponentName(type) || 'Unknown', contextKey) : void 0; } { var name = getComponentName(type) || 'Unknown'; checkPropTypes(childContextTypes, childContext, 'child context', name, // In practice, there is one case in which we won't get a stack. It's when // somebody calls unstable_renderSubtreeIntoContainer() and we process // context from the parent component instance. The stack will be missing // because it's outside of the reconciliation, and so the pointer has not // been set. This is rare and doesn't matter. We'll also remove that API. getCurrentFiberStackInDev); } return _assign({}, parentContext, childContext); } function pushContextProvider(workInProgress) { var instance = workInProgress.stateNode; // We push the context as early as possible to ensure stack integrity. // If the instance does not exist yet, we will push null at first, // and replace it on the stack later when invalidating the context. var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject; // Remember the parent context so we can merge with it later. // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates. previousContext = contextStackCursor.current; push(contextStackCursor, memoizedMergedChildContext, workInProgress); push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress); return true; } function invalidateContextProvider(workInProgress, type, didChange) { var instance = workInProgress.stateNode; !instance ? invariant(false, 'Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue.') : void 0; if (didChange) { // Merge parent and own context. // Skip this if we're not updating due to sCU. // This avoids unnecessarily recomputing memoized values. var mergedContext = processChildContext(workInProgress, type, previousContext); instance.__reactInternalMemoizedMergedChildContext = mergedContext; // Replace the old (or empty) context with the new one. // It is important to unwind the context in the reverse order. pop(didPerformWorkStackCursor, workInProgress); pop(contextStackCursor, workInProgress); // Now push the new context and mark that it has changed. push(contextStackCursor, mergedContext, workInProgress); push(didPerformWorkStackCursor, didChange, workInProgress); } else { pop(didPerformWorkStackCursor, workInProgress); push(didPerformWorkStackCursor, didChange, workInProgress); } } function findCurrentUnmaskedContext(fiber) { // Currently this is only used with renderSubtreeIntoContainer; not sure if it // makes sense elsewhere !(isFiberMounted(fiber) && fiber.tag === ClassComponent) ? invariant(false, 'Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue.') : void 0; var node = fiber; do { switch (node.tag) { case HostRoot: return node.stateNode.context; case ClassComponent: { var Component = node.type; if (isContextProvider(Component)) { return node.stateNode.__reactInternalMemoizedMergedChildContext; } break; } } node = node.return; } while (node !== null); invariant(false, 'Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue.'); } var onCommitFiberRoot = null; var onCommitFiberUnmount = null; var hasLoggedError = false; function catchErrors(fn) { return function (arg) { try { return fn(arg); } catch (err) { if (true && !hasLoggedError) { hasLoggedError = true; warningWithoutStack$1(false, 'React DevTools encountered an error: %s', err); } } }; } var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined'; function injectInternals(internals) { if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') { // No DevTools return false; } var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__; if (hook.isDisabled) { // This isn't a real property on the hook, but it can be set to opt out // of DevTools integration and associated warnings and logs. // https://github.com/facebook/react/issues/3877 return true; } if (!hook.supportsFiber) { { warningWithoutStack$1(false, 'The installed version of React DevTools is too old and will not work ' + 'with the current version of React. Please update React DevTools. ' + 'https://fb.me/react-devtools'); } // DevTools exists, even though it doesn't support Fiber. return true; } try { var rendererID = hook.inject(internals); // We have successfully injected, so now it is safe to set up hooks. onCommitFiberRoot = catchErrors(function (root) { return hook.onCommitFiberRoot(rendererID, root); }); onCommitFiberUnmount = catchErrors(function (fiber) { return hook.onCommitFiberUnmount(rendererID, fiber); }); } catch (err) { // Catch all errors because it is unsafe to throw during initialization. { warningWithoutStack$1(false, 'React DevTools encountered an error: %s.', err); } } // DevTools exists return true; } function onCommitRoot(root) { if (typeof onCommitFiberRoot === 'function') { onCommitFiberRoot(root); } } function onCommitUnmount(fiber) { if (typeof onCommitFiberUnmount === 'function') { onCommitFiberUnmount(fiber); } } // Max 31 bit integer. The max integer size in V8 for 32-bit systems. // Math.pow(2, 30) - 1 // 0b111111111111111111111111111111 var maxSigned31BitInt = 1073741823; var NoWork = 0; var Never = 1; var Sync = maxSigned31BitInt; var UNIT_SIZE = 10; var MAGIC_NUMBER_OFFSET = maxSigned31BitInt - 1; // 1 unit of expiration time represents 10ms. function msToExpirationTime(ms) { // Always add an offset so that we don't clash with the magic number for NoWork. return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0); } function expirationTimeToMs(expirationTime) { return (MAGIC_NUMBER_OFFSET - expirationTime) * UNIT_SIZE; } function ceiling(num, precision) { return ((num / precision | 0) + 1) * precision; } function computeExpirationBucket(currentTime, expirationInMs, bucketSizeMs) { return MAGIC_NUMBER_OFFSET - ceiling(MAGIC_NUMBER_OFFSET - currentTime + expirationInMs / UNIT_SIZE, bucketSizeMs / UNIT_SIZE); } var LOW_PRIORITY_EXPIRATION = 5000; var LOW_PRIORITY_BATCH_SIZE = 250; function computeAsyncExpiration(currentTime) { return computeExpirationBucket(currentTime, LOW_PRIORITY_EXPIRATION, LOW_PRIORITY_BATCH_SIZE); } // We intentionally set a higher expiration time for interactive updates in // dev than in production. // // If the main thread is being blocked so long that you hit the expiration, // it's a problem that could be solved with better scheduling. // // People will be more likely to notice this and fix it with the long // expiration time in development. // // In production we opt for better UX at the risk of masking scheduling // problems, by expiring fast. var HIGH_PRIORITY_EXPIRATION = 500; var HIGH_PRIORITY_BATCH_SIZE = 100; function computeInteractiveExpiration(currentTime) { return computeExpirationBucket(currentTime, HIGH_PRIORITY_EXPIRATION, HIGH_PRIORITY_BATCH_SIZE); } var NoContext = 0; var ConcurrentMode = 1; var StrictMode = 2; var ProfileMode = 4; var hasBadMapPolyfill = void 0; { hasBadMapPolyfill = false; try { var nonExtensibleObject = Object.preventExtensions({}); var testMap = new Map([[nonExtensibleObject, null]]); var testSet = new Set([nonExtensibleObject]); // This is necessary for Rollup to not consider these unused. // https://github.com/rollup/rollup/issues/1771 // TODO: we can remove these if Rollup fixes the bug. testMap.set(0, 0); testSet.add(0); } catch (e) { // TODO: Consider warning about bad polyfills hasBadMapPolyfill = true; } } // A Fiber is work on a Component that needs to be done or was done. There can // be more than one per component. var debugCounter = void 0; { debugCounter = 1; } function FiberNode(tag, pendingProps, key, mode) { // Instance this.tag = tag; this.key = key; this.elementType = null; this.type = null; this.stateNode = null; // Fiber this.return = null; this.child = null; this.sibling = null; this.index = 0; this.ref = null; this.pendingProps = pendingProps; this.memoizedProps = null; this.updateQueue = null; this.memoizedState = null; this.contextDependencies = null; this.mode = mode; // Effects this.effectTag = NoEffect; this.nextEffect = null; this.firstEffect = null; this.lastEffect = null; this.expirationTime = NoWork; this.childExpirationTime = NoWork; this.alternate = null; if (enableProfilerTimer) { // Note: The following is done to avoid a v8 performance cliff. // // Initializing the fields below to smis and later updating them with // double values will cause Fibers to end up having separate shapes. // This behavior/bug has something to do with Object.preventExtension(). // Fortunately this only impacts DEV builds. // Unfortunately it makes React unusably slow for some applications. // To work around this, initialize the fields below with doubles. // // Learn more about this here: // https://github.com/facebook/react/issues/14365 // https://bugs.chromium.org/p/v8/issues/detail?id=8538 this.actualDuration = Number.NaN; this.actualStartTime = Number.NaN; this.selfBaseDuration = Number.NaN; this.treeBaseDuration = Number.NaN; // It's okay to replace the initial doubles with smis after initialization. // This won't trigger the performance cliff mentioned above, // and it simplifies other profiler code (including DevTools). this.actualDuration = 0; this.actualStartTime = -1; this.selfBaseDuration = 0; this.treeBaseDuration = 0; } { this._debugID = debugCounter++; this._debugSource = null; this._debugOwner = null; this._debugIsCurrentlyTiming = false; this._debugHookTypes = null; if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') { Object.preventExtensions(this); } } } // This is a constructor function, rather than a POJO constructor, still // please ensure we do the following: // 1) Nobody should add any instance methods on this. Instance methods can be // more difficult to predict when they get optimized and they are almost // never inlined properly in static compilers. // 2) Nobody should rely on `instanceof Fiber` for type testing. We should // always know when it is a fiber. // 3) We might want to experiment with using numeric keys since they are easier // to optimize in a non-JIT environment. // 4) We can easily go from a constructor to a createFiber object literal if that // is faster. // 5) It should be easy to port this to a C struct and keep a C implementation // compatible. var createFiber = function (tag, pendingProps, key, mode) { // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors return new FiberNode(tag, pendingProps, key, mode); }; function shouldConstruct(Component) { var prototype = Component.prototype; return !!(prototype && prototype.isReactComponent); } function isSimpleFunctionComponent(type) { return typeof type === 'function' && !shouldConstruct(type) && type.defaultProps === undefined; } function resolveLazyComponentTag(Component) { if (typeof Component === 'function') { return shouldConstruct(Component) ? ClassComponent : FunctionComponent; } else if (Component !== undefined && Component !== null) { var $$typeof = Component.$$typeof; if ($$typeof === REACT_FORWARD_REF_TYPE) { return ForwardRef; } if ($$typeof === REACT_MEMO_TYPE) { return MemoComponent; } } return IndeterminateComponent; } // This is used to create an alternate fiber to do work on. function createWorkInProgress(current, pendingProps, expirationTime) { var workInProgress = current.alternate; if (workInProgress === null) { // We use a double buffering pooling technique because we know that we'll // only ever need at most two versions of a tree. We pool the "other" unused // node that we're free to reuse. This is lazily created to avoid allocating // extra objects for things that are never updated. It also allow us to // reclaim the extra memory if needed. workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode); workInProgress.elementType = current.elementType; workInProgress.type = current.type; workInProgress.stateNode = current.stateNode; { // DEV-only fields workInProgress._debugID = current._debugID; workInProgress._debugSource = current._debugSource; workInProgress._debugOwner = current._debugOwner; workInProgress._debugHookTypes = current._debugHookTypes; } workInProgress.alternate = current; current.alternate = workInProgress; } else { workInProgress.pendingProps = pendingProps; // We already have an alternate. // Reset the effect tag. workInProgress.effectTag = NoEffect; // The effect list is no longer valid. workInProgress.nextEffect = null; workInProgress.firstEffect = null; workInProgress.lastEffect = null; if (enableProfilerTimer) { // We intentionally reset, rather than copy, actualDuration & actualStartTime. // This prevents time from endlessly accumulating in new commits. // This has the downside of resetting values for different priority renders, // But works for yielding (the common case) and should support resuming. workInProgress.actualDuration = 0; workInProgress.actualStartTime = -1; } } workInProgress.childExpirationTime = current.childExpirationTime; workInProgress.expirationTime = current.expirationTime; workInProgress.child = current.child; workInProgress.memoizedProps = current.memoizedProps; workInProgress.memoizedState = current.memoizedState; workInProgress.updateQueue = current.updateQueue; workInProgress.contextDependencies = current.contextDependencies; // These will be overridden during the parent's reconciliation workInProgress.sibling = current.sibling; workInProgress.index = current.index; workInProgress.ref = current.ref; if (enableProfilerTimer) { workInProgress.selfBaseDuration = current.selfBaseDuration; workInProgress.treeBaseDuration = current.treeBaseDuration; } return workInProgress; } function createHostRootFiber(isConcurrent) { var mode = isConcurrent ? ConcurrentMode | StrictMode : NoContext; if (enableProfilerTimer && isDevToolsPresent) { // Always collect profile timings when DevTools are present. // This enables DevTools to start capturing timing at any point– // Without some nodes in the tree having empty base times. mode |= ProfileMode; } return createFiber(HostRoot, null, null, mode); } function createFiberFromTypeAndProps(type, // React$ElementType key, pendingProps, owner, mode, expirationTime) { var fiber = void 0; var fiberTag = IndeterminateComponent; // The resolved type is set if we know what the final type will be. I.e. it's not lazy. var resolvedType = type; if (typeof type === 'function') { if (shouldConstruct(type)) { fiberTag = ClassComponent; } } else if (typeof type === 'string') { fiberTag = HostComponent; } else { getTag: switch (type) { case REACT_FRAGMENT_TYPE: return createFiberFromFragment(pendingProps.children, mode, expirationTime, key); case REACT_CONCURRENT_MODE_TYPE: return createFiberFromMode(pendingProps, mode | ConcurrentMode | StrictMode, expirationTime, key); case REACT_STRICT_MODE_TYPE: return createFiberFromMode(pendingProps, mode | StrictMode, expirationTime, key); case REACT_PROFILER_TYPE: return createFiberFromProfiler(pendingProps, mode, expirationTime, key); case REACT_SUSPENSE_TYPE: return createFiberFromSuspense(pendingProps, mode, expirationTime, key); default: { if (typeof type === 'object' && type !== null) { switch (type.$$typeof) { case REACT_PROVIDER_TYPE: fiberTag = ContextProvider; break getTag; case REACT_CONTEXT_TYPE: // This is a consumer fiberTag = ContextConsumer; break getTag; case REACT_FORWARD_REF_TYPE: fiberTag = ForwardRef; break getTag; case REACT_MEMO_TYPE: fiberTag = MemoComponent; break getTag; case REACT_LAZY_TYPE: fiberTag = LazyComponent; resolvedType = null; break getTag; } } var info = ''; { if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.'; } var ownerName = owner ? getComponentName(owner.type) : null; if (ownerName) { info += '\n\nCheck the render method of `' + ownerName + '`.'; } } invariant(false, 'Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s', type == null ? type : typeof type, info); } } } fiber = createFiber(fiberTag, pendingProps, key, mode); fiber.elementType = type; fiber.type = resolvedType; fiber.expirationTime = expirationTime; return fiber; } function createFiberFromElement(element, mode, expirationTime) { var owner = null; { owner = element._owner; } var type = element.type; var key = element.key; var pendingProps = element.props; var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, expirationTime); { fiber._debugSource = element._source; fiber._debugOwner = element._owner; } return fiber; } function createFiberFromFragment(elements, mode, expirationTime, key) { var fiber = createFiber(Fragment, elements, key, mode); fiber.expirationTime = expirationTime; return fiber; } function createFiberFromProfiler(pendingProps, mode, expirationTime, key) { { if (typeof pendingProps.id !== 'string' || typeof pendingProps.onRender !== 'function') { warningWithoutStack$1(false, 'Profiler must specify an "id" string and "onRender" function as props'); } } var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); // TODO: The Profiler fiber shouldn't have a type. It has a tag. fiber.elementType = REACT_PROFILER_TYPE; fiber.type = REACT_PROFILER_TYPE; fiber.expirationTime = expirationTime; return fiber; } function createFiberFromMode(pendingProps, mode, expirationTime, key) { var fiber = createFiber(Mode, pendingProps, key, mode); // TODO: The Mode fiber shouldn't have a type. It has a tag. var type = (mode & ConcurrentMode) === NoContext ? REACT_STRICT_MODE_TYPE : REACT_CONCURRENT_MODE_TYPE; fiber.elementType = type; fiber.type = type; fiber.expirationTime = expirationTime; return fiber; } function createFiberFromSuspense(pendingProps, mode, expirationTime, key) { var fiber = createFiber(SuspenseComponent, pendingProps, key, mode); // TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag. var type = REACT_SUSPENSE_TYPE; fiber.elementType = type; fiber.type = type; fiber.expirationTime = expirationTime; return fiber; } function createFiberFromText(content, mode, expirationTime) { var fiber = createFiber(HostText, content, null, mode); fiber.expirationTime = expirationTime; return fiber; } function createFiberFromHostInstanceForDeletion() { var fiber = createFiber(HostComponent, null, null, NoContext); // TODO: These should not need a type. fiber.elementType = 'DELETED'; fiber.type = 'DELETED'; return fiber; } function createFiberFromPortal(portal, mode, expirationTime) { var pendingProps = portal.children !== null ? portal.children : []; var fiber = createFiber(HostPortal, pendingProps, portal.key, mode); fiber.expirationTime = expirationTime; fiber.stateNode = { containerInfo: portal.containerInfo, pendingChildren: null, // Used by persistent updates implementation: portal.implementation }; return fiber; } // Used for stashing WIP properties to replay failed work in DEV. function assignFiberPropertiesInDEV(target, source) { if (target === null) { // This Fiber's initial properties will always be overwritten. // We only use a Fiber to ensure the same hidden class so DEV isn't slow. target = createFiber(IndeterminateComponent, null, null, NoContext); } // This is intentionally written as a list of all properties. // We tried to use Object.assign() instead but this is called in // the hottest path, and Object.assign() was too slow: // https://github.com/facebook/react/issues/12502 // This code is DEV-only so size is not a concern. target.tag = source.tag; target.key = source.key; target.elementType = source.elementType; target.type = source.type; target.stateNode = source.stateNode; target.return = source.return; target.child = source.child; target.sibling = source.sibling; target.index = source.index; target.ref = source.ref; target.pendingProps = source.pendingProps; target.memoizedProps = source.memoizedProps; target.updateQueue = source.updateQueue; target.memoizedState = source.memoizedState; target.contextDependencies = source.contextDependencies; target.mode = source.mode; target.effectTag = source.effectTag; target.nextEffect = source.nextEffect; target.firstEffect = source.firstEffect; target.lastEffect = source.lastEffect; target.expirationTime = source.expirationTime; target.childExpirationTime = source.childExpirationTime; target.alternate = source.alternate; if (enableProfilerTimer) { target.actualDuration = source.actualDuration; target.actualStartTime = source.actualStartTime; target.selfBaseDuration = source.selfBaseDuration; target.treeBaseDuration = source.treeBaseDuration; } target._debugID = source._debugID; target._debugSource = source._debugSource; target._debugOwner = source._debugOwner; target._debugIsCurrentlyTiming = source._debugIsCurrentlyTiming; target._debugHookTypes = source._debugHookTypes; return target; } // TODO: This should be lifted into the renderer. // The following attributes are only used by interaction tracing builds. // They enable interactions to be associated with their async work, // And expose interaction metadata to the React DevTools Profiler plugin. // Note that these attributes are only defined when the enableSchedulerTracing flag is enabled. // Exported FiberRoot type includes all properties, // To avoid requiring potentially error-prone :any casts throughout the project. // Profiling properties are only safe to access in profiling builds (when enableSchedulerTracing is true). // The types are defined separately within this file to ensure they stay in sync. // (We don't have to use an inline :any cast when enableSchedulerTracing is disabled.) function createFiberRoot(containerInfo, isConcurrent, hydrate) { // Cyclic construction. This cheats the type system right now because // stateNode is any. var uninitializedFiber = createHostRootFiber(isConcurrent); var root = void 0; if (enableSchedulerTracing) { root = { current: uninitializedFiber, containerInfo: containerInfo, pendingChildren: null, earliestPendingTime: NoWork, latestPendingTime: NoWork, earliestSuspendedTime: NoWork, latestSuspendedTime: NoWork, latestPingedTime: NoWork, pingCache: null, didError: false, pendingCommitExpirationTime: NoWork, finishedWork: null, timeoutHandle: noTimeout, context: null, pendingContext: null, hydrate: hydrate, nextExpirationTimeToWorkOn: NoWork, expirationTime: NoWork, firstBatch: null, nextScheduledRoot: null, interactionThreadID: tracing.unstable_getThreadID(), memoizedInteractions: new Set(), pendingInteractionMap: new Map() }; } else { root = { current: uninitializedFiber, containerInfo: containerInfo, pendingChildren: null, pingCache: null, earliestPendingTime: NoWork, latestPendingTime: NoWork, earliestSuspendedTime: NoWork, latestSuspendedTime: NoWork, latestPingedTime: NoWork, didError: false, pendingCommitExpirationTime: NoWork, finishedWork: null, timeoutHandle: noTimeout, context: null, pendingContext: null, hydrate: hydrate, nextExpirationTimeToWorkOn: NoWork, expirationTime: NoWork, firstBatch: null, nextScheduledRoot: null }; } uninitializedFiber.stateNode = root; // The reason for the way the Flow types are structured in this file, // Is to avoid needing :any casts everywhere interaction tracing fields are used. // Unfortunately that requires an :any cast for non-interaction tracing capable builds. // $FlowFixMe Remove this :any cast and replace it with something better. return root; } /** * Forked from fbjs/warning: * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js * * Only change is we use console.warn instead of console.error, * and do nothing when 'console' is not supported. * This really simplifies the code. * --- * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var lowPriorityWarning = function () {}; { var printWarning = function (format) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.warn(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; lowPriorityWarning = function (condition, format) { if (format === undefined) { throw new Error('`lowPriorityWarning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (!condition) { for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } printWarning.apply(undefined, [format].concat(args)); } }; } var lowPriorityWarning$1 = lowPriorityWarning; var ReactStrictModeWarnings = { discardPendingWarnings: function () {}, flushPendingDeprecationWarnings: function () {}, flushPendingUnsafeLifecycleWarnings: function () {}, recordDeprecationWarnings: function (fiber, instance) {}, recordUnsafeLifecycleWarnings: function (fiber, instance) {}, recordLegacyContextWarning: function (fiber, instance) {}, flushLegacyContextWarning: function () {} }; { var LIFECYCLE_SUGGESTIONS = { UNSAFE_componentWillMount: 'componentDidMount', UNSAFE_componentWillReceiveProps: 'static getDerivedStateFromProps', UNSAFE_componentWillUpdate: 'componentDidUpdate' }; var pendingComponentWillMountWarnings = []; var pendingComponentWillReceivePropsWarnings = []; var pendingComponentWillUpdateWarnings = []; var pendingUnsafeLifecycleWarnings = new Map(); var pendingLegacyContextWarning = new Map(); // Tracks components we have already warned about. var didWarnAboutDeprecatedLifecycles = new Set(); var didWarnAboutUnsafeLifecycles = new Set(); var didWarnAboutLegacyContext = new Set(); var setToSortedString = function (set) { var array = []; set.forEach(function (value) { array.push(value); }); return array.sort().join(', '); }; ReactStrictModeWarnings.discardPendingWarnings = function () { pendingComponentWillMountWarnings = []; pendingComponentWillReceivePropsWarnings = []; pendingComponentWillUpdateWarnings = []; pendingUnsafeLifecycleWarnings = new Map(); pendingLegacyContextWarning = new Map(); }; ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () { pendingUnsafeLifecycleWarnings.forEach(function (lifecycleWarningsMap, strictRoot) { var lifecyclesWarningMessages = []; Object.keys(lifecycleWarningsMap).forEach(function (lifecycle) { var lifecycleWarnings = lifecycleWarningsMap[lifecycle]; if (lifecycleWarnings.length > 0) { var componentNames = new Set(); lifecycleWarnings.forEach(function (fiber) { componentNames.add(getComponentName(fiber.type) || 'Component'); didWarnAboutUnsafeLifecycles.add(fiber.type); }); var formatted = lifecycle.replace('UNSAFE_', ''); var suggestion = LIFECYCLE_SUGGESTIONS[lifecycle]; var sortedComponentNames = setToSortedString(componentNames); lifecyclesWarningMessages.push(formatted + ': Please update the following components to use ' + (suggestion + ' instead: ' + sortedComponentNames)); } }); if (lifecyclesWarningMessages.length > 0) { var strictRootComponentStack = getStackByFiberInDevAndProd(strictRoot); warningWithoutStack$1(false, 'Unsafe lifecycle methods were found within a strict-mode tree:%s' + '\n\n%s' + '\n\nLearn more about this warning here:' + '\nhttps://fb.me/react-strict-mode-warnings', strictRootComponentStack, lifecyclesWarningMessages.join('\n\n')); } }); pendingUnsafeLifecycleWarnings = new Map(); }; var findStrictRoot = function (fiber) { var maybeStrictRoot = null; var node = fiber; while (node !== null) { if (node.mode & StrictMode) { maybeStrictRoot = node; } node = node.return; } return maybeStrictRoot; }; ReactStrictModeWarnings.flushPendingDeprecationWarnings = function () { if (pendingComponentWillMountWarnings.length > 0) { var uniqueNames = new Set(); pendingComponentWillMountWarnings.forEach(function (fiber) { uniqueNames.add(getComponentName(fiber.type) || 'Component'); didWarnAboutDeprecatedLifecycles.add(fiber.type); }); var sortedNames = setToSortedString(uniqueNames); lowPriorityWarning$1(false, 'componentWillMount is deprecated and will be removed in the next major version. ' + 'Use componentDidMount instead. As a temporary workaround, ' + 'you can rename to UNSAFE_componentWillMount.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here:' + '\nhttps://fb.me/react-async-component-lifecycle-hooks', sortedNames); pendingComponentWillMountWarnings = []; } if (pendingComponentWillReceivePropsWarnings.length > 0) { var _uniqueNames = new Set(); pendingComponentWillReceivePropsWarnings.forEach(function (fiber) { _uniqueNames.add(getComponentName(fiber.type) || 'Component'); didWarnAboutDeprecatedLifecycles.add(fiber.type); }); var _sortedNames = setToSortedString(_uniqueNames); lowPriorityWarning$1(false, 'componentWillReceiveProps is deprecated and will be removed in the next major version. ' + 'Use static getDerivedStateFromProps instead.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here:' + '\nhttps://fb.me/react-async-component-lifecycle-hooks', _sortedNames); pendingComponentWillReceivePropsWarnings = []; } if (pendingComponentWillUpdateWarnings.length > 0) { var _uniqueNames2 = new Set(); pendingComponentWillUpdateWarnings.forEach(function (fiber) { _uniqueNames2.add(getComponentName(fiber.type) || 'Component'); didWarnAboutDeprecatedLifecycles.add(fiber.type); }); var _sortedNames2 = setToSortedString(_uniqueNames2); lowPriorityWarning$1(false, 'componentWillUpdate is deprecated and will be removed in the next major version. ' + 'Use componentDidUpdate instead. As a temporary workaround, ' + 'you can rename to UNSAFE_componentWillUpdate.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here:' + '\nhttps://fb.me/react-async-component-lifecycle-hooks', _sortedNames2); pendingComponentWillUpdateWarnings = []; } }; ReactStrictModeWarnings.recordDeprecationWarnings = function (fiber, instance) { // Dedup strategy: Warn once per component. if (didWarnAboutDeprecatedLifecycles.has(fiber.type)) { return; } // Don't warn about react-lifecycles-compat polyfilled components. if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) { pendingComponentWillMountWarnings.push(fiber); } if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) { pendingComponentWillReceivePropsWarnings.push(fiber); } if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) { pendingComponentWillUpdateWarnings.push(fiber); } }; ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) { var strictRoot = findStrictRoot(fiber); if (strictRoot === null) { warningWithoutStack$1(false, 'Expected to find a StrictMode component in a strict mode tree. ' + 'This error is likely caused by a bug in React. Please file an issue.'); return; } // Dedup strategy: Warn once per component. // This is difficult to track any other way since component names // are often vague and are likely to collide between 3rd party libraries. // An expand property is probably okay to use here since it's DEV-only, // and will only be set in the event of serious warnings. if (didWarnAboutUnsafeLifecycles.has(fiber.type)) { return; } var warningsForRoot = void 0; if (!pendingUnsafeLifecycleWarnings.has(strictRoot)) { warningsForRoot = { UNSAFE_componentWillMount: [], UNSAFE_componentWillReceiveProps: [], UNSAFE_componentWillUpdate: [] }; pendingUnsafeLifecycleWarnings.set(strictRoot, warningsForRoot); } else { warningsForRoot = pendingUnsafeLifecycleWarnings.get(strictRoot); } var unsafeLifecycles = []; if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillMount === 'function') { unsafeLifecycles.push('UNSAFE_componentWillMount'); } if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillReceiveProps === 'function') { unsafeLifecycles.push('UNSAFE_componentWillReceiveProps'); } if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true || typeof instance.UNSAFE_componentWillUpdate === 'function') { unsafeLifecycles.push('UNSAFE_componentWillUpdate'); } if (unsafeLifecycles.length > 0) { unsafeLifecycles.forEach(function (lifecycle) { warningsForRoot[lifecycle].push(fiber); }); } }; ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) { var strictRoot = findStrictRoot(fiber); if (strictRoot === null) { warningWithoutStack$1(false, 'Expected to find a StrictMode component in a strict mode tree. ' + 'This error is likely caused by a bug in React. Please file an issue.'); return; } // Dedup strategy: Warn once per component. if (didWarnAboutLegacyContext.has(fiber.type)) { return; } var warningsForRoot = pendingLegacyContextWarning.get(strictRoot); if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') { if (warningsForRoot === undefined) { warningsForRoot = []; pendingLegacyContextWarning.set(strictRoot, warningsForRoot); } warningsForRoot.push(fiber); } }; ReactStrictModeWarnings.flushLegacyContextWarning = function () { pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) { var uniqueNames = new Set(); fiberArray.forEach(function (fiber) { uniqueNames.add(getComponentName(fiber.type) || 'Component'); didWarnAboutLegacyContext.add(fiber.type); }); var sortedNames = setToSortedString(uniqueNames); var strictRootComponentStack = getStackByFiberInDevAndProd(strictRoot); warningWithoutStack$1(false, 'Legacy context API has been detected within a strict-mode tree: %s' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here:' + '\nhttps://fb.me/react-strict-mode-warnings', strictRootComponentStack, sortedNames); }); }; } // This lets us hook into Fiber to debug what it's doing. // See https://github.com/facebook/react/pull/8033. // This is not part of the public API, not even for React DevTools. // You may only inject a debugTool if you work on React Fiber itself. var ReactFiberInstrumentation = { debugTool: null }; var ReactFiberInstrumentation_1 = ReactFiberInstrumentation; // TODO: Offscreen updates should never suspend. However, a promise that // suspended inside an offscreen subtree should be able to ping at the priority // of the outer render. function markPendingPriorityLevel(root, expirationTime) { // If there's a gap between completing a failed root and retrying it, // additional updates may be scheduled. Clear `didError`, in case the update // is sufficient to fix the error. root.didError = false; // Update the latest and earliest pending times var earliestPendingTime = root.earliestPendingTime; if (earliestPendingTime === NoWork) { // No other pending updates. root.earliestPendingTime = root.latestPendingTime = expirationTime; } else { if (earliestPendingTime < expirationTime) { // This is the earliest pending update. root.earliestPendingTime = expirationTime; } else { var latestPendingTime = root.latestPendingTime; if (latestPendingTime > expirationTime) { // This is the latest pending update root.latestPendingTime = expirationTime; } } } findNextExpirationTimeToWorkOn(expirationTime, root); } function markCommittedPriorityLevels(root, earliestRemainingTime) { root.didError = false; if (earliestRemainingTime === NoWork) { // Fast path. There's no remaining work. Clear everything. root.earliestPendingTime = NoWork; root.latestPendingTime = NoWork; root.earliestSuspendedTime = NoWork; root.latestSuspendedTime = NoWork; root.latestPingedTime = NoWork; findNextExpirationTimeToWorkOn(NoWork, root); return; } if (earliestRemainingTime < root.latestPingedTime) { root.latestPingedTime = NoWork; } // Let's see if the previous latest known pending level was just flushed. var latestPendingTime = root.latestPendingTime; if (latestPendingTime !== NoWork) { if (latestPendingTime > earliestRemainingTime) { // We've flushed all the known pending levels. root.earliestPendingTime = root.latestPendingTime = NoWork; } else { var earliestPendingTime = root.earliestPendingTime; if (earliestPendingTime > earliestRemainingTime) { // We've flushed the earliest known pending level. Set this to the // latest pending time. root.earliestPendingTime = root.latestPendingTime; } } } // Now let's handle the earliest remaining level in the whole tree. We need to // decide whether to treat it as a pending level or as suspended. Check // it falls within the range of known suspended levels. var earliestSuspendedTime = root.earliestSuspendedTime; if (earliestSuspendedTime === NoWork) { // There's no suspended work. Treat the earliest remaining level as a // pending level. markPendingPriorityLevel(root, earliestRemainingTime); findNextExpirationTimeToWorkOn(NoWork, root); return; } var latestSuspendedTime = root.latestSuspendedTime; if (earliestRemainingTime < latestSuspendedTime) { // The earliest remaining level is later than all the suspended work. That // means we've flushed all the suspended work. root.earliestSuspendedTime = NoWork; root.latestSuspendedTime = NoWork; root.latestPingedTime = NoWork; // There's no suspended work. Treat the earliest remaining level as a // pending level. markPendingPriorityLevel(root, earliestRemainingTime); findNextExpirationTimeToWorkOn(NoWork, root); return; } if (earliestRemainingTime > earliestSuspendedTime) { // The earliest remaining time is earlier than all the suspended work. // Treat it as a pending update. markPendingPriorityLevel(root, earliestRemainingTime); findNextExpirationTimeToWorkOn(NoWork, root); return; } // The earliest remaining time falls within the range of known suspended // levels. We should treat this as suspended work. findNextExpirationTimeToWorkOn(NoWork, root); } function hasLowerPriorityWork(root, erroredExpirationTime) { var latestPendingTime = root.latestPendingTime; var latestSuspendedTime = root.latestSuspendedTime; var latestPingedTime = root.latestPingedTime; return latestPendingTime !== NoWork && latestPendingTime < erroredExpirationTime || latestSuspendedTime !== NoWork && latestSuspendedTime < erroredExpirationTime || latestPingedTime !== NoWork && latestPingedTime < erroredExpirationTime; } function isPriorityLevelSuspended(root, expirationTime) { var earliestSuspendedTime = root.earliestSuspendedTime; var latestSuspendedTime = root.latestSuspendedTime; return earliestSuspendedTime !== NoWork && expirationTime <= earliestSuspendedTime && expirationTime >= latestSuspendedTime; } function markSuspendedPriorityLevel(root, suspendedTime) { root.didError = false; clearPing(root, suspendedTime); // First, check the known pending levels and update them if needed. var earliestPendingTime = root.earliestPendingTime; var latestPendingTime = root.latestPendingTime; if (earliestPendingTime === suspendedTime) { if (latestPendingTime === suspendedTime) { // Both known pending levels were suspended. Clear them. root.earliestPendingTime = root.latestPendingTime = NoWork; } else { // The earliest pending level was suspended. Clear by setting it to the // latest pending level. root.earliestPendingTime = latestPendingTime; } } else if (latestPendingTime === suspendedTime) { // The latest pending level was suspended. Clear by setting it to the // latest pending level. root.latestPendingTime = earliestPendingTime; } // Finally, update the known suspended levels. var earliestSuspendedTime = root.earliestSuspendedTime; var latestSuspendedTime = root.latestSuspendedTime; if (earliestSuspendedTime === NoWork) { // No other suspended levels. root.earliestSuspendedTime = root.latestSuspendedTime = suspendedTime; } else { if (earliestSuspendedTime < suspendedTime) { // This is the earliest suspended level. root.earliestSuspendedTime = suspendedTime; } else if (latestSuspendedTime > suspendedTime) { // This is the latest suspended level root.latestSuspendedTime = suspendedTime; } } findNextExpirationTimeToWorkOn(suspendedTime, root); } function markPingedPriorityLevel(root, pingedTime) { root.didError = false; // TODO: When we add back resuming, we need to ensure the progressed work // is thrown out and not reused during the restarted render. One way to // invalidate the progressed work is to restart at expirationTime + 1. var latestPingedTime = root.latestPingedTime; if (latestPingedTime === NoWork || latestPingedTime > pingedTime) { root.latestPingedTime = pingedTime; } findNextExpirationTimeToWorkOn(pingedTime, root); } function clearPing(root, completedTime) { var latestPingedTime = root.latestPingedTime; if (latestPingedTime >= completedTime) { root.latestPingedTime = NoWork; } } function findEarliestOutstandingPriorityLevel(root, renderExpirationTime) { var earliestExpirationTime = renderExpirationTime; var earliestPendingTime = root.earliestPendingTime; var earliestSuspendedTime = root.earliestSuspendedTime; if (earliestPendingTime > earliestExpirationTime) { earliestExpirationTime = earliestPendingTime; } if (earliestSuspendedTime > earliestExpirationTime) { earliestExpirationTime = earliestSuspendedTime; } return earliestExpirationTime; } function didExpireAtExpirationTime(root, currentTime) { var expirationTime = root.expirationTime; if (expirationTime !== NoWork && currentTime <= expirationTime) { // The root has expired. Flush all work up to the current time. root.nextExpirationTimeToWorkOn = currentTime; } } function findNextExpirationTimeToWorkOn(completedExpirationTime, root) { var earliestSuspendedTime = root.earliestSuspendedTime; var latestSuspendedTime = root.latestSuspendedTime; var earliestPendingTime = root.earliestPendingTime; var latestPingedTime = root.latestPingedTime; // Work on the earliest pending time. Failing that, work on the latest // pinged time. var nextExpirationTimeToWorkOn = earliestPendingTime !== NoWork ? earliestPendingTime : latestPingedTime; // If there is no pending or pinged work, check if there's suspended work // that's lower priority than what we just completed. if (nextExpirationTimeToWorkOn === NoWork && (completedExpirationTime === NoWork || latestSuspendedTime < completedExpirationTime)) { // The lowest priority suspended work is the work most likely to be // committed next. Let's start rendering it again, so that if it times out, // it's ready to commit. nextExpirationTimeToWorkOn = latestSuspendedTime; } var expirationTime = nextExpirationTimeToWorkOn; if (expirationTime !== NoWork && earliestSuspendedTime > expirationTime) { // Expire using the earliest known expiration time. expirationTime = earliestSuspendedTime; } root.nextExpirationTimeToWorkOn = nextExpirationTimeToWorkOn; root.expirationTime = expirationTime; } function resolveDefaultProps(Component, baseProps) { if (Component && Component.defaultProps) { // Resolve default props. Taken from ReactElement var props = _assign({}, baseProps); var defaultProps = Component.defaultProps; for (var propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } return props; } return baseProps; } function readLazyComponentType(lazyComponent) { var status = lazyComponent._status; var result = lazyComponent._result; switch (status) { case Resolved: { var Component = result; return Component; } case Rejected: { var error = result; throw error; } case Pending: { var thenable = result; throw thenable; } default: { lazyComponent._status = Pending; var ctor = lazyComponent._ctor; var _thenable = ctor(); _thenable.then(function (moduleObject) { if (lazyComponent._status === Pending) { var defaultExport = moduleObject.default; { if (defaultExport === undefined) { warning$1(false, 'lazy: Expected the result of a dynamic import() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + "const MyComponent = lazy(() => import('./MyComponent'))", moduleObject); } } lazyComponent._status = Resolved; lazyComponent._result = defaultExport; } }, function (error) { if (lazyComponent._status === Pending) { lazyComponent._status = Rejected; lazyComponent._result = error; } }); // Handle synchronous thenables. switch (lazyComponent._status) { case Resolved: return lazyComponent._result; case Rejected: throw lazyComponent._result; } lazyComponent._result = _thenable; throw _thenable; } } } var fakeInternalInstance = {}; var isArray$1 = Array.isArray; // React.Component uses a shared frozen object by default. // We'll use it to determine whether we need to initialize legacy refs. var emptyRefsObject = new React.Component().refs; var didWarnAboutStateAssignmentForComponent = void 0; var didWarnAboutUninitializedState = void 0; var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = void 0; var didWarnAboutLegacyLifecyclesAndDerivedState = void 0; var didWarnAboutUndefinedDerivedState = void 0; var warnOnUndefinedDerivedState = void 0; var warnOnInvalidCallback$1 = void 0; var didWarnAboutDirectlyAssigningPropsToState = void 0; var didWarnAboutContextTypeAndContextTypes = void 0; var didWarnAboutInvalidateContextType = void 0; { didWarnAboutStateAssignmentForComponent = new Set(); didWarnAboutUninitializedState = new Set(); didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set(); didWarnAboutLegacyLifecyclesAndDerivedState = new Set(); didWarnAboutDirectlyAssigningPropsToState = new Set(); didWarnAboutUndefinedDerivedState = new Set(); didWarnAboutContextTypeAndContextTypes = new Set(); didWarnAboutInvalidateContextType = new Set(); var didWarnOnInvalidCallback = new Set(); warnOnInvalidCallback$1 = function (callback, callerName) { if (callback === null || typeof callback === 'function') { return; } var key = callerName + '_' + callback; if (!didWarnOnInvalidCallback.has(key)) { didWarnOnInvalidCallback.add(key); warningWithoutStack$1(false, '%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback); } }; warnOnUndefinedDerivedState = function (type, partialState) { if (partialState === undefined) { var componentName = getComponentName(type) || 'Component'; if (!didWarnAboutUndefinedDerivedState.has(componentName)) { didWarnAboutUndefinedDerivedState.add(componentName); warningWithoutStack$1(false, '%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName); } } }; // This is so gross but it's at least non-critical and can be removed if // it causes problems. This is meant to give a nicer error message for // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component, // ...)) which otherwise throws a "_processChildContext is not a function" // exception. Object.defineProperty(fakeInternalInstance, '_processChildContext', { enumerable: false, value: function () { invariant(false, '_processChildContext is not available in React 16+. This likely means you have multiple copies of React and are attempting to nest a React 15 tree inside a React 16 tree using unstable_renderSubtreeIntoContainer, which isn\'t supported. Try to make sure you have only one copy of React (and ideally, switch to ReactDOM.createPortal).'); } }); Object.freeze(fakeInternalInstance); } function applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) { var prevState = workInProgress.memoizedState; { if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) { // Invoke the function an extra time to help detect side-effects. getDerivedStateFromProps(nextProps, prevState); } } var partialState = getDerivedStateFromProps(nextProps, prevState); { warnOnUndefinedDerivedState(ctor, partialState); } // Merge the partial state and the previous state. var memoizedState = partialState === null || partialState === undefined ? prevState : _assign({}, prevState, partialState); workInProgress.memoizedState = memoizedState; // Once the update queue is empty, persist the derived state onto the // base state. var updateQueue = workInProgress.updateQueue; if (updateQueue !== null && workInProgress.expirationTime === NoWork) { updateQueue.baseState = memoizedState; } } var classComponentUpdater = { isMounted: isMounted, enqueueSetState: function (inst, payload, callback) { var fiber = get(inst); var currentTime = requestCurrentTime(); var expirationTime = computeExpirationForFiber(currentTime, fiber); var update = createUpdate(expirationTime); update.payload = payload; if (callback !== undefined && callback !== null) { { warnOnInvalidCallback$1(callback, 'setState'); } update.callback = callback; } flushPassiveEffects(); enqueueUpdate(fiber, update); scheduleWork(fiber, expirationTime); }, enqueueReplaceState: function (inst, payload, callback) { var fiber = get(inst); var currentTime = requestCurrentTime(); var expirationTime = computeExpirationForFiber(currentTime, fiber); var update = createUpdate(expirationTime); update.tag = ReplaceState; update.payload = payload; if (callback !== undefined && callback !== null) { { warnOnInvalidCallback$1(callback, 'replaceState'); } update.callback = callback; } flushPassiveEffects(); enqueueUpdate(fiber, update); scheduleWork(fiber, expirationTime); }, enqueueForceUpdate: function (inst, callback) { var fiber = get(inst); var currentTime = requestCurrentTime(); var expirationTime = computeExpirationForFiber(currentTime, fiber); var update = createUpdate(expirationTime); update.tag = ForceUpdate; if (callback !== undefined && callback !== null) { { warnOnInvalidCallback$1(callback, 'forceUpdate'); } update.callback = callback; } flushPassiveEffects(); enqueueUpdate(fiber, update); scheduleWork(fiber, expirationTime); } }; function checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) { var instance = workInProgress.stateNode; if (typeof instance.shouldComponentUpdate === 'function') { startPhaseTimer(workInProgress, 'shouldComponentUpdate'); var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext); stopPhaseTimer(); { !(shouldUpdate !== undefined) ? warningWithoutStack$1(false, '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', getComponentName(ctor) || 'Component') : void 0; } return shouldUpdate; } if (ctor.prototype && ctor.prototype.isPureReactComponent) { return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState); } return true; } function checkClassInstance(workInProgress, ctor, newProps) { var instance = workInProgress.stateNode; { var name = getComponentName(ctor) || 'Component'; var renderPresent = instance.render; if (!renderPresent) { if (ctor.prototype && typeof ctor.prototype.render === 'function') { warningWithoutStack$1(false, '%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name); } else { warningWithoutStack$1(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name); } } var noGetInitialStateOnES6 = !instance.getInitialState || instance.getInitialState.isReactClassApproved || instance.state; !noGetInitialStateOnES6 ? warningWithoutStack$1(false, 'getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name) : void 0; var noGetDefaultPropsOnES6 = !instance.getDefaultProps || instance.getDefaultProps.isReactClassApproved; !noGetDefaultPropsOnES6 ? warningWithoutStack$1(false, 'getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name) : void 0; var noInstancePropTypes = !instance.propTypes; !noInstancePropTypes ? warningWithoutStack$1(false, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name) : void 0; var noInstanceContextType = !instance.contextType; !noInstanceContextType ? warningWithoutStack$1(false, 'contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name) : void 0; var noInstanceContextTypes = !instance.contextTypes; !noInstanceContextTypes ? warningWithoutStack$1(false, 'contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name) : void 0; if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) { didWarnAboutContextTypeAndContextTypes.add(ctor); warningWithoutStack$1(false, '%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name); } var noComponentShouldUpdate = typeof instance.componentShouldUpdate !== 'function'; !noComponentShouldUpdate ? warningWithoutStack$1(false, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name) : void 0; if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') { warningWithoutStack$1(false, '%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentName(ctor) || 'A pure component'); } var noComponentDidUnmount = typeof instance.componentDidUnmount !== 'function'; !noComponentDidUnmount ? warningWithoutStack$1(false, '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name) : void 0; var noComponentDidReceiveProps = typeof instance.componentDidReceiveProps !== 'function'; !noComponentDidReceiveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name) : void 0; var noComponentWillRecieveProps = typeof instance.componentWillRecieveProps !== 'function'; !noComponentWillRecieveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name) : void 0; var noUnsafeComponentWillRecieveProps = typeof instance.UNSAFE_componentWillRecieveProps !== 'function'; !noUnsafeComponentWillRecieveProps ? warningWithoutStack$1(false, '%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name) : void 0; var hasMutatedProps = instance.props !== newProps; !(instance.props === undefined || !hasMutatedProps) ? warningWithoutStack$1(false, '%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name) : void 0; var noInstanceDefaultProps = !instance.defaultProps; !noInstanceDefaultProps ? warningWithoutStack$1(false, 'Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name) : void 0; if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) { didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor); warningWithoutStack$1(false, '%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentName(ctor)); } var noInstanceGetDerivedStateFromProps = typeof instance.getDerivedStateFromProps !== 'function'; !noInstanceGetDerivedStateFromProps ? warningWithoutStack$1(false, '%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name) : void 0; var noInstanceGetDerivedStateFromCatch = typeof instance.getDerivedStateFromError !== 'function'; !noInstanceGetDerivedStateFromCatch ? warningWithoutStack$1(false, '%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name) : void 0; var noStaticGetSnapshotBeforeUpdate = typeof ctor.getSnapshotBeforeUpdate !== 'function'; !noStaticGetSnapshotBeforeUpdate ? warningWithoutStack$1(false, '%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name) : void 0; var _state = instance.state; if (_state && (typeof _state !== 'object' || isArray$1(_state))) { warningWithoutStack$1(false, '%s.state: must be set to an object or null', name); } if (typeof instance.getChildContext === 'function') { !(typeof ctor.childContextTypes === 'object') ? warningWithoutStack$1(false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name) : void 0; } } } function adoptClassInstance(workInProgress, instance) { instance.updater = classComponentUpdater; workInProgress.stateNode = instance; // The instance needs access to the fiber so that it can schedule updates set(instance, workInProgress); { instance._reactInternalInstance = fakeInternalInstance; } } function constructClassInstance(workInProgress, ctor, props, renderExpirationTime) { var isLegacyContextConsumer = false; var unmaskedContext = emptyContextObject; var context = null; var contextType = ctor.contextType; { if ('contextType' in ctor) { var isValid = // Allow null for conditional declaration contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a <Context.Consumer> if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) { didWarnAboutInvalidateContextType.add(ctor); var addendum = ''; if (contextType === undefined) { addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.'; } else if (typeof contextType !== 'object') { addendum = ' However, it is set to a ' + typeof contextType + '.'; } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) { addendum = ' Did you accidentally pass the Context.Provider instead?'; } else if (contextType._context !== undefined) { // <Context.Consumer> addendum = ' Did you accidentally pass the Context.Consumer instead?'; } else { addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.'; } warningWithoutStack$1(false, '%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentName(ctor) || 'Component', addendum); } } } if (typeof contextType === 'object' && contextType !== null) { context = readContext(contextType); } else { unmaskedContext = getUnmaskedContext(workInProgress, ctor, true); var contextTypes = ctor.contextTypes; isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined; context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject; } // Instantiate twice to help detect side-effects. { if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) { new ctor(props, context); // eslint-disable-line no-new } } var instance = new ctor(props, context); var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null; adoptClassInstance(workInProgress, instance); { if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) { var componentName = getComponentName(ctor) || 'Component'; if (!didWarnAboutUninitializedState.has(componentName)) { didWarnAboutUninitializedState.add(componentName); warningWithoutStack$1(false, '`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName); } } // If new component APIs are defined, "unsafe" lifecycles won't be called. // Warn about these lifecycles if they are present. // Don't warn about react-lifecycles-compat polyfilled methods though. if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') { var foundWillMountName = null; var foundWillReceivePropsName = null; var foundWillUpdateName = null; if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) { foundWillMountName = 'componentWillMount'; } else if (typeof instance.UNSAFE_componentWillMount === 'function') { foundWillMountName = 'UNSAFE_componentWillMount'; } if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) { foundWillReceivePropsName = 'componentWillReceiveProps'; } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') { foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps'; } if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) { foundWillUpdateName = 'componentWillUpdate'; } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') { foundWillUpdateName = 'UNSAFE_componentWillUpdate'; } if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) { var _componentName = getComponentName(ctor) || 'Component'; var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()'; if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) { didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName); warningWithoutStack$1(false, 'Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://fb.me/react-async-component-lifecycle-hooks', _componentName, newApiName, foundWillMountName !== null ? '\n ' + foundWillMountName : '', foundWillReceivePropsName !== null ? '\n ' + foundWillReceivePropsName : '', foundWillUpdateName !== null ? '\n ' + foundWillUpdateName : ''); } } } } // Cache unmasked context so we can avoid recreating masked context unless necessary. // ReactFiberContext usually updates this cache but can't for newly-created instances. if (isLegacyContextConsumer) { cacheContext(workInProgress, unmaskedContext, context); } return instance; } function callComponentWillMount(workInProgress, instance) { startPhaseTimer(workInProgress, 'componentWillMount'); var oldState = instance.state; if (typeof instance.componentWillMount === 'function') { instance.componentWillMount(); } if (typeof instance.UNSAFE_componentWillMount === 'function') { instance.UNSAFE_componentWillMount(); } stopPhaseTimer(); if (oldState !== instance.state) { { warningWithoutStack$1(false, '%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentName(workInProgress.type) || 'Component'); } classComponentUpdater.enqueueReplaceState(instance, instance.state, null); } } function callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) { var oldState = instance.state; startPhaseTimer(workInProgress, 'componentWillReceiveProps'); if (typeof instance.componentWillReceiveProps === 'function') { instance.componentWillReceiveProps(newProps, nextContext); } if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') { instance.UNSAFE_componentWillReceiveProps(newProps, nextContext); } stopPhaseTimer(); if (instance.state !== oldState) { { var componentName = getComponentName(workInProgress.type) || 'Component'; if (!didWarnAboutStateAssignmentForComponent.has(componentName)) { didWarnAboutStateAssignmentForComponent.add(componentName); warningWithoutStack$1(false, '%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName); } } classComponentUpdater.enqueueReplaceState(instance, instance.state, null); } } // Invokes the mount life-cycles on a previously never rendered instance. function mountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) { { checkClassInstance(workInProgress, ctor, newProps); } var instance = workInProgress.stateNode; instance.props = newProps; instance.state = workInProgress.memoizedState; instance.refs = emptyRefsObject; var contextType = ctor.contextType; if (typeof contextType === 'object' && contextType !== null) { instance.context = readContext(contextType); } else { var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true); instance.context = getMaskedContext(workInProgress, unmaskedContext); } { if (instance.state === newProps) { var componentName = getComponentName(ctor) || 'Component'; if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) { didWarnAboutDirectlyAssigningPropsToState.add(componentName); warningWithoutStack$1(false, '%s: It is not recommended to assign props directly to state ' + "because updates to props won't be reflected in state. " + 'In most cases, it is better to use props directly.', componentName); } } if (workInProgress.mode & StrictMode) { ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance); ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance); } if (warnAboutDeprecatedLifecycles) { ReactStrictModeWarnings.recordDeprecationWarnings(workInProgress, instance); } } var updateQueue = workInProgress.updateQueue; if (updateQueue !== null) { processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime); instance.state = workInProgress.memoizedState; } var getDerivedStateFromProps = ctor.getDerivedStateFromProps; if (typeof getDerivedStateFromProps === 'function') { applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps); instance.state = workInProgress.memoizedState; } // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) { callComponentWillMount(workInProgress, instance); // If we had additional state updates during this life-cycle, let's // process them now. updateQueue = workInProgress.updateQueue; if (updateQueue !== null) { processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime); instance.state = workInProgress.memoizedState; } } if (typeof instance.componentDidMount === 'function') { workInProgress.effectTag |= Update; } } function resumeMountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) { var instance = workInProgress.stateNode; var oldProps = workInProgress.memoizedProps; instance.props = oldProps; var oldContext = instance.context; var contextType = ctor.contextType; var nextContext = void 0; if (typeof contextType === 'object' && contextType !== null) { nextContext = readContext(contextType); } else { var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true); nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext); } var getDerivedStateFromProps = ctor.getDerivedStateFromProps; var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what // ever the previously attempted to render - not the "current". However, // during componentDidUpdate we pass the "current" props. // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) { if (oldProps !== newProps || oldContext !== nextContext) { callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext); } } resetHasForceUpdateBeforeProcessing(); var oldState = workInProgress.memoizedState; var newState = instance.state = oldState; var updateQueue = workInProgress.updateQueue; if (updateQueue !== null) { processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime); newState = workInProgress.memoizedState; } if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) { // If an update was already in progress, we should schedule an Update // effect even though we're bailing out, so that cWU/cDU are called. if (typeof instance.componentDidMount === 'function') { workInProgress.effectTag |= Update; } return false; } if (typeof getDerivedStateFromProps === 'function') { applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps); newState = workInProgress.memoizedState; } var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext); if (shouldUpdate) { // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) { startPhaseTimer(workInProgress, 'componentWillMount'); if (typeof instance.componentWillMount === 'function') { instance.componentWillMount(); } if (typeof instance.UNSAFE_componentWillMount === 'function') { instance.UNSAFE_componentWillMount(); } stopPhaseTimer(); } if (typeof instance.componentDidMount === 'function') { workInProgress.effectTag |= Update; } } else { // If an update was already in progress, we should schedule an Update // effect even though we're bailing out, so that cWU/cDU are called. if (typeof instance.componentDidMount === 'function') { workInProgress.effectTag |= Update; } // If shouldComponentUpdate returned false, we should still update the // memoized state to indicate that this work can be reused. workInProgress.memoizedProps = newProps; workInProgress.memoizedState = newState; } // Update the existing instance's state, props, and context pointers even // if shouldComponentUpdate returns false. instance.props = newProps; instance.state = newState; instance.context = nextContext; return shouldUpdate; } // Invokes the update life-cycles and returns false if it shouldn't rerender. function updateClassInstance(current, workInProgress, ctor, newProps, renderExpirationTime) { var instance = workInProgress.stateNode; var oldProps = workInProgress.memoizedProps; instance.props = workInProgress.type === workInProgress.elementType ? oldProps : resolveDefaultProps(workInProgress.type, oldProps); var oldContext = instance.context; var contextType = ctor.contextType; var nextContext = void 0; if (typeof contextType === 'object' && contextType !== null) { nextContext = readContext(contextType); } else { var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true); nextContext = getMaskedContext(workInProgress, nextUnmaskedContext); } var getDerivedStateFromProps = ctor.getDerivedStateFromProps; var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what // ever the previously attempted to render - not the "current". However, // during componentDidUpdate we pass the "current" props. // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) { if (oldProps !== newProps || oldContext !== nextContext) { callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext); } } resetHasForceUpdateBeforeProcessing(); var oldState = workInProgress.memoizedState; var newState = instance.state = oldState; var updateQueue = workInProgress.updateQueue; if (updateQueue !== null) { processUpdateQueue(workInProgress, updateQueue, newProps, instance, renderExpirationTime); newState = workInProgress.memoizedState; } if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) { // If an update was already in progress, we should schedule an Update // effect even though we're bailing out, so that cWU/cDU are called. if (typeof instance.componentDidUpdate === 'function') { if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) { workInProgress.effectTag |= Update; } } if (typeof instance.getSnapshotBeforeUpdate === 'function') { if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) { workInProgress.effectTag |= Snapshot; } } return false; } if (typeof getDerivedStateFromProps === 'function') { applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps); newState = workInProgress.memoizedState; } var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext); if (shouldUpdate) { // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) { startPhaseTimer(workInProgress, 'componentWillUpdate'); if (typeof instance.componentWillUpdate === 'function') { instance.componentWillUpdate(newProps, newState, nextContext); } if (typeof instance.UNSAFE_componentWillUpdate === 'function') { instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext); } stopPhaseTimer(); } if (typeof instance.componentDidUpdate === 'function') { workInProgress.effectTag |= Update; } if (typeof instance.getSnapshotBeforeUpdate === 'function') { workInProgress.effectTag |= Snapshot; } } else { // If an update was already in progress, we should schedule an Update // effect even though we're bailing out, so that cWU/cDU are called. if (typeof instance.componentDidUpdate === 'function') { if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) { workInProgress.effectTag |= Update; } } if (typeof instance.getSnapshotBeforeUpdate === 'function') { if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) { workInProgress.effectTag |= Snapshot; } } // If shouldComponentUpdate returned false, we should still update the // memoized props/state to indicate that this work can be reused. workInProgress.memoizedProps = newProps; workInProgress.memoizedState = newState; } // Update the existing instance's state, props, and context pointers even // if shouldComponentUpdate returns false. instance.props = newProps; instance.state = newState; instance.context = nextContext; return shouldUpdate; } var didWarnAboutMaps = void 0; var didWarnAboutGenerators = void 0; var didWarnAboutStringRefInStrictMode = void 0; var ownerHasKeyUseWarning = void 0; var ownerHasFunctionTypeWarning = void 0; var warnForMissingKey = function (child) {}; { didWarnAboutMaps = false; didWarnAboutGenerators = false; didWarnAboutStringRefInStrictMode = {}; /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ ownerHasKeyUseWarning = {}; ownerHasFunctionTypeWarning = {}; warnForMissingKey = function (child) { if (child === null || typeof child !== 'object') { return; } if (!child._store || child._store.validated || child.key != null) { return; } !(typeof child._store === 'object') ? invariant(false, 'React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue.') : void 0; child._store.validated = true; var currentComponentErrorInfo = 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.' + getCurrentFiberStackInDev(); if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { return; } ownerHasKeyUseWarning[currentComponentErrorInfo] = true; warning$1(false, 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.'); }; } var isArray = Array.isArray; function coerceRef(returnFiber, current$$1, element) { var mixedRef = element.ref; if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') { { if (returnFiber.mode & StrictMode) { var componentName = getComponentName(returnFiber.type) || 'Component'; if (!didWarnAboutStringRefInStrictMode[componentName]) { warningWithoutStack$1(false, 'A string ref, "%s", has been found within a strict mode tree. ' + 'String refs are a source of potential bugs and should be avoided. ' + 'We recommend using createRef() instead.' + '\n%s' + '\n\nLearn more about using refs safely here:' + '\nhttps://fb.me/react-strict-mode-string-ref', mixedRef, getStackByFiberInDevAndProd(returnFiber)); didWarnAboutStringRefInStrictMode[componentName] = true; } } } if (element._owner) { var owner = element._owner; var inst = void 0; if (owner) { var ownerFiber = owner; !(ownerFiber.tag === ClassComponent) ? invariant(false, 'Function components cannot have refs. Did you mean to use React.forwardRef()?') : void 0; inst = ownerFiber.stateNode; } !inst ? invariant(false, 'Missing owner for string ref %s. This error is likely caused by a bug in React. Please file an issue.', mixedRef) : void 0; var stringRef = '' + mixedRef; // Check if previous string ref matches new string ref if (current$$1 !== null && current$$1.ref !== null && typeof current$$1.ref === 'function' && current$$1.ref._stringRef === stringRef) { return current$$1.ref; } var ref = function (value) { var refs = inst.refs; if (refs === emptyRefsObject) { // This is a lazy pooled frozen object, so we need to initialize. refs = inst.refs = {}; } if (value === null) { delete refs[stringRef]; } else { refs[stringRef] = value; } }; ref._stringRef = stringRef; return ref; } else { !(typeof mixedRef === 'string') ? invariant(false, 'Expected ref to be a function, a string, an object returned by React.createRef(), or null.') : void 0; !element._owner ? invariant(false, 'Element ref was specified as a string (%s) but no owner was set. This could happen for one of the following reasons:\n1. You may be adding a ref to a function component\n2. You may be adding a ref to a component that was not created inside a component\'s render method\n3. You have multiple copies of React loaded\nSee https://fb.me/react-refs-must-have-owner for more information.', mixedRef) : void 0; } } return mixedRef; } function throwOnInvalidObjectType(returnFiber, newChild) { if (returnFiber.type !== 'textarea') { var addendum = ''; { addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + getCurrentFiberStackInDev(); } invariant(false, 'Objects are not valid as a React child (found: %s).%s', Object.prototype.toString.call(newChild) === '[object Object]' ? 'object with keys {' + Object.keys(newChild).join(', ') + '}' : newChild, addendum); } } function warnOnFunctionType() { var currentComponentErrorInfo = 'Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.' + getCurrentFiberStackInDev(); if (ownerHasFunctionTypeWarning[currentComponentErrorInfo]) { return; } ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true; warning$1(false, 'Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.'); } // This wrapper function exists because I expect to clone the code in each path // to be able to optimize each path individually by branching early. This needs // a compiler or we can do it manually. Helpers that don't need this branching // live outside of this function. function ChildReconciler(shouldTrackSideEffects) { function deleteChild(returnFiber, childToDelete) { if (!shouldTrackSideEffects) { // Noop. return; } // Deletions are added in reversed order so we add it to the front. // At this point, the return fiber's effect list is empty except for // deletions, so we can just append the deletion to the list. The remaining // effects aren't added until the complete phase. Once we implement // resuming, this may not be true. var last = returnFiber.lastEffect; if (last !== null) { last.nextEffect = childToDelete; returnFiber.lastEffect = childToDelete; } else { returnFiber.firstEffect = returnFiber.lastEffect = childToDelete; } childToDelete.nextEffect = null; childToDelete.effectTag = Deletion; } function deleteRemainingChildren(returnFiber, currentFirstChild) { if (!shouldTrackSideEffects) { // Noop. return null; } // TODO: For the shouldClone case, this could be micro-optimized a bit by // assuming that after the first child we've already added everything. var childToDelete = currentFirstChild; while (childToDelete !== null) { deleteChild(returnFiber, childToDelete); childToDelete = childToDelete.sibling; } return null; } function mapRemainingChildren(returnFiber, currentFirstChild) { // Add the remaining children to a temporary map so that we can find them by // keys quickly. Implicit (null) keys get added to this set with their index var existingChildren = new Map(); var existingChild = currentFirstChild; while (existingChild !== null) { if (existingChild.key !== null) { existingChildren.set(existingChild.key, existingChild); } else { existingChildren.set(existingChild.index, existingChild); } existingChild = existingChild.sibling; } return existingChildren; } function useFiber(fiber, pendingProps, expirationTime) { // We currently set sibling to null and index to 0 here because it is easy // to forget to do before returning it. E.g. for the single child case. var clone = createWorkInProgress(fiber, pendingProps, expirationTime); clone.index = 0; clone.sibling = null; return clone; } function placeChild(newFiber, lastPlacedIndex, newIndex) { newFiber.index = newIndex; if (!shouldTrackSideEffects) { // Noop. return lastPlacedIndex; } var current$$1 = newFiber.alternate; if (current$$1 !== null) { var oldIndex = current$$1.index; if (oldIndex < lastPlacedIndex) { // This is a move. newFiber.effectTag = Placement; return lastPlacedIndex; } else { // This item can stay in place. return oldIndex; } } else { // This is an insertion. newFiber.effectTag = Placement; return lastPlacedIndex; } } function placeSingleChild(newFiber) { // This is simpler for the single child case. We only need to do a // placement for inserting new children. if (shouldTrackSideEffects && newFiber.alternate === null) { newFiber.effectTag = Placement; } return newFiber; } function updateTextNode(returnFiber, current$$1, textContent, expirationTime) { if (current$$1 === null || current$$1.tag !== HostText) { // Insert var created = createFiberFromText(textContent, returnFiber.mode, expirationTime); created.return = returnFiber; return created; } else { // Update var existing = useFiber(current$$1, textContent, expirationTime); existing.return = returnFiber; return existing; } } function updateElement(returnFiber, current$$1, element, expirationTime) { if (current$$1 !== null && current$$1.elementType === element.type) { // Move based on index var existing = useFiber(current$$1, element.props, expirationTime); existing.ref = coerceRef(returnFiber, current$$1, element); existing.return = returnFiber; { existing._debugSource = element._source; existing._debugOwner = element._owner; } return existing; } else { // Insert var created = createFiberFromElement(element, returnFiber.mode, expirationTime); created.ref = coerceRef(returnFiber, current$$1, element); created.return = returnFiber; return created; } } function updatePortal(returnFiber, current$$1, portal, expirationTime) { if (current$$1 === null || current$$1.tag !== HostPortal || current$$1.stateNode.containerInfo !== portal.containerInfo || current$$1.stateNode.implementation !== portal.implementation) { // Insert var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime); created.return = returnFiber; return created; } else { // Update var existing = useFiber(current$$1, portal.children || [], expirationTime); existing.return = returnFiber; return existing; } } function updateFragment(returnFiber, current$$1, fragment, expirationTime, key) { if (current$$1 === null || current$$1.tag !== Fragment) { // Insert var created = createFiberFromFragment(fragment, returnFiber.mode, expirationTime, key); created.return = returnFiber; return created; } else { // Update var existing = useFiber(current$$1, fragment, expirationTime); existing.return = returnFiber; return existing; } } function createChild(returnFiber, newChild, expirationTime) { if (typeof newChild === 'string' || typeof newChild === 'number') { // Text nodes don't have keys. If the previous node is implicitly keyed // we can continue to replace it without aborting even if it is not a text // node. var created = createFiberFromText('' + newChild, returnFiber.mode, expirationTime); created.return = returnFiber; return created; } if (typeof newChild === 'object' && newChild !== null) { switch (newChild.$$typeof) { case REACT_ELEMENT_TYPE: { var _created = createFiberFromElement(newChild, returnFiber.mode, expirationTime); _created.ref = coerceRef(returnFiber, null, newChild); _created.return = returnFiber; return _created; } case REACT_PORTAL_TYPE: { var _created2 = createFiberFromPortal(newChild, returnFiber.mode, expirationTime); _created2.return = returnFiber; return _created2; } } if (isArray(newChild) || getIteratorFn(newChild)) { var _created3 = createFiberFromFragment(newChild, returnFiber.mode, expirationTime, null); _created3.return = returnFiber; return _created3; } throwOnInvalidObjectType(returnFiber, newChild); } { if (typeof newChild === 'function') { warnOnFunctionType(); } } return null; } function updateSlot(returnFiber, oldFiber, newChild, expirationTime) { // Update the fiber if the keys match, otherwise return null. var key = oldFiber !== null ? oldFiber.key : null; if (typeof newChild === 'string' || typeof newChild === 'number') { // Text nodes don't have keys. If the previous node is implicitly keyed // we can continue to replace it without aborting even if it is not a text // node. if (key !== null) { return null; } return updateTextNode(returnFiber, oldFiber, '' + newChild, expirationTime); } if (typeof newChild === 'object' && newChild !== null) { switch (newChild.$$typeof) { case REACT_ELEMENT_TYPE: { if (newChild.key === key) { if (newChild.type === REACT_FRAGMENT_TYPE) { return updateFragment(returnFiber, oldFiber, newChild.props.children, expirationTime, key); } return updateElement(returnFiber, oldFiber, newChild, expirationTime); } else { return null; } } case REACT_PORTAL_TYPE: { if (newChild.key === key) { return updatePortal(returnFiber, oldFiber, newChild, expirationTime); } else { return null; } } } if (isArray(newChild) || getIteratorFn(newChild)) { if (key !== null) { return null; } return updateFragment(returnFiber, oldFiber, newChild, expirationTime, null); } throwOnInvalidObjectType(returnFiber, newChild); } { if (typeof newChild === 'function') { warnOnFunctionType(); } } return null; } function updateFromMap(existingChildren, returnFiber, newIdx, newChild, expirationTime) { if (typeof newChild === 'string' || typeof newChild === 'number') { // Text nodes don't have keys, so we neither have to check the old nor // new node for the key. If both are text nodes, they match. var matchedFiber = existingChildren.get(newIdx) || null; return updateTextNode(returnFiber, matchedFiber, '' + newChild, expirationTime); } if (typeof newChild === 'object' && newChild !== null) { switch (newChild.$$typeof) { case REACT_ELEMENT_TYPE: { var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null; if (newChild.type === REACT_FRAGMENT_TYPE) { return updateFragment(returnFiber, _matchedFiber, newChild.props.children, expirationTime, newChild.key); } return updateElement(returnFiber, _matchedFiber, newChild, expirationTime); } case REACT_PORTAL_TYPE: { var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null; return updatePortal(returnFiber, _matchedFiber2, newChild, expirationTime); } } if (isArray(newChild) || getIteratorFn(newChild)) { var _matchedFiber3 = existingChildren.get(newIdx) || null; return updateFragment(returnFiber, _matchedFiber3, newChild, expirationTime, null); } throwOnInvalidObjectType(returnFiber, newChild); } { if (typeof newChild === 'function') { warnOnFunctionType(); } } return null; } /** * Warns if there is a duplicate or missing key */ function warnOnInvalidKey(child, knownKeys) { { if (typeof child !== 'object' || child === null) { return knownKeys; } switch (child.$$typeof) { case REACT_ELEMENT_TYPE: case REACT_PORTAL_TYPE: warnForMissingKey(child); var key = child.key; if (typeof key !== 'string') { break; } if (knownKeys === null) { knownKeys = new Set(); knownKeys.add(key); break; } if (!knownKeys.has(key)) { knownKeys.add(key); break; } warning$1(false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.', key); break; default: break; } } return knownKeys; } function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, expirationTime) { // This algorithm can't optimize by searching from both ends since we // don't have backpointers on fibers. I'm trying to see how far we can get // with that model. If it ends up not being worth the tradeoffs, we can // add it later. // Even with a two ended optimization, we'd want to optimize for the case // where there are few changes and brute force the comparison instead of // going for the Map. It'd like to explore hitting that path first in // forward-only mode and only go for the Map once we notice that we need // lots of look ahead. This doesn't handle reversal as well as two ended // search but that's unusual. Besides, for the two ended optimization to // work on Iterables, we'd need to copy the whole set. // In this first iteration, we'll just live with hitting the bad case // (adding everything to a Map) in for every insert/move. // If you change this code, also update reconcileChildrenIterator() which // uses the same algorithm. { // First, validate keys. var knownKeys = null; for (var i = 0; i < newChildren.length; i++) { var child = newChildren[i]; knownKeys = warnOnInvalidKey(child, knownKeys); } } var resultingFirstChild = null; var previousNewFiber = null; var oldFiber = currentFirstChild; var lastPlacedIndex = 0; var newIdx = 0; var nextOldFiber = null; for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) { if (oldFiber.index > newIdx) { nextOldFiber = oldFiber; oldFiber = null; } else { nextOldFiber = oldFiber.sibling; } var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], expirationTime); if (newFiber === null) { // TODO: This breaks on empty slots like null children. That's // unfortunate because it triggers the slow path all the time. We need // a better way to communicate whether this was a miss or null, // boolean, undefined, etc. if (oldFiber === null) { oldFiber = nextOldFiber; } break; } if (shouldTrackSideEffects) { if (oldFiber && newFiber.alternate === null) { // We matched the slot, but we didn't reuse the existing fiber, so we // need to delete the existing child. deleteChild(returnFiber, oldFiber); } } lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = newFiber; } else { // TODO: Defer siblings if we're not at the right index for this slot. // I.e. if we had null values before, then we want to defer this // for each null value. However, we also don't want to call updateSlot // with the previous one. previousNewFiber.sibling = newFiber; } previousNewFiber = newFiber; oldFiber = nextOldFiber; } if (newIdx === newChildren.length) { // We've reached the end of the new children. We can delete the rest. deleteRemainingChildren(returnFiber, oldFiber); return resultingFirstChild; } if (oldFiber === null) { // If we don't have any more existing children we can choose a fast path // since the rest will all be insertions. for (; newIdx < newChildren.length; newIdx++) { var _newFiber = createChild(returnFiber, newChildren[newIdx], expirationTime); if (!_newFiber) { continue; } lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx); if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = _newFiber; } else { previousNewFiber.sibling = _newFiber; } previousNewFiber = _newFiber; } return resultingFirstChild; } // Add all children to a key map for quick lookups. var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves. for (; newIdx < newChildren.length; newIdx++) { var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], expirationTime); if (_newFiber2) { if (shouldTrackSideEffects) { if (_newFiber2.alternate !== null) { // The new fiber is a work in progress, but if there exists a // current, that means that we reused the fiber. We need to delete // it from the child list so that we don't add it to the deletion // list. existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key); } } lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx); if (previousNewFiber === null) { resultingFirstChild = _newFiber2; } else { previousNewFiber.sibling = _newFiber2; } previousNewFiber = _newFiber2; } } if (shouldTrackSideEffects) { // Any existing children that weren't consumed above were deleted. We need // to add them to the deletion list. existingChildren.forEach(function (child) { return deleteChild(returnFiber, child); }); } return resultingFirstChild; } function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, expirationTime) { // This is the same implementation as reconcileChildrenArray(), // but using the iterator instead. var iteratorFn = getIteratorFn(newChildrenIterable); !(typeof iteratorFn === 'function') ? invariant(false, 'An object is not an iterable. This error is likely caused by a bug in React. Please file an issue.') : void 0; { // We don't support rendering Generators because it's a mutation. // See https://github.com/facebook/react/issues/12995 if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag newChildrenIterable[Symbol.toStringTag] === 'Generator') { !didWarnAboutGenerators ? warning$1(false, 'Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.') : void 0; didWarnAboutGenerators = true; } // Warn about using Maps as children if (newChildrenIterable.entries === iteratorFn) { !didWarnAboutMaps ? warning$1(false, 'Using Maps as children is unsupported and will likely yield ' + 'unexpected results. Convert it to a sequence/iterable of keyed ' + 'ReactElements instead.') : void 0; didWarnAboutMaps = true; } // First, validate keys. // We'll get a different iterator later for the main pass. var _newChildren = iteratorFn.call(newChildrenIterable); if (_newChildren) { var knownKeys = null; var _step = _newChildren.next(); for (; !_step.done; _step = _newChildren.next()) { var child = _step.value; knownKeys = warnOnInvalidKey(child, knownKeys); } } } var newChildren = iteratorFn.call(newChildrenIterable); !(newChildren != null) ? invariant(false, 'An iterable object provided no iterator.') : void 0; var resultingFirstChild = null; var previousNewFiber = null; var oldFiber = currentFirstChild; var lastPlacedIndex = 0; var newIdx = 0; var nextOldFiber = null; var step = newChildren.next(); for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) { if (oldFiber.index > newIdx) { nextOldFiber = oldFiber; oldFiber = null; } else { nextOldFiber = oldFiber.sibling; } var newFiber = updateSlot(returnFiber, oldFiber, step.value, expirationTime); if (newFiber === null) { // TODO: This breaks on empty slots like null children. That's // unfortunate because it triggers the slow path all the time. We need // a better way to communicate whether this was a miss or null, // boolean, undefined, etc. if (!oldFiber) { oldFiber = nextOldFiber; } break; } if (shouldTrackSideEffects) { if (oldFiber && newFiber.alternate === null) { // We matched the slot, but we didn't reuse the existing fiber, so we // need to delete the existing child. deleteChild(returnFiber, oldFiber); } } lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = newFiber; } else { // TODO: Defer siblings if we're not at the right index for this slot. // I.e. if we had null values before, then we want to defer this // for each null value. However, we also don't want to call updateSlot // with the previous one. previousNewFiber.sibling = newFiber; } previousNewFiber = newFiber; oldFiber = nextOldFiber; } if (step.done) { // We've reached the end of the new children. We can delete the rest. deleteRemainingChildren(returnFiber, oldFiber); return resultingFirstChild; } if (oldFiber === null) { // If we don't have any more existing children we can choose a fast path // since the rest will all be insertions. for (; !step.done; newIdx++, step = newChildren.next()) { var _newFiber3 = createChild(returnFiber, step.value, expirationTime); if (_newFiber3 === null) { continue; } lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx); if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = _newFiber3; } else { previousNewFiber.sibling = _newFiber3; } previousNewFiber = _newFiber3; } return resultingFirstChild; } // Add all children to a key map for quick lookups. var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves. for (; !step.done; newIdx++, step = newChildren.next()) { var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, expirationTime); if (_newFiber4 !== null) { if (shouldTrackSideEffects) { if (_newFiber4.alternate !== null) { // The new fiber is a work in progress, but if there exists a // current, that means that we reused the fiber. We need to delete // it from the child list so that we don't add it to the deletion // list. existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key); } } lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx); if (previousNewFiber === null) { resultingFirstChild = _newFiber4; } else { previousNewFiber.sibling = _newFiber4; } previousNewFiber = _newFiber4; } } if (shouldTrackSideEffects) { // Any existing children that weren't consumed above were deleted. We need // to add them to the deletion list. existingChildren.forEach(function (child) { return deleteChild(returnFiber, child); }); } return resultingFirstChild; } function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, expirationTime) { // There's no need to check for keys on text nodes since we don't have a // way to define them. if (currentFirstChild !== null && currentFirstChild.tag === HostText) { // We already have an existing node so let's just update it and delete // the rest. deleteRemainingChildren(returnFiber, currentFirstChild.sibling); var existing = useFiber(currentFirstChild, textContent, expirationTime); existing.return = returnFiber; return existing; } // The existing first child is not a text node so we need to create one // and delete the existing ones. deleteRemainingChildren(returnFiber, currentFirstChild); var created = createFiberFromText(textContent, returnFiber.mode, expirationTime); created.return = returnFiber; return created; } function reconcileSingleElement(returnFiber, currentFirstChild, element, expirationTime) { var key = element.key; var child = currentFirstChild; while (child !== null) { // TODO: If key === null and child.key === null, then this only applies to // the first item in the list. if (child.key === key) { if (child.tag === Fragment ? element.type === REACT_FRAGMENT_TYPE : child.elementType === element.type) { deleteRemainingChildren(returnFiber, child.sibling); var existing = useFiber(child, element.type === REACT_FRAGMENT_TYPE ? element.props.children : element.props, expirationTime); existing.ref = coerceRef(returnFiber, child, element); existing.return = returnFiber; { existing._debugSource = element._source; existing._debugOwner = element._owner; } return existing; } else { deleteRemainingChildren(returnFiber, child); break; } } else { deleteChild(returnFiber, child); } child = child.sibling; } if (element.type === REACT_FRAGMENT_TYPE) { var created = createFiberFromFragment(element.props.children, returnFiber.mode, expirationTime, element.key); created.return = returnFiber; return created; } else { var _created4 = createFiberFromElement(element, returnFiber.mode, expirationTime); _created4.ref = coerceRef(returnFiber, currentFirstChild, element); _created4.return = returnFiber; return _created4; } } function reconcileSinglePortal(returnFiber, currentFirstChild, portal, expirationTime) { var key = portal.key; var child = currentFirstChild; while (child !== null) { // TODO: If key === null and child.key === null, then this only applies to // the first item in the list. if (child.key === key) { if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) { deleteRemainingChildren(returnFiber, child.sibling); var existing = useFiber(child, portal.children || [], expirationTime); existing.return = returnFiber; return existing; } else { deleteRemainingChildren(returnFiber, child); break; } } else { deleteChild(returnFiber, child); } child = child.sibling; } var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime); created.return = returnFiber; return created; } // This API will tag the children with the side-effect of the reconciliation // itself. They will be added to the side-effect list as we pass through the // children and the parent. function reconcileChildFibers(returnFiber, currentFirstChild, newChild, expirationTime) { // This function is not recursive. // If the top level item is an array, we treat it as a set of children, // not as a fragment. Nested arrays on the other hand will be treated as // fragment nodes. Recursion happens at the normal flow. // Handle top level unkeyed fragments as if they were arrays. // This leads to an ambiguity between <>{[...]}</> and <>...</>. // We treat the ambiguous cases above the same. var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null; if (isUnkeyedTopLevelFragment) { newChild = newChild.props.children; } // Handle object types var isObject = typeof newChild === 'object' && newChild !== null; if (isObject) { switch (newChild.$$typeof) { case REACT_ELEMENT_TYPE: return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, expirationTime)); case REACT_PORTAL_TYPE: return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, expirationTime)); } } if (typeof newChild === 'string' || typeof newChild === 'number') { return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, expirationTime)); } if (isArray(newChild)) { return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, expirationTime); } if (getIteratorFn(newChild)) { return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, expirationTime); } if (isObject) { throwOnInvalidObjectType(returnFiber, newChild); } { if (typeof newChild === 'function') { warnOnFunctionType(); } } if (typeof newChild === 'undefined' && !isUnkeyedTopLevelFragment) { // If the new child is undefined, and the return fiber is a composite // component, throw an error. If Fiber return types are disabled, // we already threw above. switch (returnFiber.tag) { case ClassComponent: { { var instance = returnFiber.stateNode; if (instance.render._isMockFunction) { // We allow auto-mocks to proceed as if they're returning null. break; } } } // Intentionally fall through to the next case, which handles both // functions and classes // eslint-disable-next-lined no-fallthrough case FunctionComponent: { var Component = returnFiber.type; invariant(false, '%s(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.', Component.displayName || Component.name || 'Component'); } } } // Remaining cases are all treated as empty. return deleteRemainingChildren(returnFiber, currentFirstChild); } return reconcileChildFibers; } var reconcileChildFibers = ChildReconciler(true); var mountChildFibers = ChildReconciler(false); function cloneChildFibers(current$$1, workInProgress) { !(current$$1 === null || workInProgress.child === current$$1.child) ? invariant(false, 'Resuming work not yet implemented.') : void 0; if (workInProgress.child === null) { return; } var currentChild = workInProgress.child; var newChild = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime); workInProgress.child = newChild; newChild.return = workInProgress; while (currentChild.sibling !== null) { currentChild = currentChild.sibling; newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps, currentChild.expirationTime); newChild.return = workInProgress; } newChild.sibling = null; } var NO_CONTEXT = {}; var contextStackCursor$1 = createCursor(NO_CONTEXT); var contextFiberStackCursor = createCursor(NO_CONTEXT); var rootInstanceStackCursor = createCursor(NO_CONTEXT); function requiredContext(c) { !(c !== NO_CONTEXT) ? invariant(false, 'Expected host context to exist. This error is likely caused by a bug in React. Please file an issue.') : void 0; return c; } function getRootHostContainer() { var rootInstance = requiredContext(rootInstanceStackCursor.current); return rootInstance; } function pushHostContainer(fiber, nextRootInstance) { // Push current root instance onto the stack; // This allows us to reset root when portals are popped. push(rootInstanceStackCursor, nextRootInstance, fiber); // Track the context and the Fiber that provided it. // This enables us to pop only Fibers that provide unique contexts. push(contextFiberStackCursor, fiber, fiber); // Finally, we need to push the host context to the stack. // However, we can't just call getRootHostContext() and push it because // we'd have a different number of entries on the stack depending on // whether getRootHostContext() throws somewhere in renderer code or not. // So we push an empty value first. This lets us safely unwind on errors. push(contextStackCursor$1, NO_CONTEXT, fiber); var nextRootContext = getRootHostContext(nextRootInstance); // Now that we know this function doesn't throw, replace it. pop(contextStackCursor$1, fiber); push(contextStackCursor$1, nextRootContext, fiber); } function popHostContainer(fiber) { pop(contextStackCursor$1, fiber); pop(contextFiberStackCursor, fiber); pop(rootInstanceStackCursor, fiber); } function getHostContext() { var context = requiredContext(contextStackCursor$1.current); return context; } function pushHostContext(fiber) { var rootInstance = requiredContext(rootInstanceStackCursor.current); var context = requiredContext(contextStackCursor$1.current); var nextContext = getChildHostContext(context, fiber.type, rootInstance); // Don't push this Fiber's context unless it's unique. if (context === nextContext) { return; } // Track the context and the Fiber that provided it. // This enables us to pop only Fibers that provide unique contexts. push(contextFiberStackCursor, fiber, fiber); push(contextStackCursor$1, nextContext, fiber); } function popHostContext(fiber) { // Do not pop unless this Fiber provided the current context. // pushHostContext() only pushes Fibers that provide unique contexts. if (contextFiberStackCursor.current !== fiber) { return; } pop(contextStackCursor$1, fiber); pop(contextFiberStackCursor, fiber); } var NoEffect$1 = /* */0; var UnmountSnapshot = /* */2; var UnmountMutation = /* */4; var MountMutation = /* */8; var UnmountLayout = /* */16; var MountLayout = /* */32; var MountPassive = /* */64; var UnmountPassive = /* */128; var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; var didWarnAboutMismatchedHooksForComponent = void 0; { didWarnAboutMismatchedHooksForComponent = new Set(); } // These are set right before calling the component. var renderExpirationTime = NoWork; // The work-in-progress fiber. I've named it differently to distinguish it from // the work-in-progress hook. var currentlyRenderingFiber$1 = null; // Hooks are stored as a linked list on the fiber's memoizedState field. The // current hook list is the list that belongs to the current fiber. The // work-in-progress hook list is a new list that will be added to the // work-in-progress fiber. var currentHook = null; var nextCurrentHook = null; var firstWorkInProgressHook = null; var workInProgressHook = null; var nextWorkInProgressHook = null; var remainingExpirationTime = NoWork; var componentUpdateQueue = null; var sideEffectTag = 0; // Updates scheduled during render will trigger an immediate re-render at the // end of the current pass. We can't store these updates on the normal queue, // because if the work is aborted, they should be discarded. Because this is // a relatively rare case, we also don't want to add an additional field to // either the hook or queue object types. So we store them in a lazily create // map of queue -> render-phase updates, which are discarded once the component // completes without re-rendering. // Whether an update was scheduled during the currently executing render pass. var didScheduleRenderPhaseUpdate = false; // Lazily created map of render-phase updates var renderPhaseUpdates = null; // Counter to prevent infinite loops. var numberOfReRenders = 0; var RE_RENDER_LIMIT = 25; // In DEV, this is the name of the currently executing primitive hook var currentHookNameInDev = null; // In DEV, this list ensures that hooks are called in the same order between renders. // The list stores the order of hooks used during the initial render (mount). // Subsequent renders (updates) reference this list. var hookTypesDev = null; var hookTypesUpdateIndexDev = -1; function mountHookTypesDev() { { var hookName = currentHookNameInDev; if (hookTypesDev === null) { hookTypesDev = [hookName]; } else { hookTypesDev.push(hookName); } } } function updateHookTypesDev() { { var hookName = currentHookNameInDev; if (hookTypesDev !== null) { hookTypesUpdateIndexDev++; if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) { warnOnHookMismatchInDev(hookName); } } } } function warnOnHookMismatchInDev(currentHookName) { { var componentName = getComponentName(currentlyRenderingFiber$1.type); if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) { didWarnAboutMismatchedHooksForComponent.add(componentName); if (hookTypesDev !== null) { var table = ''; var secondColumnStart = 30; for (var i = 0; i <= hookTypesUpdateIndexDev; i++) { var oldHookName = hookTypesDev[i]; var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName; var row = i + 1 + '. ' + oldHookName; // Extra space so second column lines up // lol @ IE not supporting String#repeat while (row.length < secondColumnStart) { row += ' '; } row += newHookName + '\n'; table += row; } warning$1(false, 'React has detected a change in the order of Hooks called by %s. ' + 'This will lead to bugs and errors if not fixed. ' + 'For more information, read the Rules of Hooks: https://fb.me/rules-of-hooks\n\n' + ' Previous render Next render\n' + ' ------------------------------------------------------\n' + '%s' + ' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n', componentName, table); } } } } function throwInvalidHookError() { invariant(false, 'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.'); } function areHookInputsEqual(nextDeps, prevDeps) { if (prevDeps === null) { { warning$1(false, '%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev); } return false; } { // Don't bother comparing lengths in prod because these arrays should be // passed inline. if (nextDeps.length !== prevDeps.length) { warning$1(false, 'The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, '[' + nextDeps.join(', ') + ']', '[' + prevDeps.join(', ') + ']'); } } for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) { if (is(nextDeps[i], prevDeps[i])) { continue; } return false; } return true; } function renderWithHooks(current, workInProgress, Component, props, refOrContext, nextRenderExpirationTime) { renderExpirationTime = nextRenderExpirationTime; currentlyRenderingFiber$1 = workInProgress; nextCurrentHook = current !== null ? current.memoizedState : null; { hookTypesDev = current !== null ? current._debugHookTypes : null; hookTypesUpdateIndexDev = -1; } // The following should have already been reset // currentHook = null; // workInProgressHook = null; // remainingExpirationTime = NoWork; // componentUpdateQueue = null; // didScheduleRenderPhaseUpdate = false; // renderPhaseUpdates = null; // numberOfReRenders = 0; // sideEffectTag = 0; // TODO Warn if no hooks are used at all during mount, then some are used during update. // Currently we will identify the update render as a mount because nextCurrentHook === null. // This is tricky because it's valid for certain types of components (e.g. React.lazy) // Using nextCurrentHook to differentiate between mount/update only works if at least one stateful hook is used. // Non-stateful hooks (e.g. context) don't get added to memoizedState, // so nextCurrentHook would be null during updates and mounts. { if (nextCurrentHook !== null) { ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV; } else if (hookTypesDev !== null) { // This dispatcher handles an edge case where a component is updating, // but no stateful hooks have been used. // We want to match the production code behavior (which will use HooksDispatcherOnMount), // but with the extra DEV validation to ensure hooks ordering hasn't changed. // This dispatcher does that. ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV; } else { ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV; } } var children = Component(props, refOrContext); if (didScheduleRenderPhaseUpdate) { do { didScheduleRenderPhaseUpdate = false; numberOfReRenders += 1; // Start over from the beginning of the list nextCurrentHook = current !== null ? current.memoizedState : null; nextWorkInProgressHook = firstWorkInProgressHook; currentHook = null; workInProgressHook = null; componentUpdateQueue = null; { // Also validate hook order for cascading updates. hookTypesUpdateIndexDev = -1; } ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV; children = Component(props, refOrContext); } while (didScheduleRenderPhaseUpdate); renderPhaseUpdates = null; numberOfReRenders = 0; } // We can assume the previous dispatcher is always this one, since we set it // at the beginning of the render phase and there's no re-entrancy. ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; var renderedWork = currentlyRenderingFiber$1; renderedWork.memoizedState = firstWorkInProgressHook; renderedWork.expirationTime = remainingExpirationTime; renderedWork.updateQueue = componentUpdateQueue; renderedWork.effectTag |= sideEffectTag; { renderedWork._debugHookTypes = hookTypesDev; } // This check uses currentHook so that it works the same in DEV and prod bundles. // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles. var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null; renderExpirationTime = NoWork; currentlyRenderingFiber$1 = null; currentHook = null; nextCurrentHook = null; firstWorkInProgressHook = null; workInProgressHook = null; nextWorkInProgressHook = null; { currentHookNameInDev = null; hookTypesDev = null; hookTypesUpdateIndexDev = -1; } remainingExpirationTime = NoWork; componentUpdateQueue = null; sideEffectTag = 0; // These were reset above // didScheduleRenderPhaseUpdate = false; // renderPhaseUpdates = null; // numberOfReRenders = 0; !!didRenderTooFewHooks ? invariant(false, 'Rendered fewer hooks than expected. This may be caused by an accidental early return statement.') : void 0; return children; } function bailoutHooks(current, workInProgress, expirationTime) { workInProgress.updateQueue = current.updateQueue; workInProgress.effectTag &= ~(Passive | Update); if (current.expirationTime <= expirationTime) { current.expirationTime = NoWork; } } function resetHooks() { // We can assume the previous dispatcher is always this one, since we set it // at the beginning of the render phase and there's no re-entrancy. ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; // This is used to reset the state of this module when a component throws. // It's also called inside mountIndeterminateComponent if we determine the // component is a module-style component. renderExpirationTime = NoWork; currentlyRenderingFiber$1 = null; currentHook = null; nextCurrentHook = null; firstWorkInProgressHook = null; workInProgressHook = null; nextWorkInProgressHook = null; { hookTypesDev = null; hookTypesUpdateIndexDev = -1; currentHookNameInDev = null; } remainingExpirationTime = NoWork; componentUpdateQueue = null; sideEffectTag = 0; didScheduleRenderPhaseUpdate = false; renderPhaseUpdates = null; numberOfReRenders = 0; } function mountWorkInProgressHook() { var hook = { memoizedState: null, baseState: null, queue: null, baseUpdate: null, next: null }; if (workInProgressHook === null) { // This is the first hook in the list firstWorkInProgressHook = workInProgressHook = hook; } else { // Append to the end of the list workInProgressHook = workInProgressHook.next = hook; } return workInProgressHook; } function updateWorkInProgressHook() { // This function is used both for updates and for re-renders triggered by a // render phase update. It assumes there is either a current hook we can // clone, or a work-in-progress hook from a previous render pass that we can // use as a base. When we reach the end of the base list, we must switch to // the dispatcher used for mounts. if (nextWorkInProgressHook !== null) { // There's already a work-in-progress. Reuse it. workInProgressHook = nextWorkInProgressHook; nextWorkInProgressHook = workInProgressHook.next; currentHook = nextCurrentHook; nextCurrentHook = currentHook !== null ? currentHook.next : null; } else { // Clone from the current hook. !(nextCurrentHook !== null) ? invariant(false, 'Rendered more hooks than during the previous render.') : void 0; currentHook = nextCurrentHook; var newHook = { memoizedState: currentHook.memoizedState, baseState: currentHook.baseState, queue: currentHook.queue, baseUpdate: currentHook.baseUpdate, next: null }; if (workInProgressHook === null) { // This is the first hook in the list. workInProgressHook = firstWorkInProgressHook = newHook; } else { // Append to the end of the list. workInProgressHook = workInProgressHook.next = newHook; } nextCurrentHook = currentHook.next; } return workInProgressHook; } function createFunctionComponentUpdateQueue() { return { lastEffect: null }; } function basicStateReducer(state, action) { return typeof action === 'function' ? action(state) : action; } function mountReducer(reducer, initialArg, init) { var hook = mountWorkInProgressHook(); var initialState = void 0; if (init !== undefined) { initialState = init(initialArg); } else { initialState = initialArg; } hook.memoizedState = hook.baseState = initialState; var queue = hook.queue = { last: null, dispatch: null, lastRenderedReducer: reducer, lastRenderedState: initialState }; var dispatch = queue.dispatch = dispatchAction.bind(null, // Flow doesn't know this is non-null, but we do. currentlyRenderingFiber$1, queue); return [hook.memoizedState, dispatch]; } function updateReducer(reducer, initialArg, init) { var hook = updateWorkInProgressHook(); var queue = hook.queue; !(queue !== null) ? invariant(false, 'Should have a queue. This is likely a bug in React. Please file an issue.') : void 0; queue.lastRenderedReducer = reducer; if (numberOfReRenders > 0) { // This is a re-render. Apply the new render phase updates to the previous var _dispatch = queue.dispatch; if (renderPhaseUpdates !== null) { // Render phase updates are stored in a map of queue -> linked list var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); if (firstRenderPhaseUpdate !== undefined) { renderPhaseUpdates.delete(queue); var newState = hook.memoizedState; var update = firstRenderPhaseUpdate; do { // Process this render phase update. We don't have to check the // priority because it will always be the same as the current // render's. var _action = update.action; newState = reducer(newState, _action); update = update.next; } while (update !== null); // Mark that the fiber performed work, but only if the new state is // different from the current state. if (!is(newState, hook.memoizedState)) { markWorkInProgressReceivedUpdate(); } hook.memoizedState = newState; // Don't persist the state accumlated from the render phase updates to // the base state unless the queue is empty. // TODO: Not sure if this is the desired semantics, but it's what we // do for gDSFP. I can't remember why. if (hook.baseUpdate === queue.last) { hook.baseState = newState; } queue.lastRenderedState = newState; return [newState, _dispatch]; } } return [hook.memoizedState, _dispatch]; } // The last update in the entire queue var last = queue.last; // The last update that is part of the base state. var baseUpdate = hook.baseUpdate; var baseState = hook.baseState; // Find the first unprocessed update. var first = void 0; if (baseUpdate !== null) { if (last !== null) { // For the first update, the queue is a circular linked list where // `queue.last.next = queue.first`. Once the first update commits, and // the `baseUpdate` is no longer empty, we can unravel the list. last.next = null; } first = baseUpdate.next; } else { first = last !== null ? last.next : null; } if (first !== null) { var _newState = baseState; var newBaseState = null; var newBaseUpdate = null; var prevUpdate = baseUpdate; var _update = first; var didSkip = false; do { var updateExpirationTime = _update.expirationTime; if (updateExpirationTime < renderExpirationTime) { // Priority is insufficient. Skip this update. If this is the first // skipped update, the previous update/state is the new base // update/state. if (!didSkip) { didSkip = true; newBaseUpdate = prevUpdate; newBaseState = _newState; } // Update the remaining priority in the queue. if (updateExpirationTime > remainingExpirationTime) { remainingExpirationTime = updateExpirationTime; } } else { // Process this update. if (_update.eagerReducer === reducer) { // If this update was processed eagerly, and its reducer matches the // current reducer, we can use the eagerly computed state. _newState = _update.eagerState; } else { var _action2 = _update.action; _newState = reducer(_newState, _action2); } } prevUpdate = _update; _update = _update.next; } while (_update !== null && _update !== first); if (!didSkip) { newBaseUpdate = prevUpdate; newBaseState = _newState; } // Mark that the fiber performed work, but only if the new state is // different from the current state. if (!is(_newState, hook.memoizedState)) { markWorkInProgressReceivedUpdate(); } hook.memoizedState = _newState; hook.baseUpdate = newBaseUpdate; hook.baseState = newBaseState; queue.lastRenderedState = _newState; } var dispatch = queue.dispatch; return [hook.memoizedState, dispatch]; } function mountState(initialState) { var hook = mountWorkInProgressHook(); if (typeof initialState === 'function') { initialState = initialState(); } hook.memoizedState = hook.baseState = initialState; var queue = hook.queue = { last: null, dispatch: null, lastRenderedReducer: basicStateReducer, lastRenderedState: initialState }; var dispatch = queue.dispatch = dispatchAction.bind(null, // Flow doesn't know this is non-null, but we do. currentlyRenderingFiber$1, queue); return [hook.memoizedState, dispatch]; } function updateState(initialState) { return updateReducer(basicStateReducer, initialState); } function pushEffect(tag, create, destroy, deps) { var effect = { tag: tag, create: create, destroy: destroy, deps: deps, // Circular next: null }; if (componentUpdateQueue === null) { componentUpdateQueue = createFunctionComponentUpdateQueue(); componentUpdateQueue.lastEffect = effect.next = effect; } else { var _lastEffect = componentUpdateQueue.lastEffect; if (_lastEffect === null) { componentUpdateQueue.lastEffect = effect.next = effect; } else { var firstEffect = _lastEffect.next; _lastEffect.next = effect; effect.next = firstEffect; componentUpdateQueue.lastEffect = effect; } } return effect; } function mountRef(initialValue) { var hook = mountWorkInProgressHook(); var ref = { current: initialValue }; { Object.seal(ref); } hook.memoizedState = ref; return ref; } function updateRef(initialValue) { var hook = updateWorkInProgressHook(); return hook.memoizedState; } function mountEffectImpl(fiberEffectTag, hookEffectTag, create, deps) { var hook = mountWorkInProgressHook(); var nextDeps = deps === undefined ? null : deps; sideEffectTag |= fiberEffectTag; hook.memoizedState = pushEffect(hookEffectTag, create, undefined, nextDeps); } function updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) { var hook = updateWorkInProgressHook(); var nextDeps = deps === undefined ? null : deps; var destroy = undefined; if (currentHook !== null) { var prevEffect = currentHook.memoizedState; destroy = prevEffect.destroy; if (nextDeps !== null) { var prevDeps = prevEffect.deps; if (areHookInputsEqual(nextDeps, prevDeps)) { pushEffect(NoEffect$1, create, destroy, nextDeps); return; } } } sideEffectTag |= fiberEffectTag; hook.memoizedState = pushEffect(hookEffectTag, create, destroy, nextDeps); } function mountEffect(create, deps) { return mountEffectImpl(Update | Passive, UnmountPassive | MountPassive, create, deps); } function updateEffect(create, deps) { return updateEffectImpl(Update | Passive, UnmountPassive | MountPassive, create, deps); } function mountLayoutEffect(create, deps) { return mountEffectImpl(Update, UnmountMutation | MountLayout, create, deps); } function updateLayoutEffect(create, deps) { return updateEffectImpl(Update, UnmountMutation | MountLayout, create, deps); } function imperativeHandleEffect(create, ref) { if (typeof ref === 'function') { var refCallback = ref; var _inst = create(); refCallback(_inst); return function () { refCallback(null); }; } else if (ref !== null && ref !== undefined) { var refObject = ref; { !refObject.hasOwnProperty('current') ? warning$1(false, 'Expected useImperativeHandle() first argument to either be a ' + 'ref callback or React.createRef() object. Instead received: %s.', 'an object with keys {' + Object.keys(refObject).join(', ') + '}') : void 0; } var _inst2 = create(); refObject.current = _inst2; return function () { refObject.current = null; }; } } function mountImperativeHandle(ref, create, deps) { { !(typeof create === 'function') ? warning$1(false, 'Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null') : void 0; } // TODO: If deps are provided, should we skip comparing the ref itself? var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null; return mountEffectImpl(Update, UnmountMutation | MountLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps); } function updateImperativeHandle(ref, create, deps) { { !(typeof create === 'function') ? warning$1(false, 'Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null') : void 0; } // TODO: If deps are provided, should we skip comparing the ref itself? var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null; return updateEffectImpl(Update, UnmountMutation | MountLayout, imperativeHandleEffect.bind(null, create, ref), effectDeps); } function mountDebugValue(value, formatterFn) { // This hook is normally a no-op. // The react-debug-hooks package injects its own implementation // so that e.g. DevTools can display custom hook values. } var updateDebugValue = mountDebugValue; function mountCallback(callback, deps) { var hook = mountWorkInProgressHook(); var nextDeps = deps === undefined ? null : deps; hook.memoizedState = [callback, nextDeps]; return callback; } function updateCallback(callback, deps) { var hook = updateWorkInProgressHook(); var nextDeps = deps === undefined ? null : deps; var prevState = hook.memoizedState; if (prevState !== null) { if (nextDeps !== null) { var prevDeps = prevState[1]; if (areHookInputsEqual(nextDeps, prevDeps)) { return prevState[0]; } } } hook.memoizedState = [callback, nextDeps]; return callback; } function mountMemo(nextCreate, deps) { var hook = mountWorkInProgressHook(); var nextDeps = deps === undefined ? null : deps; var nextValue = nextCreate(); hook.memoizedState = [nextValue, nextDeps]; return nextValue; } function updateMemo(nextCreate, deps) { var hook = updateWorkInProgressHook(); var nextDeps = deps === undefined ? null : deps; var prevState = hook.memoizedState; if (prevState !== null) { // Assume these are defined. If they're not, areHookInputsEqual will warn. if (nextDeps !== null) { var prevDeps = prevState[1]; if (areHookInputsEqual(nextDeps, prevDeps)) { return prevState[0]; } } } var nextValue = nextCreate(); hook.memoizedState = [nextValue, nextDeps]; return nextValue; } // in a test-like environment, we want to warn if dispatchAction() // is called outside of a batchedUpdates/TestUtils.act(...) call. var shouldWarnForUnbatchedSetState = false; { // jest isn't a 'global', it's just exposed to tests via a wrapped function // further, this isn't a test file, so flow doesn't recognize the symbol. So... // $FlowExpectedError - because requirements don't give a damn about your type sigs. if ('undefined' !== typeof jest) { shouldWarnForUnbatchedSetState = true; } } function dispatchAction(fiber, queue, action) { !(numberOfReRenders < RE_RENDER_LIMIT) ? invariant(false, 'Too many re-renders. React limits the number of renders to prevent an infinite loop.') : void 0; { !(arguments.length <= 3) ? warning$1(false, "State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().') : void 0; } var alternate = fiber.alternate; if (fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1) { // This is a render phase update. Stash it in a lazily-created map of // queue -> linked list of updates. After this render pass, we'll restart // and apply the stashed updates on top of the work-in-progress hook. didScheduleRenderPhaseUpdate = true; var update = { expirationTime: renderExpirationTime, action: action, eagerReducer: null, eagerState: null, next: null }; if (renderPhaseUpdates === null) { renderPhaseUpdates = new Map(); } var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); if (firstRenderPhaseUpdate === undefined) { renderPhaseUpdates.set(queue, update); } else { // Append the update to the end of the list. var lastRenderPhaseUpdate = firstRenderPhaseUpdate; while (lastRenderPhaseUpdate.next !== null) { lastRenderPhaseUpdate = lastRenderPhaseUpdate.next; } lastRenderPhaseUpdate.next = update; } } else { flushPassiveEffects(); var currentTime = requestCurrentTime(); var _expirationTime = computeExpirationForFiber(currentTime, fiber); var _update2 = { expirationTime: _expirationTime, action: action, eagerReducer: null, eagerState: null, next: null }; // Append the update to the end of the list. var _last = queue.last; if (_last === null) { // This is the first update. Create a circular list. _update2.next = _update2; } else { var first = _last.next; if (first !== null) { // Still circular. _update2.next = first; } _last.next = _update2; } queue.last = _update2; if (fiber.expirationTime === NoWork && (alternate === null || alternate.expirationTime === NoWork)) { // The queue is currently empty, which means we can eagerly compute the // next state before entering the render phase. If the new state is the // same as the current state, we may be able to bail out entirely. var _lastRenderedReducer = queue.lastRenderedReducer; if (_lastRenderedReducer !== null) { var prevDispatcher = void 0; { prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; } try { var currentState = queue.lastRenderedState; var _eagerState = _lastRenderedReducer(currentState, action); // Stash the eagerly computed state, and the reducer used to compute // it, on the update object. If the reducer hasn't changed by the // time we enter the render phase, then the eager state can be used // without calling the reducer again. _update2.eagerReducer = _lastRenderedReducer; _update2.eagerState = _eagerState; if (is(_eagerState, currentState)) { // Fast path. We can bail out without scheduling React to re-render. // It's still possible that we'll need to rebase this update later, // if the component re-renders for a different reason and by that // time the reducer has changed. return; } } catch (error) { // Suppress the error. It will throw again in the render phase. } finally { { ReactCurrentDispatcher$1.current = prevDispatcher; } } } } { if (shouldWarnForUnbatchedSetState === true) { warnIfNotCurrentlyBatchingInDev(fiber); } } scheduleWork(fiber, _expirationTime); } } var ContextOnlyDispatcher = { readContext: readContext, useCallback: throwInvalidHookError, useContext: throwInvalidHookError, useEffect: throwInvalidHookError, useImperativeHandle: throwInvalidHookError, useLayoutEffect: throwInvalidHookError, useMemo: throwInvalidHookError, useReducer: throwInvalidHookError, useRef: throwInvalidHookError, useState: throwInvalidHookError, useDebugValue: throwInvalidHookError }; var HooksDispatcherOnMountInDEV = null; var HooksDispatcherOnMountWithHookTypesInDEV = null; var HooksDispatcherOnUpdateInDEV = null; var InvalidNestedHooksDispatcherOnMountInDEV = null; var InvalidNestedHooksDispatcherOnUpdateInDEV = null; { var warnInvalidContextAccess = function () { warning$1(false, 'Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); }; var warnInvalidHookAccess = function () { warning$1(false, 'Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://fb.me/rules-of-hooks'); }; HooksDispatcherOnMountInDEV = { readContext: function (context, observedBits) { return readContext(context, observedBits); }, useCallback: function (callback, deps) { currentHookNameInDev = 'useCallback'; mountHookTypesDev(); return mountCallback(callback, deps); }, useContext: function (context, observedBits) { currentHookNameInDev = 'useContext'; mountHookTypesDev(); return readContext(context, observedBits); }, useEffect: function (create, deps) { currentHookNameInDev = 'useEffect'; mountHookTypesDev(); return mountEffect(create, deps); }, useImperativeHandle: function (ref, create, deps) { currentHookNameInDev = 'useImperativeHandle'; mountHookTypesDev(); return mountImperativeHandle(ref, create, deps); }, useLayoutEffect: function (create, deps) { currentHookNameInDev = 'useLayoutEffect'; mountHookTypesDev(); return mountLayoutEffect(create, deps); }, useMemo: function (create, deps) { currentHookNameInDev = 'useMemo'; mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountMemo(create, deps); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useReducer: function (reducer, initialArg, init) { currentHookNameInDev = 'useReducer'; mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountReducer(reducer, initialArg, init); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useRef: function (initialValue) { currentHookNameInDev = 'useRef'; mountHookTypesDev(); return mountRef(initialValue); }, useState: function (initialState) { currentHookNameInDev = 'useState'; mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountState(initialState); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useDebugValue: function (value, formatterFn) { currentHookNameInDev = 'useDebugValue'; mountHookTypesDev(); return mountDebugValue(value, formatterFn); } }; HooksDispatcherOnMountWithHookTypesInDEV = { readContext: function (context, observedBits) { return readContext(context, observedBits); }, useCallback: function (callback, deps) { currentHookNameInDev = 'useCallback'; updateHookTypesDev(); return mountCallback(callback, deps); }, useContext: function (context, observedBits) { currentHookNameInDev = 'useContext'; updateHookTypesDev(); return readContext(context, observedBits); }, useEffect: function (create, deps) { currentHookNameInDev = 'useEffect'; updateHookTypesDev(); return mountEffect(create, deps); }, useImperativeHandle: function (ref, create, deps) { currentHookNameInDev = 'useImperativeHandle'; updateHookTypesDev(); return mountImperativeHandle(ref, create, deps); }, useLayoutEffect: function (create, deps) { currentHookNameInDev = 'useLayoutEffect'; updateHookTypesDev(); return mountLayoutEffect(create, deps); }, useMemo: function (create, deps) { currentHookNameInDev = 'useMemo'; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountMemo(create, deps); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useReducer: function (reducer, initialArg, init) { currentHookNameInDev = 'useReducer'; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountReducer(reducer, initialArg, init); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useRef: function (initialValue) { currentHookNameInDev = 'useRef'; updateHookTypesDev(); return mountRef(initialValue); }, useState: function (initialState) { currentHookNameInDev = 'useState'; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountState(initialState); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useDebugValue: function (value, formatterFn) { currentHookNameInDev = 'useDebugValue'; updateHookTypesDev(); return mountDebugValue(value, formatterFn); } }; HooksDispatcherOnUpdateInDEV = { readContext: function (context, observedBits) { return readContext(context, observedBits); }, useCallback: function (callback, deps) { currentHookNameInDev = 'useCallback'; updateHookTypesDev(); return updateCallback(callback, deps); }, useContext: function (context, observedBits) { currentHookNameInDev = 'useContext'; updateHookTypesDev(); return readContext(context, observedBits); }, useEffect: function (create, deps) { currentHookNameInDev = 'useEffect'; updateHookTypesDev(); return updateEffect(create, deps); }, useImperativeHandle: function (ref, create, deps) { currentHookNameInDev = 'useImperativeHandle'; updateHookTypesDev(); return updateImperativeHandle(ref, create, deps); }, useLayoutEffect: function (create, deps) { currentHookNameInDev = 'useLayoutEffect'; updateHookTypesDev(); return updateLayoutEffect(create, deps); }, useMemo: function (create, deps) { currentHookNameInDev = 'useMemo'; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return updateMemo(create, deps); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useReducer: function (reducer, initialArg, init) { currentHookNameInDev = 'useReducer'; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return updateReducer(reducer, initialArg, init); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useRef: function (initialValue) { currentHookNameInDev = 'useRef'; updateHookTypesDev(); return updateRef(initialValue); }, useState: function (initialState) { currentHookNameInDev = 'useState'; updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return updateState(initialState); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useDebugValue: function (value, formatterFn) { currentHookNameInDev = 'useDebugValue'; updateHookTypesDev(); return updateDebugValue(value, formatterFn); } }; InvalidNestedHooksDispatcherOnMountInDEV = { readContext: function (context, observedBits) { warnInvalidContextAccess(); return readContext(context, observedBits); }, useCallback: function (callback, deps) { currentHookNameInDev = 'useCallback'; warnInvalidHookAccess(); mountHookTypesDev(); return mountCallback(callback, deps); }, useContext: function (context, observedBits) { currentHookNameInDev = 'useContext'; warnInvalidHookAccess(); mountHookTypesDev(); return readContext(context, observedBits); }, useEffect: function (create, deps) { currentHookNameInDev = 'useEffect'; warnInvalidHookAccess(); mountHookTypesDev(); return mountEffect(create, deps); }, useImperativeHandle: function (ref, create, deps) { currentHookNameInDev = 'useImperativeHandle'; warnInvalidHookAccess(); mountHookTypesDev(); return mountImperativeHandle(ref, create, deps); }, useLayoutEffect: function (create, deps) { currentHookNameInDev = 'useLayoutEffect'; warnInvalidHookAccess(); mountHookTypesDev(); return mountLayoutEffect(create, deps); }, useMemo: function (create, deps) { currentHookNameInDev = 'useMemo'; warnInvalidHookAccess(); mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountMemo(create, deps); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useReducer: function (reducer, initialArg, init) { currentHookNameInDev = 'useReducer'; warnInvalidHookAccess(); mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountReducer(reducer, initialArg, init); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useRef: function (initialValue) { currentHookNameInDev = 'useRef'; warnInvalidHookAccess(); mountHookTypesDev(); return mountRef(initialValue); }, useState: function (initialState) { currentHookNameInDev = 'useState'; warnInvalidHookAccess(); mountHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV; try { return mountState(initialState); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useDebugValue: function (value, formatterFn) { currentHookNameInDev = 'useDebugValue'; warnInvalidHookAccess(); mountHookTypesDev(); return mountDebugValue(value, formatterFn); } }; InvalidNestedHooksDispatcherOnUpdateInDEV = { readContext: function (context, observedBits) { warnInvalidContextAccess(); return readContext(context, observedBits); }, useCallback: function (callback, deps) { currentHookNameInDev = 'useCallback'; warnInvalidHookAccess(); updateHookTypesDev(); return updateCallback(callback, deps); }, useContext: function (context, observedBits) { currentHookNameInDev = 'useContext'; warnInvalidHookAccess(); updateHookTypesDev(); return readContext(context, observedBits); }, useEffect: function (create, deps) { currentHookNameInDev = 'useEffect'; warnInvalidHookAccess(); updateHookTypesDev(); return updateEffect(create, deps); }, useImperativeHandle: function (ref, create, deps) { currentHookNameInDev = 'useImperativeHandle'; warnInvalidHookAccess(); updateHookTypesDev(); return updateImperativeHandle(ref, create, deps); }, useLayoutEffect: function (create, deps) { currentHookNameInDev = 'useLayoutEffect'; warnInvalidHookAccess(); updateHookTypesDev(); return updateLayoutEffect(create, deps); }, useMemo: function (create, deps) { currentHookNameInDev = 'useMemo'; warnInvalidHookAccess(); updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return updateMemo(create, deps); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useReducer: function (reducer, initialArg, init) { currentHookNameInDev = 'useReducer'; warnInvalidHookAccess(); updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return updateReducer(reducer, initialArg, init); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useRef: function (initialValue) { currentHookNameInDev = 'useRef'; warnInvalidHookAccess(); updateHookTypesDev(); return updateRef(initialValue); }, useState: function (initialState) { currentHookNameInDev = 'useState'; warnInvalidHookAccess(); updateHookTypesDev(); var prevDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV; try { return updateState(initialState); } finally { ReactCurrentDispatcher$1.current = prevDispatcher; } }, useDebugValue: function (value, formatterFn) { currentHookNameInDev = 'useDebugValue'; warnInvalidHookAccess(); updateHookTypesDev(); return updateDebugValue(value, formatterFn); } }; } var commitTime = 0; var profilerStartTime = -1; function getCommitTime() { return commitTime; } function recordCommitTime() { if (!enableProfilerTimer) { return; } commitTime = scheduler.unstable_now(); } function startProfilerTimer(fiber) { if (!enableProfilerTimer) { return; } profilerStartTime = scheduler.unstable_now(); if (fiber.actualStartTime < 0) { fiber.actualStartTime = scheduler.unstable_now(); } } function stopProfilerTimerIfRunning(fiber) { if (!enableProfilerTimer) { return; } profilerStartTime = -1; } function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) { if (!enableProfilerTimer) { return; } if (profilerStartTime >= 0) { var elapsedTime = scheduler.unstable_now() - profilerStartTime; fiber.actualDuration += elapsedTime; if (overrideBaseTime) { fiber.selfBaseDuration = elapsedTime; } profilerStartTime = -1; } } // The deepest Fiber on the stack involved in a hydration context. // This may have been an insertion or a hydration. var hydrationParentFiber = null; var nextHydratableInstance = null; var isHydrating = false; function enterHydrationState(fiber) { if (!supportsHydration) { return false; } var parentInstance = fiber.stateNode.containerInfo; nextHydratableInstance = getFirstHydratableChild(parentInstance); hydrationParentFiber = fiber; isHydrating = true; return true; } function reenterHydrationStateFromDehydratedSuspenseInstance(fiber) { if (!supportsHydration) { return false; } var suspenseInstance = fiber.stateNode; nextHydratableInstance = getNextHydratableSibling(suspenseInstance); popToNextHostParent(fiber); isHydrating = true; return true; } function deleteHydratableInstance(returnFiber, instance) { { switch (returnFiber.tag) { case HostRoot: didNotHydrateContainerInstance(returnFiber.stateNode.containerInfo, instance); break; case HostComponent: didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance); break; } } var childToDelete = createFiberFromHostInstanceForDeletion(); childToDelete.stateNode = instance; childToDelete.return = returnFiber; childToDelete.effectTag = Deletion; // This might seem like it belongs on progressedFirstDeletion. However, // these children are not part of the reconciliation list of children. // Even if we abort and rereconcile the children, that will try to hydrate // again and the nodes are still in the host tree so these will be // recreated. if (returnFiber.lastEffect !== null) { returnFiber.lastEffect.nextEffect = childToDelete; returnFiber.lastEffect = childToDelete; } else { returnFiber.firstEffect = returnFiber.lastEffect = childToDelete; } } function insertNonHydratedInstance(returnFiber, fiber) { fiber.effectTag |= Placement; { switch (returnFiber.tag) { case HostRoot: { var parentContainer = returnFiber.stateNode.containerInfo; switch (fiber.tag) { case HostComponent: var type = fiber.type; var props = fiber.pendingProps; didNotFindHydratableContainerInstance(parentContainer, type, props); break; case HostText: var text = fiber.pendingProps; didNotFindHydratableContainerTextInstance(parentContainer, text); break; case SuspenseComponent: break; } break; } case HostComponent: { var parentType = returnFiber.type; var parentProps = returnFiber.memoizedProps; var parentInstance = returnFiber.stateNode; switch (fiber.tag) { case HostComponent: var _type = fiber.type; var _props = fiber.pendingProps; didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type, _props); break; case HostText: var _text = fiber.pendingProps; didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text); break; case SuspenseComponent: didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance); break; } break; } default: return; } } } function tryHydrate(fiber, nextInstance) { switch (fiber.tag) { case HostComponent: { var type = fiber.type; var props = fiber.pendingProps; var instance = canHydrateInstance(nextInstance, type, props); if (instance !== null) { fiber.stateNode = instance; return true; } return false; } case HostText: { var text = fiber.pendingProps; var textInstance = canHydrateTextInstance(nextInstance, text); if (textInstance !== null) { fiber.stateNode = textInstance; return true; } return false; } case SuspenseComponent: { if (enableSuspenseServerRenderer) { var suspenseInstance = canHydrateSuspenseInstance(nextInstance); if (suspenseInstance !== null) { // Downgrade the tag to a dehydrated component until we've hydrated it. fiber.tag = DehydratedSuspenseComponent; fiber.stateNode = suspenseInstance; return true; } } return false; } default: return false; } } function tryToClaimNextHydratableInstance(fiber) { if (!isHydrating) { return; } var nextInstance = nextHydratableInstance; if (!nextInstance) { // Nothing to hydrate. Make it an insertion. insertNonHydratedInstance(hydrationParentFiber, fiber); isHydrating = false; hydrationParentFiber = fiber; return; } var firstAttemptedInstance = nextInstance; if (!tryHydrate(fiber, nextInstance)) { // If we can't hydrate this instance let's try the next one. // We use this as a heuristic. It's based on intuition and not data so it // might be flawed or unnecessary. nextInstance = getNextHydratableSibling(firstAttemptedInstance); if (!nextInstance || !tryHydrate(fiber, nextInstance)) { // Nothing to hydrate. Make it an insertion. insertNonHydratedInstance(hydrationParentFiber, fiber); isHydrating = false; hydrationParentFiber = fiber; return; } // We matched the next one, we'll now assume that the first one was // superfluous and we'll delete it. Since we can't eagerly delete it // we'll have to schedule a deletion. To do that, this node needs a dummy // fiber associated with it. deleteHydratableInstance(hydrationParentFiber, firstAttemptedInstance); } hydrationParentFiber = fiber; nextHydratableInstance = getFirstHydratableChild(nextInstance); } function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) { if (!supportsHydration) { invariant(false, 'Expected prepareToHydrateHostInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.'); } var instance = fiber.stateNode; var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber); // TODO: Type this specific to this type of component. fiber.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there // is a new ref we mark this as an update. if (updatePayload !== null) { return true; } return false; } function prepareToHydrateHostTextInstance(fiber) { if (!supportsHydration) { invariant(false, 'Expected prepareToHydrateHostTextInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.'); } var textInstance = fiber.stateNode; var textContent = fiber.memoizedProps; var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber); { if (shouldUpdate) { // We assume that prepareToHydrateHostTextInstance is called in a context where the // hydration parent is the parent host component of this host text. var returnFiber = hydrationParentFiber; if (returnFiber !== null) { switch (returnFiber.tag) { case HostRoot: { var parentContainer = returnFiber.stateNode.containerInfo; didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent); break; } case HostComponent: { var parentType = returnFiber.type; var parentProps = returnFiber.memoizedProps; var parentInstance = returnFiber.stateNode; didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent); break; } } } } } return shouldUpdate; } function skipPastDehydratedSuspenseInstance(fiber) { if (!supportsHydration) { invariant(false, 'Expected skipPastDehydratedSuspenseInstance() to never be called. This error is likely caused by a bug in React. Please file an issue.'); } var suspenseInstance = fiber.stateNode; !suspenseInstance ? invariant(false, 'Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue.') : void 0; nextHydratableInstance = getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance); } function popToNextHostParent(fiber) { var parent = fiber.return; while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== DehydratedSuspenseComponent) { parent = parent.return; } hydrationParentFiber = parent; } function popHydrationState(fiber) { if (!supportsHydration) { return false; } if (fiber !== hydrationParentFiber) { // We're deeper than the current hydration context, inside an inserted // tree. return false; } if (!isHydrating) { // If we're not currently hydrating but we're in a hydration context, then // we were an insertion and now need to pop up reenter hydration of our // siblings. popToNextHostParent(fiber); isHydrating = true; return false; } var type = fiber.type; // If we have any remaining hydratable nodes, we need to delete them now. // We only do this deeper than head and body since they tend to have random // other nodes in them. We also ignore components with pure text content in // side of them. // TODO: Better heuristic. if (fiber.tag !== HostComponent || type !== 'head' && type !== 'body' && !shouldSetTextContent(type, fiber.memoizedProps)) { var nextInstance = nextHydratableInstance; while (nextInstance) { deleteHydratableInstance(fiber, nextInstance); nextInstance = getNextHydratableSibling(nextInstance); } } popToNextHostParent(fiber); nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null; return true; } function resetHydrationState() { if (!supportsHydration) { return; } hydrationParentFiber = null; nextHydratableInstance = null; isHydrating = false; } var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner; var didReceiveUpdate = false; var didWarnAboutBadClass = void 0; var didWarnAboutContextTypeOnFunctionComponent = void 0; var didWarnAboutGetDerivedStateOnFunctionComponent = void 0; var didWarnAboutFunctionRefs = void 0; var didWarnAboutReassigningProps = void 0; { didWarnAboutBadClass = {}; didWarnAboutContextTypeOnFunctionComponent = {}; didWarnAboutGetDerivedStateOnFunctionComponent = {}; didWarnAboutFunctionRefs = {}; didWarnAboutReassigningProps = false; } function reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime) { if (current$$1 === null) { // If this is a fresh new component that hasn't been rendered yet, we // won't update its child set by applying minimal side-effects. Instead, // we will add them all to the child before it gets rendered. That means // we can optimize this reconciliation pass by not tracking side-effects. workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime); } else { // If the current child is the same as the work in progress, it means that // we haven't yet started any work on these children. Therefore, we use // the clone algorithm to create a copy of all the current children. // If we had any progressed work already, that is invalid at this point so // let's throw it out. workInProgress.child = reconcileChildFibers(workInProgress, current$$1.child, nextChildren, renderExpirationTime); } } function forceUnmountCurrentAndReconcile(current$$1, workInProgress, nextChildren, renderExpirationTime) { // This function is fork of reconcileChildren. It's used in cases where we // want to reconcile without matching against the existing set. This has the // effect of all current children being unmounted; even if the type and key // are the same, the old child is unmounted and a new child is created. // // To do this, we're going to go through the reconcile algorithm twice. In // the first pass, we schedule a deletion for all the current children by // passing null. workInProgress.child = reconcileChildFibers(workInProgress, current$$1.child, null, renderExpirationTime); // In the second pass, we mount the new children. The trick here is that we // pass null in place of where we usually pass the current child set. This has // the effect of remounting all children regardless of whether their their // identity matches. workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime); } function updateForwardRef(current$$1, workInProgress, Component, nextProps, renderExpirationTime) { // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens after the first render suspends. // We'll need to figure out if this is fine or can cause issues. { if (workInProgress.type !== workInProgress.elementType) { // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. var innerPropTypes = Component.propTypes; if (innerPropTypes) { checkPropTypes(innerPropTypes, nextProps, // Resolved props 'prop', getComponentName(Component), getCurrentFiberStackInDev); } } } var render = Component.render; var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent var nextChildren = void 0; prepareToReadContext(workInProgress, renderExpirationTime); { ReactCurrentOwner$3.current = workInProgress; setCurrentPhase('render'); nextChildren = renderWithHooks(current$$1, workInProgress, render, nextProps, ref, renderExpirationTime); if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) { // Only double-render components with Hooks if (workInProgress.memoizedState !== null) { nextChildren = renderWithHooks(current$$1, workInProgress, render, nextProps, ref, renderExpirationTime); } } setCurrentPhase(null); } if (current$$1 !== null && !didReceiveUpdate) { bailoutHooks(current$$1, workInProgress, renderExpirationTime); return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime); } // React DevTools reads this flag. workInProgress.effectTag |= PerformedWork; reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime); return workInProgress.child; } function updateMemoComponent(current$$1, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) { if (current$$1 === null) { var type = Component.type; if (isSimpleFunctionComponent(type) && Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either. Component.defaultProps === undefined) { // If this is a plain function component without default props, // and with only the default shallow comparison, we upgrade it // to a SimpleMemoComponent to allow fast path updates. workInProgress.tag = SimpleMemoComponent; workInProgress.type = type; { validateFunctionComponentInDev(workInProgress, type); } return updateSimpleMemoComponent(current$$1, workInProgress, type, nextProps, updateExpirationTime, renderExpirationTime); } { var innerPropTypes = type.propTypes; if (innerPropTypes) { // Inner memo component props aren't currently validated in createElement. // We could move it there, but we'd still need this for lazy code path. checkPropTypes(innerPropTypes, nextProps, // Resolved props 'prop', getComponentName(type), getCurrentFiberStackInDev); } } var child = createFiberFromTypeAndProps(Component.type, null, nextProps, null, workInProgress.mode, renderExpirationTime); child.ref = workInProgress.ref; child.return = workInProgress; workInProgress.child = child; return child; } { var _type = Component.type; var _innerPropTypes = _type.propTypes; if (_innerPropTypes) { // Inner memo component props aren't currently validated in createElement. // We could move it there, but we'd still need this for lazy code path. checkPropTypes(_innerPropTypes, nextProps, // Resolved props 'prop', getComponentName(_type), getCurrentFiberStackInDev); } } var currentChild = current$$1.child; // This is always exactly one child if (updateExpirationTime < renderExpirationTime) { // This will be the props with resolved defaultProps, // unlike current.memoizedProps which will be the unresolved ones. var prevProps = currentChild.memoizedProps; // Default to shallow comparison var compare = Component.compare; compare = compare !== null ? compare : shallowEqual; if (compare(prevProps, nextProps) && current$$1.ref === workInProgress.ref) { return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime); } } // React DevTools reads this flag. workInProgress.effectTag |= PerformedWork; var newChild = createWorkInProgress(currentChild, nextProps, renderExpirationTime); newChild.ref = workInProgress.ref; newChild.return = workInProgress; workInProgress.child = newChild; return newChild; } function updateSimpleMemoComponent(current$$1, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) { // TODO: current can be non-null here even if the component // hasn't yet mounted. This happens when the inner render suspends. // We'll need to figure out if this is fine or can cause issues. { if (workInProgress.type !== workInProgress.elementType) { // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. var outerMemoType = workInProgress.elementType; if (outerMemoType.$$typeof === REACT_LAZY_TYPE) { // We warn when you define propTypes on lazy() // so let's just skip over it to find memo() outer wrapper. // Inner props for memo are validated later. outerMemoType = refineResolvedLazyComponent(outerMemoType); } var outerPropTypes = outerMemoType && outerMemoType.propTypes; if (outerPropTypes) { checkPropTypes(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps) 'prop', getComponentName(outerMemoType), getCurrentFiberStackInDev); } // Inner propTypes will be validated in the function component path. } } if (current$$1 !== null) { var prevProps = current$$1.memoizedProps; if (shallowEqual(prevProps, nextProps) && current$$1.ref === workInProgress.ref) { didReceiveUpdate = false; if (updateExpirationTime < renderExpirationTime) { return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime); } } } return updateFunctionComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime); } function updateFragment(current$$1, workInProgress, renderExpirationTime) { var nextChildren = workInProgress.pendingProps; reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime); return workInProgress.child; } function updateMode(current$$1, workInProgress, renderExpirationTime) { var nextChildren = workInProgress.pendingProps.children; reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime); return workInProgress.child; } function updateProfiler(current$$1, workInProgress, renderExpirationTime) { if (enableProfilerTimer) { workInProgress.effectTag |= Update; } var nextProps = workInProgress.pendingProps; var nextChildren = nextProps.children; reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime); return workInProgress.child; } function markRef(current$$1, workInProgress) { var ref = workInProgress.ref; if (current$$1 === null && ref !== null || current$$1 !== null && current$$1.ref !== ref) { // Schedule a Ref effect workInProgress.effectTag |= Ref; } } function updateFunctionComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime) { { if (workInProgress.type !== workInProgress.elementType) { // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. var innerPropTypes = Component.propTypes; if (innerPropTypes) { checkPropTypes(innerPropTypes, nextProps, // Resolved props 'prop', getComponentName(Component), getCurrentFiberStackInDev); } } } var unmaskedContext = getUnmaskedContext(workInProgress, Component, true); var context = getMaskedContext(workInProgress, unmaskedContext); var nextChildren = void 0; prepareToReadContext(workInProgress, renderExpirationTime); { ReactCurrentOwner$3.current = workInProgress; setCurrentPhase('render'); nextChildren = renderWithHooks(current$$1, workInProgress, Component, nextProps, context, renderExpirationTime); if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) { // Only double-render components with Hooks if (workInProgress.memoizedState !== null) { nextChildren = renderWithHooks(current$$1, workInProgress, Component, nextProps, context, renderExpirationTime); } } setCurrentPhase(null); } if (current$$1 !== null && !didReceiveUpdate) { bailoutHooks(current$$1, workInProgress, renderExpirationTime); return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime); } // React DevTools reads this flag. workInProgress.effectTag |= PerformedWork; reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime); return workInProgress.child; } function updateClassComponent(current$$1, workInProgress, Component, nextProps, renderExpirationTime) { { if (workInProgress.type !== workInProgress.elementType) { // Lazy component props can't be validated in createElement // because they're only guaranteed to be resolved here. var innerPropTypes = Component.propTypes; if (innerPropTypes) { checkPropTypes(innerPropTypes, nextProps, // Resolved props 'prop', getComponentName(Component), getCurrentFiberStackInDev); } } } // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. var hasContext = void 0; if (isContextProvider(Component)) { hasContext = true; pushContextProvider(workInProgress); } else { hasContext = false; } prepareToReadContext(workInProgress, renderExpirationTime); var instance = workInProgress.stateNode; var shouldUpdate = void 0; if (instance === null) { if (current$$1 !== null) { // An class component without an instance only mounts if it suspended // inside a non- concurrent tree, in an inconsistent state. We want to // tree it like a new mount, even though an empty version of it already // committed. Disconnect the alternate pointers. current$$1.alternate = null; workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect workInProgress.effectTag |= Placement; } // In the initial pass we might need to construct the instance. constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime); mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime); shouldUpdate = true; } else if (current$$1 === null) { // In a resume, we'll already have an instance we can reuse. shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderExpirationTime); } else { shouldUpdate = updateClassInstance(current$$1, workInProgress, Component, nextProps, renderExpirationTime); } var nextUnitOfWork = finishClassComponent(current$$1, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime); { var inst = workInProgress.stateNode; if (inst.props !== nextProps) { !didWarnAboutReassigningProps ? warning$1(false, 'It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentName(workInProgress.type) || 'a component') : void 0; didWarnAboutReassigningProps = true; } } return nextUnitOfWork; } function finishClassComponent(current$$1, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime) { // Refs should update even if shouldComponentUpdate returns false markRef(current$$1, workInProgress); var didCaptureError = (workInProgress.effectTag & DidCapture) !== NoEffect; if (!shouldUpdate && !didCaptureError) { // Context providers should defer to sCU for rendering if (hasContext) { invalidateContextProvider(workInProgress, Component, false); } return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime); } var instance = workInProgress.stateNode; // Rerender ReactCurrentOwner$3.current = workInProgress; var nextChildren = void 0; if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') { // If we captured an error, but getDerivedStateFrom catch is not defined, // unmount all the children. componentDidCatch will schedule an update to // re-render a fallback. This is temporary until we migrate everyone to // the new API. // TODO: Warn in a future release. nextChildren = null; if (enableProfilerTimer) { stopProfilerTimerIfRunning(workInProgress); } } else { { setCurrentPhase('render'); nextChildren = instance.render(); if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) { instance.render(); } setCurrentPhase(null); } } // React DevTools reads this flag. workInProgress.effectTag |= PerformedWork; if (current$$1 !== null && didCaptureError) { // If we're recovering from an error, reconcile without reusing any of // the existing children. Conceptually, the normal children and the children // that are shown on error are two different sets, so we shouldn't reuse // normal children even if their identities match. forceUnmountCurrentAndReconcile(current$$1, workInProgress, nextChildren, renderExpirationTime); } else { reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime); } // Memoize state using the values we just used to render. // TODO: Restructure so we never read values from the instance. workInProgress.memoizedState = instance.state; // The context might have changed so we need to recalculate it. if (hasContext) { invalidateContextProvider(workInProgress, Component, true); } return workInProgress.child; } function pushHostRootContext(workInProgress) { var root = workInProgress.stateNode; if (root.pendingContext) { pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context); } else if (root.context) { // Should always be set pushTopLevelContextObject(workInProgress, root.context, false); } pushHostContainer(workInProgress, root.containerInfo); } function updateHostRoot(current$$1, workInProgress, renderExpirationTime) { pushHostRootContext(workInProgress); var updateQueue = workInProgress.updateQueue; !(updateQueue !== null) ? invariant(false, 'If the root does not have an updateQueue, we should have already bailed out. This error is likely caused by a bug in React. Please file an issue.') : void 0; var nextProps = workInProgress.pendingProps; var prevState = workInProgress.memoizedState; var prevChildren = prevState !== null ? prevState.element : null; processUpdateQueue(workInProgress, updateQueue, nextProps, null, renderExpirationTime); var nextState = workInProgress.memoizedState; // Caution: React DevTools currently depends on this property // being called "element". var nextChildren = nextState.element; if (nextChildren === prevChildren) { // If the state is the same as before, that's a bailout because we had // no work that expires at this time. resetHydrationState(); return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime); } var root = workInProgress.stateNode; if ((current$$1 === null || current$$1.child === null) && root.hydrate && enterHydrationState(workInProgress)) { // If we don't have any current children this might be the first pass. // We always try to hydrate. If this isn't a hydration pass there won't // be any children to hydrate which is effectively the same thing as // not hydrating. // This is a bit of a hack. We track the host root as a placement to // know that we're currently in a mounting state. That way isMounted // works as expected. We must reset this before committing. // TODO: Delete this when we delete isMounted and findDOMNode. workInProgress.effectTag |= Placement; // Ensure that children mount into this root without tracking // side-effects. This ensures that we don't store Placement effects on // nodes that will be hydrated. workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime); } else { // Otherwise reset hydration state in case we aborted and resumed another // root. reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime); resetHydrationState(); } return workInProgress.child; } function updateHostComponent(current$$1, workInProgress, renderExpirationTime) { pushHostContext(workInProgress); if (current$$1 === null) { tryToClaimNextHydratableInstance(workInProgress); } var type = workInProgress.type; var nextProps = workInProgress.pendingProps; var prevProps = current$$1 !== null ? current$$1.memoizedProps : null; var nextChildren = nextProps.children; var isDirectTextChild = shouldSetTextContent(type, nextProps); if (isDirectTextChild) { // We special case a direct text child of a host node. This is a common // case. We won't handle it as a reified child. We will instead handle // this in the host environment that also have access to this prop. That // avoids allocating another HostText fiber and traversing it. nextChildren = null; } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) { // If we're switching from a direct text child to a normal child, or to // empty, we need to schedule the text content to be reset. workInProgress.effectTag |= ContentReset; } markRef(current$$1, workInProgress); // Check the host config to see if the children are offscreen/hidden. if (renderExpirationTime !== Never && workInProgress.mode & ConcurrentMode && shouldDeprioritizeSubtree(type, nextProps)) { // Schedule this fiber to re-render at offscreen priority. Then bailout. workInProgress.expirationTime = workInProgress.childExpirationTime = Never; return null; } reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime); return workInProgress.child; } function updateHostText(current$$1, workInProgress) { if (current$$1 === null) { tryToClaimNextHydratableInstance(workInProgress); } // Nothing to do here. This is terminal. We'll do the completion step // immediately after. return null; } function mountLazyComponent(_current, workInProgress, elementType, updateExpirationTime, renderExpirationTime) { if (_current !== null) { // An lazy component only mounts if it suspended inside a non- // concurrent tree, in an inconsistent state. We want to treat it like // a new mount, even though an empty version of it already committed. // Disconnect the alternate pointers. _current.alternate = null; workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect workInProgress.effectTag |= Placement; } var props = workInProgress.pendingProps; // We can't start a User Timing measurement with correct label yet. // Cancel and resume right after we know the tag. cancelWorkTimer(workInProgress); var Component = readLazyComponentType(elementType); // Store the unwrapped component in the type. workInProgress.type = Component; var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component); startWorkTimer(workInProgress); var resolvedProps = resolveDefaultProps(Component, props); var child = void 0; switch (resolvedTag) { case FunctionComponent: { { validateFunctionComponentInDev(workInProgress, Component); } child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime); break; } case ClassComponent: { child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime); break; } case ForwardRef: { child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderExpirationTime); break; } case MemoComponent: { { if (workInProgress.type !== workInProgress.elementType) { var outerPropTypes = Component.propTypes; if (outerPropTypes) { checkPropTypes(outerPropTypes, resolvedProps, // Resolved for outer only 'prop', getComponentName(Component), getCurrentFiberStackInDev); } } } child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too updateExpirationTime, renderExpirationTime); break; } default: { var hint = ''; { if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) { hint = ' Did you wrap a component in React.lazy() more than once?'; } } // This message intentionally doesn't mention ForwardRef or MemoComponent // because the fact that it's a separate type of work is an // implementation detail. invariant(false, 'Element type is invalid. Received a promise that resolves to: %s. Lazy element type must resolve to a class or function.%s', Component, hint); } } return child; } function mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderExpirationTime) { if (_current !== null) { // An incomplete component only mounts if it suspended inside a non- // concurrent tree, in an inconsistent state. We want to treat it like // a new mount, even though an empty version of it already committed. // Disconnect the alternate pointers. _current.alternate = null; workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect workInProgress.effectTag |= Placement; } // Promote the fiber to a class and try rendering again. workInProgress.tag = ClassComponent; // The rest of this function is a fork of `updateClassComponent` // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. var hasContext = void 0; if (isContextProvider(Component)) { hasContext = true; pushContextProvider(workInProgress); } else { hasContext = false; } prepareToReadContext(workInProgress, renderExpirationTime); constructClassInstance(workInProgress, Component, nextProps, renderExpirationTime); mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime); return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime); } function mountIndeterminateComponent(_current, workInProgress, Component, renderExpirationTime) { if (_current !== null) { // An indeterminate component only mounts if it suspended inside a non- // concurrent tree, in an inconsistent state. We want to treat it like // a new mount, even though an empty version of it already committed. // Disconnect the alternate pointers. _current.alternate = null; workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect workInProgress.effectTag |= Placement; } var props = workInProgress.pendingProps; var unmaskedContext = getUnmaskedContext(workInProgress, Component, false); var context = getMaskedContext(workInProgress, unmaskedContext); prepareToReadContext(workInProgress, renderExpirationTime); var value = void 0; { if (Component.prototype && typeof Component.prototype.render === 'function') { var componentName = getComponentName(Component) || 'Unknown'; if (!didWarnAboutBadClass[componentName]) { warningWithoutStack$1(false, "The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName); didWarnAboutBadClass[componentName] = true; } } if (workInProgress.mode & StrictMode) { ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null); } ReactCurrentOwner$3.current = workInProgress; value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime); } // React DevTools reads this flag. workInProgress.effectTag |= PerformedWork; if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) { // Proceed under the assumption that this is a class instance workInProgress.tag = ClassComponent; // Throw out any hooks that were used. resetHooks(); // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. var hasContext = false; if (isContextProvider(Component)) { hasContext = true; pushContextProvider(workInProgress); } else { hasContext = false; } workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null; var getDerivedStateFromProps = Component.getDerivedStateFromProps; if (typeof getDerivedStateFromProps === 'function') { applyDerivedStateFromProps(workInProgress, Component, getDerivedStateFromProps, props); } adoptClassInstance(workInProgress, value); mountClassInstance(workInProgress, Component, props, renderExpirationTime); return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime); } else { // Proceed under the assumption that this is a function component workInProgress.tag = FunctionComponent; { if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) { // Only double-render components with Hooks if (workInProgress.memoizedState !== null) { value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime); } } } reconcileChildren(null, workInProgress, value, renderExpirationTime); { validateFunctionComponentInDev(workInProgress, Component); } return workInProgress.child; } } function validateFunctionComponentInDev(workInProgress, Component) { if (Component) { !!Component.childContextTypes ? warningWithoutStack$1(false, '%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component') : void 0; } if (workInProgress.ref !== null) { var info = ''; var ownerName = getCurrentFiberOwnerNameInDevOrNull(); if (ownerName) { info += '\n\nCheck the render method of `' + ownerName + '`.'; } var warningKey = ownerName || workInProgress._debugID || ''; var debugSource = workInProgress._debugSource; if (debugSource) { warningKey = debugSource.fileName + ':' + debugSource.lineNumber; } if (!didWarnAboutFunctionRefs[warningKey]) { didWarnAboutFunctionRefs[warningKey] = true; warning$1(false, 'Function components cannot be given refs. ' + 'Attempts to access this ref will fail. ' + 'Did you mean to use React.forwardRef()?%s', info); } } if (typeof Component.getDerivedStateFromProps === 'function') { var componentName = getComponentName(Component) || 'Unknown'; if (!didWarnAboutGetDerivedStateOnFunctionComponent[componentName]) { warningWithoutStack$1(false, '%s: Function components do not support getDerivedStateFromProps.', componentName); didWarnAboutGetDerivedStateOnFunctionComponent[componentName] = true; } } if (typeof Component.contextType === 'object' && Component.contextType !== null) { var _componentName = getComponentName(Component) || 'Unknown'; if (!didWarnAboutContextTypeOnFunctionComponent[_componentName]) { warningWithoutStack$1(false, '%s: Function components do not support contextType.', _componentName); didWarnAboutContextTypeOnFunctionComponent[_componentName] = true; } } } function updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime) { var mode = workInProgress.mode; var nextProps = workInProgress.pendingProps; // We should attempt to render the primary children unless this boundary // already suspended during this render (`alreadyCaptured` is true). var nextState = workInProgress.memoizedState; var nextDidTimeout = void 0; if ((workInProgress.effectTag & DidCapture) === NoEffect) { // This is the first attempt. nextState = null; nextDidTimeout = false; } else { // Something in this boundary's subtree already suspended. Switch to // rendering the fallback children. nextState = { timedOutAt: nextState !== null ? nextState.timedOutAt : NoWork }; nextDidTimeout = true; workInProgress.effectTag &= ~DidCapture; } // This next part is a bit confusing. If the children timeout, we switch to // showing the fallback children in place of the "primary" children. // However, we don't want to delete the primary children because then their // state will be lost (both the React state and the host state, e.g. // uncontrolled form inputs). Instead we keep them mounted and hide them. // Both the fallback children AND the primary children are rendered at the // same time. Once the primary children are un-suspended, we can delete // the fallback children — don't need to preserve their state. // // The two sets of children are siblings in the host environment, but // semantically, for purposes of reconciliation, they are two separate sets. // So we store them using two fragment fibers. // // However, we want to avoid allocating extra fibers for every placeholder. // They're only necessary when the children time out, because that's the // only time when both sets are mounted. // // So, the extra fragment fibers are only used if the children time out. // Otherwise, we render the primary children directly. This requires some // custom reconciliation logic to preserve the state of the primary // children. It's essentially a very basic form of re-parenting. // `child` points to the child fiber. In the normal case, this is the first // fiber of the primary children set. In the timed-out case, it's a // a fragment fiber containing the primary children. var child = void 0; // `next` points to the next fiber React should render. In the normal case, // it's the same as `child`: the first fiber of the primary children set. // In the timed-out case, it's a fragment fiber containing the *fallback* // children -- we skip over the primary children entirely. var next = void 0; if (current$$1 === null) { if (enableSuspenseServerRenderer) { // If we're currently hydrating, try to hydrate this boundary. // But only if this has a fallback. if (nextProps.fallback !== undefined) { tryToClaimNextHydratableInstance(workInProgress); // This could've changed the tag if this was a dehydrated suspense component. if (workInProgress.tag === DehydratedSuspenseComponent) { return updateDehydratedSuspenseComponent(null, workInProgress, renderExpirationTime); } } } // This is the initial mount. This branch is pretty simple because there's // no previous state that needs to be preserved. if (nextDidTimeout) { // Mount separate fragments for primary and fallback children. var nextFallbackChildren = nextProps.fallback; var primaryChildFragment = createFiberFromFragment(null, mode, NoWork, null); if ((workInProgress.mode & ConcurrentMode) === NoContext) { // Outside of concurrent mode, we commit the effects from the var progressedState = workInProgress.memoizedState; var progressedPrimaryChild = progressedState !== null ? workInProgress.child.child : workInProgress.child; primaryChildFragment.child = progressedPrimaryChild; } var fallbackChildFragment = createFiberFromFragment(nextFallbackChildren, mode, renderExpirationTime, null); primaryChildFragment.sibling = fallbackChildFragment; child = primaryChildFragment; // Skip the primary children, and continue working on the // fallback children. next = fallbackChildFragment; child.return = next.return = workInProgress; } else { // Mount the primary children without an intermediate fragment fiber. var nextPrimaryChildren = nextProps.children; child = next = mountChildFibers(workInProgress, null, nextPrimaryChildren, renderExpirationTime); } } else { // This is an update. This branch is more complicated because we need to // ensure the state of the primary children is preserved. var prevState = current$$1.memoizedState; var prevDidTimeout = prevState !== null; if (prevDidTimeout) { // The current tree already timed out. That means each child set is var currentPrimaryChildFragment = current$$1.child; var currentFallbackChildFragment = currentPrimaryChildFragment.sibling; if (nextDidTimeout) { // Still timed out. Reuse the current primary children by cloning // its fragment. We're going to skip over these entirely. var _nextFallbackChildren = nextProps.fallback; var _primaryChildFragment = createWorkInProgress(currentPrimaryChildFragment, currentPrimaryChildFragment.pendingProps, NoWork); if ((workInProgress.mode & ConcurrentMode) === NoContext) { // Outside of concurrent mode, we commit the effects from the var _progressedState = workInProgress.memoizedState; var _progressedPrimaryChild = _progressedState !== null ? workInProgress.child.child : workInProgress.child; if (_progressedPrimaryChild !== currentPrimaryChildFragment.child) { _primaryChildFragment.child = _progressedPrimaryChild; } } // Because primaryChildFragment is a new fiber that we're inserting as the // parent of a new tree, we need to set its treeBaseDuration. if (enableProfilerTimer && workInProgress.mode & ProfileMode) { // treeBaseDuration is the sum of all the child tree base durations. var treeBaseDuration = 0; var hiddenChild = _primaryChildFragment.child; while (hiddenChild !== null) { treeBaseDuration += hiddenChild.treeBaseDuration; hiddenChild = hiddenChild.sibling; } _primaryChildFragment.treeBaseDuration = treeBaseDuration; } // Clone the fallback child fragment, too. These we'll continue // working on. var _fallbackChildFragment = _primaryChildFragment.sibling = createWorkInProgress(currentFallbackChildFragment, _nextFallbackChildren, currentFallbackChildFragment.expirationTime); child = _primaryChildFragment; _primaryChildFragment.childExpirationTime = NoWork; // Skip the primary children, and continue working on the // fallback children. next = _fallbackChildFragment; child.return = next.return = workInProgress; } else { // No longer suspended. Switch back to showing the primary children, // and remove the intermediate fragment fiber. var _nextPrimaryChildren = nextProps.children; var currentPrimaryChild = currentPrimaryChildFragment.child; var primaryChild = reconcileChildFibers(workInProgress, currentPrimaryChild, _nextPrimaryChildren, renderExpirationTime); // If this render doesn't suspend, we need to delete the fallback // children. Wait until the complete phase, after we've confirmed the // fallback is no longer needed. // TODO: Would it be better to store the fallback fragment on // the stateNode? // Continue rendering the children, like we normally do. child = next = primaryChild; } } else { // The current tree has not already timed out. That means the primary // children are not wrapped in a fragment fiber. var _currentPrimaryChild = current$$1.child; if (nextDidTimeout) { // Timed out. Wrap the children in a fragment fiber to keep them // separate from the fallback children. var _nextFallbackChildren2 = nextProps.fallback; var _primaryChildFragment2 = createFiberFromFragment( // It shouldn't matter what the pending props are because we aren't // going to render this fragment. null, mode, NoWork, null); _primaryChildFragment2.child = _currentPrimaryChild; // Even though we're creating a new fiber, there are no new children, // because we're reusing an already mounted tree. So we don't need to // schedule a placement. // primaryChildFragment.effectTag |= Placement; if ((workInProgress.mode & ConcurrentMode) === NoContext) { // Outside of concurrent mode, we commit the effects from the var _progressedState2 = workInProgress.memoizedState; var _progressedPrimaryChild2 = _progressedState2 !== null ? workInProgress.child.child : workInProgress.child; _primaryChildFragment2.child = _progressedPrimaryChild2; } // Because primaryChildFragment is a new fiber that we're inserting as the // parent of a new tree, we need to set its treeBaseDuration. if (enableProfilerTimer && workInProgress.mode & ProfileMode) { // treeBaseDuration is the sum of all the child tree base durations. var _treeBaseDuration = 0; var _hiddenChild = _primaryChildFragment2.child; while (_hiddenChild !== null) { _treeBaseDuration += _hiddenChild.treeBaseDuration; _hiddenChild = _hiddenChild.sibling; } _primaryChildFragment2.treeBaseDuration = _treeBaseDuration; } // Create a fragment from the fallback children, too. var _fallbackChildFragment2 = _primaryChildFragment2.sibling = createFiberFromFragment(_nextFallbackChildren2, mode, renderExpirationTime, null); _fallbackChildFragment2.effectTag |= Placement; child = _primaryChildFragment2; _primaryChildFragment2.childExpirationTime = NoWork; // Skip the primary children, and continue working on the // fallback children. next = _fallbackChildFragment2; child.return = next.return = workInProgress; } else { // Still haven't timed out. Continue rendering the children, like we // normally do. var _nextPrimaryChildren2 = nextProps.children; next = child = reconcileChildFibers(workInProgress, _currentPrimaryChild, _nextPrimaryChildren2, renderExpirationTime); } } workInProgress.stateNode = current$$1.stateNode; } workInProgress.memoizedState = nextState; workInProgress.child = child; return next; } function updateDehydratedSuspenseComponent(current$$1, workInProgress, renderExpirationTime) { if (current$$1 === null) { // During the first pass, we'll bail out and not drill into the children. // Instead, we'll leave the content in place and try to hydrate it later. workInProgress.expirationTime = Never; return null; } // We use childExpirationTime to indicate that a child might depend on context, so if // any context has changed, we need to treat is as if the input might have changed. var hasContextChanged$$1 = current$$1.childExpirationTime >= renderExpirationTime; if (didReceiveUpdate || hasContextChanged$$1) { // This boundary has changed since the first render. This means that we are now unable to // hydrate it. We might still be able to hydrate it using an earlier expiration time but // during this render we can't. Instead, we're going to delete the whole subtree and // instead inject a new real Suspense boundary to take its place, which may render content // or fallback. The real Suspense boundary will suspend for a while so we have some time // to ensure it can produce real content, but all state and pending events will be lost. // Detach from the current dehydrated boundary. current$$1.alternate = null; workInProgress.alternate = null; // Insert a deletion in the effect list. var returnFiber = workInProgress.return; !(returnFiber !== null) ? invariant(false, 'Suspense boundaries are never on the root. This is probably a bug in React.') : void 0; var last = returnFiber.lastEffect; if (last !== null) { last.nextEffect = current$$1; returnFiber.lastEffect = current$$1; } else { returnFiber.firstEffect = returnFiber.lastEffect = current$$1; } current$$1.nextEffect = null; current$$1.effectTag = Deletion; // Upgrade this work in progress to a real Suspense component. workInProgress.tag = SuspenseComponent; workInProgress.stateNode = null; workInProgress.memoizedState = null; // This is now an insertion. workInProgress.effectTag |= Placement; // Retry as a real Suspense component. return updateSuspenseComponent(null, workInProgress, renderExpirationTime); } if ((workInProgress.effectTag & DidCapture) === NoEffect) { // This is the first attempt. reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress); var nextProps = workInProgress.pendingProps; var nextChildren = nextProps.children; workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime); return workInProgress.child; } else { // Something suspended. Leave the existing children in place. // TODO: In non-concurrent mode, should we commit the nodes we have hydrated so far? workInProgress.child = null; return null; } } function updatePortalComponent(current$$1, workInProgress, renderExpirationTime) { pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); var nextChildren = workInProgress.pendingProps; if (current$$1 === null) { // Portals are special because we don't append the children during mount // but at commit. Therefore we need to track insertions which the normal // flow doesn't do during mount. This doesn't happen at the root because // the root always starts with a "current" with a null child. // TODO: Consider unifying this with how the root works. workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime); } else { reconcileChildren(current$$1, workInProgress, nextChildren, renderExpirationTime); } return workInProgress.child; } function updateContextProvider(current$$1, workInProgress, renderExpirationTime) { var providerType = workInProgress.type; var context = providerType._context; var newProps = workInProgress.pendingProps; var oldProps = workInProgress.memoizedProps; var newValue = newProps.value; { var providerPropTypes = workInProgress.type.propTypes; if (providerPropTypes) { checkPropTypes(providerPropTypes, newProps, 'prop', 'Context.Provider', getCurrentFiberStackInDev); } } pushProvider(workInProgress, newValue); if (oldProps !== null) { var oldValue = oldProps.value; var changedBits = calculateChangedBits(context, newValue, oldValue); if (changedBits === 0) { // No change. Bailout early if children are the same. if (oldProps.children === newProps.children && !hasContextChanged()) { return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime); } } else { // The context value changed. Search for matching consumers and schedule // them to update. propagateContextChange(workInProgress, context, changedBits, renderExpirationTime); } } var newChildren = newProps.children; reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime); return workInProgress.child; } var hasWarnedAboutUsingContextAsConsumer = false; function updateContextConsumer(current$$1, workInProgress, renderExpirationTime) { var context = workInProgress.type; // The logic below for Context differs depending on PROD or DEV mode. In // DEV mode, we create a separate object for Context.Consumer that acts // like a proxy to Context. This proxy object adds unnecessary code in PROD // so we use the old behaviour (Context.Consumer references Context) to // reduce size and overhead. The separate object references context via // a property called "_context", which also gives us the ability to check // in DEV mode if this property exists or not and warn if it does not. { if (context._context === undefined) { // This may be because it's a Context (rather than a Consumer). // Or it may be because it's older React where they're the same thing. // We only want to warn if we're sure it's a new React. if (context !== context.Consumer) { if (!hasWarnedAboutUsingContextAsConsumer) { hasWarnedAboutUsingContextAsConsumer = true; warning$1(false, 'Rendering <Context> directly is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?'); } } } else { context = context._context; } } var newProps = workInProgress.pendingProps; var render = newProps.children; { !(typeof render === 'function') ? warningWithoutStack$1(false, 'A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.') : void 0; } prepareToReadContext(workInProgress, renderExpirationTime); var newValue = readContext(context, newProps.unstable_observedBits); var newChildren = void 0; { ReactCurrentOwner$3.current = workInProgress; setCurrentPhase('render'); newChildren = render(newValue); setCurrentPhase(null); } // React DevTools reads this flag. workInProgress.effectTag |= PerformedWork; reconcileChildren(current$$1, workInProgress, newChildren, renderExpirationTime); return workInProgress.child; } function markWorkInProgressReceivedUpdate() { didReceiveUpdate = true; } function bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime) { cancelWorkTimer(workInProgress); if (current$$1 !== null) { // Reuse previous context list workInProgress.contextDependencies = current$$1.contextDependencies; } if (enableProfilerTimer) { // Don't update "base" render times for bailouts. stopProfilerTimerIfRunning(workInProgress); } // Check if the children have any pending work. var childExpirationTime = workInProgress.childExpirationTime; if (childExpirationTime < renderExpirationTime) { // The children don't have any work either. We can skip them. // TODO: Once we add back resuming, we should check if the children are // a work-in-progress set. If so, we need to transfer their effects. return null; } else { // This fiber doesn't have work, but its subtree does. Clone the child // fibers and continue. cloneChildFibers(current$$1, workInProgress); return workInProgress.child; } } function beginWork(current$$1, workInProgress, renderExpirationTime) { var updateExpirationTime = workInProgress.expirationTime; if (current$$1 !== null) { var oldProps = current$$1.memoizedProps; var newProps = workInProgress.pendingProps; if (oldProps !== newProps || hasContextChanged()) { // If props or context changed, mark the fiber as having performed work. // This may be unset if the props are determined to be equal later (memo). didReceiveUpdate = true; } else if (updateExpirationTime < renderExpirationTime) { didReceiveUpdate = false; // This fiber does not have any pending work. Bailout without entering // the begin phase. There's still some bookkeeping we that needs to be done // in this optimized path, mostly pushing stuff onto the stack. switch (workInProgress.tag) { case HostRoot: pushHostRootContext(workInProgress); resetHydrationState(); break; case HostComponent: pushHostContext(workInProgress); break; case ClassComponent: { var Component = workInProgress.type; if (isContextProvider(Component)) { pushContextProvider(workInProgress); } break; } case HostPortal: pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo); break; case ContextProvider: { var newValue = workInProgress.memoizedProps.value; pushProvider(workInProgress, newValue); break; } case Profiler: if (enableProfilerTimer) { workInProgress.effectTag |= Update; } break; case SuspenseComponent: { var state = workInProgress.memoizedState; var didTimeout = state !== null; if (didTimeout) { // If this boundary is currently timed out, we need to decide // whether to retry the primary children, or to skip over it and // go straight to the fallback. Check the priority of the primary var primaryChildFragment = workInProgress.child; var primaryChildExpirationTime = primaryChildFragment.childExpirationTime; if (primaryChildExpirationTime !== NoWork && primaryChildExpirationTime >= renderExpirationTime) { // The primary children have pending work. Use the normal path // to attempt to render the primary children again. return updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime); } else { // The primary children do not have pending work with sufficient // priority. Bailout. var child = bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime); if (child !== null) { // The fallback children have pending work. Skip over the // primary children and work on the fallback. return child.sibling; } else { return null; } } } break; } case DehydratedSuspenseComponent: { if (enableSuspenseServerRenderer) { // We know that this component will suspend again because if it has // been unsuspended it has committed as a regular Suspense component. // If it needs to be retried, it should have work scheduled on it. workInProgress.effectTag |= DidCapture; break; } } } return bailoutOnAlreadyFinishedWork(current$$1, workInProgress, renderExpirationTime); } } else { didReceiveUpdate = false; } // Before entering the begin phase, clear the expiration time. workInProgress.expirationTime = NoWork; switch (workInProgress.tag) { case IndeterminateComponent: { var elementType = workInProgress.elementType; return mountIndeterminateComponent(current$$1, workInProgress, elementType, renderExpirationTime); } case LazyComponent: { var _elementType = workInProgress.elementType; return mountLazyComponent(current$$1, workInProgress, _elementType, updateExpirationTime, renderExpirationTime); } case FunctionComponent: { var _Component = workInProgress.type; var unresolvedProps = workInProgress.pendingProps; var resolvedProps = workInProgress.elementType === _Component ? unresolvedProps : resolveDefaultProps(_Component, unresolvedProps); return updateFunctionComponent(current$$1, workInProgress, _Component, resolvedProps, renderExpirationTime); } case ClassComponent: { var _Component2 = workInProgress.type; var _unresolvedProps = workInProgress.pendingProps; var _resolvedProps = workInProgress.elementType === _Component2 ? _unresolvedProps : resolveDefaultProps(_Component2, _unresolvedProps); return updateClassComponent(current$$1, workInProgress, _Component2, _resolvedProps, renderExpirationTime); } case HostRoot: return updateHostRoot(current$$1, workInProgress, renderExpirationTime); case HostComponent: return updateHostComponent(current$$1, workInProgress, renderExpirationTime); case HostText: return updateHostText(current$$1, workInProgress); case SuspenseComponent: return updateSuspenseComponent(current$$1, workInProgress, renderExpirationTime); case HostPortal: return updatePortalComponent(current$$1, workInProgress, renderExpirationTime); case ForwardRef: { var type = workInProgress.type; var _unresolvedProps2 = workInProgress.pendingProps; var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2); return updateForwardRef(current$$1, workInProgress, type, _resolvedProps2, renderExpirationTime); } case Fragment: return updateFragment(current$$1, workInProgress, renderExpirationTime); case Mode: return updateMode(current$$1, workInProgress, renderExpirationTime); case Profiler: return updateProfiler(current$$1, workInProgress, renderExpirationTime); case ContextProvider: return updateContextProvider(current$$1, workInProgress, renderExpirationTime); case ContextConsumer: return updateContextConsumer(current$$1, workInProgress, renderExpirationTime); case MemoComponent: { var _type2 = workInProgress.type; var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props. var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3); { if (workInProgress.type !== workInProgress.elementType) { var outerPropTypes = _type2.propTypes; if (outerPropTypes) { checkPropTypes(outerPropTypes, _resolvedProps3, // Resolved for outer only 'prop', getComponentName(_type2), getCurrentFiberStackInDev); } } } _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3); return updateMemoComponent(current$$1, workInProgress, _type2, _resolvedProps3, updateExpirationTime, renderExpirationTime); } case SimpleMemoComponent: { return updateSimpleMemoComponent(current$$1, workInProgress, workInProgress.type, workInProgress.pendingProps, updateExpirationTime, renderExpirationTime); } case IncompleteClassComponent: { var _Component3 = workInProgress.type; var _unresolvedProps4 = workInProgress.pendingProps; var _resolvedProps4 = workInProgress.elementType === _Component3 ? _unresolvedProps4 : resolveDefaultProps(_Component3, _unresolvedProps4); return mountIncompleteClassComponent(current$$1, workInProgress, _Component3, _resolvedProps4, renderExpirationTime); } case DehydratedSuspenseComponent: { if (enableSuspenseServerRenderer) { return updateDehydratedSuspenseComponent(current$$1, workInProgress, renderExpirationTime); } break; } } invariant(false, 'Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue.'); } var valueCursor = createCursor(null); var rendererSigil = void 0; { // Use this to detect multiple renderers using the same context rendererSigil = {}; } var currentlyRenderingFiber = null; var lastContextDependency = null; var lastContextWithAllBitsObserved = null; var isDisallowedContextReadInDEV = false; function resetContextDependences() { // This is called right before React yields execution, to ensure `readContext` // cannot be called outside the render phase. currentlyRenderingFiber = null; lastContextDependency = null; lastContextWithAllBitsObserved = null; { isDisallowedContextReadInDEV = false; } } function enterDisallowedContextReadInDEV() { { isDisallowedContextReadInDEV = true; } } function exitDisallowedContextReadInDEV() { { isDisallowedContextReadInDEV = false; } } function pushProvider(providerFiber, nextValue) { var context = providerFiber.type._context; if (isPrimaryRenderer) { push(valueCursor, context._currentValue, providerFiber); context._currentValue = nextValue; { !(context._currentRenderer === undefined || context._currentRenderer === null || context._currentRenderer === rendererSigil) ? warningWithoutStack$1(false, 'Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.') : void 0; context._currentRenderer = rendererSigil; } } else { push(valueCursor, context._currentValue2, providerFiber); context._currentValue2 = nextValue; { !(context._currentRenderer2 === undefined || context._currentRenderer2 === null || context._currentRenderer2 === rendererSigil) ? warningWithoutStack$1(false, 'Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.') : void 0; context._currentRenderer2 = rendererSigil; } } } function popProvider(providerFiber) { var currentValue = valueCursor.current; pop(valueCursor, providerFiber); var context = providerFiber.type._context; if (isPrimaryRenderer) { context._currentValue = currentValue; } else { context._currentValue2 = currentValue; } } function calculateChangedBits(context, newValue, oldValue) { if (is(oldValue, newValue)) { // No change return 0; } else { var changedBits = typeof context._calculateChangedBits === 'function' ? context._calculateChangedBits(oldValue, newValue) : maxSigned31BitInt; { !((changedBits & maxSigned31BitInt) === changedBits) ? warning$1(false, 'calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: %s', changedBits) : void 0; } return changedBits | 0; } } function scheduleWorkOnParentPath(parent, renderExpirationTime) { // Update the child expiration time of all the ancestors, including // the alternates. var node = parent; while (node !== null) { var alternate = node.alternate; if (node.childExpirationTime < renderExpirationTime) { node.childExpirationTime = renderExpirationTime; if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) { alternate.childExpirationTime = renderExpirationTime; } } else if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) { alternate.childExpirationTime = renderExpirationTime; } else { // Neither alternate was updated, which means the rest of the // ancestor path already has sufficient priority. break; } node = node.return; } } function propagateContextChange(workInProgress, context, changedBits, renderExpirationTime) { var fiber = workInProgress.child; if (fiber !== null) { // Set the return pointer of the child to the work-in-progress fiber. fiber.return = workInProgress; } while (fiber !== null) { var nextFiber = void 0; // Visit this fiber. var list = fiber.contextDependencies; if (list !== null) { nextFiber = fiber.child; var dependency = list.first; while (dependency !== null) { // Check if the context matches. if (dependency.context === context && (dependency.observedBits & changedBits) !== 0) { // Match! Schedule an update on this fiber. if (fiber.tag === ClassComponent) { // Schedule a force update on the work-in-progress. var update = createUpdate(renderExpirationTime); update.tag = ForceUpdate; // TODO: Because we don't have a work-in-progress, this will add the // update to the current fiber, too, which means it will persist even if // this render is thrown away. Since it's a race condition, not sure it's // worth fixing. enqueueUpdate(fiber, update); } if (fiber.expirationTime < renderExpirationTime) { fiber.expirationTime = renderExpirationTime; } var alternate = fiber.alternate; if (alternate !== null && alternate.expirationTime < renderExpirationTime) { alternate.expirationTime = renderExpirationTime; } scheduleWorkOnParentPath(fiber.return, renderExpirationTime); // Mark the expiration time on the list, too. if (list.expirationTime < renderExpirationTime) { list.expirationTime = renderExpirationTime; } // Since we already found a match, we can stop traversing the // dependency list. break; } dependency = dependency.next; } } else if (fiber.tag === ContextProvider) { // Don't scan deeper if this is a matching provider nextFiber = fiber.type === workInProgress.type ? null : fiber.child; } else if (enableSuspenseServerRenderer && fiber.tag === DehydratedSuspenseComponent) { // If a dehydrated suspense component is in this subtree, we don't know // if it will have any context consumers in it. The best we can do is // mark it as having updates on its children. if (fiber.expirationTime < renderExpirationTime) { fiber.expirationTime = renderExpirationTime; } var _alternate = fiber.alternate; if (_alternate !== null && _alternate.expirationTime < renderExpirationTime) { _alternate.expirationTime = renderExpirationTime; } // This is intentionally passing this fiber as the parent // because we want to schedule this fiber as having work // on its children. We'll use the childExpirationTime on // this fiber to indicate that a context has changed. scheduleWorkOnParentPath(fiber, renderExpirationTime); nextFiber = fiber.sibling; } else { // Traverse down. nextFiber = fiber.child; } if (nextFiber !== null) { // Set the return pointer of the child to the work-in-progress fiber. nextFiber.return = fiber; } else { // No child. Traverse to next sibling. nextFiber = fiber; while (nextFiber !== null) { if (nextFiber === workInProgress) { // We're back to the root of this subtree. Exit. nextFiber = null; break; } var sibling = nextFiber.sibling; if (sibling !== null) { // Set the return pointer of the sibling to the work-in-progress fiber. sibling.return = nextFiber.return; nextFiber = sibling; break; } // No more siblings. Traverse up. nextFiber = nextFiber.return; } } fiber = nextFiber; } } function prepareToReadContext(workInProgress, renderExpirationTime) { currentlyRenderingFiber = workInProgress; lastContextDependency = null; lastContextWithAllBitsObserved = null; var currentDependencies = workInProgress.contextDependencies; if (currentDependencies !== null && currentDependencies.expirationTime >= renderExpirationTime) { // Context list has a pending update. Mark that this fiber performed work. markWorkInProgressReceivedUpdate(); } // Reset the work-in-progress list workInProgress.contextDependencies = null; } function readContext(context, observedBits) { { // This warning would fire if you read context inside a Hook like useMemo. // Unlike the class check below, it's not enforced in production for perf. !!isDisallowedContextReadInDEV ? warning$1(false, 'Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().') : void 0; } if (lastContextWithAllBitsObserved === context) { // Nothing to do. We already observe everything in this context. } else if (observedBits === false || observedBits === 0) { // Do not observe any updates. } else { var resolvedObservedBits = void 0; // Avoid deopting on observable arguments or heterogeneous types. if (typeof observedBits !== 'number' || observedBits === maxSigned31BitInt) { // Observe all updates. lastContextWithAllBitsObserved = context; resolvedObservedBits = maxSigned31BitInt; } else { resolvedObservedBits = observedBits; } var contextItem = { context: context, observedBits: resolvedObservedBits, next: null }; if (lastContextDependency === null) { !(currentlyRenderingFiber !== null) ? invariant(false, 'Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo().') : void 0; // This is the first dependency for this component. Create a new list. lastContextDependency = contextItem; currentlyRenderingFiber.contextDependencies = { first: contextItem, expirationTime: NoWork }; } else { // Append a new context item. lastContextDependency = lastContextDependency.next = contextItem; } } return isPrimaryRenderer ? context._currentValue : context._currentValue2; } // UpdateQueue is a linked list of prioritized updates. // // Like fibers, update queues come in pairs: a current queue, which represents // the visible state of the screen, and a work-in-progress queue, which can be // mutated and processed asynchronously before it is committed — a form of // double buffering. If a work-in-progress render is discarded before finishing, // we create a new work-in-progress by cloning the current queue. // // Both queues share a persistent, singly-linked list structure. To schedule an // update, we append it to the end of both queues. Each queue maintains a // pointer to first update in the persistent list that hasn't been processed. // The work-in-progress pointer always has a position equal to or greater than // the current queue, since we always work on that one. The current queue's // pointer is only updated during the commit phase, when we swap in the // work-in-progress. // // For example: // // Current pointer: A - B - C - D - E - F // Work-in-progress pointer: D - E - F // ^ // The work-in-progress queue has // processed more updates than current. // // The reason we append to both queues is because otherwise we might drop // updates without ever processing them. For example, if we only add updates to // the work-in-progress queue, some updates could be lost whenever a work-in // -progress render restarts by cloning from current. Similarly, if we only add // updates to the current queue, the updates will be lost whenever an already // in-progress queue commits and swaps with the current queue. However, by // adding to both queues, we guarantee that the update will be part of the next // work-in-progress. (And because the work-in-progress queue becomes the // current queue once it commits, there's no danger of applying the same // update twice.) // // Prioritization // -------------- // // Updates are not sorted by priority, but by insertion; new updates are always // appended to the end of the list. // // The priority is still important, though. When processing the update queue // during the render phase, only the updates with sufficient priority are // included in the result. If we skip an update because it has insufficient // priority, it remains in the queue to be processed later, during a lower // priority render. Crucially, all updates subsequent to a skipped update also // remain in the queue *regardless of their priority*. That means high priority // updates are sometimes processed twice, at two separate priorities. We also // keep track of a base state, that represents the state before the first // update in the queue is applied. // // For example: // // Given a base state of '', and the following queue of updates // // A1 - B2 - C1 - D2 // // where the number indicates the priority, and the update is applied to the // previous state by appending a letter, React will process these updates as // two separate renders, one per distinct priority level: // // First render, at priority 1: // Base state: '' // Updates: [A1, C1] // Result state: 'AC' // // Second render, at priority 2: // Base state: 'A' <- The base state does not include C1, // because B2 was skipped. // Updates: [B2, C1, D2] <- C1 was rebased on top of B2 // Result state: 'ABCD' // // Because we process updates in insertion order, and rebase high priority // updates when preceding updates are skipped, the final result is deterministic // regardless of priority. Intermediate state may vary according to system // resources, but the final state is always the same. var UpdateState = 0; var ReplaceState = 1; var ForceUpdate = 2; var CaptureUpdate = 3; // Global state that is reset at the beginning of calling `processUpdateQueue`. // It should only be read right after calling `processUpdateQueue`, via // `checkHasForceUpdateAfterProcessing`. var hasForceUpdate = false; var didWarnUpdateInsideUpdate = void 0; var currentlyProcessingQueue = void 0; var resetCurrentlyProcessingQueue = void 0; { didWarnUpdateInsideUpdate = false; currentlyProcessingQueue = null; resetCurrentlyProcessingQueue = function () { currentlyProcessingQueue = null; }; } function createUpdateQueue(baseState) { var queue = { baseState: baseState, firstUpdate: null, lastUpdate: null, firstCapturedUpdate: null, lastCapturedUpdate: null, firstEffect: null, lastEffect: null, firstCapturedEffect: null, lastCapturedEffect: null }; return queue; } function cloneUpdateQueue(currentQueue) { var queue = { baseState: currentQueue.baseState, firstUpdate: currentQueue.firstUpdate, lastUpdate: currentQueue.lastUpdate, // TODO: With resuming, if we bail out and resuse the child tree, we should // keep these effects. firstCapturedUpdate: null, lastCapturedUpdate: null, firstEffect: null, lastEffect: null, firstCapturedEffect: null, lastCapturedEffect: null }; return queue; } function createUpdate(expirationTime) { return { expirationTime: expirationTime, tag: UpdateState, payload: null, callback: null, next: null, nextEffect: null }; } function appendUpdateToQueue(queue, update) { // Append the update to the end of the list. if (queue.lastUpdate === null) { // Queue is empty queue.firstUpdate = queue.lastUpdate = update; } else { queue.lastUpdate.next = update; queue.lastUpdate = update; } } function enqueueUpdate(fiber, update) { // Update queues are created lazily. var alternate = fiber.alternate; var queue1 = void 0; var queue2 = void 0; if (alternate === null) { // There's only one fiber. queue1 = fiber.updateQueue; queue2 = null; if (queue1 === null) { queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState); } } else { // There are two owners. queue1 = fiber.updateQueue; queue2 = alternate.updateQueue; if (queue1 === null) { if (queue2 === null) { // Neither fiber has an update queue. Create new ones. queue1 = fiber.updateQueue = createUpdateQueue(fiber.memoizedState); queue2 = alternate.updateQueue = createUpdateQueue(alternate.memoizedState); } else { // Only one fiber has an update queue. Clone to create a new one. queue1 = fiber.updateQueue = cloneUpdateQueue(queue2); } } else { if (queue2 === null) { // Only one fiber has an update queue. Clone to create a new one. queue2 = alternate.updateQueue = cloneUpdateQueue(queue1); } else { // Both owners have an update queue. } } } if (queue2 === null || queue1 === queue2) { // There's only a single queue. appendUpdateToQueue(queue1, update); } else { // There are two queues. We need to append the update to both queues, // while accounting for the persistent structure of the list — we don't // want the same update to be added multiple times. if (queue1.lastUpdate === null || queue2.lastUpdate === null) { // One of the queues is not empty. We must add the update to both queues. appendUpdateToQueue(queue1, update); appendUpdateToQueue(queue2, update); } else { // Both queues are non-empty. The last update is the same in both lists, // because of structural sharing. So, only append to one of the lists. appendUpdateToQueue(queue1, update); // But we still need to update the `lastUpdate` pointer of queue2. queue2.lastUpdate = update; } } { if (fiber.tag === ClassComponent && (currentlyProcessingQueue === queue1 || queue2 !== null && currentlyProcessingQueue === queue2) && !didWarnUpdateInsideUpdate) { warningWithoutStack$1(false, 'An update (setState, replaceState, or forceUpdate) was scheduled ' + 'from inside an update function. Update functions should be pure, ' + 'with zero side-effects. Consider using componentDidUpdate or a ' + 'callback.'); didWarnUpdateInsideUpdate = true; } } } function enqueueCapturedUpdate(workInProgress, update) { // Captured updates go into a separate list, and only on the work-in- // progress queue. var workInProgressQueue = workInProgress.updateQueue; if (workInProgressQueue === null) { workInProgressQueue = workInProgress.updateQueue = createUpdateQueue(workInProgress.memoizedState); } else { // TODO: I put this here rather than createWorkInProgress so that we don't // clone the queue unnecessarily. There's probably a better way to // structure this. workInProgressQueue = ensureWorkInProgressQueueIsAClone(workInProgress, workInProgressQueue); } // Append the update to the end of the list. if (workInProgressQueue.lastCapturedUpdate === null) { // This is the first render phase update workInProgressQueue.firstCapturedUpdate = workInProgressQueue.lastCapturedUpdate = update; } else { workInProgressQueue.lastCapturedUpdate.next = update; workInProgressQueue.lastCapturedUpdate = update; } } function ensureWorkInProgressQueueIsAClone(workInProgress, queue) { var current = workInProgress.alternate; if (current !== null) { // If the work-in-progress queue is equal to the current queue, // we need to clone it first. if (queue === current.updateQueue) { queue = workInProgress.updateQueue = cloneUpdateQueue(queue); } } return queue; } function getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) { switch (update.tag) { case ReplaceState: { var _payload = update.payload; if (typeof _payload === 'function') { // Updater function { enterDisallowedContextReadInDEV(); if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) { _payload.call(instance, prevState, nextProps); } } var nextState = _payload.call(instance, prevState, nextProps); { exitDisallowedContextReadInDEV(); } return nextState; } // State object return _payload; } case CaptureUpdate: { workInProgress.effectTag = workInProgress.effectTag & ~ShouldCapture | DidCapture; } // Intentional fallthrough case UpdateState: { var _payload2 = update.payload; var partialState = void 0; if (typeof _payload2 === 'function') { // Updater function { enterDisallowedContextReadInDEV(); if (debugRenderPhaseSideEffects || debugRenderPhaseSideEffectsForStrictMode && workInProgress.mode & StrictMode) { _payload2.call(instance, prevState, nextProps); } } partialState = _payload2.call(instance, prevState, nextProps); { exitDisallowedContextReadInDEV(); } } else { // Partial state object partialState = _payload2; } if (partialState === null || partialState === undefined) { // Null and undefined are treated as no-ops. return prevState; } // Merge the partial state and the previous state. return _assign({}, prevState, partialState); } case ForceUpdate: { hasForceUpdate = true; return prevState; } } return prevState; } function processUpdateQueue(workInProgress, queue, props, instance, renderExpirationTime) { hasForceUpdate = false; queue = ensureWorkInProgressQueueIsAClone(workInProgress, queue); { currentlyProcessingQueue = queue; } // These values may change as we process the queue. var newBaseState = queue.baseState; var newFirstUpdate = null; var newExpirationTime = NoWork; // Iterate through the list of updates to compute the result. var update = queue.firstUpdate; var resultState = newBaseState; while (update !== null) { var updateExpirationTime = update.expirationTime; if (updateExpirationTime < renderExpirationTime) { // This update does not have sufficient priority. Skip it. if (newFirstUpdate === null) { // This is the first skipped update. It will be the first update in // the new list. newFirstUpdate = update; // Since this is the first update that was skipped, the current result // is the new base state. newBaseState = resultState; } // Since this update will remain in the list, update the remaining // expiration time. if (newExpirationTime < updateExpirationTime) { newExpirationTime = updateExpirationTime; } } else { // This update does have sufficient priority. Process it and compute // a new result. resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance); var _callback = update.callback; if (_callback !== null) { workInProgress.effectTag |= Callback; // Set this to null, in case it was mutated during an aborted render. update.nextEffect = null; if (queue.lastEffect === null) { queue.firstEffect = queue.lastEffect = update; } else { queue.lastEffect.nextEffect = update; queue.lastEffect = update; } } } // Continue to the next update. update = update.next; } // Separately, iterate though the list of captured updates. var newFirstCapturedUpdate = null; update = queue.firstCapturedUpdate; while (update !== null) { var _updateExpirationTime = update.expirationTime; if (_updateExpirationTime < renderExpirationTime) { // This update does not have sufficient priority. Skip it. if (newFirstCapturedUpdate === null) { // This is the first skipped captured update. It will be the first // update in the new list. newFirstCapturedUpdate = update; // If this is the first update that was skipped, the current result is // the new base state. if (newFirstUpdate === null) { newBaseState = resultState; } } // Since this update will remain in the list, update the remaining // expiration time. if (newExpirationTime < _updateExpirationTime) { newExpirationTime = _updateExpirationTime; } } else { // This update does have sufficient priority. Process it and compute // a new result. resultState = getStateFromUpdate(workInProgress, queue, update, resultState, props, instance); var _callback2 = update.callback; if (_callback2 !== null) { workInProgress.effectTag |= Callback; // Set this to null, in case it was mutated during an aborted render. update.nextEffect = null; if (queue.lastCapturedEffect === null) { queue.firstCapturedEffect = queue.lastCapturedEffect = update; } else { queue.lastCapturedEffect.nextEffect = update; queue.lastCapturedEffect = update; } } } update = update.next; } if (newFirstUpdate === null) { queue.lastUpdate = null; } if (newFirstCapturedUpdate === null) { queue.lastCapturedUpdate = null; } else { workInProgress.effectTag |= Callback; } if (newFirstUpdate === null && newFirstCapturedUpdate === null) { // We processed every update, without skipping. That means the new base // state is the same as the result state. newBaseState = resultState; } queue.baseState = newBaseState; queue.firstUpdate = newFirstUpdate; queue.firstCapturedUpdate = newFirstCapturedUpdate; // Set the remaining expiration time to be whatever is remaining in the queue. // This should be fine because the only two other things that contribute to // expiration time are props and context. We're already in the middle of the // begin phase by the time we start processing the queue, so we've already // dealt with the props. Context in components that specify // shouldComponentUpdate is tricky; but we'll have to account for // that regardless. workInProgress.expirationTime = newExpirationTime; workInProgress.memoizedState = resultState; { currentlyProcessingQueue = null; } } function callCallback(callback, context) { !(typeof callback === 'function') ? invariant(false, 'Invalid argument passed as callback. Expected a function. Instead received: %s', callback) : void 0; callback.call(context); } function resetHasForceUpdateBeforeProcessing() { hasForceUpdate = false; } function checkHasForceUpdateAfterProcessing() { return hasForceUpdate; } function commitUpdateQueue(finishedWork, finishedQueue, instance, renderExpirationTime) { // If the finished render included captured updates, and there are still // lower priority updates left over, we need to keep the captured updates // in the queue so that they are rebased and not dropped once we process the // queue again at the lower priority. if (finishedQueue.firstCapturedUpdate !== null) { // Join the captured update list to the end of the normal list. if (finishedQueue.lastUpdate !== null) { finishedQueue.lastUpdate.next = finishedQueue.firstCapturedUpdate; finishedQueue.lastUpdate = finishedQueue.lastCapturedUpdate; } // Clear the list of captured updates. finishedQueue.firstCapturedUpdate = finishedQueue.lastCapturedUpdate = null; } // Commit the effects commitUpdateEffects(finishedQueue.firstEffect, instance); finishedQueue.firstEffect = finishedQueue.lastEffect = null; commitUpdateEffects(finishedQueue.firstCapturedEffect, instance); finishedQueue.firstCapturedEffect = finishedQueue.lastCapturedEffect = null; } function commitUpdateEffects(effect, instance) { while (effect !== null) { var _callback3 = effect.callback; if (_callback3 !== null) { effect.callback = null; callCallback(_callback3, instance); } effect = effect.nextEffect; } } function createCapturedValue(value, source) { // If the value is an error, call this function immediately after it is thrown // so the stack is accurate. return { value: value, source: source, stack: getStackByFiberInDevAndProd(source) }; } function markUpdate(workInProgress) { // Tag the fiber with an update effect. This turns a Placement into // a PlacementAndUpdate. workInProgress.effectTag |= Update; } function markRef$1(workInProgress) { workInProgress.effectTag |= Ref; } var appendAllChildren = void 0; var updateHostContainer = void 0; var updateHostComponent$1 = void 0; var updateHostText$1 = void 0; if (supportsMutation) { // Mutation mode appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) { // We only have the top Fiber that was created but we need recurse down its // children to find all the terminal nodes. var node = workInProgress.child; while (node !== null) { if (node.tag === HostComponent || node.tag === HostText) { appendInitialChild(parent, node.stateNode); } else if (node.tag === HostPortal) { // If we have a portal child, then we don't want to traverse // down its children. Instead, we'll get insertions from each child in // the portal directly. } else if (node.child !== null) { node.child.return = node; node = node.child; continue; } if (node === workInProgress) { return; } while (node.sibling === null) { if (node.return === null || node.return === workInProgress) { return; } node = node.return; } node.sibling.return = node.return; node = node.sibling; } }; updateHostContainer = function (workInProgress) { // Noop }; updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) { // If we have an alternate, that means this is an update and we need to // schedule a side-effect to do the updates. var oldProps = current.memoizedProps; if (oldProps === newProps) { // In mutation mode, this is sufficient for a bailout because // we won't touch this node even if children changed. return; } // If we get updated because one of our children updated, we don't // have newProps so we'll have to reuse them. // TODO: Split the update API as separate for the props vs. children. // Even better would be if children weren't special cased at all tho. var instance = workInProgress.stateNode; var currentHostContext = getHostContext(); // TODO: Experiencing an error where oldProps is null. Suggests a host // component is hitting the resume path. Figure out why. Possibly // related to `hidden`. var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext); // TODO: Type this specific to this type of component. workInProgress.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there // is a new ref we mark this as an update. All the work is done in commitWork. if (updatePayload) { markUpdate(workInProgress); } }; updateHostText$1 = function (current, workInProgress, oldText, newText) { // If the text differs, mark it as an update. All the work in done in commitWork. if (oldText !== newText) { markUpdate(workInProgress); } }; } else if (supportsPersistence) { // Persistent host tree mode appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) { // We only have the top Fiber that was created but we need recurse down its // children to find all the terminal nodes. var node = workInProgress.child; while (node !== null) { // eslint-disable-next-line no-labels branches: if (node.tag === HostComponent) { var instance = node.stateNode; if (needsVisibilityToggle) { var props = node.memoizedProps; var type = node.type; if (isHidden) { // This child is inside a timed out tree. Hide it. instance = cloneHiddenInstance(instance, type, props, node); } else { // This child was previously inside a timed out tree. If it was not // updated during this render, it may need to be unhidden. Clone // again to be sure. instance = cloneUnhiddenInstance(instance, type, props, node); } node.stateNode = instance; } appendInitialChild(parent, instance); } else if (node.tag === HostText) { var _instance = node.stateNode; if (needsVisibilityToggle) { var text = node.memoizedProps; var rootContainerInstance = getRootHostContainer(); var currentHostContext = getHostContext(); if (isHidden) { _instance = createHiddenTextInstance(text, rootContainerInstance, currentHostContext, workInProgress); } else { _instance = createTextInstance(text, rootContainerInstance, currentHostContext, workInProgress); } node.stateNode = _instance; } appendInitialChild(parent, _instance); } else if (node.tag === HostPortal) { // If we have a portal child, then we don't want to traverse // down its children. Instead, we'll get insertions from each child in // the portal directly. } else if (node.tag === SuspenseComponent) { var current = node.alternate; if (current !== null) { var oldState = current.memoizedState; var newState = node.memoizedState; var oldIsHidden = oldState !== null; var newIsHidden = newState !== null; if (oldIsHidden !== newIsHidden) { // The placeholder either just timed out or switched back to the normal // children after having previously timed out. Toggle the visibility of // the direct host children. var primaryChildParent = newIsHidden ? node.child : node; if (primaryChildParent !== null) { appendAllChildren(parent, primaryChildParent, true, newIsHidden); } // eslint-disable-next-line no-labels break branches; } } if (node.child !== null) { // Continue traversing like normal node.child.return = node; node = node.child; continue; } } else if (node.child !== null) { node.child.return = node; node = node.child; continue; } // $FlowFixMe This is correct but Flow is confused by the labeled break. node = node; if (node === workInProgress) { return; } while (node.sibling === null) { if (node.return === null || node.return === workInProgress) { return; } node = node.return; } node.sibling.return = node.return; node = node.sibling; } }; // An unfortunate fork of appendAllChildren because we have two different parent types. var appendAllChildrenToContainer = function (containerChildSet, workInProgress, needsVisibilityToggle, isHidden) { // We only have the top Fiber that was created but we need recurse down its // children to find all the terminal nodes. var node = workInProgress.child; while (node !== null) { // eslint-disable-next-line no-labels branches: if (node.tag === HostComponent) { var instance = node.stateNode; if (needsVisibilityToggle) { var props = node.memoizedProps; var type = node.type; if (isHidden) { // This child is inside a timed out tree. Hide it. instance = cloneHiddenInstance(instance, type, props, node); } else { // This child was previously inside a timed out tree. If it was not // updated during this render, it may need to be unhidden. Clone // again to be sure. instance = cloneUnhiddenInstance(instance, type, props, node); } node.stateNode = instance; } appendChildToContainerChildSet(containerChildSet, instance); } else if (node.tag === HostText) { var _instance2 = node.stateNode; if (needsVisibilityToggle) { var text = node.memoizedProps; var rootContainerInstance = getRootHostContainer(); var currentHostContext = getHostContext(); if (isHidden) { _instance2 = createHiddenTextInstance(text, rootContainerInstance, currentHostContext, workInProgress); } else { _instance2 = createTextInstance(text, rootContainerInstance, currentHostContext, workInProgress); } node.stateNode = _instance2; } appendChildToContainerChildSet(containerChildSet, _instance2); } else if (node.tag === HostPortal) { // If we have a portal child, then we don't want to traverse // down its children. Instead, we'll get insertions from each child in // the portal directly. } else if (node.tag === SuspenseComponent) { var current = node.alternate; if (current !== null) { var oldState = current.memoizedState; var newState = node.memoizedState; var oldIsHidden = oldState !== null; var newIsHidden = newState !== null; if (oldIsHidden !== newIsHidden) { // The placeholder either just timed out or switched back to the normal // children after having previously timed out. Toggle the visibility of // the direct host children. var primaryChildParent = newIsHidden ? node.child : node; if (primaryChildParent !== null) { appendAllChildrenToContainer(containerChildSet, primaryChildParent, true, newIsHidden); } // eslint-disable-next-line no-labels break branches; } } if (node.child !== null) { // Continue traversing like normal node.child.return = node; node = node.child; continue; } } else if (node.child !== null) { node.child.return = node; node = node.child; continue; } // $FlowFixMe This is correct but Flow is confused by the labeled break. node = node; if (node === workInProgress) { return; } while (node.sibling === null) { if (node.return === null || node.return === workInProgress) { return; } node = node.return; } node.sibling.return = node.return; node = node.sibling; } }; updateHostContainer = function (workInProgress) { var portalOrRoot = workInProgress.stateNode; var childrenUnchanged = workInProgress.firstEffect === null; if (childrenUnchanged) { // No changes, just reuse the existing instance. } else { var container = portalOrRoot.containerInfo; var newChildSet = createContainerChildSet(container); // If children might have changed, we have to add them all to the set. appendAllChildrenToContainer(newChildSet, workInProgress, false, false); portalOrRoot.pendingChildren = newChildSet; // Schedule an update on the container to swap out the container. markUpdate(workInProgress); finalizeContainerChildren(container, newChildSet); } }; updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) { var currentInstance = current.stateNode; var oldProps = current.memoizedProps; // If there are no effects associated with this node, then none of our children had any updates. // This guarantees that we can reuse all of them. var childrenUnchanged = workInProgress.firstEffect === null; if (childrenUnchanged && oldProps === newProps) { // No changes, just reuse the existing instance. // Note that this might release a previous clone. workInProgress.stateNode = currentInstance; return; } var recyclableInstance = workInProgress.stateNode; var currentHostContext = getHostContext(); var updatePayload = null; if (oldProps !== newProps) { updatePayload = prepareUpdate(recyclableInstance, type, oldProps, newProps, rootContainerInstance, currentHostContext); } if (childrenUnchanged && updatePayload === null) { // No changes, just reuse the existing instance. // Note that this might release a previous clone. workInProgress.stateNode = currentInstance; return; } var newInstance = cloneInstance(currentInstance, updatePayload, type, oldProps, newProps, workInProgress, childrenUnchanged, recyclableInstance); if (finalizeInitialChildren(newInstance, type, newProps, rootContainerInstance, currentHostContext)) { markUpdate(workInProgress); } workInProgress.stateNode = newInstance; if (childrenUnchanged) { // If there are no other effects in this tree, we need to flag this node as having one. // Even though we're not going to use it for anything. // Otherwise parents won't know that there are new children to propagate upwards. markUpdate(workInProgress); } else { // If children might have changed, we have to add them all to the set. appendAllChildren(newInstance, workInProgress, false, false); } }; updateHostText$1 = function (current, workInProgress, oldText, newText) { if (oldText !== newText) { // If the text content differs, we'll create a new text instance for it. var rootContainerInstance = getRootHostContainer(); var currentHostContext = getHostContext(); workInProgress.stateNode = createTextInstance(newText, rootContainerInstance, currentHostContext, workInProgress); // We'll have to mark it as having an effect, even though we won't use the effect for anything. // This lets the parents know that at least one of their children has changed. markUpdate(workInProgress); } }; } else { // No host operations updateHostContainer = function (workInProgress) { // Noop }; updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) { // Noop }; updateHostText$1 = function (current, workInProgress, oldText, newText) { // Noop }; } function completeWork(current, workInProgress, renderExpirationTime) { var newProps = workInProgress.pendingProps; switch (workInProgress.tag) { case IndeterminateComponent: break; case LazyComponent: break; case SimpleMemoComponent: case FunctionComponent: break; case ClassComponent: { var Component = workInProgress.type; if (isContextProvider(Component)) { popContext(workInProgress); } break; } case HostRoot: { popHostContainer(workInProgress); popTopLevelContextObject(workInProgress); var fiberRoot = workInProgress.stateNode; if (fiberRoot.pendingContext) { fiberRoot.context = fiberRoot.pendingContext; fiberRoot.pendingContext = null; } if (current === null || current.child === null) { // If we hydrated, pop so that we can delete any remaining children // that weren't hydrated. popHydrationState(workInProgress); // This resets the hacky state to fix isMounted before committing. // TODO: Delete this when we delete isMounted and findDOMNode. workInProgress.effectTag &= ~Placement; } updateHostContainer(workInProgress); break; } case HostComponent: { popHostContext(workInProgress); var rootContainerInstance = getRootHostContainer(); var type = workInProgress.type; if (current !== null && workInProgress.stateNode != null) { updateHostComponent$1(current, workInProgress, type, newProps, rootContainerInstance); if (current.ref !== workInProgress.ref) { markRef$1(workInProgress); } } else { if (!newProps) { !(workInProgress.stateNode !== null) ? invariant(false, 'We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.') : void 0; // This can happen when we abort work. break; } var currentHostContext = getHostContext(); // TODO: Move createInstance to beginWork and keep it on a context // "stack" as the parent. Then append children as we go in beginWork // or completeWork depending on we want to add then top->down or // bottom->up. Top->down is faster in IE11. var wasHydrated = popHydrationState(workInProgress); if (wasHydrated) { // TODO: Move this and createInstance step into the beginPhase // to consolidate. if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, currentHostContext)) { // If changes to the hydrated node needs to be applied at the // commit-phase we mark this as such. markUpdate(workInProgress); } } else { var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress); appendAllChildren(instance, workInProgress, false, false); // Certain renderers require commit-time effects for initial mount. // (eg DOM renderer supports auto-focus for certain elements). // Make sure such renderers get scheduled for later work. if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance, currentHostContext)) { markUpdate(workInProgress); } workInProgress.stateNode = instance; } if (workInProgress.ref !== null) { // If there is a ref on a host node we need to schedule a callback markRef$1(workInProgress); } } break; } case HostText: { var newText = newProps; if (current && workInProgress.stateNode != null) { var oldText = current.memoizedProps; // If we have an alternate, that means this is an update and we need // to schedule a side-effect to do the updates. updateHostText$1(current, workInProgress, oldText, newText); } else { if (typeof newText !== 'string') { !(workInProgress.stateNode !== null) ? invariant(false, 'We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.') : void 0; // This can happen when we abort work. } var _rootContainerInstance = getRootHostContainer(); var _currentHostContext = getHostContext(); var _wasHydrated = popHydrationState(workInProgress); if (_wasHydrated) { if (prepareToHydrateHostTextInstance(workInProgress)) { markUpdate(workInProgress); } } else { workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress); } } break; } case ForwardRef: break; case SuspenseComponent: { var nextState = workInProgress.memoizedState; if ((workInProgress.effectTag & DidCapture) !== NoEffect) { // Something suspended. Re-render with the fallback children. workInProgress.expirationTime = renderExpirationTime; // Do not reset the effect list. return workInProgress; } var nextDidTimeout = nextState !== null; var prevDidTimeout = current !== null && current.memoizedState !== null; if (current !== null && !nextDidTimeout && prevDidTimeout) { // We just switched from the fallback to the normal children. Delete // the fallback. // TODO: Would it be better to store the fallback fragment on var currentFallbackChild = current.child.sibling; if (currentFallbackChild !== null) { // Deletions go at the beginning of the return fiber's effect list var first = workInProgress.firstEffect; if (first !== null) { workInProgress.firstEffect = currentFallbackChild; currentFallbackChild.nextEffect = first; } else { workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChild; currentFallbackChild.nextEffect = null; } currentFallbackChild.effectTag = Deletion; } } if (nextDidTimeout || prevDidTimeout) { // If the children are hidden, or if they were previous hidden, schedule // an effect to toggle their visibility. This is also used to attach a // retry listener to the promise. workInProgress.effectTag |= Update; } break; } case Fragment: break; case Mode: break; case Profiler: break; case HostPortal: popHostContainer(workInProgress); updateHostContainer(workInProgress); break; case ContextProvider: // Pop provider fiber popProvider(workInProgress); break; case ContextConsumer: break; case MemoComponent: break; case IncompleteClassComponent: { // Same as class component case. I put it down here so that the tags are // sequential to ensure this switch is compiled to a jump table. var _Component = workInProgress.type; if (isContextProvider(_Component)) { popContext(workInProgress); } break; } case DehydratedSuspenseComponent: { if (enableSuspenseServerRenderer) { if (current === null) { var _wasHydrated2 = popHydrationState(workInProgress); !_wasHydrated2 ? invariant(false, 'A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React.') : void 0; skipPastDehydratedSuspenseInstance(workInProgress); } else if ((workInProgress.effectTag & DidCapture) === NoEffect) { // This boundary did not suspend so it's now hydrated. // To handle any future suspense cases, we're going to now upgrade it // to a Suspense component. We detach it from the existing current fiber. current.alternate = null; workInProgress.alternate = null; workInProgress.tag = SuspenseComponent; workInProgress.memoizedState = null; workInProgress.stateNode = null; } } break; } default: invariant(false, 'Unknown unit of work tag. This error is likely caused by a bug in React. Please file an issue.'); } return null; } function shouldCaptureSuspense(workInProgress) { // In order to capture, the Suspense component must have a fallback prop. if (workInProgress.memoizedProps.fallback === undefined) { return false; } // If it was the primary children that just suspended, capture and render the // fallback. Otherwise, don't capture and bubble to the next boundary. var nextState = workInProgress.memoizedState; return nextState === null; } // This module is forked in different environments. // By default, return `true` to log errors to the console. // Forks can return `false` if this isn't desirable. function showErrorDialog(capturedError) { return true; } function logCapturedError(capturedError) { var logError = showErrorDialog(capturedError); // Allow injected showErrorDialog() to prevent default console.error logging. // This enables renderers like ReactNative to better manage redbox behavior. if (logError === false) { return; } var error = capturedError.error; { var componentName = capturedError.componentName, componentStack = capturedError.componentStack, errorBoundaryName = capturedError.errorBoundaryName, errorBoundaryFound = capturedError.errorBoundaryFound, willRetry = capturedError.willRetry; // Browsers support silencing uncaught errors by calling // `preventDefault()` in window `error` handler. // We record this information as an expando on the error. if (error != null && error._suppressLogging) { if (errorBoundaryFound && willRetry) { // The error is recoverable and was silenced. // Ignore it and don't print the stack addendum. // This is handy for testing error boundaries without noise. return; } // The error is fatal. Since the silencing might have // been accidental, we'll surface it anyway. // However, the browser would have silenced the original error // so we'll print it first, and then print the stack addendum. console.error(error); // For a more detailed description of this block, see: // https://github.com/facebook/react/pull/13384 } var componentNameMessage = componentName ? 'The above error occurred in the <' + componentName + '> component:' : 'The above error occurred in one of your React components:'; var errorBoundaryMessage = void 0; // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow. if (errorBoundaryFound && errorBoundaryName) { if (willRetry) { errorBoundaryMessage = 'React will try to recreate this component tree from scratch ' + ('using the error boundary you provided, ' + errorBoundaryName + '.'); } else { errorBoundaryMessage = 'This error was initially handled by the error boundary ' + errorBoundaryName + '.\n' + 'Recreating the tree from scratch failed so React will unmount the tree.'; } } else { errorBoundaryMessage = 'Consider adding an error boundary to your tree to customize error handling behavior.\n' + 'Visit https://fb.me/react-error-boundaries to learn more about error boundaries.'; } var combinedMessage = '' + componentNameMessage + componentStack + '\n\n' + ('' + errorBoundaryMessage); // In development, we provide our own message with just the component stack. // We don't include the original error message and JS stack because the browser // has already printed it. Even if the application swallows the error, it is still // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils. console.error(combinedMessage); } } var didWarnAboutUndefinedSnapshotBeforeUpdate = null; { didWarnAboutUndefinedSnapshotBeforeUpdate = new Set(); } var PossiblyWeakSet$1 = typeof WeakSet === 'function' ? WeakSet : Set; function logError(boundary, errorInfo) { var source = errorInfo.source; var stack = errorInfo.stack; if (stack === null && source !== null) { stack = getStackByFiberInDevAndProd(source); } var capturedError = { componentName: source !== null ? getComponentName(source.type) : null, componentStack: stack !== null ? stack : '', error: errorInfo.value, errorBoundary: null, errorBoundaryName: null, errorBoundaryFound: false, willRetry: false }; if (boundary !== null && boundary.tag === ClassComponent) { capturedError.errorBoundary = boundary.stateNode; capturedError.errorBoundaryName = getComponentName(boundary.type); capturedError.errorBoundaryFound = true; capturedError.willRetry = true; } try { logCapturedError(capturedError); } catch (e) { // This method must not throw, or React internal state will get messed up. // If console.error is overridden, or logCapturedError() shows a dialog that throws, // we want to report this error outside of the normal stack as a last resort. // https://github.com/facebook/react/issues/13188 setTimeout(function () { throw e; }); } } var callComponentWillUnmountWithTimer = function (current$$1, instance) { startPhaseTimer(current$$1, 'componentWillUnmount'); instance.props = current$$1.memoizedProps; instance.state = current$$1.memoizedState; instance.componentWillUnmount(); stopPhaseTimer(); }; // Capture errors so they don't interrupt unmounting. function safelyCallComponentWillUnmount(current$$1, instance) { { invokeGuardedCallback(null, callComponentWillUnmountWithTimer, null, current$$1, instance); if (hasCaughtError()) { var unmountError = clearCaughtError(); captureCommitPhaseError(current$$1, unmountError); } } } function safelyDetachRef(current$$1) { var ref = current$$1.ref; if (ref !== null) { if (typeof ref === 'function') { { invokeGuardedCallback(null, ref, null, null); if (hasCaughtError()) { var refError = clearCaughtError(); captureCommitPhaseError(current$$1, refError); } } } else { ref.current = null; } } } function safelyCallDestroy(current$$1, destroy) { { invokeGuardedCallback(null, destroy, null); if (hasCaughtError()) { var error = clearCaughtError(); captureCommitPhaseError(current$$1, error); } } } function commitBeforeMutationLifeCycles(current$$1, finishedWork) { switch (finishedWork.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { commitHookEffectList(UnmountSnapshot, NoEffect$1, finishedWork); return; } case ClassComponent: { if (finishedWork.effectTag & Snapshot) { if (current$$1 !== null) { var prevProps = current$$1.memoizedProps; var prevState = current$$1.memoizedState; startPhaseTimer(finishedWork, 'getSnapshotBeforeUpdate'); var instance = finishedWork.stateNode; // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. { if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { !(instance.props === finishedWork.memoizedProps) ? warning$1(false, 'Expected %s props to match memoized props before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0; !(instance.state === finishedWork.memoizedState) ? warning$1(false, 'Expected %s state to match memoized state before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0; } } var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState); { var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate; if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) { didWarnSet.add(finishedWork.type); warningWithoutStack$1(false, '%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentName(finishedWork.type)); } } instance.__reactInternalSnapshotBeforeUpdate = snapshot; stopPhaseTimer(); } } return; } case HostRoot: case HostComponent: case HostText: case HostPortal: case IncompleteClassComponent: // Nothing to do for these component types return; default: { invariant(false, 'This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.'); } } } function commitHookEffectList(unmountTag, mountTag, finishedWork) { var updateQueue = finishedWork.updateQueue; var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null; if (lastEffect !== null) { var firstEffect = lastEffect.next; var effect = firstEffect; do { if ((effect.tag & unmountTag) !== NoEffect$1) { // Unmount var destroy = effect.destroy; effect.destroy = undefined; if (destroy !== undefined) { destroy(); } } if ((effect.tag & mountTag) !== NoEffect$1) { // Mount var create = effect.create; effect.destroy = create(); { var _destroy = effect.destroy; if (_destroy !== undefined && typeof _destroy !== 'function') { var addendum = void 0; if (_destroy === null) { addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).'; } else if (typeof _destroy.then === 'function') { addendum = '\n\nIt looks like you wrote useEffect(async () => ...) or returned a Promise. ' + 'Instead, write the async function inside your effect ' + 'and call it immediately:\n\n' + 'useEffect(() => {\n' + ' async function fetchData() {\n' + ' // You can await here\n' + ' const response = await MyAPI.getData(someId);\n' + ' // ...\n' + ' }\n' + ' fetchData();\n' + '}, [someId]); // Or [] if effect doesn\'t need props or state\n\n' + 'Learn more about data fetching with Hooks: https://fb.me/react-hooks-data-fetching'; } else { addendum = ' You returned: ' + _destroy; } warningWithoutStack$1(false, 'An effect function must not return anything besides a function, ' + 'which is used for clean-up.%s%s', addendum, getStackByFiberInDevAndProd(finishedWork)); } } } effect = effect.next; } while (effect !== firstEffect); } } function commitPassiveHookEffects(finishedWork) { commitHookEffectList(UnmountPassive, NoEffect$1, finishedWork); commitHookEffectList(NoEffect$1, MountPassive, finishedWork); } function commitLifeCycles(finishedRoot, current$$1, finishedWork, committedExpirationTime) { switch (finishedWork.tag) { case FunctionComponent: case ForwardRef: case SimpleMemoComponent: { commitHookEffectList(UnmountLayout, MountLayout, finishedWork); break; } case ClassComponent: { var instance = finishedWork.stateNode; if (finishedWork.effectTag & Update) { if (current$$1 === null) { startPhaseTimer(finishedWork, 'componentDidMount'); // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. { if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { !(instance.props === finishedWork.memoizedProps) ? warning$1(false, 'Expected %s props to match memoized props before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0; !(instance.state === finishedWork.memoizedState) ? warning$1(false, 'Expected %s state to match memoized state before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0; } } instance.componentDidMount(); stopPhaseTimer(); } else { var prevProps = finishedWork.elementType === finishedWork.type ? current$$1.memoizedProps : resolveDefaultProps(finishedWork.type, current$$1.memoizedProps); var prevState = current$$1.memoizedState; startPhaseTimer(finishedWork, 'componentDidUpdate'); // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. { if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { !(instance.props === finishedWork.memoizedProps) ? warning$1(false, 'Expected %s props to match memoized props before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0; !(instance.state === finishedWork.memoizedState) ? warning$1(false, 'Expected %s state to match memoized state before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0; } } instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate); stopPhaseTimer(); } } var updateQueue = finishedWork.updateQueue; if (updateQueue !== null) { { if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) { !(instance.props === finishedWork.memoizedProps) ? warning$1(false, 'Expected %s props to match memoized props before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0; !(instance.state === finishedWork.memoizedState) ? warning$1(false, 'Expected %s state to match memoized state before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0; } } // We could update instance props and state here, // but instead we rely on them being set during last render. // TODO: revisit this when we implement resuming. commitUpdateQueue(finishedWork, updateQueue, instance, committedExpirationTime); } return; } case HostRoot: { var _updateQueue = finishedWork.updateQueue; if (_updateQueue !== null) { var _instance = null; if (finishedWork.child !== null) { switch (finishedWork.child.tag) { case HostComponent: _instance = getPublicInstance(finishedWork.child.stateNode); break; case ClassComponent: _instance = finishedWork.child.stateNode; break; } } commitUpdateQueue(finishedWork, _updateQueue, _instance, committedExpirationTime); } return; } case HostComponent: { var _instance2 = finishedWork.stateNode; // Renderers may schedule work to be done after host components are mounted // (eg DOM renderer may schedule auto-focus for inputs and form controls). // These effects should only be committed when components are first mounted, // aka when there is no current/alternate. if (current$$1 === null && finishedWork.effectTag & Update) { var type = finishedWork.type; var props = finishedWork.memoizedProps; commitMount(_instance2, type, props, finishedWork); } return; } case HostText: { // We have no life-cycles associated with text. return; } case HostPortal: { // We have no life-cycles associated with portals. return; } case Profiler: { if (enableProfilerTimer) { var onRender = finishedWork.memoizedProps.onRender; if (enableSchedulerTracing) { onRender(finishedWork.memoizedProps.id, current$$1 === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime(), finishedRoot.memoizedInteractions); } else { onRender(finishedWork.memoizedProps.id, current$$1 === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime()); } } return; } case SuspenseComponent: break; case IncompleteClassComponent: break; default: { invariant(false, 'This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.'); } } } function hideOrUnhideAllChildren(finishedWork, isHidden) { if (supportsMutation) { // We only have the top Fiber that was inserted but we need to recurse down its var node = finishedWork; while (true) { if (node.tag === HostComponent) { var instance = node.stateNode; if (isHidden) { hideInstance(instance); } else { unhideInstance(node.stateNode, node.memoizedProps); } } else if (node.tag === HostText) { var _instance3 = node.stateNode; if (isHidden) { hideTextInstance(_instance3); } else { unhideTextInstance(_instance3, node.memoizedProps); } } else if (node.tag === SuspenseComponent && node.memoizedState !== null) { // Found a nested Suspense component that timed out. Skip over the var fallbackChildFragment = node.child.sibling; fallbackChildFragment.return = node; node = fallbackChildFragment; continue; } else if (node.child !== null) { node.child.return = node; node = node.child; continue; } if (node === finishedWork) { return; } while (node.sibling === null) { if (node.return === null || node.return === finishedWork) { return; } node = node.return; } node.sibling.return = node.return; node = node.sibling; } } } function commitAttachRef(finishedWork) { var ref = finishedWork.ref; if (ref !== null) { var instance = finishedWork.stateNode; var instanceToUse = void 0; switch (finishedWork.tag) { case HostComponent: instanceToUse = getPublicInstance(instance); break; default: instanceToUse = instance; } if (typeof ref === 'function') { ref(instanceToUse); } else { { if (!ref.hasOwnProperty('current')) { warningWithoutStack$1(false, 'Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().%s', getComponentName(finishedWork.type), getStackByFiberInDevAndProd(finishedWork)); } } ref.current = instanceToUse; } } } function commitDetachRef(current$$1) { var currentRef = current$$1.ref; if (currentRef !== null) { if (typeof currentRef === 'function') { currentRef(null); } else { currentRef.current = null; } } } // User-originating errors (lifecycles and refs) should not interrupt // deletion, so don't let them throw. Host-originating errors should // interrupt deletion, so it's okay function commitUnmount(current$$1) { onCommitUnmount(current$$1); switch (current$$1.tag) { case FunctionComponent: case ForwardRef: case MemoComponent: case SimpleMemoComponent: { var updateQueue = current$$1.updateQueue; if (updateQueue !== null) { var lastEffect = updateQueue.lastEffect; if (lastEffect !== null) { var firstEffect = lastEffect.next; var effect = firstEffect; do { var destroy = effect.destroy; if (destroy !== undefined) { safelyCallDestroy(current$$1, destroy); } effect = effect.next; } while (effect !== firstEffect); } } break; } case ClassComponent: { safelyDetachRef(current$$1); var instance = current$$1.stateNode; if (typeof instance.componentWillUnmount === 'function') { safelyCallComponentWillUnmount(current$$1, instance); } return; } case HostComponent: { safelyDetachRef(current$$1); return; } case HostPortal: { // TODO: this is recursive. // We are also not using this parent because // the portal will get pushed immediately. if (supportsMutation) { unmountHostComponents(current$$1); } else if (supportsPersistence) { emptyPortalContainer(current$$1); } return; } } } function commitNestedUnmounts(root) { // While we're inside a removed host node we don't want to call // removeChild on the inner nodes because they're removed by the top // call anyway. We also want to call componentWillUnmount on all // composites before this host node is removed from the tree. Therefore var node = root; while (true) { commitUnmount(node); // Visit children because they may contain more composite or host nodes. // Skip portals because commitUnmount() currently visits them recursively. if (node.child !== null && ( // If we use mutation we drill down into portals using commitUnmount above. // If we don't use mutation we drill down into portals here instead. !supportsMutation || node.tag !== HostPortal)) { node.child.return = node; node = node.child; continue; } if (node === root) { return; } while (node.sibling === null) { if (node.return === null || node.return === root) { return; } node = node.return; } node.sibling.return = node.return; node = node.sibling; } } function detachFiber(current$$1) { // Cut off the return pointers to disconnect it from the tree. Ideally, we // should clear the child pointer of the parent alternate to let this // get GC:ed but we don't know which for sure which parent is the current // one so we'll settle for GC:ing the subtree of this child. This child // itself will be GC:ed when the parent updates the next time. current$$1.return = null; current$$1.child = null; current$$1.memoizedState = null; current$$1.updateQueue = null; var alternate = current$$1.alternate; if (alternate !== null) { alternate.return = null; alternate.child = null; alternate.memoizedState = null; alternate.updateQueue = null; } } function emptyPortalContainer(current$$1) { if (!supportsPersistence) { return; } var portal = current$$1.stateNode; var containerInfo = portal.containerInfo; var emptyChildSet = createContainerChildSet(containerInfo); replaceContainerChildren(containerInfo, emptyChildSet); } function commitContainer(finishedWork) { if (!supportsPersistence) { return; } switch (finishedWork.tag) { case ClassComponent: { return; } case HostComponent: { return; } case HostText: { return; } case HostRoot: case HostPortal: { var portalOrRoot = finishedWork.stateNode; var containerInfo = portalOrRoot.containerInfo, _pendingChildren = portalOrRoot.pendingChildren; replaceContainerChildren(containerInfo, _pendingChildren); return; } default: { invariant(false, 'This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.'); } } } function getHostParentFiber(fiber) { var parent = fiber.return; while (parent !== null) { if (isHostParent(parent)) { return parent; } parent = parent.return; } invariant(false, 'Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.'); } function isHostParent(fiber) { return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal; } function getHostSibling(fiber) { // We're going to search forward into the tree until we find a sibling host // node. Unfortunately, if multiple insertions are done in a row we have to // search past them. This leads to exponential search for the next sibling. var node = fiber; siblings: while (true) { // If we didn't find anything, let's try the next sibling. while (node.sibling === null) { if (node.return === null || isHostParent(node.return)) { // If we pop out of the root or hit the parent the fiber we are the // last sibling. return null; } node = node.return; } node.sibling.return = node.return; node = node.sibling; while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedSuspenseComponent) { // If it is not host node and, we might have a host node inside it. // Try to search down until we find one. if (node.effectTag & Placement) { // If we don't have a child, try the siblings instead. continue siblings; } // If we don't have a child, try the siblings instead. // We also skip portals because they are not part of this host tree. if (node.child === null || node.tag === HostPortal) { continue siblings; } else { node.child.return = node; node = node.child; } } // Check if this host node is stable or about to be placed. if (!(node.effectTag & Placement)) { // Found it! return node.stateNode; } } } function commitPlacement(finishedWork) { if (!supportsMutation) { return; } // Recursively insert all host nodes into the parent. var parentFiber = getHostParentFiber(finishedWork); // Note: these two variables *must* always be updated together. var parent = void 0; var isContainer = void 0; switch (parentFiber.tag) { case HostComponent: parent = parentFiber.stateNode; isContainer = false; break; case HostRoot: parent = parentFiber.stateNode.containerInfo; isContainer = true; break; case HostPortal: parent = parentFiber.stateNode.containerInfo; isContainer = true; break; default: invariant(false, 'Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue.'); } if (parentFiber.effectTag & ContentReset) { // Reset the text content of the parent before doing any insertions resetTextContent(parent); // Clear ContentReset from the effect tag parentFiber.effectTag &= ~ContentReset; } var before = getHostSibling(finishedWork); // We only have the top Fiber that was inserted but we need to recurse down its // children to find all the terminal nodes. var node = finishedWork; while (true) { if (node.tag === HostComponent || node.tag === HostText) { if (before) { if (isContainer) { insertInContainerBefore(parent, node.stateNode, before); } else { insertBefore(parent, node.stateNode, before); } } else { if (isContainer) { appendChildToContainer(parent, node.stateNode); } else { appendChild(parent, node.stateNode); } } } else if (node.tag === HostPortal) { // If the insertion itself is a portal, then we don't want to traverse // down its children. Instead, we'll get insertions from each child in // the portal directly. } else if (node.child !== null) { node.child.return = node; node = node.child; continue; } if (node === finishedWork) { return; } while (node.sibling === null) { if (node.return === null || node.return === finishedWork) { return; } node = node.return; } node.sibling.return = node.return; node = node.sibling; } } function unmountHostComponents(current$$1) { // We only have the top Fiber that was deleted but we need to recurse down its var node = current$$1; // Each iteration, currentParent is populated with node's host parent if not // currentParentIsValid. var currentParentIsValid = false; // Note: these two variables *must* always be updated together. var currentParent = void 0; var currentParentIsContainer = void 0; while (true) { if (!currentParentIsValid) { var parent = node.return; findParent: while (true) { !(parent !== null) ? invariant(false, 'Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.') : void 0; switch (parent.tag) { case HostComponent: currentParent = parent.stateNode; currentParentIsContainer = false; break findParent; case HostRoot: currentParent = parent.stateNode.containerInfo; currentParentIsContainer = true; break findParent; case HostPortal: currentParent = parent.stateNode.containerInfo; currentParentIsContainer = true; break findParent; } parent = parent.return; } currentParentIsValid = true; } if (node.tag === HostComponent || node.tag === HostText) { commitNestedUnmounts(node); // After all the children have unmounted, it is now safe to remove the // node from the tree. if (currentParentIsContainer) { removeChildFromContainer(currentParent, node.stateNode); } else { removeChild(currentParent, node.stateNode); } // Don't visit children because we already visited them. } else if (enableSuspenseServerRenderer && node.tag === DehydratedSuspenseComponent) { // Delete the dehydrated suspense boundary and all of its content. if (currentParentIsContainer) { clearSuspenseBoundaryFromContainer(currentParent, node.stateNode); } else { clearSuspenseBoundary(currentParent, node.stateNode); } } else if (node.tag === HostPortal) { if (node.child !== null) { // When we go into a portal, it becomes the parent to remove from. // We will reassign it back when we pop the portal on the way up. currentParent = node.stateNode.containerInfo; currentParentIsContainer = true; // Visit children because portals might contain host components. node.child.return = node; node = node.child; continue; } } else { commitUnmount(node); // Visit children because we may find more host components below. if (node.child !== null) { node.child.return = node; node = node.child; continue; } } if (node === current$$1) { return; } while (node.sibling === null) { if (node.return === null || node.return === current$$1) { return; } node = node.return; if (node.tag === HostPortal) { // When we go out of the portal, we need to restore the parent. // Since we don't keep a stack of them, we will search for it. currentParentIsValid = false; } } node.sibling.return = node.return; node = node.sibling; } } function commitDeletion(current$$1) { if (supportsMutation) { // Recursively delete all host nodes from the parent. // Detach refs and call componentWillUnmount() on the whole subtree. unmountHostComponents(current$$1); } else { // Detach refs and call componentWillUnmount() on the whole subtree. commitNestedUnmounts(current$$1); } detachFiber(current$$1); } function commitWork(current$$1, finishedWork) { if (!supportsMutation) { switch (finishedWork.tag) { case FunctionComponent: case ForwardRef: case MemoComponent: case SimpleMemoComponent: { // Note: We currently never use MountMutation, but useLayout uses // UnmountMutation. commitHookEffectList(UnmountMutation, MountMutation, finishedWork); return; } } commitContainer(finishedWork); return; } switch (finishedWork.tag) { case FunctionComponent: case ForwardRef: case MemoComponent: case SimpleMemoComponent: { // Note: We currently never use MountMutation, but useLayout uses // UnmountMutation. commitHookEffectList(UnmountMutation, MountMutation, finishedWork); return; } case ClassComponent: { return; } case HostComponent: { var instance = finishedWork.stateNode; if (instance != null) { // Commit the work prepared earlier. var newProps = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps // as the newProps. The updatePayload will contain the real change in // this case. var oldProps = current$$1 !== null ? current$$1.memoizedProps : newProps; var type = finishedWork.type; // TODO: Type the updateQueue to be specific to host components. var updatePayload = finishedWork.updateQueue; finishedWork.updateQueue = null; if (updatePayload !== null) { commitUpdate(instance, updatePayload, type, oldProps, newProps, finishedWork); } } return; } case HostText: { !(finishedWork.stateNode !== null) ? invariant(false, 'This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue.') : void 0; var textInstance = finishedWork.stateNode; var newText = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps // as the newProps. The updatePayload will contain the real change in // this case. var oldText = current$$1 !== null ? current$$1.memoizedProps : newText; commitTextUpdate(textInstance, oldText, newText); return; } case HostRoot: { return; } case Profiler: { return; } case SuspenseComponent: { var newState = finishedWork.memoizedState; var newDidTimeout = void 0; var primaryChildParent = finishedWork; if (newState === null) { newDidTimeout = false; } else { newDidTimeout = true; primaryChildParent = finishedWork.child; if (newState.timedOutAt === NoWork) { // If the children had not already timed out, record the time. // This is used to compute the elapsed time during subsequent // attempts to render the children. newState.timedOutAt = requestCurrentTime(); } } if (primaryChildParent !== null) { hideOrUnhideAllChildren(primaryChildParent, newDidTimeout); } // If this boundary just timed out, then it will have a set of thenables. // For each thenable, attach a listener so that when it resolves, React // attempts to re-render the boundary in the primary (pre-timeout) state. var thenables = finishedWork.updateQueue; if (thenables !== null) { finishedWork.updateQueue = null; var retryCache = finishedWork.stateNode; if (retryCache === null) { retryCache = finishedWork.stateNode = new PossiblyWeakSet$1(); } thenables.forEach(function (thenable) { // Memoize using the boundary fiber to prevent redundant listeners. var retry = retryTimedOutBoundary.bind(null, finishedWork, thenable); if (enableSchedulerTracing) { retry = tracing.unstable_wrap(retry); } if (!retryCache.has(thenable)) { retryCache.add(thenable); thenable.then(retry, retry); } }); } return; } case IncompleteClassComponent: { return; } default: { invariant(false, 'This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.'); } } } function commitResetTextContent(current$$1) { if (!supportsMutation) { return; } resetTextContent(current$$1.stateNode); } var PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set; var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; function createRootErrorUpdate(fiber, errorInfo, expirationTime) { var update = createUpdate(expirationTime); // Unmount the root by rendering null. update.tag = CaptureUpdate; // Caution: React DevTools currently depends on this property // being called "element". update.payload = { element: null }; var error = errorInfo.value; update.callback = function () { onUncaughtError(error); logError(fiber, errorInfo); }; return update; } function createClassErrorUpdate(fiber, errorInfo, expirationTime) { var update = createUpdate(expirationTime); update.tag = CaptureUpdate; var getDerivedStateFromError = fiber.type.getDerivedStateFromError; if (typeof getDerivedStateFromError === 'function') { var error = errorInfo.value; update.payload = function () { return getDerivedStateFromError(error); }; } var inst = fiber.stateNode; if (inst !== null && typeof inst.componentDidCatch === 'function') { update.callback = function callback() { if (typeof getDerivedStateFromError !== 'function') { // To preserve the preexisting retry behavior of error boundaries, // we keep track of which ones already failed during this batch. // This gets reset before we yield back to the browser. // TODO: Warn in strict mode if getDerivedStateFromError is // not defined. markLegacyErrorBoundaryAsFailed(this); } var error = errorInfo.value; var stack = errorInfo.stack; logError(fiber, errorInfo); this.componentDidCatch(error, { componentStack: stack !== null ? stack : '' }); { if (typeof getDerivedStateFromError !== 'function') { // If componentDidCatch is the only error boundary method defined, // then it needs to call setState to recover from errors. // If no state update is scheduled then the boundary will swallow the error. !(fiber.expirationTime === Sync) ? warningWithoutStack$1(false, '%s: Error boundaries should implement getDerivedStateFromError(). ' + 'In that method, return a state update to display an error message or fallback UI.', getComponentName(fiber.type) || 'Unknown') : void 0; } } }; } return update; } function attachPingListener(root, renderExpirationTime, thenable) { // Attach a listener to the promise to "ping" the root and retry. But // only if one does not already exist for the current render expiration // time (which acts like a "thread ID" here). var pingCache = root.pingCache; var threadIDs = void 0; if (pingCache === null) { pingCache = root.pingCache = new PossiblyWeakMap(); threadIDs = new Set(); pingCache.set(thenable, threadIDs); } else { threadIDs = pingCache.get(thenable); if (threadIDs === undefined) { threadIDs = new Set(); pingCache.set(thenable, threadIDs); } } if (!threadIDs.has(renderExpirationTime)) { // Memoize using the thread ID to prevent redundant listeners. threadIDs.add(renderExpirationTime); var ping = pingSuspendedRoot.bind(null, root, thenable, renderExpirationTime); if (enableSchedulerTracing) { ping = tracing.unstable_wrap(ping); } thenable.then(ping, ping); } } function throwException(root, returnFiber, sourceFiber, value, renderExpirationTime) { // The source fiber did not complete. sourceFiber.effectTag |= Incomplete; // Its effect list is no longer valid. sourceFiber.firstEffect = sourceFiber.lastEffect = null; if (value !== null && typeof value === 'object' && typeof value.then === 'function') { // This is a thenable. var thenable = value; // Find the earliest timeout threshold of all the placeholders in the // ancestor path. We could avoid this traversal by storing the thresholds on // the stack, but we choose not to because we only hit this path if we're // IO-bound (i.e. if something suspends). Whereas the stack is used even in // the non-IO- bound case. var _workInProgress = returnFiber; var earliestTimeoutMs = -1; var startTimeMs = -1; do { if (_workInProgress.tag === SuspenseComponent) { var current$$1 = _workInProgress.alternate; if (current$$1 !== null) { var currentState = current$$1.memoizedState; if (currentState !== null) { // Reached a boundary that already timed out. Do not search // any further. var timedOutAt = currentState.timedOutAt; startTimeMs = expirationTimeToMs(timedOutAt); // Do not search any further. break; } } var timeoutPropMs = _workInProgress.pendingProps.maxDuration; if (typeof timeoutPropMs === 'number') { if (timeoutPropMs <= 0) { earliestTimeoutMs = 0; } else if (earliestTimeoutMs === -1 || timeoutPropMs < earliestTimeoutMs) { earliestTimeoutMs = timeoutPropMs; } } } // If there is a DehydratedSuspenseComponent we don't have to do anything because // if something suspends inside it, we will simply leave that as dehydrated. It // will never timeout. _workInProgress = _workInProgress.return; } while (_workInProgress !== null); // Schedule the nearest Suspense to re-render the timed out view. _workInProgress = returnFiber; do { if (_workInProgress.tag === SuspenseComponent && shouldCaptureSuspense(_workInProgress)) { // Found the nearest boundary. // Stash the promise on the boundary fiber. If the boundary times out, we'll var thenables = _workInProgress.updateQueue; if (thenables === null) { var updateQueue = new Set(); updateQueue.add(thenable); _workInProgress.updateQueue = updateQueue; } else { thenables.add(thenable); } // If the boundary is outside of concurrent mode, we should *not* // suspend the commit. Pretend as if the suspended component rendered // null and keep rendering. In the commit phase, we'll schedule a // subsequent synchronous update to re-render the Suspense. // // Note: It doesn't matter whether the component that suspended was // inside a concurrent mode tree. If the Suspense is outside of it, we // should *not* suspend the commit. if ((_workInProgress.mode & ConcurrentMode) === NoEffect) { _workInProgress.effectTag |= DidCapture; // We're going to commit this fiber even though it didn't complete. // But we shouldn't call any lifecycle methods or callbacks. Remove // all lifecycle effect tags. sourceFiber.effectTag &= ~(LifecycleEffectMask | Incomplete); if (sourceFiber.tag === ClassComponent) { var currentSourceFiber = sourceFiber.alternate; if (currentSourceFiber === null) { // This is a new mount. Change the tag so it's not mistaken for a // completed class component. For example, we should not call // componentWillUnmount if it is deleted. sourceFiber.tag = IncompleteClassComponent; } else { // When we try rendering again, we should not reuse the current fiber, // since it's known to be in an inconsistent state. Use a force updte to // prevent a bail out. var update = createUpdate(Sync); update.tag = ForceUpdate; enqueueUpdate(sourceFiber, update); } } // The source fiber did not complete. Mark it with Sync priority to // indicate that it still has pending work. sourceFiber.expirationTime = Sync; // Exit without suspending. return; } // Confirmed that the boundary is in a concurrent mode tree. Continue // with the normal suspend path. attachPingListener(root, renderExpirationTime, thenable); var absoluteTimeoutMs = void 0; if (earliestTimeoutMs === -1) { // If no explicit threshold is given, default to an arbitrarily large // value. The actual size doesn't matter because the threshold for the // whole tree will be clamped to the expiration time. absoluteTimeoutMs = maxSigned31BitInt; } else { if (startTimeMs === -1) { // This suspend happened outside of any already timed-out // placeholders. We don't know exactly when the update was // scheduled, but we can infer an approximate start time from the // expiration time. First, find the earliest uncommitted expiration // time in the tree, including work that is suspended. Then subtract // the offset used to compute an async update's expiration time. // This will cause high priority (interactive) work to expire // earlier than necessary, but we can account for this by adjusting // for the Just Noticeable Difference. var earliestExpirationTime = findEarliestOutstandingPriorityLevel(root, renderExpirationTime); var earliestExpirationTimeMs = expirationTimeToMs(earliestExpirationTime); startTimeMs = earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION; } absoluteTimeoutMs = startTimeMs + earliestTimeoutMs; } // Mark the earliest timeout in the suspended fiber's ancestor path. // After completing the root, we'll take the largest of all the // suspended fiber's timeouts and use it to compute a timeout for the // whole tree. renderDidSuspend(root, absoluteTimeoutMs, renderExpirationTime); _workInProgress.effectTag |= ShouldCapture; _workInProgress.expirationTime = renderExpirationTime; return; } else if (enableSuspenseServerRenderer && _workInProgress.tag === DehydratedSuspenseComponent) { attachPingListener(root, renderExpirationTime, thenable); // Since we already have a current fiber, we can eagerly add a retry listener. var retryCache = _workInProgress.memoizedState; if (retryCache === null) { retryCache = _workInProgress.memoizedState = new PossiblyWeakSet(); var _current = _workInProgress.alternate; !_current ? invariant(false, 'A dehydrated suspense boundary must commit before trying to render. This is probably a bug in React.') : void 0; _current.memoizedState = retryCache; } // Memoize using the boundary fiber to prevent redundant listeners. if (!retryCache.has(thenable)) { retryCache.add(thenable); var retry = retryTimedOutBoundary.bind(null, _workInProgress, thenable); if (enableSchedulerTracing) { retry = tracing.unstable_wrap(retry); } thenable.then(retry, retry); } _workInProgress.effectTag |= ShouldCapture; _workInProgress.expirationTime = renderExpirationTime; return; } // This boundary already captured during this render. Continue to the next // boundary. _workInProgress = _workInProgress.return; } while (_workInProgress !== null); // No boundary was found. Fallthrough to error mode. // TODO: Use invariant so the message is stripped in prod? value = new Error((getComponentName(sourceFiber.type) || 'A React component') + ' suspended while rendering, but no fallback UI was specified.\n' + '\n' + 'Add a <Suspense fallback=...> component higher in the tree to ' + 'provide a loading indicator or placeholder to display.' + getStackByFiberInDevAndProd(sourceFiber)); } // We didn't find a boundary that could handle this type of exception. Start // over and traverse parent path again, this time treating the exception // as an error. renderDidError(); value = createCapturedValue(value, sourceFiber); var workInProgress = returnFiber; do { switch (workInProgress.tag) { case HostRoot: { var _errorInfo = value; workInProgress.effectTag |= ShouldCapture; workInProgress.expirationTime = renderExpirationTime; var _update = createRootErrorUpdate(workInProgress, _errorInfo, renderExpirationTime); enqueueCapturedUpdate(workInProgress, _update); return; } case ClassComponent: // Capture and retry var errorInfo = value; var ctor = workInProgress.type; var instance = workInProgress.stateNode; if ((workInProgress.effectTag & DidCapture) === NoEffect && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance))) { workInProgress.effectTag |= ShouldCapture; workInProgress.expirationTime = renderExpirationTime; // Schedule the error boundary to re-render using updated state var _update2 = createClassErrorUpdate(workInProgress, errorInfo, renderExpirationTime); enqueueCapturedUpdate(workInProgress, _update2); return; } break; default: break; } workInProgress = workInProgress.return; } while (workInProgress !== null); } function unwindWork(workInProgress, renderExpirationTime) { switch (workInProgress.tag) { case ClassComponent: { var Component = workInProgress.type; if (isContextProvider(Component)) { popContext(workInProgress); } var effectTag = workInProgress.effectTag; if (effectTag & ShouldCapture) { workInProgress.effectTag = effectTag & ~ShouldCapture | DidCapture; return workInProgress; } return null; } case HostRoot: { popHostContainer(workInProgress); popTopLevelContextObject(workInProgress); var _effectTag = workInProgress.effectTag; !((_effectTag & DidCapture) === NoEffect) ? invariant(false, 'The root failed to unmount after an error. This is likely a bug in React. Please file an issue.') : void 0; workInProgress.effectTag = _effectTag & ~ShouldCapture | DidCapture; return workInProgress; } case HostComponent: { // TODO: popHydrationState popHostContext(workInProgress); return null; } case SuspenseComponent: { var _effectTag2 = workInProgress.effectTag; if (_effectTag2 & ShouldCapture) { workInProgress.effectTag = _effectTag2 & ~ShouldCapture | DidCapture; // Captured a suspense effect. Re-render the boundary. return workInProgress; } return null; } case DehydratedSuspenseComponent: { if (enableSuspenseServerRenderer) { // TODO: popHydrationState var _effectTag3 = workInProgress.effectTag; if (_effectTag3 & ShouldCapture) { workInProgress.effectTag = _effectTag3 & ~ShouldCapture | DidCapture; // Captured a suspense effect. Re-render the boundary. return workInProgress; } } return null; } case HostPortal: popHostContainer(workInProgress); return null; case ContextProvider: popProvider(workInProgress); return null; default: return null; } } function unwindInterruptedWork(interruptedWork) { switch (interruptedWork.tag) { case ClassComponent: { var childContextTypes = interruptedWork.type.childContextTypes; if (childContextTypes !== null && childContextTypes !== undefined) { popContext(interruptedWork); } break; } case HostRoot: { popHostContainer(interruptedWork); popTopLevelContextObject(interruptedWork); break; } case HostComponent: { popHostContext(interruptedWork); break; } case HostPortal: popHostContainer(interruptedWork); break; case ContextProvider: popProvider(interruptedWork); break; default: break; } } var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; var ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner; var didWarnAboutStateTransition = void 0; var didWarnSetStateChildContext = void 0; var warnAboutUpdateOnUnmounted = void 0; var warnAboutInvalidUpdates = void 0; if (enableSchedulerTracing) { // Provide explicit error message when production+profiling bundle of e.g. react-dom // is used with production (non-profiling) bundle of scheduler/tracing !(tracing.__interactionsRef != null && tracing.__interactionsRef.current != null) ? invariant(false, 'It is not supported to run the profiling version of a renderer (for example, `react-dom/profiling`) without also replacing the `scheduler/tracing` module with `scheduler/tracing-profiling`. Your bundler might have a setting for aliasing both modules. Learn more at http://fb.me/react-profiling') : void 0; } { didWarnAboutStateTransition = false; didWarnSetStateChildContext = false; var didWarnStateUpdateForUnmountedComponent = {}; warnAboutUpdateOnUnmounted = function (fiber, isClass) { // We show the whole stack but dedupe on the top component's name because // the problematic code almost always lies inside that component. var componentName = getComponentName(fiber.type) || 'ReactComponent'; if (didWarnStateUpdateForUnmountedComponent[componentName]) { return; } warningWithoutStack$1(false, "Can't perform a React state update on an unmounted component. This " + 'is a no-op, but it indicates a memory leak in your application. To ' + 'fix, cancel all subscriptions and asynchronous tasks in %s.%s', isClass ? 'the componentWillUnmount method' : 'a useEffect cleanup function', getStackByFiberInDevAndProd(fiber)); didWarnStateUpdateForUnmountedComponent[componentName] = true; }; warnAboutInvalidUpdates = function (instance) { switch (phase) { case 'getChildContext': if (didWarnSetStateChildContext) { return; } warningWithoutStack$1(false, 'setState(...): Cannot call setState() inside getChildContext()'); didWarnSetStateChildContext = true; break; case 'render': if (didWarnAboutStateTransition) { return; } warningWithoutStack$1(false, 'Cannot update during an existing state transition (such as within ' + '`render`). Render methods should be a pure function of props and state.'); didWarnAboutStateTransition = true; break; } }; } // Used to ensure computeUniqueAsyncExpiration is monotonically decreasing. var lastUniqueAsyncExpiration = Sync - 1; var isWorking = false; // The next work in progress fiber that we're currently working on. var nextUnitOfWork = null; var nextRoot = null; // The time at which we're currently rendering work. var nextRenderExpirationTime = NoWork; var nextLatestAbsoluteTimeoutMs = -1; var nextRenderDidError = false; // The next fiber with an effect that we're currently committing. var nextEffect = null; var isCommitting$1 = false; var rootWithPendingPassiveEffects = null; var passiveEffectCallbackHandle = null; var passiveEffectCallback = null; var legacyErrorBoundariesThatAlreadyFailed = null; // Used for performance tracking. var interruptedBy = null; var stashedWorkInProgressProperties = void 0; var replayUnitOfWork = void 0; var mayReplayFailedUnitOfWork = void 0; var isReplayingFailedUnitOfWork = void 0; var originalReplayError = void 0; var rethrowOriginalError = void 0; if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) { stashedWorkInProgressProperties = null; mayReplayFailedUnitOfWork = true; isReplayingFailedUnitOfWork = false; originalReplayError = null; replayUnitOfWork = function (failedUnitOfWork, thrownValue, isYieldy) { if (thrownValue !== null && typeof thrownValue === 'object' && typeof thrownValue.then === 'function') { // Don't replay promises. Treat everything else like an error. // TODO: Need to figure out a different strategy if/when we add // support for catching other types. return; } // Restore the original state of the work-in-progress if (stashedWorkInProgressProperties === null) { // This should never happen. Don't throw because this code is DEV-only. warningWithoutStack$1(false, 'Could not replay rendering after an error. This is likely a bug in React. ' + 'Please file an issue.'); return; } assignFiberPropertiesInDEV(failedUnitOfWork, stashedWorkInProgressProperties); switch (failedUnitOfWork.tag) { case HostRoot: popHostContainer(failedUnitOfWork); popTopLevelContextObject(failedUnitOfWork); break; case HostComponent: popHostContext(failedUnitOfWork); break; case ClassComponent: { var Component = failedUnitOfWork.type; if (isContextProvider(Component)) { popContext(failedUnitOfWork); } break; } case HostPortal: popHostContainer(failedUnitOfWork); break; case ContextProvider: popProvider(failedUnitOfWork); break; } // Replay the begin phase. isReplayingFailedUnitOfWork = true; originalReplayError = thrownValue; invokeGuardedCallback(null, workLoop, null, isYieldy); isReplayingFailedUnitOfWork = false; originalReplayError = null; if (hasCaughtError()) { var replayError = clearCaughtError(); if (replayError != null && thrownValue != null) { try { // Reading the expando property is intentionally // inside `try` because it might be a getter or Proxy. if (replayError._suppressLogging) { // Also suppress logging for the original error. thrownValue._suppressLogging = true; } } catch (inner) { // Ignore. } } } else { // If the begin phase did not fail the second time, set this pointer // back to the original value. nextUnitOfWork = failedUnitOfWork; } }; rethrowOriginalError = function () { throw originalReplayError; }; } function resetStack() { if (nextUnitOfWork !== null) { var interruptedWork = nextUnitOfWork.return; while (interruptedWork !== null) { unwindInterruptedWork(interruptedWork); interruptedWork = interruptedWork.return; } } { ReactStrictModeWarnings.discardPendingWarnings(); checkThatStackIsEmpty(); } nextRoot = null; nextRenderExpirationTime = NoWork; nextLatestAbsoluteTimeoutMs = -1; nextRenderDidError = false; nextUnitOfWork = null; } function commitAllHostEffects() { while (nextEffect !== null) { { setCurrentFiber(nextEffect); } recordEffect(); var effectTag = nextEffect.effectTag; if (effectTag & ContentReset) { commitResetTextContent(nextEffect); } if (effectTag & Ref) { var current$$1 = nextEffect.alternate; if (current$$1 !== null) { commitDetachRef(current$$1); } } // The following switch statement is only concerned about placement, // updates, and deletions. To avoid needing to add a case for every // possible bitmap value, we remove the secondary effects from the // effect tag and switch on that value. var primaryEffectTag = effectTag & (Placement | Update | Deletion); switch (primaryEffectTag) { case Placement: { commitPlacement(nextEffect); // Clear the "placement" from effect tag so that we know that this is inserted, before // any life-cycles like componentDidMount gets called. // TODO: findDOMNode doesn't rely on this any more but isMounted // does and isMounted is deprecated anyway so we should be able // to kill this. nextEffect.effectTag &= ~Placement; break; } case PlacementAndUpdate: { // Placement commitPlacement(nextEffect); // Clear the "placement" from effect tag so that we know that this is inserted, before // any life-cycles like componentDidMount gets called. nextEffect.effectTag &= ~Placement; // Update var _current = nextEffect.alternate; commitWork(_current, nextEffect); break; } case Update: { var _current2 = nextEffect.alternate; commitWork(_current2, nextEffect); break; } case Deletion: { commitDeletion(nextEffect); break; } } nextEffect = nextEffect.nextEffect; } { resetCurrentFiber(); } } function commitBeforeMutationLifecycles() { while (nextEffect !== null) { { setCurrentFiber(nextEffect); } var effectTag = nextEffect.effectTag; if (effectTag & Snapshot) { recordEffect(); var current$$1 = nextEffect.alternate; commitBeforeMutationLifeCycles(current$$1, nextEffect); } nextEffect = nextEffect.nextEffect; } { resetCurrentFiber(); } } function commitAllLifeCycles(finishedRoot, committedExpirationTime) { { ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings(); ReactStrictModeWarnings.flushLegacyContextWarning(); if (warnAboutDeprecatedLifecycles) { ReactStrictModeWarnings.flushPendingDeprecationWarnings(); } } while (nextEffect !== null) { { setCurrentFiber(nextEffect); } var effectTag = nextEffect.effectTag; if (effectTag & (Update | Callback)) { recordEffect(); var current$$1 = nextEffect.alternate; commitLifeCycles(finishedRoot, current$$1, nextEffect, committedExpirationTime); } if (effectTag & Ref) { recordEffect(); commitAttachRef(nextEffect); } if (effectTag & Passive) { rootWithPendingPassiveEffects = finishedRoot; } nextEffect = nextEffect.nextEffect; } { resetCurrentFiber(); } } function commitPassiveEffects(root, firstEffect) { rootWithPendingPassiveEffects = null; passiveEffectCallbackHandle = null; passiveEffectCallback = null; // Set this to true to prevent re-entrancy var previousIsRendering = isRendering; isRendering = true; var effect = firstEffect; do { { setCurrentFiber(effect); } if (effect.effectTag & Passive) { var didError = false; var error = void 0; { invokeGuardedCallback(null, commitPassiveHookEffects, null, effect); if (hasCaughtError()) { didError = true; error = clearCaughtError(); } } if (didError) { captureCommitPhaseError(effect, error); } } effect = effect.nextEffect; } while (effect !== null); { resetCurrentFiber(); } isRendering = previousIsRendering; // Check if work was scheduled by one of the effects var rootExpirationTime = root.expirationTime; if (rootExpirationTime !== NoWork) { requestWork(root, rootExpirationTime); } // Flush any sync work that was scheduled by effects if (!isBatchingUpdates && !isRendering) { performSyncWork(); } } function isAlreadyFailedLegacyErrorBoundary(instance) { return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance); } function markLegacyErrorBoundaryAsFailed(instance) { if (legacyErrorBoundariesThatAlreadyFailed === null) { legacyErrorBoundariesThatAlreadyFailed = new Set([instance]); } else { legacyErrorBoundariesThatAlreadyFailed.add(instance); } } function flushPassiveEffects() { if (passiveEffectCallbackHandle !== null) { cancelPassiveEffects(passiveEffectCallbackHandle); } if (passiveEffectCallback !== null) { // We call the scheduled callback instead of commitPassiveEffects directly // to ensure tracing works correctly. passiveEffectCallback(); } } function commitRoot(root, finishedWork) { isWorking = true; isCommitting$1 = true; startCommitTimer(); !(root.current !== finishedWork) ? invariant(false, 'Cannot commit the same tree as before. This is probably a bug related to the return field. This error is likely caused by a bug in React. Please file an issue.') : void 0; var committedExpirationTime = root.pendingCommitExpirationTime; !(committedExpirationTime !== NoWork) ? invariant(false, 'Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue.') : void 0; root.pendingCommitExpirationTime = NoWork; // Update the pending priority levels to account for the work that we are // about to commit. This needs to happen before calling the lifecycles, since // they may schedule additional updates. var updateExpirationTimeBeforeCommit = finishedWork.expirationTime; var childExpirationTimeBeforeCommit = finishedWork.childExpirationTime; var earliestRemainingTimeBeforeCommit = childExpirationTimeBeforeCommit > updateExpirationTimeBeforeCommit ? childExpirationTimeBeforeCommit : updateExpirationTimeBeforeCommit; markCommittedPriorityLevels(root, earliestRemainingTimeBeforeCommit); var prevInteractions = null; if (enableSchedulerTracing) { // Restore any pending interactions at this point, // So that cascading work triggered during the render phase will be accounted for. prevInteractions = tracing.__interactionsRef.current; tracing.__interactionsRef.current = root.memoizedInteractions; } // Reset this to null before calling lifecycles ReactCurrentOwner$2.current = null; var firstEffect = void 0; if (finishedWork.effectTag > PerformedWork) { // A fiber's effect list consists only of its children, not itself. So if // the root has an effect, we need to add it to the end of the list. The // resulting list is the set that would belong to the root's parent, if // it had one; that is, all the effects in the tree including the root. if (finishedWork.lastEffect !== null) { finishedWork.lastEffect.nextEffect = finishedWork; firstEffect = finishedWork.firstEffect; } else { firstEffect = finishedWork; } } else { // There is no effect on the root. firstEffect = finishedWork.firstEffect; } prepareForCommit(root.containerInfo); // Invoke instances of getSnapshotBeforeUpdate before mutation. nextEffect = firstEffect; startCommitSnapshotEffectsTimer(); while (nextEffect !== null) { var didError = false; var error = void 0; { invokeGuardedCallback(null, commitBeforeMutationLifecycles, null); if (hasCaughtError()) { didError = true; error = clearCaughtError(); } } if (didError) { !(nextEffect !== null) ? invariant(false, 'Should have next effect. This error is likely caused by a bug in React. Please file an issue.') : void 0; captureCommitPhaseError(nextEffect, error); // Clean-up if (nextEffect !== null) { nextEffect = nextEffect.nextEffect; } } } stopCommitSnapshotEffectsTimer(); if (enableProfilerTimer) { // Mark the current commit time to be shared by all Profilers in this batch. // This enables them to be grouped later. recordCommitTime(); } // Commit all the side-effects within a tree. We'll do this in two passes. // The first pass performs all the host insertions, updates, deletions and // ref unmounts. nextEffect = firstEffect; startCommitHostEffectsTimer(); while (nextEffect !== null) { var _didError = false; var _error = void 0; { invokeGuardedCallback(null, commitAllHostEffects, null); if (hasCaughtError()) { _didError = true; _error = clearCaughtError(); } } if (_didError) { !(nextEffect !== null) ? invariant(false, 'Should have next effect. This error is likely caused by a bug in React. Please file an issue.') : void 0; captureCommitPhaseError(nextEffect, _error); // Clean-up if (nextEffect !== null) { nextEffect = nextEffect.nextEffect; } } } stopCommitHostEffectsTimer(); resetAfterCommit(root.containerInfo); // The work-in-progress tree is now the current tree. This must come after // the first pass of the commit phase, so that the previous tree is still // current during componentWillUnmount, but before the second pass, so that // the finished work is current during componentDidMount/Update. root.current = finishedWork; // In the second pass we'll perform all life-cycles and ref callbacks. // Life-cycles happen as a separate pass so that all placements, updates, // and deletions in the entire tree have already been invoked. // This pass also triggers any renderer-specific initial effects. nextEffect = firstEffect; startCommitLifeCyclesTimer(); while (nextEffect !== null) { var _didError2 = false; var _error2 = void 0; { invokeGuardedCallback(null, commitAllLifeCycles, null, root, committedExpirationTime); if (hasCaughtError()) { _didError2 = true; _error2 = clearCaughtError(); } } if (_didError2) { !(nextEffect !== null) ? invariant(false, 'Should have next effect. This error is likely caused by a bug in React. Please file an issue.') : void 0; captureCommitPhaseError(nextEffect, _error2); if (nextEffect !== null) { nextEffect = nextEffect.nextEffect; } } } if (firstEffect !== null && rootWithPendingPassiveEffects !== null) { // This commit included a passive effect. These do not need to fire until // after the next paint. Schedule an callback to fire them in an async // event. To ensure serial execution, the callback will be flushed early if // we enter rootWithPendingPassiveEffects commit phase before then. var callback = commitPassiveEffects.bind(null, root, firstEffect); if (enableSchedulerTracing) { // TODO: Avoid this extra callback by mutating the tracing ref directly, // like we do at the beginning of commitRoot. I've opted not to do that // here because that code is still in flux. callback = tracing.unstable_wrap(callback); } passiveEffectCallbackHandle = scheduler.unstable_runWithPriority(scheduler.unstable_NormalPriority, function () { return schedulePassiveEffects(callback); }); passiveEffectCallback = callback; } isCommitting$1 = false; isWorking = false; stopCommitLifeCyclesTimer(); stopCommitTimer(); onCommitRoot(finishedWork.stateNode); if (true && ReactFiberInstrumentation_1.debugTool) { ReactFiberInstrumentation_1.debugTool.onCommitWork(finishedWork); } var updateExpirationTimeAfterCommit = finishedWork.expirationTime; var childExpirationTimeAfterCommit = finishedWork.childExpirationTime; var earliestRemainingTimeAfterCommit = childExpirationTimeAfterCommit > updateExpirationTimeAfterCommit ? childExpirationTimeAfterCommit : updateExpirationTimeAfterCommit; if (earliestRemainingTimeAfterCommit === NoWork) { // If there's no remaining work, we can clear the set of already failed // error boundaries. legacyErrorBoundariesThatAlreadyFailed = null; } onCommit(root, earliestRemainingTimeAfterCommit); if (enableSchedulerTracing) { tracing.__interactionsRef.current = prevInteractions; var subscriber = void 0; try { subscriber = tracing.__subscriberRef.current; if (subscriber !== null && root.memoizedInteractions.size > 0) { var threadID = computeThreadID(committedExpirationTime, root.interactionThreadID); subscriber.onWorkStopped(root.memoizedInteractions, threadID); } } catch (error) { // It's not safe for commitRoot() to throw. // Store the error for now and we'll re-throw in finishRendering(). if (!hasUnhandledError) { hasUnhandledError = true; unhandledError = error; } } finally { // Clear completed interactions from the pending Map. // Unless the render was suspended or cascading work was scheduled, // In which case– leave pending interactions until the subsequent render. var pendingInteractionMap = root.pendingInteractionMap; pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) { // Only decrement the pending interaction count if we're done. // If there's still work at the current priority, // That indicates that we are waiting for suspense data. if (scheduledExpirationTime > earliestRemainingTimeAfterCommit) { pendingInteractionMap.delete(scheduledExpirationTime); scheduledInteractions.forEach(function (interaction) { interaction.__count--; if (subscriber !== null && interaction.__count === 0) { try { subscriber.onInteractionScheduledWorkCompleted(interaction); } catch (error) { // It's not safe for commitRoot() to throw. // Store the error for now and we'll re-throw in finishRendering(). if (!hasUnhandledError) { hasUnhandledError = true; unhandledError = error; } } } }); } }); } } } function resetChildExpirationTime(workInProgress, renderTime) { if (renderTime !== Never && workInProgress.childExpirationTime === Never) { // The children of this component are hidden. Don't bubble their // expiration times. return; } var newChildExpirationTime = NoWork; // Bubble up the earliest expiration time. if (enableProfilerTimer && workInProgress.mode & ProfileMode) { // We're in profiling mode. // Let's use this same traversal to update the render durations. var actualDuration = workInProgress.actualDuration; var treeBaseDuration = workInProgress.selfBaseDuration; // When a fiber is cloned, its actualDuration is reset to 0. // This value will only be updated if work is done on the fiber (i.e. it doesn't bailout). // When work is done, it should bubble to the parent's actualDuration. // If the fiber has not been cloned though, (meaning no work was done), // Then this value will reflect the amount of time spent working on a previous render. // In that case it should not bubble. // We determine whether it was cloned by comparing the child pointer. var shouldBubbleActualDurations = workInProgress.alternate === null || workInProgress.child !== workInProgress.alternate.child; var child = workInProgress.child; while (child !== null) { var childUpdateExpirationTime = child.expirationTime; var childChildExpirationTime = child.childExpirationTime; if (childUpdateExpirationTime > newChildExpirationTime) { newChildExpirationTime = childUpdateExpirationTime; } if (childChildExpirationTime > newChildExpirationTime) { newChildExpirationTime = childChildExpirationTime; } if (shouldBubbleActualDurations) { actualDuration += child.actualDuration; } treeBaseDuration += child.treeBaseDuration; child = child.sibling; } workInProgress.actualDuration = actualDuration; workInProgress.treeBaseDuration = treeBaseDuration; } else { var _child = workInProgress.child; while (_child !== null) { var _childUpdateExpirationTime = _child.expirationTime; var _childChildExpirationTime = _child.childExpirationTime; if (_childUpdateExpirationTime > newChildExpirationTime) { newChildExpirationTime = _childUpdateExpirationTime; } if (_childChildExpirationTime > newChildExpirationTime) { newChildExpirationTime = _childChildExpirationTime; } _child = _child.sibling; } } workInProgress.childExpirationTime = newChildExpirationTime; } function completeUnitOfWork(workInProgress) { // Attempt to complete the current unit of work, then move to the // next sibling. If there are no more siblings, return to the // parent fiber. while (true) { // The current, flushed, state of this fiber is the alternate. // Ideally nothing should rely on this, but relying on it here // means that we don't need an additional field on the work in // progress. var current$$1 = workInProgress.alternate; { setCurrentFiber(workInProgress); } var returnFiber = workInProgress.return; var siblingFiber = workInProgress.sibling; if ((workInProgress.effectTag & Incomplete) === NoEffect) { if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) { // Don't replay if it fails during completion phase. mayReplayFailedUnitOfWork = false; } // This fiber completed. // Remember we're completing this unit so we can find a boundary if it fails. nextUnitOfWork = workInProgress; if (enableProfilerTimer) { if (workInProgress.mode & ProfileMode) { startProfilerTimer(workInProgress); } nextUnitOfWork = completeWork(current$$1, workInProgress, nextRenderExpirationTime); if (workInProgress.mode & ProfileMode) { // Update render duration assuming we didn't error. stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false); } } else { nextUnitOfWork = completeWork(current$$1, workInProgress, nextRenderExpirationTime); } if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) { // We're out of completion phase so replaying is fine now. mayReplayFailedUnitOfWork = true; } stopWorkTimer(workInProgress); resetChildExpirationTime(workInProgress, nextRenderExpirationTime); { resetCurrentFiber(); } if (nextUnitOfWork !== null) { // Completing this fiber spawned new work. Work on that next. return nextUnitOfWork; } if (returnFiber !== null && // Do not append effects to parents if a sibling failed to complete (returnFiber.effectTag & Incomplete) === NoEffect) { // Append all the effects of the subtree and this fiber onto the effect // list of the parent. The completion order of the children affects the // side-effect order. if (returnFiber.firstEffect === null) { returnFiber.firstEffect = workInProgress.firstEffect; } if (workInProgress.lastEffect !== null) { if (returnFiber.lastEffect !== null) { returnFiber.lastEffect.nextEffect = workInProgress.firstEffect; } returnFiber.lastEffect = workInProgress.lastEffect; } // If this fiber had side-effects, we append it AFTER the children's // side-effects. We can perform certain side-effects earlier if // needed, by doing multiple passes over the effect list. We don't want // to schedule our own side-effect on our own list because if end up // reusing children we'll schedule this effect onto itself since we're // at the end. var effectTag = workInProgress.effectTag; // Skip both NoWork and PerformedWork tags when creating the effect list. // PerformedWork effect is read by React DevTools but shouldn't be committed. if (effectTag > PerformedWork) { if (returnFiber.lastEffect !== null) { returnFiber.lastEffect.nextEffect = workInProgress; } else { returnFiber.firstEffect = workInProgress; } returnFiber.lastEffect = workInProgress; } } if (true && ReactFiberInstrumentation_1.debugTool) { ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress); } if (siblingFiber !== null) { // If there is more work to do in this returnFiber, do that next. return siblingFiber; } else if (returnFiber !== null) { // If there's no more work in this returnFiber. Complete the returnFiber. workInProgress = returnFiber; continue; } else { // We've reached the root. return null; } } else { if (enableProfilerTimer && workInProgress.mode & ProfileMode) { // Record the render duration for the fiber that errored. stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false); // Include the time spent working on failed children before continuing. var actualDuration = workInProgress.actualDuration; var child = workInProgress.child; while (child !== null) { actualDuration += child.actualDuration; child = child.sibling; } workInProgress.actualDuration = actualDuration; } // This fiber did not complete because something threw. Pop values off // the stack without entering the complete phase. If this is a boundary, // capture values if possible. var next = unwindWork(workInProgress, nextRenderExpirationTime); // Because this fiber did not complete, don't reset its expiration time. if (workInProgress.effectTag & DidCapture) { // Restarting an error boundary stopFailedWorkTimer(workInProgress); } else { stopWorkTimer(workInProgress); } { resetCurrentFiber(); } if (next !== null) { stopWorkTimer(workInProgress); if (true && ReactFiberInstrumentation_1.debugTool) { ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress); } // If completing this work spawned new work, do that next. We'll come // back here again. // Since we're restarting, remove anything that is not a host effect // from the effect tag. next.effectTag &= HostEffectMask; return next; } if (returnFiber !== null) { // Mark the parent fiber as incomplete and clear its effect list. returnFiber.firstEffect = returnFiber.lastEffect = null; returnFiber.effectTag |= Incomplete; } if (true && ReactFiberInstrumentation_1.debugTool) { ReactFiberInstrumentation_1.debugTool.onCompleteWork(workInProgress); } if (siblingFiber !== null) { // If there is more work to do in this returnFiber, do that next. return siblingFiber; } else if (returnFiber !== null) { // If there's no more work in this returnFiber. Complete the returnFiber. workInProgress = returnFiber; continue; } else { return null; } } } // Without this explicit null return Flow complains of invalid return type // TODO Remove the above while(true) loop // eslint-disable-next-line no-unreachable return null; } function performUnitOfWork(workInProgress) { // The current, flushed, state of this fiber is the alternate. // Ideally nothing should rely on this, but relying on it here // means that we don't need an additional field on the work in // progress. var current$$1 = workInProgress.alternate; // See if beginning this work spawns more work. startWorkTimer(workInProgress); { setCurrentFiber(workInProgress); } if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) { stashedWorkInProgressProperties = assignFiberPropertiesInDEV(stashedWorkInProgressProperties, workInProgress); } var next = void 0; if (enableProfilerTimer) { if (workInProgress.mode & ProfileMode) { startProfilerTimer(workInProgress); } next = beginWork(current$$1, workInProgress, nextRenderExpirationTime); workInProgress.memoizedProps = workInProgress.pendingProps; if (workInProgress.mode & ProfileMode) { // Record the render duration assuming we didn't bailout (or error). stopProfilerTimerIfRunningAndRecordDelta(workInProgress, true); } } else { next = beginWork(current$$1, workInProgress, nextRenderExpirationTime); workInProgress.memoizedProps = workInProgress.pendingProps; } { resetCurrentFiber(); if (isReplayingFailedUnitOfWork) { // Currently replaying a failed unit of work. This should be unreachable, // because the render phase is meant to be idempotent, and it should // have thrown again. Since it didn't, rethrow the original error, so // React's internal stack is not misaligned. rethrowOriginalError(); } } if (true && ReactFiberInstrumentation_1.debugTool) { ReactFiberInstrumentation_1.debugTool.onBeginWork(workInProgress); } if (next === null) { // If this doesn't spawn new work, complete the current work. next = completeUnitOfWork(workInProgress); } ReactCurrentOwner$2.current = null; return next; } function workLoop(isYieldy) { if (!isYieldy) { // Flush work without yielding while (nextUnitOfWork !== null) { nextUnitOfWork = performUnitOfWork(nextUnitOfWork); } } else { // Flush asynchronous work until there's a higher priority event while (nextUnitOfWork !== null && !shouldYieldToRenderer()) { nextUnitOfWork = performUnitOfWork(nextUnitOfWork); } } } function renderRoot(root, isYieldy) { !!isWorking ? invariant(false, 'renderRoot was called recursively. This error is likely caused by a bug in React. Please file an issue.') : void 0; flushPassiveEffects(); isWorking = true; var previousDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = ContextOnlyDispatcher; var expirationTime = root.nextExpirationTimeToWorkOn; // Check if we're starting from a fresh stack, or if we're resuming from // previously yielded work. if (expirationTime !== nextRenderExpirationTime || root !== nextRoot || nextUnitOfWork === null) { // Reset the stack and start working from the root. resetStack(); nextRoot = root; nextRenderExpirationTime = expirationTime; nextUnitOfWork = createWorkInProgress(nextRoot.current, null, nextRenderExpirationTime); root.pendingCommitExpirationTime = NoWork; if (enableSchedulerTracing) { // Determine which interactions this batch of work currently includes, // So that we can accurately attribute time spent working on it, var interactions = new Set(); root.pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) { if (scheduledExpirationTime >= expirationTime) { scheduledInteractions.forEach(function (interaction) { return interactions.add(interaction); }); } }); // Store the current set of interactions on the FiberRoot for a few reasons: // We can re-use it in hot functions like renderRoot() without having to recalculate it. // We will also use it in commitWork() to pass to any Profiler onRender() hooks. // This also provides DevTools with a way to access it when the onCommitRoot() hook is called. root.memoizedInteractions = interactions; if (interactions.size > 0) { var subscriber = tracing.__subscriberRef.current; if (subscriber !== null) { var threadID = computeThreadID(expirationTime, root.interactionThreadID); try { subscriber.onWorkStarted(interactions, threadID); } catch (error) { // Work thrown by an interaction tracing subscriber should be rethrown, // But only once it's safe (to avoid leaving the scheduler in an invalid state). // Store the error for now and we'll re-throw in finishRendering(). if (!hasUnhandledError) { hasUnhandledError = true; unhandledError = error; } } } } } } var prevInteractions = null; if (enableSchedulerTracing) { // We're about to start new traced work. // Restore pending interactions so cascading work triggered during the render phase will be accounted for. prevInteractions = tracing.__interactionsRef.current; tracing.__interactionsRef.current = root.memoizedInteractions; } var didFatal = false; startWorkLoopTimer(nextUnitOfWork); do { try { workLoop(isYieldy); } catch (thrownValue) { resetContextDependences(); resetHooks(); // Reset in case completion throws. // This is only used in DEV and when replaying is on. var mayReplay = void 0; if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) { mayReplay = mayReplayFailedUnitOfWork; mayReplayFailedUnitOfWork = true; } if (nextUnitOfWork === null) { // This is a fatal error. didFatal = true; onUncaughtError(thrownValue); } else { if (enableProfilerTimer && nextUnitOfWork.mode & ProfileMode) { // Record the time spent rendering before an error was thrown. // This avoids inaccurate Profiler durations in the case of a suspended render. stopProfilerTimerIfRunningAndRecordDelta(nextUnitOfWork, true); } { // Reset global debug state // We assume this is defined in DEV resetCurrentlyProcessingQueue(); } if (true && replayFailedUnitOfWorkWithInvokeGuardedCallback) { if (mayReplay) { var failedUnitOfWork = nextUnitOfWork; replayUnitOfWork(failedUnitOfWork, thrownValue, isYieldy); } } // TODO: we already know this isn't true in some cases. // At least this shows a nicer error message until we figure out the cause. // https://github.com/facebook/react/issues/12449#issuecomment-386727431 !(nextUnitOfWork !== null) ? invariant(false, 'Failed to replay rendering after an error. This is likely caused by a bug in React. Please file an issue with a reproducing case to help us find it.') : void 0; var sourceFiber = nextUnitOfWork; var returnFiber = sourceFiber.return; if (returnFiber === null) { // This is the root. The root could capture its own errors. However, // we don't know if it errors before or after we pushed the host // context. This information is needed to avoid a stack mismatch. // Because we're not sure, treat this as a fatal error. We could track // which phase it fails in, but doesn't seem worth it. At least // for now. didFatal = true; onUncaughtError(thrownValue); } else { throwException(root, returnFiber, sourceFiber, thrownValue, nextRenderExpirationTime); nextUnitOfWork = completeUnitOfWork(sourceFiber); continue; } } } break; } while (true); if (enableSchedulerTracing) { // Traced work is done for now; restore the previous interactions. tracing.__interactionsRef.current = prevInteractions; } // We're done performing work. Time to clean up. isWorking = false; ReactCurrentDispatcher.current = previousDispatcher; resetContextDependences(); resetHooks(); // Yield back to main thread. if (didFatal) { var _didCompleteRoot = false; stopWorkLoopTimer(interruptedBy, _didCompleteRoot); interruptedBy = null; // There was a fatal error. { resetStackAfterFatalErrorInDev(); } // `nextRoot` points to the in-progress root. A non-null value indicates // that we're in the middle of an async render. Set it to null to indicate // there's no more work to be done in the current batch. nextRoot = null; onFatal(root); return; } if (nextUnitOfWork !== null) { // There's still remaining async work in this tree, but we ran out of time // in the current frame. Yield back to the renderer. Unless we're // interrupted by a higher priority update, we'll continue later from where // we left off. var _didCompleteRoot2 = false; stopWorkLoopTimer(interruptedBy, _didCompleteRoot2); interruptedBy = null; onYield(root); return; } // We completed the whole tree. var didCompleteRoot = true; stopWorkLoopTimer(interruptedBy, didCompleteRoot); var rootWorkInProgress = root.current.alternate; !(rootWorkInProgress !== null) ? invariant(false, 'Finished root should have a work-in-progress. This error is likely caused by a bug in React. Please file an issue.') : void 0; // `nextRoot` points to the in-progress root. A non-null value indicates // that we're in the middle of an async render. Set it to null to indicate // there's no more work to be done in the current batch. nextRoot = null; interruptedBy = null; if (nextRenderDidError) { // There was an error if (hasLowerPriorityWork(root, expirationTime)) { // There's lower priority work. If so, it may have the effect of fixing // the exception that was just thrown. Exit without committing. This is // similar to a suspend, but without a timeout because we're not waiting // for a promise to resolve. React will restart at the lower // priority level. markSuspendedPriorityLevel(root, expirationTime); var suspendedExpirationTime = expirationTime; var rootExpirationTime = root.expirationTime; onSuspend(root, rootWorkInProgress, suspendedExpirationTime, rootExpirationTime, -1 // Indicates no timeout ); return; } else if ( // There's no lower priority work, but we're rendering asynchronously. // Synchronously attempt to render the same level one more time. This is // similar to a suspend, but without a timeout because we're not waiting // for a promise to resolve. !root.didError && isYieldy) { root.didError = true; var _suspendedExpirationTime = root.nextExpirationTimeToWorkOn = expirationTime; var _rootExpirationTime = root.expirationTime = Sync; onSuspend(root, rootWorkInProgress, _suspendedExpirationTime, _rootExpirationTime, -1 // Indicates no timeout ); return; } } if (isYieldy && nextLatestAbsoluteTimeoutMs !== -1) { // The tree was suspended. var _suspendedExpirationTime2 = expirationTime; markSuspendedPriorityLevel(root, _suspendedExpirationTime2); // Find the earliest uncommitted expiration time in the tree, including // work that is suspended. The timeout threshold cannot be longer than // the overall expiration. var earliestExpirationTime = findEarliestOutstandingPriorityLevel(root, expirationTime); var earliestExpirationTimeMs = expirationTimeToMs(earliestExpirationTime); if (earliestExpirationTimeMs < nextLatestAbsoluteTimeoutMs) { nextLatestAbsoluteTimeoutMs = earliestExpirationTimeMs; } // Subtract the current time from the absolute timeout to get the number // of milliseconds until the timeout. In other words, convert an absolute // timestamp to a relative time. This is the value that is passed // to `setTimeout`. var currentTimeMs = expirationTimeToMs(requestCurrentTime()); var msUntilTimeout = nextLatestAbsoluteTimeoutMs - currentTimeMs; msUntilTimeout = msUntilTimeout < 0 ? 0 : msUntilTimeout; // TODO: Account for the Just Noticeable Difference var _rootExpirationTime2 = root.expirationTime; onSuspend(root, rootWorkInProgress, _suspendedExpirationTime2, _rootExpirationTime2, msUntilTimeout); return; } // Ready to commit. onComplete(root, rootWorkInProgress, expirationTime); } function captureCommitPhaseError(sourceFiber, value) { var expirationTime = Sync; var fiber = sourceFiber.return; while (fiber !== null) { switch (fiber.tag) { case ClassComponent: var ctor = fiber.type; var instance = fiber.stateNode; if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) { var errorInfo = createCapturedValue(value, sourceFiber); var update = createClassErrorUpdate(fiber, errorInfo, expirationTime); enqueueUpdate(fiber, update); scheduleWork(fiber, expirationTime); return; } break; case HostRoot: { var _errorInfo = createCapturedValue(value, sourceFiber); var _update = createRootErrorUpdate(fiber, _errorInfo, expirationTime); enqueueUpdate(fiber, _update); scheduleWork(fiber, expirationTime); return; } } fiber = fiber.return; } if (sourceFiber.tag === HostRoot) { // Error was thrown at the root. There is no parent, so the root // itself should capture it. var rootFiber = sourceFiber; var _errorInfo2 = createCapturedValue(value, rootFiber); var _update2 = createRootErrorUpdate(rootFiber, _errorInfo2, expirationTime); enqueueUpdate(rootFiber, _update2); scheduleWork(rootFiber, expirationTime); } } function computeThreadID(expirationTime, interactionThreadID) { // Interaction threads are unique per root and expiration time. return expirationTime * 1000 + interactionThreadID; } // Creates a unique async expiration time. function computeUniqueAsyncExpiration() { var currentTime = requestCurrentTime(); var result = computeAsyncExpiration(currentTime); if (result >= lastUniqueAsyncExpiration) { // Since we assume the current time monotonically increases, we only hit // this branch when computeUniqueAsyncExpiration is fired multiple times // within a 200ms window (or whatever the async bucket size is). result = lastUniqueAsyncExpiration - 1; } lastUniqueAsyncExpiration = result; return lastUniqueAsyncExpiration; } function computeExpirationForFiber(currentTime, fiber) { var priorityLevel = scheduler.unstable_getCurrentPriorityLevel(); var expirationTime = void 0; if ((fiber.mode & ConcurrentMode) === NoContext) { // Outside of concurrent mode, updates are always synchronous. expirationTime = Sync; } else if (isWorking && !isCommitting$1) { // During render phase, updates expire during as the current render. expirationTime = nextRenderExpirationTime; } else { switch (priorityLevel) { case scheduler.unstable_ImmediatePriority: expirationTime = Sync; break; case scheduler.unstable_UserBlockingPriority: expirationTime = computeInteractiveExpiration(currentTime); break; case scheduler.unstable_NormalPriority: // This is a normal, concurrent update expirationTime = computeAsyncExpiration(currentTime); break; case scheduler.unstable_LowPriority: case scheduler.unstable_IdlePriority: expirationTime = Never; break; default: invariant(false, 'Unknown priority level. This error is likely caused by a bug in React. Please file an issue.'); } // If we're in the middle of rendering a tree, do not update at the same // expiration time that is already rendering. if (nextRoot !== null && expirationTime === nextRenderExpirationTime) { expirationTime -= 1; } } // Keep track of the lowest pending interactive expiration time. This // allows us to synchronously flush all interactive updates // when needed. // TODO: Move this to renderer? if (priorityLevel === scheduler.unstable_UserBlockingPriority && (lowestPriorityPendingInteractiveExpirationTime === NoWork || expirationTime < lowestPriorityPendingInteractiveExpirationTime)) { lowestPriorityPendingInteractiveExpirationTime = expirationTime; } return expirationTime; } function renderDidSuspend(root, absoluteTimeoutMs, suspendedTime) { // Schedule the timeout. if (absoluteTimeoutMs >= 0 && nextLatestAbsoluteTimeoutMs < absoluteTimeoutMs) { nextLatestAbsoluteTimeoutMs = absoluteTimeoutMs; } } function renderDidError() { nextRenderDidError = true; } function pingSuspendedRoot(root, thenable, pingTime) { // A promise that previously suspended React from committing has resolved. // If React is still suspended, try again at the previous level (pingTime). var pingCache = root.pingCache; if (pingCache !== null) { // The thenable resolved, so we no longer need to memoize, because it will // never be thrown again. pingCache.delete(thenable); } if (nextRoot !== null && nextRenderExpirationTime === pingTime) { // Received a ping at the same priority level at which we're currently // rendering. Restart from the root. nextRoot = null; } else { // Confirm that the root is still suspended at this level. Otherwise exit. if (isPriorityLevelSuspended(root, pingTime)) { // Ping at the original level markPingedPriorityLevel(root, pingTime); var rootExpirationTime = root.expirationTime; if (rootExpirationTime !== NoWork) { requestWork(root, rootExpirationTime); } } } } function retryTimedOutBoundary(boundaryFiber, thenable) { // The boundary fiber (a Suspense component) previously timed out and was // rendered in its fallback state. One of the promises that suspended it has // resolved, which means at least part of the tree was likely unblocked. Try var retryCache = void 0; if (enableSuspenseServerRenderer) { switch (boundaryFiber.tag) { case SuspenseComponent: retryCache = boundaryFiber.stateNode; break; case DehydratedSuspenseComponent: retryCache = boundaryFiber.memoizedState; break; default: invariant(false, 'Pinged unknown suspense boundary type. This is probably a bug in React.'); } } else { retryCache = boundaryFiber.stateNode; } if (retryCache !== null) { // The thenable resolved, so we no longer need to memoize, because it will // never be thrown again. retryCache.delete(thenable); } var currentTime = requestCurrentTime(); var retryTime = computeExpirationForFiber(currentTime, boundaryFiber); var root = scheduleWorkToRoot(boundaryFiber, retryTime); if (root !== null) { markPendingPriorityLevel(root, retryTime); var rootExpirationTime = root.expirationTime; if (rootExpirationTime !== NoWork) { requestWork(root, rootExpirationTime); } } } function scheduleWorkToRoot(fiber, expirationTime) { recordScheduleUpdate(); { if (fiber.tag === ClassComponent) { var instance = fiber.stateNode; warnAboutInvalidUpdates(instance); } } // Update the source fiber's expiration time if (fiber.expirationTime < expirationTime) { fiber.expirationTime = expirationTime; } var alternate = fiber.alternate; if (alternate !== null && alternate.expirationTime < expirationTime) { alternate.expirationTime = expirationTime; } // Walk the parent path to the root and update the child expiration time. var node = fiber.return; var root = null; if (node === null && fiber.tag === HostRoot) { root = fiber.stateNode; } else { while (node !== null) { alternate = node.alternate; if (node.childExpirationTime < expirationTime) { node.childExpirationTime = expirationTime; if (alternate !== null && alternate.childExpirationTime < expirationTime) { alternate.childExpirationTime = expirationTime; } } else if (alternate !== null && alternate.childExpirationTime < expirationTime) { alternate.childExpirationTime = expirationTime; } if (node.return === null && node.tag === HostRoot) { root = node.stateNode; break; } node = node.return; } } if (enableSchedulerTracing) { if (root !== null) { var interactions = tracing.__interactionsRef.current; if (interactions.size > 0) { var pendingInteractionMap = root.pendingInteractionMap; var pendingInteractions = pendingInteractionMap.get(expirationTime); if (pendingInteractions != null) { interactions.forEach(function (interaction) { if (!pendingInteractions.has(interaction)) { // Update the pending async work count for previously unscheduled interaction. interaction.__count++; } pendingInteractions.add(interaction); }); } else { pendingInteractionMap.set(expirationTime, new Set(interactions)); // Update the pending async work count for the current interactions. interactions.forEach(function (interaction) { interaction.__count++; }); } var subscriber = tracing.__subscriberRef.current; if (subscriber !== null) { var threadID = computeThreadID(expirationTime, root.interactionThreadID); subscriber.onWorkScheduled(interactions, threadID); } } } } return root; } function warnIfNotCurrentlyBatchingInDev(fiber) { { if (isRendering === false && isBatchingUpdates === false) { warningWithoutStack$1(false, 'An update to %s inside a test was not wrapped in act(...).\n\n' + 'When testing, code that causes React state updates should be wrapped into act(...):\n\n' + 'act(() => {\n' + ' /* fire events that update state */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see in the browser." + ' Learn more at https://fb.me/react-wrap-tests-with-act' + '%s', getComponentName(fiber.type), getStackByFiberInDevAndProd(fiber)); } } } function scheduleWork(fiber, expirationTime) { var root = scheduleWorkToRoot(fiber, expirationTime); if (root === null) { { switch (fiber.tag) { case ClassComponent: warnAboutUpdateOnUnmounted(fiber, true); break; case FunctionComponent: case ForwardRef: case MemoComponent: case SimpleMemoComponent: warnAboutUpdateOnUnmounted(fiber, false); break; } } return; } if (!isWorking && nextRenderExpirationTime !== NoWork && expirationTime > nextRenderExpirationTime) { // This is an interruption. (Used for performance tracking.) interruptedBy = fiber; resetStack(); } markPendingPriorityLevel(root, expirationTime); if ( // If we're in the render phase, we don't need to schedule this root // for an update, because we'll do it before we exit... !isWorking || isCommitting$1 || // ...unless this is a different root than the one we're rendering. nextRoot !== root) { var rootExpirationTime = root.expirationTime; requestWork(root, rootExpirationTime); } if (nestedUpdateCount > NESTED_UPDATE_LIMIT) { // Reset this back to zero so subsequent updates don't throw. nestedUpdateCount = 0; invariant(false, 'Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.'); } } function syncUpdates(fn, a, b, c, d) { return scheduler.unstable_runWithPriority(scheduler.unstable_ImmediatePriority, function () { return fn(a, b, c, d); }); } // TODO: Everything below this is written as if it has been lifted to the // renderers. I'll do this in a follow-up. // Linked-list of roots var firstScheduledRoot = null; var lastScheduledRoot = null; var callbackExpirationTime = NoWork; var callbackID = void 0; var isRendering = false; var nextFlushedRoot = null; var nextFlushedExpirationTime = NoWork; var lowestPriorityPendingInteractiveExpirationTime = NoWork; var hasUnhandledError = false; var unhandledError = null; var isBatchingUpdates = false; var isUnbatchingUpdates = false; var completedBatches = null; var originalStartTimeMs = scheduler.unstable_now(); var currentRendererTime = msToExpirationTime(originalStartTimeMs); var currentSchedulerTime = currentRendererTime; // Use these to prevent an infinite loop of nested updates var NESTED_UPDATE_LIMIT = 50; var nestedUpdateCount = 0; var lastCommittedRootDuringThisBatch = null; function recomputeCurrentRendererTime() { var currentTimeMs = scheduler.unstable_now() - originalStartTimeMs; currentRendererTime = msToExpirationTime(currentTimeMs); } function scheduleCallbackWithExpirationTime(root, expirationTime) { if (callbackExpirationTime !== NoWork) { // A callback is already scheduled. Check its expiration time (timeout). if (expirationTime < callbackExpirationTime) { // Existing callback has sufficient timeout. Exit. return; } else { if (callbackID !== null) { // Existing callback has insufficient timeout. Cancel and schedule a // new one. scheduler.unstable_cancelCallback(callbackID); } } // The request callback timer is already running. Don't start a new one. } else { startRequestCallbackTimer(); } callbackExpirationTime = expirationTime; var currentMs = scheduler.unstable_now() - originalStartTimeMs; var expirationTimeMs = expirationTimeToMs(expirationTime); var timeout = expirationTimeMs - currentMs; callbackID = scheduler.unstable_scheduleCallback(performAsyncWork, { timeout: timeout }); } // For every call to renderRoot, one of onFatal, onComplete, onSuspend, and // onYield is called upon exiting. We use these in lieu of returning a tuple. // I've also chosen not to inline them into renderRoot because these will // eventually be lifted into the renderer. function onFatal(root) { root.finishedWork = null; } function onComplete(root, finishedWork, expirationTime) { root.pendingCommitExpirationTime = expirationTime; root.finishedWork = finishedWork; } function onSuspend(root, finishedWork, suspendedExpirationTime, rootExpirationTime, msUntilTimeout) { root.expirationTime = rootExpirationTime; if (msUntilTimeout === 0 && !shouldYieldToRenderer()) { // Don't wait an additional tick. Commit the tree immediately. root.pendingCommitExpirationTime = suspendedExpirationTime; root.finishedWork = finishedWork; } else if (msUntilTimeout > 0) { // Wait `msUntilTimeout` milliseconds before committing. root.timeoutHandle = scheduleTimeout(onTimeout.bind(null, root, finishedWork, suspendedExpirationTime), msUntilTimeout); } } function onYield(root) { root.finishedWork = null; } function onTimeout(root, finishedWork, suspendedExpirationTime) { // The root timed out. Commit it. root.pendingCommitExpirationTime = suspendedExpirationTime; root.finishedWork = finishedWork; // Read the current time before entering the commit phase. We can be // certain this won't cause tearing related to batching of event updates // because we're at the top of a timer event. recomputeCurrentRendererTime(); currentSchedulerTime = currentRendererTime; flushRoot(root, suspendedExpirationTime); } function onCommit(root, expirationTime) { root.expirationTime = expirationTime; root.finishedWork = null; } function requestCurrentTime() { // requestCurrentTime is called by the scheduler to compute an expiration // time. // // Expiration times are computed by adding to the current time (the start // time). However, if two updates are scheduled within the same event, we // should treat their start times as simultaneous, even if the actual clock // time has advanced between the first and second call. // In other words, because expiration times determine how updates are batched, // we want all updates of like priority that occur within the same event to // receive the same expiration time. Otherwise we get tearing. // // We keep track of two separate times: the current "renderer" time and the // current "scheduler" time. The renderer time can be updated whenever; it // only exists to minimize the calls performance.now. // // But the scheduler time can only be updated if there's no pending work, or // if we know for certain that we're not in the middle of an event. if (isRendering) { // We're already rendering. Return the most recently read time. return currentSchedulerTime; } // Check if there's pending work. findHighestPriorityRoot(); if (nextFlushedExpirationTime === NoWork || nextFlushedExpirationTime === Never) { // If there's no pending work, or if the pending work is offscreen, we can // read the current time without risk of tearing. recomputeCurrentRendererTime(); currentSchedulerTime = currentRendererTime; return currentSchedulerTime; } // There's already pending work. We might be in the middle of a browser // event. If we were to read the current time, it could cause multiple updates // within the same event to receive different expiration times, leading to // tearing. Return the last read time. During the next idle callback, the // time will be updated. return currentSchedulerTime; } // requestWork is called by the scheduler whenever a root receives an update. // It's up to the renderer to call renderRoot at some point in the future. function requestWork(root, expirationTime) { addRootToSchedule(root, expirationTime); if (isRendering) { // Prevent reentrancy. Remaining work will be scheduled at the end of // the currently rendering batch. return; } if (isBatchingUpdates) { // Flush work at the end of the batch. if (isUnbatchingUpdates) { // ...unless we're inside unbatchedUpdates, in which case we should // flush it now. nextFlushedRoot = root; nextFlushedExpirationTime = Sync; performWorkOnRoot(root, Sync, false); } return; } // TODO: Get rid of Sync and use current time? if (expirationTime === Sync) { performSyncWork(); } else { scheduleCallbackWithExpirationTime(root, expirationTime); } } function addRootToSchedule(root, expirationTime) { // Add the root to the schedule. // Check if this root is already part of the schedule. if (root.nextScheduledRoot === null) { // This root is not already scheduled. Add it. root.expirationTime = expirationTime; if (lastScheduledRoot === null) { firstScheduledRoot = lastScheduledRoot = root; root.nextScheduledRoot = root; } else { lastScheduledRoot.nextScheduledRoot = root; lastScheduledRoot = root; lastScheduledRoot.nextScheduledRoot = firstScheduledRoot; } } else { // This root is already scheduled, but its priority may have increased. var remainingExpirationTime = root.expirationTime; if (expirationTime > remainingExpirationTime) { // Update the priority. root.expirationTime = expirationTime; } } } function findHighestPriorityRoot() { var highestPriorityWork = NoWork; var highestPriorityRoot = null; if (lastScheduledRoot !== null) { var previousScheduledRoot = lastScheduledRoot; var root = firstScheduledRoot; while (root !== null) { var remainingExpirationTime = root.expirationTime; if (remainingExpirationTime === NoWork) { // This root no longer has work. Remove it from the scheduler. // TODO: This check is redudant, but Flow is confused by the branch // below where we set lastScheduledRoot to null, even though we break // from the loop right after. !(previousScheduledRoot !== null && lastScheduledRoot !== null) ? invariant(false, 'Should have a previous and last root. This error is likely caused by a bug in React. Please file an issue.') : void 0; if (root === root.nextScheduledRoot) { // This is the only root in the list. root.nextScheduledRoot = null; firstScheduledRoot = lastScheduledRoot = null; break; } else if (root === firstScheduledRoot) { // This is the first root in the list. var next = root.nextScheduledRoot; firstScheduledRoot = next; lastScheduledRoot.nextScheduledRoot = next; root.nextScheduledRoot = null; } else if (root === lastScheduledRoot) { // This is the last root in the list. lastScheduledRoot = previousScheduledRoot; lastScheduledRoot.nextScheduledRoot = firstScheduledRoot; root.nextScheduledRoot = null; break; } else { previousScheduledRoot.nextScheduledRoot = root.nextScheduledRoot; root.nextScheduledRoot = null; } root = previousScheduledRoot.nextScheduledRoot; } else { if (remainingExpirationTime > highestPriorityWork) { // Update the priority, if it's higher highestPriorityWork = remainingExpirationTime; highestPriorityRoot = root; } if (root === lastScheduledRoot) { break; } if (highestPriorityWork === Sync) { // Sync is highest priority by definition so // we can stop searching. break; } previousScheduledRoot = root; root = root.nextScheduledRoot; } } } nextFlushedRoot = highestPriorityRoot; nextFlushedExpirationTime = highestPriorityWork; } // TODO: This wrapper exists because many of the older tests (the ones that use // flushDeferredPri) rely on the number of times `shouldYield` is called. We // should get rid of it. var didYield = false; function shouldYieldToRenderer() { if (didYield) { return true; } if (scheduler.unstable_shouldYield()) { didYield = true; return true; } return false; } function performAsyncWork() { try { if (!shouldYieldToRenderer()) { // The callback timed out. That means at least one update has expired. // Iterate through the root schedule. If they contain expired work, set // the next render expiration time to the current time. This has the effect // of flushing all expired work in a single batch, instead of flushing each // level one at a time. if (firstScheduledRoot !== null) { recomputeCurrentRendererTime(); var root = firstScheduledRoot; do { didExpireAtExpirationTime(root, currentRendererTime); // The root schedule is circular, so this is never null. root = root.nextScheduledRoot; } while (root !== firstScheduledRoot); } } performWork(NoWork, true); } finally { didYield = false; } } function performSyncWork() { performWork(Sync, false); } function performWork(minExpirationTime, isYieldy) { // Keep working on roots until there's no more work, or until there's a higher // priority event. findHighestPriorityRoot(); if (isYieldy) { recomputeCurrentRendererTime(); currentSchedulerTime = currentRendererTime; if (enableUserTimingAPI) { var didExpire = nextFlushedExpirationTime > currentRendererTime; var timeout = expirationTimeToMs(nextFlushedExpirationTime); stopRequestCallbackTimer(didExpire, timeout); } while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork && minExpirationTime <= nextFlushedExpirationTime && !(didYield && currentRendererTime > nextFlushedExpirationTime)) { performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, currentRendererTime > nextFlushedExpirationTime); findHighestPriorityRoot(); recomputeCurrentRendererTime(); currentSchedulerTime = currentRendererTime; } } else { while (nextFlushedRoot !== null && nextFlushedExpirationTime !== NoWork && minExpirationTime <= nextFlushedExpirationTime) { performWorkOnRoot(nextFlushedRoot, nextFlushedExpirationTime, false); findHighestPriorityRoot(); } } // We're done flushing work. Either we ran out of time in this callback, // or there's no more work left with sufficient priority. // If we're inside a callback, set this to false since we just completed it. if (isYieldy) { callbackExpirationTime = NoWork; callbackID = null; } // If there's work left over, schedule a new callback. if (nextFlushedExpirationTime !== NoWork) { scheduleCallbackWithExpirationTime(nextFlushedRoot, nextFlushedExpirationTime); } // Clean-up. finishRendering(); } function flushRoot(root, expirationTime) { !!isRendering ? invariant(false, 'work.commit(): Cannot commit while already rendering. This likely means you attempted to commit from inside a lifecycle method.') : void 0; // Perform work on root as if the given expiration time is the current time. // This has the effect of synchronously flushing all work up to and // including the given time. nextFlushedRoot = root; nextFlushedExpirationTime = expirationTime; performWorkOnRoot(root, expirationTime, false); // Flush any sync work that was scheduled by lifecycles performSyncWork(); } function finishRendering() { nestedUpdateCount = 0; lastCommittedRootDuringThisBatch = null; if (completedBatches !== null) { var batches = completedBatches; completedBatches = null; for (var i = 0; i < batches.length; i++) { var batch = batches[i]; try { batch._onComplete(); } catch (error) { if (!hasUnhandledError) { hasUnhandledError = true; unhandledError = error; } } } } if (hasUnhandledError) { var error = unhandledError; unhandledError = null; hasUnhandledError = false; throw error; } } function performWorkOnRoot(root, expirationTime, isYieldy) { !!isRendering ? invariant(false, 'performWorkOnRoot was called recursively. This error is likely caused by a bug in React. Please file an issue.') : void 0; isRendering = true; // Check if this is async work or sync/expired work. if (!isYieldy) { // Flush work without yielding. // TODO: Non-yieldy work does not necessarily imply expired work. A renderer // may want to perform some work without yielding, but also without // requiring the root to complete (by triggering placeholders). var finishedWork = root.finishedWork; if (finishedWork !== null) { // This root is already complete. We can commit it. completeRoot(root, finishedWork, expirationTime); } else { root.finishedWork = null; // If this root previously suspended, clear its existing timeout, since // we're about to try rendering again. var timeoutHandle = root.timeoutHandle; if (timeoutHandle !== noTimeout) { root.timeoutHandle = noTimeout; // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above cancelTimeout(timeoutHandle); } renderRoot(root, isYieldy); finishedWork = root.finishedWork; if (finishedWork !== null) { // We've completed the root. Commit it. completeRoot(root, finishedWork, expirationTime); } } } else { // Flush async work. var _finishedWork = root.finishedWork; if (_finishedWork !== null) { // This root is already complete. We can commit it. completeRoot(root, _finishedWork, expirationTime); } else { root.finishedWork = null; // If this root previously suspended, clear its existing timeout, since // we're about to try rendering again. var _timeoutHandle = root.timeoutHandle; if (_timeoutHandle !== noTimeout) { root.timeoutHandle = noTimeout; // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above cancelTimeout(_timeoutHandle); } renderRoot(root, isYieldy); _finishedWork = root.finishedWork; if (_finishedWork !== null) { // We've completed the root. Check the if we should yield one more time // before committing. if (!shouldYieldToRenderer()) { // Still time left. Commit the root. completeRoot(root, _finishedWork, expirationTime); } else { // There's no time left. Mark this root as complete. We'll come // back and commit it later. root.finishedWork = _finishedWork; } } } } isRendering = false; } function completeRoot(root, finishedWork, expirationTime) { // Check if there's a batch that matches this expiration time. var firstBatch = root.firstBatch; if (firstBatch !== null && firstBatch._expirationTime >= expirationTime) { if (completedBatches === null) { completedBatches = [firstBatch]; } else { completedBatches.push(firstBatch); } if (firstBatch._defer) { // This root is blocked from committing by a batch. Unschedule it until // we receive another update. root.finishedWork = finishedWork; root.expirationTime = NoWork; return; } } // Commit the root. root.finishedWork = null; // Check if this is a nested update (a sync update scheduled during the // commit phase). if (root === lastCommittedRootDuringThisBatch) { // If the next root is the same as the previous root, this is a nested // update. To prevent an infinite loop, increment the nested update count. nestedUpdateCount++; } else { // Reset whenever we switch roots. lastCommittedRootDuringThisBatch = root; nestedUpdateCount = 0; } scheduler.unstable_runWithPriority(scheduler.unstable_ImmediatePriority, function () { commitRoot(root, finishedWork); }); } function onUncaughtError(error) { !(nextFlushedRoot !== null) ? invariant(false, 'Should be working on a root. This error is likely caused by a bug in React. Please file an issue.') : void 0; // Unschedule this root so we don't work on it again until there's // another update. nextFlushedRoot.expirationTime = NoWork; if (!hasUnhandledError) { hasUnhandledError = true; unhandledError = error; } } // TODO: Batching should be implemented at the renderer level, not inside // the reconciler. function batchedUpdates$1(fn, a) { var previousIsBatchingUpdates = isBatchingUpdates; isBatchingUpdates = true; try { return fn(a); } finally { isBatchingUpdates = previousIsBatchingUpdates; if (!isBatchingUpdates && !isRendering) { performSyncWork(); } } } // TODO: Batching should be implemented at the renderer level, not inside // the reconciler. function unbatchedUpdates(fn, a) { if (isBatchingUpdates && !isUnbatchingUpdates) { isUnbatchingUpdates = true; try { return fn(a); } finally { isUnbatchingUpdates = false; } } return fn(a); } // TODO: Batching should be implemented at the renderer level, not within // the reconciler. function flushSync(fn, a) { !!isRendering ? invariant(false, 'flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering.') : void 0; var previousIsBatchingUpdates = isBatchingUpdates; isBatchingUpdates = true; try { return syncUpdates(fn, a); } finally { isBatchingUpdates = previousIsBatchingUpdates; performSyncWork(); } } function interactiveUpdates$1(fn, a, b) { // If there are any pending interactive updates, synchronously flush them. // This needs to happen before we read any handlers, because the effect of // the previous event may influence which handlers are called during // this event. if (!isBatchingUpdates && !isRendering && lowestPriorityPendingInteractiveExpirationTime !== NoWork) { // Synchronously flush pending interactive updates. performWork(lowestPriorityPendingInteractiveExpirationTime, false); lowestPriorityPendingInteractiveExpirationTime = NoWork; } var previousIsBatchingUpdates = isBatchingUpdates; isBatchingUpdates = true; try { return scheduler.unstable_runWithPriority(scheduler.unstable_UserBlockingPriority, function () { return fn(a, b); }); } finally { isBatchingUpdates = previousIsBatchingUpdates; if (!isBatchingUpdates && !isRendering) { performSyncWork(); } } } function flushInteractiveUpdates$1() { if (!isRendering && lowestPriorityPendingInteractiveExpirationTime !== NoWork) { // Synchronously flush pending interactive updates. performWork(lowestPriorityPendingInteractiveExpirationTime, false); lowestPriorityPendingInteractiveExpirationTime = NoWork; } } function flushControlled(fn) { var previousIsBatchingUpdates = isBatchingUpdates; isBatchingUpdates = true; try { syncUpdates(fn); } finally { isBatchingUpdates = previousIsBatchingUpdates; if (!isBatchingUpdates && !isRendering) { performSyncWork(); } } } // 0 is PROD, 1 is DEV. // Might add PROFILE later. var didWarnAboutNestedUpdates = void 0; var didWarnAboutFindNodeInStrictMode = void 0; { didWarnAboutNestedUpdates = false; didWarnAboutFindNodeInStrictMode = {}; } function getContextForSubtree(parentComponent) { if (!parentComponent) { return emptyContextObject; } var fiber = get(parentComponent); var parentContext = findCurrentUnmaskedContext(fiber); if (fiber.tag === ClassComponent) { var Component = fiber.type; if (isContextProvider(Component)) { return processChildContext(fiber, Component, parentContext); } } return parentContext; } function scheduleRootUpdate(current$$1, element, expirationTime, callback) { { if (phase === 'render' && current !== null && !didWarnAboutNestedUpdates) { didWarnAboutNestedUpdates = true; warningWithoutStack$1(false, 'Render methods should be a pure function of props and state; ' + 'triggering nested component updates from render is not allowed. ' + 'If necessary, trigger nested updates in componentDidUpdate.\n\n' + 'Check the render method of %s.', getComponentName(current.type) || 'Unknown'); } } var update = createUpdate(expirationTime); // Caution: React DevTools currently depends on this property // being called "element". update.payload = { element: element }; callback = callback === undefined ? null : callback; if (callback !== null) { !(typeof callback === 'function') ? warningWithoutStack$1(false, 'render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback) : void 0; update.callback = callback; } flushPassiveEffects(); enqueueUpdate(current$$1, update); scheduleWork(current$$1, expirationTime); return expirationTime; } function updateContainerAtExpirationTime(element, container, parentComponent, expirationTime, callback) { // TODO: If this is a nested container, this won't be the root. var current$$1 = container.current; { if (ReactFiberInstrumentation_1.debugTool) { if (current$$1.alternate === null) { ReactFiberInstrumentation_1.debugTool.onMountContainer(container); } else if (element === null) { ReactFiberInstrumentation_1.debugTool.onUnmountContainer(container); } else { ReactFiberInstrumentation_1.debugTool.onUpdateContainer(container); } } } var context = getContextForSubtree(parentComponent); if (container.context === null) { container.context = context; } else { container.pendingContext = context; } return scheduleRootUpdate(current$$1, element, expirationTime, callback); } function findHostInstance(component) { var fiber = get(component); if (fiber === undefined) { if (typeof component.render === 'function') { invariant(false, 'Unable to find node on an unmounted component.'); } else { invariant(false, 'Argument appears to not be a ReactComponent. Keys: %s', Object.keys(component)); } } var hostFiber = findCurrentHostFiber(fiber); if (hostFiber === null) { return null; } return hostFiber.stateNode; } function findHostInstanceWithWarning(component, methodName) { { var fiber = get(component); if (fiber === undefined) { if (typeof component.render === 'function') { invariant(false, 'Unable to find node on an unmounted component.'); } else { invariant(false, 'Argument appears to not be a ReactComponent. Keys: %s', Object.keys(component)); } } var hostFiber = findCurrentHostFiber(fiber); if (hostFiber === null) { return null; } if (hostFiber.mode & StrictMode) { var componentName = getComponentName(fiber.type) || 'Component'; if (!didWarnAboutFindNodeInStrictMode[componentName]) { didWarnAboutFindNodeInStrictMode[componentName] = true; if (fiber.mode & StrictMode) { warningWithoutStack$1(false, '%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which is inside StrictMode. ' + 'Instead, add a ref directly to the element you want to reference.' + '\n%s' + '\n\nLearn more about using refs safely here:' + '\nhttps://fb.me/react-strict-mode-find-node', methodName, methodName, componentName, getStackByFiberInDevAndProd(hostFiber)); } else { warningWithoutStack$1(false, '%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which renders StrictMode children. ' + 'Instead, add a ref directly to the element you want to reference.' + '\n%s' + '\n\nLearn more about using refs safely here:' + '\nhttps://fb.me/react-strict-mode-find-node', methodName, methodName, componentName, getStackByFiberInDevAndProd(hostFiber)); } } } return hostFiber.stateNode; } return findHostInstance(component); } function createContainer(containerInfo, isConcurrent, hydrate) { return createFiberRoot(containerInfo, isConcurrent, hydrate); } function updateContainer(element, container, parentComponent, callback) { var current$$1 = container.current; var currentTime = requestCurrentTime(); var expirationTime = computeExpirationForFiber(currentTime, current$$1); return updateContainerAtExpirationTime(element, container, parentComponent, expirationTime, callback); } function getPublicRootInstance(container) { var containerFiber = container.current; if (!containerFiber.child) { return null; } switch (containerFiber.child.tag) { case HostComponent: return getPublicInstance(containerFiber.child.stateNode); default: return containerFiber.child.stateNode; } } function findHostInstanceWithNoPortals(fiber) { var hostFiber = findCurrentHostFiberWithNoPortals(fiber); if (hostFiber === null) { return null; } return hostFiber.stateNode; } var overrideProps = null; { var copyWithSetImpl = function (obj, path, idx, value) { if (idx >= path.length) { return value; } var key = path[idx]; var updated = Array.isArray(obj) ? obj.slice() : _assign({}, obj); // $FlowFixMe number or string is fine here updated[key] = copyWithSetImpl(obj[key], path, idx + 1, value); return updated; }; var copyWithSet = function (obj, path, value) { return copyWithSetImpl(obj, path, 0, value); }; // Support DevTools props for function components, forwardRef, memo, host components, etc. overrideProps = function (fiber, path, value) { flushPassiveEffects(); fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value); if (fiber.alternate) { fiber.alternate.pendingProps = fiber.pendingProps; } scheduleWork(fiber, Sync); }; } function injectIntoDevTools(devToolsConfig) { var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance; var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; return injectInternals(_assign({}, devToolsConfig, { overrideProps: overrideProps, currentDispatcherRef: ReactCurrentDispatcher, findHostInstanceByFiber: function (fiber) { var hostFiber = findCurrentHostFiber(fiber); if (hostFiber === null) { return null; } return hostFiber.stateNode; }, findFiberByHostInstance: function (instance) { if (!findFiberByHostInstance) { // Might not be implemented by the renderer. return null; } return findFiberByHostInstance(instance); } })); } // This file intentionally does *not* have the Flow annotation. // Don't add it. See `./inline-typed.js` for an explanation. function createPortal$1(children, containerInfo, // TODO: figure out the API for cross-renderer implementation. implementation) { var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; return { // This tag allow us to uniquely identify this as a React Portal $$typeof: REACT_PORTAL_TYPE, key: key == null ? null : '' + key, children: children, containerInfo: containerInfo, implementation: implementation }; } // TODO: this is special because it gets imported during build. var ReactVersion = '16.8.6'; // TODO: This type is shared between the reconciler and ReactDOM, but will // eventually be lifted out to the renderer. var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; var topLevelUpdateWarnings = void 0; var warnOnInvalidCallback = void 0; var didWarnAboutUnstableCreatePortal = false; { if (typeof Map !== 'function' || // $FlowIssue Flow incorrectly thinks Map has no prototype Map.prototype == null || typeof Map.prototype.forEach !== 'function' || typeof Set !== 'function' || // $FlowIssue Flow incorrectly thinks Set has no prototype Set.prototype == null || typeof Set.prototype.clear !== 'function' || typeof Set.prototype.forEach !== 'function') { warningWithoutStack$1(false, 'React depends on Map and Set built-in types. Make sure that you load a ' + 'polyfill in older browsers. https://fb.me/react-polyfills'); } topLevelUpdateWarnings = function (container) { if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) { var hostInstance = findHostInstanceWithNoPortals(container._reactRootContainer._internalRoot.current); if (hostInstance) { !(hostInstance.parentNode === container) ? warningWithoutStack$1(false, 'render(...): It looks like the React-rendered content of this ' + 'container was removed without using React. This is not ' + 'supported and will cause errors. Instead, call ' + 'ReactDOM.unmountComponentAtNode to empty a container.') : void 0; } } var isRootRenderedBySomeReact = !!container._reactRootContainer; var rootEl = getReactRootElementInContainer(container); var hasNonRootReactChild = !!(rootEl && getInstanceFromNode$1(rootEl)); !(!hasNonRootReactChild || isRootRenderedBySomeReact) ? warningWithoutStack$1(false, 'render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.') : void 0; !(container.nodeType !== ELEMENT_NODE || !container.tagName || container.tagName.toUpperCase() !== 'BODY') ? warningWithoutStack$1(false, 'render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.') : void 0; }; warnOnInvalidCallback = function (callback, callerName) { !(callback === null || typeof callback === 'function') ? warningWithoutStack$1(false, '%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback) : void 0; }; } setRestoreImplementation(restoreControlledState$1); function ReactBatch(root) { var expirationTime = computeUniqueAsyncExpiration(); this._expirationTime = expirationTime; this._root = root; this._next = null; this._callbacks = null; this._didComplete = false; this._hasChildren = false; this._children = null; this._defer = true; } ReactBatch.prototype.render = function (children) { !this._defer ? invariant(false, 'batch.render: Cannot render a batch that already committed.') : void 0; this._hasChildren = true; this._children = children; var internalRoot = this._root._internalRoot; var expirationTime = this._expirationTime; var work = new ReactWork(); updateContainerAtExpirationTime(children, internalRoot, null, expirationTime, work._onCommit); return work; }; ReactBatch.prototype.then = function (onComplete) { if (this._didComplete) { onComplete(); return; } var callbacks = this._callbacks; if (callbacks === null) { callbacks = this._callbacks = []; } callbacks.push(onComplete); }; ReactBatch.prototype.commit = function () { var internalRoot = this._root._internalRoot; var firstBatch = internalRoot.firstBatch; !(this._defer && firstBatch !== null) ? invariant(false, 'batch.commit: Cannot commit a batch multiple times.') : void 0; if (!this._hasChildren) { // This batch is empty. Return. this._next = null; this._defer = false; return; } var expirationTime = this._expirationTime; // Ensure this is the first batch in the list. if (firstBatch !== this) { // This batch is not the earliest batch. We need to move it to the front. // Update its expiration time to be the expiration time of the earliest // batch, so that we can flush it without flushing the other batches. if (this._hasChildren) { expirationTime = this._expirationTime = firstBatch._expirationTime; // Rendering this batch again ensures its children will be the final state // when we flush (updates are processed in insertion order: last // update wins). // TODO: This forces a restart. Should we print a warning? this.render(this._children); } // Remove the batch from the list. var previous = null; var batch = firstBatch; while (batch !== this) { previous = batch; batch = batch._next; } !(previous !== null) ? invariant(false, 'batch.commit: Cannot commit a batch multiple times.') : void 0; previous._next = batch._next; // Add it to the front. this._next = firstBatch; firstBatch = internalRoot.firstBatch = this; } // Synchronously flush all the work up to this batch's expiration time. this._defer = false; flushRoot(internalRoot, expirationTime); // Pop the batch from the list. var next = this._next; this._next = null; firstBatch = internalRoot.firstBatch = next; // Append the next earliest batch's children to the update queue. if (firstBatch !== null && firstBatch._hasChildren) { firstBatch.render(firstBatch._children); } }; ReactBatch.prototype._onComplete = function () { if (this._didComplete) { return; } this._didComplete = true; var callbacks = this._callbacks; if (callbacks === null) { return; } // TODO: Error handling. for (var i = 0; i < callbacks.length; i++) { var _callback = callbacks[i]; _callback(); } }; function ReactWork() { this._callbacks = null; this._didCommit = false; // TODO: Avoid need to bind by replacing callbacks in the update queue with // list of Work objects. this._onCommit = this._onCommit.bind(this); } ReactWork.prototype.then = function (onCommit) { if (this._didCommit) { onCommit(); return; } var callbacks = this._callbacks; if (callbacks === null) { callbacks = this._callbacks = []; } callbacks.push(onCommit); }; ReactWork.prototype._onCommit = function () { if (this._didCommit) { return; } this._didCommit = true; var callbacks = this._callbacks; if (callbacks === null) { return; } // TODO: Error handling. for (var i = 0; i < callbacks.length; i++) { var _callback2 = callbacks[i]; !(typeof _callback2 === 'function') ? invariant(false, 'Invalid argument passed as callback. Expected a function. Instead received: %s', _callback2) : void 0; _callback2(); } }; function ReactRoot(container, isConcurrent, hydrate) { var root = createContainer(container, isConcurrent, hydrate); this._internalRoot = root; } ReactRoot.prototype.render = function (children, callback) { var root = this._internalRoot; var work = new ReactWork(); callback = callback === undefined ? null : callback; { warnOnInvalidCallback(callback, 'render'); } if (callback !== null) { work.then(callback); } updateContainer(children, root, null, work._onCommit); return work; }; ReactRoot.prototype.unmount = function (callback) { var root = this._internalRoot; var work = new ReactWork(); callback = callback === undefined ? null : callback; { warnOnInvalidCallback(callback, 'render'); } if (callback !== null) { work.then(callback); } updateContainer(null, root, null, work._onCommit); return work; }; ReactRoot.prototype.legacy_renderSubtreeIntoContainer = function (parentComponent, children, callback) { var root = this._internalRoot; var work = new ReactWork(); callback = callback === undefined ? null : callback; { warnOnInvalidCallback(callback, 'render'); } if (callback !== null) { work.then(callback); } updateContainer(children, root, parentComponent, work._onCommit); return work; }; ReactRoot.prototype.createBatch = function () { var batch = new ReactBatch(this); var expirationTime = batch._expirationTime; var internalRoot = this._internalRoot; var firstBatch = internalRoot.firstBatch; if (firstBatch === null) { internalRoot.firstBatch = batch; batch._next = null; } else { // Insert sorted by expiration time then insertion order var insertAfter = null; var insertBefore = firstBatch; while (insertBefore !== null && insertBefore._expirationTime >= expirationTime) { insertAfter = insertBefore; insertBefore = insertBefore._next; } batch._next = insertBefore; if (insertAfter !== null) { insertAfter._next = batch; } } return batch; }; /** * True if the supplied DOM node is a valid node element. * * @param {?DOMElement} node The candidate DOM node. * @return {boolean} True if the DOM is a valid DOM node. * @internal */ function isValidContainer(node) { return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || node.nodeType === COMMENT_NODE && node.nodeValue === ' react-mount-point-unstable ')); } function getReactRootElementInContainer(container) { if (!container) { return null; } if (container.nodeType === DOCUMENT_NODE) { return container.documentElement; } else { return container.firstChild; } } function shouldHydrateDueToLegacyHeuristic(container) { var rootElement = getReactRootElementInContainer(container); return !!(rootElement && rootElement.nodeType === ELEMENT_NODE && rootElement.hasAttribute(ROOT_ATTRIBUTE_NAME)); } setBatchingImplementation(batchedUpdates$1, interactiveUpdates$1, flushInteractiveUpdates$1); var warnedAboutHydrateAPI = false; function legacyCreateRootFromDOMContainer(container, forceHydrate) { var shouldHydrate = forceHydrate || shouldHydrateDueToLegacyHeuristic(container); // First clear any existing content. if (!shouldHydrate) { var warned = false; var rootSibling = void 0; while (rootSibling = container.lastChild) { { if (!warned && rootSibling.nodeType === ELEMENT_NODE && rootSibling.hasAttribute(ROOT_ATTRIBUTE_NAME)) { warned = true; warningWithoutStack$1(false, 'render(): Target node has markup rendered by React, but there ' + 'are unrelated nodes as well. This is most commonly caused by ' + 'white-space inserted around server-rendered markup.'); } } container.removeChild(rootSibling); } } { if (shouldHydrate && !forceHydrate && !warnedAboutHydrateAPI) { warnedAboutHydrateAPI = true; lowPriorityWarning$1(false, 'render(): Calling ReactDOM.render() to hydrate server-rendered markup ' + 'will stop working in React v17. Replace the ReactDOM.render() call ' + 'with ReactDOM.hydrate() if you want React to attach to the server HTML.'); } } // Legacy roots are not async by default. var isConcurrent = false; return new ReactRoot(container, isConcurrent, shouldHydrate); } function legacyRenderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback) { { topLevelUpdateWarnings(container); } // TODO: Without `any` type, Flow says "Property cannot be accessed on any // member of intersection type." Whyyyyyy. var root = container._reactRootContainer; if (!root) { // Initial mount root = container._reactRootContainer = legacyCreateRootFromDOMContainer(container, forceHydrate); if (typeof callback === 'function') { var originalCallback = callback; callback = function () { var instance = getPublicRootInstance(root._internalRoot); originalCallback.call(instance); }; } // Initial mount should not be batched. unbatchedUpdates(function () { if (parentComponent != null) { root.legacy_renderSubtreeIntoContainer(parentComponent, children, callback); } else { root.render(children, callback); } }); } else { if (typeof callback === 'function') { var _originalCallback = callback; callback = function () { var instance = getPublicRootInstance(root._internalRoot); _originalCallback.call(instance); }; } // Update if (parentComponent != null) { root.legacy_renderSubtreeIntoContainer(parentComponent, children, callback); } else { root.render(children, callback); } } return getPublicRootInstance(root._internalRoot); } function createPortal$$1(children, container) { var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; !isValidContainer(container) ? invariant(false, 'Target container is not a DOM element.') : void 0; // TODO: pass ReactDOM portal implementation as third argument return createPortal$1(children, container, null, key); } var ReactDOM = { createPortal: createPortal$$1, findDOMNode: function (componentOrElement) { { var owner = ReactCurrentOwner.current; if (owner !== null && owner.stateNode !== null) { var warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender; !warnedAboutRefsInRender ? warningWithoutStack$1(false, '%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentName(owner.type) || 'A component') : void 0; owner.stateNode._warnedAboutRefsInRender = true; } } if (componentOrElement == null) { return null; } if (componentOrElement.nodeType === ELEMENT_NODE) { return componentOrElement; } { return findHostInstanceWithWarning(componentOrElement, 'findDOMNode'); } return findHostInstance(componentOrElement); }, hydrate: function (element, container, callback) { !isValidContainer(container) ? invariant(false, 'Target container is not a DOM element.') : void 0; { !!container._reactHasBeenPassedToCreateRootDEV ? warningWithoutStack$1(false, 'You are calling ReactDOM.hydrate() on a container that was previously ' + 'passed to ReactDOM.%s(). This is not supported. ' + 'Did you mean to call createRoot(container, {hydrate: true}).render(element)?', enableStableConcurrentModeAPIs ? 'createRoot' : 'unstable_createRoot') : void 0; } // TODO: throw or warn if we couldn't hydrate? return legacyRenderSubtreeIntoContainer(null, element, container, true, callback); }, render: function (element, container, callback) { !isValidContainer(container) ? invariant(false, 'Target container is not a DOM element.') : void 0; { !!container._reactHasBeenPassedToCreateRootDEV ? warningWithoutStack$1(false, 'You are calling ReactDOM.render() on a container that was previously ' + 'passed to ReactDOM.%s(). This is not supported. ' + 'Did you mean to call root.render(element)?', enableStableConcurrentModeAPIs ? 'createRoot' : 'unstable_createRoot') : void 0; } return legacyRenderSubtreeIntoContainer(null, element, container, false, callback); }, unstable_renderSubtreeIntoContainer: function (parentComponent, element, containerNode, callback) { !isValidContainer(containerNode) ? invariant(false, 'Target container is not a DOM element.') : void 0; !(parentComponent != null && has(parentComponent)) ? invariant(false, 'parentComponent must be a valid React Component') : void 0; return legacyRenderSubtreeIntoContainer(parentComponent, element, containerNode, false, callback); }, unmountComponentAtNode: function (container) { !isValidContainer(container) ? invariant(false, 'unmountComponentAtNode(...): Target container is not a DOM element.') : void 0; { !!container._reactHasBeenPassedToCreateRootDEV ? warningWithoutStack$1(false, 'You are calling ReactDOM.unmountComponentAtNode() on a container that was previously ' + 'passed to ReactDOM.%s(). This is not supported. Did you mean to call root.unmount()?', enableStableConcurrentModeAPIs ? 'createRoot' : 'unstable_createRoot') : void 0; } if (container._reactRootContainer) { { var rootEl = getReactRootElementInContainer(container); var renderedByDifferentReact = rootEl && !getInstanceFromNode$1(rootEl); !!renderedByDifferentReact ? warningWithoutStack$1(false, "unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by another copy of React.') : void 0; } // Unmount should not be batched. unbatchedUpdates(function () { legacyRenderSubtreeIntoContainer(null, null, container, false, function () { container._reactRootContainer = null; }); }); // If you call unmountComponentAtNode twice in quick succession, you'll // get `true` twice. That's probably fine? return true; } else { { var _rootEl = getReactRootElementInContainer(container); var hasNonRootReactChild = !!(_rootEl && getInstanceFromNode$1(_rootEl)); // Check if the container itself is a React root node. var isContainerReactRoot = container.nodeType === ELEMENT_NODE && isValidContainer(container.parentNode) && !!container.parentNode._reactRootContainer; !!hasNonRootReactChild ? warningWithoutStack$1(false, "unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.') : void 0; } return false; } }, // Temporary alias since we already shipped React 16 RC with it. // TODO: remove in React 17. unstable_createPortal: function () { if (!didWarnAboutUnstableCreatePortal) { didWarnAboutUnstableCreatePortal = true; lowPriorityWarning$1(false, 'The ReactDOM.unstable_createPortal() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactDOM.createPortal() instead. It has the exact same API, ' + 'but without the "unstable_" prefix.'); } return createPortal$$1.apply(undefined, arguments); }, unstable_batchedUpdates: batchedUpdates$1, unstable_interactiveUpdates: interactiveUpdates$1, flushSync: flushSync, unstable_createRoot: createRoot, unstable_flushControlled: flushControlled, __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: { // Keep in sync with ReactDOMUnstableNativeDependencies.js // and ReactTestUtils.js. This is an array for better minification. Events: [getInstanceFromNode$1, getNodeFromInstance$1, getFiberCurrentPropsFromNode$1, injection.injectEventPluginsByName, eventNameDispatchConfigs, accumulateTwoPhaseDispatches, accumulateDirectDispatches, enqueueStateRestore, restoreStateIfNeeded, dispatchEvent, runEventsInBatch] } }; function createRoot(container, options) { var functionName = enableStableConcurrentModeAPIs ? 'createRoot' : 'unstable_createRoot'; !isValidContainer(container) ? invariant(false, '%s(...): Target container is not a DOM element.', functionName) : void 0; { !!container._reactRootContainer ? warningWithoutStack$1(false, 'You are calling ReactDOM.%s() on a container that was previously ' + 'passed to ReactDOM.render(). This is not supported.', enableStableConcurrentModeAPIs ? 'createRoot' : 'unstable_createRoot') : void 0; container._reactHasBeenPassedToCreateRootDEV = true; } var hydrate = options != null && options.hydrate === true; return new ReactRoot(container, true, hydrate); } if (enableStableConcurrentModeAPIs) { ReactDOM.createRoot = createRoot; ReactDOM.unstable_createRoot = undefined; } var foundDevTools = injectIntoDevTools({ findFiberByHostInstance: getClosestInstanceFromNode, bundleType: 1, version: ReactVersion, rendererPackageName: 'react-dom' }); { if (!foundDevTools && canUseDOM && window.top === window.self) { // If we're in Chrome or Firefox, provide a download link if not installed. if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) { var protocol = window.location.protocol; // Don't warn in exotic cases like chrome-extension://. if (/^(https?|file):$/.test(protocol)) { console.info('%cDownload the React DevTools ' + 'for a better development experience: ' + 'https://fb.me/react-devtools' + (protocol === 'file:' ? '\nYou might need to use a local HTTP server (instead of file://): ' + 'https://fb.me/react-devtools-faq' : ''), 'font-weight:bold'); } } } } var ReactDOM$2 = Object.freeze({ default: ReactDOM }); var ReactDOM$3 = ( ReactDOM$2 && ReactDOM ) || ReactDOM$2; // TODO: decide on the top-level export form. // This is hacky but makes it work with both Rollup and Jest. var reactDom = ReactDOM$3.default || ReactDOM$3; module.exports = reactDom; })(); } }).call(this,require('_process')) },{"_process":405,"object-assign":402,"prop-types/checkPropTypes":406,"react":417,"scheduler":436,"scheduler/tracing":437}],412:[function(require,module,exports){ /** @license React v16.8.6 * react-dom.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* Modernizr 3.0.0pre (Custom Build) | MIT */ 'use strict';var aa=require("react"),n=require("object-assign"),r=require("scheduler");function ba(a,b,c,d,e,f,g,h){if(!a){a=void 0;if(void 0===b)a=Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var l=[c,d,e,f,g,h],k=0;a=Error(b.replace(/%s/g,function(){return l[k++]}));a.name="Invariant Violation"}a.framesToPop=1;throw a;}} function x(a){for(var b=arguments.length-1,c="https://reactjs.org/docs/error-decoder.html?invariant="+a,d=0;d<b;d++)c+="&args[]="+encodeURIComponent(arguments[d+1]);ba(!1,"Minified React error #"+a+"; visit %s for the full message or use the non-minified dev environment for full errors and additional helpful warnings. ",c)}aa?void 0:x("227");function ca(a,b,c,d,e,f,g,h,l){var k=Array.prototype.slice.call(arguments,3);try{b.apply(c,k)}catch(m){this.onError(m)}} var da=!1,ea=null,fa=!1,ha=null,ia={onError:function(a){da=!0;ea=a}};function ja(a,b,c,d,e,f,g,h,l){da=!1;ea=null;ca.apply(ia,arguments)}function ka(a,b,c,d,e,f,g,h,l){ja.apply(this,arguments);if(da){if(da){var k=ea;da=!1;ea=null}else x("198"),k=void 0;fa||(fa=!0,ha=k)}}var la=null,ma={}; function na(){if(la)for(var a in ma){var b=ma[a],c=la.indexOf(a);-1<c?void 0:x("96",a);if(!oa[c]){b.extractEvents?void 0:x("97",a);oa[c]=b;c=b.eventTypes;for(var d in c){var e=void 0;var f=c[d],g=b,h=d;pa.hasOwnProperty(h)?x("99",h):void 0;pa[h]=f;var l=f.phasedRegistrationNames;if(l){for(e in l)l.hasOwnProperty(e)&&qa(l[e],g,h);e=!0}else f.registrationName?(qa(f.registrationName,g,h),e=!0):e=!1;e?void 0:x("98",d,a)}}}} function qa(a,b,c){ra[a]?x("100",a):void 0;ra[a]=b;sa[a]=b.eventTypes[c].dependencies}var oa=[],pa={},ra={},sa={},ta=null,ua=null,va=null;function wa(a,b,c){var d=a.type||"unknown-event";a.currentTarget=va(c);ka(d,b,void 0,a);a.currentTarget=null}function xa(a,b){null==b?x("30"):void 0;if(null==a)return b;if(Array.isArray(a)){if(Array.isArray(b))return a.push.apply(a,b),a;a.push(b);return a}return Array.isArray(b)?[a].concat(b):[a,b]} function ya(a,b,c){Array.isArray(a)?a.forEach(b,c):a&&b.call(c,a)}var za=null;function Aa(a){if(a){var b=a._dispatchListeners,c=a._dispatchInstances;if(Array.isArray(b))for(var d=0;d<b.length&&!a.isPropagationStopped();d++)wa(a,b[d],c[d]);else b&&wa(a,b,c);a._dispatchListeners=null;a._dispatchInstances=null;a.isPersistent()||a.constructor.release(a)}} var Ba={injectEventPluginOrder:function(a){la?x("101"):void 0;la=Array.prototype.slice.call(a);na()},injectEventPluginsByName:function(a){var b=!1,c;for(c in a)if(a.hasOwnProperty(c)){var d=a[c];ma.hasOwnProperty(c)&&ma[c]===d||(ma[c]?x("102",c):void 0,ma[c]=d,b=!0)}b&&na()}}; function Ca(a,b){var c=a.stateNode;if(!c)return null;var d=ta(c);if(!d)return null;c=d[b];a:switch(b){case "onClick":case "onClickCapture":case "onDoubleClick":case "onDoubleClickCapture":case "onMouseDown":case "onMouseDownCapture":case "onMouseMove":case "onMouseMoveCapture":case "onMouseUp":case "onMouseUpCapture":(d=!d.disabled)||(a=a.type,d=!("button"===a||"input"===a||"select"===a||"textarea"===a));a=!d;break a;default:a=!1}if(a)return null;c&&"function"!==typeof c?x("231",b,typeof c):void 0; return c}function Da(a){null!==a&&(za=xa(za,a));a=za;za=null;if(a&&(ya(a,Aa),za?x("95"):void 0,fa))throw a=ha,fa=!1,ha=null,a;}var Ea=Math.random().toString(36).slice(2),Fa="__reactInternalInstance$"+Ea,Ga="__reactEventHandlers$"+Ea;function Ha(a){if(a[Fa])return a[Fa];for(;!a[Fa];)if(a.parentNode)a=a.parentNode;else return null;a=a[Fa];return 5===a.tag||6===a.tag?a:null}function Ia(a){a=a[Fa];return!a||5!==a.tag&&6!==a.tag?null:a} function Ja(a){if(5===a.tag||6===a.tag)return a.stateNode;x("33")}function Ka(a){return a[Ga]||null}function La(a){do a=a.return;while(a&&5!==a.tag);return a?a:null}function Ma(a,b,c){if(b=Ca(a,c.dispatchConfig.phasedRegistrationNames[b]))c._dispatchListeners=xa(c._dispatchListeners,b),c._dispatchInstances=xa(c._dispatchInstances,a)} function Na(a){if(a&&a.dispatchConfig.phasedRegistrationNames){for(var b=a._targetInst,c=[];b;)c.push(b),b=La(b);for(b=c.length;0<b--;)Ma(c[b],"captured",a);for(b=0;b<c.length;b++)Ma(c[b],"bubbled",a)}}function Oa(a,b,c){a&&c&&c.dispatchConfig.registrationName&&(b=Ca(a,c.dispatchConfig.registrationName))&&(c._dispatchListeners=xa(c._dispatchListeners,b),c._dispatchInstances=xa(c._dispatchInstances,a))}function Pa(a){a&&a.dispatchConfig.registrationName&&Oa(a._targetInst,null,a)} function Qa(a){ya(a,Na)}var Ra=!("undefined"===typeof window||!window.document||!window.document.createElement);function Sa(a,b){var c={};c[a.toLowerCase()]=b.toLowerCase();c["Webkit"+a]="webkit"+b;c["Moz"+a]="moz"+b;return c}var Ta={animationend:Sa("Animation","AnimationEnd"),animationiteration:Sa("Animation","AnimationIteration"),animationstart:Sa("Animation","AnimationStart"),transitionend:Sa("Transition","TransitionEnd")},Ua={},Va={}; Ra&&(Va=document.createElement("div").style,"AnimationEvent"in window||(delete Ta.animationend.animation,delete Ta.animationiteration.animation,delete Ta.animationstart.animation),"TransitionEvent"in window||delete Ta.transitionend.transition);function Wa(a){if(Ua[a])return Ua[a];if(!Ta[a])return a;var b=Ta[a],c;for(c in b)if(b.hasOwnProperty(c)&&c in Va)return Ua[a]=b[c];return a} var Xa=Wa("animationend"),Ya=Wa("animationiteration"),Za=Wa("animationstart"),$a=Wa("transitionend"),ab="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),bb=null,cb=null,db=null; function eb(){if(db)return db;var a,b=cb,c=b.length,d,e="value"in bb?bb.value:bb.textContent,f=e.length;for(a=0;a<c&&b[a]===e[a];a++);var g=c-a;for(d=1;d<=g&&b[c-d]===e[f-d];d++);return db=e.slice(a,1<d?1-d:void 0)}function fb(){return!0}function gb(){return!1} function y(a,b,c,d){this.dispatchConfig=a;this._targetInst=b;this.nativeEvent=c;a=this.constructor.Interface;for(var e in a)a.hasOwnProperty(e)&&((b=a[e])?this[e]=b(c):"target"===e?this.target=d:this[e]=c[e]);this.isDefaultPrevented=(null!=c.defaultPrevented?c.defaultPrevented:!1===c.returnValue)?fb:gb;this.isPropagationStopped=gb;return this} n(y.prototype,{preventDefault:function(){this.defaultPrevented=!0;var a=this.nativeEvent;a&&(a.preventDefault?a.preventDefault():"unknown"!==typeof a.returnValue&&(a.returnValue=!1),this.isDefaultPrevented=fb)},stopPropagation:function(){var a=this.nativeEvent;a&&(a.stopPropagation?a.stopPropagation():"unknown"!==typeof a.cancelBubble&&(a.cancelBubble=!0),this.isPropagationStopped=fb)},persist:function(){this.isPersistent=fb},isPersistent:gb,destructor:function(){var a=this.constructor.Interface, b;for(b in a)this[b]=null;this.nativeEvent=this._targetInst=this.dispatchConfig=null;this.isPropagationStopped=this.isDefaultPrevented=gb;this._dispatchInstances=this._dispatchListeners=null}});y.Interface={type:null,target:null,currentTarget:function(){return null},eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(a){return a.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null}; y.extend=function(a){function b(){}function c(){return d.apply(this,arguments)}var d=this;b.prototype=d.prototype;var e=new b;n(e,c.prototype);c.prototype=e;c.prototype.constructor=c;c.Interface=n({},d.Interface,a);c.extend=d.extend;hb(c);return c};hb(y);function ib(a,b,c,d){if(this.eventPool.length){var e=this.eventPool.pop();this.call(e,a,b,c,d);return e}return new this(a,b,c,d)}function jb(a){a instanceof this?void 0:x("279");a.destructor();10>this.eventPool.length&&this.eventPool.push(a)} function hb(a){a.eventPool=[];a.getPooled=ib;a.release=jb}var kb=y.extend({data:null}),lb=y.extend({data:null}),mb=[9,13,27,32],nb=Ra&&"CompositionEvent"in window,ob=null;Ra&&"documentMode"in document&&(ob=document.documentMode); var pb=Ra&&"TextEvent"in window&&!ob,qb=Ra&&(!nb||ob&&8<ob&&11>=ob),rb=String.fromCharCode(32),sb={beforeInput:{phasedRegistrationNames:{bubbled:"onBeforeInput",captured:"onBeforeInputCapture"},dependencies:["compositionend","keypress","textInput","paste"]},compositionEnd:{phasedRegistrationNames:{bubbled:"onCompositionEnd",captured:"onCompositionEndCapture"},dependencies:"blur compositionend keydown keypress keyup mousedown".split(" ")},compositionStart:{phasedRegistrationNames:{bubbled:"onCompositionStart", captured:"onCompositionStartCapture"},dependencies:"blur compositionstart keydown keypress keyup mousedown".split(" ")},compositionUpdate:{phasedRegistrationNames:{bubbled:"onCompositionUpdate",captured:"onCompositionUpdateCapture"},dependencies:"blur compositionupdate keydown keypress keyup mousedown".split(" ")}},tb=!1; function ub(a,b){switch(a){case "keyup":return-1!==mb.indexOf(b.keyCode);case "keydown":return 229!==b.keyCode;case "keypress":case "mousedown":case "blur":return!0;default:return!1}}function vb(a){a=a.detail;return"object"===typeof a&&"data"in a?a.data:null}var wb=!1;function xb(a,b){switch(a){case "compositionend":return vb(b);case "keypress":if(32!==b.which)return null;tb=!0;return rb;case "textInput":return a=b.data,a===rb&&tb?null:a;default:return null}} function yb(a,b){if(wb)return"compositionend"===a||!nb&&ub(a,b)?(a=eb(),db=cb=bb=null,wb=!1,a):null;switch(a){case "paste":return null;case "keypress":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1<b.char.length)return b.char;if(b.which)return String.fromCharCode(b.which)}return null;case "compositionend":return qb&&"ko"!==b.locale?null:b.data;default:return null}} var zb={eventTypes:sb,extractEvents:function(a,b,c,d){var e=void 0;var f=void 0;if(nb)b:{switch(a){case "compositionstart":e=sb.compositionStart;break b;case "compositionend":e=sb.compositionEnd;break b;case "compositionupdate":e=sb.compositionUpdate;break b}e=void 0}else wb?ub(a,c)&&(e=sb.compositionEnd):"keydown"===a&&229===c.keyCode&&(e=sb.compositionStart);e?(qb&&"ko"!==c.locale&&(wb||e!==sb.compositionStart?e===sb.compositionEnd&&wb&&(f=eb()):(bb=d,cb="value"in bb?bb.value:bb.textContent,wb= !0)),e=kb.getPooled(e,b,c,d),f?e.data=f:(f=vb(c),null!==f&&(e.data=f)),Qa(e),f=e):f=null;(a=pb?xb(a,c):yb(a,c))?(b=lb.getPooled(sb.beforeInput,b,c,d),b.data=a,Qa(b)):b=null;return null===f?b:null===b?f:[f,b]}},Ab=null,Bb=null,Cb=null;function Db(a){if(a=ua(a)){"function"!==typeof Ab?x("280"):void 0;var b=ta(a.stateNode);Ab(a.stateNode,a.type,b)}}function Eb(a){Bb?Cb?Cb.push(a):Cb=[a]:Bb=a}function Fb(){if(Bb){var a=Bb,b=Cb;Cb=Bb=null;Db(a);if(b)for(a=0;a<b.length;a++)Db(b[a])}} function Gb(a,b){return a(b)}function Hb(a,b,c){return a(b,c)}function Ib(){}var Jb=!1;function Kb(a,b){if(Jb)return a(b);Jb=!0;try{return Gb(a,b)}finally{if(Jb=!1,null!==Bb||null!==Cb)Ib(),Fb()}}var Lb={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function Mb(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return"input"===b?!!Lb[a.type]:"textarea"===b?!0:!1} function Nb(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}function Ob(a){if(!Ra)return!1;a="on"+a;var b=a in document;b||(b=document.createElement("div"),b.setAttribute(a,"return;"),b="function"===typeof b[a]);return b}function Pb(a){var b=a.type;return(a=a.nodeName)&&"input"===a.toLowerCase()&&("checkbox"===b||"radio"===b)} function Qb(a){var b=Pb(a)?"checked":"value",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=""+a[b];if(!a.hasOwnProperty(b)&&"undefined"!==typeof c&&"function"===typeof c.get&&"function"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=""+a;f.call(this,a)}});Object.defineProperty(a,b,{enumerable:c.enumerable});return{getValue:function(){return d},setValue:function(a){d=""+a},stopTracking:function(){a._valueTracker= null;delete a[b]}}}}function Rb(a){a._valueTracker||(a._valueTracker=Qb(a))}function Sb(a){if(!a)return!1;var b=a._valueTracker;if(!b)return!0;var c=b.getValue();var d="";a&&(d=Pb(a)?a.checked?"true":"false":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}var Tb=aa.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;Tb.hasOwnProperty("ReactCurrentDispatcher")||(Tb.ReactCurrentDispatcher={current:null}); var Ub=/^(.*)[\\\/]/,z="function"===typeof Symbol&&Symbol.for,Vb=z?Symbol.for("react.element"):60103,Wb=z?Symbol.for("react.portal"):60106,Xb=z?Symbol.for("react.fragment"):60107,Yb=z?Symbol.for("react.strict_mode"):60108,Zb=z?Symbol.for("react.profiler"):60114,$b=z?Symbol.for("react.provider"):60109,ac=z?Symbol.for("react.context"):60110,bc=z?Symbol.for("react.concurrent_mode"):60111,cc=z?Symbol.for("react.forward_ref"):60112,dc=z?Symbol.for("react.suspense"):60113,ec=z?Symbol.for("react.memo"): 60115,fc=z?Symbol.for("react.lazy"):60116,gc="function"===typeof Symbol&&Symbol.iterator;function hc(a){if(null===a||"object"!==typeof a)return null;a=gc&&a[gc]||a["@@iterator"];return"function"===typeof a?a:null} function ic(a){if(null==a)return null;if("function"===typeof a)return a.displayName||a.name||null;if("string"===typeof a)return a;switch(a){case bc:return"ConcurrentMode";case Xb:return"Fragment";case Wb:return"Portal";case Zb:return"Profiler";case Yb:return"StrictMode";case dc:return"Suspense"}if("object"===typeof a)switch(a.$$typeof){case ac:return"Context.Consumer";case $b:return"Context.Provider";case cc:var b=a.render;b=b.displayName||b.name||"";return a.displayName||(""!==b?"ForwardRef("+b+ ")":"ForwardRef");case ec:return ic(a.type);case fc:if(a=1===a._status?a._result:null)return ic(a)}return null}function jc(a){var b="";do{a:switch(a.tag){case 3:case 4:case 6:case 7:case 10:case 9:var c="";break a;default:var d=a._debugOwner,e=a._debugSource,f=ic(a.type);c=null;d&&(c=ic(d.type));d=f;f="";e?f=" (at "+e.fileName.replace(Ub,"")+":"+e.lineNumber+")":c&&(f=" (created by "+c+")");c="\n in "+(d||"Unknown")+f}b+=c;a=a.return}while(a);return b} var kc=/^[: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][: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\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,lc=Object.prototype.hasOwnProperty,mc={},nc={}; function oc(a){if(lc.call(nc,a))return!0;if(lc.call(mc,a))return!1;if(kc.test(a))return nc[a]=!0;mc[a]=!0;return!1}function pc(a,b,c,d){if(null!==c&&0===c.type)return!1;switch(typeof b){case "function":case "symbol":return!0;case "boolean":if(d)return!1;if(null!==c)return!c.acceptsBooleans;a=a.toLowerCase().slice(0,5);return"data-"!==a&&"aria-"!==a;default:return!1}} function qc(a,b,c,d){if(null===b||"undefined"===typeof b||pc(a,b,c,d))return!0;if(d)return!1;if(null!==c)switch(c.type){case 3:return!b;case 4:return!1===b;case 5:return isNaN(b);case 6:return isNaN(b)||1>b}return!1}function C(a,b,c,d,e){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b}var D={}; "children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){D[a]=new C(a,0,!1,a,null)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];D[b]=new C(b,1,!1,a[1],null)});["contentEditable","draggable","spellCheck","value"].forEach(function(a){D[a]=new C(a,2,!1,a.toLowerCase(),null)}); ["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){D[a]=new C(a,2,!1,a,null)});"allowFullScreen async autoFocus autoPlay controls default defer disabled formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){D[a]=new C(a,3,!1,a.toLowerCase(),null)});["checked","multiple","muted","selected"].forEach(function(a){D[a]=new C(a,3,!0,a,null)}); ["capture","download"].forEach(function(a){D[a]=new C(a,4,!1,a,null)});["cols","rows","size","span"].forEach(function(a){D[a]=new C(a,6,!1,a,null)});["rowSpan","start"].forEach(function(a){D[a]=new C(a,5,!1,a.toLowerCase(),null)});var rc=/[\-:]([a-z])/g;function sc(a){return a[1].toUpperCase()} "accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=a.replace(rc, sc);D[b]=new C(b,1,!1,a,null)});"xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(rc,sc);D[b]=new C(b,1,!1,a,"http://www.w3.org/1999/xlink")});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(rc,sc);D[b]=new C(b,1,!1,a,"http://www.w3.org/XML/1998/namespace")});["tabIndex","crossOrigin"].forEach(function(a){D[a]=new C(a,1,!1,a.toLowerCase(),null)}); function tc(a,b,c,d){var e=D.hasOwnProperty(b)?D[b]:null;var f=null!==e?0===e.type:d?!1:!(2<b.length)||"o"!==b[0]&&"O"!==b[0]||"n"!==b[1]&&"N"!==b[1]?!1:!0;f||(qc(b,c,e,d)&&(c=null),d||null===e?oc(b)&&(null===c?a.removeAttribute(b):a.setAttribute(b,""+c)):e.mustUseProperty?a[e.propertyName]=null===c?3===e.type?!1:"":c:(b=e.attributeName,d=e.attributeNamespace,null===c?a.removeAttribute(b):(e=e.type,c=3===e||4===e&&!0===c?"":""+c,d?a.setAttributeNS(d,b,c):a.setAttribute(b,c))))} function uc(a){switch(typeof a){case "boolean":case "number":case "object":case "string":case "undefined":return a;default:return""}}function vc(a,b){var c=b.checked;return n({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})} function wc(a,b){var c=null==b.defaultValue?"":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=uc(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:"checkbox"===b.type||"radio"===b.type?null!=b.checked:null!=b.value}}function xc(a,b){b=b.checked;null!=b&&tc(a,"checked",b,!1)} function yc(a,b){xc(a,b);var c=uc(b.value),d=b.type;if(null!=c)if("number"===d){if(0===c&&""===a.value||a.value!=c)a.value=""+c}else a.value!==""+c&&(a.value=""+c);else if("submit"===d||"reset"===d){a.removeAttribute("value");return}b.hasOwnProperty("value")?zc(a,b.type,c):b.hasOwnProperty("defaultValue")&&zc(a,b.type,uc(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)} function Ac(a,b,c){if(b.hasOwnProperty("value")||b.hasOwnProperty("defaultValue")){var d=b.type;if(!("submit"!==d&&"reset"!==d||void 0!==b.value&&null!==b.value))return;b=""+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b}c=a.name;""!==c&&(a.name="");a.defaultChecked=!a.defaultChecked;a.defaultChecked=!!a._wrapperState.initialChecked;""!==c&&(a.name=c)} function zc(a,b,c){if("number"!==b||a.ownerDocument.activeElement!==a)null==c?a.defaultValue=""+a._wrapperState.initialValue:a.defaultValue!==""+c&&(a.defaultValue=""+c)}var Bc={change:{phasedRegistrationNames:{bubbled:"onChange",captured:"onChangeCapture"},dependencies:"blur change click focus input keydown keyup selectionchange".split(" ")}};function Cc(a,b,c){a=y.getPooled(Bc.change,a,b,c);a.type="change";Eb(c);Qa(a);return a}var Dc=null,Ec=null;function Fc(a){Da(a)} function Gc(a){var b=Ja(a);if(Sb(b))return a}function Hc(a,b){if("change"===a)return b}var Ic=!1;Ra&&(Ic=Ob("input")&&(!document.documentMode||9<document.documentMode));function Jc(){Dc&&(Dc.detachEvent("onpropertychange",Kc),Ec=Dc=null)}function Kc(a){"value"===a.propertyName&&Gc(Ec)&&(a=Cc(Ec,a,Nb(a)),Kb(Fc,a))}function Lc(a,b,c){"focus"===a?(Jc(),Dc=b,Ec=c,Dc.attachEvent("onpropertychange",Kc)):"blur"===a&&Jc()}function Mc(a){if("selectionchange"===a||"keyup"===a||"keydown"===a)return Gc(Ec)} function Nc(a,b){if("click"===a)return Gc(b)}function Oc(a,b){if("input"===a||"change"===a)return Gc(b)} var Pc={eventTypes:Bc,_isInputEventSupported:Ic,extractEvents:function(a,b,c,d){var e=b?Ja(b):window,f=void 0,g=void 0,h=e.nodeName&&e.nodeName.toLowerCase();"select"===h||"input"===h&&"file"===e.type?f=Hc:Mb(e)?Ic?f=Oc:(f=Mc,g=Lc):(h=e.nodeName)&&"input"===h.toLowerCase()&&("checkbox"===e.type||"radio"===e.type)&&(f=Nc);if(f&&(f=f(a,b)))return Cc(f,c,d);g&&g(a,e,b);"blur"===a&&(a=e._wrapperState)&&a.controlled&&"number"===e.type&&zc(e,"number",e.value)}},Qc=y.extend({view:null,detail:null}),Rc={Alt:"altKey", Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Sc(a){var b=this.nativeEvent;return b.getModifierState?b.getModifierState(a):(a=Rc[a])?!!b[a]:!1}function Tc(){return Sc} var Uc=0,Vc=0,Wc=!1,Xc=!1,Yc=Qc.extend({screenX:null,screenY:null,clientX:null,clientY:null,pageX:null,pageY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:Tc,button:null,buttons:null,relatedTarget:function(a){return a.relatedTarget||(a.fromElement===a.srcElement?a.toElement:a.fromElement)},movementX:function(a){if("movementX"in a)return a.movementX;var b=Uc;Uc=a.screenX;return Wc?"mousemove"===a.type?a.screenX-b:0:(Wc=!0,0)},movementY:function(a){if("movementY"in a)return a.movementY; var b=Vc;Vc=a.screenY;return Xc?"mousemove"===a.type?a.screenY-b:0:(Xc=!0,0)}}),Zc=Yc.extend({pointerId:null,width:null,height:null,pressure:null,tangentialPressure:null,tiltX:null,tiltY:null,twist:null,pointerType:null,isPrimary:null}),$c={mouseEnter:{registrationName:"onMouseEnter",dependencies:["mouseout","mouseover"]},mouseLeave:{registrationName:"onMouseLeave",dependencies:["mouseout","mouseover"]},pointerEnter:{registrationName:"onPointerEnter",dependencies:["pointerout","pointerover"]},pointerLeave:{registrationName:"onPointerLeave", dependencies:["pointerout","pointerover"]}},ad={eventTypes:$c,extractEvents:function(a,b,c,d){var e="mouseover"===a||"pointerover"===a,f="mouseout"===a||"pointerout"===a;if(e&&(c.relatedTarget||c.fromElement)||!f&&!e)return null;e=d.window===d?d:(e=d.ownerDocument)?e.defaultView||e.parentWindow:window;f?(f=b,b=(b=c.relatedTarget||c.toElement)?Ha(b):null):f=null;if(f===b)return null;var g=void 0,h=void 0,l=void 0,k=void 0;if("mouseout"===a||"mouseover"===a)g=Yc,h=$c.mouseLeave,l=$c.mouseEnter,k="mouse"; else if("pointerout"===a||"pointerover"===a)g=Zc,h=$c.pointerLeave,l=$c.pointerEnter,k="pointer";var m=null==f?e:Ja(f);e=null==b?e:Ja(b);a=g.getPooled(h,f,c,d);a.type=k+"leave";a.target=m;a.relatedTarget=e;c=g.getPooled(l,b,c,d);c.type=k+"enter";c.target=e;c.relatedTarget=m;d=b;if(f&&d)a:{b=f;e=d;k=0;for(g=b;g;g=La(g))k++;g=0;for(l=e;l;l=La(l))g++;for(;0<k-g;)b=La(b),k--;for(;0<g-k;)e=La(e),g--;for(;k--;){if(b===e||b===e.alternate)break a;b=La(b);e=La(e)}b=null}else b=null;e=b;for(b=[];f&&f!==e;){k= f.alternate;if(null!==k&&k===e)break;b.push(f);f=La(f)}for(f=[];d&&d!==e;){k=d.alternate;if(null!==k&&k===e)break;f.push(d);d=La(d)}for(d=0;d<b.length;d++)Oa(b[d],"bubbled",a);for(d=f.length;0<d--;)Oa(f[d],"captured",c);return[a,c]}};function bd(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var cd=Object.prototype.hasOwnProperty; function dd(a,b){if(bd(a,b))return!0;if("object"!==typeof a||null===a||"object"!==typeof b||null===b)return!1;var c=Object.keys(a),d=Object.keys(b);if(c.length!==d.length)return!1;for(d=0;d<c.length;d++)if(!cd.call(b,c[d])||!bd(a[c[d]],b[c[d]]))return!1;return!0}function ed(a){var b=a;if(a.alternate)for(;b.return;)b=b.return;else{if(0!==(b.effectTag&2))return 1;for(;b.return;)if(b=b.return,0!==(b.effectTag&2))return 1}return 3===b.tag?2:3}function fd(a){2!==ed(a)?x("188"):void 0} function gd(a){var b=a.alternate;if(!b)return b=ed(a),3===b?x("188"):void 0,1===b?null:a;for(var c=a,d=b;;){var e=c.return,f=e?e.alternate:null;if(!e||!f)break;if(e.child===f.child){for(var g=e.child;g;){if(g===c)return fd(e),a;if(g===d)return fd(e),b;g=g.sibling}x("188")}if(c.return!==d.return)c=e,d=f;else{g=!1;for(var h=e.child;h;){if(h===c){g=!0;c=e;d=f;break}if(h===d){g=!0;d=e;c=f;break}h=h.sibling}if(!g){for(h=f.child;h;){if(h===c){g=!0;c=f;d=e;break}if(h===d){g=!0;d=f;c=e;break}h=h.sibling}g? void 0:x("189")}}c.alternate!==d?x("190"):void 0}3!==c.tag?x("188"):void 0;return c.stateNode.current===c?a:b}function hd(a){a=gd(a);if(!a)return null;for(var b=a;;){if(5===b.tag||6===b.tag)return b;if(b.child)b.child.return=b,b=b.child;else{if(b===a)break;for(;!b.sibling;){if(!b.return||b.return===a)return null;b=b.return}b.sibling.return=b.return;b=b.sibling}}return null} var id=y.extend({animationName:null,elapsedTime:null,pseudoElement:null}),jd=y.extend({clipboardData:function(a){return"clipboardData"in a?a.clipboardData:window.clipboardData}}),kd=Qc.extend({relatedTarget:null});function ld(a){var b=a.keyCode;"charCode"in a?(a=a.charCode,0===a&&13===b&&(a=13)):a=b;10===a&&(a=13);return 32<=a||13===a?a:0} var md={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},nd={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4", 116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},od=Qc.extend({key:function(a){if(a.key){var b=md[a.key]||a.key;if("Unidentified"!==b)return b}return"keypress"===a.type?(a=ld(a),13===a?"Enter":String.fromCharCode(a)):"keydown"===a.type||"keyup"===a.type?nd[a.keyCode]||"Unidentified":""},location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:Tc,charCode:function(a){return"keypress"=== a.type?ld(a):0},keyCode:function(a){return"keydown"===a.type||"keyup"===a.type?a.keyCode:0},which:function(a){return"keypress"===a.type?ld(a):"keydown"===a.type||"keyup"===a.type?a.keyCode:0}}),pd=Yc.extend({dataTransfer:null}),qd=Qc.extend({touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:Tc}),rd=y.extend({propertyName:null,elapsedTime:null,pseudoElement:null}),sd=Yc.extend({deltaX:function(a){return"deltaX"in a?a.deltaX:"wheelDeltaX"in a?-a.wheelDeltaX:0},deltaY:function(a){return"deltaY"in a?a.deltaY:"wheelDeltaY"in a?-a.wheelDeltaY:"wheelDelta"in a?-a.wheelDelta:0},deltaZ:null,deltaMode:null}),td=[["abort","abort"],[Xa,"animationEnd"],[Ya,"animationIteration"],[Za,"animationStart"],["canplay","canPlay"],["canplaythrough","canPlayThrough"],["drag","drag"],["dragenter","dragEnter"],["dragexit","dragExit"],["dragleave","dragLeave"],["dragover","dragOver"],["durationchange","durationChange"],["emptied","emptied"],["encrypted","encrypted"], ["ended","ended"],["error","error"],["gotpointercapture","gotPointerCapture"],["load","load"],["loadeddata","loadedData"],["loadedmetadata","loadedMetadata"],["loadstart","loadStart"],["lostpointercapture","lostPointerCapture"],["mousemove","mouseMove"],["mouseout","mouseOut"],["mouseover","mouseOver"],["playing","playing"],["pointermove","pointerMove"],["pointerout","pointerOut"],["pointerover","pointerOver"],["progress","progress"],["scroll","scroll"],["seeking","seeking"],["stalled","stalled"], ["suspend","suspend"],["timeupdate","timeUpdate"],["toggle","toggle"],["touchmove","touchMove"],[$a,"transitionEnd"],["waiting","waiting"],["wheel","wheel"]],ud={},vd={};function wd(a,b){var c=a[0];a=a[1];var d="on"+(a[0].toUpperCase()+a.slice(1));b={phasedRegistrationNames:{bubbled:d,captured:d+"Capture"},dependencies:[c],isInteractive:b};ud[a]=b;vd[c]=b} [["blur","blur"],["cancel","cancel"],["click","click"],["close","close"],["contextmenu","contextMenu"],["copy","copy"],["cut","cut"],["auxclick","auxClick"],["dblclick","doubleClick"],["dragend","dragEnd"],["dragstart","dragStart"],["drop","drop"],["focus","focus"],["input","input"],["invalid","invalid"],["keydown","keyDown"],["keypress","keyPress"],["keyup","keyUp"],["mousedown","mouseDown"],["mouseup","mouseUp"],["paste","paste"],["pause","pause"],["play","play"],["pointercancel","pointerCancel"], ["pointerdown","pointerDown"],["pointerup","pointerUp"],["ratechange","rateChange"],["reset","reset"],["seeked","seeked"],["submit","submit"],["touchcancel","touchCancel"],["touchend","touchEnd"],["touchstart","touchStart"],["volumechange","volumeChange"]].forEach(function(a){wd(a,!0)});td.forEach(function(a){wd(a,!1)}); var xd={eventTypes:ud,isInteractiveTopLevelEventType:function(a){a=vd[a];return void 0!==a&&!0===a.isInteractive},extractEvents:function(a,b,c,d){var e=vd[a];if(!e)return null;switch(a){case "keypress":if(0===ld(c))return null;case "keydown":case "keyup":a=od;break;case "blur":case "focus":a=kd;break;case "click":if(2===c.button)return null;case "auxclick":case "dblclick":case "mousedown":case "mousemove":case "mouseup":case "mouseout":case "mouseover":case "contextmenu":a=Yc;break;case "drag":case "dragend":case "dragenter":case "dragexit":case "dragleave":case "dragover":case "dragstart":case "drop":a= pd;break;case "touchcancel":case "touchend":case "touchmove":case "touchstart":a=qd;break;case Xa:case Ya:case Za:a=id;break;case $a:a=rd;break;case "scroll":a=Qc;break;case "wheel":a=sd;break;case "copy":case "cut":case "paste":a=jd;break;case "gotpointercapture":case "lostpointercapture":case "pointercancel":case "pointerdown":case "pointermove":case "pointerout":case "pointerover":case "pointerup":a=Zc;break;default:a=y}b=a.getPooled(e,b,c,d);Qa(b);return b}},yd=xd.isInteractiveTopLevelEventType, zd=[];function Ad(a){var b=a.targetInst,c=b;do{if(!c){a.ancestors.push(c);break}var d;for(d=c;d.return;)d=d.return;d=3!==d.tag?null:d.stateNode.containerInfo;if(!d)break;a.ancestors.push(c);c=Ha(d)}while(c);for(c=0;c<a.ancestors.length;c++){b=a.ancestors[c];var e=Nb(a.nativeEvent);d=a.topLevelType;for(var f=a.nativeEvent,g=null,h=0;h<oa.length;h++){var l=oa[h];l&&(l=l.extractEvents(d,b,f,e))&&(g=xa(g,l))}Da(g)}}var Bd=!0; function E(a,b){if(!b)return null;var c=(yd(a)?Cd:Dd).bind(null,a);b.addEventListener(a,c,!1)}function Ed(a,b){if(!b)return null;var c=(yd(a)?Cd:Dd).bind(null,a);b.addEventListener(a,c,!0)}function Cd(a,b){Hb(Dd,a,b)} function Dd(a,b){if(Bd){var c=Nb(b);c=Ha(c);null===c||"number"!==typeof c.tag||2===ed(c)||(c=null);if(zd.length){var d=zd.pop();d.topLevelType=a;d.nativeEvent=b;d.targetInst=c;a=d}else a={topLevelType:a,nativeEvent:b,targetInst:c,ancestors:[]};try{Kb(Ad,a)}finally{a.topLevelType=null,a.nativeEvent=null,a.targetInst=null,a.ancestors.length=0,10>zd.length&&zd.push(a)}}}var Fd={},Gd=0,Hd="_reactListenersID"+(""+Math.random()).slice(2); function Id(a){Object.prototype.hasOwnProperty.call(a,Hd)||(a[Hd]=Gd++,Fd[a[Hd]]={});return Fd[a[Hd]]}function Jd(a){a=a||("undefined"!==typeof document?document:void 0);if("undefined"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}}function Kd(a){for(;a&&a.firstChild;)a=a.firstChild;return a} function Ld(a,b){var c=Kd(a);a=0;for(var d;c;){if(3===c.nodeType){d=a+c.textContent.length;if(a<=b&&d>=b)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=Kd(c)}}function Md(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Md(a,b.parentNode):"contains"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1} function Nd(){for(var a=window,b=Jd();b instanceof a.HTMLIFrameElement;){try{var c="string"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;b=Jd(a.document)}return b}function Od(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&("input"===b&&("text"===a.type||"search"===a.type||"tel"===a.type||"url"===a.type||"password"===a.type)||"textarea"===b||"true"===a.contentEditable)} function Pd(){var a=Nd();if(Od(a)){if("selectionStart"in a)var b={start:a.selectionStart,end:a.selectionEnd};else a:{b=(b=a.ownerDocument)&&b.defaultView||window;var c=b.getSelection&&b.getSelection();if(c&&0!==c.rangeCount){b=c.anchorNode;var d=c.anchorOffset,e=c.focusNode;c=c.focusOffset;try{b.nodeType,e.nodeType}catch(A){b=null;break a}var f=0,g=-1,h=-1,l=0,k=0,m=a,p=null;b:for(;;){for(var t;;){m!==b||0!==d&&3!==m.nodeType||(g=f+d);m!==e||0!==c&&3!==m.nodeType||(h=f+c);3===m.nodeType&&(f+=m.nodeValue.length); if(null===(t=m.firstChild))break;p=m;m=t}for(;;){if(m===a)break b;p===b&&++l===d&&(g=f);p===e&&++k===c&&(h=f);if(null!==(t=m.nextSibling))break;m=p;p=m.parentNode}m=t}b=-1===g||-1===h?null:{start:g,end:h}}else b=null}b=b||{start:0,end:0}}else b=null;return{focusedElem:a,selectionRange:b}} function Qd(a){var b=Nd(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Md(c.ownerDocument.documentElement,c)){if(null!==d&&Od(c))if(b=d.start,a=d.end,void 0===a&&(a=b),"selectionStart"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Ld(c,f);var g=Ld(c, d);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)))}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});"function"===typeof c.focus&&c.focus();for(c=0;c<b.length;c++)a=b[c],a.element.scrollLeft=a.left,a.element.scrollTop=a.top}} var Rd=Ra&&"documentMode"in document&&11>=document.documentMode,Sd={select:{phasedRegistrationNames:{bubbled:"onSelect",captured:"onSelectCapture"},dependencies:"blur contextmenu dragend focus keydown keyup mousedown mouseup selectionchange".split(" ")}},Td=null,Ud=null,Vd=null,Wd=!1; function Xd(a,b){var c=b.window===b?b.document:9===b.nodeType?b:b.ownerDocument;if(Wd||null==Td||Td!==Jd(c))return null;c=Td;"selectionStart"in c&&Od(c)?c={start:c.selectionStart,end:c.selectionEnd}:(c=(c.ownerDocument&&c.ownerDocument.defaultView||window).getSelection(),c={anchorNode:c.anchorNode,anchorOffset:c.anchorOffset,focusNode:c.focusNode,focusOffset:c.focusOffset});return Vd&&dd(Vd,c)?null:(Vd=c,a=y.getPooled(Sd.select,Ud,a,b),a.type="select",a.target=Td,Qa(a),a)} var Yd={eventTypes:Sd,extractEvents:function(a,b,c,d){var e=d.window===d?d.document:9===d.nodeType?d:d.ownerDocument,f;if(!(f=!e)){a:{e=Id(e);f=sa.onSelect;for(var g=0;g<f.length;g++){var h=f[g];if(!e.hasOwnProperty(h)||!e[h]){e=!1;break a}}e=!0}f=!e}if(f)return null;e=b?Ja(b):window;switch(a){case "focus":if(Mb(e)||"true"===e.contentEditable)Td=e,Ud=b,Vd=null;break;case "blur":Vd=Ud=Td=null;break;case "mousedown":Wd=!0;break;case "contextmenu":case "mouseup":case "dragend":return Wd=!1,Xd(c,d);case "selectionchange":if(Rd)break; case "keydown":case "keyup":return Xd(c,d)}return null}};Ba.injectEventPluginOrder("ResponderEventPlugin SimpleEventPlugin EnterLeaveEventPlugin ChangeEventPlugin SelectEventPlugin BeforeInputEventPlugin".split(" "));ta=Ka;ua=Ia;va=Ja;Ba.injectEventPluginsByName({SimpleEventPlugin:xd,EnterLeaveEventPlugin:ad,ChangeEventPlugin:Pc,SelectEventPlugin:Yd,BeforeInputEventPlugin:zb});function Zd(a){var b="";aa.Children.forEach(a,function(a){null!=a&&(b+=a)});return b} function $d(a,b){a=n({children:void 0},b);if(b=Zd(b.children))a.children=b;return a}function ae(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e<c.length;e++)b["$"+c[e]]=!0;for(c=0;c<a.length;c++)e=b.hasOwnProperty("$"+a[c].value),a[c].selected!==e&&(a[c].selected=e),e&&d&&(a[c].defaultSelected=!0)}else{c=""+uc(c);b=null;for(e=0;e<a.length;e++){if(a[e].value===c){a[e].selected=!0;d&&(a[e].defaultSelected=!0);return}null!==b||a[e].disabled||(b=a[e])}null!==b&&(b.selected=!0)}} function be(a,b){null!=b.dangerouslySetInnerHTML?x("91"):void 0;return n({},b,{value:void 0,defaultValue:void 0,children:""+a._wrapperState.initialValue})}function ce(a,b){var c=b.value;null==c&&(c=b.defaultValue,b=b.children,null!=b&&(null!=c?x("92"):void 0,Array.isArray(b)&&(1>=b.length?void 0:x("93"),b=b[0]),c=b),null==c&&(c=""));a._wrapperState={initialValue:uc(c)}} function de(a,b){var c=uc(b.value),d=uc(b.defaultValue);null!=c&&(c=""+c,c!==a.value&&(a.value=c),null==b.defaultValue&&a.defaultValue!==c&&(a.defaultValue=c));null!=d&&(a.defaultValue=""+d)}function ee(a){var b=a.textContent;b===a._wrapperState.initialValue&&(a.value=b)}var fe={html:"http://www.w3.org/1999/xhtml",mathml:"http://www.w3.org/1998/Math/MathML",svg:"http://www.w3.org/2000/svg"}; function ge(a){switch(a){case "svg":return"http://www.w3.org/2000/svg";case "math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function he(a,b){return null==a||"http://www.w3.org/1999/xhtml"===a?ge(b):"http://www.w3.org/2000/svg"===a&&"foreignObject"===b?"http://www.w3.org/1999/xhtml":a} var ie=void 0,je=function(a){return"undefined"!==typeof MSApp&&MSApp.execUnsafeLocalFunction?function(b,c,d,e){MSApp.execUnsafeLocalFunction(function(){return a(b,c,d,e)})}:a}(function(a,b){if(a.namespaceURI!==fe.svg||"innerHTML"in a)a.innerHTML=b;else{ie=ie||document.createElement("div");ie.innerHTML="<svg>"+b+"</svg>";for(b=ie.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}}); function ke(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b} var le={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0, floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},me=["Webkit","ms","Moz","O"];Object.keys(le).forEach(function(a){me.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);le[b]=le[a]})});function ne(a,b,c){return null==b||"boolean"===typeof b||""===b?"":c||"number"!==typeof b||0===b||le.hasOwnProperty(a)&&le[a]?(""+b).trim():b+"px"} function oe(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf("--"),e=ne(c,b[c],d);"float"===c&&(c="cssFloat");d?a.setProperty(c,e):a[c]=e}}var pe=n({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0}); function qe(a,b){b&&(pe[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML?x("137",a,""):void 0),null!=b.dangerouslySetInnerHTML&&(null!=b.children?x("60"):void 0,"object"===typeof b.dangerouslySetInnerHTML&&"__html"in b.dangerouslySetInnerHTML?void 0:x("61")),null!=b.style&&"object"!==typeof b.style?x("62",""):void 0)} function re(a,b){if(-1===a.indexOf("-"))return"string"===typeof b.is;switch(a){case "annotation-xml":case "color-profile":case "font-face":case "font-face-src":case "font-face-uri":case "font-face-format":case "font-face-name":case "missing-glyph":return!1;default:return!0}} function se(a,b){a=9===a.nodeType||11===a.nodeType?a:a.ownerDocument;var c=Id(a);b=sa[b];for(var d=0;d<b.length;d++){var e=b[d];if(!c.hasOwnProperty(e)||!c[e]){switch(e){case "scroll":Ed("scroll",a);break;case "focus":case "blur":Ed("focus",a);Ed("blur",a);c.blur=!0;c.focus=!0;break;case "cancel":case "close":Ob(e)&&Ed(e,a);break;case "invalid":case "submit":case "reset":break;default:-1===ab.indexOf(e)&&E(e,a)}c[e]=!0}}}function te(){}var ue=null,ve=null; function we(a,b){switch(a){case "button":case "input":case "select":case "textarea":return!!b.autoFocus}return!1}function xe(a,b){return"textarea"===a||"option"===a||"noscript"===a||"string"===typeof b.children||"number"===typeof b.children||"object"===typeof b.dangerouslySetInnerHTML&&null!==b.dangerouslySetInnerHTML&&null!=b.dangerouslySetInnerHTML.__html} var ye="function"===typeof setTimeout?setTimeout:void 0,ze="function"===typeof clearTimeout?clearTimeout:void 0,Ae=r.unstable_scheduleCallback,Be=r.unstable_cancelCallback; function Ce(a,b,c,d,e){a[Ga]=e;"input"===c&&"radio"===e.type&&null!=e.name&&xc(a,e);re(c,d);d=re(c,e);for(var f=0;f<b.length;f+=2){var g=b[f],h=b[f+1];"style"===g?oe(a,h):"dangerouslySetInnerHTML"===g?je(a,h):"children"===g?ke(a,h):tc(a,g,h,d)}switch(c){case "input":yc(a,e);break;case "textarea":de(a,e);break;case "select":b=a._wrapperState.wasMultiple,a._wrapperState.wasMultiple=!!e.multiple,c=e.value,null!=c?ae(a,!!e.multiple,c,!1):b!==!!e.multiple&&(null!=e.defaultValue?ae(a,!!e.multiple,e.defaultValue, !0):ae(a,!!e.multiple,e.multiple?[]:"",!1))}}function De(a){for(a=a.nextSibling;a&&1!==a.nodeType&&3!==a.nodeType;)a=a.nextSibling;return a}function Ee(a){for(a=a.firstChild;a&&1!==a.nodeType&&3!==a.nodeType;)a=a.nextSibling;return a}new Set;var Fe=[],Ge=-1;function F(a){0>Ge||(a.current=Fe[Ge],Fe[Ge]=null,Ge--)}function G(a,b){Ge++;Fe[Ge]=a.current;a.current=b}var He={},H={current:He},I={current:!1},Ie=He; function Je(a,b){var c=a.type.contextTypes;if(!c)return He;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}function J(a){a=a.childContextTypes;return null!==a&&void 0!==a}function Ke(a){F(I,a);F(H,a)}function Le(a){F(I,a);F(H,a)} function Me(a,b,c){H.current!==He?x("168"):void 0;G(H,b,a);G(I,c,a)}function Ne(a,b,c){var d=a.stateNode;a=b.childContextTypes;if("function"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)e in a?void 0:x("108",ic(b)||"Unknown",e);return n({},c,d)}function Oe(a){var b=a.stateNode;b=b&&b.__reactInternalMemoizedMergedChildContext||He;Ie=H.current;G(H,b,a);G(I,I.current,a);return!0} function Pe(a,b,c){var d=a.stateNode;d?void 0:x("169");c?(b=Ne(a,b,Ie),d.__reactInternalMemoizedMergedChildContext=b,F(I,a),F(H,a),G(H,b,a)):F(I,a);G(I,c,a)}var Qe=null,Re=null;function Se(a){return function(b){try{return a(b)}catch(c){}}} function Te(a){if("undefined"===typeof __REACT_DEVTOOLS_GLOBAL_HOOK__)return!1;var b=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(b.isDisabled||!b.supportsFiber)return!0;try{var c=b.inject(a);Qe=Se(function(a){return b.onCommitFiberRoot(c,a)});Re=Se(function(a){return b.onCommitFiberUnmount(c,a)})}catch(d){}return!0} function Ue(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.contextDependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.effectTag=0;this.lastEffect=this.firstEffect=this.nextEffect=null;this.childExpirationTime=this.expirationTime=0;this.alternate=null}function K(a,b,c,d){return new Ue(a,b,c,d)} function Ve(a){a=a.prototype;return!(!a||!a.isReactComponent)}function We(a){if("function"===typeof a)return Ve(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===cc)return 11;if(a===ec)return 14}return 2} function Xe(a,b){var c=a.alternate;null===c?(c=K(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.effectTag=0,c.nextEffect=null,c.firstEffect=null,c.lastEffect=null);c.childExpirationTime=a.childExpirationTime;c.expirationTime=a.expirationTime;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;c.contextDependencies=a.contextDependencies;c.sibling=a.sibling; c.index=a.index;c.ref=a.ref;return c} function Ye(a,b,c,d,e,f){var g=2;d=a;if("function"===typeof a)Ve(a)&&(g=1);else if("string"===typeof a)g=5;else a:switch(a){case Xb:return Ze(c.children,e,f,b);case bc:return $e(c,e|3,f,b);case Yb:return $e(c,e|2,f,b);case Zb:return a=K(12,c,b,e|4),a.elementType=Zb,a.type=Zb,a.expirationTime=f,a;case dc:return a=K(13,c,b,e),a.elementType=dc,a.type=dc,a.expirationTime=f,a;default:if("object"===typeof a&&null!==a)switch(a.$$typeof){case $b:g=10;break a;case ac:g=9;break a;case cc:g=11;break a;case ec:g= 14;break a;case fc:g=16;d=null;break a}x("130",null==a?a:typeof a,"")}b=K(g,c,b,e);b.elementType=a;b.type=d;b.expirationTime=f;return b}function Ze(a,b,c,d){a=K(7,a,d,b);a.expirationTime=c;return a}function $e(a,b,c,d){a=K(8,a,d,b);b=0===(b&1)?Yb:bc;a.elementType=b;a.type=b;a.expirationTime=c;return a}function af(a,b,c){a=K(6,a,null,b);a.expirationTime=c;return a} function bf(a,b,c){b=K(4,null!==a.children?a.children:[],a.key,b);b.expirationTime=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b}function cf(a,b){a.didError=!1;var c=a.earliestPendingTime;0===c?a.earliestPendingTime=a.latestPendingTime=b:c<b?a.earliestPendingTime=b:a.latestPendingTime>b&&(a.latestPendingTime=b);df(b,a)} function ef(a,b){a.didError=!1;if(0===b)a.earliestPendingTime=0,a.latestPendingTime=0,a.earliestSuspendedTime=0,a.latestSuspendedTime=0,a.latestPingedTime=0;else{b<a.latestPingedTime&&(a.latestPingedTime=0);var c=a.latestPendingTime;0!==c&&(c>b?a.earliestPendingTime=a.latestPendingTime=0:a.earliestPendingTime>b&&(a.earliestPendingTime=a.latestPendingTime));c=a.earliestSuspendedTime;0===c?cf(a,b):b<a.latestSuspendedTime?(a.earliestSuspendedTime=0,a.latestSuspendedTime=0,a.latestPingedTime=0,cf(a,b)): b>c&&cf(a,b)}df(0,a)}function ff(a,b){a.didError=!1;a.latestPingedTime>=b&&(a.latestPingedTime=0);var c=a.earliestPendingTime,d=a.latestPendingTime;c===b?a.earliestPendingTime=d===b?a.latestPendingTime=0:d:d===b&&(a.latestPendingTime=c);c=a.earliestSuspendedTime;d=a.latestSuspendedTime;0===c?a.earliestSuspendedTime=a.latestSuspendedTime=b:c<b?a.earliestSuspendedTime=b:d>b&&(a.latestSuspendedTime=b);df(b,a)} function gf(a,b){var c=a.earliestPendingTime;a=a.earliestSuspendedTime;c>b&&(b=c);a>b&&(b=a);return b}function df(a,b){var c=b.earliestSuspendedTime,d=b.latestSuspendedTime,e=b.earliestPendingTime,f=b.latestPingedTime;e=0!==e?e:f;0===e&&(0===a||d<a)&&(e=d);a=e;0!==a&&c>a&&(a=c);b.nextExpirationTimeToWorkOn=e;b.expirationTime=a}function L(a,b){if(a&&a.defaultProps){b=n({},b);a=a.defaultProps;for(var c in a)void 0===b[c]&&(b[c]=a[c])}return b} function hf(a){var b=a._result;switch(a._status){case 1:return b;case 2:throw b;case 0:throw b;default:a._status=0;b=a._ctor;b=b();b.then(function(b){0===a._status&&(b=b.default,a._status=1,a._result=b)},function(b){0===a._status&&(a._status=2,a._result=b)});switch(a._status){case 1:return a._result;case 2:throw a._result;}a._result=b;throw b;}}var jf=(new aa.Component).refs; function kf(a,b,c,d){b=a.memoizedState;c=c(d,b);c=null===c||void 0===c?b:n({},b,c);a.memoizedState=c;d=a.updateQueue;null!==d&&0===a.expirationTime&&(d.baseState=c)} var tf={isMounted:function(a){return(a=a._reactInternalFiber)?2===ed(a):!1},enqueueSetState:function(a,b,c){a=a._reactInternalFiber;var d=lf();d=mf(d,a);var e=nf(d);e.payload=b;void 0!==c&&null!==c&&(e.callback=c);of();pf(a,e);qf(a,d)},enqueueReplaceState:function(a,b,c){a=a._reactInternalFiber;var d=lf();d=mf(d,a);var e=nf(d);e.tag=rf;e.payload=b;void 0!==c&&null!==c&&(e.callback=c);of();pf(a,e);qf(a,d)},enqueueForceUpdate:function(a,b){a=a._reactInternalFiber;var c=lf();c=mf(c,a);var d=nf(c);d.tag= sf;void 0!==b&&null!==b&&(d.callback=b);of();pf(a,d);qf(a,c)}};function uf(a,b,c,d,e,f,g){a=a.stateNode;return"function"===typeof a.shouldComponentUpdate?a.shouldComponentUpdate(d,f,g):b.prototype&&b.prototype.isPureReactComponent?!dd(c,d)||!dd(e,f):!0} function vf(a,b,c){var d=!1,e=He;var f=b.contextType;"object"===typeof f&&null!==f?f=M(f):(e=J(b)?Ie:H.current,d=b.contextTypes,f=(d=null!==d&&void 0!==d)?Je(a,e):He);b=new b(c,f);a.memoizedState=null!==b.state&&void 0!==b.state?b.state:null;b.updater=tf;a.stateNode=b;b._reactInternalFiber=a;d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=e,a.__reactInternalMemoizedMaskedChildContext=f);return b} function wf(a,b,c,d){a=b.state;"function"===typeof b.componentWillReceiveProps&&b.componentWillReceiveProps(c,d);"function"===typeof b.UNSAFE_componentWillReceiveProps&&b.UNSAFE_componentWillReceiveProps(c,d);b.state!==a&&tf.enqueueReplaceState(b,b.state,null)} function xf(a,b,c,d){var e=a.stateNode;e.props=c;e.state=a.memoizedState;e.refs=jf;var f=b.contextType;"object"===typeof f&&null!==f?e.context=M(f):(f=J(b)?Ie:H.current,e.context=Je(a,f));f=a.updateQueue;null!==f&&(yf(a,f,c,e,d),e.state=a.memoizedState);f=b.getDerivedStateFromProps;"function"===typeof f&&(kf(a,b,f,c),e.state=a.memoizedState);"function"===typeof b.getDerivedStateFromProps||"function"===typeof e.getSnapshotBeforeUpdate||"function"!==typeof e.UNSAFE_componentWillMount&&"function"!== typeof e.componentWillMount||(b=e.state,"function"===typeof e.componentWillMount&&e.componentWillMount(),"function"===typeof e.UNSAFE_componentWillMount&&e.UNSAFE_componentWillMount(),b!==e.state&&tf.enqueueReplaceState(e,e.state,null),f=a.updateQueue,null!==f&&(yf(a,f,c,e,d),e.state=a.memoizedState));"function"===typeof e.componentDidMount&&(a.effectTag|=4)}var zf=Array.isArray; function Af(a,b,c){a=c.ref;if(null!==a&&"function"!==typeof a&&"object"!==typeof a){if(c._owner){c=c._owner;var d=void 0;c&&(1!==c.tag?x("309"):void 0,d=c.stateNode);d?void 0:x("147",a);var e=""+a;if(null!==b&&null!==b.ref&&"function"===typeof b.ref&&b.ref._stringRef===e)return b.ref;b=function(a){var b=d.refs;b===jf&&(b=d.refs={});null===a?delete b[e]:b[e]=a};b._stringRef=e;return b}"string"!==typeof a?x("284"):void 0;c._owner?void 0:x("290",a)}return a} function Bf(a,b){"textarea"!==a.type&&x("31","[object Object]"===Object.prototype.toString.call(b)?"object with keys {"+Object.keys(b).join(", ")+"}":b,"")} function Cf(a){function b(b,c){if(a){var d=b.lastEffect;null!==d?(d.nextEffect=c,b.lastEffect=c):b.firstEffect=b.lastEffect=c;c.nextEffect=null;c.effectTag=8}}function c(c,d){if(!a)return null;for(;null!==d;)b(c,d),d=d.sibling;return null}function d(a,b){for(a=new Map;null!==b;)null!==b.key?a.set(b.key,b):a.set(b.index,b),b=b.sibling;return a}function e(a,b,c){a=Xe(a,b,c);a.index=0;a.sibling=null;return a}function f(b,c,d){b.index=d;if(!a)return c;d=b.alternate;if(null!==d)return d=d.index,d<c?(b.effectTag= 2,c):d;b.effectTag=2;return c}function g(b){a&&null===b.alternate&&(b.effectTag=2);return b}function h(a,b,c,d){if(null===b||6!==b.tag)return b=af(c,a.mode,d),b.return=a,b;b=e(b,c,d);b.return=a;return b}function l(a,b,c,d){if(null!==b&&b.elementType===c.type)return d=e(b,c.props,d),d.ref=Af(a,b,c),d.return=a,d;d=Ye(c.type,c.key,c.props,null,a.mode,d);d.ref=Af(a,b,c);d.return=a;return d}function k(a,b,c,d){if(null===b||4!==b.tag||b.stateNode.containerInfo!==c.containerInfo||b.stateNode.implementation!== c.implementation)return b=bf(c,a.mode,d),b.return=a,b;b=e(b,c.children||[],d);b.return=a;return b}function m(a,b,c,d,f){if(null===b||7!==b.tag)return b=Ze(c,a.mode,d,f),b.return=a,b;b=e(b,c,d);b.return=a;return b}function p(a,b,c){if("string"===typeof b||"number"===typeof b)return b=af(""+b,a.mode,c),b.return=a,b;if("object"===typeof b&&null!==b){switch(b.$$typeof){case Vb:return c=Ye(b.type,b.key,b.props,null,a.mode,c),c.ref=Af(a,null,b),c.return=a,c;case Wb:return b=bf(b,a.mode,c),b.return=a,b}if(zf(b)|| hc(b))return b=Ze(b,a.mode,c,null),b.return=a,b;Bf(a,b)}return null}function t(a,b,c,d){var e=null!==b?b.key:null;if("string"===typeof c||"number"===typeof c)return null!==e?null:h(a,b,""+c,d);if("object"===typeof c&&null!==c){switch(c.$$typeof){case Vb:return c.key===e?c.type===Xb?m(a,b,c.props.children,d,e):l(a,b,c,d):null;case Wb:return c.key===e?k(a,b,c,d):null}if(zf(c)||hc(c))return null!==e?null:m(a,b,c,d,null);Bf(a,c)}return null}function A(a,b,c,d,e){if("string"===typeof d||"number"===typeof d)return a= a.get(c)||null,h(b,a,""+d,e);if("object"===typeof d&&null!==d){switch(d.$$typeof){case Vb:return a=a.get(null===d.key?c:d.key)||null,d.type===Xb?m(b,a,d.props.children,e,d.key):l(b,a,d,e);case Wb:return a=a.get(null===d.key?c:d.key)||null,k(b,a,d,e)}if(zf(d)||hc(d))return a=a.get(c)||null,m(b,a,d,e,null);Bf(b,d)}return null}function v(e,g,h,k){for(var l=null,m=null,q=g,u=g=0,B=null;null!==q&&u<h.length;u++){q.index>u?(B=q,q=null):B=q.sibling;var w=t(e,q,h[u],k);if(null===w){null===q&&(q=B);break}a&& q&&null===w.alternate&&b(e,q);g=f(w,g,u);null===m?l=w:m.sibling=w;m=w;q=B}if(u===h.length)return c(e,q),l;if(null===q){for(;u<h.length;u++)if(q=p(e,h[u],k))g=f(q,g,u),null===m?l=q:m.sibling=q,m=q;return l}for(q=d(e,q);u<h.length;u++)if(B=A(q,e,u,h[u],k))a&&null!==B.alternate&&q.delete(null===B.key?u:B.key),g=f(B,g,u),null===m?l=B:m.sibling=B,m=B;a&&q.forEach(function(a){return b(e,a)});return l}function R(e,g,h,k){var l=hc(h);"function"!==typeof l?x("150"):void 0;h=l.call(h);null==h?x("151"):void 0; for(var m=l=null,q=g,u=g=0,B=null,w=h.next();null!==q&&!w.done;u++,w=h.next()){q.index>u?(B=q,q=null):B=q.sibling;var v=t(e,q,w.value,k);if(null===v){q||(q=B);break}a&&q&&null===v.alternate&&b(e,q);g=f(v,g,u);null===m?l=v:m.sibling=v;m=v;q=B}if(w.done)return c(e,q),l;if(null===q){for(;!w.done;u++,w=h.next())w=p(e,w.value,k),null!==w&&(g=f(w,g,u),null===m?l=w:m.sibling=w,m=w);return l}for(q=d(e,q);!w.done;u++,w=h.next())w=A(q,e,u,w.value,k),null!==w&&(a&&null!==w.alternate&&q.delete(null===w.key?u: w.key),g=f(w,g,u),null===m?l=w:m.sibling=w,m=w);a&&q.forEach(function(a){return b(e,a)});return l}return function(a,d,f,h){var k="object"===typeof f&&null!==f&&f.type===Xb&&null===f.key;k&&(f=f.props.children);var l="object"===typeof f&&null!==f;if(l)switch(f.$$typeof){case Vb:a:{l=f.key;for(k=d;null!==k;){if(k.key===l)if(7===k.tag?f.type===Xb:k.elementType===f.type){c(a,k.sibling);d=e(k,f.type===Xb?f.props.children:f.props,h);d.ref=Af(a,k,f);d.return=a;a=d;break a}else{c(a,k);break}else b(a,k);k= k.sibling}f.type===Xb?(d=Ze(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=Ye(f.type,f.key,f.props,null,a.mode,h),h.ref=Af(a,d,f),h.return=a,a=h)}return g(a);case Wb:a:{for(k=f.key;null!==d;){if(d.key===k)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[],h);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=d.sibling}d=bf(f,a.mode,h);d.return=a;a=d}return g(a)}if("string"===typeof f||"number"===typeof f)return f= ""+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f,h),d.return=a,a=d):(c(a,d),d=af(f,a.mode,h),d.return=a,a=d),g(a);if(zf(f))return v(a,d,f,h);if(hc(f))return R(a,d,f,h);l&&Bf(a,f);if("undefined"===typeof f&&!k)switch(a.tag){case 1:case 0:h=a.type,x("152",h.displayName||h.name||"Component")}return c(a,d)}}var Df=Cf(!0),Ef=Cf(!1),Ff={},N={current:Ff},Gf={current:Ff},Hf={current:Ff};function If(a){a===Ff?x("174"):void 0;return a} function Jf(a,b){G(Hf,b,a);G(Gf,a,a);G(N,Ff,a);var c=b.nodeType;switch(c){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:he(null,"");break;default:c=8===c?b.parentNode:b,b=c.namespaceURI||null,c=c.tagName,b=he(b,c)}F(N,a);G(N,b,a)}function Kf(a){F(N,a);F(Gf,a);F(Hf,a)}function Lf(a){If(Hf.current);var b=If(N.current);var c=he(b,a.type);b!==c&&(G(Gf,a,a),G(N,c,a))}function Mf(a){Gf.current===a&&(F(N,a),F(Gf,a))} var Nf=0,Of=2,Pf=4,Qf=8,Rf=16,Sf=32,Tf=64,Uf=128,Vf=Tb.ReactCurrentDispatcher,Wf=0,Xf=null,O=null,P=null,Yf=null,Q=null,Zf=null,$f=0,ag=null,bg=0,cg=!1,dg=null,eg=0;function fg(){x("321")}function gg(a,b){if(null===b)return!1;for(var c=0;c<b.length&&c<a.length;c++)if(!bd(a[c],b[c]))return!1;return!0} function hg(a,b,c,d,e,f){Wf=f;Xf=b;P=null!==a?a.memoizedState:null;Vf.current=null===P?ig:jg;b=c(d,e);if(cg){do cg=!1,eg+=1,P=null!==a?a.memoizedState:null,Zf=Yf,ag=Q=O=null,Vf.current=jg,b=c(d,e);while(cg);dg=null;eg=0}Vf.current=kg;a=Xf;a.memoizedState=Yf;a.expirationTime=$f;a.updateQueue=ag;a.effectTag|=bg;a=null!==O&&null!==O.next;Wf=0;Zf=Q=Yf=P=O=Xf=null;$f=0;ag=null;bg=0;a?x("300"):void 0;return b}function lg(){Vf.current=kg;Wf=0;Zf=Q=Yf=P=O=Xf=null;$f=0;ag=null;bg=0;cg=!1;dg=null;eg=0} function mg(){var a={memoizedState:null,baseState:null,queue:null,baseUpdate:null,next:null};null===Q?Yf=Q=a:Q=Q.next=a;return Q}function ng(){if(null!==Zf)Q=Zf,Zf=Q.next,O=P,P=null!==O?O.next:null;else{null===P?x("310"):void 0;O=P;var a={memoizedState:O.memoizedState,baseState:O.baseState,queue:O.queue,baseUpdate:O.baseUpdate,next:null};Q=null===Q?Yf=a:Q.next=a;P=O.next}return Q}function og(a,b){return"function"===typeof b?b(a):b} function pg(a){var b=ng(),c=b.queue;null===c?x("311"):void 0;c.lastRenderedReducer=a;if(0<eg){var d=c.dispatch;if(null!==dg){var e=dg.get(c);if(void 0!==e){dg.delete(c);var f=b.memoizedState;do f=a(f,e.action),e=e.next;while(null!==e);bd(f,b.memoizedState)||(qg=!0);b.memoizedState=f;b.baseUpdate===c.last&&(b.baseState=f);c.lastRenderedState=f;return[f,d]}}return[b.memoizedState,d]}d=c.last;var g=b.baseUpdate;f=b.baseState;null!==g?(null!==d&&(d.next=null),d=g.next):d=null!==d?d.next:null;if(null!== d){var h=e=null,l=d,k=!1;do{var m=l.expirationTime;m<Wf?(k||(k=!0,h=g,e=f),m>$f&&($f=m)):f=l.eagerReducer===a?l.eagerState:a(f,l.action);g=l;l=l.next}while(null!==l&&l!==d);k||(h=g,e=f);bd(f,b.memoizedState)||(qg=!0);b.memoizedState=f;b.baseUpdate=h;b.baseState=e;c.lastRenderedState=f}return[b.memoizedState,c.dispatch]} function rg(a,b,c,d){a={tag:a,create:b,destroy:c,deps:d,next:null};null===ag?(ag={lastEffect:null},ag.lastEffect=a.next=a):(b=ag.lastEffect,null===b?ag.lastEffect=a.next=a:(c=b.next,b.next=a,a.next=c,ag.lastEffect=a));return a}function sg(a,b,c,d){var e=mg();bg|=a;e.memoizedState=rg(b,c,void 0,void 0===d?null:d)} function tg(a,b,c,d){var e=ng();d=void 0===d?null:d;var f=void 0;if(null!==O){var g=O.memoizedState;f=g.destroy;if(null!==d&&gg(d,g.deps)){rg(Nf,c,f,d);return}}bg|=a;e.memoizedState=rg(b,c,f,d)}function ug(a,b){if("function"===typeof b)return a=a(),b(a),function(){b(null)};if(null!==b&&void 0!==b)return a=a(),b.current=a,function(){b.current=null}}function vg(){} function wg(a,b,c){25>eg?void 0:x("301");var d=a.alternate;if(a===Xf||null!==d&&d===Xf)if(cg=!0,a={expirationTime:Wf,action:c,eagerReducer:null,eagerState:null,next:null},null===dg&&(dg=new Map),c=dg.get(b),void 0===c)dg.set(b,a);else{for(b=c;null!==b.next;)b=b.next;b.next=a}else{of();var e=lf();e=mf(e,a);var f={expirationTime:e,action:c,eagerReducer:null,eagerState:null,next:null},g=b.last;if(null===g)f.next=f;else{var h=g.next;null!==h&&(f.next=h);g.next=f}b.last=f;if(0===a.expirationTime&&(null=== d||0===d.expirationTime)&&(d=b.lastRenderedReducer,null!==d))try{var l=b.lastRenderedState,k=d(l,c);f.eagerReducer=d;f.eagerState=k;if(bd(k,l))return}catch(m){}finally{}qf(a,e)}} var kg={readContext:M,useCallback:fg,useContext:fg,useEffect:fg,useImperativeHandle:fg,useLayoutEffect:fg,useMemo:fg,useReducer:fg,useRef:fg,useState:fg,useDebugValue:fg},ig={readContext:M,useCallback:function(a,b){mg().memoizedState=[a,void 0===b?null:b];return a},useContext:M,useEffect:function(a,b){return sg(516,Uf|Tf,a,b)},useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return sg(4,Pf|Sf,ug.bind(null,b,a),c)},useLayoutEffect:function(a,b){return sg(4,Pf|Sf,a,b)}, useMemo:function(a,b){var c=mg();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=mg();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a=d.queue={last:null,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};a=a.dispatch=wg.bind(null,Xf,a);return[d.memoizedState,a]},useRef:function(a){var b=mg();a={current:a};return b.memoizedState=a},useState:function(a){var b=mg();"function"===typeof a&&(a=a());b.memoizedState=b.baseState=a;a=b.queue={last:null,dispatch:null, lastRenderedReducer:og,lastRenderedState:a};a=a.dispatch=wg.bind(null,Xf,a);return[b.memoizedState,a]},useDebugValue:vg},jg={readContext:M,useCallback:function(a,b){var c=ng();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&gg(b,d[1]))return d[0];c.memoizedState=[a,b];return a},useContext:M,useEffect:function(a,b){return tg(516,Uf|Tf,a,b)},useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return tg(4,Pf|Sf,ug.bind(null,b,a),c)},useLayoutEffect:function(a, b){return tg(4,Pf|Sf,a,b)},useMemo:function(a,b){var c=ng();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&gg(b,d[1]))return d[0];a=a();c.memoizedState=[a,b];return a},useReducer:pg,useRef:function(){return ng().memoizedState},useState:function(a){return pg(og,a)},useDebugValue:vg},xg=null,yg=null,zg=!1; function Ag(a,b){var c=K(5,null,null,0);c.elementType="DELETED";c.type="DELETED";c.stateNode=b;c.return=a;c.effectTag=8;null!==a.lastEffect?(a.lastEffect.nextEffect=c,a.lastEffect=c):a.firstEffect=a.lastEffect=c}function Bg(a,b){switch(a.tag){case 5:var c=a.type;b=1!==b.nodeType||c.toLowerCase()!==b.nodeName.toLowerCase()?null:b;return null!==b?(a.stateNode=b,!0):!1;case 6:return b=""===a.pendingProps||3!==b.nodeType?null:b,null!==b?(a.stateNode=b,!0):!1;case 13:return!1;default:return!1}} function Cg(a){if(zg){var b=yg;if(b){var c=b;if(!Bg(a,b)){b=De(c);if(!b||!Bg(a,b)){a.effectTag|=2;zg=!1;xg=a;return}Ag(xg,c)}xg=a;yg=Ee(b)}else a.effectTag|=2,zg=!1,xg=a}}function Dg(a){for(a=a.return;null!==a&&5!==a.tag&&3!==a.tag&&18!==a.tag;)a=a.return;xg=a}function Eg(a){if(a!==xg)return!1;if(!zg)return Dg(a),zg=!0,!1;var b=a.type;if(5!==a.tag||"head"!==b&&"body"!==b&&!xe(b,a.memoizedProps))for(b=yg;b;)Ag(a,b),b=De(b);Dg(a);yg=xg?De(a.stateNode):null;return!0}function Fg(){yg=xg=null;zg=!1} var Gg=Tb.ReactCurrentOwner,qg=!1;function S(a,b,c,d){b.child=null===a?Ef(b,null,c,d):Df(b,a.child,c,d)}function Hg(a,b,c,d,e){c=c.render;var f=b.ref;Ig(b,e);d=hg(a,b,c,d,f,e);if(null!==a&&!qg)return b.updateQueue=a.updateQueue,b.effectTag&=-517,a.expirationTime<=e&&(a.expirationTime=0),Jg(a,b,e);b.effectTag|=1;S(a,b,d,e);return b.child} function Kg(a,b,c,d,e,f){if(null===a){var g=c.type;if("function"===typeof g&&!Ve(g)&&void 0===g.defaultProps&&null===c.compare&&void 0===c.defaultProps)return b.tag=15,b.type=g,Lg(a,b,g,d,e,f);a=Ye(c.type,null,d,null,b.mode,f);a.ref=b.ref;a.return=b;return b.child=a}g=a.child;if(e<f&&(e=g.memoizedProps,c=c.compare,c=null!==c?c:dd,c(e,d)&&a.ref===b.ref))return Jg(a,b,f);b.effectTag|=1;a=Xe(g,d,f);a.ref=b.ref;a.return=b;return b.child=a} function Lg(a,b,c,d,e,f){return null!==a&&dd(a.memoizedProps,d)&&a.ref===b.ref&&(qg=!1,e<f)?Jg(a,b,f):Mg(a,b,c,d,f)}function Ng(a,b){var c=b.ref;if(null===a&&null!==c||null!==a&&a.ref!==c)b.effectTag|=128}function Mg(a,b,c,d,e){var f=J(c)?Ie:H.current;f=Je(b,f);Ig(b,e);c=hg(a,b,c,d,f,e);if(null!==a&&!qg)return b.updateQueue=a.updateQueue,b.effectTag&=-517,a.expirationTime<=e&&(a.expirationTime=0),Jg(a,b,e);b.effectTag|=1;S(a,b,c,e);return b.child} function Og(a,b,c,d,e){if(J(c)){var f=!0;Oe(b)}else f=!1;Ig(b,e);if(null===b.stateNode)null!==a&&(a.alternate=null,b.alternate=null,b.effectTag|=2),vf(b,c,d,e),xf(b,c,d,e),d=!0;else if(null===a){var g=b.stateNode,h=b.memoizedProps;g.props=h;var l=g.context,k=c.contextType;"object"===typeof k&&null!==k?k=M(k):(k=J(c)?Ie:H.current,k=Je(b,k));var m=c.getDerivedStateFromProps,p="function"===typeof m||"function"===typeof g.getSnapshotBeforeUpdate;p||"function"!==typeof g.UNSAFE_componentWillReceiveProps&& "function"!==typeof g.componentWillReceiveProps||(h!==d||l!==k)&&wf(b,g,d,k);Pg=!1;var t=b.memoizedState;l=g.state=t;var A=b.updateQueue;null!==A&&(yf(b,A,d,g,e),l=b.memoizedState);h!==d||t!==l||I.current||Pg?("function"===typeof m&&(kf(b,c,m,d),l=b.memoizedState),(h=Pg||uf(b,c,h,d,t,l,k))?(p||"function"!==typeof g.UNSAFE_componentWillMount&&"function"!==typeof g.componentWillMount||("function"===typeof g.componentWillMount&&g.componentWillMount(),"function"===typeof g.UNSAFE_componentWillMount&& g.UNSAFE_componentWillMount()),"function"===typeof g.componentDidMount&&(b.effectTag|=4)):("function"===typeof g.componentDidMount&&(b.effectTag|=4),b.memoizedProps=d,b.memoizedState=l),g.props=d,g.state=l,g.context=k,d=h):("function"===typeof g.componentDidMount&&(b.effectTag|=4),d=!1)}else g=b.stateNode,h=b.memoizedProps,g.props=b.type===b.elementType?h:L(b.type,h),l=g.context,k=c.contextType,"object"===typeof k&&null!==k?k=M(k):(k=J(c)?Ie:H.current,k=Je(b,k)),m=c.getDerivedStateFromProps,(p="function"=== typeof m||"function"===typeof g.getSnapshotBeforeUpdate)||"function"!==typeof g.UNSAFE_componentWillReceiveProps&&"function"!==typeof g.componentWillReceiveProps||(h!==d||l!==k)&&wf(b,g,d,k),Pg=!1,l=b.memoizedState,t=g.state=l,A=b.updateQueue,null!==A&&(yf(b,A,d,g,e),t=b.memoizedState),h!==d||l!==t||I.current||Pg?("function"===typeof m&&(kf(b,c,m,d),t=b.memoizedState),(m=Pg||uf(b,c,h,d,l,t,k))?(p||"function"!==typeof g.UNSAFE_componentWillUpdate&&"function"!==typeof g.componentWillUpdate||("function"=== typeof g.componentWillUpdate&&g.componentWillUpdate(d,t,k),"function"===typeof g.UNSAFE_componentWillUpdate&&g.UNSAFE_componentWillUpdate(d,t,k)),"function"===typeof g.componentDidUpdate&&(b.effectTag|=4),"function"===typeof g.getSnapshotBeforeUpdate&&(b.effectTag|=256)):("function"!==typeof g.componentDidUpdate||h===a.memoizedProps&&l===a.memoizedState||(b.effectTag|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&l===a.memoizedState||(b.effectTag|=256),b.memoizedProps=d,b.memoizedState= t),g.props=d,g.state=t,g.context=k,d=m):("function"!==typeof g.componentDidUpdate||h===a.memoizedProps&&l===a.memoizedState||(b.effectTag|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&l===a.memoizedState||(b.effectTag|=256),d=!1);return Qg(a,b,c,d,f,e)} function Qg(a,b,c,d,e,f){Ng(a,b);var g=0!==(b.effectTag&64);if(!d&&!g)return e&&Pe(b,c,!1),Jg(a,b,f);d=b.stateNode;Gg.current=b;var h=g&&"function"!==typeof c.getDerivedStateFromError?null:d.render();b.effectTag|=1;null!==a&&g?(b.child=Df(b,a.child,null,f),b.child=Df(b,null,h,f)):S(a,b,h,f);b.memoizedState=d.state;e&&Pe(b,c,!0);return b.child}function Rg(a){var b=a.stateNode;b.pendingContext?Me(a,b.pendingContext,b.pendingContext!==b.context):b.context&&Me(a,b.context,!1);Jf(a,b.containerInfo)} function Sg(a,b,c){var d=b.mode,e=b.pendingProps,f=b.memoizedState;if(0===(b.effectTag&64)){f=null;var g=!1}else f={timedOutAt:null!==f?f.timedOutAt:0},g=!0,b.effectTag&=-65;if(null===a)if(g){var h=e.fallback;a=Ze(null,d,0,null);0===(b.mode&1)&&(a.child=null!==b.memoizedState?b.child.child:b.child);d=Ze(h,d,c,null);a.sibling=d;c=a;c.return=d.return=b}else c=d=Ef(b,null,e.children,c);else null!==a.memoizedState?(d=a.child,h=d.sibling,g?(c=e.fallback,e=Xe(d,d.pendingProps,0),0===(b.mode&1)&&(g=null!== b.memoizedState?b.child.child:b.child,g!==d.child&&(e.child=g)),d=e.sibling=Xe(h,c,h.expirationTime),c=e,e.childExpirationTime=0,c.return=d.return=b):c=d=Df(b,d.child,e.children,c)):(h=a.child,g?(g=e.fallback,e=Ze(null,d,0,null),e.child=h,0===(b.mode&1)&&(e.child=null!==b.memoizedState?b.child.child:b.child),d=e.sibling=Ze(g,d,c,null),d.effectTag|=2,c=e,e.childExpirationTime=0,c.return=d.return=b):d=c=Df(b,h,e.children,c)),b.stateNode=a.stateNode;b.memoizedState=f;b.child=c;return d} function Jg(a,b,c){null!==a&&(b.contextDependencies=a.contextDependencies);if(b.childExpirationTime<c)return null;null!==a&&b.child!==a.child?x("153"):void 0;if(null!==b.child){a=b.child;c=Xe(a,a.pendingProps,a.expirationTime);b.child=c;for(c.return=b;null!==a.sibling;)a=a.sibling,c=c.sibling=Xe(a,a.pendingProps,a.expirationTime),c.return=b;c.sibling=null}return b.child} function Tg(a,b,c){var d=b.expirationTime;if(null!==a)if(a.memoizedProps!==b.pendingProps||I.current)qg=!0;else{if(d<c){qg=!1;switch(b.tag){case 3:Rg(b);Fg();break;case 5:Lf(b);break;case 1:J(b.type)&&Oe(b);break;case 4:Jf(b,b.stateNode.containerInfo);break;case 10:Ug(b,b.memoizedProps.value);break;case 13:if(null!==b.memoizedState){d=b.child.childExpirationTime;if(0!==d&&d>=c)return Sg(a,b,c);b=Jg(a,b,c);return null!==b?b.sibling:null}}return Jg(a,b,c)}}else qg=!1;b.expirationTime=0;switch(b.tag){case 2:d= b.elementType;null!==a&&(a.alternate=null,b.alternate=null,b.effectTag|=2);a=b.pendingProps;var e=Je(b,H.current);Ig(b,c);e=hg(null,b,d,a,e,c);b.effectTag|=1;if("object"===typeof e&&null!==e&&"function"===typeof e.render&&void 0===e.$$typeof){b.tag=1;lg();if(J(d)){var f=!0;Oe(b)}else f=!1;b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null;var g=d.getDerivedStateFromProps;"function"===typeof g&&kf(b,d,g,a);e.updater=tf;b.stateNode=e;e._reactInternalFiber=b;xf(b,d,a,c);b=Qg(null,b,d,!0,f, c)}else b.tag=0,S(null,b,e,c),b=b.child;return b;case 16:e=b.elementType;null!==a&&(a.alternate=null,b.alternate=null,b.effectTag|=2);f=b.pendingProps;a=hf(e);b.type=a;e=b.tag=We(a);f=L(a,f);g=void 0;switch(e){case 0:g=Mg(null,b,a,f,c);break;case 1:g=Og(null,b,a,f,c);break;case 11:g=Hg(null,b,a,f,c);break;case 14:g=Kg(null,b,a,L(a.type,f),d,c);break;default:x("306",a,"")}return g;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:L(d,e),Mg(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps, e=b.elementType===d?e:L(d,e),Og(a,b,d,e,c);case 3:Rg(b);d=b.updateQueue;null===d?x("282"):void 0;e=b.memoizedState;e=null!==e?e.element:null;yf(b,d,b.pendingProps,null,c);d=b.memoizedState.element;if(d===e)Fg(),b=Jg(a,b,c);else{e=b.stateNode;if(e=(null===a||null===a.child)&&e.hydrate)yg=Ee(b.stateNode.containerInfo),xg=b,e=zg=!0;e?(b.effectTag|=2,b.child=Ef(b,null,d,c)):(S(a,b,d,c),Fg());b=b.child}return b;case 5:return Lf(b),null===a&&Cg(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null, g=e.children,xe(d,e)?g=null:null!==f&&xe(d,f)&&(b.effectTag|=16),Ng(a,b),1!==c&&b.mode&1&&e.hidden?(b.expirationTime=b.childExpirationTime=1,b=null):(S(a,b,g,c),b=b.child),b;case 6:return null===a&&Cg(b),null;case 13:return Sg(a,b,c);case 4:return Jf(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Df(b,null,d,c):S(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:L(d,e),Hg(a,b,d,e,c);case 7:return S(a,b,b.pendingProps,c),b.child;case 8:return S(a,b,b.pendingProps.children, c),b.child;case 12:return S(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;g=b.memoizedProps;f=e.value;Ug(b,f);if(null!==g){var h=g.value;f=bd(h,f)?0:("function"===typeof d._calculateChangedBits?d._calculateChangedBits(h,f):1073741823)|0;if(0===f){if(g.children===e.children&&!I.current){b=Jg(a,b,c);break a}}else for(h=b.child,null!==h&&(h.return=b);null!==h;){var l=h.contextDependencies;if(null!==l){g=h.child;for(var k=l.first;null!==k;){if(k.context===d&&0!== (k.observedBits&f)){1===h.tag&&(k=nf(c),k.tag=sf,pf(h,k));h.expirationTime<c&&(h.expirationTime=c);k=h.alternate;null!==k&&k.expirationTime<c&&(k.expirationTime=c);k=c;for(var m=h.return;null!==m;){var p=m.alternate;if(m.childExpirationTime<k)m.childExpirationTime=k,null!==p&&p.childExpirationTime<k&&(p.childExpirationTime=k);else if(null!==p&&p.childExpirationTime<k)p.childExpirationTime=k;else break;m=m.return}l.expirationTime<c&&(l.expirationTime=c);break}k=k.next}}else g=10===h.tag?h.type===b.type? null:h.child:h.child;if(null!==g)g.return=h;else for(g=h;null!==g;){if(g===b){g=null;break}h=g.sibling;if(null!==h){h.return=g.return;g=h;break}g=g.return}h=g}}S(a,b,e.children,c);b=b.child}return b;case 9:return e=b.type,f=b.pendingProps,d=f.children,Ig(b,c),e=M(e,f.unstable_observedBits),d=d(e),b.effectTag|=1,S(a,b,d,c),b.child;case 14:return e=b.type,f=L(e,b.pendingProps),f=L(e.type,f),Kg(a,b,e,f,d,c);case 15:return Lg(a,b,b.type,b.pendingProps,d,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType=== d?e:L(d,e),null!==a&&(a.alternate=null,b.alternate=null,b.effectTag|=2),b.tag=1,J(d)?(a=!0,Oe(b)):a=!1,Ig(b,c),vf(b,d,e,c),xf(b,d,e,c),Qg(null,b,d,!0,a,c)}x("156")}var Vg={current:null},Wg=null,Xg=null,Yg=null;function Ug(a,b){var c=a.type._context;G(Vg,c._currentValue,a);c._currentValue=b}function Zg(a){var b=Vg.current;F(Vg,a);a.type._context._currentValue=b}function Ig(a,b){Wg=a;Yg=Xg=null;var c=a.contextDependencies;null!==c&&c.expirationTime>=b&&(qg=!0);a.contextDependencies=null} function M(a,b){if(Yg!==a&&!1!==b&&0!==b){if("number"!==typeof b||1073741823===b)Yg=a,b=1073741823;b={context:a,observedBits:b,next:null};null===Xg?(null===Wg?x("308"):void 0,Xg=b,Wg.contextDependencies={first:b,expirationTime:0}):Xg=Xg.next=b}return a._currentValue}var $g=0,rf=1,sf=2,ah=3,Pg=!1;function bh(a){return{baseState:a,firstUpdate:null,lastUpdate:null,firstCapturedUpdate:null,lastCapturedUpdate:null,firstEffect:null,lastEffect:null,firstCapturedEffect:null,lastCapturedEffect:null}} function ch(a){return{baseState:a.baseState,firstUpdate:a.firstUpdate,lastUpdate:a.lastUpdate,firstCapturedUpdate:null,lastCapturedUpdate:null,firstEffect:null,lastEffect:null,firstCapturedEffect:null,lastCapturedEffect:null}}function nf(a){return{expirationTime:a,tag:$g,payload:null,callback:null,next:null,nextEffect:null}}function dh(a,b){null===a.lastUpdate?a.firstUpdate=a.lastUpdate=b:(a.lastUpdate.next=b,a.lastUpdate=b)} function pf(a,b){var c=a.alternate;if(null===c){var d=a.updateQueue;var e=null;null===d&&(d=a.updateQueue=bh(a.memoizedState))}else d=a.updateQueue,e=c.updateQueue,null===d?null===e?(d=a.updateQueue=bh(a.memoizedState),e=c.updateQueue=bh(c.memoizedState)):d=a.updateQueue=ch(e):null===e&&(e=c.updateQueue=ch(d));null===e||d===e?dh(d,b):null===d.lastUpdate||null===e.lastUpdate?(dh(d,b),dh(e,b)):(dh(d,b),e.lastUpdate=b)} function eh(a,b){var c=a.updateQueue;c=null===c?a.updateQueue=bh(a.memoizedState):fh(a,c);null===c.lastCapturedUpdate?c.firstCapturedUpdate=c.lastCapturedUpdate=b:(c.lastCapturedUpdate.next=b,c.lastCapturedUpdate=b)}function fh(a,b){var c=a.alternate;null!==c&&b===c.updateQueue&&(b=a.updateQueue=ch(b));return b} function gh(a,b,c,d,e,f){switch(c.tag){case rf:return a=c.payload,"function"===typeof a?a.call(f,d,e):a;case ah:a.effectTag=a.effectTag&-2049|64;case $g:a=c.payload;e="function"===typeof a?a.call(f,d,e):a;if(null===e||void 0===e)break;return n({},d,e);case sf:Pg=!0}return d} function yf(a,b,c,d,e){Pg=!1;b=fh(a,b);for(var f=b.baseState,g=null,h=0,l=b.firstUpdate,k=f;null!==l;){var m=l.expirationTime;m<e?(null===g&&(g=l,f=k),h<m&&(h=m)):(k=gh(a,b,l,k,c,d),null!==l.callback&&(a.effectTag|=32,l.nextEffect=null,null===b.lastEffect?b.firstEffect=b.lastEffect=l:(b.lastEffect.nextEffect=l,b.lastEffect=l)));l=l.next}m=null;for(l=b.firstCapturedUpdate;null!==l;){var p=l.expirationTime;p<e?(null===m&&(m=l,null===g&&(f=k)),h<p&&(h=p)):(k=gh(a,b,l,k,c,d),null!==l.callback&&(a.effectTag|= 32,l.nextEffect=null,null===b.lastCapturedEffect?b.firstCapturedEffect=b.lastCapturedEffect=l:(b.lastCapturedEffect.nextEffect=l,b.lastCapturedEffect=l)));l=l.next}null===g&&(b.lastUpdate=null);null===m?b.lastCapturedUpdate=null:a.effectTag|=32;null===g&&null===m&&(f=k);b.baseState=f;b.firstUpdate=g;b.firstCapturedUpdate=m;a.expirationTime=h;a.memoizedState=k} function hh(a,b,c){null!==b.firstCapturedUpdate&&(null!==b.lastUpdate&&(b.lastUpdate.next=b.firstCapturedUpdate,b.lastUpdate=b.lastCapturedUpdate),b.firstCapturedUpdate=b.lastCapturedUpdate=null);ih(b.firstEffect,c);b.firstEffect=b.lastEffect=null;ih(b.firstCapturedEffect,c);b.firstCapturedEffect=b.lastCapturedEffect=null}function ih(a,b){for(;null!==a;){var c=a.callback;if(null!==c){a.callback=null;var d=b;"function"!==typeof c?x("191",c):void 0;c.call(d)}a=a.nextEffect}} function jh(a,b){return{value:a,source:b,stack:jc(b)}}function kh(a){a.effectTag|=4}var lh=void 0,mh=void 0,nh=void 0,oh=void 0;lh=function(a,b){for(var c=b.child;null!==c;){if(5===c.tag||6===c.tag)a.appendChild(c.stateNode);else if(4!==c.tag&&null!==c.child){c.child.return=c;c=c.child;continue}if(c===b)break;for(;null===c.sibling;){if(null===c.return||c.return===b)return;c=c.return}c.sibling.return=c.return;c=c.sibling}};mh=function(){}; nh=function(a,b,c,d,e){var f=a.memoizedProps;if(f!==d){var g=b.stateNode;If(N.current);a=null;switch(c){case "input":f=vc(g,f);d=vc(g,d);a=[];break;case "option":f=$d(g,f);d=$d(g,d);a=[];break;case "select":f=n({},f,{value:void 0});d=n({},d,{value:void 0});a=[];break;case "textarea":f=be(g,f);d=be(g,d);a=[];break;default:"function"!==typeof f.onClick&&"function"===typeof d.onClick&&(g.onclick=te)}qe(c,d);g=c=void 0;var h=null;for(c in f)if(!d.hasOwnProperty(c)&&f.hasOwnProperty(c)&&null!=f[c])if("style"=== c){var l=f[c];for(g in l)l.hasOwnProperty(g)&&(h||(h={}),h[g]="")}else"dangerouslySetInnerHTML"!==c&&"children"!==c&&"suppressContentEditableWarning"!==c&&"suppressHydrationWarning"!==c&&"autoFocus"!==c&&(ra.hasOwnProperty(c)?a||(a=[]):(a=a||[]).push(c,null));for(c in d){var k=d[c];l=null!=f?f[c]:void 0;if(d.hasOwnProperty(c)&&k!==l&&(null!=k||null!=l))if("style"===c)if(l){for(g in l)!l.hasOwnProperty(g)||k&&k.hasOwnProperty(g)||(h||(h={}),h[g]="");for(g in k)k.hasOwnProperty(g)&&l[g]!==k[g]&&(h|| (h={}),h[g]=k[g])}else h||(a||(a=[]),a.push(c,h)),h=k;else"dangerouslySetInnerHTML"===c?(k=k?k.__html:void 0,l=l?l.__html:void 0,null!=k&&l!==k&&(a=a||[]).push(c,""+k)):"children"===c?l===k||"string"!==typeof k&&"number"!==typeof k||(a=a||[]).push(c,""+k):"suppressContentEditableWarning"!==c&&"suppressHydrationWarning"!==c&&(ra.hasOwnProperty(c)?(null!=k&&se(e,c),a||l===k||(a=[])):(a=a||[]).push(c,k))}h&&(a=a||[]).push("style",h);e=a;(b.updateQueue=e)&&kh(b)}};oh=function(a,b,c,d){c!==d&&kh(b)}; var ph="function"===typeof WeakSet?WeakSet:Set;function qh(a,b){var c=b.source,d=b.stack;null===d&&null!==c&&(d=jc(c));null!==c&&ic(c.type);b=b.value;null!==a&&1===a.tag&&ic(a.type);try{console.error(b)}catch(e){setTimeout(function(){throw e;})}}function rh(a){var b=a.ref;if(null!==b)if("function"===typeof b)try{b(null)}catch(c){sh(a,c)}else b.current=null} function th(a,b,c){c=c.updateQueue;c=null!==c?c.lastEffect:null;if(null!==c){var d=c=c.next;do{if((d.tag&a)!==Nf){var e=d.destroy;d.destroy=void 0;void 0!==e&&e()}(d.tag&b)!==Nf&&(e=d.create,d.destroy=e());d=d.next}while(d!==c)}} function uh(a,b){for(var c=a;;){if(5===c.tag){var d=c.stateNode;if(b)d.style.display="none";else{d=c.stateNode;var e=c.memoizedProps.style;e=void 0!==e&&null!==e&&e.hasOwnProperty("display")?e.display:null;d.style.display=ne("display",e)}}else if(6===c.tag)c.stateNode.nodeValue=b?"":c.memoizedProps;else if(13===c.tag&&null!==c.memoizedState){d=c.child.sibling;d.return=c;c=d;continue}else if(null!==c.child){c.child.return=c;c=c.child;continue}if(c===a)break;for(;null===c.sibling;){if(null===c.return|| c.return===a)return;c=c.return}c.sibling.return=c.return;c=c.sibling}} function vh(a){"function"===typeof Re&&Re(a);switch(a.tag){case 0:case 11:case 14:case 15:var b=a.updateQueue;if(null!==b&&(b=b.lastEffect,null!==b)){var c=b=b.next;do{var d=c.destroy;if(void 0!==d){var e=a;try{d()}catch(f){sh(e,f)}}c=c.next}while(c!==b)}break;case 1:rh(a);b=a.stateNode;if("function"===typeof b.componentWillUnmount)try{b.props=a.memoizedProps,b.state=a.memoizedState,b.componentWillUnmount()}catch(f){sh(a,f)}break;case 5:rh(a);break;case 4:wh(a)}} function xh(a){return 5===a.tag||3===a.tag||4===a.tag} function yh(a){a:{for(var b=a.return;null!==b;){if(xh(b)){var c=b;break a}b=b.return}x("160");c=void 0}var d=b=void 0;switch(c.tag){case 5:b=c.stateNode;d=!1;break;case 3:b=c.stateNode.containerInfo;d=!0;break;case 4:b=c.stateNode.containerInfo;d=!0;break;default:x("161")}c.effectTag&16&&(ke(b,""),c.effectTag&=-17);a:b:for(c=a;;){for(;null===c.sibling;){if(null===c.return||xh(c.return)){c=null;break a}c=c.return}c.sibling.return=c.return;for(c=c.sibling;5!==c.tag&&6!==c.tag&&18!==c.tag;){if(c.effectTag& 2)continue b;if(null===c.child||4===c.tag)continue b;else c.child.return=c,c=c.child}if(!(c.effectTag&2)){c=c.stateNode;break a}}for(var e=a;;){if(5===e.tag||6===e.tag)if(c)if(d){var f=b,g=e.stateNode,h=c;8===f.nodeType?f.parentNode.insertBefore(g,h):f.insertBefore(g,h)}else b.insertBefore(e.stateNode,c);else d?(g=b,h=e.stateNode,8===g.nodeType?(f=g.parentNode,f.insertBefore(h,g)):(f=g,f.appendChild(h)),g=g._reactRootContainer,null!==g&&void 0!==g||null!==f.onclick||(f.onclick=te)):b.appendChild(e.stateNode); else if(4!==e.tag&&null!==e.child){e.child.return=e;e=e.child;continue}if(e===a)break;for(;null===e.sibling;){if(null===e.return||e.return===a)return;e=e.return}e.sibling.return=e.return;e=e.sibling}} function wh(a){for(var b=a,c=!1,d=void 0,e=void 0;;){if(!c){c=b.return;a:for(;;){null===c?x("160"):void 0;switch(c.tag){case 5:d=c.stateNode;e=!1;break a;case 3:d=c.stateNode.containerInfo;e=!0;break a;case 4:d=c.stateNode.containerInfo;e=!0;break a}c=c.return}c=!0}if(5===b.tag||6===b.tag){a:for(var f=b,g=f;;)if(vh(g),null!==g.child&&4!==g.tag)g.child.return=g,g=g.child;else{if(g===f)break;for(;null===g.sibling;){if(null===g.return||g.return===f)break a;g=g.return}g.sibling.return=g.return;g=g.sibling}e? (f=d,g=b.stateNode,8===f.nodeType?f.parentNode.removeChild(g):f.removeChild(g)):d.removeChild(b.stateNode)}else if(4===b.tag){if(null!==b.child){d=b.stateNode.containerInfo;e=!0;b.child.return=b;b=b.child;continue}}else if(vh(b),null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return;b=b.return;4===b.tag&&(c=!1)}b.sibling.return=b.return;b=b.sibling}} function zh(a,b){switch(b.tag){case 0:case 11:case 14:case 15:th(Pf,Qf,b);break;case 1:break;case 5:var c=b.stateNode;if(null!=c){var d=b.memoizedProps;a=null!==a?a.memoizedProps:d;var e=b.type,f=b.updateQueue;b.updateQueue=null;null!==f&&Ce(c,f,e,a,d,b)}break;case 6:null===b.stateNode?x("162"):void 0;b.stateNode.nodeValue=b.memoizedProps;break;case 3:break;case 12:break;case 13:c=b.memoizedState;d=void 0;a=b;null===c?d=!1:(d=!0,a=b.child,0===c.timedOutAt&&(c.timedOutAt=lf()));null!==a&&uh(a,d);c= b.updateQueue;if(null!==c){b.updateQueue=null;var g=b.stateNode;null===g&&(g=b.stateNode=new ph);c.forEach(function(a){var c=Ah.bind(null,b,a);g.has(a)||(g.add(a),a.then(c,c))})}break;case 17:break;default:x("163")}}var Bh="function"===typeof WeakMap?WeakMap:Map;function Ch(a,b,c){c=nf(c);c.tag=ah;c.payload={element:null};var d=b.value;c.callback=function(){Dh(d);qh(a,b)};return c} function Eh(a,b,c){c=nf(c);c.tag=ah;var d=a.type.getDerivedStateFromError;if("function"===typeof d){var e=b.value;c.payload=function(){return d(e)}}var f=a.stateNode;null!==f&&"function"===typeof f.componentDidCatch&&(c.callback=function(){"function"!==typeof d&&(null===Fh?Fh=new Set([this]):Fh.add(this));var c=b.value,e=b.stack;qh(a,b);this.componentDidCatch(c,{componentStack:null!==e?e:""})});return c} function Gh(a){switch(a.tag){case 1:J(a.type)&&Ke(a);var b=a.effectTag;return b&2048?(a.effectTag=b&-2049|64,a):null;case 3:return Kf(a),Le(a),b=a.effectTag,0!==(b&64)?x("285"):void 0,a.effectTag=b&-2049|64,a;case 5:return Mf(a),null;case 13:return b=a.effectTag,b&2048?(a.effectTag=b&-2049|64,a):null;case 18:return null;case 4:return Kf(a),null;case 10:return Zg(a),null;default:return null}} var Hh=Tb.ReactCurrentDispatcher,Ih=Tb.ReactCurrentOwner,Jh=1073741822,Kh=!1,T=null,Lh=null,U=0,Mh=-1,Nh=!1,V=null,Oh=!1,Ph=null,Qh=null,Rh=null,Fh=null;function Sh(){if(null!==T)for(var a=T.return;null!==a;){var b=a;switch(b.tag){case 1:var c=b.type.childContextTypes;null!==c&&void 0!==c&&Ke(b);break;case 3:Kf(b);Le(b);break;case 5:Mf(b);break;case 4:Kf(b);break;case 10:Zg(b)}a=a.return}Lh=null;U=0;Mh=-1;Nh=!1;T=null} function Th(){for(;null!==V;){var a=V.effectTag;a&16&&ke(V.stateNode,"");if(a&128){var b=V.alternate;null!==b&&(b=b.ref,null!==b&&("function"===typeof b?b(null):b.current=null))}switch(a&14){case 2:yh(V);V.effectTag&=-3;break;case 6:yh(V);V.effectTag&=-3;zh(V.alternate,V);break;case 4:zh(V.alternate,V);break;case 8:a=V,wh(a),a.return=null,a.child=null,a.memoizedState=null,a.updateQueue=null,a=a.alternate,null!==a&&(a.return=null,a.child=null,a.memoizedState=null,a.updateQueue=null)}V=V.nextEffect}} function Uh(){for(;null!==V;){if(V.effectTag&256)a:{var a=V.alternate,b=V;switch(b.tag){case 0:case 11:case 15:th(Of,Nf,b);break a;case 1:if(b.effectTag&256&&null!==a){var c=a.memoizedProps,d=a.memoizedState;a=b.stateNode;b=a.getSnapshotBeforeUpdate(b.elementType===b.type?c:L(b.type,c),d);a.__reactInternalSnapshotBeforeUpdate=b}break a;case 3:case 5:case 6:case 4:case 17:break a;default:x("163")}}V=V.nextEffect}} function Vh(a,b){for(;null!==V;){var c=V.effectTag;if(c&36){var d=V.alternate,e=V,f=b;switch(e.tag){case 0:case 11:case 15:th(Rf,Sf,e);break;case 1:var g=e.stateNode;if(e.effectTag&4)if(null===d)g.componentDidMount();else{var h=e.elementType===e.type?d.memoizedProps:L(e.type,d.memoizedProps);g.componentDidUpdate(h,d.memoizedState,g.__reactInternalSnapshotBeforeUpdate)}d=e.updateQueue;null!==d&&hh(e,d,g,f);break;case 3:d=e.updateQueue;if(null!==d){g=null;if(null!==e.child)switch(e.child.tag){case 5:g= e.child.stateNode;break;case 1:g=e.child.stateNode}hh(e,d,g,f)}break;case 5:f=e.stateNode;null===d&&e.effectTag&4&&we(e.type,e.memoizedProps)&&f.focus();break;case 6:break;case 4:break;case 12:break;case 13:break;case 17:break;default:x("163")}}c&128&&(e=V.ref,null!==e&&(f=V.stateNode,"function"===typeof e?e(f):e.current=f));c&512&&(Ph=a);V=V.nextEffect}} function Wh(a,b){Rh=Qh=Ph=null;var c=W;W=!0;do{if(b.effectTag&512){var d=!1,e=void 0;try{var f=b;th(Uf,Nf,f);th(Nf,Tf,f)}catch(g){d=!0,e=g}d&&sh(b,e)}b=b.nextEffect}while(null!==b);W=c;c=a.expirationTime;0!==c&&Xh(a,c);X||W||Yh(1073741823,!1)}function of(){null!==Qh&&Be(Qh);null!==Rh&&Rh()} function Zh(a,b){Oh=Kh=!0;a.current===b?x("177"):void 0;var c=a.pendingCommitExpirationTime;0===c?x("261"):void 0;a.pendingCommitExpirationTime=0;var d=b.expirationTime,e=b.childExpirationTime;ef(a,e>d?e:d);Ih.current=null;d=void 0;1<b.effectTag?null!==b.lastEffect?(b.lastEffect.nextEffect=b,d=b.firstEffect):d=b:d=b.firstEffect;ue=Bd;ve=Pd();Bd=!1;for(V=d;null!==V;){e=!1;var f=void 0;try{Uh()}catch(h){e=!0,f=h}e&&(null===V?x("178"):void 0,sh(V,f),null!==V&&(V=V.nextEffect))}for(V=d;null!==V;){e=!1; f=void 0;try{Th()}catch(h){e=!0,f=h}e&&(null===V?x("178"):void 0,sh(V,f),null!==V&&(V=V.nextEffect))}Qd(ve);ve=null;Bd=!!ue;ue=null;a.current=b;for(V=d;null!==V;){e=!1;f=void 0;try{Vh(a,c)}catch(h){e=!0,f=h}e&&(null===V?x("178"):void 0,sh(V,f),null!==V&&(V=V.nextEffect))}if(null!==d&&null!==Ph){var g=Wh.bind(null,a,d);Qh=r.unstable_runWithPriority(r.unstable_NormalPriority,function(){return Ae(g)});Rh=g}Kh=Oh=!1;"function"===typeof Qe&&Qe(b.stateNode);c=b.expirationTime;b=b.childExpirationTime;b= b>c?b:c;0===b&&(Fh=null);$h(a,b)} function ai(a){for(;;){var b=a.alternate,c=a.return,d=a.sibling;if(0===(a.effectTag&1024)){T=a;a:{var e=b;b=a;var f=U;var g=b.pendingProps;switch(b.tag){case 2:break;case 16:break;case 15:case 0:break;case 1:J(b.type)&&Ke(b);break;case 3:Kf(b);Le(b);g=b.stateNode;g.pendingContext&&(g.context=g.pendingContext,g.pendingContext=null);if(null===e||null===e.child)Eg(b),b.effectTag&=-3;mh(b);break;case 5:Mf(b);var h=If(Hf.current);f=b.type;if(null!==e&&null!=b.stateNode)nh(e,b,f,g,h),e.ref!==b.ref&&(b.effectTag|= 128);else if(g){var l=If(N.current);if(Eg(b)){g=b;e=g.stateNode;var k=g.type,m=g.memoizedProps,p=h;e[Fa]=g;e[Ga]=m;f=void 0;h=k;switch(h){case "iframe":case "object":E("load",e);break;case "video":case "audio":for(k=0;k<ab.length;k++)E(ab[k],e);break;case "source":E("error",e);break;case "img":case "image":case "link":E("error",e);E("load",e);break;case "form":E("reset",e);E("submit",e);break;case "details":E("toggle",e);break;case "input":wc(e,m);E("invalid",e);se(p,"onChange");break;case "select":e._wrapperState= {wasMultiple:!!m.multiple};E("invalid",e);se(p,"onChange");break;case "textarea":ce(e,m),E("invalid",e),se(p,"onChange")}qe(h,m);k=null;for(f in m)m.hasOwnProperty(f)&&(l=m[f],"children"===f?"string"===typeof l?e.textContent!==l&&(k=["children",l]):"number"===typeof l&&e.textContent!==""+l&&(k=["children",""+l]):ra.hasOwnProperty(f)&&null!=l&&se(p,f));switch(h){case "input":Rb(e);Ac(e,m,!0);break;case "textarea":Rb(e);ee(e,m);break;case "select":case "option":break;default:"function"===typeof m.onClick&& (e.onclick=te)}f=k;g.updateQueue=f;g=null!==f?!0:!1;g&&kh(b)}else{m=b;p=f;e=g;k=9===h.nodeType?h:h.ownerDocument;l===fe.html&&(l=ge(p));l===fe.html?"script"===p?(e=k.createElement("div"),e.innerHTML="<script>\x3c/script>",k=e.removeChild(e.firstChild)):"string"===typeof e.is?k=k.createElement(p,{is:e.is}):(k=k.createElement(p),"select"===p&&(p=k,e.multiple?p.multiple=!0:e.size&&(p.size=e.size))):k=k.createElementNS(l,p);e=k;e[Fa]=m;e[Ga]=g;lh(e,b,!1,!1);p=e;k=f;m=g;var t=h,A=re(k,m);switch(k){case "iframe":case "object":E("load", p);h=m;break;case "video":case "audio":for(h=0;h<ab.length;h++)E(ab[h],p);h=m;break;case "source":E("error",p);h=m;break;case "img":case "image":case "link":E("error",p);E("load",p);h=m;break;case "form":E("reset",p);E("submit",p);h=m;break;case "details":E("toggle",p);h=m;break;case "input":wc(p,m);h=vc(p,m);E("invalid",p);se(t,"onChange");break;case "option":h=$d(p,m);break;case "select":p._wrapperState={wasMultiple:!!m.multiple};h=n({},m,{value:void 0});E("invalid",p);se(t,"onChange");break;case "textarea":ce(p, m);h=be(p,m);E("invalid",p);se(t,"onChange");break;default:h=m}qe(k,h);l=void 0;var v=k,R=p,u=h;for(l in u)if(u.hasOwnProperty(l)){var q=u[l];"style"===l?oe(R,q):"dangerouslySetInnerHTML"===l?(q=q?q.__html:void 0,null!=q&&je(R,q)):"children"===l?"string"===typeof q?("textarea"!==v||""!==q)&&ke(R,q):"number"===typeof q&&ke(R,""+q):"suppressContentEditableWarning"!==l&&"suppressHydrationWarning"!==l&&"autoFocus"!==l&&(ra.hasOwnProperty(l)?null!=q&&se(t,l):null!=q&&tc(R,l,q,A))}switch(k){case "input":Rb(p); Ac(p,m,!1);break;case "textarea":Rb(p);ee(p,m);break;case "option":null!=m.value&&p.setAttribute("value",""+uc(m.value));break;case "select":h=p;h.multiple=!!m.multiple;p=m.value;null!=p?ae(h,!!m.multiple,p,!1):null!=m.defaultValue&&ae(h,!!m.multiple,m.defaultValue,!0);break;default:"function"===typeof h.onClick&&(p.onclick=te)}(g=we(f,g))&&kh(b);b.stateNode=e}null!==b.ref&&(b.effectTag|=128)}else null===b.stateNode?x("166"):void 0;break;case 6:e&&null!=b.stateNode?oh(e,b,e.memoizedProps,g):("string"!== typeof g&&(null===b.stateNode?x("166"):void 0),e=If(Hf.current),If(N.current),Eg(b)?(g=b,f=g.stateNode,e=g.memoizedProps,f[Fa]=g,(g=f.nodeValue!==e)&&kh(b)):(f=b,g=(9===e.nodeType?e:e.ownerDocument).createTextNode(g),g[Fa]=b,f.stateNode=g));break;case 11:break;case 13:g=b.memoizedState;if(0!==(b.effectTag&64)){b.expirationTime=f;T=b;break a}g=null!==g;f=null!==e&&null!==e.memoizedState;null!==e&&!g&&f&&(e=e.child.sibling,null!==e&&(h=b.firstEffect,null!==h?(b.firstEffect=e,e.nextEffect=h):(b.firstEffect= b.lastEffect=e,e.nextEffect=null),e.effectTag=8));if(g||f)b.effectTag|=4;break;case 7:break;case 8:break;case 12:break;case 4:Kf(b);mh(b);break;case 10:Zg(b);break;case 9:break;case 14:break;case 17:J(b.type)&&Ke(b);break;case 18:break;default:x("156")}T=null}b=a;if(1===U||1!==b.childExpirationTime){g=0;for(f=b.child;null!==f;)e=f.expirationTime,h=f.childExpirationTime,e>g&&(g=e),h>g&&(g=h),f=f.sibling;b.childExpirationTime=g}if(null!==T)return T;null!==c&&0===(c.effectTag&1024)&&(null===c.firstEffect&& (c.firstEffect=a.firstEffect),null!==a.lastEffect&&(null!==c.lastEffect&&(c.lastEffect.nextEffect=a.firstEffect),c.lastEffect=a.lastEffect),1<a.effectTag&&(null!==c.lastEffect?c.lastEffect.nextEffect=a:c.firstEffect=a,c.lastEffect=a))}else{a=Gh(a,U);if(null!==a)return a.effectTag&=1023,a;null!==c&&(c.firstEffect=c.lastEffect=null,c.effectTag|=1024)}if(null!==d)return d;if(null!==c)a=c;else break}return null} function bi(a){var b=Tg(a.alternate,a,U);a.memoizedProps=a.pendingProps;null===b&&(b=ai(a));Ih.current=null;return b} function ci(a,b){Kh?x("243"):void 0;of();Kh=!0;var c=Hh.current;Hh.current=kg;var d=a.nextExpirationTimeToWorkOn;if(d!==U||a!==Lh||null===T)Sh(),Lh=a,U=d,T=Xe(Lh.current,null,U),a.pendingCommitExpirationTime=0;var e=!1;do{try{if(b)for(;null!==T&&!di();)T=bi(T);else for(;null!==T;)T=bi(T)}catch(u){if(Yg=Xg=Wg=null,lg(),null===T)e=!0,Dh(u);else{null===T?x("271"):void 0;var f=T,g=f.return;if(null===g)e=!0,Dh(u);else{a:{var h=a,l=g,k=f,m=u;g=U;k.effectTag|=1024;k.firstEffect=k.lastEffect=null;if(null!== m&&"object"===typeof m&&"function"===typeof m.then){var p=m;m=l;var t=-1,A=-1;do{if(13===m.tag){var v=m.alternate;if(null!==v&&(v=v.memoizedState,null!==v)){A=10*(1073741822-v.timedOutAt);break}v=m.pendingProps.maxDuration;if("number"===typeof v)if(0>=v)t=0;else if(-1===t||v<t)t=v}m=m.return}while(null!==m);m=l;do{if(v=13===m.tag)v=void 0===m.memoizedProps.fallback?!1:null===m.memoizedState;if(v){l=m.updateQueue;null===l?(l=new Set,l.add(p),m.updateQueue=l):l.add(p);if(0===(m.mode&1)){m.effectTag|= 64;k.effectTag&=-1957;1===k.tag&&(null===k.alternate?k.tag=17:(g=nf(1073741823),g.tag=sf,pf(k,g)));k.expirationTime=1073741823;break a}k=h;l=g;var R=k.pingCache;null===R?(R=k.pingCache=new Bh,v=new Set,R.set(p,v)):(v=R.get(p),void 0===v&&(v=new Set,R.set(p,v)));v.has(l)||(v.add(l),k=ei.bind(null,k,p,l),p.then(k,k));-1===t?h=1073741823:(-1===A&&(A=10*(1073741822-gf(h,g))-5E3),h=A+t);0<=h&&Mh<h&&(Mh=h);m.effectTag|=2048;m.expirationTime=g;break a}m=m.return}while(null!==m);m=Error((ic(k.type)||"A React component")+ " suspended while rendering, but no fallback UI was specified.\n\nAdd a <Suspense fallback=...> component higher in the tree to provide a loading indicator or placeholder to display."+jc(k))}Nh=!0;m=jh(m,k);h=l;do{switch(h.tag){case 3:h.effectTag|=2048;h.expirationTime=g;g=Ch(h,m,g);eh(h,g);break a;case 1:if(t=m,A=h.type,k=h.stateNode,0===(h.effectTag&64)&&("function"===typeof A.getDerivedStateFromError||null!==k&&"function"===typeof k.componentDidCatch&&(null===Fh||!Fh.has(k)))){h.effectTag|=2048; h.expirationTime=g;g=Eh(h,t,g);eh(h,g);break a}}h=h.return}while(null!==h)}T=ai(f);continue}}}break}while(1);Kh=!1;Hh.current=c;Yg=Xg=Wg=null;lg();if(e)Lh=null,a.finishedWork=null;else if(null!==T)a.finishedWork=null;else{c=a.current.alternate;null===c?x("281"):void 0;Lh=null;if(Nh){e=a.latestPendingTime;f=a.latestSuspendedTime;g=a.latestPingedTime;if(0!==e&&e<d||0!==f&&f<d||0!==g&&g<d){ff(a,d);fi(a,c,d,a.expirationTime,-1);return}if(!a.didError&&b){a.didError=!0;d=a.nextExpirationTimeToWorkOn=d; b=a.expirationTime=1073741823;fi(a,c,d,b,-1);return}}b&&-1!==Mh?(ff(a,d),b=10*(1073741822-gf(a,d)),b<Mh&&(Mh=b),b=10*(1073741822-lf()),b=Mh-b,fi(a,c,d,a.expirationTime,0>b?0:b)):(a.pendingCommitExpirationTime=d,a.finishedWork=c)}} function sh(a,b){for(var c=a.return;null!==c;){switch(c.tag){case 1:var d=c.stateNode;if("function"===typeof c.type.getDerivedStateFromError||"function"===typeof d.componentDidCatch&&(null===Fh||!Fh.has(d))){a=jh(b,a);a=Eh(c,a,1073741823);pf(c,a);qf(c,1073741823);return}break;case 3:a=jh(b,a);a=Ch(c,a,1073741823);pf(c,a);qf(c,1073741823);return}c=c.return}3===a.tag&&(c=jh(b,a),c=Ch(a,c,1073741823),pf(a,c),qf(a,1073741823))} function mf(a,b){var c=r.unstable_getCurrentPriorityLevel(),d=void 0;if(0===(b.mode&1))d=1073741823;else if(Kh&&!Oh)d=U;else{switch(c){case r.unstable_ImmediatePriority:d=1073741823;break;case r.unstable_UserBlockingPriority:d=1073741822-10*(((1073741822-a+15)/10|0)+1);break;case r.unstable_NormalPriority:d=1073741822-25*(((1073741822-a+500)/25|0)+1);break;case r.unstable_LowPriority:case r.unstable_IdlePriority:d=1;break;default:x("313")}null!==Lh&&d===U&&--d}c===r.unstable_UserBlockingPriority&& (0===gi||d<gi)&&(gi=d);return d}function ei(a,b,c){var d=a.pingCache;null!==d&&d.delete(b);if(null!==Lh&&U===c)Lh=null;else if(b=a.earliestSuspendedTime,d=a.latestSuspendedTime,0!==b&&c<=b&&c>=d){a.didError=!1;b=a.latestPingedTime;if(0===b||b>c)a.latestPingedTime=c;df(c,a);c=a.expirationTime;0!==c&&Xh(a,c)}}function Ah(a,b){var c=a.stateNode;null!==c&&c.delete(b);b=lf();b=mf(b,a);a=hi(a,b);null!==a&&(cf(a,b),b=a.expirationTime,0!==b&&Xh(a,b))} function hi(a,b){a.expirationTime<b&&(a.expirationTime=b);var c=a.alternate;null!==c&&c.expirationTime<b&&(c.expirationTime=b);var d=a.return,e=null;if(null===d&&3===a.tag)e=a.stateNode;else for(;null!==d;){c=d.alternate;d.childExpirationTime<b&&(d.childExpirationTime=b);null!==c&&c.childExpirationTime<b&&(c.childExpirationTime=b);if(null===d.return&&3===d.tag){e=d.stateNode;break}d=d.return}return e} function qf(a,b){a=hi(a,b);null!==a&&(!Kh&&0!==U&&b>U&&Sh(),cf(a,b),Kh&&!Oh&&Lh===a||Xh(a,a.expirationTime),ii>ji&&(ii=0,x("185")))}function ki(a,b,c,d,e){return r.unstable_runWithPriority(r.unstable_ImmediatePriority,function(){return a(b,c,d,e)})}var li=null,Y=null,mi=0,ni=void 0,W=!1,oi=null,Z=0,gi=0,pi=!1,qi=null,X=!1,ri=!1,si=null,ti=r.unstable_now(),ui=1073741822-(ti/10|0),vi=ui,ji=50,ii=0,wi=null;function xi(){ui=1073741822-((r.unstable_now()-ti)/10|0)} function yi(a,b){if(0!==mi){if(b<mi)return;null!==ni&&r.unstable_cancelCallback(ni)}mi=b;a=r.unstable_now()-ti;ni=r.unstable_scheduleCallback(zi,{timeout:10*(1073741822-b)-a})}function fi(a,b,c,d,e){a.expirationTime=d;0!==e||di()?0<e&&(a.timeoutHandle=ye(Ai.bind(null,a,b,c),e)):(a.pendingCommitExpirationTime=c,a.finishedWork=b)}function Ai(a,b,c){a.pendingCommitExpirationTime=c;a.finishedWork=b;xi();vi=ui;Bi(a,c)}function $h(a,b){a.expirationTime=b;a.finishedWork=null} function lf(){if(W)return vi;Ci();if(0===Z||1===Z)xi(),vi=ui;return vi}function Xh(a,b){null===a.nextScheduledRoot?(a.expirationTime=b,null===Y?(li=Y=a,a.nextScheduledRoot=a):(Y=Y.nextScheduledRoot=a,Y.nextScheduledRoot=li)):b>a.expirationTime&&(a.expirationTime=b);W||(X?ri&&(oi=a,Z=1073741823,Di(a,1073741823,!1)):1073741823===b?Yh(1073741823,!1):yi(a,b))} function Ci(){var a=0,b=null;if(null!==Y)for(var c=Y,d=li;null!==d;){var e=d.expirationTime;if(0===e){null===c||null===Y?x("244"):void 0;if(d===d.nextScheduledRoot){li=Y=d.nextScheduledRoot=null;break}else if(d===li)li=e=d.nextScheduledRoot,Y.nextScheduledRoot=e,d.nextScheduledRoot=null;else if(d===Y){Y=c;Y.nextScheduledRoot=li;d.nextScheduledRoot=null;break}else c.nextScheduledRoot=d.nextScheduledRoot,d.nextScheduledRoot=null;d=c.nextScheduledRoot}else{e>a&&(a=e,b=d);if(d===Y)break;if(1073741823=== a)break;c=d;d=d.nextScheduledRoot}}oi=b;Z=a}var Ei=!1;function di(){return Ei?!0:r.unstable_shouldYield()?Ei=!0:!1}function zi(){try{if(!di()&&null!==li){xi();var a=li;do{var b=a.expirationTime;0!==b&&ui<=b&&(a.nextExpirationTimeToWorkOn=ui);a=a.nextScheduledRoot}while(a!==li)}Yh(0,!0)}finally{Ei=!1}} function Yh(a,b){Ci();if(b)for(xi(),vi=ui;null!==oi&&0!==Z&&a<=Z&&!(Ei&&ui>Z);)Di(oi,Z,ui>Z),Ci(),xi(),vi=ui;else for(;null!==oi&&0!==Z&&a<=Z;)Di(oi,Z,!1),Ci();b&&(mi=0,ni=null);0!==Z&&yi(oi,Z);ii=0;wi=null;if(null!==si)for(a=si,si=null,b=0;b<a.length;b++){var c=a[b];try{c._onComplete()}catch(d){pi||(pi=!0,qi=d)}}if(pi)throw a=qi,qi=null,pi=!1,a;}function Bi(a,b){W?x("253"):void 0;oi=a;Z=b;Di(a,b,!1);Yh(1073741823,!1)} function Di(a,b,c){W?x("245"):void 0;W=!0;if(c){var d=a.finishedWork;null!==d?Fi(a,d,b):(a.finishedWork=null,d=a.timeoutHandle,-1!==d&&(a.timeoutHandle=-1,ze(d)),ci(a,c),d=a.finishedWork,null!==d&&(di()?a.finishedWork=d:Fi(a,d,b)))}else d=a.finishedWork,null!==d?Fi(a,d,b):(a.finishedWork=null,d=a.timeoutHandle,-1!==d&&(a.timeoutHandle=-1,ze(d)),ci(a,c),d=a.finishedWork,null!==d&&Fi(a,d,b));W=!1} function Fi(a,b,c){var d=a.firstBatch;if(null!==d&&d._expirationTime>=c&&(null===si?si=[d]:si.push(d),d._defer)){a.finishedWork=b;a.expirationTime=0;return}a.finishedWork=null;a===wi?ii++:(wi=a,ii=0);r.unstable_runWithPriority(r.unstable_ImmediatePriority,function(){Zh(a,b)})}function Dh(a){null===oi?x("246"):void 0;oi.expirationTime=0;pi||(pi=!0,qi=a)}function Gi(a,b){var c=X;X=!0;try{return a(b)}finally{(X=c)||W||Yh(1073741823,!1)}} function Hi(a,b){if(X&&!ri){ri=!0;try{return a(b)}finally{ri=!1}}return a(b)}function Ii(a,b,c){X||W||0===gi||(Yh(gi,!1),gi=0);var d=X;X=!0;try{return r.unstable_runWithPriority(r.unstable_UserBlockingPriority,function(){return a(b,c)})}finally{(X=d)||W||Yh(1073741823,!1)}} function Ji(a,b,c,d,e){var f=b.current;a:if(c){c=c._reactInternalFiber;b:{2===ed(c)&&1===c.tag?void 0:x("170");var g=c;do{switch(g.tag){case 3:g=g.stateNode.context;break b;case 1:if(J(g.type)){g=g.stateNode.__reactInternalMemoizedMergedChildContext;break b}}g=g.return}while(null!==g);x("171");g=void 0}if(1===c.tag){var h=c.type;if(J(h)){c=Ne(c,h,g);break a}}c=g}else c=He;null===b.context?b.context=c:b.pendingContext=c;b=e;e=nf(d);e.payload={element:a};b=void 0===b?null:b;null!==b&&(e.callback=b); of();pf(f,e);qf(f,d);return d}function Ki(a,b,c,d){var e=b.current,f=lf();e=mf(f,e);return Ji(a,b,c,e,d)}function Li(a){a=a.current;if(!a.child)return null;switch(a.child.tag){case 5:return a.child.stateNode;default:return a.child.stateNode}}function Mi(a,b,c){var d=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:Wb,key:null==d?null:""+d,children:a,containerInfo:b,implementation:c}} Ab=function(a,b,c){switch(b){case "input":yc(a,c);b=c.name;if("radio"===c.type&&null!=b){for(c=a;c.parentNode;)c=c.parentNode;c=c.querySelectorAll("input[name="+JSON.stringify(""+b)+'][type="radio"]');for(b=0;b<c.length;b++){var d=c[b];if(d!==a&&d.form===a.form){var e=Ka(d);e?void 0:x("90");Sb(d);yc(d,e)}}}break;case "textarea":de(a,c);break;case "select":b=c.value,null!=b&&ae(a,!!c.multiple,b,!1)}}; function Ni(a){var b=1073741822-25*(((1073741822-lf()+500)/25|0)+1);b>=Jh&&(b=Jh-1);this._expirationTime=Jh=b;this._root=a;this._callbacks=this._next=null;this._hasChildren=this._didComplete=!1;this._children=null;this._defer=!0}Ni.prototype.render=function(a){this._defer?void 0:x("250");this._hasChildren=!0;this._children=a;var b=this._root._internalRoot,c=this._expirationTime,d=new Oi;Ji(a,b,null,c,d._onCommit);return d}; Ni.prototype.then=function(a){if(this._didComplete)a();else{var b=this._callbacks;null===b&&(b=this._callbacks=[]);b.push(a)}}; Ni.prototype.commit=function(){var a=this._root._internalRoot,b=a.firstBatch;this._defer&&null!==b?void 0:x("251");if(this._hasChildren){var c=this._expirationTime;if(b!==this){this._hasChildren&&(c=this._expirationTime=b._expirationTime,this.render(this._children));for(var d=null,e=b;e!==this;)d=e,e=e._next;null===d?x("251"):void 0;d._next=e._next;this._next=b;a.firstBatch=this}this._defer=!1;Bi(a,c);b=this._next;this._next=null;b=a.firstBatch=b;null!==b&&b._hasChildren&&b.render(b._children)}else this._next= null,this._defer=!1};Ni.prototype._onComplete=function(){if(!this._didComplete){this._didComplete=!0;var a=this._callbacks;if(null!==a)for(var b=0;b<a.length;b++)(0,a[b])()}};function Oi(){this._callbacks=null;this._didCommit=!1;this._onCommit=this._onCommit.bind(this)}Oi.prototype.then=function(a){if(this._didCommit)a();else{var b=this._callbacks;null===b&&(b=this._callbacks=[]);b.push(a)}}; Oi.prototype._onCommit=function(){if(!this._didCommit){this._didCommit=!0;var a=this._callbacks;if(null!==a)for(var b=0;b<a.length;b++){var c=a[b];"function"!==typeof c?x("191",c):void 0;c()}}}; function Pi(a,b,c){b=K(3,null,null,b?3:0);a={current:b,containerInfo:a,pendingChildren:null,pingCache:null,earliestPendingTime:0,latestPendingTime:0,earliestSuspendedTime:0,latestSuspendedTime:0,latestPingedTime:0,didError:!1,pendingCommitExpirationTime:0,finishedWork:null,timeoutHandle:-1,context:null,pendingContext:null,hydrate:c,nextExpirationTimeToWorkOn:0,expirationTime:0,firstBatch:null,nextScheduledRoot:null};this._internalRoot=b.stateNode=a} Pi.prototype.render=function(a,b){var c=this._internalRoot,d=new Oi;b=void 0===b?null:b;null!==b&&d.then(b);Ki(a,c,null,d._onCommit);return d};Pi.prototype.unmount=function(a){var b=this._internalRoot,c=new Oi;a=void 0===a?null:a;null!==a&&c.then(a);Ki(null,b,null,c._onCommit);return c};Pi.prototype.legacy_renderSubtreeIntoContainer=function(a,b,c){var d=this._internalRoot,e=new Oi;c=void 0===c?null:c;null!==c&&e.then(c);Ki(b,d,a,e._onCommit);return e}; Pi.prototype.createBatch=function(){var a=new Ni(this),b=a._expirationTime,c=this._internalRoot,d=c.firstBatch;if(null===d)c.firstBatch=a,a._next=null;else{for(c=null;null!==d&&d._expirationTime>=b;)c=d,d=d._next;a._next=d;null!==c&&(c._next=a)}return a};function Qi(a){return!(!a||1!==a.nodeType&&9!==a.nodeType&&11!==a.nodeType&&(8!==a.nodeType||" react-mount-point-unstable "!==a.nodeValue))}Gb=Gi;Hb=Ii;Ib=function(){W||0===gi||(Yh(gi,!1),gi=0)}; function Ri(a,b){b||(b=a?9===a.nodeType?a.documentElement:a.firstChild:null,b=!(!b||1!==b.nodeType||!b.hasAttribute("data-reactroot")));if(!b)for(var c;c=a.lastChild;)a.removeChild(c);return new Pi(a,!1,b)} function Si(a,b,c,d,e){var f=c._reactRootContainer;if(f){if("function"===typeof e){var g=e;e=function(){var a=Li(f._internalRoot);g.call(a)}}null!=a?f.legacy_renderSubtreeIntoContainer(a,b,e):f.render(b,e)}else{f=c._reactRootContainer=Ri(c,d);if("function"===typeof e){var h=e;e=function(){var a=Li(f._internalRoot);h.call(a)}}Hi(function(){null!=a?f.legacy_renderSubtreeIntoContainer(a,b,e):f.render(b,e)})}return Li(f._internalRoot)} function Ti(a,b){var c=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;Qi(b)?void 0:x("200");return Mi(a,b,null,c)} var Vi={createPortal:Ti,findDOMNode:function(a){if(null==a)return null;if(1===a.nodeType)return a;var b=a._reactInternalFiber;void 0===b&&("function"===typeof a.render?x("188"):x("268",Object.keys(a)));a=hd(b);a=null===a?null:a.stateNode;return a},hydrate:function(a,b,c){Qi(b)?void 0:x("200");return Si(null,a,b,!0,c)},render:function(a,b,c){Qi(b)?void 0:x("200");return Si(null,a,b,!1,c)},unstable_renderSubtreeIntoContainer:function(a,b,c,d){Qi(c)?void 0:x("200");null==a||void 0===a._reactInternalFiber? x("38"):void 0;return Si(a,b,c,!1,d)},unmountComponentAtNode:function(a){Qi(a)?void 0:x("40");return a._reactRootContainer?(Hi(function(){Si(null,null,a,!1,function(){a._reactRootContainer=null})}),!0):!1},unstable_createPortal:function(){return Ti.apply(void 0,arguments)},unstable_batchedUpdates:Gi,unstable_interactiveUpdates:Ii,flushSync:function(a,b){W?x("187"):void 0;var c=X;X=!0;try{return ki(a,b)}finally{X=c,Yh(1073741823,!1)}},unstable_createRoot:Ui,unstable_flushControlled:function(a){var b= X;X=!0;try{ki(a)}finally{(X=b)||W||Yh(1073741823,!1)}},__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:{Events:[Ia,Ja,Ka,Ba.injectEventPluginsByName,pa,Qa,function(a){ya(a,Pa)},Eb,Fb,Dd,Da]}};function Ui(a,b){Qi(a)?void 0:x("299","unstable_createRoot");return new Pi(a,!0,null!=b&&!0===b.hydrate)} (function(a){var b=a.findFiberByHostInstance;return Te(n({},a,{overrideProps:null,currentDispatcherRef:Tb.ReactCurrentDispatcher,findHostInstanceByFiber:function(a){a=hd(a);return null===a?null:a.stateNode},findFiberByHostInstance:function(a){return b?b(a):null}}))})({findFiberByHostInstance:Ha,bundleType:0,version:"16.8.6",rendererPackageName:"react-dom"});var Wi={default:Vi},Xi=Wi&&Vi||Wi;module.exports=Xi.default||Xi; },{"object-assign":402,"react":417,"scheduler":436}],413:[function(require,module,exports){ (function (process){ 'use strict'; function checkDCE() { /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ if ( typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined' || typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== 'function' ) { return; } if (process.env.NODE_ENV !== 'production') { // This branch is unreachable because this function is only called // in production, but the condition is true only in development. // Therefore if the branch is still here, dead code elimination wasn't // properly applied. // Don't change the message. React DevTools relies on it. Also make sure // this message doesn't occur elsewhere in this function, or it will cause // a false positive. throw new Error('^_^'); } try { // Verify that the code above has been dead code eliminated (DCE'd). __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE); } catch (err) { // DevTools shouldn't crash React, no matter what. // We should still report in case we break this code. console.error(err); } } if (process.env.NODE_ENV === 'production') { // DCE check should happen before ReactDOM bundle executes so that // DevTools can report bad minification during injection. checkDCE(); module.exports = require('./cjs/react-dom.production.min.js'); } else { module.exports = require('./cjs/react-dom.development.js'); } }).call(this,require('_process')) },{"./cjs/react-dom.development.js":411,"./cjs/react-dom.production.min.js":412,"_process":405}],414:[function(require,module,exports){ (function (process){ 'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react-dom-server.browser.production.min.js'); } else { module.exports = require('./cjs/react-dom-server.browser.development.js'); } }).call(this,require('_process')) },{"./cjs/react-dom-server.browser.development.js":409,"./cjs/react-dom-server.browser.production.min.js":410,"_process":405}],415:[function(require,module,exports){ (function (process){ /** @license React v16.8.6 * react.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; if (process.env.NODE_ENV !== "production") { (function() { 'use strict'; var _assign = require('object-assign'); var checkPropTypes = require('prop-types/checkPropTypes'); // TODO: this is special because it gets imported during build. var ReactVersion = '16.8.6'; // The Symbol used to tag the ReactElement-like types. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var hasSymbol = typeof Symbol === 'function' && Symbol.for; var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7; var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca; var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb; var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc; var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2; var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd; var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf; var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0; var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1; var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3; var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4; var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; function getIteratorFn(maybeIterable) { if (maybeIterable === null || typeof maybeIterable !== 'object') { return null; } var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; if (typeof maybeIterator === 'function') { return maybeIterator; } return null; } /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var validateFormat = function () {}; { validateFormat = function (format) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } }; } function invariant(condition, format, a, b, c, d, e, f) { validateFormat(format); if (!condition) { var error = void 0; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } // Relying on the `invariant()` implementation lets us // preserve the format and params in the www builds. /** * Forked from fbjs/warning: * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js * * Only change is we use console.warn instead of console.error, * and do nothing when 'console' is not supported. * This really simplifies the code. * --- * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var lowPriorityWarning = function () {}; { var printWarning = function (format) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.warn(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; lowPriorityWarning = function (condition, format) { if (format === undefined) { throw new Error('`lowPriorityWarning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (!condition) { for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } printWarning.apply(undefined, [format].concat(args)); } }; } var lowPriorityWarning$1 = lowPriorityWarning; /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warningWithoutStack = function () {}; { warningWithoutStack = function (condition, format) { for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } if (format === undefined) { throw new Error('`warningWithoutStack(condition, format, ...args)` requires a warning ' + 'message argument'); } if (args.length > 8) { // Check before the condition to catch violations early. throw new Error('warningWithoutStack() currently supports at most 8 arguments.'); } if (condition) { return; } if (typeof console !== 'undefined') { var argsWithFormat = args.map(function (item) { return '' + item; }); argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it // breaks IE9: https://github.com/facebook/react/issues/13610 Function.prototype.apply.call(console.error, console, argsWithFormat); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); throw new Error(message); } catch (x) {} }; } var warningWithoutStack$1 = warningWithoutStack; var didWarnStateUpdateForUnmountedComponent = {}; function warnNoop(publicInstance, callerName) { { var _constructor = publicInstance.constructor; var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass'; var warningKey = componentName + '.' + callerName; if (didWarnStateUpdateForUnmountedComponent[warningKey]) { return; } warningWithoutStack$1(false, "Can't call %s on a component that is not yet mounted. " + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName); didWarnStateUpdateForUnmountedComponent[warningKey] = true; } } /** * This is the abstract API for an update queue. */ var ReactNoopUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { return false; }, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {?function} callback Called after component is updated. * @param {?string} callerName name of the calling function in the public API. * @internal */ enqueueForceUpdate: function (publicInstance, callback, callerName) { warnNoop(publicInstance, 'forceUpdate'); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @param {?function} callback Called after component is updated. * @param {?string} callerName name of the calling function in the public API. * @internal */ enqueueReplaceState: function (publicInstance, completeState, callback, callerName) { warnNoop(publicInstance, 'replaceState'); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @param {?function} callback Called after component is updated. * @param {?string} Name of the calling function in the public API. * @internal */ enqueueSetState: function (publicInstance, partialState, callback, callerName) { warnNoop(publicInstance, 'setState'); } }; var emptyObject = {}; { Object.freeze(emptyObject); } /** * Base class helpers for the updating state of a component. */ function Component(props, context, updater) { this.props = props; this.context = context; // If a component has string refs, we will assign a different object later. this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } Component.prototype.isReactComponent = {}; /** * Sets a subset of the state. Always use this to mutate * state. You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * There is no guarantee that calls to `setState` will run synchronously, * as they may eventually be batched together. You can provide an optional * callback that will be executed when the call to setState is actually * completed. * * When a function is provided to setState, it will be called at some point in * the future (not synchronously). It will be called with the up to date * component arguments (state, props, context). These values can be different * from this.* because your function may be called after receiveProps but before * shouldComponentUpdate, and this new state, props, and context will not yet be * assigned to this. * * @param {object|function} partialState Next partial state or function to * produce next partial state to be merged with current state. * @param {?function} callback Called after state is updated. * @final * @protected */ Component.prototype.setState = function (partialState, callback) { !(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? invariant(false, 'setState(...): takes an object of state variables to update or a function which returns an object of state variables.') : void 0; this.updater.enqueueSetState(this, partialState, callback, 'setState'); }; /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {?function} callback Called after update is complete. * @final * @protected */ Component.prototype.forceUpdate = function (callback) { this.updater.enqueueForceUpdate(this, callback, 'forceUpdate'); }; /** * Deprecated APIs. These APIs used to exist on classic React classes but since * we would like to deprecate them, we're not going to move them over to this * modern base class. Instead, we define a getter that warns if it's accessed. */ { var deprecatedAPIs = { isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'], replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).'] }; var defineDeprecationWarning = function (methodName, info) { Object.defineProperty(Component.prototype, methodName, { get: function () { lowPriorityWarning$1(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]); return undefined; } }); }; for (var fnName in deprecatedAPIs) { if (deprecatedAPIs.hasOwnProperty(fnName)) { defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); } } } function ComponentDummy() {} ComponentDummy.prototype = Component.prototype; /** * Convenience component with default shallow equality check for sCU. */ function PureComponent(props, context, updater) { this.props = props; this.context = context; // If a component has string refs, we will assign a different object later. this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; } var pureComponentPrototype = PureComponent.prototype = new ComponentDummy(); pureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods. _assign(pureComponentPrototype, Component.prototype); pureComponentPrototype.isPureReactComponent = true; // an immutable object with a single mutable value function createRef() { var refObject = { current: null }; { Object.seal(refObject); } return refObject; } /** * Keeps track of the current dispatcher. */ var ReactCurrentDispatcher = { /** * @internal * @type {ReactComponent} */ current: null }; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; var BEFORE_SLASH_RE = /^(.*)[\\\/]/; var describeComponentFrame = function (name, source, ownerName) { var sourceInfo = ''; if (source) { var path = source.fileName; var fileName = path.replace(BEFORE_SLASH_RE, ''); { // In DEV, include code for a common special case: // prefer "folder/index.js" instead of just "index.js". if (/^index\./.test(fileName)) { var match = path.match(BEFORE_SLASH_RE); if (match) { var pathBeforeSlash = match[1]; if (pathBeforeSlash) { var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, ''); fileName = folderName + '/' + fileName; } } } } sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')'; } else if (ownerName) { sourceInfo = ' (created by ' + ownerName + ')'; } return '\n in ' + (name || 'Unknown') + sourceInfo; }; var Resolved = 1; function refineResolvedLazyComponent(lazyComponent) { return lazyComponent._status === Resolved ? lazyComponent._result : null; } function getWrappedName(outerType, innerType, wrapperName) { var functionName = innerType.displayName || innerType.name || ''; return outerType.displayName || (functionName !== '' ? wrapperName + '(' + functionName + ')' : wrapperName); } function getComponentName(type) { if (type == null) { // Host root, text node or just invalid type. return null; } { if (typeof type.tag === 'number') { warningWithoutStack$1(false, 'Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.'); } } if (typeof type === 'function') { return type.displayName || type.name || null; } if (typeof type === 'string') { return type; } switch (type) { case REACT_CONCURRENT_MODE_TYPE: return 'ConcurrentMode'; case REACT_FRAGMENT_TYPE: return 'Fragment'; case REACT_PORTAL_TYPE: return 'Portal'; case REACT_PROFILER_TYPE: return 'Profiler'; case REACT_STRICT_MODE_TYPE: return 'StrictMode'; case REACT_SUSPENSE_TYPE: return 'Suspense'; } if (typeof type === 'object') { switch (type.$$typeof) { case REACT_CONTEXT_TYPE: return 'Context.Consumer'; case REACT_PROVIDER_TYPE: return 'Context.Provider'; case REACT_FORWARD_REF_TYPE: return getWrappedName(type, type.render, 'ForwardRef'); case REACT_MEMO_TYPE: return getComponentName(type.type); case REACT_LAZY_TYPE: { var thenable = type; var resolvedThenable = refineResolvedLazyComponent(thenable); if (resolvedThenable) { return getComponentName(resolvedThenable); } } } } return null; } var ReactDebugCurrentFrame = {}; var currentlyValidatingElement = null; function setCurrentlyValidatingElement(element) { { currentlyValidatingElement = element; } } { // Stack implementation injected by the current renderer. ReactDebugCurrentFrame.getCurrentStack = null; ReactDebugCurrentFrame.getStackAddendum = function () { var stack = ''; // Add an extra top frame while an element is being validated if (currentlyValidatingElement) { var name = getComponentName(currentlyValidatingElement.type); var owner = currentlyValidatingElement._owner; stack += describeComponentFrame(name, currentlyValidatingElement._source, owner && getComponentName(owner.type)); } // Delegate to the injected renderer-specific implementation var impl = ReactDebugCurrentFrame.getCurrentStack; if (impl) { stack += impl() || ''; } return stack; }; } var ReactSharedInternals = { ReactCurrentDispatcher: ReactCurrentDispatcher, ReactCurrentOwner: ReactCurrentOwner, // Used by renderers to avoid bundling object-assign twice in UMD bundles: assign: _assign }; { _assign(ReactSharedInternals, { // These should not be included in production. ReactDebugCurrentFrame: ReactDebugCurrentFrame, // Shim for React DOM 16.0.0 which still destructured (but not used) this. // TODO: remove in React 17.0. ReactComponentTreeHook: {} }); } /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = warningWithoutStack$1; { warning = function (condition, format) { if (condition) { return; } var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; var stack = ReactDebugCurrentFrame.getStackAddendum(); // eslint-disable-next-line react-internal/warning-and-invariant-args for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } warningWithoutStack$1.apply(undefined, [false, format + '%s'].concat(args, [stack])); }; } var warning$1 = warning; var hasOwnProperty = Object.prototype.hasOwnProperty; var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; var specialPropKeyWarningShown = void 0; var specialPropRefWarningShown = void 0; function hasValidRef(config) { { if (hasOwnProperty.call(config, 'ref')) { var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; if (getter && getter.isReactWarning) { return false; } } } return config.ref !== undefined; } function hasValidKey(config) { { if (hasOwnProperty.call(config, 'key')) { var getter = Object.getOwnPropertyDescriptor(config, 'key').get; if (getter && getter.isReactWarning) { return false; } } } return config.key !== undefined; } function defineKeyPropWarningGetter(props, displayName) { var warnAboutAccessingKey = function () { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; warningWithoutStack$1(false, '%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName); } }; warnAboutAccessingKey.isReactWarning = true; Object.defineProperty(props, 'key', { get: warnAboutAccessingKey, configurable: true }); } function defineRefPropWarningGetter(props, displayName) { var warnAboutAccessingRef = function () { if (!specialPropRefWarningShown) { specialPropRefWarningShown = true; warningWithoutStack$1(false, '%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName); } }; warnAboutAccessingRef.isReactWarning = true; Object.defineProperty(props, 'ref', { get: warnAboutAccessingRef, configurable: true }); } /** * Factory method to create a new React element. This no longer adheres to * the class pattern, so do not use new to call it. Also, no instanceof check * will work. Instead test $$typeof field against Symbol.for('react.element') to check * if something is a React Element. * * @param {*} type * @param {*} key * @param {string|object} ref * @param {*} self A *temporary* helper to detect places where `this` is * different from the `owner` when React.createElement is called, so that we * can warn. We want to get rid of owner and replace string `ref`s with arrow * functions, and as long as `this` and owner are the same, there will be no * change in behavior. * @param {*} source An annotation object (added by a transpiler or otherwise) * indicating filename, line number, and/or other information. * @param {*} owner * @param {*} props * @internal */ var ReactElement = function (type, key, ref, self, source, owner, props) { var element = { // This tag allows us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type: type, key: key, ref: ref, props: props, // Record the component responsible for creating this element. _owner: owner }; { // The validation flag is currently mutative. We put it on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. element._store = {}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. Object.defineProperty(element._store, 'validated', { configurable: false, enumerable: false, writable: true, value: false }); // self and source are DEV only properties. Object.defineProperty(element, '_self', { configurable: false, enumerable: false, writable: false, value: self }); // Two elements created in two different places should be considered // equal for testing purposes and therefore we hide it from enumeration. Object.defineProperty(element, '_source', { configurable: false, enumerable: false, writable: false, value: source }); if (Object.freeze) { Object.freeze(element.props); Object.freeze(element); } } return element; }; /** * Create and return a new ReactElement of the given type. * See https://reactjs.org/docs/react-api.html#createelement */ function createElement(type, config, children) { var propName = void 0; // Reserved names are extracted var props = {}; var key = null; var ref = null; var self = null; var source = null; if (config != null) { if (hasValidRef(config)) { ref = config.ref; } if (hasValidKey(config)) { key = '' + config.key; } self = config.__self === undefined ? null : config.__self; source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } { if (Object.freeze) { Object.freeze(childArray); } } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } } { if (key || ref) { var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; if (key) { defineKeyPropWarningGetter(props, displayName); } if (ref) { defineRefPropWarningGetter(props, displayName); } } } return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); } /** * Return a function that produces ReactElements of a given type. * See https://reactjs.org/docs/react-api.html#createfactory */ function cloneAndReplaceKey(oldElement, newKey) { var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); return newElement; } /** * Clone and return a new ReactElement using element as the starting point. * See https://reactjs.org/docs/react-api.html#cloneelement */ function cloneElement(element, config, children) { !!(element === null || element === undefined) ? invariant(false, 'React.cloneElement(...): The argument must be a React element, but you passed %s.', element) : void 0; var propName = void 0; // Original props are copied var props = _assign({}, element.props); // Reserved names are extracted var key = element.key; var ref = element.ref; // Self is preserved since the owner is preserved. var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a // transpiler, and the original source is probably a better indicator of the // true owner. var source = element._source; // Owner will be preserved, unless ref is overridden var owner = element._owner; if (config != null) { if (hasValidRef(config)) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (hasValidKey(config)) { key = '' + config.key; } // Remaining properties override existing props var defaultProps = void 0; if (element.type && element.type.defaultProps) { defaultProps = element.type.defaultProps; } for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { if (config[propName] === undefined && defaultProps !== undefined) { // Resolve default props props[propName] = defaultProps[propName]; } else { props[propName] = config[propName]; } } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return ReactElement(element.type, key, ref, self, source, owner, props); } /** * Verifies the object is a ReactElement. * See https://reactjs.org/docs/react-api.html#isvalidelement * @param {?object} object * @return {boolean} True if `object` is a ReactElement. * @final */ function isValidElement(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; } var SEPARATOR = '.'; var SUBSEPARATOR = ':'; /** * Escape and wrap key so it is safe to use as a reactid * * @param {string} key to be escaped. * @return {string} the escaped key. */ function escape(key) { var escapeRegex = /[=:]/g; var escaperLookup = { '=': '=0', ':': '=2' }; var escapedString = ('' + key).replace(escapeRegex, function (match) { return escaperLookup[match]; }); return '$' + escapedString; } /** * TODO: Test that a single child and an array with one item have the same key * pattern. */ var didWarnAboutMaps = false; var userProvidedKeyEscapeRegex = /\/+/g; function escapeUserProvidedKey(text) { return ('' + text).replace(userProvidedKeyEscapeRegex, '$&/'); } var POOL_SIZE = 10; var traverseContextPool = []; function getPooledTraverseContext(mapResult, keyPrefix, mapFunction, mapContext) { if (traverseContextPool.length) { var traverseContext = traverseContextPool.pop(); traverseContext.result = mapResult; traverseContext.keyPrefix = keyPrefix; traverseContext.func = mapFunction; traverseContext.context = mapContext; traverseContext.count = 0; return traverseContext; } else { return { result: mapResult, keyPrefix: keyPrefix, func: mapFunction, context: mapContext, count: 0 }; } } function releaseTraverseContext(traverseContext) { traverseContext.result = null; traverseContext.keyPrefix = null; traverseContext.func = null; traverseContext.context = null; traverseContext.count = 0; if (traverseContextPool.length < POOL_SIZE) { traverseContextPool.push(traverseContext); } } /** * @param {?*} children Children tree container. * @param {!string} nameSoFar Name of the key path so far. * @param {!function} callback Callback to invoke with each child found. * @param {?*} traverseContext Used to pass information throughout the traversal * process. * @return {!number} The number of children in this subtree. */ function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) { var type = typeof children; if (type === 'undefined' || type === 'boolean') { // All of the above are perceived as null. children = null; } var invokeCallback = false; if (children === null) { invokeCallback = true; } else { switch (type) { case 'string': case 'number': invokeCallback = true; break; case 'object': switch (children.$$typeof) { case REACT_ELEMENT_TYPE: case REACT_PORTAL_TYPE: invokeCallback = true; } } } if (invokeCallback) { callback(traverseContext, children, // If it's the only child, treat the name as if it was wrapped in an array // so that it's consistent if the number of children grows. nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar); return 1; } var child = void 0; var nextName = void 0; var subtreeCount = 0; // Count of children found in the current subtree. var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = nextNamePrefix + getComponentKey(child, i); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { var iteratorFn = getIteratorFn(children); if (typeof iteratorFn === 'function') { { // Warn about using Maps as children if (iteratorFn === children.entries) { !didWarnAboutMaps ? warning$1(false, 'Using Maps as children is unsupported and will likely yield ' + 'unexpected results. Convert it to a sequence/iterable of keyed ' + 'ReactElements instead.') : void 0; didWarnAboutMaps = true; } } var iterator = iteratorFn.call(children); var step = void 0; var ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = nextNamePrefix + getComponentKey(child, ii++); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else if (type === 'object') { var addendum = ''; { addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + ReactDebugCurrentFrame.getStackAddendum(); } var childrenString = '' + children; invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum); } } return subtreeCount; } /** * Traverses children that are typically specified as `props.children`, but * might also be specified through attributes: * * - `traverseAllChildren(this.props.children, ...)` * - `traverseAllChildren(this.props.leftPanelChildren, ...)` * * The `traverseContext` is an optional argument that is passed through the * entire traversal. It can be used to store accumulations or anything else that * the callback might find relevant. * * @param {?*} children Children tree object. * @param {!function} callback To invoke upon traversing each child. * @param {?*} traverseContext Context for traversal. * @return {!number} The number of children in this subtree. */ function traverseAllChildren(children, callback, traverseContext) { if (children == null) { return 0; } return traverseAllChildrenImpl(children, '', callback, traverseContext); } /** * Generate a key string that identifies a component within a set. * * @param {*} component A component that could contain a manual key. * @param {number} index Index that is used if a manual key is not provided. * @return {string} */ function getComponentKey(component, index) { // Do some typechecking here since we call this blindly. We want to ensure // that we don't block potential future ES APIs. if (typeof component === 'object' && component !== null && component.key != null) { // Explicit key return escape(component.key); } // Implicit key determined by the index in the set return index.toString(36); } function forEachSingleChild(bookKeeping, child, name) { var func = bookKeeping.func, context = bookKeeping.context; func.call(context, child, bookKeeping.count++); } /** * Iterates through children that are typically specified as `props.children`. * * See https://reactjs.org/docs/react-api.html#reactchildrenforeach * * The provided forEachFunc(child, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} forEachFunc * @param {*} forEachContext Context for forEachContext. */ function forEachChildren(children, forEachFunc, forEachContext) { if (children == null) { return children; } var traverseContext = getPooledTraverseContext(null, null, forEachFunc, forEachContext); traverseAllChildren(children, forEachSingleChild, traverseContext); releaseTraverseContext(traverseContext); } function mapSingleChildIntoContext(bookKeeping, child, childKey) { var result = bookKeeping.result, keyPrefix = bookKeeping.keyPrefix, func = bookKeeping.func, context = bookKeeping.context; var mappedChild = func.call(context, child, bookKeeping.count++); if (Array.isArray(mappedChild)) { mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, function (c) { return c; }); } else if (mappedChild != null) { if (isValidElement(mappedChild)) { mappedChild = cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as // traverseAllChildren used to do for objects as children keyPrefix + (mappedChild.key && (!child || child.key !== mappedChild.key) ? escapeUserProvidedKey(mappedChild.key) + '/' : '') + childKey); } result.push(mappedChild); } } function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) { var escapedPrefix = ''; if (prefix != null) { escapedPrefix = escapeUserProvidedKey(prefix) + '/'; } var traverseContext = getPooledTraverseContext(array, escapedPrefix, func, context); traverseAllChildren(children, mapSingleChildIntoContext, traverseContext); releaseTraverseContext(traverseContext); } /** * Maps children that are typically specified as `props.children`. * * See https://reactjs.org/docs/react-api.html#reactchildrenmap * * The provided mapFunction(child, key, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} func The map function. * @param {*} context Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapChildren(children, func, context) { if (children == null) { return children; } var result = []; mapIntoWithKeyPrefixInternal(children, result, null, func, context); return result; } /** * Count the number of children that are typically specified as * `props.children`. * * See https://reactjs.org/docs/react-api.html#reactchildrencount * * @param {?*} children Children tree container. * @return {number} The number of children. */ function countChildren(children) { return traverseAllChildren(children, function () { return null; }, null); } /** * Flatten a children object (typically specified as `props.children`) and * return an array with appropriately re-keyed children. * * See https://reactjs.org/docs/react-api.html#reactchildrentoarray */ function toArray(children) { var result = []; mapIntoWithKeyPrefixInternal(children, result, null, function (child) { return child; }); return result; } /** * Returns the first child in a collection of children and verifies that there * is only one child in the collection. * * See https://reactjs.org/docs/react-api.html#reactchildrenonly * * The current implementation of this function assumes that a single child gets * passed without a wrapper, but the purpose of this helper function is to * abstract away the particular structure of children. * * @param {?object} children Child collection structure. * @return {ReactElement} The first and only `ReactElement` contained in the * structure. */ function onlyChild(children) { !isValidElement(children) ? invariant(false, 'React.Children.only expected to receive a single React element child.') : void 0; return children; } function createContext(defaultValue, calculateChangedBits) { if (calculateChangedBits === undefined) { calculateChangedBits = null; } else { { !(calculateChangedBits === null || typeof calculateChangedBits === 'function') ? warningWithoutStack$1(false, 'createContext: Expected the optional second argument to be a ' + 'function. Instead received: %s', calculateChangedBits) : void 0; } } var context = { $$typeof: REACT_CONTEXT_TYPE, _calculateChangedBits: calculateChangedBits, // As a workaround to support multiple concurrent renderers, we categorize // some renderers as primary and others as secondary. We only expect // there to be two concurrent renderers at most: React Native (primary) and // Fabric (secondary); React DOM (primary) and React ART (secondary). // Secondary renderers store their context values on separate fields. _currentValue: defaultValue, _currentValue2: defaultValue, // Used to track how many concurrent renderers this context currently // supports within in a single renderer. Such as parallel server rendering. _threadCount: 0, // These are circular Provider: null, Consumer: null }; context.Provider = { $$typeof: REACT_PROVIDER_TYPE, _context: context }; var hasWarnedAboutUsingNestedContextConsumers = false; var hasWarnedAboutUsingConsumerProvider = false; { // A separate object, but proxies back to the original context object for // backwards compatibility. It has a different $$typeof, so we can properly // warn for the incorrect usage of Context as a Consumer. var Consumer = { $$typeof: REACT_CONTEXT_TYPE, _context: context, _calculateChangedBits: context._calculateChangedBits }; // $FlowFixMe: Flow complains about not setting a value, which is intentional here Object.defineProperties(Consumer, { Provider: { get: function () { if (!hasWarnedAboutUsingConsumerProvider) { hasWarnedAboutUsingConsumerProvider = true; warning$1(false, 'Rendering <Context.Consumer.Provider> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Provider> instead?'); } return context.Provider; }, set: function (_Provider) { context.Provider = _Provider; } }, _currentValue: { get: function () { return context._currentValue; }, set: function (_currentValue) { context._currentValue = _currentValue; } }, _currentValue2: { get: function () { return context._currentValue2; }, set: function (_currentValue2) { context._currentValue2 = _currentValue2; } }, _threadCount: { get: function () { return context._threadCount; }, set: function (_threadCount) { context._threadCount = _threadCount; } }, Consumer: { get: function () { if (!hasWarnedAboutUsingNestedContextConsumers) { hasWarnedAboutUsingNestedContextConsumers = true; warning$1(false, 'Rendering <Context.Consumer.Consumer> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?'); } return context.Consumer; } } }); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty context.Consumer = Consumer; } { context._currentRenderer = null; context._currentRenderer2 = null; } return context; } function lazy(ctor) { var lazyType = { $$typeof: REACT_LAZY_TYPE, _ctor: ctor, // React uses these fields to store the result. _status: -1, _result: null }; { // In production, this would just set it on the object. var defaultProps = void 0; var propTypes = void 0; Object.defineProperties(lazyType, { defaultProps: { configurable: true, get: function () { return defaultProps; }, set: function (newDefaultProps) { warning$1(false, 'React.lazy(...): It is not supported to assign `defaultProps` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.'); defaultProps = newDefaultProps; // Match production behavior more closely: Object.defineProperty(lazyType, 'defaultProps', { enumerable: true }); } }, propTypes: { configurable: true, get: function () { return propTypes; }, set: function (newPropTypes) { warning$1(false, 'React.lazy(...): It is not supported to assign `propTypes` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.'); propTypes = newPropTypes; // Match production behavior more closely: Object.defineProperty(lazyType, 'propTypes', { enumerable: true }); } } }); } return lazyType; } function forwardRef(render) { { if (render != null && render.$$typeof === REACT_MEMO_TYPE) { warningWithoutStack$1(false, 'forwardRef requires a render function but received a `memo` ' + 'component. Instead of forwardRef(memo(...)), use ' + 'memo(forwardRef(...)).'); } else if (typeof render !== 'function') { warningWithoutStack$1(false, 'forwardRef requires a render function but was given %s.', render === null ? 'null' : typeof render); } else { !( // Do not warn for 0 arguments because it could be due to usage of the 'arguments' object render.length === 0 || render.length === 2) ? warningWithoutStack$1(false, 'forwardRef render functions accept exactly two parameters: props and ref. %s', render.length === 1 ? 'Did you forget to use the ref parameter?' : 'Any additional parameter will be undefined.') : void 0; } if (render != null) { !(render.defaultProps == null && render.propTypes == null) ? warningWithoutStack$1(false, 'forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?') : void 0; } } return { $$typeof: REACT_FORWARD_REF_TYPE, render: render }; } function isValidElementType(type) { return typeof type === 'string' || typeof type === 'function' || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill. type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE); } function memo(type, compare) { { if (!isValidElementType(type)) { warningWithoutStack$1(false, 'memo: The first argument must be a component. Instead ' + 'received: %s', type === null ? 'null' : typeof type); } } return { $$typeof: REACT_MEMO_TYPE, type: type, compare: compare === undefined ? null : compare }; } function resolveDispatcher() { var dispatcher = ReactCurrentDispatcher.current; !(dispatcher !== null) ? invariant(false, 'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.') : void 0; return dispatcher; } function useContext(Context, unstable_observedBits) { var dispatcher = resolveDispatcher(); { !(unstable_observedBits === undefined) ? warning$1(false, 'useContext() second argument is reserved for future ' + 'use in React. Passing it is not supported. ' + 'You passed: %s.%s', unstable_observedBits, typeof unstable_observedBits === 'number' && Array.isArray(arguments[2]) ? '\n\nDid you call array.map(useContext)? ' + 'Calling Hooks inside a loop is not supported. ' + 'Learn more at https://fb.me/rules-of-hooks' : '') : void 0; // TODO: add a more generic warning for invalid values. if (Context._context !== undefined) { var realContext = Context._context; // Don't deduplicate because this legitimately causes bugs // and nobody should be using this in existing code. if (realContext.Consumer === Context) { warning$1(false, 'Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be ' + 'removed in a future major release. Did you mean to call useContext(Context) instead?'); } else if (realContext.Provider === Context) { warning$1(false, 'Calling useContext(Context.Provider) is not supported. ' + 'Did you mean to call useContext(Context) instead?'); } } } return dispatcher.useContext(Context, unstable_observedBits); } function useState(initialState) { var dispatcher = resolveDispatcher(); return dispatcher.useState(initialState); } function useReducer(reducer, initialArg, init) { var dispatcher = resolveDispatcher(); return dispatcher.useReducer(reducer, initialArg, init); } function useRef(initialValue) { var dispatcher = resolveDispatcher(); return dispatcher.useRef(initialValue); } function useEffect(create, inputs) { var dispatcher = resolveDispatcher(); return dispatcher.useEffect(create, inputs); } function useLayoutEffect(create, inputs) { var dispatcher = resolveDispatcher(); return dispatcher.useLayoutEffect(create, inputs); } function useCallback(callback, inputs) { var dispatcher = resolveDispatcher(); return dispatcher.useCallback(callback, inputs); } function useMemo(create, inputs) { var dispatcher = resolveDispatcher(); return dispatcher.useMemo(create, inputs); } function useImperativeHandle(ref, create, inputs) { var dispatcher = resolveDispatcher(); return dispatcher.useImperativeHandle(ref, create, inputs); } function useDebugValue(value, formatterFn) { { var dispatcher = resolveDispatcher(); return dispatcher.useDebugValue(value, formatterFn); } } /** * ReactElementValidator provides a wrapper around a element factory * which validates the props passed to the element. This is intended to be * used only in DEV and could be replaced by a static type checker for languages * that support it. */ var propTypesMisspellWarningShown = void 0; { propTypesMisspellWarningShown = false; } function getDeclarationErrorAddendum() { if (ReactCurrentOwner.current) { var name = getComponentName(ReactCurrentOwner.current.type); if (name) { return '\n\nCheck the render method of `' + name + '`.'; } } return ''; } function getSourceInfoErrorAddendum(elementProps) { if (elementProps !== null && elementProps !== undefined && elementProps.__source !== undefined) { var source = elementProps.__source; var fileName = source.fileName.replace(/^.*[\\\/]/, ''); var lineNumber = source.lineNumber; return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.'; } return ''; } /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ var ownerHasKeyUseWarning = {}; function getCurrentComponentErrorInfo(parentType) { var info = getDeclarationErrorAddendum(); if (!info) { var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; if (parentName) { info = '\n\nCheck the top-level render call using <' + parentName + '>.'; } } return info; } /** * Warn if the element doesn't have an explicit key assigned to it. * This element is in an array. The array could grow and shrink or be * reordered. All children that haven't already been validated are required to * have a "key" property assigned to it. Error statuses are cached so a warning * will only be shown once. * * @internal * @param {ReactElement} element Element that requires a key. * @param {*} parentType element's parent's type. */ function validateExplicitKey(element, parentType) { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { return; } ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a // property, it may be the creator of the child that's responsible for // assigning it a key. var childOwner = ''; if (element && element._owner && element._owner !== ReactCurrentOwner.current) { // Give the component that originally created this child. childOwner = ' It was passed a child from ' + getComponentName(element._owner.type) + '.'; } setCurrentlyValidatingElement(element); { warning$1(false, 'Each child in a list should have a unique "key" prop.' + '%s%s See https://fb.me/react-warning-keys for more information.', currentComponentErrorInfo, childOwner); } setCurrentlyValidatingElement(null); } /** * Ensure that every element either is passed in a static location, in an * array with an explicit keys property defined, or in an object literal * with valid key property. * * @internal * @param {ReactNode} node Statically passed child of any type. * @param {*} parentType node's parent's type. */ function validateChildKeys(node, parentType) { if (typeof node !== 'object') { return; } if (Array.isArray(node)) { for (var i = 0; i < node.length; i++) { var child = node[i]; if (isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (isValidElement(node)) { // This element was passed in a valid location. if (node._store) { node._store.validated = true; } } else if (node) { var iteratorFn = getIteratorFn(node); if (typeof iteratorFn === 'function') { // Entry iterators used to provide implicit keys, // but now we print a separate warning for them later. if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step = void 0; while (!(step = iterator.next()).done) { if (isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } /** * Given an element, validate that its props follow the propTypes definition, * provided by the type. * * @param {ReactElement} element */ function validatePropTypes(element) { var type = element.type; if (type === null || type === undefined || typeof type === 'string') { return; } var name = getComponentName(type); var propTypes = void 0; if (typeof type === 'function') { propTypes = type.propTypes; } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. // Inner props are checked in the reconciler. type.$$typeof === REACT_MEMO_TYPE)) { propTypes = type.propTypes; } else { return; } if (propTypes) { setCurrentlyValidatingElement(element); checkPropTypes(propTypes, element.props, 'prop', name, ReactDebugCurrentFrame.getStackAddendum); setCurrentlyValidatingElement(null); } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) { propTypesMisspellWarningShown = true; warningWithoutStack$1(false, 'Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', name || 'Unknown'); } if (typeof type.getDefaultProps === 'function') { !type.getDefaultProps.isReactClassApproved ? warningWithoutStack$1(false, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.') : void 0; } } /** * Given a fragment, validate that it can only be provided with fragment props * @param {ReactElement} fragment */ function validateFragmentProps(fragment) { setCurrentlyValidatingElement(fragment); var keys = Object.keys(fragment.props); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (key !== 'children' && key !== 'key') { warning$1(false, 'Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key); break; } } if (fragment.ref !== null) { warning$1(false, 'Invalid attribute `ref` supplied to `React.Fragment`.'); } setCurrentlyValidatingElement(null); } function createElementWithValidation(type, props, children) { var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to // succeed and there will likely be errors in render. if (!validType) { var info = ''; if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports."; } var sourceInfo = getSourceInfoErrorAddendum(props); if (sourceInfo) { info += sourceInfo; } else { info += getDeclarationErrorAddendum(); } var typeString = void 0; if (type === null) { typeString = 'null'; } else if (Array.isArray(type)) { typeString = 'array'; } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) { typeString = '<' + (getComponentName(type.type) || 'Unknown') + ' />'; info = ' Did you accidentally export a JSX literal instead of a component?'; } else { typeString = typeof type; } warning$1(false, 'React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info); } var element = createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used. // TODO: Drop this when these are no longer allowed as the type argument. if (element == null) { return element; } // Skip key warning if the type isn't valid since our key validation logic // doesn't expect a non-string/function type and can throw confusing errors. // We don't want exception behavior to differ between dev and prod. // (Rendering will throw with a helpful message and as soon as the type is // fixed, the key warnings will appear.) if (validType) { for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], type); } } if (type === REACT_FRAGMENT_TYPE) { validateFragmentProps(element); } else { validatePropTypes(element); } return element; } function createFactoryWithValidation(type) { var validatedFactory = createElementWithValidation.bind(null, type); validatedFactory.type = type; // Legacy hook: remove it { Object.defineProperty(validatedFactory, 'type', { enumerable: false, get: function () { lowPriorityWarning$1(false, 'Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.'); Object.defineProperty(this, 'type', { value: type }); return type; } }); } return validatedFactory; } function cloneElementWithValidation(element, props, children) { var newElement = cloneElement.apply(this, arguments); for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], newElement.type); } validatePropTypes(newElement); return newElement; } // Helps identify side effects in begin-phase lifecycle hooks and setState reducers: // In some cases, StrictMode should also double-render lifecycles. // This can be confusing for tests though, // And it can be bad for performance in production. // This feature flag can be used to control the behavior: // To preserve the "Pause on caught exceptions" behavior of the debugger, we // replay the begin phase of a failed component inside invokeGuardedCallback. // Warn about deprecated, async-unsafe lifecycles; relates to RFC #6: // Gather advanced timing metrics for Profiler subtrees. // Trace which interactions trigger each commit. // Only used in www builds. // TODO: true? Here it might just be false. // Only used in www builds. // Only used in www builds. // React Fire: prevent the value and checked attributes from syncing // with their related DOM properties // These APIs will no longer be "unstable" in the upcoming 16.7 release, // Control this behavior with a flag to support 16.6 minor releases in the meanwhile. var enableStableConcurrentModeAPIs = false; var React = { Children: { map: mapChildren, forEach: forEachChildren, count: countChildren, toArray: toArray, only: onlyChild }, createRef: createRef, Component: Component, PureComponent: PureComponent, createContext: createContext, forwardRef: forwardRef, lazy: lazy, memo: memo, useCallback: useCallback, useContext: useContext, useEffect: useEffect, useImperativeHandle: useImperativeHandle, useDebugValue: useDebugValue, useLayoutEffect: useLayoutEffect, useMemo: useMemo, useReducer: useReducer, useRef: useRef, useState: useState, Fragment: REACT_FRAGMENT_TYPE, StrictMode: REACT_STRICT_MODE_TYPE, Suspense: REACT_SUSPENSE_TYPE, createElement: createElementWithValidation, cloneElement: cloneElementWithValidation, createFactory: createFactoryWithValidation, isValidElement: isValidElement, version: ReactVersion, unstable_ConcurrentMode: REACT_CONCURRENT_MODE_TYPE, unstable_Profiler: REACT_PROFILER_TYPE, __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: ReactSharedInternals }; // Note: some APIs are added with feature flags. // Make sure that stable builds for open source // don't modify the React object to avoid deopts. // Also let's not expose their names in stable builds. if (enableStableConcurrentModeAPIs) { React.ConcurrentMode = REACT_CONCURRENT_MODE_TYPE; React.Profiler = REACT_PROFILER_TYPE; React.unstable_ConcurrentMode = undefined; React.unstable_Profiler = undefined; } var React$2 = Object.freeze({ default: React }); var React$3 = ( React$2 && React ) || React$2; // TODO: decide on the top-level export form. // This is hacky but makes it work with both Rollup and Jest. var react = React$3.default || React$3; module.exports = react; })(); } }).call(this,require('_process')) },{"_process":405,"object-assign":402,"prop-types/checkPropTypes":406}],416:[function(require,module,exports){ /** @license React v16.8.6 * react.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict';var k=require("object-assign"),n="function"===typeof Symbol&&Symbol.for,p=n?Symbol.for("react.element"):60103,q=n?Symbol.for("react.portal"):60106,r=n?Symbol.for("react.fragment"):60107,t=n?Symbol.for("react.strict_mode"):60108,u=n?Symbol.for("react.profiler"):60114,v=n?Symbol.for("react.provider"):60109,w=n?Symbol.for("react.context"):60110,x=n?Symbol.for("react.concurrent_mode"):60111,y=n?Symbol.for("react.forward_ref"):60112,z=n?Symbol.for("react.suspense"):60113,aa=n?Symbol.for("react.memo"): 60115,ba=n?Symbol.for("react.lazy"):60116,A="function"===typeof Symbol&&Symbol.iterator;function ca(a,b,d,c,e,g,h,f){if(!a){a=void 0;if(void 0===b)a=Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var l=[d,c,e,g,h,f],m=0;a=Error(b.replace(/%s/g,function(){return l[m++]}));a.name="Invariant Violation"}a.framesToPop=1;throw a;}} function B(a){for(var b=arguments.length-1,d="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=0;c<b;c++)d+="&args[]="+encodeURIComponent(arguments[c+1]);ca(!1,"Minified React error #"+a+"; visit %s for the full message or use the non-minified dev environment for full errors and additional helpful warnings. ",d)}var C={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},D={}; function E(a,b,d){this.props=a;this.context=b;this.refs=D;this.updater=d||C}E.prototype.isReactComponent={};E.prototype.setState=function(a,b){"object"!==typeof a&&"function"!==typeof a&&null!=a?B("85"):void 0;this.updater.enqueueSetState(this,a,b,"setState")};E.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,"forceUpdate")};function F(){}F.prototype=E.prototype;function G(a,b,d){this.props=a;this.context=b;this.refs=D;this.updater=d||C}var H=G.prototype=new F; H.constructor=G;k(H,E.prototype);H.isPureReactComponent=!0;var I={current:null},J={current:null},K=Object.prototype.hasOwnProperty,L={key:!0,ref:!0,__self:!0,__source:!0}; function M(a,b,d){var c=void 0,e={},g=null,h=null;if(null!=b)for(c in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(g=""+b.key),b)K.call(b,c)&&!L.hasOwnProperty(c)&&(e[c]=b[c]);var f=arguments.length-2;if(1===f)e.children=d;else if(1<f){for(var l=Array(f),m=0;m<f;m++)l[m]=arguments[m+2];e.children=l}if(a&&a.defaultProps)for(c in f=a.defaultProps,f)void 0===e[c]&&(e[c]=f[c]);return{$$typeof:p,type:a,key:g,ref:h,props:e,_owner:J.current}} function da(a,b){return{$$typeof:p,type:a.type,key:b,ref:a.ref,props:a.props,_owner:a._owner}}function N(a){return"object"===typeof a&&null!==a&&a.$$typeof===p}function escape(a){var b={"=":"=0",":":"=2"};return"$"+(""+a).replace(/[=:]/g,function(a){return b[a]})}var O=/\/+/g,P=[];function Q(a,b,d,c){if(P.length){var e=P.pop();e.result=a;e.keyPrefix=b;e.func=d;e.context=c;e.count=0;return e}return{result:a,keyPrefix:b,func:d,context:c,count:0}} function R(a){a.result=null;a.keyPrefix=null;a.func=null;a.context=null;a.count=0;10>P.length&&P.push(a)} function S(a,b,d,c){var e=typeof a;if("undefined"===e||"boolean"===e)a=null;var g=!1;if(null===a)g=!0;else switch(e){case "string":case "number":g=!0;break;case "object":switch(a.$$typeof){case p:case q:g=!0}}if(g)return d(c,a,""===b?"."+T(a,0):b),1;g=0;b=""===b?".":b+":";if(Array.isArray(a))for(var h=0;h<a.length;h++){e=a[h];var f=b+T(e,h);g+=S(e,f,d,c)}else if(null===a||"object"!==typeof a?f=null:(f=A&&a[A]||a["@@iterator"],f="function"===typeof f?f:null),"function"===typeof f)for(a=f.call(a),h= 0;!(e=a.next()).done;)e=e.value,f=b+T(e,h++),g+=S(e,f,d,c);else"object"===e&&(d=""+a,B("31","[object Object]"===d?"object with keys {"+Object.keys(a).join(", ")+"}":d,""));return g}function U(a,b,d){return null==a?0:S(a,"",b,d)}function T(a,b){return"object"===typeof a&&null!==a&&null!=a.key?escape(a.key):b.toString(36)}function ea(a,b){a.func.call(a.context,b,a.count++)} function fa(a,b,d){var c=a.result,e=a.keyPrefix;a=a.func.call(a.context,b,a.count++);Array.isArray(a)?V(a,c,d,function(a){return a}):null!=a&&(N(a)&&(a=da(a,e+(!a.key||b&&b.key===a.key?"":(""+a.key).replace(O,"$&/")+"/")+d)),c.push(a))}function V(a,b,d,c,e){var g="";null!=d&&(g=(""+d).replace(O,"$&/")+"/");b=Q(b,g,c,e);U(a,fa,b);R(b)}function W(){var a=I.current;null===a?B("321"):void 0;return a} var X={Children:{map:function(a,b,d){if(null==a)return a;var c=[];V(a,c,null,b,d);return c},forEach:function(a,b,d){if(null==a)return a;b=Q(null,null,b,d);U(a,ea,b);R(b)},count:function(a){return U(a,function(){return null},null)},toArray:function(a){var b=[];V(a,b,null,function(a){return a});return b},only:function(a){N(a)?void 0:B("143");return a}},createRef:function(){return{current:null}},Component:E,PureComponent:G,createContext:function(a,b){void 0===b&&(b=null);a={$$typeof:w,_calculateChangedBits:b, _currentValue:a,_currentValue2:a,_threadCount:0,Provider:null,Consumer:null};a.Provider={$$typeof:v,_context:a};return a.Consumer=a},forwardRef:function(a){return{$$typeof:y,render:a}},lazy:function(a){return{$$typeof:ba,_ctor:a,_status:-1,_result:null}},memo:function(a,b){return{$$typeof:aa,type:a,compare:void 0===b?null:b}},useCallback:function(a,b){return W().useCallback(a,b)},useContext:function(a,b){return W().useContext(a,b)},useEffect:function(a,b){return W().useEffect(a,b)},useImperativeHandle:function(a, b,d){return W().useImperativeHandle(a,b,d)},useDebugValue:function(){},useLayoutEffect:function(a,b){return W().useLayoutEffect(a,b)},useMemo:function(a,b){return W().useMemo(a,b)},useReducer:function(a,b,d){return W().useReducer(a,b,d)},useRef:function(a){return W().useRef(a)},useState:function(a){return W().useState(a)},Fragment:r,StrictMode:t,Suspense:z,createElement:M,cloneElement:function(a,b,d){null===a||void 0===a?B("267",a):void 0;var c=void 0,e=k({},a.props),g=a.key,h=a.ref,f=a._owner;if(null!= b){void 0!==b.ref&&(h=b.ref,f=J.current);void 0!==b.key&&(g=""+b.key);var l=void 0;a.type&&a.type.defaultProps&&(l=a.type.defaultProps);for(c in b)K.call(b,c)&&!L.hasOwnProperty(c)&&(e[c]=void 0===b[c]&&void 0!==l?l[c]:b[c])}c=arguments.length-2;if(1===c)e.children=d;else if(1<c){l=Array(c);for(var m=0;m<c;m++)l[m]=arguments[m+2];e.children=l}return{$$typeof:p,type:a.type,key:g,ref:h,props:e,_owner:f}},createFactory:function(a){var b=M.bind(null,a);b.type=a;return b},isValidElement:N,version:"16.8.6", unstable_ConcurrentMode:x,unstable_Profiler:u,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:{ReactCurrentDispatcher:I,ReactCurrentOwner:J,assign:k}},Y={default:X},Z=Y&&X||Y;module.exports=Z.default||Z; },{"object-assign":402}],417:[function(require,module,exports){ (function (process){ 'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/react.production.min.js'); } else { module.exports = require('./cjs/react.development.js'); } }).call(this,require('_process')) },{"./cjs/react.development.js":415,"./cjs/react.production.min.js":416,"_process":405}],418:[function(require,module,exports){ module.exports = require('./lib/_stream_duplex.js'); },{"./lib/_stream_duplex.js":419}],419:[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 pna = require('process-nextick-args'); /*</replacement>*/ /*<replacement>*/ var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { keys.push(key); }return keys; }; /*</replacement>*/ module.exports = Duplex; /*<replacement>*/ var util = 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 () { 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 () { if (this._readableState === undefined || this._writableState === undefined) { return false; } return this._readableState.destroyed && this._writableState.destroyed; }, set: function (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":421,"./_stream_writable":423,"core-util-is":190,"inherits":203,"process-nextick-args":404}],420:[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'; module.exports = PassThrough; var Transform = require('./_stream_transform'); /*<replacement>*/ var util = 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":422,"core-util-is":190,"inherits":203}],421:[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 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 (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 = 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 () {}; } /*</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 () { if (this._readableState === undefined) { return false; } return this._readableState.destroyed; }, set: function (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 && Object.getPrototypeOf(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 () { 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":419,"./internal/streams/BufferList":424,"./internal/streams/destroy":425,"./internal/streams/stream":426,"_process":405,"core-util-is":190,"events":199,"inherits":203,"isarray":205,"process-nextick-args":404,"safe-buffer":431,"string_decoder/":453,"util":180}],422:[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'; module.exports = Transform; var Duplex = require('./_stream_duplex'); /*<replacement>*/ var util = 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":419,"core-util-is":190,"inherits":203}],423:[function(require,module,exports){ (function (process,global,setImmediate){ // 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 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 ? setImmediate : pna.nextTick; /*</replacement>*/ /*<replacement>*/ var Duplex; /*</replacement>*/ Writable.WritableState = WritableState; /*<replacement>*/ var util = 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 Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { realHasInstance = Function.prototype[Symbol.hasInstance]; Object.defineProperty(Writable, Symbol.hasInstance, { value: function (object) { if (realHasInstance.call(this, object)) return true; if (this !== Writable) return false; return object && object._writableState instanceof WritableState; } }); } else { realHasInstance = function (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 () { 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 () { if (this._writableState === undefined) { return false; } return this._writableState.destroyed; }, set: function (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 : {},require("timers").setImmediate) },{"./_stream_duplex":419,"./internal/streams/destroy":425,"./internal/streams/stream":426,"_process":405,"core-util-is":190,"inherits":203,"process-nextick-args":404,"safe-buffer":431,"timers":455,"util-deprecate":458}],424:[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":431,"util":180}],425:[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":404}],426:[function(require,module,exports){ module.exports = require('events').EventEmitter; },{"events":199}],427:[function(require,module,exports){ module.exports = require('./readable').PassThrough },{"./readable":428}],428:[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":419,"./lib/_stream_passthrough.js":420,"./lib/_stream_readable.js":421,"./lib/_stream_transform.js":422,"./lib/_stream_writable.js":423}],429:[function(require,module,exports){ module.exports = require('./readable').Transform },{"./readable":428}],430:[function(require,module,exports){ module.exports = require('./lib/_stream_writable.js'); },{"./lib/_stream_writable.js":423}],431:[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":182}],432:[function(require,module,exports){ (function (process){ /** @license React v0.13.6 * scheduler-tracing.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; if (process.env.NODE_ENV !== "production") { (function() { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); // Helps identify side effects in begin-phase lifecycle hooks and setState reducers: // In some cases, StrictMode should also double-render lifecycles. // This can be confusing for tests though, // And it can be bad for performance in production. // This feature flag can be used to control the behavior: // To preserve the "Pause on caught exceptions" behavior of the debugger, we // replay the begin phase of a failed component inside invokeGuardedCallback. // Warn about deprecated, async-unsafe lifecycles; relates to RFC #6: // Gather advanced timing metrics for Profiler subtrees. // Trace which interactions trigger each commit. var enableSchedulerTracing = true; // Only used in www builds. // TODO: true? Here it might just be false. // Only used in www builds. // Only used in www builds. // React Fire: prevent the value and checked attributes from syncing // with their related DOM properties // These APIs will no longer be "unstable" in the upcoming 16.7 release, // Control this behavior with a flag to support 16.6 minor releases in the meanwhile. var DEFAULT_THREAD_ID = 0; // Counters used to generate unique IDs. var interactionIDCounter = 0; var threadIDCounter = 0; // Set of currently traced interactions. // Interactions "stack"– // Meaning that newly traced interactions are appended to the previously active set. // When an interaction goes out of scope, the previous set (if any) is restored. exports.__interactionsRef = null; // Listener(s) to notify when interactions begin and end. exports.__subscriberRef = null; if (enableSchedulerTracing) { exports.__interactionsRef = { current: new Set() }; exports.__subscriberRef = { current: null }; } function unstable_clear(callback) { if (!enableSchedulerTracing) { return callback(); } var prevInteractions = exports.__interactionsRef.current; exports.__interactionsRef.current = new Set(); try { return callback(); } finally { exports.__interactionsRef.current = prevInteractions; } } function unstable_getCurrent() { if (!enableSchedulerTracing) { return null; } else { return exports.__interactionsRef.current; } } function unstable_getThreadID() { return ++threadIDCounter; } function unstable_trace(name, timestamp, callback) { var threadID = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : DEFAULT_THREAD_ID; if (!enableSchedulerTracing) { return callback(); } var interaction = { __count: 1, id: interactionIDCounter++, name: name, timestamp: timestamp }; var prevInteractions = exports.__interactionsRef.current; // Traced interactions should stack/accumulate. // To do that, clone the current interactions. // The previous set will be restored upon completion. var interactions = new Set(prevInteractions); interactions.add(interaction); exports.__interactionsRef.current = interactions; var subscriber = exports.__subscriberRef.current; var returnValue = void 0; try { if (subscriber !== null) { subscriber.onInteractionTraced(interaction); } } finally { try { if (subscriber !== null) { subscriber.onWorkStarted(interactions, threadID); } } finally { try { returnValue = callback(); } finally { exports.__interactionsRef.current = prevInteractions; try { if (subscriber !== null) { subscriber.onWorkStopped(interactions, threadID); } } finally { interaction.__count--; // If no async work was scheduled for this interaction, // Notify subscribers that it's completed. if (subscriber !== null && interaction.__count === 0) { subscriber.onInteractionScheduledWorkCompleted(interaction); } } } } } return returnValue; } function unstable_wrap(callback) { var threadID = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_THREAD_ID; if (!enableSchedulerTracing) { return callback; } var wrappedInteractions = exports.__interactionsRef.current; var subscriber = exports.__subscriberRef.current; if (subscriber !== null) { subscriber.onWorkScheduled(wrappedInteractions, threadID); } // Update the pending async work count for the current interactions. // Update after calling subscribers in case of error. wrappedInteractions.forEach(function (interaction) { interaction.__count++; }); var hasRun = false; function wrapped() { var prevInteractions = exports.__interactionsRef.current; exports.__interactionsRef.current = wrappedInteractions; subscriber = exports.__subscriberRef.current; try { var returnValue = void 0; try { if (subscriber !== null) { subscriber.onWorkStarted(wrappedInteractions, threadID); } } finally { try { returnValue = callback.apply(undefined, arguments); } finally { exports.__interactionsRef.current = prevInteractions; if (subscriber !== null) { subscriber.onWorkStopped(wrappedInteractions, threadID); } } } return returnValue; } finally { if (!hasRun) { // We only expect a wrapped function to be executed once, // But in the event that it's executed more than once– // Only decrement the outstanding interaction counts once. hasRun = true; // Update pending async counts for all wrapped interactions. // If this was the last scheduled async work for any of them, // Mark them as completed. wrappedInteractions.forEach(function (interaction) { interaction.__count--; if (subscriber !== null && interaction.__count === 0) { subscriber.onInteractionScheduledWorkCompleted(interaction); } }); } } } wrapped.cancel = function cancel() { subscriber = exports.__subscriberRef.current; try { if (subscriber !== null) { subscriber.onWorkCanceled(wrappedInteractions, threadID); } } finally { // Update pending async counts for all wrapped interactions. // If this was the last scheduled async work for any of them, // Mark them as completed. wrappedInteractions.forEach(function (interaction) { interaction.__count--; if (subscriber && interaction.__count === 0) { subscriber.onInteractionScheduledWorkCompleted(interaction); } }); } }; return wrapped; } var subscribers = null; if (enableSchedulerTracing) { subscribers = new Set(); } function unstable_subscribe(subscriber) { if (enableSchedulerTracing) { subscribers.add(subscriber); if (subscribers.size === 1) { exports.__subscriberRef.current = { onInteractionScheduledWorkCompleted: onInteractionScheduledWorkCompleted, onInteractionTraced: onInteractionTraced, onWorkCanceled: onWorkCanceled, onWorkScheduled: onWorkScheduled, onWorkStarted: onWorkStarted, onWorkStopped: onWorkStopped }; } } } function unstable_unsubscribe(subscriber) { if (enableSchedulerTracing) { subscribers.delete(subscriber); if (subscribers.size === 0) { exports.__subscriberRef.current = null; } } } function onInteractionTraced(interaction) { var didCatchError = false; var caughtError = null; subscribers.forEach(function (subscriber) { try { subscriber.onInteractionTraced(interaction); } catch (error) { if (!didCatchError) { didCatchError = true; caughtError = error; } } }); if (didCatchError) { throw caughtError; } } function onInteractionScheduledWorkCompleted(interaction) { var didCatchError = false; var caughtError = null; subscribers.forEach(function (subscriber) { try { subscriber.onInteractionScheduledWorkCompleted(interaction); } catch (error) { if (!didCatchError) { didCatchError = true; caughtError = error; } } }); if (didCatchError) { throw caughtError; } } function onWorkScheduled(interactions, threadID) { var didCatchError = false; var caughtError = null; subscribers.forEach(function (subscriber) { try { subscriber.onWorkScheduled(interactions, threadID); } catch (error) { if (!didCatchError) { didCatchError = true; caughtError = error; } } }); if (didCatchError) { throw caughtError; } } function onWorkStarted(interactions, threadID) { var didCatchError = false; var caughtError = null; subscribers.forEach(function (subscriber) { try { subscriber.onWorkStarted(interactions, threadID); } catch (error) { if (!didCatchError) { didCatchError = true; caughtError = error; } } }); if (didCatchError) { throw caughtError; } } function onWorkStopped(interactions, threadID) { var didCatchError = false; var caughtError = null; subscribers.forEach(function (subscriber) { try { subscriber.onWorkStopped(interactions, threadID); } catch (error) { if (!didCatchError) { didCatchError = true; caughtError = error; } } }); if (didCatchError) { throw caughtError; } } function onWorkCanceled(interactions, threadID) { var didCatchError = false; var caughtError = null; subscribers.forEach(function (subscriber) { try { subscriber.onWorkCanceled(interactions, threadID); } catch (error) { if (!didCatchError) { didCatchError = true; caughtError = error; } } }); if (didCatchError) { throw caughtError; } } exports.unstable_clear = unstable_clear; exports.unstable_getCurrent = unstable_getCurrent; exports.unstable_getThreadID = unstable_getThreadID; exports.unstable_trace = unstable_trace; exports.unstable_wrap = unstable_wrap; exports.unstable_subscribe = unstable_subscribe; exports.unstable_unsubscribe = unstable_unsubscribe; })(); } }).call(this,require('_process')) },{"_process":405}],433:[function(require,module,exports){ /** @license React v0.13.6 * scheduler-tracing.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict';Object.defineProperty(exports,"__esModule",{value:!0});var b=0;exports.__interactionsRef=null;exports.__subscriberRef=null;exports.unstable_clear=function(a){return a()};exports.unstable_getCurrent=function(){return null};exports.unstable_getThreadID=function(){return++b};exports.unstable_trace=function(a,d,c){return c()};exports.unstable_wrap=function(a){return a};exports.unstable_subscribe=function(){};exports.unstable_unsubscribe=function(){}; },{}],434:[function(require,module,exports){ (function (process,global){ /** @license React v0.13.6 * scheduler.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; if (process.env.NODE_ENV !== "production") { (function() { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var enableSchedulerDebugging = false; /* eslint-disable no-var */ // TODO: Use symbols? var ImmediatePriority = 1; var UserBlockingPriority = 2; var NormalPriority = 3; var LowPriority = 4; var IdlePriority = 5; // Max 31 bit integer. The max integer size in V8 for 32-bit systems. // Math.pow(2, 30) - 1 // 0b111111111111111111111111111111 var maxSigned31BitInt = 1073741823; // Times out immediately var IMMEDIATE_PRIORITY_TIMEOUT = -1; // Eventually times out var USER_BLOCKING_PRIORITY = 250; var NORMAL_PRIORITY_TIMEOUT = 5000; var LOW_PRIORITY_TIMEOUT = 10000; // Never times out var IDLE_PRIORITY = maxSigned31BitInt; // Callbacks are stored as a circular, doubly linked list. var firstCallbackNode = null; var currentDidTimeout = false; // Pausing the scheduler is useful for debugging. var isSchedulerPaused = false; var currentPriorityLevel = NormalPriority; var currentEventStartTime = -1; var currentExpirationTime = -1; // This is set when a callback is being executed, to prevent re-entrancy. var isExecutingCallback = false; var isHostCallbackScheduled = false; var hasNativePerformanceNow = typeof performance === 'object' && typeof performance.now === 'function'; function ensureHostCallbackIsScheduled() { if (isExecutingCallback) { // Don't schedule work yet; wait until the next time we yield. return; } // Schedule the host callback using the earliest expiration in the list. var expirationTime = firstCallbackNode.expirationTime; if (!isHostCallbackScheduled) { isHostCallbackScheduled = true; } else { // Cancel the existing host callback. cancelHostCallback(); } requestHostCallback(flushWork, expirationTime); } function flushFirstCallback() { var flushedNode = firstCallbackNode; // Remove the node from the list before calling the callback. That way the // list is in a consistent state even if the callback throws. var next = firstCallbackNode.next; if (firstCallbackNode === next) { // This is the last callback in the list. firstCallbackNode = null; next = null; } else { var lastCallbackNode = firstCallbackNode.previous; firstCallbackNode = lastCallbackNode.next = next; next.previous = lastCallbackNode; } flushedNode.next = flushedNode.previous = null; // Now it's safe to call the callback. var callback = flushedNode.callback; var expirationTime = flushedNode.expirationTime; var priorityLevel = flushedNode.priorityLevel; var previousPriorityLevel = currentPriorityLevel; var previousExpirationTime = currentExpirationTime; currentPriorityLevel = priorityLevel; currentExpirationTime = expirationTime; var continuationCallback; try { continuationCallback = callback(); } finally { currentPriorityLevel = previousPriorityLevel; currentExpirationTime = previousExpirationTime; } // A callback may return a continuation. The continuation should be scheduled // with the same priority and expiration as the just-finished callback. if (typeof continuationCallback === 'function') { var continuationNode = { callback: continuationCallback, priorityLevel: priorityLevel, expirationTime: expirationTime, next: null, previous: null }; // Insert the new callback into the list, sorted by its expiration. This is // almost the same as the code in `scheduleCallback`, except the callback // is inserted into the list *before* callbacks of equal expiration instead // of after. if (firstCallbackNode === null) { // This is the first callback in the list. firstCallbackNode = continuationNode.next = continuationNode.previous = continuationNode; } else { var nextAfterContinuation = null; var node = firstCallbackNode; do { if (node.expirationTime >= expirationTime) { // This callback expires at or after the continuation. We will insert // the continuation *before* this callback. nextAfterContinuation = node; break; } node = node.next; } while (node !== firstCallbackNode); if (nextAfterContinuation === null) { // No equal or lower priority callback was found, which means the new // callback is the lowest priority callback in the list. nextAfterContinuation = firstCallbackNode; } else if (nextAfterContinuation === firstCallbackNode) { // The new callback is the highest priority callback in the list. firstCallbackNode = continuationNode; ensureHostCallbackIsScheduled(); } var previous = nextAfterContinuation.previous; previous.next = nextAfterContinuation.previous = continuationNode; continuationNode.next = nextAfterContinuation; continuationNode.previous = previous; } } } function flushImmediateWork() { if ( // Confirm we've exited the outer most event handler currentEventStartTime === -1 && firstCallbackNode !== null && firstCallbackNode.priorityLevel === ImmediatePriority) { isExecutingCallback = true; try { do { flushFirstCallback(); } while ( // Keep flushing until there are no more immediate callbacks firstCallbackNode !== null && firstCallbackNode.priorityLevel === ImmediatePriority); } finally { isExecutingCallback = false; if (firstCallbackNode !== null) { // There's still work remaining. Request another callback. ensureHostCallbackIsScheduled(); } else { isHostCallbackScheduled = false; } } } } function flushWork(didTimeout) { // Exit right away if we're currently paused if (enableSchedulerDebugging && isSchedulerPaused) { return; } isExecutingCallback = true; var previousDidTimeout = currentDidTimeout; currentDidTimeout = didTimeout; try { if (didTimeout) { // Flush all the expired callbacks without yielding. while (firstCallbackNode !== null && !(enableSchedulerDebugging && isSchedulerPaused)) { // TODO Wrap in feature flag // Read the current time. Flush all the callbacks that expire at or // earlier than that time. Then read the current time again and repeat. // This optimizes for as few performance.now calls as possible. var currentTime = exports.unstable_now(); if (firstCallbackNode.expirationTime <= currentTime) { do { flushFirstCallback(); } while (firstCallbackNode !== null && firstCallbackNode.expirationTime <= currentTime && !(enableSchedulerDebugging && isSchedulerPaused)); continue; } break; } } else { // Keep flushing callbacks until we run out of time in the frame. if (firstCallbackNode !== null) { do { if (enableSchedulerDebugging && isSchedulerPaused) { break; } flushFirstCallback(); } while (firstCallbackNode !== null && !shouldYieldToHost()); } } } finally { isExecutingCallback = false; currentDidTimeout = previousDidTimeout; if (firstCallbackNode !== null) { // There's still work remaining. Request another callback. ensureHostCallbackIsScheduled(); } else { isHostCallbackScheduled = false; } // Before exiting, flush all the immediate work that was scheduled. flushImmediateWork(); } } function unstable_runWithPriority(priorityLevel, eventHandler) { switch (priorityLevel) { case ImmediatePriority: case UserBlockingPriority: case NormalPriority: case LowPriority: case IdlePriority: break; default: priorityLevel = NormalPriority; } var previousPriorityLevel = currentPriorityLevel; var previousEventStartTime = currentEventStartTime; currentPriorityLevel = priorityLevel; currentEventStartTime = exports.unstable_now(); try { return eventHandler(); } finally { currentPriorityLevel = previousPriorityLevel; currentEventStartTime = previousEventStartTime; // Before exiting, flush all the immediate work that was scheduled. flushImmediateWork(); } } function unstable_next(eventHandler) { var priorityLevel = void 0; switch (currentPriorityLevel) { case ImmediatePriority: case UserBlockingPriority: case NormalPriority: // Shift down to normal priority priorityLevel = NormalPriority; break; default: // Anything lower than normal priority should remain at the current level. priorityLevel = currentPriorityLevel; break; } var previousPriorityLevel = currentPriorityLevel; var previousEventStartTime = currentEventStartTime; currentPriorityLevel = priorityLevel; currentEventStartTime = exports.unstable_now(); try { return eventHandler(); } finally { currentPriorityLevel = previousPriorityLevel; currentEventStartTime = previousEventStartTime; // Before exiting, flush all the immediate work that was scheduled. flushImmediateWork(); } } function unstable_wrapCallback(callback) { var parentPriorityLevel = currentPriorityLevel; return function () { // This is a fork of runWithPriority, inlined for performance. var previousPriorityLevel = currentPriorityLevel; var previousEventStartTime = currentEventStartTime; currentPriorityLevel = parentPriorityLevel; currentEventStartTime = exports.unstable_now(); try { return callback.apply(this, arguments); } finally { currentPriorityLevel = previousPriorityLevel; currentEventStartTime = previousEventStartTime; flushImmediateWork(); } }; } function unstable_scheduleCallback(callback, deprecated_options) { var startTime = currentEventStartTime !== -1 ? currentEventStartTime : exports.unstable_now(); var expirationTime; if (typeof deprecated_options === 'object' && deprecated_options !== null && typeof deprecated_options.timeout === 'number') { // FIXME: Remove this branch once we lift expiration times out of React. expirationTime = startTime + deprecated_options.timeout; } else { switch (currentPriorityLevel) { case ImmediatePriority: expirationTime = startTime + IMMEDIATE_PRIORITY_TIMEOUT; break; case UserBlockingPriority: expirationTime = startTime + USER_BLOCKING_PRIORITY; break; case IdlePriority: expirationTime = startTime + IDLE_PRIORITY; break; case LowPriority: expirationTime = startTime + LOW_PRIORITY_TIMEOUT; break; case NormalPriority: default: expirationTime = startTime + NORMAL_PRIORITY_TIMEOUT; } } var newNode = { callback: callback, priorityLevel: currentPriorityLevel, expirationTime: expirationTime, next: null, previous: null }; // Insert the new callback into the list, ordered first by expiration, then // by insertion. So the new callback is inserted any other callback with // equal expiration. if (firstCallbackNode === null) { // This is the first callback in the list. firstCallbackNode = newNode.next = newNode.previous = newNode; ensureHostCallbackIsScheduled(); } else { var next = null; var node = firstCallbackNode; do { if (node.expirationTime > expirationTime) { // The new callback expires before this one. next = node; break; } node = node.next; } while (node !== firstCallbackNode); if (next === null) { // No callback with a later expiration was found, which means the new // callback has the latest expiration in the list. next = firstCallbackNode; } else if (next === firstCallbackNode) { // The new callback has the earliest expiration in the entire list. firstCallbackNode = newNode; ensureHostCallbackIsScheduled(); } var previous = next.previous; previous.next = next.previous = newNode; newNode.next = next; newNode.previous = previous; } return newNode; } function unstable_pauseExecution() { isSchedulerPaused = true; } function unstable_continueExecution() { isSchedulerPaused = false; if (firstCallbackNode !== null) { ensureHostCallbackIsScheduled(); } } function unstable_getFirstCallbackNode() { return firstCallbackNode; } function unstable_cancelCallback(callbackNode) { var next = callbackNode.next; if (next === null) { // Already cancelled. return; } if (next === callbackNode) { // This is the only scheduled callback. Clear the list. firstCallbackNode = null; } else { // Remove the callback from its position in the list. if (callbackNode === firstCallbackNode) { firstCallbackNode = next; } var previous = callbackNode.previous; previous.next = next; next.previous = previous; } callbackNode.next = callbackNode.previous = null; } function unstable_getCurrentPriorityLevel() { return currentPriorityLevel; } function unstable_shouldYield() { return !currentDidTimeout && (firstCallbackNode !== null && firstCallbackNode.expirationTime < currentExpirationTime || shouldYieldToHost()); } // The remaining code is essentially a polyfill for requestIdleCallback. It // works by scheduling a requestAnimationFrame, storing the time for the start // of the frame, then scheduling a postMessage which gets scheduled after paint. // Within the postMessage handler do as much work as possible until time + frame // rate. By separating the idle call into a separate event tick we ensure that // layout, paint and other browser work is counted against the available time. // The frame rate is dynamically adjusted. // We capture a local reference to any global, in case it gets polyfilled after // this module is initially evaluated. We want to be using a // consistent implementation. var localDate = Date; // This initialization code may run even on server environments if a component // just imports ReactDOM (e.g. for findDOMNode). Some environments might not // have setTimeout or clearTimeout. However, we always expect them to be defined // on the client. https://github.com/facebook/react/pull/13088 var localSetTimeout = typeof setTimeout === 'function' ? setTimeout : undefined; var localClearTimeout = typeof clearTimeout === 'function' ? clearTimeout : undefined; // We don't expect either of these to necessarily be defined, but we will error // later if they are missing on the client. var localRequestAnimationFrame = typeof requestAnimationFrame === 'function' ? requestAnimationFrame : undefined; var localCancelAnimationFrame = typeof cancelAnimationFrame === 'function' ? cancelAnimationFrame : undefined; // requestAnimationFrame does not run when the tab is in the background. If // we're backgrounded we prefer for that work to happen so that the page // continues to load in the background. So we also schedule a 'setTimeout' as // a fallback. // TODO: Need a better heuristic for backgrounded work. var ANIMATION_FRAME_TIMEOUT = 100; var rAFID; var rAFTimeoutID; var requestAnimationFrameWithTimeout = function (callback) { // schedule rAF and also a setTimeout rAFID = localRequestAnimationFrame(function (timestamp) { // cancel the setTimeout localClearTimeout(rAFTimeoutID); callback(timestamp); }); rAFTimeoutID = localSetTimeout(function () { // cancel the requestAnimationFrame localCancelAnimationFrame(rAFID); callback(exports.unstable_now()); }, ANIMATION_FRAME_TIMEOUT); }; if (hasNativePerformanceNow) { var Performance = performance; exports.unstable_now = function () { return Performance.now(); }; } else { exports.unstable_now = function () { return localDate.now(); }; } var requestHostCallback; var cancelHostCallback; var shouldYieldToHost; var globalValue = null; if (typeof window !== 'undefined') { globalValue = window; } else if (typeof global !== 'undefined') { globalValue = global; } if (globalValue && globalValue._schedMock) { // Dynamic injection, only for testing purposes. var globalImpl = globalValue._schedMock; requestHostCallback = globalImpl[0]; cancelHostCallback = globalImpl[1]; shouldYieldToHost = globalImpl[2]; exports.unstable_now = globalImpl[3]; } else if ( // If Scheduler runs in a non-DOM environment, it falls back to a naive // implementation using setTimeout. typeof window === 'undefined' || // Check if MessageChannel is supported, too. typeof MessageChannel !== 'function') { // If this accidentally gets imported in a non-browser environment, e.g. JavaScriptCore, // fallback to a naive implementation. var _callback = null; var _flushCallback = function (didTimeout) { if (_callback !== null) { try { _callback(didTimeout); } finally { _callback = null; } } }; requestHostCallback = function (cb, ms) { if (_callback !== null) { // Protect against re-entrancy. setTimeout(requestHostCallback, 0, cb); } else { _callback = cb; setTimeout(_flushCallback, 0, false); } }; cancelHostCallback = function () { _callback = null; }; shouldYieldToHost = function () { return false; }; } else { if (typeof console !== 'undefined') { // TODO: Remove fb.me link if (typeof localRequestAnimationFrame !== 'function') { console.error("This browser doesn't support requestAnimationFrame. " + 'Make sure that you load a ' + 'polyfill in older browsers. https://fb.me/react-polyfills'); } if (typeof localCancelAnimationFrame !== 'function') { console.error("This browser doesn't support cancelAnimationFrame. " + 'Make sure that you load a ' + 'polyfill in older browsers. https://fb.me/react-polyfills'); } } var scheduledHostCallback = null; var isMessageEventScheduled = false; var timeoutTime = -1; var isAnimationFrameScheduled = false; var isFlushingHostCallback = false; var frameDeadline = 0; // We start out assuming that we run at 30fps but then the heuristic tracking // will adjust this value to a faster fps if we get more frequent animation // frames. var previousFrameTime = 33; var activeFrameTime = 33; shouldYieldToHost = function () { return frameDeadline <= exports.unstable_now(); }; // We use the postMessage trick to defer idle work until after the repaint. var channel = new MessageChannel(); var port = channel.port2; channel.port1.onmessage = function (event) { isMessageEventScheduled = false; var prevScheduledCallback = scheduledHostCallback; var prevTimeoutTime = timeoutTime; scheduledHostCallback = null; timeoutTime = -1; var currentTime = exports.unstable_now(); var didTimeout = false; if (frameDeadline - currentTime <= 0) { // There's no time left in this idle period. Check if the callback has // a timeout and whether it's been exceeded. if (prevTimeoutTime !== -1 && prevTimeoutTime <= currentTime) { // Exceeded the timeout. Invoke the callback even though there's no // time left. didTimeout = true; } else { // No timeout. if (!isAnimationFrameScheduled) { // Schedule another animation callback so we retry later. isAnimationFrameScheduled = true; requestAnimationFrameWithTimeout(animationTick); } // Exit without invoking the callback. scheduledHostCallback = prevScheduledCallback; timeoutTime = prevTimeoutTime; return; } } if (prevScheduledCallback !== null) { isFlushingHostCallback = true; try { prevScheduledCallback(didTimeout); } finally { isFlushingHostCallback = false; } } }; var animationTick = function (rafTime) { if (scheduledHostCallback !== null) { // Eagerly schedule the next animation callback at the beginning of the // frame. If the scheduler queue is not empty at the end of the frame, it // will continue flushing inside that callback. If the queue *is* empty, // then it will exit immediately. Posting the callback at the start of the // frame ensures it's fired within the earliest possible frame. If we // waited until the end of the frame to post the callback, we risk the // browser skipping a frame and not firing the callback until the frame // after that. requestAnimationFrameWithTimeout(animationTick); } else { // No pending work. Exit. isAnimationFrameScheduled = false; return; } var nextFrameTime = rafTime - frameDeadline + activeFrameTime; if (nextFrameTime < activeFrameTime && previousFrameTime < activeFrameTime) { if (nextFrameTime < 8) { // Defensive coding. We don't support higher frame rates than 120hz. // If the calculated frame time gets lower than 8, it is probably a bug. nextFrameTime = 8; } // If one frame goes long, then the next one can be short to catch up. // If two frames are short in a row, then that's an indication that we // actually have a higher frame rate than what we're currently optimizing. // We adjust our heuristic dynamically accordingly. For example, if we're // running on 120hz display or 90hz VR display. // Take the max of the two in case one of them was an anomaly due to // missed frame deadlines. activeFrameTime = nextFrameTime < previousFrameTime ? previousFrameTime : nextFrameTime; } else { previousFrameTime = nextFrameTime; } frameDeadline = rafTime + activeFrameTime; if (!isMessageEventScheduled) { isMessageEventScheduled = true; port.postMessage(undefined); } }; requestHostCallback = function (callback, absoluteTimeout) { scheduledHostCallback = callback; timeoutTime = absoluteTimeout; if (isFlushingHostCallback || absoluteTimeout < 0) { // Don't wait for the next frame. Continue working ASAP, in a new event. port.postMessage(undefined); } else if (!isAnimationFrameScheduled) { // If rAF didn't already schedule one, we need to schedule a frame. // TODO: If this rAF doesn't materialize because the browser throttles, we // might want to still have setTimeout trigger rIC as a backup to ensure // that we keep performing work. isAnimationFrameScheduled = true; requestAnimationFrameWithTimeout(animationTick); } }; cancelHostCallback = function () { scheduledHostCallback = null; isMessageEventScheduled = false; timeoutTime = -1; }; } exports.unstable_ImmediatePriority = ImmediatePriority; exports.unstable_UserBlockingPriority = UserBlockingPriority; exports.unstable_NormalPriority = NormalPriority; exports.unstable_IdlePriority = IdlePriority; exports.unstable_LowPriority = LowPriority; exports.unstable_runWithPriority = unstable_runWithPriority; exports.unstable_next = unstable_next; exports.unstable_scheduleCallback = unstable_scheduleCallback; exports.unstable_cancelCallback = unstable_cancelCallback; exports.unstable_wrapCallback = unstable_wrapCallback; exports.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel; exports.unstable_shouldYield = unstable_shouldYield; exports.unstable_continueExecution = unstable_continueExecution; exports.unstable_pauseExecution = unstable_pauseExecution; exports.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode; })(); } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":405}],435:[function(require,module,exports){ (function (global){ /** @license React v0.13.6 * scheduler.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict';Object.defineProperty(exports,"__esModule",{value:!0});var d=null,e=!1,g=3,k=-1,l=-1,m=!1,n=!1;function p(){if(!m){var a=d.expirationTime;n?q():n=!0;r(t,a)}} function u(){var a=d,b=d.next;if(d===b)d=null;else{var c=d.previous;d=c.next=b;b.previous=c}a.next=a.previous=null;c=a.callback;b=a.expirationTime;a=a.priorityLevel;var f=g,Q=l;g=a;l=b;try{var h=c()}finally{g=f,l=Q}if("function"===typeof h)if(h={callback:h,priorityLevel:a,expirationTime:b,next:null,previous:null},null===d)d=h.next=h.previous=h;else{c=null;a=d;do{if(a.expirationTime>=b){c=a;break}a=a.next}while(a!==d);null===c?c=d:c===d&&(d=h,p());b=c.previous;b.next=c.previous=h;h.next=c;h.previous= b}}function v(){if(-1===k&&null!==d&&1===d.priorityLevel){m=!0;try{do u();while(null!==d&&1===d.priorityLevel)}finally{m=!1,null!==d?p():n=!1}}}function t(a){m=!0;var b=e;e=a;try{if(a)for(;null!==d;){var c=exports.unstable_now();if(d.expirationTime<=c){do u();while(null!==d&&d.expirationTime<=c)}else break}else if(null!==d){do u();while(null!==d&&!w())}}finally{m=!1,e=b,null!==d?p():n=!1,v()}} var x=Date,y="function"===typeof setTimeout?setTimeout:void 0,z="function"===typeof clearTimeout?clearTimeout:void 0,A="function"===typeof requestAnimationFrame?requestAnimationFrame:void 0,B="function"===typeof cancelAnimationFrame?cancelAnimationFrame:void 0,C,D;function E(a){C=A(function(b){z(D);a(b)});D=y(function(){B(C);a(exports.unstable_now())},100)} if("object"===typeof performance&&"function"===typeof performance.now){var F=performance;exports.unstable_now=function(){return F.now()}}else exports.unstable_now=function(){return x.now()};var r,q,w,G=null;"undefined"!==typeof window?G=window:"undefined"!==typeof global&&(G=global); if(G&&G._schedMock){var H=G._schedMock;r=H[0];q=H[1];w=H[2];exports.unstable_now=H[3]}else if("undefined"===typeof window||"function"!==typeof MessageChannel){var I=null,J=function(a){if(null!==I)try{I(a)}finally{I=null}};r=function(a){null!==I?setTimeout(r,0,a):(I=a,setTimeout(J,0,!1))};q=function(){I=null};w=function(){return!1}}else{"undefined"!==typeof console&&("function"!==typeof A&&console.error("This browser doesn't support requestAnimationFrame. Make sure that you load a polyfill in older browsers. https://fb.me/react-polyfills"), "function"!==typeof B&&console.error("This browser doesn't support cancelAnimationFrame. Make sure that you load a polyfill in older browsers. https://fb.me/react-polyfills"));var K=null,L=!1,M=-1,N=!1,O=!1,P=0,R=33,S=33;w=function(){return P<=exports.unstable_now()};var T=new MessageChannel,U=T.port2;T.port1.onmessage=function(){L=!1;var a=K,b=M;K=null;M=-1;var c=exports.unstable_now(),f=!1;if(0>=P-c)if(-1!==b&&b<=c)f=!0;else{N||(N=!0,E(V));K=a;M=b;return}if(null!==a){O=!0;try{a(f)}finally{O=!1}}}; var V=function(a){if(null!==K){E(V);var b=a-P+S;b<S&&R<S?(8>b&&(b=8),S=b<R?R:b):R=b;P=a+S;L||(L=!0,U.postMessage(void 0))}else N=!1};r=function(a,b){K=a;M=b;O||0>b?U.postMessage(void 0):N||(N=!0,E(V))};q=function(){K=null;L=!1;M=-1}}exports.unstable_ImmediatePriority=1;exports.unstable_UserBlockingPriority=2;exports.unstable_NormalPriority=3;exports.unstable_IdlePriority=5;exports.unstable_LowPriority=4; exports.unstable_runWithPriority=function(a,b){switch(a){case 1:case 2:case 3:case 4:case 5:break;default:a=3}var c=g,f=k;g=a;k=exports.unstable_now();try{return b()}finally{g=c,k=f,v()}};exports.unstable_next=function(a){switch(g){case 1:case 2:case 3:var b=3;break;default:b=g}var c=g,f=k;g=b;k=exports.unstable_now();try{return a()}finally{g=c,k=f,v()}}; exports.unstable_scheduleCallback=function(a,b){var c=-1!==k?k:exports.unstable_now();if("object"===typeof b&&null!==b&&"number"===typeof b.timeout)b=c+b.timeout;else switch(g){case 1:b=c+-1;break;case 2:b=c+250;break;case 5:b=c+1073741823;break;case 4:b=c+1E4;break;default:b=c+5E3}a={callback:a,priorityLevel:g,expirationTime:b,next:null,previous:null};if(null===d)d=a.next=a.previous=a,p();else{c=null;var f=d;do{if(f.expirationTime>b){c=f;break}f=f.next}while(f!==d);null===c?c=d:c===d&&(d=a,p()); b=c.previous;b.next=c.previous=a;a.next=c;a.previous=b}return a};exports.unstable_cancelCallback=function(a){var b=a.next;if(null!==b){if(b===a)d=null;else{a===d&&(d=b);var c=a.previous;c.next=b;b.previous=c}a.next=a.previous=null}};exports.unstable_wrapCallback=function(a){var b=g;return function(){var c=g,f=k;g=b;k=exports.unstable_now();try{return a.apply(this,arguments)}finally{g=c,k=f,v()}}};exports.unstable_getCurrentPriorityLevel=function(){return g}; exports.unstable_shouldYield=function(){return!e&&(null!==d&&d.expirationTime<l||w())};exports.unstable_continueExecution=function(){null!==d&&p()};exports.unstable_pauseExecution=function(){};exports.unstable_getFirstCallbackNode=function(){return d}; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],436:[function(require,module,exports){ (function (process){ 'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/scheduler.production.min.js'); } else { module.exports = require('./cjs/scheduler.development.js'); } }).call(this,require('_process')) },{"./cjs/scheduler.development.js":434,"./cjs/scheduler.production.min.js":435,"_process":405}],437:[function(require,module,exports){ (function (process){ 'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./cjs/scheduler-tracing.production.min.js'); } else { module.exports = require('./cjs/scheduler-tracing.development.js'); } }).call(this,require('_process')) },{"./cjs/scheduler-tracing.development.js":432,"./cjs/scheduler-tracing.production.min.js":433,"_process":405}],438:[function(require,module,exports){ (function (process){ exports = module.exports = SemVer var debug /* istanbul ignore next */ if (typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG)) { debug = function () { var args = Array.prototype.slice.call(arguments, 0) args.unshift('SEMVER') console.log.apply(console, args) } } else { debug = function () {} } // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. exports.SEMVER_SPEC_VERSION = '2.0.0' var MAX_LENGTH = 256 var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991 // Max safe segment length for coercion. var MAX_SAFE_COMPONENT_LENGTH = 16 // The actual regexps go on exports.re var re = exports.re = [] var src = exports.src = [] var R = 0 // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. var NUMERICIDENTIFIER = R++ src[NUMERICIDENTIFIER] = '0|[1-9]\\d*' var NUMERICIDENTIFIERLOOSE = R++ src[NUMERICIDENTIFIERLOOSE] = '[0-9]+' // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. var NONNUMERICIDENTIFIER = R++ src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' // ## Main Version // Three dot-separated numeric identifiers. var MAINVERSION = R++ src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')' var MAINVERSIONLOOSE = R++ src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')' // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. var PRERELEASEIDENTIFIER = R++ src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + '|' + src[NONNUMERICIDENTIFIER] + ')' var PRERELEASEIDENTIFIERLOOSE = R++ src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + '|' + src[NONNUMERICIDENTIFIER] + ')' // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. var PRERELEASE = R++ src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))' var PRERELEASELOOSE = R++ src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))' // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. var BUILDIDENTIFIER = R++ src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+' // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. var BUILD = R++ src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))' // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. var FULL = R++ var FULLPLAIN = 'v?' + src[MAINVERSION] + src[PRERELEASE] + '?' + src[BUILD] + '?' src[FULL] = '^' + FULLPLAIN + '$' // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + src[PRERELEASELOOSE] + '?' + src[BUILD] + '?' var LOOSE = R++ src[LOOSE] = '^' + LOOSEPLAIN + '$' var GTLT = R++ src[GTLT] = '((?:<|>)?=?)' // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. var XRANGEIDENTIFIERLOOSE = R++ src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' var XRANGEIDENTIFIER = R++ src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*' var XRANGEPLAIN = R++ src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:' + src[PRERELEASE] + ')?' + src[BUILD] + '?' + ')?)?' var XRANGEPLAINLOOSE = R++ src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:' + src[PRERELEASELOOSE] + ')?' + src[BUILD] + '?' + ')?)?' var XRANGE = R++ src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$' var XRANGELOOSE = R++ src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$' // Coercion. // Extract anything that could conceivably be a part of a valid semver var COERCE = R++ src[COERCE] = '(?:^|[^\\d])' + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:$|[^\\d])' // Tilde ranges. // Meaning is "reasonably at or greater than" var LONETILDE = R++ src[LONETILDE] = '(?:~>?)' var TILDETRIM = R++ src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+' re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g') var tildeTrimReplace = '$1~' var TILDE = R++ src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$' var TILDELOOSE = R++ src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$' // Caret ranges. // Meaning is "at least and backwards compatible with" var LONECARET = R++ src[LONECARET] = '(?:\\^)' var CARETTRIM = R++ src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+' re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g') var caretTrimReplace = '$1^' var CARET = R++ src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$' var CARETLOOSE = R++ src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$' // A simple gt/lt/eq thing, or just "" to indicate "any version" var COMPARATORLOOSE = R++ src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$' var COMPARATOR = R++ src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$' // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` var COMPARATORTRIM = R++ src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')' // this one has to use the /g flag re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g') var comparatorTrimReplace = '$1$2$3' // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. var HYPHENRANGE = R++ src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAIN] + ')' + '\\s*$' var HYPHENRANGELOOSE = R++ src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAINLOOSE] + ')' + '\\s*$' // Star ranges basically just allow anything at all. var STAR = R++ src[STAR] = '(<|>)?=?\\s*\\*' // Compile to actual regexp objects. // All are flag-free, unless they were created above with a flag. for (var i = 0; i < R; i++) { debug(i, src[i]) if (!re[i]) { re[i] = new RegExp(src[i]) } } exports.parse = parse function parse (version, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (version instanceof SemVer) { return version } if (typeof version !== 'string') { return null } if (version.length > MAX_LENGTH) { return null } var r = options.loose ? re[LOOSE] : re[FULL] if (!r.test(version)) { return null } try { return new SemVer(version, options) } catch (er) { return null } } exports.valid = valid function valid (version, options) { var v = parse(version, options) return v ? v.version : null } exports.clean = clean function clean (version, options) { var s = parse(version.trim().replace(/^[=v]+/, ''), options) return s ? s.version : null } exports.SemVer = SemVer function SemVer (version, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (version instanceof SemVer) { if (version.loose === options.loose) { return version } else { version = version.version } } else if (typeof version !== 'string') { throw new TypeError('Invalid Version: ' + version) } if (version.length > MAX_LENGTH) { throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') } if (!(this instanceof SemVer)) { return new SemVer(version, options) } debug('SemVer', version, options) this.options = options this.loose = !!options.loose var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]) if (!m) { throw new TypeError('Invalid Version: ' + version) } this.raw = version // these are actually numbers this.major = +m[1] this.minor = +m[2] this.patch = +m[3] if (this.major > MAX_SAFE_INTEGER || this.major < 0) { throw new TypeError('Invalid major version') } if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { throw new TypeError('Invalid minor version') } if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { throw new TypeError('Invalid patch version') } // numberify any prerelease numeric ids if (!m[4]) { this.prerelease = [] } else { this.prerelease = m[4].split('.').map(function (id) { if (/^[0-9]+$/.test(id)) { var num = +id if (num >= 0 && num < MAX_SAFE_INTEGER) { return num } } return id }) } this.build = m[5] ? m[5].split('.') : [] this.format() } SemVer.prototype.format = function () { this.version = this.major + '.' + this.minor + '.' + this.patch if (this.prerelease.length) { this.version += '-' + this.prerelease.join('.') } return this.version } SemVer.prototype.toString = function () { return this.version } SemVer.prototype.compare = function (other) { debug('SemVer.compare', this.version, this.options, other) if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return this.compareMain(other) || this.comparePre(other) } SemVer.prototype.compareMain = function (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch) } SemVer.prototype.comparePre = function (other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options) } // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) { return -1 } else if (!this.prerelease.length && other.prerelease.length) { return 1 } else if (!this.prerelease.length && !other.prerelease.length) { return 0 } var i = 0 do { var a = this.prerelease[i] var b = other.prerelease[i] debug('prerelease compare', i, a, b) if (a === undefined && b === undefined) { return 0 } else if (b === undefined) { return 1 } else if (a === undefined) { return -1 } else if (a === b) { continue } else { return compareIdentifiers(a, b) } } while (++i) } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. SemVer.prototype.inc = function (release, identifier) { switch (release) { case 'premajor': this.prerelease.length = 0 this.patch = 0 this.minor = 0 this.major++ this.inc('pre', identifier) break case 'preminor': this.prerelease.length = 0 this.patch = 0 this.minor++ this.inc('pre', identifier) break case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0 this.inc('patch', identifier) this.inc('pre', identifier) break // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) { this.inc('patch', identifier) } this.inc('pre', identifier) break case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { this.major++ } this.minor = 0 this.patch = 0 this.prerelease = [] break case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++ } this.patch = 0 this.prerelease = [] break case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) { this.patch++ } this.prerelease = [] break // This probably shouldn't be used publicly. // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. case 'pre': if (this.prerelease.length === 0) { this.prerelease = [0] } else { var i = this.prerelease.length while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++ i = -2 } } if (i === -1) { // didn't increment anything this.prerelease.push(0) } } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 if (this.prerelease[0] === identifier) { if (isNaN(this.prerelease[1])) { this.prerelease = [identifier, 0] } } else { this.prerelease = [identifier, 0] } } break default: throw new Error('invalid increment argument: ' + release) } this.format() this.raw = this.version return this } exports.inc = inc function inc (version, release, loose, identifier) { if (typeof (loose) === 'string') { identifier = loose loose = undefined } try { return new SemVer(version, loose).inc(release, identifier).version } catch (er) { return null } } exports.diff = diff function diff (version1, version2) { if (eq(version1, version2)) { return null } else { var v1 = parse(version1) var v2 = parse(version2) var prefix = '' if (v1.prerelease.length || v2.prerelease.length) { prefix = 'pre' var defaultResult = 'prerelease' } for (var key in v1) { if (key === 'major' || key === 'minor' || key === 'patch') { if (v1[key] !== v2[key]) { return prefix + key } } } return defaultResult // may be undefined } } exports.compareIdentifiers = compareIdentifiers var numeric = /^[0-9]+$/ function compareIdentifiers (a, b) { var anum = numeric.test(a) var bnum = numeric.test(b) if (anum && bnum) { a = +a b = +b } return a === b ? 0 : (anum && !bnum) ? -1 : (bnum && !anum) ? 1 : a < b ? -1 : 1 } exports.rcompareIdentifiers = rcompareIdentifiers function rcompareIdentifiers (a, b) { return compareIdentifiers(b, a) } exports.major = major function major (a, loose) { return new SemVer(a, loose).major } exports.minor = minor function minor (a, loose) { return new SemVer(a, loose).minor } exports.patch = patch function patch (a, loose) { return new SemVer(a, loose).patch } exports.compare = compare function compare (a, b, loose) { return new SemVer(a, loose).compare(new SemVer(b, loose)) } exports.compareLoose = compareLoose function compareLoose (a, b) { return compare(a, b, true) } exports.rcompare = rcompare function rcompare (a, b, loose) { return compare(b, a, loose) } exports.sort = sort function sort (list, loose) { return list.sort(function (a, b) { return exports.compare(a, b, loose) }) } exports.rsort = rsort function rsort (list, loose) { return list.sort(function (a, b) { return exports.rcompare(a, b, loose) }) } exports.gt = gt function gt (a, b, loose) { return compare(a, b, loose) > 0 } exports.lt = lt function lt (a, b, loose) { return compare(a, b, loose) < 0 } exports.eq = eq function eq (a, b, loose) { return compare(a, b, loose) === 0 } exports.neq = neq function neq (a, b, loose) { return compare(a, b, loose) !== 0 } exports.gte = gte function gte (a, b, loose) { return compare(a, b, loose) >= 0 } exports.lte = lte function lte (a, b, loose) { return compare(a, b, loose) <= 0 } exports.cmp = cmp function cmp (a, op, b, loose) { switch (op) { case '===': if (typeof a === 'object') a = a.version if (typeof b === 'object') b = b.version return a === b case '!==': if (typeof a === 'object') a = a.version if (typeof b === 'object') b = b.version return a !== b case '': case '=': case '==': return eq(a, b, loose) case '!=': return neq(a, b, loose) case '>': return gt(a, b, loose) case '>=': return gte(a, b, loose) case '<': return lt(a, b, loose) case '<=': return lte(a, b, loose) default: throw new TypeError('Invalid operator: ' + op) } } exports.Comparator = Comparator function Comparator (comp, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (comp instanceof Comparator) { if (comp.loose === !!options.loose) { return comp } else { comp = comp.value } } if (!(this instanceof Comparator)) { return new Comparator(comp, options) } debug('comparator', comp, options) this.options = options this.loose = !!options.loose this.parse(comp) if (this.semver === ANY) { this.value = '' } else { this.value = this.operator + this.semver.version } debug('comp', this) } var ANY = {} Comparator.prototype.parse = function (comp) { var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR] var m = comp.match(r) if (!m) { throw new TypeError('Invalid comparator: ' + comp) } this.operator = m[1] if (this.operator === '=') { this.operator = '' } // if it literally is just '>' or '' then allow anything. if (!m[2]) { this.semver = ANY } else { this.semver = new SemVer(m[2], this.options.loose) } } Comparator.prototype.toString = function () { return this.value } Comparator.prototype.test = function (version) { debug('Comparator.test', version, this.options.loose) if (this.semver === ANY) { return true } if (typeof version === 'string') { version = new SemVer(version, this.options) } return cmp(version, this.operator, this.semver, this.options) } Comparator.prototype.intersects = function (comp, options) { if (!(comp instanceof Comparator)) { throw new TypeError('a Comparator is required') } if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } var rangeTmp if (this.operator === '') { rangeTmp = new Range(comp.value, options) return satisfies(this.value, rangeTmp, options) } else if (comp.operator === '') { rangeTmp = new Range(this.value, options) return satisfies(comp.semver, rangeTmp, options) } var sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>') var sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<') var sameSemVer = this.semver.version === comp.semver.version var differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<=') var oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, options) && ((this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<')) var oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, options) && ((this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>')) return sameDirectionIncreasing || sameDirectionDecreasing || (sameSemVer && differentDirectionsInclusive) || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan } exports.Range = Range function Range (range, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false } } if (range instanceof Range) { if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) { return range } else { return new Range(range.raw, options) } } if (range instanceof Comparator) { return new Range(range.value, options) } if (!(this instanceof Range)) { return new Range(range, options) } this.options = options this.loose = !!options.loose this.includePrerelease = !!options.includePrerelease // First, split based on boolean or || this.raw = range this.set = range.split(/\s*\|\|\s*/).map(function (range) { return this.parseRange(range.trim()) }, this).filter(function (c) { // throw out any that are not relevant for whatever reason return c.length }) if (!this.set.length) { throw new TypeError('Invalid SemVer Range: ' + range) } this.format() } Range.prototype.format = function () { this.range = this.set.map(function (comps) { return comps.join(' ').trim() }).join('||').trim() return this.range } Range.prototype.toString = function () { return this.range } Range.prototype.parseRange = function (range) { var loose = this.options.loose range = range.trim() // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE] range = range.replace(hr, hyphenReplace) debug('hyphen replace', range) // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace) debug('comparator trim', range, re[COMPARATORTRIM]) // `~ 1.2.3` => `~1.2.3` range = range.replace(re[TILDETRIM], tildeTrimReplace) // `^ 1.2.3` => `^1.2.3` range = range.replace(re[CARETTRIM], caretTrimReplace) // normalize spaces range = range.split(/\s+/).join(' ') // At this point, the range is completely trimmed and // ready to be split into comparators. var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR] var set = range.split(' ').map(function (comp) { return parseComparator(comp, this.options) }, this).join(' ').split(/\s+/) if (this.options.loose) { // in loose mode, throw out any that are not valid comparators set = set.filter(function (comp) { return !!comp.match(compRe) }) } set = set.map(function (comp) { return new Comparator(comp, this.options) }, this) return set } Range.prototype.intersects = function (range, options) { if (!(range instanceof Range)) { throw new TypeError('a Range is required') } return this.set.some(function (thisComparators) { return thisComparators.every(function (thisComparator) { return range.set.some(function (rangeComparators) { return rangeComparators.every(function (rangeComparator) { return thisComparator.intersects(rangeComparator, options) }) }) }) }) } // Mostly just for testing and legacy API reasons exports.toComparators = toComparators function toComparators (range, options) { return new Range(range, options).set.map(function (comp) { return comp.map(function (c) { return c.value }).join(' ').trim().split(' ') }) } // comprised of xranges, tildes, stars, and gtlt's at this point. // already replaced the hyphen ranges // turn into a set of JUST comparators. function parseComparator (comp, options) { debug('comp', comp, options) comp = replaceCarets(comp, options) debug('caret', comp) comp = replaceTildes(comp, options) debug('tildes', comp) comp = replaceXRanges(comp, options) debug('xrange', comp) comp = replaceStars(comp, options) debug('stars', comp) return comp } function isX (id) { return !id || id.toLowerCase() === 'x' || id === '*' } // ~, ~> --> * (any, kinda silly) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 function replaceTildes (comp, options) { return comp.trim().split(/\s+/).map(function (comp) { return replaceTilde(comp, options) }).join(' ') } function replaceTilde (comp, options) { var r = options.loose ? re[TILDELOOSE] : re[TILDE] return comp.replace(r, function (_, M, m, p, pr) { debug('tilde', comp, _, M, m, p, pr) var ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' } else if (isX(p)) { // ~1.2 == >=1.2.0 <1.3.0 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' } else if (pr) { debug('replaceTilde pr', pr) ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0' } else { // ~1.2.3 == >=1.2.3 <1.3.0 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0' } debug('tilde return', ret) return ret }) } // ^ --> * (any, kinda silly) // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 // ^1.2.3 --> >=1.2.3 <2.0.0 // ^1.2.0 --> >=1.2.0 <2.0.0 function replaceCarets (comp, options) { return comp.trim().split(/\s+/).map(function (comp) { return replaceCaret(comp, options) }).join(' ') } function replaceCaret (comp, options) { debug('caret', comp, options) var r = options.loose ? re[CARETLOOSE] : re[CARET] return comp.replace(r, function (_, M, m, p, pr) { debug('caret', comp, _, M, m, p, pr) var ret if (isX(M)) { ret = '' } else if (isX(m)) { ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' } else if (isX(p)) { if (M === '0') { ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' } else { ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' } } else if (pr) { debug('replaceCaret pr', pr) if (M === '0') { if (m === '0') { ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + m + '.' + (+p + 1) } else { ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0' } } else { ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + (+M + 1) + '.0.0' } } else { debug('no pr') if (M === '0') { if (m === '0') { ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + m + '.' + (+p + 1) } else { ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0' } } else { ret = '>=' + M + '.' + m + '.' + p + ' <' + (+M + 1) + '.0.0' } } debug('caret return', ret) return ret }) } function replaceXRanges (comp, options) { debug('replaceXRanges', comp, options) return comp.split(/\s+/).map(function (comp) { return replaceXRange(comp, options) }).join(' ') } function replaceXRange (comp, options) { comp = comp.trim() var r = options.loose ? re[XRANGELOOSE] : re[XRANGE] return comp.replace(r, function (ret, gtlt, M, m, p, pr) { debug('xRange', comp, ret, gtlt, M, m, p, pr) var xM = isX(M) var xm = xM || isX(m) var xp = xm || isX(p) var anyX = xp if (gtlt === '=' && anyX) { gtlt = '' } if (xM) { if (gtlt === '>' || gtlt === '<') { // nothing is allowed ret = '<0.0.0' } else { // nothing is forbidden ret = '*' } } else if (gtlt && anyX) { // we know patch is an x, because we have any x at all. // replace X with 0 if (xm) { m = 0 } p = 0 if (gtlt === '>') { // >1 => >=2.0.0 // >1.2 => >=1.3.0 // >1.2.3 => >= 1.2.4 gtlt = '>=' if (xm) { M = +M + 1 m = 0 p = 0 } else { m = +m + 1 p = 0 } } else if (gtlt === '<=') { // <=0.7.x is actually <0.8.0, since any 0.7.x should // pass. Similarly, <=7.x is actually <8.0.0, etc. gtlt = '<' if (xm) { M = +M + 1 } else { m = +m + 1 } } ret = gtlt + M + '.' + m + '.' + p } else if (xm) { ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' } else if (xp) { ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' } debug('xRange return', ret) return ret }) } // Because * is AND-ed with everything else in the comparator, // and '' means "any version", just remove the *s entirely. function replaceStars (comp, options) { debug('replaceStars', comp, options) // Looseness is ignored here. star is always as loose as it gets! return comp.trim().replace(re[STAR], '') } // This function is passed to string.replace(re[HYPHENRANGE]) // M, m, patch, prerelease, build // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do // 1.2 - 3.4 => >=1.2.0 <3.5.0 function hyphenReplace ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) { if (isX(fM)) { from = '' } else if (isX(fm)) { from = '>=' + fM + '.0.0' } else if (isX(fp)) { from = '>=' + fM + '.' + fm + '.0' } else { from = '>=' + from } if (isX(tM)) { to = '' } else if (isX(tm)) { to = '<' + (+tM + 1) + '.0.0' } else if (isX(tp)) { to = '<' + tM + '.' + (+tm + 1) + '.0' } else if (tpr) { to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr } else { to = '<=' + to } return (from + ' ' + to).trim() } // if ANY of the sets match ALL of its comparators, then pass Range.prototype.test = function (version) { if (!version) { return false } if (typeof version === 'string') { version = new SemVer(version, this.options) } for (var i = 0; i < this.set.length; i++) { if (testSet(this.set[i], version, this.options)) { return true } } return false } function testSet (set, version, options) { for (var i = 0; i < set.length; i++) { if (!set[i].test(version)) { return false } } if (version.prerelease.length && !options.includePrerelease) { // Find the set of versions that are allowed to have prereleases // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 // That should allow `1.2.3-pr.2` to pass. // However, `1.2.4-alpha.notready` should NOT be allowed, // even though it's within the range set by the comparators. for (i = 0; i < set.length; i++) { debug(set[i].semver) if (set[i].semver === ANY) { continue } if (set[i].semver.prerelease.length > 0) { var allowed = set[i].semver if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { return true } } } // Version has a -pre, but it's not one of the ones we like. return false } return true } exports.satisfies = satisfies function satisfies (version, range, options) { try { range = new Range(range, options) } catch (er) { return false } return range.test(version) } exports.maxSatisfying = maxSatisfying function maxSatisfying (versions, range, options) { var max = null var maxSV = null try { var rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach(function (v) { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) max = v maxSV = new SemVer(max, options) } } }) return max } exports.minSatisfying = minSatisfying function minSatisfying (versions, range, options) { var min = null var minSV = null try { var rangeObj = new Range(range, options) } catch (er) { return null } versions.forEach(function (v) { if (rangeObj.test(v)) { // satisfies(v, range, options) if (!min || minSV.compare(v) === 1) { // compare(min, v, true) min = v minSV = new SemVer(min, options) } } }) return min } exports.minVersion = minVersion function minVersion (range, loose) { range = new Range(range, loose) var minver = new SemVer('0.0.0') if (range.test(minver)) { return minver } minver = new SemVer('0.0.0-0') if (range.test(minver)) { return minver } minver = null for (var i = 0; i < range.set.length; ++i) { var comparators = range.set[i] comparators.forEach(function (comparator) { // Clone to avoid manipulating the comparator's semver object. var compver = new SemVer(comparator.semver.version) switch (comparator.operator) { case '>': if (compver.prerelease.length === 0) { compver.patch++ } else { compver.prerelease.push(0) } compver.raw = compver.format() /* fallthrough */ case '': case '>=': if (!minver || gt(minver, compver)) { minver = compver } break case '<': case '<=': /* Ignore maximum versions */ break /* istanbul ignore next */ default: throw new Error('Unexpected operation: ' + comparator.operator) } }) } if (minver && range.test(minver)) { return minver } return null } exports.validRange = validRange function validRange (range, options) { try { // Return '*' instead of '' so that truthiness works. // This will throw if it's invalid anyway return new Range(range, options).range || '*' } catch (er) { return null } } // Determine if version is less than all the versions possible in the range exports.ltr = ltr function ltr (version, range, options) { return outside(version, range, '<', options) } // Determine if version is greater than all the versions possible in the range. exports.gtr = gtr function gtr (version, range, options) { return outside(version, range, '>', options) } exports.outside = outside function outside (version, range, hilo, options) { version = new SemVer(version, options) range = new Range(range, options) var gtfn, ltefn, ltfn, comp, ecomp switch (hilo) { case '>': gtfn = gt ltefn = lte ltfn = lt comp = '>' ecomp = '>=' break case '<': gtfn = lt ltefn = gte ltfn = gt comp = '<' ecomp = '<=' break default: throw new TypeError('Must provide a hilo val of "<" or ">"') } // If it satisifes the range it is not outside if (satisfies(version, range, options)) { return false } // From now on, variable terms are as if we're in "gtr" mode. // but note that everything is flipped for the "ltr" function. for (var i = 0; i < range.set.length; ++i) { var comparators = range.set[i] var high = null var low = null comparators.forEach(function (comparator) { if (comparator.semver === ANY) { comparator = new Comparator('>=0.0.0') } high = high || comparator low = low || comparator if (gtfn(comparator.semver, high.semver, options)) { high = comparator } else if (ltfn(comparator.semver, low.semver, options)) { low = comparator } }) // If the edge version comparator has a operator then our version // isn't outside it if (high.operator === comp || high.operator === ecomp) { return false } // If the lowest version comparator has an operator and our version // is less than it then it isn't higher than the range if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { return false } else if (low.operator === ecomp && ltfn(version, low.semver)) { return false } } return true } exports.prerelease = prerelease function prerelease (version, options) { var parsed = parse(version, options) return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } exports.intersects = intersects function intersects (r1, r2, options) { r1 = new Range(r1, options) r2 = new Range(r2, options) return r1.intersects(r2) } exports.coerce = coerce function coerce (version) { if (version instanceof SemVer) { return version } if (typeof version !== 'string') { return null } var match = version.match(re[COERCE]) if (match == null) { return null } return parse(match[1] + '.' + (match[2] || '0') + '.' + (match[3] || '0')) } }).call(this,require('_process')) },{"_process":405}],439:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var util = require('./util'); var has = Object.prototype.hasOwnProperty; var hasNativeMap = typeof Map !== "undefined"; /** * A data structure which is a combination of an array and a set. Adding a new * member is O(1), testing for membership is O(1), and finding the index of an * element is O(1). Removing elements from the set is not supported. Only * strings are supported for membership. */ function ArraySet() { this._array = []; this._set = hasNativeMap ? new Map() : Object.create(null); } /** * Static method for creating ArraySet instances from an existing array. */ ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { var set = new ArraySet(); for (var i = 0, len = aArray.length; i < len; i++) { set.add(aArray[i], aAllowDuplicates); } return set; }; /** * Return how many unique items are in this ArraySet. If duplicates have been * added, than those do not count towards the size. * * @returns Number */ ArraySet.prototype.size = function ArraySet_size() { return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; }; /** * Add the given string to this set. * * @param String aStr */ ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { var sStr = hasNativeMap ? aStr : util.toSetString(aStr); var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); var idx = this._array.length; if (!isDuplicate || aAllowDuplicates) { this._array.push(aStr); } if (!isDuplicate) { if (hasNativeMap) { this._set.set(aStr, idx); } else { this._set[sStr] = idx; } } }; /** * Is the given string a member of this set? * * @param String aStr */ ArraySet.prototype.has = function ArraySet_has(aStr) { if (hasNativeMap) { return this._set.has(aStr); } else { var sStr = util.toSetString(aStr); return has.call(this._set, sStr); } }; /** * What is the index of the given string in the array? * * @param String aStr */ ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { if (hasNativeMap) { var idx = this._set.get(aStr); if (idx >= 0) { return idx; } } else { var sStr = util.toSetString(aStr); if (has.call(this._set, sStr)) { return this._set[sStr]; } } throw new Error('"' + aStr + '" is not in the set.'); }; /** * What is the element at the given index? * * @param Number aIdx */ ArraySet.prototype.at = function ArraySet_at(aIdx) { if (aIdx >= 0 && aIdx < this._array.length) { return this._array[aIdx]; } throw new Error('No element indexed by ' + aIdx); }; /** * Returns the array representation of this set (which has the proper indices * indicated by indexOf). Note that this is a copy of the internal array used * for storing the members so that no one can mess with internal state. */ ArraySet.prototype.toArray = function ArraySet_toArray() { return this._array.slice(); }; exports.ArraySet = ArraySet; },{"./util":448}],440:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause * * Based on the Base 64 VLQ implementation in Closure Compiler: * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java * * Copyright 2011 The Closure Compiler Authors. 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. * * Neither the name of Google Inc. 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 * OWNER 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. */ var base64 = require('./base64'); // A single base 64 digit can contain 6 bits of data. For the base 64 variable // length quantities we use in the source map spec, the first bit is the sign, // the next four bits are the actual value, and the 6th bit is the // continuation bit. The continuation bit tells us whether there are more // digits in this value following this digit. // // Continuation // | Sign // | | // V V // 101011 var VLQ_BASE_SHIFT = 5; // binary: 100000 var VLQ_BASE = 1 << VLQ_BASE_SHIFT; // binary: 011111 var VLQ_BASE_MASK = VLQ_BASE - 1; // binary: 100000 var VLQ_CONTINUATION_BIT = VLQ_BASE; /** * Converts from a two-complement value to a value where the sign bit is * placed in the least significant bit. For example, as decimals: * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) */ function toVLQSigned(aValue) { return aValue < 0 ? ((-aValue) << 1) + 1 : (aValue << 1) + 0; } /** * Converts to a two-complement value from a value where the sign bit is * placed in the least significant bit. For example, as decimals: * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 */ function fromVLQSigned(aValue) { var isNegative = (aValue & 1) === 1; var shifted = aValue >> 1; return isNegative ? -shifted : shifted; } /** * Returns the base 64 VLQ encoded value. */ exports.encode = function base64VLQ_encode(aValue) { var encoded = ""; var digit; var vlq = toVLQSigned(aValue); do { digit = vlq & VLQ_BASE_MASK; vlq >>>= VLQ_BASE_SHIFT; if (vlq > 0) { // There are still more digits in this value, so we must make sure the // continuation bit is marked. digit |= VLQ_CONTINUATION_BIT; } encoded += base64.encode(digit); } while (vlq > 0); return encoded; }; /** * Decodes the next base 64 VLQ value from the given string and returns the * value and the rest of the string via the out parameter. */ exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { var strLen = aStr.length; var result = 0; var shift = 0; var continuation, digit; do { if (aIndex >= strLen) { throw new Error("Expected more digits in base 64 VLQ value."); } digit = base64.decode(aStr.charCodeAt(aIndex++)); if (digit === -1) { throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); } continuation = !!(digit & VLQ_CONTINUATION_BIT); digit &= VLQ_BASE_MASK; result = result + (digit << shift); shift += VLQ_BASE_SHIFT; } while (continuation); aOutParam.value = fromVLQSigned(result); aOutParam.rest = aIndex; }; },{"./base64":441}],441:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); /** * Encode an integer in the range of 0 to 63 to a single base 64 digit. */ exports.encode = function (number) { if (0 <= number && number < intToCharMap.length) { return intToCharMap[number]; } throw new TypeError("Must be between 0 and 63: " + number); }; /** * Decode a single base 64 character code digit to an integer. Returns -1 on * failure. */ exports.decode = function (charCode) { var bigA = 65; // 'A' var bigZ = 90; // 'Z' var littleA = 97; // 'a' var littleZ = 122; // 'z' var zero = 48; // '0' var nine = 57; // '9' var plus = 43; // '+' var slash = 47; // '/' var littleOffset = 26; var numberOffset = 52; // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ if (bigA <= charCode && charCode <= bigZ) { return (charCode - bigA); } // 26 - 51: abcdefghijklmnopqrstuvwxyz if (littleA <= charCode && charCode <= littleZ) { return (charCode - littleA + littleOffset); } // 52 - 61: 0123456789 if (zero <= charCode && charCode <= nine) { return (charCode - zero + numberOffset); } // 62: + if (charCode == plus) { return 62; } // 63: / if (charCode == slash) { return 63; } // Invalid base64 digit. return -1; }; },{}],442:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ exports.GREATEST_LOWER_BOUND = 1; exports.LEAST_UPPER_BOUND = 2; /** * Recursive implementation of binary search. * * @param aLow Indices here and lower do not contain the needle. * @param aHigh Indices here and higher do not contain the needle. * @param aNeedle The element being searched for. * @param aHaystack The non-empty array being searched. * @param aCompare Function which takes two elements and returns -1, 0, or 1. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. */ function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { // This function terminates when one of the following is true: // // 1. We find the exact element we are looking for. // // 2. We did not find the exact element, but we can return the index of // the next-closest element. // // 3. We did not find the exact element, and there is no next-closest // element than the one we are searching for, so we return -1. var mid = Math.floor((aHigh - aLow) / 2) + aLow; var cmp = aCompare(aNeedle, aHaystack[mid], true); if (cmp === 0) { // Found the element we are looking for. return mid; } else if (cmp > 0) { // Our needle is greater than aHaystack[mid]. if (aHigh - mid > 1) { // The element is in the upper half. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); } // The exact needle element was not found in this haystack. Determine if // we are in termination case (3) or (2) and return the appropriate thing. if (aBias == exports.LEAST_UPPER_BOUND) { return aHigh < aHaystack.length ? aHigh : -1; } else { return mid; } } else { // Our needle is less than aHaystack[mid]. if (mid - aLow > 1) { // The element is in the lower half. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); } // we are in termination case (3) or (2) and return the appropriate thing. if (aBias == exports.LEAST_UPPER_BOUND) { return mid; } else { return aLow < 0 ? -1 : aLow; } } } /** * This is an implementation of binary search which will always try and return * the index of the closest element if there is no exact hit. This is because * mappings between original and generated line/col pairs are single points, * and there is an implicit region between each of them, so a miss just means * that you aren't on the very start of a region. * * @param aNeedle The element you are looking for. * @param aHaystack The array that is being searched. * @param aCompare A function which takes the needle and an element in the * array and returns -1, 0, or 1 depending on whether the needle is less * than, equal to, or greater than the element, respectively. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. */ exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { if (aHaystack.length === 0) { return -1; } var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare, aBias || exports.GREATEST_LOWER_BOUND); if (index < 0) { return -1; } // We have found either the exact element, or the next-closest element than // the one we are searching for. However, there may be more than one such // element. Make sure we always return the smallest of these. while (index - 1 >= 0) { if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { break; } --index; } return index; }; },{}],443:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2014 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var util = require('./util'); /** * Determine whether mappingB is after mappingA with respect to generated * position. */ function generatedPositionAfter(mappingA, mappingB) { // Optimized for most common case var lineA = mappingA.generatedLine; var lineB = mappingB.generatedLine; var columnA = mappingA.generatedColumn; var columnB = mappingB.generatedColumn; return lineB > lineA || lineB == lineA && columnB >= columnA || util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; } /** * A data structure to provide a sorted view of accumulated mappings in a * performance conscious manner. It trades a neglibable overhead in general * case for a large speedup in case of mappings being added in order. */ function MappingList() { this._array = []; this._sorted = true; // Serves as infimum this._last = {generatedLine: -1, generatedColumn: 0}; } /** * Iterate through internal items. This method takes the same arguments that * `Array.prototype.forEach` takes. * * NOTE: The order of the mappings is NOT guaranteed. */ MappingList.prototype.unsortedForEach = function MappingList_forEach(aCallback, aThisArg) { this._array.forEach(aCallback, aThisArg); }; /** * Add the given source mapping. * * @param Object aMapping */ MappingList.prototype.add = function MappingList_add(aMapping) { if (generatedPositionAfter(this._last, aMapping)) { this._last = aMapping; this._array.push(aMapping); } else { this._sorted = false; this._array.push(aMapping); } }; /** * Returns the flat, sorted array of mappings. The mappings are sorted by * generated position. * * WARNING: This method returns internal data without copying, for * performance. The return value must NOT be mutated, and should be treated as * an immutable borrow. If you want to take ownership, you must make your own * copy. */ MappingList.prototype.toArray = function MappingList_toArray() { if (!this._sorted) { this._array.sort(util.compareByGeneratedPositionsInflated); this._sorted = true; } return this._array; }; exports.MappingList = MappingList; },{"./util":448}],444:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ // It turns out that some (most?) JavaScript engines don't self-host // `Array.prototype.sort`. This makes sense because C++ will likely remain // faster than JS when doing raw CPU-intensive sorting. However, when using a // custom comparator function, calling back and forth between the VM's C++ and // JIT'd JS is rather slow *and* loses JIT type information, resulting in // worse generated code for the comparator function than would be optimal. In // fact, when sorting with a comparator, these costs outweigh the benefits of // sorting in C++. By using our own JS-implemented Quick Sort (below), we get // a ~3500ms mean speed-up in `bench/bench.html`. /** * Swap the elements indexed by `x` and `y` in the array `ary`. * * @param {Array} ary * The array. * @param {Number} x * The index of the first item. * @param {Number} y * The index of the second item. */ function swap(ary, x, y) { var temp = ary[x]; ary[x] = ary[y]; ary[y] = temp; } /** * Returns a random integer within the range `low .. high` inclusive. * * @param {Number} low * The lower bound on the range. * @param {Number} high * The upper bound on the range. */ function randomIntInRange(low, high) { return Math.round(low + (Math.random() * (high - low))); } /** * The Quick Sort algorithm. * * @param {Array} ary * An array to sort. * @param {function} comparator * Function to use to compare two items. * @param {Number} p * Start index of the array * @param {Number} r * End index of the array */ function doQuickSort(ary, comparator, p, r) { // If our lower bound is less than our upper bound, we (1) partition the // array into two pieces and (2) recurse on each half. If it is not, this is // the empty array and our base case. if (p < r) { // (1) Partitioning. // // The partitioning chooses a pivot between `p` and `r` and moves all // elements that are less than or equal to the pivot to the before it, and // all the elements that are greater than it after it. The effect is that // once partition is done, the pivot is in the exact place it will be when // the array is put in sorted order, and it will not need to be moved // again. This runs in O(n) time. // Always choose a random pivot so that an input array which is reverse // sorted does not cause O(n^2) running time. var pivotIndex = randomIntInRange(p, r); var i = p - 1; swap(ary, pivotIndex, r); var pivot = ary[r]; // Immediately after `j` is incremented in this loop, the following hold // true: // // * Every element in `ary[p .. i]` is less than or equal to the pivot. // // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. for (var j = p; j < r; j++) { if (comparator(ary[j], pivot) <= 0) { i += 1; swap(ary, i, j); } } swap(ary, i + 1, j); var q = i + 1; // (2) Recurse on each half. doQuickSort(ary, comparator, p, q - 1); doQuickSort(ary, comparator, q + 1, r); } } /** * Sort the given array in-place with the given comparator function. * * @param {Array} ary * An array to sort. * @param {function} comparator * Function to use to compare two items. */ exports.quickSort = function (ary, comparator) { doQuickSort(ary, comparator, 0, ary.length - 1); }; },{}],445:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var util = require('./util'); var binarySearch = require('./binary-search'); var ArraySet = require('./array-set').ArraySet; var base64VLQ = require('./base64-vlq'); var quickSort = require('./quick-sort').quickSort; function SourceMapConsumer(aSourceMap) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } return sourceMap.sections != null ? new IndexedSourceMapConsumer(sourceMap) : new BasicSourceMapConsumer(sourceMap); } SourceMapConsumer.fromSourceMap = function(aSourceMap) { return BasicSourceMapConsumer.fromSourceMap(aSourceMap); } /** * The version of the source mapping spec that we are consuming. */ SourceMapConsumer.prototype._version = 3; // `__generatedMappings` and `__originalMappings` are arrays that hold the // parsed mapping coordinates from the source map's "mappings" attribute. They // are lazily instantiated, accessed via the `_generatedMappings` and // `_originalMappings` getters respectively, and we only parse the mappings // and create these arrays once queried for a source location. We jump through // these hoops because there can be many thousands of mappings, and parsing // them is expensive, so we only want to do it if we must. // // Each object in the arrays is of the form: // // { // generatedLine: The line number in the generated code, // generatedColumn: The column number in the generated code, // source: The path to the original source file that generated this // chunk of code, // originalLine: The line number in the original source that // corresponds to this chunk of generated code, // originalColumn: The column number in the original source that // corresponds to this chunk of generated code, // name: The name of the original symbol which generated this chunk of // code. // } // // All properties except for `generatedLine` and `generatedColumn` can be // `null`. // // `_generatedMappings` is ordered by the generated positions. // // `_originalMappings` is ordered by the original positions. SourceMapConsumer.prototype.__generatedMappings = null; Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { get: function () { if (!this.__generatedMappings) { this._parseMappings(this._mappings, this.sourceRoot); } return this.__generatedMappings; } }); SourceMapConsumer.prototype.__originalMappings = null; Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { get: function () { if (!this.__originalMappings) { this._parseMappings(this._mappings, this.sourceRoot); } return this.__originalMappings; } }); SourceMapConsumer.prototype._charIsMappingSeparator = function SourceMapConsumer_charIsMappingSeparator(aStr, index) { var c = aStr.charAt(index); return c === ";" || c === ","; }; /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { throw new Error("Subclasses must implement _parseMappings"); }; SourceMapConsumer.GENERATED_ORDER = 1; SourceMapConsumer.ORIGINAL_ORDER = 2; SourceMapConsumer.GREATEST_LOWER_BOUND = 1; SourceMapConsumer.LEAST_UPPER_BOUND = 2; /** * Iterate over each mapping between an original source/line/column and a * generated line/column in this source map. * * @param Function aCallback * The function that is called with each mapping. * @param Object aContext * Optional. If specified, this object will be the value of `this` every * time that `aCallback` is called. * @param aOrder * Either `SourceMapConsumer.GENERATED_ORDER` or * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to * iterate over the mappings sorted by the generated file's line/column * order or the original's source/line/column order, respectively. Defaults to * `SourceMapConsumer.GENERATED_ORDER`. */ SourceMapConsumer.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { var context = aContext || null; var order = aOrder || SourceMapConsumer.GENERATED_ORDER; var mappings; switch (order) { case SourceMapConsumer.GENERATED_ORDER: mappings = this._generatedMappings; break; case SourceMapConsumer.ORIGINAL_ORDER: mappings = this._originalMappings; break; default: throw new Error("Unknown order of iteration."); } var sourceRoot = this.sourceRoot; mappings.map(function (mapping) { var source = mapping.source === null ? null : this._sources.at(mapping.source); if (source != null && sourceRoot != null) { source = util.join(sourceRoot, source); } return { source: source, generatedLine: mapping.generatedLine, generatedColumn: mapping.generatedColumn, originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, name: mapping.name === null ? null : this._names.at(mapping.name) }; }, this).forEach(aCallback, context); }; /** * Returns all generated line and column information for the original source, * line, and column provided. If no column is provided, returns all mappings * corresponding to a either the line we are searching for or the next * closest line that has any mappings. Otherwise, returns all mappings * corresponding to the given line and either the column we are searching for * or the next closest column that has any offsets. * * The only argument is an object with the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. * - column: Optional. the column number in the original source. * * and an array of objects is returned, each with the following properties: * * - line: The line number in the generated source, or null. * - column: The column number in the generated source, or null. */ SourceMapConsumer.prototype.allGeneratedPositionsFor = function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { var line = util.getArg(aArgs, 'line'); // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping // returns the index of the closest mapping less than the needle. By // setting needle.originalColumn to 0, we thus find the last mapping for // the given line, provided such a mapping exists. var needle = { source: util.getArg(aArgs, 'source'), originalLine: line, originalColumn: util.getArg(aArgs, 'column', 0) }; if (this.sourceRoot != null) { needle.source = util.relative(this.sourceRoot, needle.source); } if (!this._sources.has(needle.source)) { return []; } needle.source = this._sources.indexOf(needle.source); var mappings = []; var index = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions, binarySearch.LEAST_UPPER_BOUND); if (index >= 0) { var mapping = this._originalMappings[index]; if (aArgs.column === undefined) { var originalLine = mapping.originalLine; // Iterate until either we run out of mappings, or we run into // a mapping for a different line than the one we found. Since // mappings are sorted, this is guaranteed to find all mappings for // the line we found. while (mapping && mapping.originalLine === originalLine) { mappings.push({ line: util.getArg(mapping, 'generatedLine', null), column: util.getArg(mapping, 'generatedColumn', null), lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) }); mapping = this._originalMappings[++index]; } } else { var originalColumn = mapping.originalColumn; // Iterate until either we run out of mappings, or we run into // a mapping for a different line than the one we were searching for. // Since mappings are sorted, this is guaranteed to find all mappings for // the line we are searching for. while (mapping && mapping.originalLine === line && mapping.originalColumn == originalColumn) { mappings.push({ line: util.getArg(mapping, 'generatedLine', null), column: util.getArg(mapping, 'generatedColumn', null), lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) }); mapping = this._originalMappings[++index]; } } } return mappings; }; exports.SourceMapConsumer = SourceMapConsumer; /** * A BasicSourceMapConsumer instance represents a parsed source map which we can * query for information about the original file positions by giving it a file * position in the generated source. * * The only parameter is the raw source map (either as a JSON string, or * already parsed to an object). According to the spec, source maps have the * following attributes: * * - version: Which version of the source map spec this map is following. * - sources: An array of URLs to the original source files. * - names: An array of identifiers which can be referrenced by individual mappings. * - sourceRoot: Optional. The URL root from which all sources are relative. * - sourcesContent: Optional. An array of contents of the original source files. * - mappings: A string of base64 VLQs which contain the actual mappings. * - file: Optional. The generated file this source map is associated with. * * Here is an example source map, taken from the source map spec[0]: * * { * version : 3, * file: "out.js", * sourceRoot : "", * sources: ["foo.js", "bar.js"], * names: ["src", "maps", "are", "fun"], * mappings: "AA,AB;;ABCDE;" * } * * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# */ function BasicSourceMapConsumer(aSourceMap) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } var version = util.getArg(sourceMap, 'version'); var sources = util.getArg(sourceMap, 'sources'); // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which // requires the array) to play nice here. var names = util.getArg(sourceMap, 'names', []); var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); var mappings = util.getArg(sourceMap, 'mappings'); var file = util.getArg(sourceMap, 'file', null); // Once again, Sass deviates from the spec and supplies the version as a // string rather than a number, so we use loose equality checking here. if (version != this._version) { throw new Error('Unsupported version: ' + version); } sources = sources .map(String) // Some source maps produce relative source paths like "./foo.js" instead of // "foo.js". Normalize these first so that future comparisons will succeed. // See bugzil.la/1090768. .map(util.normalize) // Always ensure that absolute sources are internally stored relative to // the source root, if the source root is absolute. Not doing this would // be particularly problematic when the source root is a prefix of the // source (valid, but why??). See github issue #199 and bugzil.la/1188982. .map(function (source) { return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) ? util.relative(sourceRoot, source) : source; }); // Pass `true` below to allow duplicate names and sources. While source maps // are intended to be compressed and deduplicated, the TypeScript compiler // sometimes generates source maps with duplicates in them. See Github issue // #72 and bugzil.la/889492. this._names = ArraySet.fromArray(names.map(String), true); this._sources = ArraySet.fromArray(sources, true); this.sourceRoot = sourceRoot; this.sourcesContent = sourcesContent; this._mappings = mappings; this.file = file; } BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; /** * Create a BasicSourceMapConsumer from a SourceMapGenerator. * * @param SourceMapGenerator aSourceMap * The source map that will be consumed. * @returns BasicSourceMapConsumer */ BasicSourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap) { var smc = Object.create(BasicSourceMapConsumer.prototype); var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); smc.sourceRoot = aSourceMap._sourceRoot; smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), smc.sourceRoot); smc.file = aSourceMap._file; // Because we are modifying the entries (by converting string sources and // names to indices into the sources and names ArraySets), we have to make // a copy of the entry or else bad things happen. Shared mutable state // strikes again! See github issue #191. var generatedMappings = aSourceMap._mappings.toArray().slice(); var destGeneratedMappings = smc.__generatedMappings = []; var destOriginalMappings = smc.__originalMappings = []; for (var i = 0, length = generatedMappings.length; i < length; i++) { var srcMapping = generatedMappings[i]; var destMapping = new Mapping; destMapping.generatedLine = srcMapping.generatedLine; destMapping.generatedColumn = srcMapping.generatedColumn; if (srcMapping.source) { destMapping.source = sources.indexOf(srcMapping.source); destMapping.originalLine = srcMapping.originalLine; destMapping.originalColumn = srcMapping.originalColumn; if (srcMapping.name) { destMapping.name = names.indexOf(srcMapping.name); } destOriginalMappings.push(destMapping); } destGeneratedMappings.push(destMapping); } quickSort(smc.__originalMappings, util.compareByOriginalPositions); return smc; }; /** * The version of the source mapping spec that we are consuming. */ BasicSourceMapConsumer.prototype._version = 3; /** * The list of original sources. */ Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { get: function () { return this._sources.toArray().map(function (s) { return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s; }, this); } }); /** * Provide the JIT with a nice shape / hidden class. */ function Mapping() { this.generatedLine = 0; this.generatedColumn = 0; this.source = null; this.originalLine = null; this.originalColumn = null; this.name = null; } /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ BasicSourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { var generatedLine = 1; var previousGeneratedColumn = 0; var previousOriginalLine = 0; var previousOriginalColumn = 0; var previousSource = 0; var previousName = 0; var length = aStr.length; var index = 0; var cachedSegments = {}; var temp = {}; var originalMappings = []; var generatedMappings = []; var mapping, str, segment, end, value; while (index < length) { if (aStr.charAt(index) === ';') { generatedLine++; index++; previousGeneratedColumn = 0; } else if (aStr.charAt(index) === ',') { index++; } else { mapping = new Mapping(); mapping.generatedLine = generatedLine; // Because each offset is encoded relative to the previous one, // many segments often have the same encoding. We can exploit this // fact by caching the parsed variable length fields of each segment, // allowing us to avoid a second parse if we encounter the same // segment again. for (end = index; end < length; end++) { if (this._charIsMappingSeparator(aStr, end)) { break; } } str = aStr.slice(index, end); segment = cachedSegments[str]; if (segment) { index += str.length; } else { segment = []; while (index < end) { base64VLQ.decode(aStr, index, temp); value = temp.value; index = temp.rest; segment.push(value); } if (segment.length === 2) { throw new Error('Found a source, but no line and column'); } if (segment.length === 3) { throw new Error('Found a source and line, but no column'); } cachedSegments[str] = segment; } // Generated column. mapping.generatedColumn = previousGeneratedColumn + segment[0]; previousGeneratedColumn = mapping.generatedColumn; if (segment.length > 1) { // Original source. mapping.source = previousSource + segment[1]; previousSource += segment[1]; // Original line. mapping.originalLine = previousOriginalLine + segment[2]; previousOriginalLine = mapping.originalLine; // Lines are stored 0-based mapping.originalLine += 1; // Original column. mapping.originalColumn = previousOriginalColumn + segment[3]; previousOriginalColumn = mapping.originalColumn; if (segment.length > 4) { // Original name. mapping.name = previousName + segment[4]; previousName += segment[4]; } } generatedMappings.push(mapping); if (typeof mapping.originalLine === 'number') { originalMappings.push(mapping); } } } quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); this.__generatedMappings = generatedMappings; quickSort(originalMappings, util.compareByOriginalPositions); this.__originalMappings = originalMappings; }; /** * Find the mapping that best matches the hypothetical "needle" mapping that * we are searching for in the given "haystack" of mappings. */ BasicSourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator, aBias) { // To return the position we are searching for, we must first find the // mapping for the given position and then return the opposite position it // points to. Because the mappings are sorted, we can use binary search to // find the best mapping. if (aNeedle[aLineName] <= 0) { throw new TypeError('Line must be greater than or equal to 1, got ' + aNeedle[aLineName]); } if (aNeedle[aColumnName] < 0) { throw new TypeError('Column must be greater than or equal to 0, got ' + aNeedle[aColumnName]); } return binarySearch.search(aNeedle, aMappings, aComparator, aBias); }; /** * Compute the last column for each generated mapping. The last column is * inclusive. */ BasicSourceMapConsumer.prototype.computeColumnSpans = function SourceMapConsumer_computeColumnSpans() { for (var index = 0; index < this._generatedMappings.length; ++index) { var mapping = this._generatedMappings[index]; // Mappings do not contain a field for the last generated columnt. We // can come up with an optimistic estimate, however, by assuming that // mappings are contiguous (i.e. given two consecutive mappings, the // first mapping ends where the second one starts). if (index + 1 < this._generatedMappings.length) { var nextMapping = this._generatedMappings[index + 1]; if (mapping.generatedLine === nextMapping.generatedLine) { mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; continue; } } // The last mapping for each line spans the entire line. mapping.lastGeneratedColumn = Infinity; } }; /** * Returns the original source, line, and column information for the generated * source's line and column positions provided. The only argument is an object * with the following properties: * * - line: The line number in the generated source. * - column: The column number in the generated source. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. * * and an object is returned with the following properties: * * - source: The original source file, or null. * - line: The line number in the original source, or null. * - column: The column number in the original source, or null. * - name: The original identifier, or null. */ BasicSourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) { var needle = { generatedLine: util.getArg(aArgs, 'line'), generatedColumn: util.getArg(aArgs, 'column') }; var index = this._findMapping( needle, this._generatedMappings, "generatedLine", "generatedColumn", util.compareByGeneratedPositionsDeflated, util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) ); if (index >= 0) { var mapping = this._generatedMappings[index]; if (mapping.generatedLine === needle.generatedLine) { var source = util.getArg(mapping, 'source', null); if (source !== null) { source = this._sources.at(source); if (this.sourceRoot != null) { source = util.join(this.sourceRoot, source); } } var name = util.getArg(mapping, 'name', null); if (name !== null) { name = this._names.at(name); } return { source: source, line: util.getArg(mapping, 'originalLine', null), column: util.getArg(mapping, 'originalColumn', null), name: name }; } } return { source: null, line: null, column: null, name: null }; }; /** * Return true if we have the source content for every source in the source * map, false otherwise. */ BasicSourceMapConsumer.prototype.hasContentsOfAllSources = function BasicSourceMapConsumer_hasContentsOfAllSources() { if (!this.sourcesContent) { return false; } return this.sourcesContent.length >= this._sources.size() && !this.sourcesContent.some(function (sc) { return sc == null; }); }; /** * Returns the original source content. The only argument is the url of the * original source file. Returns null if no original source content is * available. */ BasicSourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { if (!this.sourcesContent) { return null; } if (this.sourceRoot != null) { aSource = util.relative(this.sourceRoot, aSource); } if (this._sources.has(aSource)) { return this.sourcesContent[this._sources.indexOf(aSource)]; } var url; if (this.sourceRoot != null && (url = util.urlParse(this.sourceRoot))) { // XXX: file:// URIs and absolute paths lead to unexpected behavior for // many users. We can help them out when they expect file:// URIs to // behave like it would if they were running a local HTTP server. See // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); if (url.scheme == "file" && this._sources.has(fileUriAbsPath)) { return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] } if ((!url.path || url.path == "/") && this._sources.has("/" + aSource)) { return this.sourcesContent[this._sources.indexOf("/" + aSource)]; } } // This function is used recursively from // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we // don't want to throw if we can't find the source - we just want to // return null, so we provide a flag to exit gracefully. if (nullOnMissing) { return null; } else { throw new Error('"' + aSource + '" is not in the SourceMap.'); } }; /** * Returns the generated line and column information for the original source, * line, and column positions provided. The only argument is an object with * the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. * - column: The column number in the original source. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. * * and an object is returned with the following properties: * * - line: The line number in the generated source, or null. * - column: The column number in the generated source, or null. */ BasicSourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) { var source = util.getArg(aArgs, 'source'); if (this.sourceRoot != null) { source = util.relative(this.sourceRoot, source); } if (!this._sources.has(source)) { return { line: null, column: null, lastColumn: null }; } source = this._sources.indexOf(source); var needle = { source: source, originalLine: util.getArg(aArgs, 'line'), originalColumn: util.getArg(aArgs, 'column') }; var index = this._findMapping( needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions, util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) ); if (index >= 0) { var mapping = this._originalMappings[index]; if (mapping.source === needle.source) { return { line: util.getArg(mapping, 'generatedLine', null), column: util.getArg(mapping, 'generatedColumn', null), lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) }; } } return { line: null, column: null, lastColumn: null }; }; exports.BasicSourceMapConsumer = BasicSourceMapConsumer; /** * An IndexedSourceMapConsumer instance represents a parsed source map which * we can query for information. It differs from BasicSourceMapConsumer in * that it takes "indexed" source maps (i.e. ones with a "sections" field) as * input. * * The only parameter is a raw source map (either as a JSON string, or already * parsed to an object). According to the spec for indexed source maps, they * have the following attributes: * * - version: Which version of the source map spec this map is following. * - file: Optional. The generated file this source map is associated with. * - sections: A list of section definitions. * * Each value under the "sections" field has two fields: * - offset: The offset into the original specified at which this section * begins to apply, defined as an object with a "line" and "column" * field. * - map: A source map definition. This source map could also be indexed, * but doesn't have to be. * * Instead of the "map" field, it's also possible to have a "url" field * specifying a URL to retrieve a source map from, but that's currently * unsupported. * * Here's an example source map, taken from the source map spec[0], but * modified to omit a section which uses the "url" field. * * { * version : 3, * file: "app.js", * sections: [{ * offset: {line:100, column:10}, * map: { * version : 3, * file: "section.js", * sources: ["foo.js", "bar.js"], * names: ["src", "maps", "are", "fun"], * mappings: "AAAA,E;;ABCDE;" * } * }], * } * * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt */ function IndexedSourceMapConsumer(aSourceMap) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } var version = util.getArg(sourceMap, 'version'); var sections = util.getArg(sourceMap, 'sections'); if (version != this._version) { throw new Error('Unsupported version: ' + version); } this._sources = new ArraySet(); this._names = new ArraySet(); var lastOffset = { line: -1, column: 0 }; this._sections = sections.map(function (s) { if (s.url) { // The url field will require support for asynchronicity. // See https://github.com/mozilla/source-map/issues/16 throw new Error('Support for url field in sections not implemented.'); } var offset = util.getArg(s, 'offset'); var offsetLine = util.getArg(offset, 'line'); var offsetColumn = util.getArg(offset, 'column'); if (offsetLine < lastOffset.line || (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { throw new Error('Section offsets must be ordered and non-overlapping.'); } lastOffset = offset; return { generatedOffset: { // The offset fields are 0-based, but we use 1-based indices when // encoding/decoding from VLQ. generatedLine: offsetLine + 1, generatedColumn: offsetColumn + 1 }, consumer: new SourceMapConsumer(util.getArg(s, 'map')) } }); } IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; /** * The version of the source mapping spec that we are consuming. */ IndexedSourceMapConsumer.prototype._version = 3; /** * The list of original sources. */ Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { get: function () { var sources = []; for (var i = 0; i < this._sections.length; i++) { for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { sources.push(this._sections[i].consumer.sources[j]); } } return sources; } }); /** * Returns the original source, line, and column information for the generated * source's line and column positions provided. The only argument is an object * with the following properties: * * - line: The line number in the generated source. * - column: The column number in the generated source. * * and an object is returned with the following properties: * * - source: The original source file, or null. * - line: The line number in the original source, or null. * - column: The column number in the original source, or null. * - name: The original identifier, or null. */ IndexedSourceMapConsumer.prototype.originalPositionFor = function IndexedSourceMapConsumer_originalPositionFor(aArgs) { var needle = { generatedLine: util.getArg(aArgs, 'line'), generatedColumn: util.getArg(aArgs, 'column') }; // Find the section containing the generated position we're trying to map // to an original position. var sectionIndex = binarySearch.search(needle, this._sections, function(needle, section) { var cmp = needle.generatedLine - section.generatedOffset.generatedLine; if (cmp) { return cmp; } return (needle.generatedColumn - section.generatedOffset.generatedColumn); }); var section = this._sections[sectionIndex]; if (!section) { return { source: null, line: null, column: null, name: null }; } return section.consumer.originalPositionFor({ line: needle.generatedLine - (section.generatedOffset.generatedLine - 1), column: needle.generatedColumn - (section.generatedOffset.generatedLine === needle.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0), bias: aArgs.bias }); }; /** * Return true if we have the source content for every source in the source * map, false otherwise. */ IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = function IndexedSourceMapConsumer_hasContentsOfAllSources() { return this._sections.every(function (s) { return s.consumer.hasContentsOfAllSources(); }); }; /** * Returns the original source content. The only argument is the url of the * original source file. Returns null if no original source content is * available. */ IndexedSourceMapConsumer.prototype.sourceContentFor = function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { for (var i = 0; i < this._sections.length; i++) { var section = this._sections[i]; var content = section.consumer.sourceContentFor(aSource, true); if (content) { return content; } } if (nullOnMissing) { return null; } else { throw new Error('"' + aSource + '" is not in the SourceMap.'); } }; /** * Returns the generated line and column information for the original source, * line, and column positions provided. The only argument is an object with * the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. * - column: The column number in the original source. * * and an object is returned with the following properties: * * - line: The line number in the generated source, or null. * - column: The column number in the generated source, or null. */ IndexedSourceMapConsumer.prototype.generatedPositionFor = function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { for (var i = 0; i < this._sections.length; i++) { var section = this._sections[i]; // Only consider this section if the requested source is in the list of // sources of the consumer. if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) { continue; } var generatedPosition = section.consumer.generatedPositionFor(aArgs); if (generatedPosition) { var ret = { line: generatedPosition.line + (section.generatedOffset.generatedLine - 1), column: generatedPosition.column + (section.generatedOffset.generatedLine === generatedPosition.line ? section.generatedOffset.generatedColumn - 1 : 0) }; return ret; } } return { line: null, column: null }; }; /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ IndexedSourceMapConsumer.prototype._parseMappings = function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { this.__generatedMappings = []; this.__originalMappings = []; for (var i = 0; i < this._sections.length; i++) { var section = this._sections[i]; var sectionMappings = section.consumer._generatedMappings; for (var j = 0; j < sectionMappings.length; j++) { var mapping = sectionMappings[j]; var source = section.consumer._sources.at(mapping.source); if (section.consumer.sourceRoot !== null) { source = util.join(section.consumer.sourceRoot, source); } this._sources.add(source); source = this._sources.indexOf(source); var name = section.consumer._names.at(mapping.name); this._names.add(name); name = this._names.indexOf(name); // The mappings coming from the consumer for the section have // generated positions relative to the start of the section, so we // need to offset them to be relative to the start of the concatenated // generated file. var adjustedMapping = { source: source, generatedLine: mapping.generatedLine + (section.generatedOffset.generatedLine - 1), generatedColumn: mapping.generatedColumn + (section.generatedOffset.generatedLine === mapping.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0), originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, name: name }; this.__generatedMappings.push(adjustedMapping); if (typeof adjustedMapping.originalLine === 'number') { this.__originalMappings.push(adjustedMapping); } } } quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); quickSort(this.__originalMappings, util.compareByOriginalPositions); }; exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; },{"./array-set":439,"./base64-vlq":440,"./binary-search":442,"./quick-sort":444,"./util":448}],446:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var base64VLQ = require('./base64-vlq'); var util = require('./util'); var ArraySet = require('./array-set').ArraySet; var MappingList = require('./mapping-list').MappingList; /** * An instance of the SourceMapGenerator represents a source map which is * being built incrementally. You may pass an object with the following * properties: * * - file: The filename of the generated source. * - sourceRoot: A root for all relative URLs in this source map. */ function SourceMapGenerator(aArgs) { if (!aArgs) { aArgs = {}; } this._file = util.getArg(aArgs, 'file', null); this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); this._skipValidation = util.getArg(aArgs, 'skipValidation', false); this._sources = new ArraySet(); this._names = new ArraySet(); this._mappings = new MappingList(); this._sourcesContents = null; } SourceMapGenerator.prototype._version = 3; /** * Creates a new SourceMapGenerator based on a SourceMapConsumer * * @param aSourceMapConsumer The SourceMap. */ SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { var sourceRoot = aSourceMapConsumer.sourceRoot; var generator = new SourceMapGenerator({ file: aSourceMapConsumer.file, sourceRoot: sourceRoot }); aSourceMapConsumer.eachMapping(function (mapping) { var newMapping = { generated: { line: mapping.generatedLine, column: mapping.generatedColumn } }; if (mapping.source != null) { newMapping.source = mapping.source; if (sourceRoot != null) { newMapping.source = util.relative(sourceRoot, newMapping.source); } newMapping.original = { line: mapping.originalLine, column: mapping.originalColumn }; if (mapping.name != null) { newMapping.name = mapping.name; } } generator.addMapping(newMapping); }); aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content != null) { generator.setSourceContent(sourceFile, content); } }); return generator; }; /** * Add a single mapping from original source line and column to the generated * source's line and column for this source map being created. The mapping * object should have the following properties: * * - generated: An object with the generated line and column positions. * - original: An object with the original line and column positions. * - source: The original source file (relative to the sourceRoot). * - name: An optional original token name for this mapping. */ SourceMapGenerator.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) { var generated = util.getArg(aArgs, 'generated'); var original = util.getArg(aArgs, 'original', null); var source = util.getArg(aArgs, 'source', null); var name = util.getArg(aArgs, 'name', null); if (!this._skipValidation) { this._validateMapping(generated, original, source, name); } if (source != null) { source = String(source); if (!this._sources.has(source)) { this._sources.add(source); } } if (name != null) { name = String(name); if (!this._names.has(name)) { this._names.add(name); } } this._mappings.add({ generatedLine: generated.line, generatedColumn: generated.column, originalLine: original != null && original.line, originalColumn: original != null && original.column, source: source, name: name }); }; /** * Set the source content for a source file. */ SourceMapGenerator.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { var source = aSourceFile; if (this._sourceRoot != null) { source = util.relative(this._sourceRoot, source); } if (aSourceContent != null) { // Add the source content to the _sourcesContents map. // Create a new _sourcesContents map if the property is null. if (!this._sourcesContents) { this._sourcesContents = Object.create(null); } this._sourcesContents[util.toSetString(source)] = aSourceContent; } else if (this._sourcesContents) { // Remove the source file from the _sourcesContents map. // If the _sourcesContents map is empty, set the property to null. delete this._sourcesContents[util.toSetString(source)]; if (Object.keys(this._sourcesContents).length === 0) { this._sourcesContents = null; } } }; /** * Applies the mappings of a sub-source-map for a specific source file to the * source map being generated. Each mapping to the supplied source file is * rewritten using the supplied source map. Note: The resolution for the * resulting mappings is the minimium of this map and the supplied map. * * @param aSourceMapConsumer The source map to be applied. * @param aSourceFile Optional. The filename of the source file. * If omitted, SourceMapConsumer's file property will be used. * @param aSourceMapPath Optional. The dirname of the path to the source map * to be applied. If relative, it is relative to the SourceMapConsumer. * This parameter is needed when the two source maps aren't in the same * directory, and the source map to be applied contains relative source * paths. If so, those relative source paths need to be rewritten * relative to the SourceMapGenerator. */ SourceMapGenerator.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { var sourceFile = aSourceFile; // If aSourceFile is omitted, we will use the file property of the SourceMap if (aSourceFile == null) { if (aSourceMapConsumer.file == null) { throw new Error( 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + 'or the source map\'s "file" property. Both were omitted.' ); } sourceFile = aSourceMapConsumer.file; } var sourceRoot = this._sourceRoot; // Make "sourceFile" relative if an absolute Url is passed. if (sourceRoot != null) { sourceFile = util.relative(sourceRoot, sourceFile); } // Applying the SourceMap can add and remove items from the sources and // the names array. var newSources = new ArraySet(); var newNames = new ArraySet(); // Find mappings for the "sourceFile" this._mappings.unsortedForEach(function (mapping) { if (mapping.source === sourceFile && mapping.originalLine != null) { // Check if it can be mapped by the source map, then update the mapping. var original = aSourceMapConsumer.originalPositionFor({ line: mapping.originalLine, column: mapping.originalColumn }); if (original.source != null) { // Copy mapping mapping.source = original.source; if (aSourceMapPath != null) { mapping.source = util.join(aSourceMapPath, mapping.source) } if (sourceRoot != null) { mapping.source = util.relative(sourceRoot, mapping.source); } mapping.originalLine = original.line; mapping.originalColumn = original.column; if (original.name != null) { mapping.name = original.name; } } } var source = mapping.source; if (source != null && !newSources.has(source)) { newSources.add(source); } var name = mapping.name; if (name != null && !newNames.has(name)) { newNames.add(name); } }, this); this._sources = newSources; this._names = newNames; // Copy sourcesContents of applied map. aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content != null) { if (aSourceMapPath != null) { sourceFile = util.join(aSourceMapPath, sourceFile); } if (sourceRoot != null) { sourceFile = util.relative(sourceRoot, sourceFile); } this.setSourceContent(sourceFile, content); } }, this); }; /** * A mapping can have one of the three levels of data: * * 1. Just the generated position. * 2. The Generated position, original position, and original source. * 3. Generated and original position, original source, as well as a name * token. * * To maintain consistency, we validate that any new mapping being added falls * in to one of these categories. */ SourceMapGenerator.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) { // When aOriginal is truthy but has empty values for .line and .column, // it is most likely a programmer error. In this case we throw a very // specific error message to try to guide them the right way. // For example: https://github.com/Polymer/polymer-bundler/pull/519 if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { throw new Error( 'original.line and original.column are not numbers -- you probably meant to omit ' + 'the original mapping entirely and only map the generated position. If so, pass ' + 'null for the original mapping instead of an object with empty or null values.' ); } if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) { // Case 1. return; } else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aOriginal && 'line' in aOriginal && 'column' in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) { // Cases 2 and 3. return; } else { throw new Error('Invalid mapping: ' + JSON.stringify({ generated: aGenerated, source: aSource, original: aOriginal, name: aName })); } }; /** * Serialize the accumulated mappings in to the stream of base 64 VLQs * specified by the source map format. */ SourceMapGenerator.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() { var previousGeneratedColumn = 0; var previousGeneratedLine = 1; var previousOriginalColumn = 0; var previousOriginalLine = 0; var previousName = 0; var previousSource = 0; var result = ''; var next; var mapping; var nameIdx; var sourceIdx; var mappings = this._mappings.toArray(); for (var i = 0, len = mappings.length; i < len; i++) { mapping = mappings[i]; next = '' if (mapping.generatedLine !== previousGeneratedLine) { previousGeneratedColumn = 0; while (mapping.generatedLine !== previousGeneratedLine) { next += ';'; previousGeneratedLine++; } } else { if (i > 0) { if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { continue; } next += ','; } } next += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn); previousGeneratedColumn = mapping.generatedColumn; if (mapping.source != null) { sourceIdx = this._sources.indexOf(mapping.source); next += base64VLQ.encode(sourceIdx - previousSource); previousSource = sourceIdx; // lines are stored 0-based in SourceMap spec version 3 next += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine); previousOriginalLine = mapping.originalLine - 1; next += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn); previousOriginalColumn = mapping.originalColumn; if (mapping.name != null) { nameIdx = this._names.indexOf(mapping.name); next += base64VLQ.encode(nameIdx - previousName); previousName = nameIdx; } } result += next; } return result; }; SourceMapGenerator.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { return aSources.map(function (source) { if (!this._sourcesContents) { return null; } if (aSourceRoot != null) { source = util.relative(aSourceRoot, source); } var key = util.toSetString(source); return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null; }, this); }; /** * Externalize the source map. */ SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() { var map = { version: this._version, sources: this._sources.toArray(), names: this._names.toArray(), mappings: this._serializeMappings() }; if (this._file != null) { map.file = this._file; } if (this._sourceRoot != null) { map.sourceRoot = this._sourceRoot; } if (this._sourcesContents) { map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); } return map; }; /** * Render the source map being generated to a string. */ SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() { return JSON.stringify(this.toJSON()); }; exports.SourceMapGenerator = SourceMapGenerator; },{"./array-set":439,"./base64-vlq":440,"./mapping-list":443,"./util":448}],447:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; var util = require('./util'); // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other // operating systems these days (capturing the result). var REGEX_NEWLINE = /(\r?\n)/; // Newline character code for charCodeAt() comparisons var NEWLINE_CODE = 10; // Private symbol for identifying `SourceNode`s when multiple versions of // the source-map library are loaded. This MUST NOT CHANGE across // versions! var isSourceNode = "$$$isSourceNode$$$"; /** * SourceNodes provide a way to abstract over interpolating/concatenating * snippets of generated JavaScript source code while maintaining the line and * column information associated with the original source code. * * @param aLine The original line number. * @param aColumn The original column number. * @param aSource The original source's filename. * @param aChunks Optional. An array of strings which are snippets of * generated JS, or other SourceNodes. * @param aName The original identifier. */ function SourceNode(aLine, aColumn, aSource, aChunks, aName) { this.children = []; this.sourceContents = {}; this.line = aLine == null ? null : aLine; this.column = aColumn == null ? null : aColumn; this.source = aSource == null ? null : aSource; this.name = aName == null ? null : aName; this[isSourceNode] = true; if (aChunks != null) this.add(aChunks); } /** * Creates a SourceNode from generated code and a SourceMapConsumer. * * @param aGeneratedCode The generated code * @param aSourceMapConsumer The SourceMap for the generated code * @param aRelativePath Optional. The path that relative sources in the * SourceMapConsumer should be relative to. */ SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { // The SourceNode we want to fill with the generated code // and the SourceMap var node = new SourceNode(); // All even indices of this array are one line of the generated code, // while all odd indices are the newlines between two adjacent lines // (since `REGEX_NEWLINE` captures its match). // Processed fragments are accessed by calling `shiftNextLine`. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); var remainingLinesIndex = 0; var shiftNextLine = function() { var lineContents = getNextLine(); // The last line of a file might not have a newline. var newLine = getNextLine() || ""; return lineContents + newLine; function getNextLine() { return remainingLinesIndex < remainingLines.length ? remainingLines[remainingLinesIndex++] : undefined; } }; // We need to remember the position of "remainingLines" var lastGeneratedLine = 1, lastGeneratedColumn = 0; // The generate SourceNodes we need a code range. // To extract it current and last mapping is used. // Here we store the last mapping. var lastMapping = null; aSourceMapConsumer.eachMapping(function (mapping) { if (lastMapping !== null) { // We add the code from "lastMapping" to "mapping": // First check if there is a new line in between. if (lastGeneratedLine < mapping.generatedLine) { // Associate first line with "lastMapping" addMappingWithCode(lastMapping, shiftNextLine()); lastGeneratedLine++; lastGeneratedColumn = 0; // The remaining code is added without mapping } else { // There is no new line in between. // Associate the code between "lastGeneratedColumn" and // "mapping.generatedColumn" with "lastMapping" var nextLine = remainingLines[remainingLinesIndex]; var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn); remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn); lastGeneratedColumn = mapping.generatedColumn; addMappingWithCode(lastMapping, code); // No more remaining code, continue lastMapping = mapping; return; } } // We add the generated code until the first mapping // to the SourceNode without any mapping. // Each line is added as separate string. while (lastGeneratedLine < mapping.generatedLine) { node.add(shiftNextLine()); lastGeneratedLine++; } if (lastGeneratedColumn < mapping.generatedColumn) { var nextLine = remainingLines[remainingLinesIndex]; node.add(nextLine.substr(0, mapping.generatedColumn)); remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); lastGeneratedColumn = mapping.generatedColumn; } lastMapping = mapping; }, this); // We have processed all mappings. if (remainingLinesIndex < remainingLines.length) { if (lastMapping) { // Associate the remaining code in the current line with "lastMapping" addMappingWithCode(lastMapping, shiftNextLine()); } // and add the remaining lines without any mapping node.add(remainingLines.splice(remainingLinesIndex).join("")); } // Copy sourcesContent into SourceNode aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content != null) { if (aRelativePath != null) { sourceFile = util.join(aRelativePath, sourceFile); } node.setSourceContent(sourceFile, content); } }); return node; function addMappingWithCode(mapping, code) { if (mapping === null || mapping.source === undefined) { node.add(code); } else { var source = aRelativePath ? util.join(aRelativePath, mapping.source) : mapping.source; node.add(new SourceNode(mapping.originalLine, mapping.originalColumn, source, code, mapping.name)); } } }; /** * Add a chunk of generated JS to this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ SourceNode.prototype.add = function SourceNode_add(aChunk) { if (Array.isArray(aChunk)) { aChunk.forEach(function (chunk) { this.add(chunk); }, this); } else if (aChunk[isSourceNode] || typeof aChunk === "string") { if (aChunk) { this.children.push(aChunk); } } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; /** * Add a chunk of generated JS to the beginning of this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { if (Array.isArray(aChunk)) { for (var i = aChunk.length-1; i >= 0; i--) { this.prepend(aChunk[i]); } } else if (aChunk[isSourceNode] || typeof aChunk === "string") { this.children.unshift(aChunk); } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; /** * Walk over the tree of JS snippets in this node and its children. The * walking function is called once for each snippet of JS and is passed that * snippet and the its original associated source's line/column location. * * @param aFn The traversal function. */ SourceNode.prototype.walk = function SourceNode_walk(aFn) { var chunk; for (var i = 0, len = this.children.length; i < len; i++) { chunk = this.children[i]; if (chunk[isSourceNode]) { chunk.walk(aFn); } else { if (chunk !== '') { aFn(chunk, { source: this.source, line: this.line, column: this.column, name: this.name }); } } } }; /** * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between * each of `this.children`. * * @param aSep The separator. */ SourceNode.prototype.join = function SourceNode_join(aSep) { var newChildren; var i; var len = this.children.length; if (len > 0) { newChildren = []; for (i = 0; i < len-1; i++) { newChildren.push(this.children[i]); newChildren.push(aSep); } newChildren.push(this.children[i]); this.children = newChildren; } return this; }; /** * Call String.prototype.replace on the very right-most source snippet. Useful * for trimming whitespace from the end of a source node, etc. * * @param aPattern The pattern to replace. * @param aReplacement The thing to replace the pattern with. */ SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { var lastChild = this.children[this.children.length - 1]; if (lastChild[isSourceNode]) { lastChild.replaceRight(aPattern, aReplacement); } else if (typeof lastChild === 'string') { this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); } else { this.children.push(''.replace(aPattern, aReplacement)); } return this; }; /** * Set the source content for a source file. This will be added to the SourceMapGenerator * in the sourcesContent field. * * @param aSourceFile The filename of the source file * @param aSourceContent The content of the source file */ SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) { this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; }; /** * Walk over the tree of SourceNodes. The walking function is called for each * source file content and is passed the filename and source content. * * @param aFn The traversal function. */ SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) { for (var i = 0, len = this.children.length; i < len; i++) { if (this.children[i][isSourceNode]) { this.children[i].walkSourceContents(aFn); } } var sources = Object.keys(this.sourceContents); for (var i = 0, len = sources.length; i < len; i++) { aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); } }; /** * Return the string representation of this source node. Walks over the tree * and concatenates all the various snippets together to one string. */ SourceNode.prototype.toString = function SourceNode_toString() { var str = ""; this.walk(function (chunk) { str += chunk; }); return str; }; /** * Returns the string representation of this source node along with a source * map. */ SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { var generated = { code: "", line: 1, column: 0 }; var map = new SourceMapGenerator(aArgs); var sourceMappingActive = false; var lastOriginalSource = null; var lastOriginalLine = null; var lastOriginalColumn = null; var lastOriginalName = null; this.walk(function (chunk, original) { generated.code += chunk; if (original.source !== null && original.line !== null && original.column !== null) { if(lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) { map.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name }); } lastOriginalSource = original.source; lastOriginalLine = original.line; lastOriginalColumn = original.column; lastOriginalName = original.name; sourceMappingActive = true; } else if (sourceMappingActive) { map.addMapping({ generated: { line: generated.line, column: generated.column } }); lastOriginalSource = null; sourceMappingActive = false; } for (var idx = 0, length = chunk.length; idx < length; idx++) { if (chunk.charCodeAt(idx) === NEWLINE_CODE) { generated.line++; generated.column = 0; // Mappings end at eol if (idx + 1 === length) { lastOriginalSource = null; sourceMappingActive = false; } else if (sourceMappingActive) { map.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name }); } } else { generated.column++; } } }); this.walkSourceContents(function (sourceFile, sourceContent) { map.setSourceContent(sourceFile, sourceContent); }); return { code: generated.code, map: map }; }; exports.SourceNode = SourceNode; },{"./source-map-generator":446,"./util":448}],448:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ /** * This is a helper function for getting values from parameter/options * objects. * * @param args The object we are extracting values from * @param name The name of the property we are getting. * @param defaultValue An optional value to return if the property is missing * from the object. If this is not specified and the property is missing, an * error will be thrown. */ function getArg(aArgs, aName, aDefaultValue) { if (aName in aArgs) { return aArgs[aName]; } else if (arguments.length === 3) { return aDefaultValue; } else { throw new Error('"' + aName + '" is a required argument.'); } } exports.getArg = getArg; var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/; var dataUrlRegexp = /^data:.+\,.+$/; function urlParse(aUrl) { var match = aUrl.match(urlRegexp); if (!match) { return null; } return { scheme: match[1], auth: match[2], host: match[3], port: match[4], path: match[5] }; } exports.urlParse = urlParse; function urlGenerate(aParsedUrl) { var url = ''; if (aParsedUrl.scheme) { url += aParsedUrl.scheme + ':'; } url += '//'; if (aParsedUrl.auth) { url += aParsedUrl.auth + '@'; } if (aParsedUrl.host) { url += aParsedUrl.host; } if (aParsedUrl.port) { url += ":" + aParsedUrl.port } if (aParsedUrl.path) { url += aParsedUrl.path; } return url; } exports.urlGenerate = urlGenerate; /** * Normalizes a path, or the path portion of a URL: * * - Replaces consecutive slashes with one slash. * - Removes unnecessary '.' parts. * - Removes unnecessary '<dir>/..' parts. * * Based on code in the Node.js 'path' core module. * * @param aPath The path or url to normalize. */ function normalize(aPath) { var path = aPath; var url = urlParse(aPath); if (url) { if (!url.path) { return aPath; } path = url.path; } var isAbsolute = exports.isAbsolute(path); var parts = path.split(/\/+/); for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { part = parts[i]; if (part === '.') { parts.splice(i, 1); } else if (part === '..') { up++; } else if (up > 0) { if (part === '') { // The first part is blank if the path is absolute. Trying to go // above the root is a no-op. Therefore we can remove all '..' parts // directly after the root. parts.splice(i + 1, up); up = 0; } else { parts.splice(i, 2); up--; } } } path = parts.join('/'); if (path === '') { path = isAbsolute ? '/' : '.'; } if (url) { url.path = path; return urlGenerate(url); } return path; } exports.normalize = normalize; /** * Joins two paths/URLs. * * @param aRoot The root path or URL. * @param aPath The path or URL to be joined with the root. * * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a * scheme-relative URL: Then the scheme of aRoot, if any, is prepended * first. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion * is updated with the result and aRoot is returned. Otherwise the result * is returned. * - If aPath is absolute, the result is aPath. * - Otherwise the two paths are joined with a slash. * - Joining for example 'http://' and 'www.example.com' is also supported. */ function join(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } if (aPath === "") { aPath = "."; } var aPathUrl = urlParse(aPath); var aRootUrl = urlParse(aRoot); if (aRootUrl) { aRoot = aRootUrl.path || '/'; } // `join(foo, '//www.example.org')` if (aPathUrl && !aPathUrl.scheme) { if (aRootUrl) { aPathUrl.scheme = aRootUrl.scheme; } return urlGenerate(aPathUrl); } if (aPathUrl || aPath.match(dataUrlRegexp)) { return aPath; } // `join('http://', 'www.example.com')` if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { aRootUrl.host = aPath; return urlGenerate(aRootUrl); } var joined = aPath.charAt(0) === '/' ? aPath : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); if (aRootUrl) { aRootUrl.path = joined; return urlGenerate(aRootUrl); } return joined; } exports.join = join; exports.isAbsolute = function (aPath) { return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp); }; /** * Make a path relative to a URL or another path. * * @param aRoot The root path or URL. * @param aPath The path or URL to be made relative to aRoot. */ function relative(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } aRoot = aRoot.replace(/\/$/, ''); // It is possible for the path to be above the root. In this case, simply // checking whether the root is a prefix of the path won't work. Instead, we // need to remove components from the root one by one, until either we find // a prefix that fits, or we run out of components to remove. var level = 0; while (aPath.indexOf(aRoot + '/') !== 0) { var index = aRoot.lastIndexOf("/"); if (index < 0) { return aPath; } // If the only part of the root that is left is the scheme (i.e. http://, // file:///, etc.), one or more slashes (/), or simply nothing at all, we // have exhausted all components, so the path is not relative to the root. aRoot = aRoot.slice(0, index); if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { return aPath; } ++level; } // Make sure we add a "../" for each component we removed from the root. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); } exports.relative = relative; var supportsNullProto = (function () { var obj = Object.create(null); return !('__proto__' in obj); }()); function identity (s) { return s; } /** * Because behavior goes wacky when you set `__proto__` on objects, we * have to prefix all the strings in our set with an arbitrary character. * * See https://github.com/mozilla/source-map/pull/31 and * https://github.com/mozilla/source-map/issues/30 * * @param String aStr */ function toSetString(aStr) { if (isProtoString(aStr)) { return '$' + aStr; } return aStr; } exports.toSetString = supportsNullProto ? identity : toSetString; function fromSetString(aStr) { if (isProtoString(aStr)) { return aStr.slice(1); } return aStr; } exports.fromSetString = supportsNullProto ? identity : fromSetString; function isProtoString(s) { if (!s) { return false; } var length = s.length; if (length < 9 /* "__proto__".length */) { return false; } if (s.charCodeAt(length - 1) !== 95 /* '_' */ || s.charCodeAt(length - 2) !== 95 /* '_' */ || s.charCodeAt(length - 3) !== 111 /* 'o' */ || s.charCodeAt(length - 4) !== 116 /* 't' */ || s.charCodeAt(length - 5) !== 111 /* 'o' */ || s.charCodeAt(length - 6) !== 114 /* 'r' */ || s.charCodeAt(length - 7) !== 112 /* 'p' */ || s.charCodeAt(length - 8) !== 95 /* '_' */ || s.charCodeAt(length - 9) !== 95 /* '_' */) { return false; } for (var i = length - 10; i >= 0; i--) { if (s.charCodeAt(i) !== 36 /* '$' */) { return false; } } return true; } /** * Comparator between two mappings where the original positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same original source/line/column, but different generated * line and column the same. Useful when searching for a mapping with a * stubbed out mapping. */ function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { var cmp = mappingA.source - mappingB.source; if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0 || onlyCompareOriginal) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } return mappingA.name - mappingB.name; } exports.compareByOriginalPositions = compareByOriginalPositions; /** * Comparator between two mappings with deflated source and name indices where * the generated positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same generated line and column, but different * source/name/original line and column the same. Useful when searching for a * mapping with a stubbed out mapping. */ function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0 || onlyCompareGenerated) { return cmp; } cmp = mappingA.source - mappingB.source; if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return mappingA.name - mappingB.name; } exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; function strcmp(aStr1, aStr2) { if (aStr1 === aStr2) { return 0; } if (aStr1 > aStr2) { return 1; } return -1; } /** * Comparator between two mappings with inflated source and name strings where * the generated positions are compared. */ function compareByGeneratedPositionsInflated(mappingA, mappingB) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; },{}],449:[function(require,module,exports){ /* * Copyright 2009-2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE.txt or: * http://opensource.org/licenses/BSD-3-Clause */ exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator; exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer; exports.SourceNode = require('./lib/source-node').SourceNode; },{"./lib/source-map-consumer":445,"./lib/source-map-generator":446,"./lib/source-node":447}],450:[function(require,module,exports){ 'use strict'; module.exports = (string, separator) => { if (!(typeof string === 'string' && typeof separator === 'string')) { throw new TypeError('Expected the arguments to be of type `string`'); } if (separator === '') { return [string]; } const separatorIndex = string.indexOf(separator); if (separatorIndex === -1) { return [string]; } return [ string.slice(0, separatorIndex), string.slice(separatorIndex + separator.length) ]; }; },{}],451:[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":199,"inherits":203,"readable-stream/duplex.js":418,"readable-stream/passthrough.js":427,"readable-stream/readable.js":428,"readable-stream/transform.js":429,"readable-stream/writable.js":430}],452:[function(require,module,exports){ 'use strict'; module.exports = str => encodeURIComponent(str).replace(/[!'()*]/g, x => `%${x.charCodeAt(0).toString(16).toUpperCase()}`); },{}],453:[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":431}],454:[function(require,module,exports){ 'use strict'; module.exports = { stdout: false, stderr: false }; },{}],455:[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":405,"timers":455}],456:[function(require,module,exports){ 'use strict'; let fastProto = null; // Creates an object with permanently fast properties in V8. See Toon Verwaest's // post https://medium.com/@tverwaes/setting-up-prototypes-in-v8-ec9c9491dfe2#5f62 // for more details. Use %HasFastProperties(object) and the Node.js flag // --allow-natives-syntax to check whether an object has fast properties. function FastObject(o) { // A prototype object will have "fast properties" enabled once it is checked // against the inline property cache of a function, e.g. fastProto.property: // https://github.com/v8/v8/blob/6.0.122/test/mjsunit/fast-prototype.js#L48-L63 if (fastProto !== null && typeof fastProto.property) { const result = fastProto; fastProto = FastObject.prototype = null; return result; } fastProto = FastObject.prototype = o == null ? Object.create(null) : o; return new FastObject; } // Initialize the inline property cache of FastObject FastObject(); module.exports = function toFastproperties(o) { return FastObject(o); }; },{}],457:[function(require,module,exports){ 'use strict'; module.exports = function (str) { var tail = str.length; while (/[\s\uFEFF\u00A0]/.test(str[tail - 1])) { tail--; } return str.slice(0, tail); }; },{}],458:[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 : {}) },{}],459:[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 } } },{}],460:[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'; } },{}],461:[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":460,"_process":405,"inherits":459}]},{},[7]);