← Back
Editing: client-legacy-bundle.js
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = global || self, global.fetchMock = factory()); }(this, (function () { 'use strict'; var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function commonjsRequire () { throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs'); } function unwrapExports (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } function getCjsExportFromNamespace (n) { return n && n['default'] || n; } var global$1 = (typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}); // shim for using process in browser // based off https://github.com/defunctzombie/node-process/blob/master/browser.js function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } var cachedSetTimeout = defaultSetTimout; var cachedClearTimeout = defaultClearTimeout; if (typeof global$1.setTimeout === 'function') { cachedSetTimeout = setTimeout; } if (typeof global$1.clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } function nextTick(fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } } // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; var title = 'browser'; var platform = 'browser'; var browser = true; var env = {}; var argv = []; var version = ''; // empty string to avoid regexp issues var versions = {}; var release = {}; var config = {}; function noop() {} var on = noop; var addListener = noop; var once = noop; var off = noop; var removeListener = noop; var removeAllListeners = noop; var emit = noop; function binding(name) { throw new Error('process.binding is not supported'); } function cwd () { return '/' } function chdir (dir) { throw new Error('process.chdir is not supported'); }function umask() { return 0; } // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js var performance = global$1.performance || {}; var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function(){ return (new Date()).getTime() }; // generate timestamp or delta // see http://nodejs.org/api/process.html#process_process_hrtime function hrtime(previousTimestamp){ var clocktime = performanceNow.call(performance)*1e-3; var seconds = Math.floor(clocktime); var nanoseconds = Math.floor((clocktime%1)*1e9); if (previousTimestamp) { seconds = seconds - previousTimestamp[0]; nanoseconds = nanoseconds - previousTimestamp[1]; if (nanoseconds<0) { seconds--; nanoseconds += 1e9; } } return [seconds,nanoseconds] } var startTime = new Date(); function uptime() { var currentTime = new Date(); var dif = currentTime - startTime; return dif / 1000; } var process = { nextTick: nextTick, title: title, browser: browser, env: env, argv: argv, version: version, versions: versions, on: on, addListener: addListener, once: once, off: off, removeListener: removeListener, removeAllListeners: removeAllListeners, emit: emit, binding: binding, cwd: cwd, chdir: chdir, umask: umask, hrtime: hrtime, platform: platform, release: release, config: config, uptime: uptime }; var shallowEqual_1 = createCommonjsModule(function (module, exports) { 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; } }); unwrapExports(shallowEqual_1); var generated = createCommonjsModule(function (module, exports) { 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.isClassExpression = isClassExpression; exports.isClassDeclaration = isClassDeclaration; 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.isAwaitExpression = isAwaitExpression; exports.isImport = isImport; exports.isBigIntLiteral = isBigIntLiteral; exports.isExportNamespaceSpecifier = isExportNamespaceSpecifier; exports.isOptionalMemberExpression = isOptionalMemberExpression; exports.isOptionalCallExpression = isOptionalCallExpression; 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.isSymbolTypeAnnotation = isSymbolTypeAnnotation; 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.isEnumDeclaration = isEnumDeclaration; exports.isEnumBooleanBody = isEnumBooleanBody; exports.isEnumNumberBody = isEnumNumberBody; exports.isEnumStringBody = isEnumStringBody; exports.isEnumSymbolBody = isEnumSymbolBody; exports.isEnumBooleanMember = isEnumBooleanMember; exports.isEnumNumberMember = isEnumNumberMember; exports.isEnumStringMember = isEnumStringMember; exports.isEnumDefaultedMember = isEnumDefaultedMember; 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.isV8IntrinsicIdentifier = isV8IntrinsicIdentifier; exports.isArgumentPlaceholder = isArgumentPlaceholder; exports.isBindExpression = isBindExpression; exports.isClassProperty = isClassProperty; exports.isPipelineTopicExpression = isPipelineTopicExpression; exports.isPipelineBareFunction = isPipelineBareFunction; exports.isPipelinePrimaryTopicReference = isPipelinePrimaryTopicReference; exports.isClassPrivateProperty = isClassPrivateProperty; exports.isClassPrivateMethod = isClassPrivateMethod; exports.isImportAttribute = isImportAttribute; exports.isDecorator = isDecorator; exports.isDoExpression = isDoExpression; exports.isExportDefaultSpecifier = isExportDefaultSpecifier; exports.isPrivateName = isPrivateName; exports.isRecordExpression = isRecordExpression; exports.isTupleExpression = isTupleExpression; exports.isDecimalLiteral = isDecimalLiteral; exports.isStaticBlock = isStaticBlock; 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.isTSBooleanKeyword = isTSBooleanKeyword; exports.isTSBigIntKeyword = isTSBigIntKeyword; exports.isTSIntrinsicKeyword = isTSIntrinsicKeyword; exports.isTSNeverKeyword = isTSNeverKeyword; exports.isTSNullKeyword = isTSNullKeyword; exports.isTSNumberKeyword = isTSNumberKeyword; exports.isTSObjectKeyword = isTSObjectKeyword; exports.isTSStringKeyword = isTSStringKeyword; exports.isTSSymbolKeyword = isTSSymbolKeyword; exports.isTSUndefinedKeyword = isTSUndefinedKeyword; exports.isTSUnknownKeyword = isTSUnknownKeyword; exports.isTSVoidKeyword = isTSVoidKeyword; 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.isTSNamedTupleMember = isTSNamedTupleMember; 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.isEnumBody = isEnumBody; exports.isEnumMember = isEnumMember; exports.isJSX = isJSX; exports.isPrivate = isPrivate; exports.isTSTypeElement = isTSTypeElement; exports.isTSType = isTSType; exports.isTSBaseType = isTSBaseType; exports.isNumberLiteral = isNumberLiteral; exports.isRegexLiteral = isRegexLiteral; exports.isRestProperty = isRestProperty; exports.isSpreadProperty = isSpreadProperty; var _shallowEqual = _interopRequireDefault(shallowEqual_1); 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 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 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 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 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 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 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 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 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 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 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 isSymbolTypeAnnotation(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "SymbolTypeAnnotation") { 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 isEnumDeclaration(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "EnumDeclaration") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isEnumBooleanBody(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "EnumBooleanBody") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isEnumNumberBody(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "EnumNumberBody") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isEnumStringBody(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "EnumStringBody") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isEnumSymbolBody(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "EnumSymbolBody") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isEnumBooleanMember(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "EnumBooleanMember") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isEnumNumberMember(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "EnumNumberMember") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isEnumStringMember(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "EnumStringMember") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isEnumDefaultedMember(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "EnumDefaultedMember") { 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 isV8IntrinsicIdentifier(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "V8IntrinsicIdentifier") { 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 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 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 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 isImportAttribute(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "ImportAttribute") { 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 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 isRecordExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "RecordExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTupleExpression(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TupleExpression") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isDecimalLiteral(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "DecimalLiteral") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isStaticBlock(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "StaticBlock") { 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 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 isTSBigIntKeyword(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSBigIntKeyword") { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isTSIntrinsicKeyword(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSIntrinsicKeyword") { 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 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 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 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 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 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 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 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 isTSNamedTupleMember(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSNamedTupleMember") { 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 || "AwaitExpression" === nodeType || "Import" === nodeType || "BigIntLiteral" === nodeType || "OptionalMemberExpression" === nodeType || "OptionalCallExpression" === nodeType || "TypeCastExpression" === nodeType || "JSXElement" === nodeType || "JSXFragment" === nodeType || "BindExpression" === nodeType || "PipelinePrimaryTopicReference" === nodeType || "DoExpression" === nodeType || "RecordExpression" === nodeType || "TupleExpression" === nodeType || "DecimalLiteral" === 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 || "ClassExpression" === nodeType || "ClassDeclaration" === nodeType || "ForOfStatement" === nodeType || "ClassMethod" === nodeType || "ClassPrivateMethod" === nodeType || "StaticBlock" === nodeType || "TSModuleBlock" === 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 || "StaticBlock" === nodeType || "TSModuleBlock" === 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 || "TSModuleBlock" === 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 || "EnumDeclaration" === 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 || "RegExpLiteral" === nodeType || "ArrowFunctionExpression" === nodeType || "BigIntLiteral" === nodeType || "DecimalLiteral" === 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 || "EnumDeclaration" === 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 || "DecimalLiteral" === 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 || "BigIntLiteral" === nodeType || "JSXAttribute" === nodeType || "JSXClosingElement" === nodeType || "JSXElement" === nodeType || "JSXExpressionContainer" === nodeType || "JSXSpreadChild" === nodeType || "JSXOpeningElement" === nodeType || "JSXText" === nodeType || "JSXFragment" === nodeType || "JSXOpeningFragment" === nodeType || "JSXClosingFragment" === nodeType || "DecimalLiteral" === 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" || "ClassExpression" === nodeType || "ClassDeclaration" === 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 || "ExportNamespaceSpecifier" === nodeType || "ExportDefaultSpecifier" === 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 || "SymbolTypeAnnotation" === 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 || "SymbolTypeAnnotation" === 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 || "SymbolTypeAnnotation" === 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 isEnumBody(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "EnumBody" || "EnumBooleanBody" === nodeType || "EnumNumberBody" === nodeType || "EnumStringBody" === nodeType || "EnumSymbolBody" === nodeType) { if (typeof opts === "undefined") { return true; } else { return (0, _shallowEqual.default)(node, opts); } } return false; } function isEnumMember(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "EnumMember" || "EnumBooleanMember" === nodeType || "EnumNumberMember" === nodeType || "EnumStringMember" === nodeType || "EnumDefaultedMember" === 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 || "TSBooleanKeyword" === nodeType || "TSBigIntKeyword" === nodeType || "TSIntrinsicKeyword" === nodeType || "TSNeverKeyword" === nodeType || "TSNullKeyword" === nodeType || "TSNumberKeyword" === nodeType || "TSObjectKeyword" === nodeType || "TSStringKeyword" === nodeType || "TSSymbolKeyword" === nodeType || "TSUndefinedKeyword" === nodeType || "TSUnknownKeyword" === nodeType || "TSVoidKeyword" === 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 isTSBaseType(node, opts) { if (!node) return false; const nodeType = node.type; if (nodeType === "TSBaseType" || "TSAnyKeyword" === nodeType || "TSBooleanKeyword" === nodeType || "TSBigIntKeyword" === nodeType || "TSIntrinsicKeyword" === nodeType || "TSNeverKeyword" === nodeType || "TSNullKeyword" === nodeType || "TSNumberKeyword" === nodeType || "TSObjectKeyword" === nodeType || "TSStringKeyword" === nodeType || "TSSymbolKeyword" === nodeType || "TSUndefinedKeyword" === nodeType || "TSUnknownKeyword" === nodeType || "TSVoidKeyword" === nodeType || "TSThisType" === nodeType || "TSLiteralType" === 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; } }); unwrapExports(generated); var generated_1 = generated.isArrayExpression; var generated_2 = generated.isAssignmentExpression; var generated_3 = generated.isBinaryExpression; var generated_4 = generated.isInterpreterDirective; var generated_5 = generated.isDirective; var generated_6 = generated.isDirectiveLiteral; var generated_7 = generated.isBlockStatement; var generated_8 = generated.isBreakStatement; var generated_9 = generated.isCallExpression; var generated_10 = generated.isCatchClause; var generated_11 = generated.isConditionalExpression; var generated_12 = generated.isContinueStatement; var generated_13 = generated.isDebuggerStatement; var generated_14 = generated.isDoWhileStatement; var generated_15 = generated.isEmptyStatement; var generated_16 = generated.isExpressionStatement; var generated_17 = generated.isFile; var generated_18 = generated.isForInStatement; var generated_19 = generated.isForStatement; var generated_20 = generated.isFunctionDeclaration; var generated_21 = generated.isFunctionExpression; var generated_22 = generated.isIdentifier; var generated_23 = generated.isIfStatement; var generated_24 = generated.isLabeledStatement; var generated_25 = generated.isStringLiteral; var generated_26 = generated.isNumericLiteral; var generated_27 = generated.isNullLiteral; var generated_28 = generated.isBooleanLiteral; var generated_29 = generated.isRegExpLiteral; var generated_30 = generated.isLogicalExpression; var generated_31 = generated.isMemberExpression; var generated_32 = generated.isNewExpression; var generated_33 = generated.isProgram; var generated_34 = generated.isObjectExpression; var generated_35 = generated.isObjectMethod; var generated_36 = generated.isObjectProperty; var generated_37 = generated.isRestElement; var generated_38 = generated.isReturnStatement; var generated_39 = generated.isSequenceExpression; var generated_40 = generated.isParenthesizedExpression; var generated_41 = generated.isSwitchCase; var generated_42 = generated.isSwitchStatement; var generated_43 = generated.isThisExpression; var generated_44 = generated.isThrowStatement; var generated_45 = generated.isTryStatement; var generated_46 = generated.isUnaryExpression; var generated_47 = generated.isUpdateExpression; var generated_48 = generated.isVariableDeclaration; var generated_49 = generated.isVariableDeclarator; var generated_50 = generated.isWhileStatement; var generated_51 = generated.isWithStatement; var generated_52 = generated.isAssignmentPattern; var generated_53 = generated.isArrayPattern; var generated_54 = generated.isArrowFunctionExpression; var generated_55 = generated.isClassBody; var generated_56 = generated.isClassExpression; var generated_57 = generated.isClassDeclaration; var generated_58 = generated.isExportAllDeclaration; var generated_59 = generated.isExportDefaultDeclaration; var generated_60 = generated.isExportNamedDeclaration; var generated_61 = generated.isExportSpecifier; var generated_62 = generated.isForOfStatement; var generated_63 = generated.isImportDeclaration; var generated_64 = generated.isImportDefaultSpecifier; var generated_65 = generated.isImportNamespaceSpecifier; var generated_66 = generated.isImportSpecifier; var generated_67 = generated.isMetaProperty; var generated_68 = generated.isClassMethod; var generated_69 = generated.isObjectPattern; var generated_70 = generated.isSpreadElement; var generated_71 = generated.isSuper; var generated_72 = generated.isTaggedTemplateExpression; var generated_73 = generated.isTemplateElement; var generated_74 = generated.isTemplateLiteral; var generated_75 = generated.isYieldExpression; var generated_76 = generated.isAwaitExpression; var generated_77 = generated.isImport; var generated_78 = generated.isBigIntLiteral; var generated_79 = generated.isExportNamespaceSpecifier; var generated_80 = generated.isOptionalMemberExpression; var generated_81 = generated.isOptionalCallExpression; var generated_82 = generated.isAnyTypeAnnotation; var generated_83 = generated.isArrayTypeAnnotation; var generated_84 = generated.isBooleanTypeAnnotation; var generated_85 = generated.isBooleanLiteralTypeAnnotation; var generated_86 = generated.isNullLiteralTypeAnnotation; var generated_87 = generated.isClassImplements; var generated_88 = generated.isDeclareClass; var generated_89 = generated.isDeclareFunction; var generated_90 = generated.isDeclareInterface; var generated_91 = generated.isDeclareModule; var generated_92 = generated.isDeclareModuleExports; var generated_93 = generated.isDeclareTypeAlias; var generated_94 = generated.isDeclareOpaqueType; var generated_95 = generated.isDeclareVariable; var generated_96 = generated.isDeclareExportDeclaration; var generated_97 = generated.isDeclareExportAllDeclaration; var generated_98 = generated.isDeclaredPredicate; var generated_99 = generated.isExistsTypeAnnotation; var generated_100 = generated.isFunctionTypeAnnotation; var generated_101 = generated.isFunctionTypeParam; var generated_102 = generated.isGenericTypeAnnotation; var generated_103 = generated.isInferredPredicate; var generated_104 = generated.isInterfaceExtends; var generated_105 = generated.isInterfaceDeclaration; var generated_106 = generated.isInterfaceTypeAnnotation; var generated_107 = generated.isIntersectionTypeAnnotation; var generated_108 = generated.isMixedTypeAnnotation; var generated_109 = generated.isEmptyTypeAnnotation; var generated_110 = generated.isNullableTypeAnnotation; var generated_111 = generated.isNumberLiteralTypeAnnotation; var generated_112 = generated.isNumberTypeAnnotation; var generated_113 = generated.isObjectTypeAnnotation; var generated_114 = generated.isObjectTypeInternalSlot; var generated_115 = generated.isObjectTypeCallProperty; var generated_116 = generated.isObjectTypeIndexer; var generated_117 = generated.isObjectTypeProperty; var generated_118 = generated.isObjectTypeSpreadProperty; var generated_119 = generated.isOpaqueType; var generated_120 = generated.isQualifiedTypeIdentifier; var generated_121 = generated.isStringLiteralTypeAnnotation; var generated_122 = generated.isStringTypeAnnotation; var generated_123 = generated.isSymbolTypeAnnotation; var generated_124 = generated.isThisTypeAnnotation; var generated_125 = generated.isTupleTypeAnnotation; var generated_126 = generated.isTypeofTypeAnnotation; var generated_127 = generated.isTypeAlias; var generated_128 = generated.isTypeAnnotation; var generated_129 = generated.isTypeCastExpression; var generated_130 = generated.isTypeParameter; var generated_131 = generated.isTypeParameterDeclaration; var generated_132 = generated.isTypeParameterInstantiation; var generated_133 = generated.isUnionTypeAnnotation; var generated_134 = generated.isVariance; var generated_135 = generated.isVoidTypeAnnotation; var generated_136 = generated.isEnumDeclaration; var generated_137 = generated.isEnumBooleanBody; var generated_138 = generated.isEnumNumberBody; var generated_139 = generated.isEnumStringBody; var generated_140 = generated.isEnumSymbolBody; var generated_141 = generated.isEnumBooleanMember; var generated_142 = generated.isEnumNumberMember; var generated_143 = generated.isEnumStringMember; var generated_144 = generated.isEnumDefaultedMember; var generated_145 = generated.isJSXAttribute; var generated_146 = generated.isJSXClosingElement; var generated_147 = generated.isJSXElement; var generated_148 = generated.isJSXEmptyExpression; var generated_149 = generated.isJSXExpressionContainer; var generated_150 = generated.isJSXSpreadChild; var generated_151 = generated.isJSXIdentifier; var generated_152 = generated.isJSXMemberExpression; var generated_153 = generated.isJSXNamespacedName; var generated_154 = generated.isJSXOpeningElement; var generated_155 = generated.isJSXSpreadAttribute; var generated_156 = generated.isJSXText; var generated_157 = generated.isJSXFragment; var generated_158 = generated.isJSXOpeningFragment; var generated_159 = generated.isJSXClosingFragment; var generated_160 = generated.isNoop; var generated_161 = generated.isPlaceholder; var generated_162 = generated.isV8IntrinsicIdentifier; var generated_163 = generated.isArgumentPlaceholder; var generated_164 = generated.isBindExpression; var generated_165 = generated.isClassProperty; var generated_166 = generated.isPipelineTopicExpression; var generated_167 = generated.isPipelineBareFunction; var generated_168 = generated.isPipelinePrimaryTopicReference; var generated_169 = generated.isClassPrivateProperty; var generated_170 = generated.isClassPrivateMethod; var generated_171 = generated.isImportAttribute; var generated_172 = generated.isDecorator; var generated_173 = generated.isDoExpression; var generated_174 = generated.isExportDefaultSpecifier; var generated_175 = generated.isPrivateName; var generated_176 = generated.isRecordExpression; var generated_177 = generated.isTupleExpression; var generated_178 = generated.isDecimalLiteral; var generated_179 = generated.isStaticBlock; var generated_180 = generated.isTSParameterProperty; var generated_181 = generated.isTSDeclareFunction; var generated_182 = generated.isTSDeclareMethod; var generated_183 = generated.isTSQualifiedName; var generated_184 = generated.isTSCallSignatureDeclaration; var generated_185 = generated.isTSConstructSignatureDeclaration; var generated_186 = generated.isTSPropertySignature; var generated_187 = generated.isTSMethodSignature; var generated_188 = generated.isTSIndexSignature; var generated_189 = generated.isTSAnyKeyword; var generated_190 = generated.isTSBooleanKeyword; var generated_191 = generated.isTSBigIntKeyword; var generated_192 = generated.isTSIntrinsicKeyword; var generated_193 = generated.isTSNeverKeyword; var generated_194 = generated.isTSNullKeyword; var generated_195 = generated.isTSNumberKeyword; var generated_196 = generated.isTSObjectKeyword; var generated_197 = generated.isTSStringKeyword; var generated_198 = generated.isTSSymbolKeyword; var generated_199 = generated.isTSUndefinedKeyword; var generated_200 = generated.isTSUnknownKeyword; var generated_201 = generated.isTSVoidKeyword; var generated_202 = generated.isTSThisType; var generated_203 = generated.isTSFunctionType; var generated_204 = generated.isTSConstructorType; var generated_205 = generated.isTSTypeReference; var generated_206 = generated.isTSTypePredicate; var generated_207 = generated.isTSTypeQuery; var generated_208 = generated.isTSTypeLiteral; var generated_209 = generated.isTSArrayType; var generated_210 = generated.isTSTupleType; var generated_211 = generated.isTSOptionalType; var generated_212 = generated.isTSRestType; var generated_213 = generated.isTSNamedTupleMember; var generated_214 = generated.isTSUnionType; var generated_215 = generated.isTSIntersectionType; var generated_216 = generated.isTSConditionalType; var generated_217 = generated.isTSInferType; var generated_218 = generated.isTSParenthesizedType; var generated_219 = generated.isTSTypeOperator; var generated_220 = generated.isTSIndexedAccessType; var generated_221 = generated.isTSMappedType; var generated_222 = generated.isTSLiteralType; var generated_223 = generated.isTSExpressionWithTypeArguments; var generated_224 = generated.isTSInterfaceDeclaration; var generated_225 = generated.isTSInterfaceBody; var generated_226 = generated.isTSTypeAliasDeclaration; var generated_227 = generated.isTSAsExpression; var generated_228 = generated.isTSTypeAssertion; var generated_229 = generated.isTSEnumDeclaration; var generated_230 = generated.isTSEnumMember; var generated_231 = generated.isTSModuleDeclaration; var generated_232 = generated.isTSModuleBlock; var generated_233 = generated.isTSImportType; var generated_234 = generated.isTSImportEqualsDeclaration; var generated_235 = generated.isTSExternalModuleReference; var generated_236 = generated.isTSNonNullExpression; var generated_237 = generated.isTSExportAssignment; var generated_238 = generated.isTSNamespaceExportDeclaration; var generated_239 = generated.isTSTypeAnnotation; var generated_240 = generated.isTSTypeParameterInstantiation; var generated_241 = generated.isTSTypeParameterDeclaration; var generated_242 = generated.isTSTypeParameter; var generated_243 = generated.isExpression; var generated_244 = generated.isBinary; var generated_245 = generated.isScopable; var generated_246 = generated.isBlockParent; var generated_247 = generated.isBlock; var generated_248 = generated.isStatement; var generated_249 = generated.isTerminatorless; var generated_250 = generated.isCompletionStatement; var generated_251 = generated.isConditional; var generated_252 = generated.isLoop; var generated_253 = generated.isWhile; var generated_254 = generated.isExpressionWrapper; var generated_255 = generated.isFor; var generated_256 = generated.isForXStatement; var generated_257 = generated.isFunction; var generated_258 = generated.isFunctionParent; var generated_259 = generated.isPureish; var generated_260 = generated.isDeclaration; var generated_261 = generated.isPatternLike; var generated_262 = generated.isLVal; var generated_263 = generated.isTSEntityName; var generated_264 = generated.isLiteral; var generated_265 = generated.isImmutable; var generated_266 = generated.isUserWhitespacable; var generated_267 = generated.isMethod; var generated_268 = generated.isObjectMember; var generated_269 = generated.isProperty; var generated_270 = generated.isUnaryLike; var generated_271 = generated.isPattern; var generated_272 = generated.isClass; var generated_273 = generated.isModuleDeclaration; var generated_274 = generated.isExportDeclaration; var generated_275 = generated.isModuleSpecifier; var generated_276 = generated.isFlow; var generated_277 = generated.isFlowType; var generated_278 = generated.isFlowBaseAnnotation; var generated_279 = generated.isFlowDeclaration; var generated_280 = generated.isFlowPredicate; var generated_281 = generated.isEnumBody; var generated_282 = generated.isEnumMember; var generated_283 = generated.isJSX; var generated_284 = generated.isPrivate; var generated_285 = generated.isTSTypeElement; var generated_286 = generated.isTSType; var generated_287 = generated.isTSBaseType; var generated_288 = generated.isNumberLiteral; var generated_289 = generated.isRegexLiteral; var generated_290 = generated.isRestProperty; var generated_291 = generated.isSpreadProperty; var matchesPattern_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = matchesPattern; 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; } }); unwrapExports(matchesPattern_1); var buildMatchMemberExpression_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = buildMatchMemberExpression; var _matchesPattern = _interopRequireDefault(matchesPattern_1); 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); } }); unwrapExports(buildMatchMemberExpression_1); var isReactComponent_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _buildMatchMemberExpression = _interopRequireDefault(buildMatchMemberExpression_1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const isReactComponent = (0, _buildMatchMemberExpression.default)("React.Component"); var _default = isReactComponent; exports.default = _default; }); unwrapExports(isReactComponent_1); var isCompatTag_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isCompatTag; function isCompatTag(tagName) { return !!tagName && /^[a-z]/.test(tagName); } }); unwrapExports(isCompatTag_1); /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } var _listCacheClear = listCacheClear; /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } var eq_1 = eq; /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq_1(array[length][0], key)) { return length; } } return -1; } var _assocIndexOf = assocIndexOf; /** Used for built-in method references. */ var arrayProto = Array.prototype; /** Built-in value references. */ var splice = arrayProto.splice; /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = _assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } var _listCacheDelete = listCacheDelete; /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = _assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } var _listCacheGet = listCacheGet; /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return _assocIndexOf(this.__data__, key) > -1; } var _listCacheHas = listCacheHas; /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = _assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } var _listCacheSet = listCacheSet; /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `ListCache`. ListCache.prototype.clear = _listCacheClear; ListCache.prototype['delete'] = _listCacheDelete; ListCache.prototype.get = _listCacheGet; ListCache.prototype.has = _listCacheHas; ListCache.prototype.set = _listCacheSet; var _ListCache = ListCache; /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new _ListCache; this.size = 0; } var _stackClear = stackClear; /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } var _stackDelete = stackDelete; /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } var _stackGet = stackGet; /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } var _stackHas = stackHas; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; var _freeGlobal = freeGlobal; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = _freeGlobal || freeSelf || Function('return this')(); var _root = root; /** Built-in value references. */ var Symbol$1 = _root.Symbol; var _Symbol = Symbol$1; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Built-in value references. */ var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined; /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } var _getRawTag = getRawTag; /** Used for built-in method references. */ var objectProto$1 = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString$1 = objectProto$1.toString; /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString$1.call(value); } var _objectToString = objectToString; /** `Object#toString` result references. */ var nullTag = '[object Null]', undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined; /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag$1 && symToStringTag$1 in Object(value)) ? _getRawTag(value) : _objectToString(value); } var _baseGetTag = baseGetTag; /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } var isObject_1 = isObject; /** `Object#toString` result references. */ var asyncTag = '[object AsyncFunction]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', proxyTag = '[object Proxy]'; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject_1(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = _baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } var isFunction_1 = isFunction; /** Used to detect overreaching core-js shims. */ var coreJsData = _root['__core-js_shared__']; var _coreJsData = coreJsData; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } var _isMasked = isMasked; /** Used for built-in method references. */ var funcProto = Function.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } var _toSource = toSource; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used for built-in method references. */ var funcProto$1 = Function.prototype, objectProto$2 = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString$1 = funcProto$1.toString; /** Used to check objects for own properties. */ var hasOwnProperty$1 = objectProto$2.hasOwnProperty; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString$1.call(hasOwnProperty$1).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject_1(value) || _isMasked(value)) { return false; } var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor; return pattern.test(_toSource(value)); } var _baseIsNative = baseIsNative; /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } var _getValue = getValue; /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = _getValue(object, key); return _baseIsNative(value) ? value : undefined; } var _getNative = getNative; /* Built-in method references that are verified to be native. */ var Map$1 = _getNative(_root, 'Map'); var _Map = Map$1; /* Built-in method references that are verified to be native. */ var nativeCreate = _getNative(Object, 'create'); var _nativeCreate = nativeCreate; /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = _nativeCreate ? _nativeCreate(null) : {}; this.size = 0; } var _hashClear = hashClear; /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } var _hashDelete = hashDelete; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used for built-in method references. */ var objectProto$3 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$2 = objectProto$3.hasOwnProperty; /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (_nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty$2.call(data, key) ? data[key] : undefined; } var _hashGet = hashGet; /** Used for built-in method references. */ var objectProto$4 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$3 = objectProto$4.hasOwnProperty; /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return _nativeCreate ? (data[key] !== undefined) : hasOwnProperty$3.call(data, key); } var _hashHas = hashHas; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (_nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value; return this; } var _hashSet = hashSet; /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `Hash`. Hash.prototype.clear = _hashClear; Hash.prototype['delete'] = _hashDelete; Hash.prototype.get = _hashGet; Hash.prototype.has = _hashHas; Hash.prototype.set = _hashSet; var _Hash = Hash; /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new _Hash, 'map': new (_Map || _ListCache), 'string': new _Hash }; } var _mapCacheClear = mapCacheClear; /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } var _isKeyable = isKeyable; /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return _isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } var _getMapData = getMapData; /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = _getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } var _mapCacheDelete = mapCacheDelete; /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return _getMapData(this, key).get(key); } var _mapCacheGet = mapCacheGet; /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return _getMapData(this, key).has(key); } var _mapCacheHas = mapCacheHas; /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = _getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } var _mapCacheSet = mapCacheSet; /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `MapCache`. MapCache.prototype.clear = _mapCacheClear; MapCache.prototype['delete'] = _mapCacheDelete; MapCache.prototype.get = _mapCacheGet; MapCache.prototype.has = _mapCacheHas; MapCache.prototype.set = _mapCacheSet; var _MapCache = MapCache; /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof _ListCache) { var pairs = data.__data__; if (!_Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new _MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } var _stackSet = stackSet; /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new _ListCache(entries); this.size = data.size; } // Add methods to `Stack`. Stack.prototype.clear = _stackClear; Stack.prototype['delete'] = _stackDelete; Stack.prototype.get = _stackGet; Stack.prototype.has = _stackHas; Stack.prototype.set = _stackSet; var _Stack = Stack; /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } var _arrayEach = arrayEach; var defineProperty = (function() { try { var func = _getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); var _defineProperty = defineProperty; /** * The base implementation of `assignValue` and `assignMergeValue` without * value checks. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function baseAssignValue(object, key, value) { if (key == '__proto__' && _defineProperty) { _defineProperty(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } var _baseAssignValue = baseAssignValue; /** Used for built-in method references. */ var objectProto$5 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$4 = objectProto$5.hasOwnProperty; /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty$4.call(object, key) && eq_1(objValue, value)) || (value === undefined && !(key in object))) { _baseAssignValue(object, key, value); } } var _assignValue = assignValue; /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { _baseAssignValue(object, key, newValue); } else { _assignValue(object, key, newValue); } } return object; } var _copyObject = copyObject; /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } var _baseTimes = baseTimes; /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } var isObjectLike_1 = isObjectLike; /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike_1(value) && _baseGetTag(value) == argsTag; } var _baseIsArguments = baseIsArguments; /** Used for built-in method references. */ var objectProto$6 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$5 = objectProto$6.hasOwnProperty; /** Built-in value references. */ var propertyIsEnumerable = objectProto$6.propertyIsEnumerable; /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = _baseIsArguments(function() { return arguments; }()) ? _baseIsArguments : function(value) { return isObjectLike_1(value) && hasOwnProperty$5.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; var isArguments_1 = isArguments; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; var isArray_1 = isArray; /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } var stubFalse_1 = stubFalse; var isBuffer_1 = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? _root.Buffer : undefined; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse_1; module.exports = isBuffer; }); /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { var type = typeof value; length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (type == 'number' || (type != 'symbol' && reIsUint.test(value))) && (value > -1 && value % 1 == 0 && value < length); } var _isIndex = isIndex; /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER$1 = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1; } var isLength_1 = isLength; /** `Object#toString` result references. */ var argsTag$1 = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag$1 = '[object Function]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike_1(value) && isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)]; } var _baseIsTypedArray = baseIsTypedArray; /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } var _baseUnary = baseUnary; var _nodeUtil = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && _freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { // Use `util.types` for Node.js 10+. var types = freeModule && freeModule.require && freeModule.require('util').types; if (types) { return types; } // Legacy `process.binding('util')` for Node.js < 10. return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); module.exports = nodeUtil; }); /* Node.js helper references. */ var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray; /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray; var isTypedArray_1 = isTypedArray; /** Used for built-in method references. */ var objectProto$7 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$6 = objectProto$7.hasOwnProperty; /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray_1(value), isArg = !isArr && isArguments_1(value), isBuff = !isArr && !isArg && isBuffer_1(value), isType = !isArr && !isArg && !isBuff && isTypedArray_1(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? _baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty$6.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. _isIndex(key, length) ))) { result.push(key); } } return result; } var _arrayLikeKeys = arrayLikeKeys; /** Used for built-in method references. */ var objectProto$8 = Object.prototype; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$8; return value === proto; } var _isPrototype = isPrototype; /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } var _overArg = overArg; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = _overArg(Object.keys, Object); var _nativeKeys = nativeKeys; /** Used for built-in method references. */ var objectProto$9 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$7 = objectProto$9.hasOwnProperty; /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!_isPrototype(object)) { return _nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty$7.call(object, key) && key != 'constructor') { result.push(key); } } return result; } var _baseKeys = baseKeys; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength_1(value.length) && !isFunction_1(value); } var isArrayLike_1 = isArrayLike; /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object); } var keys_1 = keys; /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && _copyObject(source, keys_1(source), object); } var _baseAssign = baseAssign; /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } var _nativeKeysIn = nativeKeysIn; /** Used for built-in method references. */ var objectProto$a = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$8 = objectProto$a.hasOwnProperty; /** * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { if (!isObject_1(object)) { return _nativeKeysIn(object); } var isProto = _isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty$8.call(object, key)))) { result.push(key); } } return result; } var _baseKeysIn = baseKeysIn; /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { return isArrayLike_1(object) ? _arrayLikeKeys(object, true) : _baseKeysIn(object); } var keysIn_1 = keysIn; /** * The base implementation of `_.assignIn` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssignIn(object, source) { return object && _copyObject(source, keysIn_1(source), object); } var _baseAssignIn = baseAssignIn; var _cloneBuffer = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? _root.Buffer : undefined, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined; /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } module.exports = cloneBuffer; }); /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } var _copyArray = copyArray; /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } var _arrayFilter = arrayFilter; /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } var stubArray_1 = stubArray; /** Used for built-in method references. */ var objectProto$b = Object.prototype; /** Built-in value references. */ var propertyIsEnumerable$1 = objectProto$b.propertyIsEnumerable; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols; /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray_1 : function(object) { if (object == null) { return []; } object = Object(object); return _arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable$1.call(object, symbol); }); }; var _getSymbols = getSymbols; /** * Copies own symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return _copyObject(source, _getSymbols(source), object); } var _copySymbols = copySymbols; /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } var _arrayPush = arrayPush; /** Built-in value references. */ var getPrototype = _overArg(Object.getPrototypeOf, Object); var _getPrototype = getPrototype; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols$1 = Object.getOwnPropertySymbols; /** * Creates an array of the own and inherited enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbolsIn = !nativeGetSymbols$1 ? stubArray_1 : function(object) { var result = []; while (object) { _arrayPush(result, _getSymbols(object)); object = _getPrototype(object); } return result; }; var _getSymbolsIn = getSymbolsIn; /** * Copies own and inherited symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbolsIn(source, object) { return _copyObject(source, _getSymbolsIn(source), object); } var _copySymbolsIn = copySymbolsIn; /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object)); } var _baseGetAllKeys = baseGetAllKeys; /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return _baseGetAllKeys(object, keys_1, _getSymbols); } var _getAllKeys = getAllKeys; /** * Creates an array of own and inherited enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeysIn(object) { return _baseGetAllKeys(object, keysIn_1, _getSymbolsIn); } var _getAllKeysIn = getAllKeysIn; /* Built-in method references that are verified to be native. */ var DataView$1 = _getNative(_root, 'DataView'); var _DataView = DataView$1; /* Built-in method references that are verified to be native. */ var Promise$1 = _getNative(_root, 'Promise'); var _Promise = Promise$1; /* Built-in method references that are verified to be native. */ var Set$1 = _getNative(_root, 'Set'); var _Set = Set$1; /* Built-in method references that are verified to be native. */ var WeakMap$1 = _getNative(_root, 'WeakMap'); var _WeakMap = WeakMap$1; /** `Object#toString` result references. */ var mapTag$1 = '[object Map]', objectTag$1 = '[object Object]', promiseTag = '[object Promise]', setTag$1 = '[object Set]', weakMapTag$1 = '[object WeakMap]'; var dataViewTag$1 = '[object DataView]'; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = _toSource(_DataView), mapCtorString = _toSource(_Map), promiseCtorString = _toSource(_Promise), setCtorString = _toSource(_Set), weakMapCtorString = _toSource(_WeakMap); /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = _baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag$1) || (_Map && getTag(new _Map) != mapTag$1) || (_Promise && getTag(_Promise.resolve()) != promiseTag) || (_Set && getTag(new _Set) != setTag$1) || (_WeakMap && getTag(new _WeakMap) != weakMapTag$1)) { getTag = function(value) { var result = _baseGetTag(value), Ctor = result == objectTag$1 ? value.constructor : undefined, ctorString = Ctor ? _toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag$1; case mapCtorString: return mapTag$1; case promiseCtorString: return promiseTag; case setCtorString: return setTag$1; case weakMapCtorString: return weakMapTag$1; } } return result; }; } var _getTag = getTag; /** Used for built-in method references. */ var objectProto$c = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$9 = objectProto$c.hasOwnProperty; /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = new array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty$9.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } var _initCloneArray = initCloneArray; /** Built-in value references. */ var Uint8Array$1 = _root.Uint8Array; var _Uint8Array = Uint8Array$1; /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new _Uint8Array(result).set(new _Uint8Array(arrayBuffer)); return result; } var _cloneArrayBuffer = cloneArrayBuffer; /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? _cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } var _cloneDataView = cloneDataView; /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } var _cloneRegExp = cloneRegExp; /** Used to convert symbols to primitives and strings. */ var symbolProto = _Symbol ? _Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * Creates a clone of the `symbol` object. * * @private * @param {Object} symbol The symbol object to clone. * @returns {Object} Returns the cloned symbol object. */ function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } var _cloneSymbol = cloneSymbol; /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? _cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } var _cloneTypedArray = cloneTypedArray; /** `Object#toString` result references. */ var boolTag$1 = '[object Boolean]', dateTag$1 = '[object Date]', mapTag$2 = '[object Map]', numberTag$1 = '[object Number]', regexpTag$1 = '[object RegExp]', setTag$2 = '[object Set]', stringTag$1 = '[object String]', symbolTag = '[object Symbol]'; var arrayBufferTag$1 = '[object ArrayBuffer]', dataViewTag$2 = '[object DataView]', float32Tag$1 = '[object Float32Array]', float64Tag$1 = '[object Float64Array]', int8Tag$1 = '[object Int8Array]', int16Tag$1 = '[object Int16Array]', int32Tag$1 = '[object Int32Array]', uint8Tag$1 = '[object Uint8Array]', uint8ClampedTag$1 = '[object Uint8ClampedArray]', uint16Tag$1 = '[object Uint16Array]', uint32Tag$1 = '[object Uint32Array]'; /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag$1: return _cloneArrayBuffer(object); case boolTag$1: case dateTag$1: return new Ctor(+object); case dataViewTag$2: return _cloneDataView(object, isDeep); case float32Tag$1: case float64Tag$1: case int8Tag$1: case int16Tag$1: case int32Tag$1: case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1: return _cloneTypedArray(object, isDeep); case mapTag$2: return new Ctor; case numberTag$1: case stringTag$1: return new Ctor(object); case regexpTag$1: return _cloneRegExp(object); case setTag$2: return new Ctor; case symbolTag: return _cloneSymbol(object); } } var _initCloneByTag = initCloneByTag; /** Built-in value references. */ var objectCreate = Object.create; /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} proto The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = (function() { function object() {} return function(proto) { if (!isObject_1(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object; object.prototype = undefined; return result; }; }()); var _baseCreate = baseCreate; /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !_isPrototype(object)) ? _baseCreate(_getPrototype(object)) : {}; } var _initCloneObject = initCloneObject; /** `Object#toString` result references. */ var mapTag$3 = '[object Map]'; /** * The base implementation of `_.isMap` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. */ function baseIsMap(value) { return isObjectLike_1(value) && _getTag(value) == mapTag$3; } var _baseIsMap = baseIsMap; /* Node.js helper references. */ var nodeIsMap = _nodeUtil && _nodeUtil.isMap; /** * Checks if `value` is classified as a `Map` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. * @example * * _.isMap(new Map); * // => true * * _.isMap(new WeakMap); * // => false */ var isMap = nodeIsMap ? _baseUnary(nodeIsMap) : _baseIsMap; var isMap_1 = isMap; /** `Object#toString` result references. */ var setTag$3 = '[object Set]'; /** * The base implementation of `_.isSet` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. */ function baseIsSet(value) { return isObjectLike_1(value) && _getTag(value) == setTag$3; } var _baseIsSet = baseIsSet; /* Node.js helper references. */ var nodeIsSet = _nodeUtil && _nodeUtil.isSet; /** * Checks if `value` is classified as a `Set` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. * @example * * _.isSet(new Set); * // => true * * _.isSet(new WeakSet); * // => false */ var isSet = nodeIsSet ? _baseUnary(nodeIsSet) : _baseIsSet; var isSet_1 = isSet; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; /** `Object#toString` result references. */ var argsTag$2 = '[object Arguments]', arrayTag$1 = '[object Array]', boolTag$2 = '[object Boolean]', dateTag$2 = '[object Date]', errorTag$1 = '[object Error]', funcTag$2 = '[object Function]', genTag$1 = '[object GeneratorFunction]', mapTag$4 = '[object Map]', numberTag$2 = '[object Number]', objectTag$2 = '[object Object]', regexpTag$2 = '[object RegExp]', setTag$4 = '[object Set]', stringTag$2 = '[object String]', symbolTag$1 = '[object Symbol]', weakMapTag$2 = '[object WeakMap]'; var arrayBufferTag$2 = '[object ArrayBuffer]', dataViewTag$3 = '[object DataView]', float32Tag$2 = '[object Float32Array]', float64Tag$2 = '[object Float64Array]', int8Tag$2 = '[object Int8Array]', int16Tag$2 = '[object Int16Array]', int32Tag$2 = '[object Int32Array]', uint8Tag$2 = '[object Uint8Array]', uint8ClampedTag$2 = '[object Uint8ClampedArray]', uint16Tag$2 = '[object Uint16Array]', uint32Tag$2 = '[object Uint32Array]'; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag$2] = cloneableTags[arrayTag$1] = cloneableTags[arrayBufferTag$2] = cloneableTags[dataViewTag$3] = cloneableTags[boolTag$2] = cloneableTags[dateTag$2] = cloneableTags[float32Tag$2] = cloneableTags[float64Tag$2] = cloneableTags[int8Tag$2] = cloneableTags[int16Tag$2] = cloneableTags[int32Tag$2] = cloneableTags[mapTag$4] = cloneableTags[numberTag$2] = cloneableTags[objectTag$2] = cloneableTags[regexpTag$2] = cloneableTags[setTag$4] = cloneableTags[stringTag$2] = cloneableTags[symbolTag$1] = cloneableTags[uint8Tag$2] = cloneableTags[uint8ClampedTag$2] = cloneableTags[uint16Tag$2] = cloneableTags[uint32Tag$2] = true; cloneableTags[errorTag$1] = cloneableTags[funcTag$2] = cloneableTags[weakMapTag$2] = false; /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} bitmask The bitmask flags. * 1 - Deep clone * 2 - Flatten inherited properties * 4 - Clone symbols * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject_1(value)) { return value; } var isArr = isArray_1(value); if (isArr) { result = _initCloneArray(value); if (!isDeep) { return _copyArray(value, result); } } else { var tag = _getTag(value), isFunc = tag == funcTag$2 || tag == genTag$1; if (isBuffer_1(value)) { return _cloneBuffer(value, isDeep); } if (tag == objectTag$2 || tag == argsTag$2 || (isFunc && !object)) { result = (isFlat || isFunc) ? {} : _initCloneObject(value); if (!isDeep) { return isFlat ? _copySymbolsIn(value, _baseAssignIn(result, value)) : _copySymbols(value, _baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = _initCloneByTag(value, tag, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new _Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); if (isSet_1(value)) { value.forEach(function(subValue) { result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); }); } else if (isMap_1(value)) { value.forEach(function(subValue, key) { result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); } var keysFunc = isFull ? (isFlat ? _getAllKeysIn : _getAllKeys) : (isFlat ? keysIn_1 : keys_1); var props = isArr ? undefined : keysFunc(value); _arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). _assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } var _baseClone = baseClone; /** Used to compose bitmasks for cloning. */ var CLONE_SYMBOLS_FLAG$1 = 4; /** * Creates a shallow clone of `value`. * * **Note:** This method is loosely based on the * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) * and supports cloning arrays, array buffers, booleans, date objects, maps, * numbers, `Object` objects, regexes, sets, strings, symbols, and typed * arrays. The own enumerable properties of `arguments` objects are cloned * as plain objects. An empty object is returned for uncloneable values such * as error objects, functions, DOM nodes, and WeakMaps. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to clone. * @returns {*} Returns the cloned value. * @see _.cloneDeep * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var shallow = _.clone(objects); * console.log(shallow[0] === objects[0]); * // => true */ function clone(value) { return _baseClone(value, CLONE_SYMBOLS_FLAG$1); } var clone_1 = clone; 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(); var toFastProperties = function toFastproperties(o) { return FastObject(o); }; var isType_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isType; 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; } }); unwrapExports(isType_1); var isPlaceholderType_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isPlaceholderType; 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; } }); unwrapExports(isPlaceholderType_1); var is_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = is; var _shallowEqual = _interopRequireDefault(shallowEqual_1); var _isType = _interopRequireDefault(isType_1); var _isPlaceholderType = _interopRequireDefault(isPlaceholderType_1); 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); } } }); unwrapExports(is_1); var identifier = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.isIdentifierStart = isIdentifierStart; exports.isIdentifierChar = isIdentifierChar; exports.isIdentifierName = isIdentifierName; 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-\u08c7\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\u0d04-\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-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\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-\uab69\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\u0b55-\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\u0d81-\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\u1abf\u1ac0\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\ua82c\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, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 107, 20, 28, 22, 13, 52, 76, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 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, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 230, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 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, 190, 0, 80, 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, 1237, 43, 8, 8952, 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, 42717, 35, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938]; 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, 370, 1, 154, 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, 2, 11, 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, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 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, 82, 0, 12, 1, 19628, 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, 4759, 9, 787719, 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 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); } function isIdentifierName(name) { let isFirst = true; for (let _i = 0, _Array$from = Array.from(name); _i < _Array$from.length; _i++) { const char = _Array$from[_i]; const cp = char.codePointAt(0); if (isFirst) { if (!isIdentifierStart(cp)) { return false; } isFirst = false; } else if (!isIdentifierChar(cp)) { return false; } } return !isFirst; } }); unwrapExports(identifier); var identifier_1 = identifier.isIdentifierStart; var identifier_2 = identifier.isIdentifierChar; var identifier_3 = identifier.isIdentifierName; var keyword = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.isReservedWord = isReservedWord; exports.isStrictReservedWord = isStrictReservedWord; exports.isStrictBindOnlyReservedWord = isStrictBindOnlyReservedWord; exports.isStrictBindReservedWord = isStrictBindReservedWord; exports.isKeyword = isKeyword; const reservedWords = { keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"], strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"], strictBind: ["eval", "arguments"] }; const keywords = new Set(reservedWords.keyword); const reservedWordsStrictSet = new Set(reservedWords.strict); const reservedWordsStrictBindSet = new Set(reservedWords.strictBind); function isReservedWord(word, inModule) { return inModule && word === "await" || word === "enum"; } function isStrictReservedWord(word, inModule) { return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word); } function isStrictBindOnlyReservedWord(word) { return reservedWordsStrictBindSet.has(word); } function isStrictBindReservedWord(word, inModule) { return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word); } function isKeyword(word) { return keywords.has(word); } }); unwrapExports(keyword); var keyword_1 = keyword.isReservedWord; var keyword_2 = keyword.isStrictReservedWord; var keyword_3 = keyword.isStrictBindOnlyReservedWord; var keyword_4 = keyword.isStrictBindReservedWord; var keyword_5 = keyword.isKeyword; var lib = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "isIdentifierName", { enumerable: true, get: function () { return identifier.isIdentifierName; } }); Object.defineProperty(exports, "isIdentifierChar", { enumerable: true, get: function () { return identifier.isIdentifierChar; } }); Object.defineProperty(exports, "isIdentifierStart", { enumerable: true, get: function () { return identifier.isIdentifierStart; } }); Object.defineProperty(exports, "isReservedWord", { enumerable: true, get: function () { return keyword.isReservedWord; } }); Object.defineProperty(exports, "isStrictBindOnlyReservedWord", { enumerable: true, get: function () { return keyword.isStrictBindOnlyReservedWord; } }); Object.defineProperty(exports, "isStrictBindReservedWord", { enumerable: true, get: function () { return keyword.isStrictBindReservedWord; } }); Object.defineProperty(exports, "isStrictReservedWord", { enumerable: true, get: function () { return keyword.isStrictReservedWord; } }); Object.defineProperty(exports, "isKeyword", { enumerable: true, get: function () { return keyword.isKeyword; } }); }); unwrapExports(lib); var isValidIdentifier_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isValidIdentifier; function isValidIdentifier(name, reserved = true) { if (typeof name !== "string") return false; if (reserved) { if ((0, lib.isKeyword)(name) || (0, lib.isStrictReservedWord)(name)) { return false; } else if (name === "await") { return false; } } return (0, lib.isIdentifierName)(name); } }); unwrapExports(isValidIdentifier_1); var constants = createCommonjsModule(function (module, exports) { 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.ASSIGNMENT_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 ASSIGNMENT_OPERATORS = ["=", "+=", ...NUMBER_BINARY_OPERATORS.map(op => op + "="), ...LOGICAL_OPERATORS.map(op => op + "=")]; exports.ASSIGNMENT_OPERATORS = ASSIGNMENT_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; }); unwrapExports(constants); var constants_1 = constants.NOT_LOCAL_BINDING; var constants_2 = constants.BLOCK_SCOPED_SYMBOL; var constants_3 = constants.INHERIT_KEYS; var constants_4 = constants.UNARY_OPERATORS; var constants_5 = constants.STRING_UNARY_OPERATORS; var constants_6 = constants.NUMBER_UNARY_OPERATORS; var constants_7 = constants.BOOLEAN_UNARY_OPERATORS; var constants_8 = constants.ASSIGNMENT_OPERATORS; var constants_9 = constants.BINARY_OPERATORS; var constants_10 = constants.NUMBER_BINARY_OPERATORS; var constants_11 = constants.BOOLEAN_BINARY_OPERATORS; var constants_12 = constants.COMPARISON_BINARY_OPERATORS; var constants_13 = constants.EQUALITY_BINARY_OPERATORS; var constants_14 = constants.BOOLEAN_NUMBER_BINARY_OPERATORS; var constants_15 = constants.UPDATE_OPERATORS; var constants_16 = constants.LOGICAL_OPERATORS; var constants_17 = constants.COMMENT_KEYS; var constants_18 = constants.FOR_INIT_KEYS; var constants_19 = constants.FLATTENABLE_KEYS; var constants_20 = constants.STATEMENT_OR_BLOCK_KEYS; var validate_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = validate; exports.validateField = validateField; exports.validateChild = validateChild; function validate(node, key, val) { if (!node) return; const fields = definitions.NODE_FIELDS[node.type]; if (!fields) return; const field = fields[key]; validateField(node, key, val, field); validateChild(node, key, val); } function validateField(node, key, val, field) { if (!(field == null ? void 0 : field.validate)) return; if (field.optional && val == null) return; field.validate(node, key, val); } function validateChild(node, key, val) { if (val == null) return; const validate = definitions.NODE_PARENT_VALIDATIONS[val.type]; if (!validate) return; validate(node, key, val); } }); unwrapExports(validate_1); var validate_2 = validate_1.validateField; var validate_3 = validate_1.validateChild; var utils = createCommonjsModule(function (module, exports) { 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.assertShape = assertShape; exports.assertOptionalChainStart = assertOptionalChainStart; exports.chain = chain; exports.default = defineType; exports.NODE_PARENT_VALIDATIONS = exports.DEPRECATED_KEYS = exports.BUILDER_KEYS = exports.NODE_FIELDS = exports.FLIPPED_ALIAS_KEYS = exports.ALIAS_KEYS = exports.VISITOR_KEYS = void 0; var _is = _interopRequireDefault(is_1); 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; const NODE_PARENT_VALIDATIONS = {}; exports.NODE_PARENT_VALIDATIONS = NODE_PARENT_VALIDATIONS; function getType(val) { if (Array.isArray(val)) { return "array"; } else if (val === null) { return "null"; } 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++) { const subkey = `${key}[${i}]`; const v = val[i]; callback(node, subkey, v); if (process.env.BABEL_TYPES_8_BREAKING) (0, validate_1.validateChild)(node, subkey, v); } } 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) { for (const type of types) { if ((0, _is.default)(type, val)) { (0, validate_1.validateChild)(node, key, val); return; } } throw new TypeError(`Property ${key} of ${node.type} expected node to be of a type ${JSON.stringify(types)} but instead got ${JSON.stringify(val == null ? void 0 : val.type)}`); } validate.oneOfNodeTypes = types; return validate; } function assertNodeOrValueType(...types) { function validate(node, key, val) { for (const type of types) { if (getType(val) === type || (0, _is.default)(type, val)) { (0, validate_1.validateChild)(node, key, val); return; } } throw new TypeError(`Property ${key} of ${node.type} expected node to be of a type ${JSON.stringify(types)} but instead got ${JSON.stringify(val == null ? void 0 : 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 assertShape(shape) { function validate(node, key, val) { const errors = []; for (const property of Object.keys(shape)) { try { (0, validate_1.validateField)(node, property, val[property], shape[property]); } catch (error) { if (error instanceof TypeError) { errors.push(error.message); continue; } throw error; } } if (errors.length) { throw new TypeError(`Property ${key} of ${node.type} expected to have the following:\n${errors.join("\n")}`); } } validate.shapeOf = shape; return validate; } function assertOptionalChainStart() { function validate(node) { var _current; let current = node; while (node) { const { type } = current; if (type === "OptionalCallExpression") { if (current.optional) return; current = current.callee; continue; } if (type === "OptionalMemberExpression") { if (current.optional) return; current = current.object; continue; } break; } throw new TypeError(`Non-optional ${node.type} must chain from an optional OptionalMemberExpression or OptionalCallExpression. Found chain from ${(_current = current) == null ? void 0 : _current.type}`); } return validate; } function chain(...fns) { function validate(...args) { for (const fn of fns) { fn(...args); } } validate.chainOf = fns; return validate; } const validTypeOpts = ["aliases", "builder", "deprecatedAlias", "fields", "inherits", "visitor", "validate"]; const validFieldKeys = ["default", "optional", "validate"]; function defineType(type, opts = {}) { const inherits = opts.inherits && store[opts.inherits] || {}; let fields = opts.fields; if (!fields) { fields = {}; if (inherits.fields) { const keys = Object.getOwnPropertyNames(inherits.fields); for (const key of keys) { const field = inherits.fields[key]; fields[key] = { default: field.default, optional: field.optional, validate: field.validate }; } } } const visitor = opts.visitor || inherits.visitor || []; const aliases = opts.aliases || inherits.aliases || []; const builder = opts.builder || inherits.builder || opts.visitor || []; for (const k of Object.keys(opts)) { if (validTypeOpts.indexOf(k) === -1) { throw new Error(`Unknown type option "${k}" on ${type}`); } } 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 (field.default !== undefined && builder.indexOf(key) === -1) { field.optional = true; } if (field.default === undefined) { field.default = null; } else if (!field.validate && field.default != null) { field.validate = assertValueType(getType(field.default)); } for (const k of Object.keys(field)) { if (validFieldKeys.indexOf(k) === -1) { throw new Error(`Unknown field key "${k}" on ${type}.${key}`); } } } 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); }); if (opts.validate) { NODE_PARENT_VALIDATIONS[type] = opts.validate; } store[type] = opts; } const store = {}; }); unwrapExports(utils); var utils_1 = utils.validate; var utils_2 = utils.typeIs; var utils_3 = utils.validateType; var utils_4 = utils.validateOptional; var utils_5 = utils.validateOptionalType; var utils_6 = utils.arrayOf; var utils_7 = utils.arrayOfType; var utils_8 = utils.validateArrayOfType; var utils_9 = utils.assertEach; var utils_10 = utils.assertOneOf; var utils_11 = utils.assertNodeType; var utils_12 = utils.assertNodeOrValueType; var utils_13 = utils.assertValueType; var utils_14 = utils.assertShape; var utils_15 = utils.assertOptionalChainStart; var utils_16 = utils.chain; var utils_17 = utils.NODE_PARENT_VALIDATIONS; var utils_18 = utils.DEPRECATED_KEYS; var utils_19 = utils.BUILDER_KEYS; var utils_20 = utils.NODE_FIELDS; var utils_21 = utils.FLIPPED_ALIAS_KEYS; var utils_22 = utils.ALIAS_KEYS; var utils_23 = utils.VISITOR_KEYS; var core = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.classMethodOrDeclareMethodCommon = exports.classMethodOrPropertyCommon = exports.patternLikeCommon = exports.functionDeclarationCommon = exports.functionTypeAnnotationCommon = exports.functionCommon = void 0; var _is = _interopRequireDefault(is_1); var _isValidIdentifier = _interopRequireDefault(isValidIdentifier_1); var _utils = _interopRequireWildcard(utils); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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: !process.env.BABEL_TYPES_8_BREAKING ? [] : undefined } }, visitor: ["elements"], aliases: ["Expression"] }); (0, _utils.default)("AssignmentExpression", { fields: { operator: { validate: function () { if (!process.env.BABEL_TYPES_8_BREAKING) { return (0, _utils.assertValueType)("string"); } const identifier = (0, _utils.assertOneOf)(...constants.ASSIGNMENT_OPERATORS); const pattern = (0, _utils.assertOneOf)("="); return function (node, key, val) { const validator = (0, _is.default)("Pattern", node.left) ? pattern : identifier; validator(node, key, val); }; }() }, left: { validate: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertNodeType)("LVal") : (0, _utils.assertNodeType)("Identifier", "MemberExpression", "ArrayPattern", "ObjectPattern") }, 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: function () { const expression = (0, _utils.assertNodeType)("Expression"); const inOp = (0, _utils.assertNodeType)("Expression", "PrivateName"); const validator = function (node, key, val) { const validator = node.operator === "in" ? inOp : expression; validator(node, key, val); }; validator.oneOfNodeTypes = ["Expression", "PrivateName"]; return validator; }() }, 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: Object.assign({ callee: { validate: (0, _utils.assertNodeType)("Expression", "V8IntrinsicIdentifier") }, arguments: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Expression", "SpreadElement", "JSXNamespacedName", "ArgumentPlaceholder"))) } }, !process.env.BABEL_TYPES_8_BREAKING ? { 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", "ArrayPattern", "ObjectPattern"), 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") }, comments: { validate: !process.env.BABEL_TYPES_8_BREAKING ? Object.assign(() => {}, { each: { oneOfNodeTypes: ["CommentBlock", "CommentLine"] } }) : (0, _utils.assertEach)((0, _utils.assertNodeType)("CommentBlock", "CommentLine")), optional: true }, tokens: { validate: (0, _utils.assertEach)(Object.assign(() => {}, { type: "any" })), optional: true } } }); (0, _utils.default)("ForInStatement", { visitor: ["left", "right", "body"], aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"], fields: { left: { validate: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertNodeType)("VariableDeclaration", "LVal") : (0, _utils.assertNodeType)("VariableDeclaration", "Identifier", "MemberExpression", "ArrayPattern", "ObjectPattern") }, 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 }, async: { 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"], validate: function () { if (!process.env.BABEL_TYPES_8_BREAKING) return () => {}; const identifier = (0, _utils.assertNodeType)("Identifier"); return function (parent, key, node) { if (!(0, _is.default)("ExportDefaultDeclaration", parent)) { identifier(node, "id", node.id); } }; }() }); (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)((0, _utils.assertValueType)("string"), Object.assign(function (node, key, val) { if (!process.env.BABEL_TYPES_8_BREAKING) return; if (!(0, _isValidIdentifier.default)(val, false)) { throw new TypeError(`"${val}" is not a valid identifier name`); } }, { type: "string" })) }, optional: { validate: (0, _utils.assertValueType)("boolean"), optional: true } }), validate(parent, key, node) { if (!process.env.BABEL_TYPES_8_BREAKING) return; const match = /\.(\w+)$/.exec(key); if (!match) return; const [, parentKey] = match; const nonComp = { computed: false }; if (parentKey === "property") { if ((0, _is.default)("MemberExpression", parent, nonComp)) return; if ((0, _is.default)("OptionalMemberExpression", parent, nonComp)) return; } else if (parentKey === "key") { if ((0, _is.default)("Property", parent, nonComp)) return; if ((0, _is.default)("Method", parent, nonComp)) return; } else if (parentKey === "exported") { if ((0, _is.default)("ExportSpecifier", parent)) return; } else if (parentKey === "imported") { if ((0, _is.default)("ImportSpecifier", parent, { imported: node })) return; } else if (parentKey === "meta") { if ((0, _is.default)("MetaProperty", parent, { meta: node })) return; } if (((0, lib.isKeyword)(node.name) || (0, lib.isReservedWord)(node.name)) && node.name !== "this") { throw new TypeError(`"${node.name}" is not a valid identifier`); } } }); (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", "Pureish", "Literal"], fields: { pattern: { validate: (0, _utils.assertValueType)("string") }, flags: { validate: (0, _utils.chain)((0, _utils.assertValueType)("string"), Object.assign(function (node, key, val) { if (!process.env.BABEL_TYPES_8_BREAKING) return; const invalid = /[^gimsuy]/.exec(val); if (invalid) { throw new TypeError(`"${invalid[0]}" is not a valid RegExp flag`); } }, { type: "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.assign({ object: { validate: (0, _utils.assertNodeType)("Expression") }, property: { validate: function () { const normal = (0, _utils.assertNodeType)("Identifier", "PrivateName"); const computed = (0, _utils.assertNodeType)("Expression"); const validator = function (node, key, val) { const validator = node.computed ? computed : normal; validator(node, key, val); }; validator.oneOfNodeTypes = ["Expression", "Identifier", "PrivateName"]; return validator; }() }, computed: { default: false } }, !process.env.BABEL_TYPES_8_BREAKING ? { 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", "generator", "async"], fields: Object.assign({}, functionCommon, functionTypeAnnotationCommon, { kind: Object.assign({ validate: (0, _utils.assertOneOf)("method", "get", "set") }, !process.env.BABEL_TYPES_8_BREAKING ? { default: "method" } : {}), computed: { default: false }, key: { validate: function () { const normal = (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral"); const computed = (0, _utils.assertNodeType)("Expression"); const validator = function (node, key, val) { const validator = node.computed ? computed : normal; validator(node, key, val); }; validator.oneOfNodeTypes = ["Expression", "Identifier", "StringLiteral", "NumericLiteral"]; return validator; }() }, decorators: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))), optional: true }, 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", ...(!process.env.BABEL_TYPES_8_BREAKING ? ["decorators"] : [])], fields: { computed: { default: false }, key: { validate: function () { const normal = (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral"); const computed = (0, _utils.assertNodeType)("Expression"); const validator = function (node, key, val) { const validator = node.computed ? computed : normal; validator(node, key, val); }; validator.oneOfNodeTypes = ["Expression", "Identifier", "StringLiteral", "NumericLiteral"]; return validator; }() }, value: { validate: (0, _utils.assertNodeType)("Expression", "PatternLike") }, shorthand: { validate: (0, _utils.chain)((0, _utils.assertValueType)("boolean"), Object.assign(function (node, key, val) { if (!process.env.BABEL_TYPES_8_BREAKING) return; if (val && node.computed) { throw new TypeError("Property shorthand of ObjectProperty cannot be true if computed is true"); } }, { type: "boolean" }), function (node, key, val) { if (!process.env.BABEL_TYPES_8_BREAKING) return; if (val && !(0, _is.default)("Identifier", node.key)) { throw new TypeError("Property shorthand of ObjectProperty cannot be true if key is not an Identifier"); } }), 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"], validate: function () { const pattern = (0, _utils.assertNodeType)("Identifier", "Pattern"); const expression = (0, _utils.assertNodeType)("Expression"); return function (parent, key, node) { if (!process.env.BABEL_TYPES_8_BREAKING) return; const validator = (0, _is.default)("ObjectPattern", parent) ? pattern : expression; validator(node, "value", node.value); }; }() }); (0, _utils.default)("RestElement", { visitor: ["argument", "typeAnnotation"], builder: ["argument"], aliases: ["LVal", "PatternLike"], deprecatedAlias: "RestProperty", fields: Object.assign({}, patternLikeCommon, { argument: { validate: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertNodeType)("LVal") : (0, _utils.assertNodeType)("Identifier", "Pattern", "MemberExpression") } }), validate(parent, key) { if (!process.env.BABEL_TYPES_8_BREAKING) return; const match = /(\w+)\[(\d+)\]/.exec(key); if (!match) throw new Error("Internal Babel error: malformed key."); const [, listKey, index] = match; if (parent[listKey].length > index + 1) { throw new TypeError(`RestElement must be last element of ${listKey}`); } } }); (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.chain)((0, _utils.assertNodeType)("BlockStatement"), Object.assign(function (node) { if (!process.env.BABEL_TYPES_8_BREAKING) return; if (!node.handler && !node.finalizer) { throw new TypeError("TryStatement expects either a handler or finalizer, or both"); } }, { oneOfNodeTypes: ["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: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertNodeType)("Expression") : (0, _utils.assertNodeType)("Identifier", "MemberExpression") }, 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.assertOneOf)("var", "let", "const") }, declarations: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("VariableDeclarator"))) } }, validate(parent, key, node) { if (!process.env.BABEL_TYPES_8_BREAKING) return; if (!(0, _is.default)("ForXStatement", parent, { left: node })) return; if (node.declarations.length !== 1) { throw new TypeError(`Exactly one VariableDeclarator is required in the VariableDeclaration of a ${parent.type}`); } } }); (0, _utils.default)("VariableDeclarator", { visitor: ["id", "init"], fields: { id: { validate: function () { if (!process.env.BABEL_TYPES_8_BREAKING) { return (0, _utils.assertNodeType)("LVal"); } const normal = (0, _utils.assertNodeType)("Identifier", "ArrayPattern", "ObjectPattern"); const without = (0, _utils.assertNodeType)("Identifier"); return function (node, key, val) { const validator = node.init ? normal : without; validator(node, key, val); }; }() }, 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)("Statement") } } }); (0, _utils.default)("WithStatement", { visitor: ["object", "body"], aliases: ["Statement"], fields: { object: { validate: (0, _utils.assertNodeType)("Expression") }, body: { validate: (0, _utils.assertNodeType)("Statement") } } }); (0, _utils.default)("AssignmentPattern", { visitor: ["left", "right", "decorators"], builder: ["left", "right"], aliases: ["Pattern", "PatternLike", "LVal"], fields: Object.assign({}, patternLikeCommon, { left: { validate: (0, _utils.assertNodeType)("Identifier", "ObjectPattern", "ArrayPattern", "MemberExpression") }, right: { 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)("ArrayPattern", { visitor: ["elements", "typeAnnotation"], builder: ["elements"], aliases: ["Pattern", "PatternLike", "LVal"], fields: Object.assign({}, patternLikeCommon, { elements: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeOrValueType)("null", "PatternLike"))) }, decorators: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))), optional: true } }) }); (0, _utils.default)("ArrowFunctionExpression", { builder: ["params", "body", "async"], visitor: ["params", "body", "returnType", "typeParameters"], aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Expression", "Pureish"], fields: Object.assign({}, functionCommon, 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"))) } } }); (0, _utils.default)("ClassExpression", { builder: ["id", "superClass", "body", "decorators"], visitor: ["id", "body", "superClass", "mixins", "typeParameters", "superTypeParameters", "implements", "decorators"], aliases: ["Scopable", "Class", "Expression"], fields: { id: { validate: (0, _utils.assertNodeType)("Identifier"), optional: true }, 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 }, decorators: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))), optional: true }, mixins: { validate: (0, _utils.assertNodeType)("InterfaceExtends"), optional: true } } }); (0, _utils.default)("ClassDeclaration", { inherits: "ClassExpression", aliases: ["Scopable", "Class", "Statement", "Declaration"], fields: { id: { validate: (0, _utils.assertNodeType)("Identifier") }, 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 }, decorators: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))), optional: true }, mixins: { validate: (0, _utils.assertNodeType)("InterfaceExtends"), optional: true }, declare: { validate: (0, _utils.assertValueType)("boolean"), optional: true }, abstract: { validate: (0, _utils.assertValueType)("boolean"), optional: true } }, validate: function () { const identifier = (0, _utils.assertNodeType)("Identifier"); return function (parent, key, node) { if (!process.env.BABEL_TYPES_8_BREAKING) return; if (!(0, _is.default)("ExportDefaultDeclaration", parent)) { identifier(node, "id", node.id); } }; }() }); (0, _utils.default)("ExportAllDeclaration", { visitor: ["source"], aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"], fields: { source: { validate: (0, _utils.assertNodeType)("StringLiteral") }, assertions: { optional: true, validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertNodeType)("ImportAttribute")) } } }); (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: { optional: true, validate: (0, _utils.chain)((0, _utils.assertNodeType)("Declaration"), Object.assign(function (node, key, val) { if (!process.env.BABEL_TYPES_8_BREAKING) return; if (val && node.specifiers.length) { throw new TypeError("Only declaration or specifiers is allowed on ExportNamedDeclaration"); } }, { oneOfNodeTypes: ["Declaration"] }), function (node, key, val) { if (!process.env.BABEL_TYPES_8_BREAKING) return; if (val && node.source) { throw new TypeError("Cannot export a declaration from a source"); } }) }, assertions: { optional: true, validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertNodeType)("ImportAttribute")) }, specifiers: { default: [], validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)(function () { const sourced = (0, _utils.assertNodeType)("ExportSpecifier", "ExportDefaultSpecifier", "ExportNamespaceSpecifier"); const sourceless = (0, _utils.assertNodeType)("ExportSpecifier"); if (!process.env.BABEL_TYPES_8_BREAKING) return sourced; return function (node, key, val) { const validator = node.source ? sourced : sourceless; validator(node, key, val); }; }())) }, source: { validate: (0, _utils.assertNodeType)("StringLiteral"), optional: true }, exportKind: (0, _utils.validateOptional)((0, _utils.assertOneOf)("type", "value")) } }); (0, _utils.default)("ExportSpecifier", { visitor: ["local", "exported"], aliases: ["ModuleSpecifier"], fields: { local: { validate: (0, _utils.assertNodeType)("Identifier") }, exported: { validate: (0, _utils.assertNodeType)("Identifier", "StringLiteral") } } }); (0, _utils.default)("ForOfStatement", { visitor: ["left", "right", "body"], builder: ["left", "right", "body", "await"], aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"], fields: { left: { validate: function () { if (!process.env.BABEL_TYPES_8_BREAKING) { return (0, _utils.assertNodeType)("VariableDeclaration", "LVal"); } const declaration = (0, _utils.assertNodeType)("VariableDeclaration"); const lval = (0, _utils.assertNodeType)("Identifier", "MemberExpression", "ArrayPattern", "ObjectPattern"); return function (node, key, val) { if ((0, _is.default)("VariableDeclaration", val)) { declaration(node, key, val); } else { lval(node, key, val); } }; }() }, right: { validate: (0, _utils.assertNodeType)("Expression") }, body: { validate: (0, _utils.assertNodeType)("Statement") }, await: { default: false } } }); (0, _utils.default)("ImportDeclaration", { visitor: ["specifiers", "source"], aliases: ["Statement", "Declaration", "ModuleDeclaration"], fields: { assertions: { optional: true, validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertNodeType)("ImportAttribute")) }, 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", "StringLiteral") }, importKind: { validate: (0, _utils.assertOneOf)("type", "typeof"), optional: true } } }); (0, _utils.default)("MetaProperty", { visitor: ["meta", "property"], aliases: ["Expression"], fields: { meta: { validate: (0, _utils.chain)((0, _utils.assertNodeType)("Identifier"), Object.assign(function (node, key, val) { if (!process.env.BABEL_TYPES_8_BREAKING) return; let property; switch (val.name) { case "function": property = "sent"; break; case "new": property = "target"; break; case "import": property = "meta"; break; } if (!(0, _is.default)("Identifier", node.property, { name: property })) { throw new TypeError("Unrecognised MetaProperty"); } }, { oneOfNodeTypes: ["Identifier"] })) }, property: { validate: (0, _utils.assertNodeType)("Identifier") } } }); const classMethodOrPropertyCommon = { abstract: { validate: (0, _utils.assertValueType)("boolean"), optional: true }, accessibility: { validate: (0, _utils.assertOneOf)("public", "private", "protected"), optional: true }, static: { default: false }, computed: { default: false }, 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({}, functionCommon, classMethodOrPropertyCommon, { kind: { validate: (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", "generator", "async"], visitor: ["key", "params", "body", "decorators", "returnType", "typeParameters"], fields: Object.assign({}, classMethodOrDeclareMethodCommon, functionTypeAnnotationCommon, { body: { validate: (0, _utils.assertNodeType)("BlockStatement") } }) }); (0, _utils.default)("ObjectPattern", { visitor: ["properties", "typeAnnotation", "decorators"], builder: ["properties"], aliases: ["Pattern", "PatternLike", "LVal"], fields: Object.assign({}, 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: { validate: (0, _utils.assertShape)({ raw: { validate: (0, _utils.assertValueType)("string") }, cooked: { validate: (0, _utils.assertValueType)("string"), optional: true } }) }, tail: { 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", "TSType")), function (node, key, val) { if (node.quasis.length !== val.length + 1) { throw new TypeError(`Number of ${node.type} quasis should be exactly one more than the number of expressions.\nExpected ${val.length + 1} quasis but got ${node.quasis.length}`); } }) } } }); (0, _utils.default)("YieldExpression", { builder: ["argument", "delegate"], visitor: ["argument"], aliases: ["Expression", "Terminatorless"], fields: { delegate: { validate: (0, _utils.chain)((0, _utils.assertValueType)("boolean"), Object.assign(function (node, key, val) { if (!process.env.BABEL_TYPES_8_BREAKING) return; if (val && !node.argument) { throw new TypeError("Property delegate of YieldExpression cannot be true if there is no argument"); } }, { type: "boolean" })), default: false }, argument: { optional: true, validate: (0, _utils.assertNodeType)("Expression") } } }); (0, _utils.default)("AwaitExpression", { builder: ["argument"], visitor: ["argument"], aliases: ["Expression", "Terminatorless"], fields: { argument: { validate: (0, _utils.assertNodeType)("Expression") } } }); (0, _utils.default)("Import", { aliases: ["Expression"] }); (0, _utils.default)("BigIntLiteral", { builder: ["value"], fields: { value: { validate: (0, _utils.assertValueType)("string") } }, aliases: ["Expression", "Pureish", "Literal", "Immutable"] }); (0, _utils.default)("ExportNamespaceSpecifier", { visitor: ["exported"], aliases: ["ModuleSpecifier"], fields: { exported: { validate: (0, _utils.assertNodeType)("Identifier") } } }); (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"); const validator = function (node, key, val) { const validator = node.computed ? computed : normal; validator(node, key, val); }; validator.oneOfNodeTypes = ["Expression", "Identifier"]; return validator; }() }, computed: { default: false }, optional: { validate: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertValueType)("boolean") : (0, _utils.chain)((0, _utils.assertValueType)("boolean"), (0, _utils.assertOptionalChainStart)()) } } }); (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: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertValueType)("boolean") : (0, _utils.chain)((0, _utils.assertValueType)("boolean"), (0, _utils.assertOptionalChainStart)()) }, typeArguments: { validate: (0, _utils.assertNodeType)("TypeParameterInstantiation"), optional: true }, typeParameters: { validate: (0, _utils.assertNodeType)("TSTypeParameterInstantiation"), optional: true } } }); }); unwrapExports(core); var core_1 = core.classMethodOrDeclareMethodCommon; var core_2 = core.classMethodOrPropertyCommon; var core_3 = core.patternLikeCommon; var core_4 = core.functionDeclarationCommon; var core_5 = core.functionTypeAnnotationCommon; var core_6 = core.functionCommon; var flow = createCommonjsModule(function (module) { var _utils = _interopRequireWildcard(utils); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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)("SymbolTypeAnnotation", { 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"] }); (0, _utils.default)("EnumDeclaration", { aliases: ["Statement", "Declaration"], visitor: ["id", "body"], fields: { id: (0, _utils.validateType)("Identifier"), body: (0, _utils.validateType)(["EnumBooleanBody", "EnumNumberBody", "EnumStringBody", "EnumSymbolBody"]) } }); (0, _utils.default)("EnumBooleanBody", { aliases: ["EnumBody"], visitor: ["members"], fields: { explicit: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), members: (0, _utils.validateArrayOfType)("EnumBooleanMember") } }); (0, _utils.default)("EnumNumberBody", { aliases: ["EnumBody"], visitor: ["members"], fields: { explicit: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), members: (0, _utils.validateArrayOfType)("EnumNumberMember") } }); (0, _utils.default)("EnumStringBody", { aliases: ["EnumBody"], visitor: ["members"], fields: { explicit: (0, _utils.validate)((0, _utils.assertValueType)("boolean")), members: (0, _utils.validateArrayOfType)(["EnumStringMember", "EnumDefaultedMember"]) } }); (0, _utils.default)("EnumSymbolBody", { aliases: ["EnumBody"], visitor: ["members"], fields: { members: (0, _utils.validateArrayOfType)("EnumDefaultedMember") } }); (0, _utils.default)("EnumBooleanMember", { aliases: ["EnumMember"], visitor: ["id"], fields: { id: (0, _utils.validateType)("Identifier"), init: (0, _utils.validateType)("BooleanLiteral") } }); (0, _utils.default)("EnumNumberMember", { aliases: ["EnumMember"], visitor: ["id", "init"], fields: { id: (0, _utils.validateType)("Identifier"), init: (0, _utils.validateType)("NumericLiteral") } }); (0, _utils.default)("EnumStringMember", { aliases: ["EnumMember"], visitor: ["id", "init"], fields: { id: (0, _utils.validateType)("Identifier"), init: (0, _utils.validateType)("StringLiteral") } }); (0, _utils.default)("EnumDefaultedMember", { aliases: ["EnumMember"], visitor: ["id"], fields: { id: (0, _utils.validateType)("Identifier") } }); }); unwrapExports(flow); var jsx = createCommonjsModule(function (module) { var _utils = _interopRequireWildcard(utils); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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", "JSXNamespacedName") } } }); (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"))) }, selfClosing: { validate: (0, _utils.assertValueType)("boolean"), optional: true } } }); (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", "JSXNamespacedName") }, selfClosing: { default: false }, 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"] }); }); unwrapExports(jsx); var placeholders = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.PLACEHOLDERS_FLIPPED_ALIAS = exports.PLACEHOLDERS_ALIAS = exports.PLACEHOLDERS = void 0; 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 == null ? void 0 : 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); }); }); }); unwrapExports(placeholders); var placeholders_1 = placeholders.PLACEHOLDERS_FLIPPED_ALIAS; var placeholders_2 = placeholders.PLACEHOLDERS_ALIAS; var placeholders_3 = placeholders.PLACEHOLDERS; var misc = createCommonjsModule(function (module) { var _utils = _interopRequireWildcard(utils); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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) } } }); (0, _utils.default)("V8IntrinsicIdentifier", { builder: ["name"], fields: { name: { validate: (0, _utils.assertValueType)("string") } } }); }); unwrapExports(misc); var experimental = createCommonjsModule(function (module) { var _utils = _interopRequireWildcard(utils); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } (0, _utils.default)("ArgumentPlaceholder", {}); (0, _utils.default)("BindExpression", { visitor: ["object", "callee"], aliases: ["Expression"], fields: !process.env.BABEL_TYPES_8_BREAKING ? { object: { validate: Object.assign(() => {}, { oneOfNodeTypes: ["Expression"] }) }, callee: { validate: Object.assign(() => {}, { oneOfNodeTypes: ["Expression"] }) } } : { object: { validate: (0, _utils.assertNodeType)("Expression") }, callee: { validate: (0, _utils.assertNodeType)("Expression") } } }); (0, _utils.default)("ClassProperty", { visitor: ["key", "value", "typeAnnotation", "decorators"], builder: ["key", "value", "typeAnnotation", "decorators", "computed", "static"], aliases: ["Property"], fields: Object.assign({}, core.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 }, declare: { validate: (0, _utils.assertValueType)("boolean"), optional: true } }) }); (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)("ClassPrivateProperty", { visitor: ["key", "value", "decorators"], builder: ["key", "value", "decorators", "static"], aliases: ["Property", "Private"], fields: { key: { validate: (0, _utils.assertNodeType)("PrivateName") }, value: { validate: (0, _utils.assertNodeType)("Expression"), optional: true }, decorators: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))), 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({}, core.classMethodOrDeclareMethodCommon, core.functionTypeAnnotationCommon, { key: { validate: (0, _utils.assertNodeType)("PrivateName") }, body: { validate: (0, _utils.assertNodeType)("BlockStatement") } }) }); (0, _utils.default)("ImportAttribute", { visitor: ["key", "value"], fields: { key: { validate: (0, _utils.assertNodeType)("Identifier", "StringLiteral") }, value: { validate: (0, _utils.assertNodeType)("StringLiteral") } } }); (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)("PrivateName", { visitor: ["id"], aliases: ["Private"], fields: { id: { validate: (0, _utils.assertNodeType)("Identifier") } } }); (0, _utils.default)("RecordExpression", { visitor: ["properties"], aliases: ["Expression"], fields: { properties: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("ObjectProperty", "SpreadElement"))) } } }); (0, _utils.default)("TupleExpression", { fields: { elements: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Expression", "SpreadElement"))), default: [] } }, visitor: ["elements"], aliases: ["Expression"] }); (0, _utils.default)("DecimalLiteral", { builder: ["value"], fields: { value: { validate: (0, _utils.assertValueType)("string") } }, aliases: ["Expression", "Pureish", "Literal", "Immutable"] }); (0, _utils.default)("StaticBlock", { visitor: ["body"], fields: { body: { validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Statement"))) } }, aliases: ["Scopable", "BlockParent"] }); }); unwrapExports(experimental); var typescript = createCommonjsModule(function (module) { var _utils = _interopRequireWildcard(utils); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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({}, core.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", "TSBooleanKeyword", "TSBigIntKeyword", "TSIntrinsicKeyword", "TSNeverKeyword", "TSNullKeyword", "TSNumberKeyword", "TSObjectKeyword", "TSStringKeyword", "TSSymbolKeyword", "TSUndefinedKeyword", "TSUnknownKeyword", "TSVoidKeyword"]; for (const type of tsKeywordTypes) { (0, _utils.default)(type, { aliases: ["TSType", "TSBaseType"], visitor: [], fields: {} }); } (0, _utils.default)("TSThisType", { aliases: ["TSType", "TSBaseType"], 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"], builder: ["parameterName", "typeAnnotation", "asserts"], fields: { parameterName: (0, _utils.validateType)(["Identifier", "TSThisType"]), typeAnnotation: (0, _utils.validateOptionalType)("TSTypeAnnotation"), asserts: (0, _utils.validateOptional)(bool) } }); (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", "TSNamedTupleMember"]) } }); (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") } }); (0, _utils.default)("TSNamedTupleMember", { visitor: ["label", "elementType"], builder: ["label", "elementType", "optional"], fields: { label: (0, _utils.validateType)("Identifier"), optional: { validate: bool, default: false }, elementType: (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", "nameType"], fields: { readonly: (0, _utils.validateOptional)(bool), typeParameter: (0, _utils.validateType)("TSTypeParameter"), optional: (0, _utils.validateOptional)(bool), typeAnnotation: (0, _utils.validateOptionalType)("TSType"), nameType: (0, _utils.validateOptionalType)("TSType") } }); (0, _utils.default)("TSLiteralType", { aliases: ["TSType", "TSBaseType"], visitor: ["literal"], fields: { literal: (0, _utils.validateType)(["NumericLiteral", "StringLiteral", "BooleanLiteral", "BigIntLiteral"]) } }); (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", { aliases: ["Scopable", "Block", "BlockParent"], 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", { builder: ["constraint", "default", "name"], 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 } } }); }); unwrapExports(typescript); var definitions = createCommonjsModule(function (module, exports) { 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, "NODE_PARENT_VALIDATIONS", { enumerable: true, get: function () { return utils.NODE_PARENT_VALIDATIONS; } }); 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; var _toFastProperties = _interopRequireDefault(toFastProperties); 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; }); unwrapExports(definitions); var definitions_1 = definitions.TYPES; var builder_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = builder; var _clone = _interopRequireDefault(clone_1); var _validate = _interopRequireDefault(validate_1); 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; } }); unwrapExports(builder_1); var generated$1 = createCommonjsModule(function (module, exports) { 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.ClassExpression = exports.classExpression = classExpression; exports.ClassDeclaration = exports.classDeclaration = classDeclaration; 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.AwaitExpression = exports.awaitExpression = awaitExpression; exports.import = exports.Import = _import; exports.BigIntLiteral = exports.bigIntLiteral = bigIntLiteral; exports.ExportNamespaceSpecifier = exports.exportNamespaceSpecifier = exportNamespaceSpecifier; exports.OptionalMemberExpression = exports.optionalMemberExpression = optionalMemberExpression; exports.OptionalCallExpression = exports.optionalCallExpression = optionalCallExpression; 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.SymbolTypeAnnotation = exports.symbolTypeAnnotation = symbolTypeAnnotation; 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.EnumDeclaration = exports.enumDeclaration = enumDeclaration; exports.EnumBooleanBody = exports.enumBooleanBody = enumBooleanBody; exports.EnumNumberBody = exports.enumNumberBody = enumNumberBody; exports.EnumStringBody = exports.enumStringBody = enumStringBody; exports.EnumSymbolBody = exports.enumSymbolBody = enumSymbolBody; exports.EnumBooleanMember = exports.enumBooleanMember = enumBooleanMember; exports.EnumNumberMember = exports.enumNumberMember = enumNumberMember; exports.EnumStringMember = exports.enumStringMember = enumStringMember; exports.EnumDefaultedMember = exports.enumDefaultedMember = enumDefaultedMember; 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.V8IntrinsicIdentifier = exports.v8IntrinsicIdentifier = v8IntrinsicIdentifier; exports.ArgumentPlaceholder = exports.argumentPlaceholder = argumentPlaceholder; exports.BindExpression = exports.bindExpression = bindExpression; exports.ClassProperty = exports.classProperty = classProperty; exports.PipelineTopicExpression = exports.pipelineTopicExpression = pipelineTopicExpression; exports.PipelineBareFunction = exports.pipelineBareFunction = pipelineBareFunction; exports.PipelinePrimaryTopicReference = exports.pipelinePrimaryTopicReference = pipelinePrimaryTopicReference; exports.ClassPrivateProperty = exports.classPrivateProperty = classPrivateProperty; exports.ClassPrivateMethod = exports.classPrivateMethod = classPrivateMethod; exports.ImportAttribute = exports.importAttribute = importAttribute; exports.Decorator = exports.decorator = decorator; exports.DoExpression = exports.doExpression = doExpression; exports.ExportDefaultSpecifier = exports.exportDefaultSpecifier = exportDefaultSpecifier; exports.PrivateName = exports.privateName = privateName; exports.RecordExpression = exports.recordExpression = recordExpression; exports.TupleExpression = exports.tupleExpression = tupleExpression; exports.DecimalLiteral = exports.decimalLiteral = decimalLiteral; exports.StaticBlock = exports.staticBlock = staticBlock; 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.tSBooleanKeyword = exports.TSBooleanKeyword = exports.tsBooleanKeyword = tsBooleanKeyword; exports.tSBigIntKeyword = exports.TSBigIntKeyword = exports.tsBigIntKeyword = tsBigIntKeyword; exports.tSIntrinsicKeyword = exports.TSIntrinsicKeyword = exports.tsIntrinsicKeyword = tsIntrinsicKeyword; exports.tSNeverKeyword = exports.TSNeverKeyword = exports.tsNeverKeyword = tsNeverKeyword; exports.tSNullKeyword = exports.TSNullKeyword = exports.tsNullKeyword = tsNullKeyword; exports.tSNumberKeyword = exports.TSNumberKeyword = exports.tsNumberKeyword = tsNumberKeyword; exports.tSObjectKeyword = exports.TSObjectKeyword = exports.tsObjectKeyword = tsObjectKeyword; exports.tSStringKeyword = exports.TSStringKeyword = exports.tsStringKeyword = tsStringKeyword; exports.tSSymbolKeyword = exports.TSSymbolKeyword = exports.tsSymbolKeyword = tsSymbolKeyword; exports.tSUndefinedKeyword = exports.TSUndefinedKeyword = exports.tsUndefinedKeyword = tsUndefinedKeyword; exports.tSUnknownKeyword = exports.TSUnknownKeyword = exports.tsUnknownKeyword = tsUnknownKeyword; exports.tSVoidKeyword = exports.TSVoidKeyword = exports.tsVoidKeyword = tsVoidKeyword; 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.tSNamedTupleMember = exports.TSNamedTupleMember = exports.tsNamedTupleMember = tsNamedTupleMember; 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(builder_1); 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 classExpression(...args) { return (0, _builder.default)("ClassExpression", ...args); } function classDeclaration(...args) { return (0, _builder.default)("ClassDeclaration", ...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 awaitExpression(...args) { return (0, _builder.default)("AwaitExpression", ...args); } function _import(...args) { return (0, _builder.default)("Import", ...args); } function bigIntLiteral(...args) { return (0, _builder.default)("BigIntLiteral", ...args); } function exportNamespaceSpecifier(...args) { return (0, _builder.default)("ExportNamespaceSpecifier", ...args); } function optionalMemberExpression(...args) { return (0, _builder.default)("OptionalMemberExpression", ...args); } function optionalCallExpression(...args) { return (0, _builder.default)("OptionalCallExpression", ...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 symbolTypeAnnotation(...args) { return (0, _builder.default)("SymbolTypeAnnotation", ...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 enumDeclaration(...args) { return (0, _builder.default)("EnumDeclaration", ...args); } function enumBooleanBody(...args) { return (0, _builder.default)("EnumBooleanBody", ...args); } function enumNumberBody(...args) { return (0, _builder.default)("EnumNumberBody", ...args); } function enumStringBody(...args) { return (0, _builder.default)("EnumStringBody", ...args); } function enumSymbolBody(...args) { return (0, _builder.default)("EnumSymbolBody", ...args); } function enumBooleanMember(...args) { return (0, _builder.default)("EnumBooleanMember", ...args); } function enumNumberMember(...args) { return (0, _builder.default)("EnumNumberMember", ...args); } function enumStringMember(...args) { return (0, _builder.default)("EnumStringMember", ...args); } function enumDefaultedMember(...args) { return (0, _builder.default)("EnumDefaultedMember", ...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 v8IntrinsicIdentifier(...args) { return (0, _builder.default)("V8IntrinsicIdentifier", ...args); } function argumentPlaceholder(...args) { return (0, _builder.default)("ArgumentPlaceholder", ...args); } function bindExpression(...args) { return (0, _builder.default)("BindExpression", ...args); } function classProperty(...args) { return (0, _builder.default)("ClassProperty", ...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 classPrivateProperty(...args) { return (0, _builder.default)("ClassPrivateProperty", ...args); } function classPrivateMethod(...args) { return (0, _builder.default)("ClassPrivateMethod", ...args); } function importAttribute(...args) { return (0, _builder.default)("ImportAttribute", ...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 privateName(...args) { return (0, _builder.default)("PrivateName", ...args); } function recordExpression(...args) { return (0, _builder.default)("RecordExpression", ...args); } function tupleExpression(...args) { return (0, _builder.default)("TupleExpression", ...args); } function decimalLiteral(...args) { return (0, _builder.default)("DecimalLiteral", ...args); } function staticBlock(...args) { return (0, _builder.default)("StaticBlock", ...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 tsBooleanKeyword(...args) { return (0, _builder.default)("TSBooleanKeyword", ...args); } function tsBigIntKeyword(...args) { return (0, _builder.default)("TSBigIntKeyword", ...args); } function tsIntrinsicKeyword(...args) { return (0, _builder.default)("TSIntrinsicKeyword", ...args); } function tsNeverKeyword(...args) { return (0, _builder.default)("TSNeverKeyword", ...args); } function tsNullKeyword(...args) { return (0, _builder.default)("TSNullKeyword", ...args); } function tsNumberKeyword(...args) { return (0, _builder.default)("TSNumberKeyword", ...args); } function tsObjectKeyword(...args) { return (0, _builder.default)("TSObjectKeyword", ...args); } function tsStringKeyword(...args) { return (0, _builder.default)("TSStringKeyword", ...args); } function tsSymbolKeyword(...args) { return (0, _builder.default)("TSSymbolKeyword", ...args); } function tsUndefinedKeyword(...args) { return (0, _builder.default)("TSUndefinedKeyword", ...args); } function tsUnknownKeyword(...args) { return (0, _builder.default)("TSUnknownKeyword", ...args); } function tsVoidKeyword(...args) { return (0, _builder.default)("TSVoidKeyword", ...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 tsNamedTupleMember(...args) { return (0, _builder.default)("TSNamedTupleMember", ...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 (0, _builder.default)("NumberLiteral", ...args); } function RegexLiteral(...args) { console.trace("The node type RegexLiteral has been renamed to RegExpLiteral"); return (0, _builder.default)("RegexLiteral", ...args); } function RestProperty(...args) { console.trace("The node type RestProperty has been renamed to RestElement"); return (0, _builder.default)("RestProperty", ...args); } function SpreadProperty(...args) { console.trace("The node type SpreadProperty has been renamed to SpreadElement"); return (0, _builder.default)("SpreadProperty", ...args); } }); unwrapExports(generated$1); var generated_1$1 = generated$1.ArrayExpression; var generated_2$1 = generated$1.arrayExpression; var generated_3$1 = generated$1.AssignmentExpression; var generated_4$1 = generated$1.assignmentExpression; var generated_5$1 = generated$1.BinaryExpression; var generated_6$1 = generated$1.binaryExpression; var generated_7$1 = generated$1.InterpreterDirective; var generated_8$1 = generated$1.interpreterDirective; var generated_9$1 = generated$1.Directive; var generated_10$1 = generated$1.directive; var generated_11$1 = generated$1.DirectiveLiteral; var generated_12$1 = generated$1.directiveLiteral; var generated_13$1 = generated$1.BlockStatement; var generated_14$1 = generated$1.blockStatement; var generated_15$1 = generated$1.BreakStatement; var generated_16$1 = generated$1.breakStatement; var generated_17$1 = generated$1.CallExpression; var generated_18$1 = generated$1.callExpression; var generated_19$1 = generated$1.CatchClause; var generated_20$1 = generated$1.catchClause; var generated_21$1 = generated$1.ConditionalExpression; var generated_22$1 = generated$1.conditionalExpression; var generated_23$1 = generated$1.ContinueStatement; var generated_24$1 = generated$1.continueStatement; var generated_25$1 = generated$1.DebuggerStatement; var generated_26$1 = generated$1.debuggerStatement; var generated_27$1 = generated$1.DoWhileStatement; var generated_28$1 = generated$1.doWhileStatement; var generated_29$1 = generated$1.EmptyStatement; var generated_30$1 = generated$1.emptyStatement; var generated_31$1 = generated$1.ExpressionStatement; var generated_32$1 = generated$1.expressionStatement; var generated_33$1 = generated$1.File; var generated_34$1 = generated$1.file; var generated_35$1 = generated$1.ForInStatement; var generated_36$1 = generated$1.forInStatement; var generated_37$1 = generated$1.ForStatement; var generated_38$1 = generated$1.forStatement; var generated_39$1 = generated$1.FunctionDeclaration; var generated_40$1 = generated$1.functionDeclaration; var generated_41$1 = generated$1.FunctionExpression; var generated_42$1 = generated$1.functionExpression; var generated_43$1 = generated$1.Identifier; var generated_44$1 = generated$1.identifier; var generated_45$1 = generated$1.IfStatement; var generated_46$1 = generated$1.ifStatement; var generated_47$1 = generated$1.LabeledStatement; var generated_48$1 = generated$1.labeledStatement; var generated_49$1 = generated$1.StringLiteral; var generated_50$1 = generated$1.stringLiteral; var generated_51$1 = generated$1.NumericLiteral; var generated_52$1 = generated$1.numericLiteral; var generated_53$1 = generated$1.NullLiteral; var generated_54$1 = generated$1.nullLiteral; var generated_55$1 = generated$1.BooleanLiteral; var generated_56$1 = generated$1.booleanLiteral; var generated_57$1 = generated$1.RegExpLiteral; var generated_58$1 = generated$1.regExpLiteral; var generated_59$1 = generated$1.LogicalExpression; var generated_60$1 = generated$1.logicalExpression; var generated_61$1 = generated$1.MemberExpression; var generated_62$1 = generated$1.memberExpression; var generated_63$1 = generated$1.NewExpression; var generated_64$1 = generated$1.newExpression; var generated_65$1 = generated$1.Program; var generated_66$1 = generated$1.program; var generated_67$1 = generated$1.ObjectExpression; var generated_68$1 = generated$1.objectExpression; var generated_69$1 = generated$1.ObjectMethod; var generated_70$1 = generated$1.objectMethod; var generated_71$1 = generated$1.ObjectProperty; var generated_72$1 = generated$1.objectProperty; var generated_73$1 = generated$1.RestElement; var generated_74$1 = generated$1.restElement; var generated_75$1 = generated$1.ReturnStatement; var generated_76$1 = generated$1.returnStatement; var generated_77$1 = generated$1.SequenceExpression; var generated_78$1 = generated$1.sequenceExpression; var generated_79$1 = generated$1.ParenthesizedExpression; var generated_80$1 = generated$1.parenthesizedExpression; var generated_81$1 = generated$1.SwitchCase; var generated_82$1 = generated$1.switchCase; var generated_83$1 = generated$1.SwitchStatement; var generated_84$1 = generated$1.switchStatement; var generated_85$1 = generated$1.ThisExpression; var generated_86$1 = generated$1.thisExpression; var generated_87$1 = generated$1.ThrowStatement; var generated_88$1 = generated$1.throwStatement; var generated_89$1 = generated$1.TryStatement; var generated_90$1 = generated$1.tryStatement; var generated_91$1 = generated$1.UnaryExpression; var generated_92$1 = generated$1.unaryExpression; var generated_93$1 = generated$1.UpdateExpression; var generated_94$1 = generated$1.updateExpression; var generated_95$1 = generated$1.VariableDeclaration; var generated_96$1 = generated$1.variableDeclaration; var generated_97$1 = generated$1.VariableDeclarator; var generated_98$1 = generated$1.variableDeclarator; var generated_99$1 = generated$1.WhileStatement; var generated_100$1 = generated$1.whileStatement; var generated_101$1 = generated$1.WithStatement; var generated_102$1 = generated$1.withStatement; var generated_103$1 = generated$1.AssignmentPattern; var generated_104$1 = generated$1.assignmentPattern; var generated_105$1 = generated$1.ArrayPattern; var generated_106$1 = generated$1.arrayPattern; var generated_107$1 = generated$1.ArrowFunctionExpression; var generated_108$1 = generated$1.arrowFunctionExpression; var generated_109$1 = generated$1.ClassBody; var generated_110$1 = generated$1.classBody; var generated_111$1 = generated$1.ClassExpression; var generated_112$1 = generated$1.classExpression; var generated_113$1 = generated$1.ClassDeclaration; var generated_114$1 = generated$1.classDeclaration; var generated_115$1 = generated$1.ExportAllDeclaration; var generated_116$1 = generated$1.exportAllDeclaration; var generated_117$1 = generated$1.ExportDefaultDeclaration; var generated_118$1 = generated$1.exportDefaultDeclaration; var generated_119$1 = generated$1.ExportNamedDeclaration; var generated_120$1 = generated$1.exportNamedDeclaration; var generated_121$1 = generated$1.ExportSpecifier; var generated_122$1 = generated$1.exportSpecifier; var generated_123$1 = generated$1.ForOfStatement; var generated_124$1 = generated$1.forOfStatement; var generated_125$1 = generated$1.ImportDeclaration; var generated_126$1 = generated$1.importDeclaration; var generated_127$1 = generated$1.ImportDefaultSpecifier; var generated_128$1 = generated$1.importDefaultSpecifier; var generated_129$1 = generated$1.ImportNamespaceSpecifier; var generated_130$1 = generated$1.importNamespaceSpecifier; var generated_131$1 = generated$1.ImportSpecifier; var generated_132$1 = generated$1.importSpecifier; var generated_133$1 = generated$1.MetaProperty; var generated_134$1 = generated$1.metaProperty; var generated_135$1 = generated$1.ClassMethod; var generated_136$1 = generated$1.classMethod; var generated_137$1 = generated$1.ObjectPattern; var generated_138$1 = generated$1.objectPattern; var generated_139$1 = generated$1.SpreadElement; var generated_140$1 = generated$1.spreadElement; var generated_141$1 = generated$1.Super; var generated_142$1 = generated$1.TaggedTemplateExpression; var generated_143$1 = generated$1.taggedTemplateExpression; var generated_144$1 = generated$1.TemplateElement; var generated_145$1 = generated$1.templateElement; var generated_146$1 = generated$1.TemplateLiteral; var generated_147$1 = generated$1.templateLiteral; var generated_148$1 = generated$1.YieldExpression; var generated_149$1 = generated$1.yieldExpression; var generated_150$1 = generated$1.AwaitExpression; var generated_151$1 = generated$1.awaitExpression; var generated_152$1 = generated$1.Import; var generated_153$1 = generated$1.BigIntLiteral; var generated_154$1 = generated$1.bigIntLiteral; var generated_155$1 = generated$1.ExportNamespaceSpecifier; var generated_156$1 = generated$1.exportNamespaceSpecifier; var generated_157$1 = generated$1.OptionalMemberExpression; var generated_158$1 = generated$1.optionalMemberExpression; var generated_159$1 = generated$1.OptionalCallExpression; var generated_160$1 = generated$1.optionalCallExpression; var generated_161$1 = generated$1.AnyTypeAnnotation; var generated_162$1 = generated$1.anyTypeAnnotation; var generated_163$1 = generated$1.ArrayTypeAnnotation; var generated_164$1 = generated$1.arrayTypeAnnotation; var generated_165$1 = generated$1.BooleanTypeAnnotation; var generated_166$1 = generated$1.booleanTypeAnnotation; var generated_167$1 = generated$1.BooleanLiteralTypeAnnotation; var generated_168$1 = generated$1.booleanLiteralTypeAnnotation; var generated_169$1 = generated$1.NullLiteralTypeAnnotation; var generated_170$1 = generated$1.nullLiteralTypeAnnotation; var generated_171$1 = generated$1.ClassImplements; var generated_172$1 = generated$1.classImplements; var generated_173$1 = generated$1.DeclareClass; var generated_174$1 = generated$1.declareClass; var generated_175$1 = generated$1.DeclareFunction; var generated_176$1 = generated$1.declareFunction; var generated_177$1 = generated$1.DeclareInterface; var generated_178$1 = generated$1.declareInterface; var generated_179$1 = generated$1.DeclareModule; var generated_180$1 = generated$1.declareModule; var generated_181$1 = generated$1.DeclareModuleExports; var generated_182$1 = generated$1.declareModuleExports; var generated_183$1 = generated$1.DeclareTypeAlias; var generated_184$1 = generated$1.declareTypeAlias; var generated_185$1 = generated$1.DeclareOpaqueType; var generated_186$1 = generated$1.declareOpaqueType; var generated_187$1 = generated$1.DeclareVariable; var generated_188$1 = generated$1.declareVariable; var generated_189$1 = generated$1.DeclareExportDeclaration; var generated_190$1 = generated$1.declareExportDeclaration; var generated_191$1 = generated$1.DeclareExportAllDeclaration; var generated_192$1 = generated$1.declareExportAllDeclaration; var generated_193$1 = generated$1.DeclaredPredicate; var generated_194$1 = generated$1.declaredPredicate; var generated_195$1 = generated$1.ExistsTypeAnnotation; var generated_196$1 = generated$1.existsTypeAnnotation; var generated_197$1 = generated$1.FunctionTypeAnnotation; var generated_198$1 = generated$1.functionTypeAnnotation; var generated_199$1 = generated$1.FunctionTypeParam; var generated_200$1 = generated$1.functionTypeParam; var generated_201$1 = generated$1.GenericTypeAnnotation; var generated_202$1 = generated$1.genericTypeAnnotation; var generated_203$1 = generated$1.InferredPredicate; var generated_204$1 = generated$1.inferredPredicate; var generated_205$1 = generated$1.InterfaceExtends; var generated_206$1 = generated$1.interfaceExtends; var generated_207$1 = generated$1.InterfaceDeclaration; var generated_208$1 = generated$1.interfaceDeclaration; var generated_209$1 = generated$1.InterfaceTypeAnnotation; var generated_210$1 = generated$1.interfaceTypeAnnotation; var generated_211$1 = generated$1.IntersectionTypeAnnotation; var generated_212$1 = generated$1.intersectionTypeAnnotation; var generated_213$1 = generated$1.MixedTypeAnnotation; var generated_214$1 = generated$1.mixedTypeAnnotation; var generated_215$1 = generated$1.EmptyTypeAnnotation; var generated_216$1 = generated$1.emptyTypeAnnotation; var generated_217$1 = generated$1.NullableTypeAnnotation; var generated_218$1 = generated$1.nullableTypeAnnotation; var generated_219$1 = generated$1.NumberLiteralTypeAnnotation; var generated_220$1 = generated$1.numberLiteralTypeAnnotation; var generated_221$1 = generated$1.NumberTypeAnnotation; var generated_222$1 = generated$1.numberTypeAnnotation; var generated_223$1 = generated$1.ObjectTypeAnnotation; var generated_224$1 = generated$1.objectTypeAnnotation; var generated_225$1 = generated$1.ObjectTypeInternalSlot; var generated_226$1 = generated$1.objectTypeInternalSlot; var generated_227$1 = generated$1.ObjectTypeCallProperty; var generated_228$1 = generated$1.objectTypeCallProperty; var generated_229$1 = generated$1.ObjectTypeIndexer; var generated_230$1 = generated$1.objectTypeIndexer; var generated_231$1 = generated$1.ObjectTypeProperty; var generated_232$1 = generated$1.objectTypeProperty; var generated_233$1 = generated$1.ObjectTypeSpreadProperty; var generated_234$1 = generated$1.objectTypeSpreadProperty; var generated_235$1 = generated$1.OpaqueType; var generated_236$1 = generated$1.opaqueType; var generated_237$1 = generated$1.QualifiedTypeIdentifier; var generated_238$1 = generated$1.qualifiedTypeIdentifier; var generated_239$1 = generated$1.StringLiteralTypeAnnotation; var generated_240$1 = generated$1.stringLiteralTypeAnnotation; var generated_241$1 = generated$1.StringTypeAnnotation; var generated_242$1 = generated$1.stringTypeAnnotation; var generated_243$1 = generated$1.SymbolTypeAnnotation; var generated_244$1 = generated$1.symbolTypeAnnotation; var generated_245$1 = generated$1.ThisTypeAnnotation; var generated_246$1 = generated$1.thisTypeAnnotation; var generated_247$1 = generated$1.TupleTypeAnnotation; var generated_248$1 = generated$1.tupleTypeAnnotation; var generated_249$1 = generated$1.TypeofTypeAnnotation; var generated_250$1 = generated$1.typeofTypeAnnotation; var generated_251$1 = generated$1.TypeAlias; var generated_252$1 = generated$1.typeAlias; var generated_253$1 = generated$1.TypeAnnotation; var generated_254$1 = generated$1.typeAnnotation; var generated_255$1 = generated$1.TypeCastExpression; var generated_256$1 = generated$1.typeCastExpression; var generated_257$1 = generated$1.TypeParameter; var generated_258$1 = generated$1.typeParameter; var generated_259$1 = generated$1.TypeParameterDeclaration; var generated_260$1 = generated$1.typeParameterDeclaration; var generated_261$1 = generated$1.TypeParameterInstantiation; var generated_262$1 = generated$1.typeParameterInstantiation; var generated_263$1 = generated$1.UnionTypeAnnotation; var generated_264$1 = generated$1.unionTypeAnnotation; var generated_265$1 = generated$1.Variance; var generated_266$1 = generated$1.variance; var generated_267$1 = generated$1.VoidTypeAnnotation; var generated_268$1 = generated$1.voidTypeAnnotation; var generated_269$1 = generated$1.EnumDeclaration; var generated_270$1 = generated$1.enumDeclaration; var generated_271$1 = generated$1.EnumBooleanBody; var generated_272$1 = generated$1.enumBooleanBody; var generated_273$1 = generated$1.EnumNumberBody; var generated_274$1 = generated$1.enumNumberBody; var generated_275$1 = generated$1.EnumStringBody; var generated_276$1 = generated$1.enumStringBody; var generated_277$1 = generated$1.EnumSymbolBody; var generated_278$1 = generated$1.enumSymbolBody; var generated_279$1 = generated$1.EnumBooleanMember; var generated_280$1 = generated$1.enumBooleanMember; var generated_281$1 = generated$1.EnumNumberMember; var generated_282$1 = generated$1.enumNumberMember; var generated_283$1 = generated$1.EnumStringMember; var generated_284$1 = generated$1.enumStringMember; var generated_285$1 = generated$1.EnumDefaultedMember; var generated_286$1 = generated$1.enumDefaultedMember; var generated_287$1 = generated$1.jSXAttribute; var generated_288$1 = generated$1.JSXAttribute; var generated_289$1 = generated$1.jsxAttribute; var generated_290$1 = generated$1.jSXClosingElement; var generated_291$1 = generated$1.JSXClosingElement; var generated_292 = generated$1.jsxClosingElement; var generated_293 = generated$1.jSXElement; var generated_294 = generated$1.JSXElement; var generated_295 = generated$1.jsxElement; var generated_296 = generated$1.jSXEmptyExpression; var generated_297 = generated$1.JSXEmptyExpression; var generated_298 = generated$1.jsxEmptyExpression; var generated_299 = generated$1.jSXExpressionContainer; var generated_300 = generated$1.JSXExpressionContainer; var generated_301 = generated$1.jsxExpressionContainer; var generated_302 = generated$1.jSXSpreadChild; var generated_303 = generated$1.JSXSpreadChild; var generated_304 = generated$1.jsxSpreadChild; var generated_305 = generated$1.jSXIdentifier; var generated_306 = generated$1.JSXIdentifier; var generated_307 = generated$1.jsxIdentifier; var generated_308 = generated$1.jSXMemberExpression; var generated_309 = generated$1.JSXMemberExpression; var generated_310 = generated$1.jsxMemberExpression; var generated_311 = generated$1.jSXNamespacedName; var generated_312 = generated$1.JSXNamespacedName; var generated_313 = generated$1.jsxNamespacedName; var generated_314 = generated$1.jSXOpeningElement; var generated_315 = generated$1.JSXOpeningElement; var generated_316 = generated$1.jsxOpeningElement; var generated_317 = generated$1.jSXSpreadAttribute; var generated_318 = generated$1.JSXSpreadAttribute; var generated_319 = generated$1.jsxSpreadAttribute; var generated_320 = generated$1.jSXText; var generated_321 = generated$1.JSXText; var generated_322 = generated$1.jsxText; var generated_323 = generated$1.jSXFragment; var generated_324 = generated$1.JSXFragment; var generated_325 = generated$1.jsxFragment; var generated_326 = generated$1.jSXOpeningFragment; var generated_327 = generated$1.JSXOpeningFragment; var generated_328 = generated$1.jsxOpeningFragment; var generated_329 = generated$1.jSXClosingFragment; var generated_330 = generated$1.JSXClosingFragment; var generated_331 = generated$1.jsxClosingFragment; var generated_332 = generated$1.Noop; var generated_333 = generated$1.noop; var generated_334 = generated$1.Placeholder; var generated_335 = generated$1.placeholder; var generated_336 = generated$1.V8IntrinsicIdentifier; var generated_337 = generated$1.v8IntrinsicIdentifier; var generated_338 = generated$1.ArgumentPlaceholder; var generated_339 = generated$1.argumentPlaceholder; var generated_340 = generated$1.BindExpression; var generated_341 = generated$1.bindExpression; var generated_342 = generated$1.ClassProperty; var generated_343 = generated$1.classProperty; var generated_344 = generated$1.PipelineTopicExpression; var generated_345 = generated$1.pipelineTopicExpression; var generated_346 = generated$1.PipelineBareFunction; var generated_347 = generated$1.pipelineBareFunction; var generated_348 = generated$1.PipelinePrimaryTopicReference; var generated_349 = generated$1.pipelinePrimaryTopicReference; var generated_350 = generated$1.ClassPrivateProperty; var generated_351 = generated$1.classPrivateProperty; var generated_352 = generated$1.ClassPrivateMethod; var generated_353 = generated$1.classPrivateMethod; var generated_354 = generated$1.ImportAttribute; var generated_355 = generated$1.importAttribute; var generated_356 = generated$1.Decorator; var generated_357 = generated$1.decorator; var generated_358 = generated$1.DoExpression; var generated_359 = generated$1.doExpression; var generated_360 = generated$1.ExportDefaultSpecifier; var generated_361 = generated$1.exportDefaultSpecifier; var generated_362 = generated$1.PrivateName; var generated_363 = generated$1.privateName; var generated_364 = generated$1.RecordExpression; var generated_365 = generated$1.recordExpression; var generated_366 = generated$1.TupleExpression; var generated_367 = generated$1.tupleExpression; var generated_368 = generated$1.DecimalLiteral; var generated_369 = generated$1.decimalLiteral; var generated_370 = generated$1.StaticBlock; var generated_371 = generated$1.staticBlock; var generated_372 = generated$1.tSParameterProperty; var generated_373 = generated$1.TSParameterProperty; var generated_374 = generated$1.tsParameterProperty; var generated_375 = generated$1.tSDeclareFunction; var generated_376 = generated$1.TSDeclareFunction; var generated_377 = generated$1.tsDeclareFunction; var generated_378 = generated$1.tSDeclareMethod; var generated_379 = generated$1.TSDeclareMethod; var generated_380 = generated$1.tsDeclareMethod; var generated_381 = generated$1.tSQualifiedName; var generated_382 = generated$1.TSQualifiedName; var generated_383 = generated$1.tsQualifiedName; var generated_384 = generated$1.tSCallSignatureDeclaration; var generated_385 = generated$1.TSCallSignatureDeclaration; var generated_386 = generated$1.tsCallSignatureDeclaration; var generated_387 = generated$1.tSConstructSignatureDeclaration; var generated_388 = generated$1.TSConstructSignatureDeclaration; var generated_389 = generated$1.tsConstructSignatureDeclaration; var generated_390 = generated$1.tSPropertySignature; var generated_391 = generated$1.TSPropertySignature; var generated_392 = generated$1.tsPropertySignature; var generated_393 = generated$1.tSMethodSignature; var generated_394 = generated$1.TSMethodSignature; var generated_395 = generated$1.tsMethodSignature; var generated_396 = generated$1.tSIndexSignature; var generated_397 = generated$1.TSIndexSignature; var generated_398 = generated$1.tsIndexSignature; var generated_399 = generated$1.tSAnyKeyword; var generated_400 = generated$1.TSAnyKeyword; var generated_401 = generated$1.tsAnyKeyword; var generated_402 = generated$1.tSBooleanKeyword; var generated_403 = generated$1.TSBooleanKeyword; var generated_404 = generated$1.tsBooleanKeyword; var generated_405 = generated$1.tSBigIntKeyword; var generated_406 = generated$1.TSBigIntKeyword; var generated_407 = generated$1.tsBigIntKeyword; var generated_408 = generated$1.tSIntrinsicKeyword; var generated_409 = generated$1.TSIntrinsicKeyword; var generated_410 = generated$1.tsIntrinsicKeyword; var generated_411 = generated$1.tSNeverKeyword; var generated_412 = generated$1.TSNeverKeyword; var generated_413 = generated$1.tsNeverKeyword; var generated_414 = generated$1.tSNullKeyword; var generated_415 = generated$1.TSNullKeyword; var generated_416 = generated$1.tsNullKeyword; var generated_417 = generated$1.tSNumberKeyword; var generated_418 = generated$1.TSNumberKeyword; var generated_419 = generated$1.tsNumberKeyword; var generated_420 = generated$1.tSObjectKeyword; var generated_421 = generated$1.TSObjectKeyword; var generated_422 = generated$1.tsObjectKeyword; var generated_423 = generated$1.tSStringKeyword; var generated_424 = generated$1.TSStringKeyword; var generated_425 = generated$1.tsStringKeyword; var generated_426 = generated$1.tSSymbolKeyword; var generated_427 = generated$1.TSSymbolKeyword; var generated_428 = generated$1.tsSymbolKeyword; var generated_429 = generated$1.tSUndefinedKeyword; var generated_430 = generated$1.TSUndefinedKeyword; var generated_431 = generated$1.tsUndefinedKeyword; var generated_432 = generated$1.tSUnknownKeyword; var generated_433 = generated$1.TSUnknownKeyword; var generated_434 = generated$1.tsUnknownKeyword; var generated_435 = generated$1.tSVoidKeyword; var generated_436 = generated$1.TSVoidKeyword; var generated_437 = generated$1.tsVoidKeyword; var generated_438 = generated$1.tSThisType; var generated_439 = generated$1.TSThisType; var generated_440 = generated$1.tsThisType; var generated_441 = generated$1.tSFunctionType; var generated_442 = generated$1.TSFunctionType; var generated_443 = generated$1.tsFunctionType; var generated_444 = generated$1.tSConstructorType; var generated_445 = generated$1.TSConstructorType; var generated_446 = generated$1.tsConstructorType; var generated_447 = generated$1.tSTypeReference; var generated_448 = generated$1.TSTypeReference; var generated_449 = generated$1.tsTypeReference; var generated_450 = generated$1.tSTypePredicate; var generated_451 = generated$1.TSTypePredicate; var generated_452 = generated$1.tsTypePredicate; var generated_453 = generated$1.tSTypeQuery; var generated_454 = generated$1.TSTypeQuery; var generated_455 = generated$1.tsTypeQuery; var generated_456 = generated$1.tSTypeLiteral; var generated_457 = generated$1.TSTypeLiteral; var generated_458 = generated$1.tsTypeLiteral; var generated_459 = generated$1.tSArrayType; var generated_460 = generated$1.TSArrayType; var generated_461 = generated$1.tsArrayType; var generated_462 = generated$1.tSTupleType; var generated_463 = generated$1.TSTupleType; var generated_464 = generated$1.tsTupleType; var generated_465 = generated$1.tSOptionalType; var generated_466 = generated$1.TSOptionalType; var generated_467 = generated$1.tsOptionalType; var generated_468 = generated$1.tSRestType; var generated_469 = generated$1.TSRestType; var generated_470 = generated$1.tsRestType; var generated_471 = generated$1.tSNamedTupleMember; var generated_472 = generated$1.TSNamedTupleMember; var generated_473 = generated$1.tsNamedTupleMember; var generated_474 = generated$1.tSUnionType; var generated_475 = generated$1.TSUnionType; var generated_476 = generated$1.tsUnionType; var generated_477 = generated$1.tSIntersectionType; var generated_478 = generated$1.TSIntersectionType; var generated_479 = generated$1.tsIntersectionType; var generated_480 = generated$1.tSConditionalType; var generated_481 = generated$1.TSConditionalType; var generated_482 = generated$1.tsConditionalType; var generated_483 = generated$1.tSInferType; var generated_484 = generated$1.TSInferType; var generated_485 = generated$1.tsInferType; var generated_486 = generated$1.tSParenthesizedType; var generated_487 = generated$1.TSParenthesizedType; var generated_488 = generated$1.tsParenthesizedType; var generated_489 = generated$1.tSTypeOperator; var generated_490 = generated$1.TSTypeOperator; var generated_491 = generated$1.tsTypeOperator; var generated_492 = generated$1.tSIndexedAccessType; var generated_493 = generated$1.TSIndexedAccessType; var generated_494 = generated$1.tsIndexedAccessType; var generated_495 = generated$1.tSMappedType; var generated_496 = generated$1.TSMappedType; var generated_497 = generated$1.tsMappedType; var generated_498 = generated$1.tSLiteralType; var generated_499 = generated$1.TSLiteralType; var generated_500 = generated$1.tsLiteralType; var generated_501 = generated$1.tSExpressionWithTypeArguments; var generated_502 = generated$1.TSExpressionWithTypeArguments; var generated_503 = generated$1.tsExpressionWithTypeArguments; var generated_504 = generated$1.tSInterfaceDeclaration; var generated_505 = generated$1.TSInterfaceDeclaration; var generated_506 = generated$1.tsInterfaceDeclaration; var generated_507 = generated$1.tSInterfaceBody; var generated_508 = generated$1.TSInterfaceBody; var generated_509 = generated$1.tsInterfaceBody; var generated_510 = generated$1.tSTypeAliasDeclaration; var generated_511 = generated$1.TSTypeAliasDeclaration; var generated_512 = generated$1.tsTypeAliasDeclaration; var generated_513 = generated$1.tSAsExpression; var generated_514 = generated$1.TSAsExpression; var generated_515 = generated$1.tsAsExpression; var generated_516 = generated$1.tSTypeAssertion; var generated_517 = generated$1.TSTypeAssertion; var generated_518 = generated$1.tsTypeAssertion; var generated_519 = generated$1.tSEnumDeclaration; var generated_520 = generated$1.TSEnumDeclaration; var generated_521 = generated$1.tsEnumDeclaration; var generated_522 = generated$1.tSEnumMember; var generated_523 = generated$1.TSEnumMember; var generated_524 = generated$1.tsEnumMember; var generated_525 = generated$1.tSModuleDeclaration; var generated_526 = generated$1.TSModuleDeclaration; var generated_527 = generated$1.tsModuleDeclaration; var generated_528 = generated$1.tSModuleBlock; var generated_529 = generated$1.TSModuleBlock; var generated_530 = generated$1.tsModuleBlock; var generated_531 = generated$1.tSImportType; var generated_532 = generated$1.TSImportType; var generated_533 = generated$1.tsImportType; var generated_534 = generated$1.tSImportEqualsDeclaration; var generated_535 = generated$1.TSImportEqualsDeclaration; var generated_536 = generated$1.tsImportEqualsDeclaration; var generated_537 = generated$1.tSExternalModuleReference; var generated_538 = generated$1.TSExternalModuleReference; var generated_539 = generated$1.tsExternalModuleReference; var generated_540 = generated$1.tSNonNullExpression; var generated_541 = generated$1.TSNonNullExpression; var generated_542 = generated$1.tsNonNullExpression; var generated_543 = generated$1.tSExportAssignment; var generated_544 = generated$1.TSExportAssignment; var generated_545 = generated$1.tsExportAssignment; var generated_546 = generated$1.tSNamespaceExportDeclaration; var generated_547 = generated$1.TSNamespaceExportDeclaration; var generated_548 = generated$1.tsNamespaceExportDeclaration; var generated_549 = generated$1.tSTypeAnnotation; var generated_550 = generated$1.TSTypeAnnotation; var generated_551 = generated$1.tsTypeAnnotation; var generated_552 = generated$1.tSTypeParameterInstantiation; var generated_553 = generated$1.TSTypeParameterInstantiation; var generated_554 = generated$1.tsTypeParameterInstantiation; var generated_555 = generated$1.tSTypeParameterDeclaration; var generated_556 = generated$1.TSTypeParameterDeclaration; var generated_557 = generated$1.tsTypeParameterDeclaration; var generated_558 = generated$1.tSTypeParameter; var generated_559 = generated$1.TSTypeParameter; var generated_560 = generated$1.tsTypeParameter; var generated_561 = generated$1.numberLiteral; var generated_562 = generated$1.NumberLiteral; var generated_563 = generated$1.regexLiteral; var generated_564 = generated$1.RegexLiteral; var generated_565 = generated$1.restProperty; var generated_566 = generated$1.RestProperty; var generated_567 = generated$1.spreadProperty; var generated_568 = generated$1.SpreadProperty; var cleanJSXElementLiteralChild_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = cleanJSXElementLiteralChild; 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$1.stringLiteral)(str)); } }); unwrapExports(cleanJSXElementLiteralChild_1); var buildChildren_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = buildChildren; var _cleanJSXElementLiteralChild = _interopRequireDefault(cleanJSXElementLiteralChild_1); 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; } }); unwrapExports(buildChildren_1); var isNode_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isNode; function isNode(node) { return !!(node && definitions.VISITOR_KEYS[node.type]); } }); unwrapExports(isNode_1); var assertNode_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = assertNode; var _isNode = _interopRequireDefault(isNode_1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function assertNode(node) { if (!(0, _isNode.default)(node)) { var _node$type; const type = (_node$type = node == null ? void 0 : node.type) != null ? _node$type : JSON.stringify(node); throw new TypeError(`Not a valid node of type "${type}"`); } } }); unwrapExports(assertNode_1); var generated$2 = createCommonjsModule(function (module, exports) { 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.assertClassExpression = assertClassExpression; exports.assertClassDeclaration = assertClassDeclaration; 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.assertAwaitExpression = assertAwaitExpression; exports.assertImport = assertImport; exports.assertBigIntLiteral = assertBigIntLiteral; exports.assertExportNamespaceSpecifier = assertExportNamespaceSpecifier; exports.assertOptionalMemberExpression = assertOptionalMemberExpression; exports.assertOptionalCallExpression = assertOptionalCallExpression; 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.assertSymbolTypeAnnotation = assertSymbolTypeAnnotation; 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.assertEnumDeclaration = assertEnumDeclaration; exports.assertEnumBooleanBody = assertEnumBooleanBody; exports.assertEnumNumberBody = assertEnumNumberBody; exports.assertEnumStringBody = assertEnumStringBody; exports.assertEnumSymbolBody = assertEnumSymbolBody; exports.assertEnumBooleanMember = assertEnumBooleanMember; exports.assertEnumNumberMember = assertEnumNumberMember; exports.assertEnumStringMember = assertEnumStringMember; exports.assertEnumDefaultedMember = assertEnumDefaultedMember; 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.assertV8IntrinsicIdentifier = assertV8IntrinsicIdentifier; exports.assertArgumentPlaceholder = assertArgumentPlaceholder; exports.assertBindExpression = assertBindExpression; exports.assertClassProperty = assertClassProperty; exports.assertPipelineTopicExpression = assertPipelineTopicExpression; exports.assertPipelineBareFunction = assertPipelineBareFunction; exports.assertPipelinePrimaryTopicReference = assertPipelinePrimaryTopicReference; exports.assertClassPrivateProperty = assertClassPrivateProperty; exports.assertClassPrivateMethod = assertClassPrivateMethod; exports.assertImportAttribute = assertImportAttribute; exports.assertDecorator = assertDecorator; exports.assertDoExpression = assertDoExpression; exports.assertExportDefaultSpecifier = assertExportDefaultSpecifier; exports.assertPrivateName = assertPrivateName; exports.assertRecordExpression = assertRecordExpression; exports.assertTupleExpression = assertTupleExpression; exports.assertDecimalLiteral = assertDecimalLiteral; exports.assertStaticBlock = assertStaticBlock; 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.assertTSBooleanKeyword = assertTSBooleanKeyword; exports.assertTSBigIntKeyword = assertTSBigIntKeyword; exports.assertTSIntrinsicKeyword = assertTSIntrinsicKeyword; exports.assertTSNeverKeyword = assertTSNeverKeyword; exports.assertTSNullKeyword = assertTSNullKeyword; exports.assertTSNumberKeyword = assertTSNumberKeyword; exports.assertTSObjectKeyword = assertTSObjectKeyword; exports.assertTSStringKeyword = assertTSStringKeyword; exports.assertTSSymbolKeyword = assertTSSymbolKeyword; exports.assertTSUndefinedKeyword = assertTSUndefinedKeyword; exports.assertTSUnknownKeyword = assertTSUnknownKeyword; exports.assertTSVoidKeyword = assertTSVoidKeyword; 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.assertTSNamedTupleMember = assertTSNamedTupleMember; 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.assertEnumBody = assertEnumBody; exports.assertEnumMember = assertEnumMember; exports.assertJSX = assertJSX; exports.assertPrivate = assertPrivate; exports.assertTSTypeElement = assertTSTypeElement; exports.assertTSType = assertTSType; exports.assertTSBaseType = assertTSBaseType; exports.assertNumberLiteral = assertNumberLiteral; exports.assertRegexLiteral = assertRegexLiteral; exports.assertRestProperty = assertRestProperty; exports.assertSpreadProperty = assertSpreadProperty; var _is = _interopRequireDefault(is_1); 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 assertClassExpression(node, opts = {}) { assert("ClassExpression", node, opts); } function assertClassDeclaration(node, opts = {}) { assert("ClassDeclaration", 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 assertAwaitExpression(node, opts = {}) { assert("AwaitExpression", node, opts); } function assertImport(node, opts = {}) { assert("Import", node, opts); } function assertBigIntLiteral(node, opts = {}) { assert("BigIntLiteral", node, opts); } function assertExportNamespaceSpecifier(node, opts = {}) { assert("ExportNamespaceSpecifier", node, opts); } function assertOptionalMemberExpression(node, opts = {}) { assert("OptionalMemberExpression", node, opts); } function assertOptionalCallExpression(node, opts = {}) { assert("OptionalCallExpression", 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 assertSymbolTypeAnnotation(node, opts = {}) { assert("SymbolTypeAnnotation", 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 assertEnumDeclaration(node, opts = {}) { assert("EnumDeclaration", node, opts); } function assertEnumBooleanBody(node, opts = {}) { assert("EnumBooleanBody", node, opts); } function assertEnumNumberBody(node, opts = {}) { assert("EnumNumberBody", node, opts); } function assertEnumStringBody(node, opts = {}) { assert("EnumStringBody", node, opts); } function assertEnumSymbolBody(node, opts = {}) { assert("EnumSymbolBody", node, opts); } function assertEnumBooleanMember(node, opts = {}) { assert("EnumBooleanMember", node, opts); } function assertEnumNumberMember(node, opts = {}) { assert("EnumNumberMember", node, opts); } function assertEnumStringMember(node, opts = {}) { assert("EnumStringMember", node, opts); } function assertEnumDefaultedMember(node, opts = {}) { assert("EnumDefaultedMember", 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 assertV8IntrinsicIdentifier(node, opts = {}) { assert("V8IntrinsicIdentifier", node, opts); } function assertArgumentPlaceholder(node, opts = {}) { assert("ArgumentPlaceholder", node, opts); } function assertBindExpression(node, opts = {}) { assert("BindExpression", node, opts); } function assertClassProperty(node, opts = {}) { assert("ClassProperty", 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 assertClassPrivateProperty(node, opts = {}) { assert("ClassPrivateProperty", node, opts); } function assertClassPrivateMethod(node, opts = {}) { assert("ClassPrivateMethod", node, opts); } function assertImportAttribute(node, opts = {}) { assert("ImportAttribute", 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 assertPrivateName(node, opts = {}) { assert("PrivateName", node, opts); } function assertRecordExpression(node, opts = {}) { assert("RecordExpression", node, opts); } function assertTupleExpression(node, opts = {}) { assert("TupleExpression", node, opts); } function assertDecimalLiteral(node, opts = {}) { assert("DecimalLiteral", node, opts); } function assertStaticBlock(node, opts = {}) { assert("StaticBlock", 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 assertTSBooleanKeyword(node, opts = {}) { assert("TSBooleanKeyword", node, opts); } function assertTSBigIntKeyword(node, opts = {}) { assert("TSBigIntKeyword", node, opts); } function assertTSIntrinsicKeyword(node, opts = {}) { assert("TSIntrinsicKeyword", node, opts); } function assertTSNeverKeyword(node, opts = {}) { assert("TSNeverKeyword", node, opts); } function assertTSNullKeyword(node, opts = {}) { assert("TSNullKeyword", node, opts); } function assertTSNumberKeyword(node, opts = {}) { assert("TSNumberKeyword", node, opts); } function assertTSObjectKeyword(node, opts = {}) { assert("TSObjectKeyword", node, opts); } function assertTSStringKeyword(node, opts = {}) { assert("TSStringKeyword", node, opts); } function assertTSSymbolKeyword(node, opts = {}) { assert("TSSymbolKeyword", node, opts); } function assertTSUndefinedKeyword(node, opts = {}) { assert("TSUndefinedKeyword", node, opts); } function assertTSUnknownKeyword(node, opts = {}) { assert("TSUnknownKeyword", node, opts); } function assertTSVoidKeyword(node, opts = {}) { assert("TSVoidKeyword", 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 assertTSNamedTupleMember(node, opts = {}) { assert("TSNamedTupleMember", 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 assertEnumBody(node, opts = {}) { assert("EnumBody", node, opts); } function assertEnumMember(node, opts = {}) { assert("EnumMember", 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 assertTSBaseType(node, opts = {}) { assert("TSBaseType", 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); } }); unwrapExports(generated$2); var generated_1$2 = generated$2.assertArrayExpression; var generated_2$2 = generated$2.assertAssignmentExpression; var generated_3$2 = generated$2.assertBinaryExpression; var generated_4$2 = generated$2.assertInterpreterDirective; var generated_5$2 = generated$2.assertDirective; var generated_6$2 = generated$2.assertDirectiveLiteral; var generated_7$2 = generated$2.assertBlockStatement; var generated_8$2 = generated$2.assertBreakStatement; var generated_9$2 = generated$2.assertCallExpression; var generated_10$2 = generated$2.assertCatchClause; var generated_11$2 = generated$2.assertConditionalExpression; var generated_12$2 = generated$2.assertContinueStatement; var generated_13$2 = generated$2.assertDebuggerStatement; var generated_14$2 = generated$2.assertDoWhileStatement; var generated_15$2 = generated$2.assertEmptyStatement; var generated_16$2 = generated$2.assertExpressionStatement; var generated_17$2 = generated$2.assertFile; var generated_18$2 = generated$2.assertForInStatement; var generated_19$2 = generated$2.assertForStatement; var generated_20$2 = generated$2.assertFunctionDeclaration; var generated_21$2 = generated$2.assertFunctionExpression; var generated_22$2 = generated$2.assertIdentifier; var generated_23$2 = generated$2.assertIfStatement; var generated_24$2 = generated$2.assertLabeledStatement; var generated_25$2 = generated$2.assertStringLiteral; var generated_26$2 = generated$2.assertNumericLiteral; var generated_27$2 = generated$2.assertNullLiteral; var generated_28$2 = generated$2.assertBooleanLiteral; var generated_29$2 = generated$2.assertRegExpLiteral; var generated_30$2 = generated$2.assertLogicalExpression; var generated_31$2 = generated$2.assertMemberExpression; var generated_32$2 = generated$2.assertNewExpression; var generated_33$2 = generated$2.assertProgram; var generated_34$2 = generated$2.assertObjectExpression; var generated_35$2 = generated$2.assertObjectMethod; var generated_36$2 = generated$2.assertObjectProperty; var generated_37$2 = generated$2.assertRestElement; var generated_38$2 = generated$2.assertReturnStatement; var generated_39$2 = generated$2.assertSequenceExpression; var generated_40$2 = generated$2.assertParenthesizedExpression; var generated_41$2 = generated$2.assertSwitchCase; var generated_42$2 = generated$2.assertSwitchStatement; var generated_43$2 = generated$2.assertThisExpression; var generated_44$2 = generated$2.assertThrowStatement; var generated_45$2 = generated$2.assertTryStatement; var generated_46$2 = generated$2.assertUnaryExpression; var generated_47$2 = generated$2.assertUpdateExpression; var generated_48$2 = generated$2.assertVariableDeclaration; var generated_49$2 = generated$2.assertVariableDeclarator; var generated_50$2 = generated$2.assertWhileStatement; var generated_51$2 = generated$2.assertWithStatement; var generated_52$2 = generated$2.assertAssignmentPattern; var generated_53$2 = generated$2.assertArrayPattern; var generated_54$2 = generated$2.assertArrowFunctionExpression; var generated_55$2 = generated$2.assertClassBody; var generated_56$2 = generated$2.assertClassExpression; var generated_57$2 = generated$2.assertClassDeclaration; var generated_58$2 = generated$2.assertExportAllDeclaration; var generated_59$2 = generated$2.assertExportDefaultDeclaration; var generated_60$2 = generated$2.assertExportNamedDeclaration; var generated_61$2 = generated$2.assertExportSpecifier; var generated_62$2 = generated$2.assertForOfStatement; var generated_63$2 = generated$2.assertImportDeclaration; var generated_64$2 = generated$2.assertImportDefaultSpecifier; var generated_65$2 = generated$2.assertImportNamespaceSpecifier; var generated_66$2 = generated$2.assertImportSpecifier; var generated_67$2 = generated$2.assertMetaProperty; var generated_68$2 = generated$2.assertClassMethod; var generated_69$2 = generated$2.assertObjectPattern; var generated_70$2 = generated$2.assertSpreadElement; var generated_71$2 = generated$2.assertSuper; var generated_72$2 = generated$2.assertTaggedTemplateExpression; var generated_73$2 = generated$2.assertTemplateElement; var generated_74$2 = generated$2.assertTemplateLiteral; var generated_75$2 = generated$2.assertYieldExpression; var generated_76$2 = generated$2.assertAwaitExpression; var generated_77$2 = generated$2.assertImport; var generated_78$2 = generated$2.assertBigIntLiteral; var generated_79$2 = generated$2.assertExportNamespaceSpecifier; var generated_80$2 = generated$2.assertOptionalMemberExpression; var generated_81$2 = generated$2.assertOptionalCallExpression; var generated_82$2 = generated$2.assertAnyTypeAnnotation; var generated_83$2 = generated$2.assertArrayTypeAnnotation; var generated_84$2 = generated$2.assertBooleanTypeAnnotation; var generated_85$2 = generated$2.assertBooleanLiteralTypeAnnotation; var generated_86$2 = generated$2.assertNullLiteralTypeAnnotation; var generated_87$2 = generated$2.assertClassImplements; var generated_88$2 = generated$2.assertDeclareClass; var generated_89$2 = generated$2.assertDeclareFunction; var generated_90$2 = generated$2.assertDeclareInterface; var generated_91$2 = generated$2.assertDeclareModule; var generated_92$2 = generated$2.assertDeclareModuleExports; var generated_93$2 = generated$2.assertDeclareTypeAlias; var generated_94$2 = generated$2.assertDeclareOpaqueType; var generated_95$2 = generated$2.assertDeclareVariable; var generated_96$2 = generated$2.assertDeclareExportDeclaration; var generated_97$2 = generated$2.assertDeclareExportAllDeclaration; var generated_98$2 = generated$2.assertDeclaredPredicate; var generated_99$2 = generated$2.assertExistsTypeAnnotation; var generated_100$2 = generated$2.assertFunctionTypeAnnotation; var generated_101$2 = generated$2.assertFunctionTypeParam; var generated_102$2 = generated$2.assertGenericTypeAnnotation; var generated_103$2 = generated$2.assertInferredPredicate; var generated_104$2 = generated$2.assertInterfaceExtends; var generated_105$2 = generated$2.assertInterfaceDeclaration; var generated_106$2 = generated$2.assertInterfaceTypeAnnotation; var generated_107$2 = generated$2.assertIntersectionTypeAnnotation; var generated_108$2 = generated$2.assertMixedTypeAnnotation; var generated_109$2 = generated$2.assertEmptyTypeAnnotation; var generated_110$2 = generated$2.assertNullableTypeAnnotation; var generated_111$2 = generated$2.assertNumberLiteralTypeAnnotation; var generated_112$2 = generated$2.assertNumberTypeAnnotation; var generated_113$2 = generated$2.assertObjectTypeAnnotation; var generated_114$2 = generated$2.assertObjectTypeInternalSlot; var generated_115$2 = generated$2.assertObjectTypeCallProperty; var generated_116$2 = generated$2.assertObjectTypeIndexer; var generated_117$2 = generated$2.assertObjectTypeProperty; var generated_118$2 = generated$2.assertObjectTypeSpreadProperty; var generated_119$2 = generated$2.assertOpaqueType; var generated_120$2 = generated$2.assertQualifiedTypeIdentifier; var generated_121$2 = generated$2.assertStringLiteralTypeAnnotation; var generated_122$2 = generated$2.assertStringTypeAnnotation; var generated_123$2 = generated$2.assertSymbolTypeAnnotation; var generated_124$2 = generated$2.assertThisTypeAnnotation; var generated_125$2 = generated$2.assertTupleTypeAnnotation; var generated_126$2 = generated$2.assertTypeofTypeAnnotation; var generated_127$2 = generated$2.assertTypeAlias; var generated_128$2 = generated$2.assertTypeAnnotation; var generated_129$2 = generated$2.assertTypeCastExpression; var generated_130$2 = generated$2.assertTypeParameter; var generated_131$2 = generated$2.assertTypeParameterDeclaration; var generated_132$2 = generated$2.assertTypeParameterInstantiation; var generated_133$2 = generated$2.assertUnionTypeAnnotation; var generated_134$2 = generated$2.assertVariance; var generated_135$2 = generated$2.assertVoidTypeAnnotation; var generated_136$2 = generated$2.assertEnumDeclaration; var generated_137$2 = generated$2.assertEnumBooleanBody; var generated_138$2 = generated$2.assertEnumNumberBody; var generated_139$2 = generated$2.assertEnumStringBody; var generated_140$2 = generated$2.assertEnumSymbolBody; var generated_141$2 = generated$2.assertEnumBooleanMember; var generated_142$2 = generated$2.assertEnumNumberMember; var generated_143$2 = generated$2.assertEnumStringMember; var generated_144$2 = generated$2.assertEnumDefaultedMember; var generated_145$2 = generated$2.assertJSXAttribute; var generated_146$2 = generated$2.assertJSXClosingElement; var generated_147$2 = generated$2.assertJSXElement; var generated_148$2 = generated$2.assertJSXEmptyExpression; var generated_149$2 = generated$2.assertJSXExpressionContainer; var generated_150$2 = generated$2.assertJSXSpreadChild; var generated_151$2 = generated$2.assertJSXIdentifier; var generated_152$2 = generated$2.assertJSXMemberExpression; var generated_153$2 = generated$2.assertJSXNamespacedName; var generated_154$2 = generated$2.assertJSXOpeningElement; var generated_155$2 = generated$2.assertJSXSpreadAttribute; var generated_156$2 = generated$2.assertJSXText; var generated_157$2 = generated$2.assertJSXFragment; var generated_158$2 = generated$2.assertJSXOpeningFragment; var generated_159$2 = generated$2.assertJSXClosingFragment; var generated_160$2 = generated$2.assertNoop; var generated_161$2 = generated$2.assertPlaceholder; var generated_162$2 = generated$2.assertV8IntrinsicIdentifier; var generated_163$2 = generated$2.assertArgumentPlaceholder; var generated_164$2 = generated$2.assertBindExpression; var generated_165$2 = generated$2.assertClassProperty; var generated_166$2 = generated$2.assertPipelineTopicExpression; var generated_167$2 = generated$2.assertPipelineBareFunction; var generated_168$2 = generated$2.assertPipelinePrimaryTopicReference; var generated_169$2 = generated$2.assertClassPrivateProperty; var generated_170$2 = generated$2.assertClassPrivateMethod; var generated_171$2 = generated$2.assertImportAttribute; var generated_172$2 = generated$2.assertDecorator; var generated_173$2 = generated$2.assertDoExpression; var generated_174$2 = generated$2.assertExportDefaultSpecifier; var generated_175$2 = generated$2.assertPrivateName; var generated_176$2 = generated$2.assertRecordExpression; var generated_177$2 = generated$2.assertTupleExpression; var generated_178$2 = generated$2.assertDecimalLiteral; var generated_179$2 = generated$2.assertStaticBlock; var generated_180$2 = generated$2.assertTSParameterProperty; var generated_181$2 = generated$2.assertTSDeclareFunction; var generated_182$2 = generated$2.assertTSDeclareMethod; var generated_183$2 = generated$2.assertTSQualifiedName; var generated_184$2 = generated$2.assertTSCallSignatureDeclaration; var generated_185$2 = generated$2.assertTSConstructSignatureDeclaration; var generated_186$2 = generated$2.assertTSPropertySignature; var generated_187$2 = generated$2.assertTSMethodSignature; var generated_188$2 = generated$2.assertTSIndexSignature; var generated_189$2 = generated$2.assertTSAnyKeyword; var generated_190$2 = generated$2.assertTSBooleanKeyword; var generated_191$2 = generated$2.assertTSBigIntKeyword; var generated_192$2 = generated$2.assertTSIntrinsicKeyword; var generated_193$2 = generated$2.assertTSNeverKeyword; var generated_194$2 = generated$2.assertTSNullKeyword; var generated_195$2 = generated$2.assertTSNumberKeyword; var generated_196$2 = generated$2.assertTSObjectKeyword; var generated_197$2 = generated$2.assertTSStringKeyword; var generated_198$2 = generated$2.assertTSSymbolKeyword; var generated_199$2 = generated$2.assertTSUndefinedKeyword; var generated_200$2 = generated$2.assertTSUnknownKeyword; var generated_201$2 = generated$2.assertTSVoidKeyword; var generated_202$2 = generated$2.assertTSThisType; var generated_203$2 = generated$2.assertTSFunctionType; var generated_204$2 = generated$2.assertTSConstructorType; var generated_205$2 = generated$2.assertTSTypeReference; var generated_206$2 = generated$2.assertTSTypePredicate; var generated_207$2 = generated$2.assertTSTypeQuery; var generated_208$2 = generated$2.assertTSTypeLiteral; var generated_209$2 = generated$2.assertTSArrayType; var generated_210$2 = generated$2.assertTSTupleType; var generated_211$2 = generated$2.assertTSOptionalType; var generated_212$2 = generated$2.assertTSRestType; var generated_213$2 = generated$2.assertTSNamedTupleMember; var generated_214$2 = generated$2.assertTSUnionType; var generated_215$2 = generated$2.assertTSIntersectionType; var generated_216$2 = generated$2.assertTSConditionalType; var generated_217$2 = generated$2.assertTSInferType; var generated_218$2 = generated$2.assertTSParenthesizedType; var generated_219$2 = generated$2.assertTSTypeOperator; var generated_220$2 = generated$2.assertTSIndexedAccessType; var generated_221$2 = generated$2.assertTSMappedType; var generated_222$2 = generated$2.assertTSLiteralType; var generated_223$2 = generated$2.assertTSExpressionWithTypeArguments; var generated_224$2 = generated$2.assertTSInterfaceDeclaration; var generated_225$2 = generated$2.assertTSInterfaceBody; var generated_226$2 = generated$2.assertTSTypeAliasDeclaration; var generated_227$2 = generated$2.assertTSAsExpression; var generated_228$2 = generated$2.assertTSTypeAssertion; var generated_229$2 = generated$2.assertTSEnumDeclaration; var generated_230$2 = generated$2.assertTSEnumMember; var generated_231$2 = generated$2.assertTSModuleDeclaration; var generated_232$2 = generated$2.assertTSModuleBlock; var generated_233$2 = generated$2.assertTSImportType; var generated_234$2 = generated$2.assertTSImportEqualsDeclaration; var generated_235$2 = generated$2.assertTSExternalModuleReference; var generated_236$2 = generated$2.assertTSNonNullExpression; var generated_237$2 = generated$2.assertTSExportAssignment; var generated_238$2 = generated$2.assertTSNamespaceExportDeclaration; var generated_239$2 = generated$2.assertTSTypeAnnotation; var generated_240$2 = generated$2.assertTSTypeParameterInstantiation; var generated_241$2 = generated$2.assertTSTypeParameterDeclaration; var generated_242$2 = generated$2.assertTSTypeParameter; var generated_243$2 = generated$2.assertExpression; var generated_244$2 = generated$2.assertBinary; var generated_245$2 = generated$2.assertScopable; var generated_246$2 = generated$2.assertBlockParent; var generated_247$2 = generated$2.assertBlock; var generated_248$2 = generated$2.assertStatement; var generated_249$2 = generated$2.assertTerminatorless; var generated_250$2 = generated$2.assertCompletionStatement; var generated_251$2 = generated$2.assertConditional; var generated_252$2 = generated$2.assertLoop; var generated_253$2 = generated$2.assertWhile; var generated_254$2 = generated$2.assertExpressionWrapper; var generated_255$2 = generated$2.assertFor; var generated_256$2 = generated$2.assertForXStatement; var generated_257$2 = generated$2.assertFunction; var generated_258$2 = generated$2.assertFunctionParent; var generated_259$2 = generated$2.assertPureish; var generated_260$2 = generated$2.assertDeclaration; var generated_261$2 = generated$2.assertPatternLike; var generated_262$2 = generated$2.assertLVal; var generated_263$2 = generated$2.assertTSEntityName; var generated_264$2 = generated$2.assertLiteral; var generated_265$2 = generated$2.assertImmutable; var generated_266$2 = generated$2.assertUserWhitespacable; var generated_267$2 = generated$2.assertMethod; var generated_268$2 = generated$2.assertObjectMember; var generated_269$2 = generated$2.assertProperty; var generated_270$2 = generated$2.assertUnaryLike; var generated_271$2 = generated$2.assertPattern; var generated_272$2 = generated$2.assertClass; var generated_273$2 = generated$2.assertModuleDeclaration; var generated_274$2 = generated$2.assertExportDeclaration; var generated_275$2 = generated$2.assertModuleSpecifier; var generated_276$2 = generated$2.assertFlow; var generated_277$2 = generated$2.assertFlowType; var generated_278$2 = generated$2.assertFlowBaseAnnotation; var generated_279$2 = generated$2.assertFlowDeclaration; var generated_280$2 = generated$2.assertFlowPredicate; var generated_281$2 = generated$2.assertEnumBody; var generated_282$2 = generated$2.assertEnumMember; var generated_283$2 = generated$2.assertJSX; var generated_284$2 = generated$2.assertPrivate; var generated_285$2 = generated$2.assertTSTypeElement; var generated_286$2 = generated$2.assertTSType; var generated_287$2 = generated$2.assertTSBaseType; var generated_288$2 = generated$2.assertNumberLiteral; var generated_289$2 = generated$2.assertRegexLiteral; var generated_290$2 = generated$2.assertRestProperty; var generated_291$2 = generated$2.assertSpreadProperty; var createTypeAnnotationBasedOnTypeof_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = createTypeAnnotationBasedOnTypeof; function createTypeAnnotationBasedOnTypeof(type) { if (type === "string") { return (0, generated$1.stringTypeAnnotation)(); } else if (type === "number") { return (0, generated$1.numberTypeAnnotation)(); } else if (type === "undefined") { return (0, generated$1.voidTypeAnnotation)(); } else if (type === "boolean") { return (0, generated$1.booleanTypeAnnotation)(); } else if (type === "function") { return (0, generated$1.genericTypeAnnotation)((0, generated$1.identifier)("Function")); } else if (type === "object") { return (0, generated$1.genericTypeAnnotation)((0, generated$1.identifier)("Object")); } else if (type === "symbol") { return (0, generated$1.genericTypeAnnotation)((0, generated$1.identifier)("Symbol")); } else { throw new Error("Invalid typeof value"); } } }); unwrapExports(createTypeAnnotationBasedOnTypeof_1); var removeTypeDuplicates_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = removeTypeDuplicates; 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; } }); unwrapExports(removeTypeDuplicates_1); var createFlowUnionType_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = createFlowUnionType; var _removeTypeDuplicates = _interopRequireDefault(removeTypeDuplicates_1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function createFlowUnionType(types) { const flattened = (0, _removeTypeDuplicates.default)(types); if (flattened.length === 1) { return flattened[0]; } else { return (0, generated$1.unionTypeAnnotation)(flattened); } } }); unwrapExports(createFlowUnionType_1); var removeTypeDuplicates_1$1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = removeTypeDuplicates; 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.isTSAnyKeyword)(node.type)) { return [node]; } if ((0, generated.isTSBaseType)(node)) { bases[node.type] = node; continue; } if ((0, generated.isTSUnionType)(node)) { if (typeGroups.indexOf(node.types) < 0) { nodes = nodes.concat(node.types); typeGroups.push(node.types); } 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; } }); unwrapExports(removeTypeDuplicates_1$1); var createTSUnionType_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = createTSUnionType; var _removeTypeDuplicates = _interopRequireDefault(removeTypeDuplicates_1$1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function createTSUnionType(typeAnnotations) { const types = typeAnnotations.map(type => type.typeAnnotations); const flattened = (0, _removeTypeDuplicates.default)(types); if (flattened.length === 1) { return flattened[0]; } else { return (0, generated$1.tsUnionType)(flattened); } } }); unwrapExports(createTSUnionType_1); var cloneNode_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = cloneNode; const has = Function.call.bind(Object.prototype.hasOwnProperty); function cloneIfNode(obj, deep, withoutLoc) { if (obj && typeof obj.type === "string") { return cloneNode(obj, deep, withoutLoc); } return obj; } function cloneIfNodeOrArray(obj, deep, withoutLoc) { if (Array.isArray(obj)) { return obj.map(node => cloneIfNode(node, deep, withoutLoc)); } return cloneIfNode(obj, deep, withoutLoc); } function cloneNode(node, deep = true, withoutLoc = false) { 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, withoutLoc) : 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)) { if (deep) { newNode[field] = type === "File" && field === "comments" ? maybeCloneComments(node.comments, deep, withoutLoc) : cloneIfNodeOrArray(node[field], true, withoutLoc); } else { newNode[field] = node[field]; } } } } if (has(node, "loc")) { if (withoutLoc) { newNode.loc = null; } else { newNode.loc = node.loc; } } if (has(node, "leadingComments")) { newNode.leadingComments = maybeCloneComments(node.leadingComments, deep, withoutLoc); } if (has(node, "innerComments")) { newNode.innerComments = maybeCloneComments(node.innerComments, deep, withoutLoc); } if (has(node, "trailingComments")) { newNode.trailingComments = maybeCloneComments(node.trailingComments, deep, withoutLoc); } if (has(node, "extra")) { newNode.extra = Object.assign({}, node.extra); } return newNode; } function cloneCommentsWithoutLoc(comments) { return comments.map(({ type, value }) => ({ type, value, loc: null })); } function maybeCloneComments(comments, deep, withoutLoc) { return deep && withoutLoc ? cloneCommentsWithoutLoc(comments) : comments; } }); unwrapExports(cloneNode_1); var clone_1$1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = clone; var _cloneNode = _interopRequireDefault(cloneNode_1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function clone(node) { return (0, _cloneNode.default)(node, false); } }); unwrapExports(clone_1$1); var cloneDeep_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = cloneDeep; var _cloneNode = _interopRequireDefault(cloneNode_1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function cloneDeep(node) { return (0, _cloneNode.default)(node); } }); unwrapExports(cloneDeep_1); var cloneDeepWithoutLoc_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = cloneDeepWithoutLoc; var _cloneNode = _interopRequireDefault(cloneNode_1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function cloneDeepWithoutLoc(node) { return (0, _cloneNode.default)(node, true, true); } }); unwrapExports(cloneDeepWithoutLoc_1); var cloneWithoutLoc_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = cloneWithoutLoc; var _cloneNode = _interopRequireDefault(cloneNode_1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function cloneWithoutLoc(node) { return (0, _cloneNode.default)(node, false, true); } }); unwrapExports(cloneWithoutLoc_1); var addComments_1 = createCommonjsModule(function (module, exports) { 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; } }); unwrapExports(addComments_1); var addComment_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = addComment; var _addComments = _interopRequireDefault(addComments_1); 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 }]); } }); unwrapExports(addComment_1); var inherit_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = inherit; function inherit(key, child, parent) { if (child && parent) { child[key] = Array.from(new Set([].concat(child[key], parent[key]).filter(Boolean))); } } }); unwrapExports(inherit_1); var inheritInnerComments_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = inheritInnerComments; var _inherit = _interopRequireDefault(inherit_1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function inheritInnerComments(child, parent) { (0, _inherit.default)("innerComments", child, parent); } }); unwrapExports(inheritInnerComments_1); var inheritLeadingComments_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = inheritLeadingComments; var _inherit = _interopRequireDefault(inherit_1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function inheritLeadingComments(child, parent) { (0, _inherit.default)("leadingComments", child, parent); } }); unwrapExports(inheritLeadingComments_1); var inheritTrailingComments_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = inheritTrailingComments; var _inherit = _interopRequireDefault(inherit_1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function inheritTrailingComments(child, parent) { (0, _inherit.default)("trailingComments", child, parent); } }); unwrapExports(inheritTrailingComments_1); var inheritsComments_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = inheritsComments; var _inheritTrailingComments = _interopRequireDefault(inheritTrailingComments_1); var _inheritLeadingComments = _interopRequireDefault(inheritLeadingComments_1); var _inheritInnerComments = _interopRequireDefault(inheritInnerComments_1); 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; } }); unwrapExports(inheritsComments_1); var removeComments_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = removeComments; function removeComments(node) { constants.COMMENT_KEYS.forEach(key => { node[key] = null; }); return node; } }); unwrapExports(removeComments_1); var generated$3 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.TSBASETYPE_TYPES = exports.TSTYPE_TYPES = exports.TSTYPEELEMENT_TYPES = exports.PRIVATE_TYPES = exports.JSX_TYPES = exports.ENUMMEMBER_TYPES = exports.ENUMBODY_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; 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 ENUMBODY_TYPES = definitions.FLIPPED_ALIAS_KEYS["EnumBody"]; exports.ENUMBODY_TYPES = ENUMBODY_TYPES; const ENUMMEMBER_TYPES = definitions.FLIPPED_ALIAS_KEYS["EnumMember"]; exports.ENUMMEMBER_TYPES = ENUMMEMBER_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; const TSBASETYPE_TYPES = definitions.FLIPPED_ALIAS_KEYS["TSBaseType"]; exports.TSBASETYPE_TYPES = TSBASETYPE_TYPES; }); unwrapExports(generated$3); var generated_1$3 = generated$3.TSBASETYPE_TYPES; var generated_2$3 = generated$3.TSTYPE_TYPES; var generated_3$3 = generated$3.TSTYPEELEMENT_TYPES; var generated_4$3 = generated$3.PRIVATE_TYPES; var generated_5$3 = generated$3.JSX_TYPES; var generated_6$3 = generated$3.ENUMMEMBER_TYPES; var generated_7$3 = generated$3.ENUMBODY_TYPES; var generated_8$3 = generated$3.FLOWPREDICATE_TYPES; var generated_9$3 = generated$3.FLOWDECLARATION_TYPES; var generated_10$3 = generated$3.FLOWBASEANNOTATION_TYPES; var generated_11$3 = generated$3.FLOWTYPE_TYPES; var generated_12$3 = generated$3.FLOW_TYPES; var generated_13$3 = generated$3.MODULESPECIFIER_TYPES; var generated_14$3 = generated$3.EXPORTDECLARATION_TYPES; var generated_15$3 = generated$3.MODULEDECLARATION_TYPES; var generated_16$3 = generated$3.CLASS_TYPES; var generated_17$3 = generated$3.PATTERN_TYPES; var generated_18$3 = generated$3.UNARYLIKE_TYPES; var generated_19$3 = generated$3.PROPERTY_TYPES; var generated_20$3 = generated$3.OBJECTMEMBER_TYPES; var generated_21$3 = generated$3.METHOD_TYPES; var generated_22$3 = generated$3.USERWHITESPACABLE_TYPES; var generated_23$3 = generated$3.IMMUTABLE_TYPES; var generated_24$3 = generated$3.LITERAL_TYPES; var generated_25$3 = generated$3.TSENTITYNAME_TYPES; var generated_26$3 = generated$3.LVAL_TYPES; var generated_27$3 = generated$3.PATTERNLIKE_TYPES; var generated_28$3 = generated$3.DECLARATION_TYPES; var generated_29$3 = generated$3.PUREISH_TYPES; var generated_30$3 = generated$3.FUNCTIONPARENT_TYPES; var generated_31$3 = generated$3.FUNCTION_TYPES; var generated_32$3 = generated$3.FORXSTATEMENT_TYPES; var generated_33$3 = generated$3.FOR_TYPES; var generated_34$3 = generated$3.EXPRESSIONWRAPPER_TYPES; var generated_35$3 = generated$3.WHILE_TYPES; var generated_36$3 = generated$3.LOOP_TYPES; var generated_37$3 = generated$3.CONDITIONAL_TYPES; var generated_38$3 = generated$3.COMPLETIONSTATEMENT_TYPES; var generated_39$3 = generated$3.TERMINATORLESS_TYPES; var generated_40$3 = generated$3.STATEMENT_TYPES; var generated_41$3 = generated$3.BLOCK_TYPES; var generated_42$3 = generated$3.BLOCKPARENT_TYPES; var generated_43$3 = generated$3.SCOPABLE_TYPES; var generated_44$3 = generated$3.BINARY_TYPES; var generated_45$3 = generated$3.EXPRESSION_TYPES; var toBlock_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = toBlock; 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, generated$1.returnStatement)(node); } else { node = (0, generated$1.expressionStatement)(node); } } blockNodes = [node]; } return (0, generated$1.blockStatement)(blockNodes); } }); unwrapExports(toBlock_1); var ensureBlock_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = ensureBlock; var _toBlock = _interopRequireDefault(toBlock_1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function ensureBlock(node, key = "body") { return node[key] = (0, _toBlock.default)(node[key], node); } }); unwrapExports(ensureBlock_1); var toIdentifier_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = toIdentifier; var _isValidIdentifier = _interopRequireDefault(isValidIdentifier_1); 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 || "_"; } }); unwrapExports(toIdentifier_1); var toBindingIdentifierName_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = toBindingIdentifierName; var _toIdentifier = _interopRequireDefault(toIdentifier_1); 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; } }); unwrapExports(toBindingIdentifierName_1); var toComputedKey_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = toComputedKey; function toComputedKey(node, key = node.key || node.property) { if (!node.computed && (0, generated.isIdentifier)(key)) key = (0, generated$1.stringLiteral)(key.name); return key; } }); unwrapExports(toComputedKey_1); var toExpression_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = toExpression; 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; } }); unwrapExports(toExpression_1); var traverseFast_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = traverseFast; 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); } } } }); unwrapExports(traverseFast_1); var removeProperties_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = removeProperties; 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; } } }); unwrapExports(removeProperties_1); var removePropertiesDeep_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = removePropertiesDeep; var _traverseFast = _interopRequireDefault(traverseFast_1); var _removeProperties = _interopRequireDefault(removeProperties_1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function removePropertiesDeep(tree, opts) { (0, _traverseFast.default)(tree, _removeProperties.default, opts); return tree; } }); unwrapExports(removePropertiesDeep_1); var toKeyAlias_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = toKeyAlias; var _cloneNode = _interopRequireDefault(cloneNode_1); var _removePropertiesDeep = _interopRequireDefault(removePropertiesDeep_1); 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++; } }; }); unwrapExports(toKeyAlias_1); var getBindingIdentifiers_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = getBindingIdentifiers; 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"] }; }); unwrapExports(getBindingIdentifiers_1); var gatherSequenceExpressions_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = gatherSequenceExpressions; var _getBindingIdentifiers = _interopRequireDefault(getBindingIdentifiers_1); var _cloneNode = _interopRequireDefault(cloneNode_1); 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) { if (!(0, generated.isEmptyStatement)(node)) { 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, generated$1.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, generated$1.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)) { if (nodes.indexOf(node) === 0) { ensureLastUndefined = true; } } else { return; } } if (ensureLastUndefined) { exprs.push(scope.buildUndefinedNode()); } if (exprs.length === 1) { return exprs[0]; } else { return (0, generated$1.sequenceExpression)(exprs); } } }); unwrapExports(gatherSequenceExpressions_1); var toSequenceExpression_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = toSequenceExpression; var _gatherSequenceExpressions = _interopRequireDefault(gatherSequenceExpressions_1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function toSequenceExpression(nodes, scope) { if (!(nodes == null ? void 0 : 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; } }); unwrapExports(toSequenceExpression_1); var toStatement_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = toStatement; 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, generated$1.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; } }); unwrapExports(toStatement_1); /** `Object#toString` result references. */ var objectTag$3 = '[object Object]'; /** Used for built-in method references. */ var funcProto$2 = Function.prototype, objectProto$d = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString$2 = funcProto$2.toString; /** Used to check objects for own properties. */ var hasOwnProperty$a = objectProto$d.hasOwnProperty; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString$2.call(Object); /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike_1(value) || _baseGetTag(value) != objectTag$3) { return false; } var proto = _getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty$a.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString$2.call(Ctor) == objectCtorString; } var isPlainObject_1 = isPlainObject; /** `Object#toString` result references. */ var regexpTag$3 = '[object RegExp]'; /** * The base implementation of `_.isRegExp` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. */ function baseIsRegExp(value) { return isObjectLike_1(value) && _baseGetTag(value) == regexpTag$3; } var _baseIsRegExp = baseIsRegExp; /* Node.js helper references. */ var nodeIsRegExp = _nodeUtil && _nodeUtil.isRegExp; /** * Checks if `value` is classified as a `RegExp` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. * @example * * _.isRegExp(/abc/); * // => true * * _.isRegExp('/abc/'); * // => false */ var isRegExp = nodeIsRegExp ? _baseUnary(nodeIsRegExp) : _baseIsRegExp; var isRegExp_1 = isRegExp; var valueToNode_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = valueToNode; var _isPlainObject = _interopRequireDefault(isPlainObject_1); var _isRegExp = _interopRequireDefault(isRegExp_1); var _isValidIdentifier = _interopRequireDefault(isValidIdentifier_1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function valueToNode(value) { if (value === undefined) { return (0, generated$1.identifier)("undefined"); } if (value === true || value === false) { return (0, generated$1.booleanLiteral)(value); } if (value === null) { return (0, generated$1.nullLiteral)(); } if (typeof value === "string") { return (0, generated$1.stringLiteral)(value); } if (typeof value === "number") { let result; if (Number.isFinite(value)) { result = (0, generated$1.numericLiteral)(Math.abs(value)); } else { let numerator; if (Number.isNaN(value)) { numerator = (0, generated$1.numericLiteral)(0); } else { numerator = (0, generated$1.numericLiteral)(1); } result = (0, generated$1.binaryExpression)("/", numerator, (0, generated$1.numericLiteral)(0)); } if (value < 0 || Object.is(value, -0)) { result = (0, generated$1.unaryExpression)("-", result); } return result; } if ((0, _isRegExp.default)(value)) { const pattern = value.source; const flags = value.toString().match(/\/([a-z]+|)$/)[1]; return (0, generated$1.regExpLiteral)(pattern, flags); } if (Array.isArray(value)) { return (0, generated$1.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$1.identifier)(key); } else { nodeKey = (0, generated$1.stringLiteral)(key); } props.push((0, generated$1.objectProperty)(nodeKey, valueToNode(value[key]))); } return (0, generated$1.objectExpression)(props); } throw new Error("don't know how to turn this value into a node"); } }); unwrapExports(valueToNode_1); var appendToMemberExpression_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = appendToMemberExpression; function appendToMemberExpression(member, append, computed = false) { member.object = (0, generated$1.memberExpression)(member.object, member.property, member.computed); member.property = append; member.computed = !!computed; return member; } }); unwrapExports(appendToMemberExpression_1); var inherits_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = inherits; var _inheritsComments = _interopRequireDefault(inheritsComments_1); 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; } }); unwrapExports(inherits_1); var prependToMemberExpression_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = prependToMemberExpression; function prependToMemberExpression(member, prepend) { member.object = (0, generated$1.memberExpression)(prepend, member.object); return member; } }); unwrapExports(prependToMemberExpression_1); var getOuterBindingIdentifiers_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = getOuterBindingIdentifiers; var _getBindingIdentifiers = _interopRequireDefault(getBindingIdentifiers_1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function getOuterBindingIdentifiers(node, duplicates) { return (0, _getBindingIdentifiers.default)(node, duplicates, true); } }); unwrapExports(getOuterBindingIdentifiers_1); var traverse_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = traverse; 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); } }); unwrapExports(traverse_1); var isBinding_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isBinding; var _getBindingIdentifiers = _interopRequireDefault(getBindingIdentifiers_1); 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; } }); unwrapExports(isBinding_1); var isLet_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isLet; function isLet(node) { return (0, generated.isVariableDeclaration)(node) && (node.kind !== "var" || node[constants.BLOCK_SCOPED_SYMBOL]); } }); unwrapExports(isLet_1); var isBlockScoped_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isBlockScoped; var _isLet = _interopRequireDefault(isLet_1); 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); } }); unwrapExports(isBlockScoped_1); var isImmutable_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isImmutable; var _isType = _interopRequireDefault(isType_1); 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; } }); unwrapExports(isImmutable_1); var isNodesEquivalent_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isNodesEquivalent; 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 == null ? void 0 : 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; } }); unwrapExports(isNodesEquivalent_1); var isReferenced_1 = createCommonjsModule(function (module, exports) { 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 "ClassMethod": case "ClassPrivateMethod": case "ObjectMethod": if (parent.params.includes(node)) { return false; } case "ObjectProperty": case "ClassProperty": case "ClassPrivateProperty": 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; } }); unwrapExports(isReferenced_1); var isScope_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isScope; function isScope(node, parent) { if ((0, generated.isBlockStatement)(node) && ((0, generated.isFunction)(parent) || (0, generated.isCatchClause)(parent))) { return false; } if ((0, generated.isPattern)(node) && ((0, generated.isFunction)(parent) || (0, generated.isCatchClause)(parent))) { return true; } return (0, generated.isScopable)(node); } }); unwrapExports(isScope_1); var isSpecifierDefault_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isSpecifierDefault; function isSpecifierDefault(specifier) { return (0, generated.isImportDefaultSpecifier)(specifier) || (0, generated.isIdentifier)(specifier.imported || specifier.exported, { name: "default" }); } }); unwrapExports(isSpecifierDefault_1); var isValidES3Identifier_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isValidES3Identifier; var _isValidIdentifier = _interopRequireDefault(isValidIdentifier_1); 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); } }); unwrapExports(isValidES3Identifier_1); var isVar_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isVar; function isVar(node) { return (0, generated.isVariableDeclaration)(node, { kind: "var" }) && !node[constants.BLOCK_SCOPED_SYMBOL]; } }); unwrapExports(isVar_1); var lib$1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); var _exportNames = { react: true, assertNode: true, createTypeAnnotationBasedOnTypeof: true, createUnionTypeAnnotation: true, createFlowUnionType: true, createTSUnionType: true, cloneNode: true, clone: true, cloneDeep: true, cloneDeepWithoutLoc: 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 _createFlowUnionType.default; } }); Object.defineProperty(exports, "createFlowUnionType", { enumerable: true, get: function () { return _createFlowUnionType.default; } }); Object.defineProperty(exports, "createTSUnionType", { enumerable: true, get: function () { return _createTSUnionType.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, "cloneDeepWithoutLoc", { enumerable: true, get: function () { return _cloneDeepWithoutLoc.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(isReactComponent_1); var _isCompatTag = _interopRequireDefault(isCompatTag_1); var _buildChildren = _interopRequireDefault(buildChildren_1); var _assertNode = _interopRequireDefault(assertNode_1); Object.keys(generated$2).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; if (key in exports && exports[key] === generated$2[key]) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return generated$2[key]; } }); }); var _createTypeAnnotationBasedOnTypeof = _interopRequireDefault(createTypeAnnotationBasedOnTypeof_1); var _createFlowUnionType = _interopRequireDefault(createFlowUnionType_1); var _createTSUnionType = _interopRequireDefault(createTSUnionType_1); Object.keys(generated$1).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; if (key in exports && exports[key] === generated$1[key]) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return generated$1[key]; } }); }); var _cloneNode = _interopRequireDefault(cloneNode_1); var _clone = _interopRequireDefault(clone_1$1); var _cloneDeep = _interopRequireDefault(cloneDeep_1); var _cloneDeepWithoutLoc = _interopRequireDefault(cloneDeepWithoutLoc_1); var _cloneWithoutLoc = _interopRequireDefault(cloneWithoutLoc_1); var _addComment = _interopRequireDefault(addComment_1); var _addComments = _interopRequireDefault(addComments_1); var _inheritInnerComments = _interopRequireDefault(inheritInnerComments_1); var _inheritLeadingComments = _interopRequireDefault(inheritLeadingComments_1); var _inheritsComments = _interopRequireDefault(inheritsComments_1); var _inheritTrailingComments = _interopRequireDefault(inheritTrailingComments_1); var _removeComments = _interopRequireDefault(removeComments_1); Object.keys(generated$3).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; if (key in exports && exports[key] === generated$3[key]) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return generated$3[key]; } }); }); Object.keys(constants).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; if (key in exports && exports[key] === constants[key]) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return constants[key]; } }); }); var _ensureBlock = _interopRequireDefault(ensureBlock_1); var _toBindingIdentifierName = _interopRequireDefault(toBindingIdentifierName_1); var _toBlock = _interopRequireDefault(toBlock_1); var _toComputedKey = _interopRequireDefault(toComputedKey_1); var _toExpression = _interopRequireDefault(toExpression_1); var _toIdentifier = _interopRequireDefault(toIdentifier_1); var _toKeyAlias = _interopRequireDefault(toKeyAlias_1); var _toSequenceExpression = _interopRequireDefault(toSequenceExpression_1); var _toStatement = _interopRequireDefault(toStatement_1); var _valueToNode = _interopRequireDefault(valueToNode_1); Object.keys(definitions).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; if (key in exports && exports[key] === definitions[key]) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return definitions[key]; } }); }); var _appendToMemberExpression = _interopRequireDefault(appendToMemberExpression_1); var _inherits = _interopRequireDefault(inherits_1); var _prependToMemberExpression = _interopRequireDefault(prependToMemberExpression_1); var _removeProperties = _interopRequireDefault(removeProperties_1); var _removePropertiesDeep = _interopRequireDefault(removePropertiesDeep_1); var _removeTypeDuplicates = _interopRequireDefault(removeTypeDuplicates_1); var _getBindingIdentifiers = _interopRequireDefault(getBindingIdentifiers_1); var _getOuterBindingIdentifiers = _interopRequireDefault(getOuterBindingIdentifiers_1); var _traverse = _interopRequireDefault(traverse_1); var _traverseFast = _interopRequireDefault(traverseFast_1); var _shallowEqual = _interopRequireDefault(shallowEqual_1); var _is = _interopRequireDefault(is_1); var _isBinding = _interopRequireDefault(isBinding_1); var _isBlockScoped = _interopRequireDefault(isBlockScoped_1); var _isImmutable = _interopRequireDefault(isImmutable_1); var _isLet = _interopRequireDefault(isLet_1); var _isNode = _interopRequireDefault(isNode_1); var _isNodesEquivalent = _interopRequireDefault(isNodesEquivalent_1); var _isPlaceholderType = _interopRequireDefault(isPlaceholderType_1); var _isReferenced = _interopRequireDefault(isReferenced_1); var _isScope = _interopRequireDefault(isScope_1); var _isSpecifierDefault = _interopRequireDefault(isSpecifierDefault_1); var _isType = _interopRequireDefault(isType_1); var _isValidES3Identifier = _interopRequireDefault(isValidES3Identifier_1); var _isValidIdentifier = _interopRequireDefault(isValidIdentifier_1); var _isVar = _interopRequireDefault(isVar_1); var _matchesPattern = _interopRequireDefault(matchesPattern_1); var _validate = _interopRequireDefault(validate_1); var _buildMatchMemberExpression = _interopRequireDefault(buildMatchMemberExpression_1); Object.keys(generated).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; if (key in exports && exports[key] === generated[key]) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return generated[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; }); unwrapExports(lib$1); var lib_1 = lib$1.react; var virtualTypes = createCommonjsModule(function (module, exports) { 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; var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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", "Pattern"], 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; }); unwrapExports(virtualTypes); var virtualTypes_1 = virtualTypes.ForAwaitStatement; var virtualTypes_2 = virtualTypes.NumericLiteralTypeAnnotation; var virtualTypes_3 = virtualTypes.ExistentialTypeParam; var virtualTypes_4 = virtualTypes.SpreadProperty; var virtualTypes_5 = virtualTypes.RestProperty; var virtualTypes_6 = virtualTypes.Flow; var virtualTypes_7 = virtualTypes.Pure; var virtualTypes_8 = virtualTypes.Generated; var virtualTypes_9 = virtualTypes.User; var virtualTypes_10 = virtualTypes.Var; var virtualTypes_11 = virtualTypes.BlockScoped; var virtualTypes_12 = virtualTypes.Referenced; var virtualTypes_13 = virtualTypes.Scope; var virtualTypes_14 = virtualTypes.Expression; var virtualTypes_15 = virtualTypes.Statement; var virtualTypes_16 = virtualTypes.BindingIdentifier; var virtualTypes_17 = virtualTypes.ReferencedMemberExpression; var virtualTypes_18 = virtualTypes.ReferencedIdentifier; var browser$1 = true; /** * Helpers. */ var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var w = d * 7; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} [options] * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ var ms = function(val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { return parse(val); } else if (type === 'number' && isFinite(val)) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( 'val is not a non-empty string or a valid number. val=' + JSON.stringify(val) ); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str); if (str.length > 100) { return; } var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y; case 'weeks': case 'week': case 'w': return n * w; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; default: return undefined; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return Math.round(ms / d) + 'd'; } if (msAbs >= h) { return Math.round(ms / h) + 'h'; } if (msAbs >= m) { return Math.round(ms / m) + 'm'; } if (msAbs >= s) { return Math.round(ms / s) + 's'; } return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { var msAbs = Math.abs(ms); if (msAbs >= d) { return plural(ms, msAbs, d, 'day'); } if (msAbs >= h) { return plural(ms, msAbs, h, 'hour'); } if (msAbs >= m) { return plural(ms, msAbs, m, 'minute'); } if (msAbs >= s) { return plural(ms, msAbs, s, 'second'); } return ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, msAbs, n, name) { var isPlural = msAbs >= n * 1.5; return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); } /** * 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 = ms; createDebug.destroy = destroy; Object.keys(env).forEach(key => { createDebug[key] = env[key]; }); /** * 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; let enableOverride = null; 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 '%'; } 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.useColors = createDebug.useColors(); debug.color = createDebug.selectColor(namespace); debug.extend = extend; debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. Object.defineProperty(debug, 'enabled', { enumerable: true, configurable: false, get: () => enableOverride === null ? createDebug.enabled(namespace) : enableOverride, set: v => { enableOverride = v; } }); // Env-specific initialization logic for debug instances if (typeof createDebug.init === 'function') { createDebug.init(debug); } return debug; } 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 + '$')); } } } /** * 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; } /** * XXX DO NOT USE. This is a temporary stub function. * XXX It WILL be removed in the next major release. */ function destroy() { console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } createDebug.enable(createDebug.load()); return createDebug; } var common = setup; var browser$2 = createCommonjsModule(function (module, exports) { /* eslint-env browser */ /** * This is the web browser implementation of `debug()`. */ exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = localstorage(); exports.destroy = (() => { let warned = false; return () => { if (!warned) { warned = true; console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); } }; })(); /** * 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.debug()` when available. * No-op when `console.debug` is not a "function". * If `console.debug` is not available, falls back * to `console.log`. * * @api public */ exports.log = console.debug || console.log || (() => {}); /** * 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 = 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; } }; }); var browser_1 = browser$2.formatArgs; var browser_2 = browser$2.save; var browser_3 = browser$2.load; var browser_4 = browser$2.useColors; var browser_5 = browser$2.storage; var browser_6 = browser$2.destroy; var browser_7 = browser$2.colors; var browser_8 = browser$2.log; // MIT lisence // from https://github.com/substack/tty-browserify/blob/1ba769a6429d242f36226538835b4034bf6b7886/index.js function isatty() { return false; } function ReadStream() { throw new Error('tty.ReadStream is not implemented'); } function WriteStream() { throw new Error('tty.ReadStream is not implemented'); } var tty = { isatty: isatty, ReadStream: ReadStream, WriteStream: WriteStream }; var tty$1 = /*#__PURE__*/Object.freeze({ __proto__: null, isatty: isatty, ReadStream: ReadStream, WriteStream: WriteStream, 'default': tty }); var lookup = []; var revLookup = []; var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; var inited = false; function init () { inited = true; var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i]; revLookup[code.charCodeAt(i)] = i; } revLookup['-'.charCodeAt(0)] = 62; revLookup['_'.charCodeAt(0)] = 63; } function toByteArray (b64) { if (!inited) { init(); } var i, j, l, tmp, placeHolders, arr; var len = b64.length; if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; // base64 is 4/3 + up to two characters of the original data arr = new Arr(len * 3 / 4 - placeHolders); // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? len - 4 : len; var L = 0; for (i = 0, j = 0; i < l; i += 4, j += 3) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; arr[L++] = (tmp >> 16) & 0xFF; arr[L++] = (tmp >> 8) & 0xFF; arr[L++] = tmp & 0xFF; } if (placeHolders === 2) { tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); arr[L++] = tmp & 0xFF; } else if (placeHolders === 1) { tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); arr[L++] = (tmp >> 8) & 0xFF; arr[L++] = 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) + (uint8[i + 1] << 8) + (uint8[i + 2]); output.push(tripletToBase64(tmp)); } return output.join('') } function fromByteArray (uint8) { if (!inited) { init(); } var tmp; var len = uint8.length; var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes var output = ''; 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]; output += lookup[tmp >> 2]; output += lookup[(tmp << 4) & 0x3F]; output += '=='; } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); output += lookup[tmp >> 10]; output += lookup[(tmp >> 4) & 0x3F]; output += lookup[(tmp << 2) & 0x3F]; output += '='; } parts.push(output); return parts.join('') } function read (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) } function write (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; } var toString = {}.toString; var isArray$1 = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; var INSPECT_MAX_BYTES = 50; /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Use Object implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * Due to various browser bugs, sometimes the Object implementation will be used even * when the browser supports typed arrays. * * Note: * * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. * * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. * * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of * incorrect length in some situations. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined ? global$1.TYPED_ARRAY_SUPPORT : true; /* * Export kMaxLength after typed array support is determined. */ var _kMaxLength = kMaxLength(); function kMaxLength () { return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff } function createBuffer (that, length) { if (kMaxLength() < length) { throw new RangeError('Invalid typed array length') } if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = new Uint8Array(length); that.__proto__ = Buffer.prototype; } else { // Fallback: Return an object instance of the Buffer class if (that === null) { that = new Buffer(length); } that.length = length; } return that } /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods * and the `Uint8Array` methods. Square bracket notation works as expected -- it * returns a single octet. * * The `Uint8Array` prototype remains unmodified. */ function Buffer (arg, encodingOrOffset, length) { if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { return new Buffer(arg, encodingOrOffset, length) } // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new Error( 'If encoding is specified then the first argument must be a string' ) } return allocUnsafe(this, arg) } return from(this, arg, encodingOrOffset, length) } Buffer.poolSize = 8192; // not used by this implementation // TODO: Legacy, not needed anymore. Remove in next major version. Buffer._augment = function (arr) { arr.__proto__ = Buffer.prototype; return arr }; function from (that, value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number') } if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { return fromArrayBuffer(that, value, encodingOrOffset, length) } if (typeof value === 'string') { return fromString(that, value, encodingOrOffset) } return fromObject(that, value) } /** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) * Buffer.from(array) * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ Buffer.from = function (value, encodingOrOffset, length) { return from(null, value, encodingOrOffset, length) }; if (Buffer.TYPED_ARRAY_SUPPORT) { Buffer.prototype.__proto__ = Uint8Array.prototype; Buffer.__proto__ = Uint8Array; } function assertSize (size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be a number') } else if (size < 0) { throw new RangeError('"size" argument must not be negative') } } function alloc (that, size, fill, encoding) { assertSize(size); if (size <= 0) { return createBuffer(that, size) } if (fill !== undefined) { // Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpretted as a start offset. return typeof encoding === 'string' ? createBuffer(that, size).fill(fill, encoding) : createBuffer(that, size).fill(fill) } return createBuffer(that, size) } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function (size, fill, encoding) { return alloc(null, size, fill, encoding) }; function allocUnsafe (that, size) { assertSize(size); that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); if (!Buffer.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < size; ++i) { that[i] = 0; } } return that } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function (size) { return allocUnsafe(null, size) }; /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function (size) { return allocUnsafe(null, size) }; function fromString (that, string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8'; } if (!Buffer.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } var length = byteLength(string, encoding) | 0; that = createBuffer(that, length); var actual = that.write(string, encoding); if (actual !== length) { // Writing a hex string, for example, that contains invalid characters will // cause everything after the first invalid character to be ignored. (e.g. // 'abxxcd' will be treated as 'ab') that = that.slice(0, actual); } return that } function fromArrayLike (that, array) { var length = array.length < 0 ? 0 : checked(array.length) | 0; that = createBuffer(that, length); for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255; } return that } function fromArrayBuffer (that, array, byteOffset, length) { array.byteLength; // this throws if `array` is not a valid ArrayBuffer if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('\'offset\' is out of bounds') } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('\'length\' is out of bounds') } if (byteOffset === undefined && length === undefined) { array = new Uint8Array(array); } else if (length === undefined) { array = new Uint8Array(array, byteOffset); } else { array = new Uint8Array(array, byteOffset, length); } if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = array; that.__proto__ = Buffer.prototype; } else { // Fallback: Return an object instance of the Buffer class that = fromArrayLike(that, array); } return that } function fromObject (that, obj) { if (internalIsBuffer(obj)) { var len = checked(obj.length) | 0; that = createBuffer(that, len); if (that.length === 0) { return that } obj.copy(that, 0, 0, len); return that } if (obj) { if ((typeof ArrayBuffer !== 'undefined' && obj.buffer instanceof ArrayBuffer) || 'length' in obj) { if (typeof obj.length !== 'number' || isnan(obj.length)) { return createBuffer(that, 0) } return fromArrayLike(that, obj) } if (obj.type === 'Buffer' && isArray$1(obj.data)) { return fromArrayLike(that, obj.data) } } throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') } function checked (length) { // Note: cannot use `length < kMaxLength()` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= kMaxLength()) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength().toString(16) + ' bytes') } return length | 0 } function SlowBuffer (length) { if (+length != length) { // eslint-disable-line eqeqeq length = 0; } return Buffer.alloc(+length) } Buffer.isBuffer = isBuffer; function internalIsBuffer (b) { return !!(b != null && b._isBuffer) } Buffer.compare = function compare (a, b) { if (!internalIsBuffer(a) || !internalIsBuffer(b)) { throw new TypeError('Arguments must be Buffers') } if (a === b) return 0 var x = a.length; var y = b.length; for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i]; y = b[i]; break } } if (x < y) return -1 if (y < x) return 1 return 0 }; Buffer.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'latin1': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } }; Buffer.concat = function concat (list, length) { if (!isArray$1(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 (!internalIsBuffer(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 (internalIsBuffer(string)) { return string.length } if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { return string.byteLength } if (typeof string !== 'string') { string = '' + string; } var len = string.length; if (len === 0) return 0 // Use a for loop to avoid recursion var loweredCase = false; for (;;) { switch (encoding) { case 'ascii': case 'latin1': case 'binary': return len case 'utf8': case 'utf-8': case undefined: return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2 case 'hex': return len >>> 1 case 'base64': return base64ToBytes(string).length default: if (loweredCase) return utf8ToBytes(string).length // assume utf8 encoding = ('' + encoding).toLowerCase(); loweredCase = true; } } } Buffer.byteLength = byteLength; function slowToString (encoding, start, end) { var loweredCase = false; // No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if (start === undefined || start < 0) { start = 0; } // Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if (start > this.length) { return '' } if (end === undefined || end > this.length) { end = this.length; } if (end <= 0) { return '' } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. end >>>= 0; start >>>= 0; if (end <= start) { return '' } if (!encoding) encoding = 'utf8'; while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'latin1': case 'binary': return latin1Slice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase(); loweredCase = true; } } } // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. Buffer.prototype._isBuffer = true; function swap (b, n, m) { var i = b[n]; b[n] = b[m]; b[m] = i; } Buffer.prototype.swap16 = function swap16 () { var len = this.length; if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') } for (var i = 0; i < len; i += 2) { swap(this, i, i + 1); } return this }; Buffer.prototype.swap32 = function swap32 () { var len = this.length; if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') } for (var i = 0; i < len; i += 4) { swap(this, i, i + 3); swap(this, i + 1, i + 2); } return this }; Buffer.prototype.swap64 = function swap64 () { var len = this.length; if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') } for (var i = 0; i < len; i += 8) { swap(this, i, i + 7); swap(this, i + 1, i + 6); swap(this, i + 2, i + 5); swap(this, i + 3, i + 4); } return this }; Buffer.prototype.toString = function toString () { var length = this.length | 0; if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) }; Buffer.prototype.equals = function equals (b) { if (!internalIsBuffer(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 = INSPECT_MAX_BYTES; if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); if (this.length > max) str += ' ... '; } return '<Buffer ' + str + '>' }; Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (!internalIsBuffer(target)) { throw new TypeError('Argument must be a Buffer') } if (start === undefined) { start = 0; } if (end === undefined) { end = target ? target.length : 0; } if (thisStart === undefined) { thisStart = 0; } if (thisEnd === undefined) { thisEnd = this.length; } if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { throw new RangeError('out of range index') } if (thisStart >= thisEnd && start >= end) { return 0 } if (thisStart >= thisEnd) { return -1 } if (start >= end) { return 1 } start >>>= 0; end >>>= 0; thisStart >>>= 0; thisEnd >>>= 0; if (this === target) return 0 var x = thisEnd - thisStart; var y = end - start; var len = Math.min(x, y); var thisCopy = this.slice(thisStart, thisEnd); var targetCopy = target.slice(start, end); for (var i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i]; y = targetCopy[i]; break } } if (x < y) return -1 if (y < x) return 1 return 0 }; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { // Empty buffer means no match if (buffer.length === 0) return -1 // Normalize byteOffset if (typeof byteOffset === 'string') { encoding = byteOffset; byteOffset = 0; } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff; } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000; } byteOffset = +byteOffset; // Coerce to Number. if (isNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : (buffer.length - 1); } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset; if (byteOffset >= buffer.length) { if (dir) return -1 else byteOffset = buffer.length - 1; } else if (byteOffset < 0) { if (dir) byteOffset = 0; else return -1 } // Normalize val if (typeof val === 'string') { val = Buffer.from(val, encoding); } // Finally, search either indexOf (if dir is true) or lastIndexOf if (internalIsBuffer(val)) { // Special case: looking for empty string/buffer always fails if (val.length === 0) { return -1 } return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF; // Search for a byte value [0-255] if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) } } return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) } throw new TypeError('val must be string, number or Buffer') } function arrayIndexOf (arr, val, byteOffset, encoding, dir) { var indexSize = 1; var arrLength = arr.length; var valLength = val.length; if (encoding !== undefined) { encoding = String(encoding).toLowerCase(); if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { if (arr.length < 2 || val.length < 2) { return -1 } indexSize = 2; arrLength /= 2; valLength /= 2; byteOffset /= 2; } } function read (buf, i) { if (indexSize === 1) { return buf[i] } else { return buf.readUInt16BE(i * indexSize) } } var i; if (dir) { var foundIndex = -1; for (i = byteOffset; i < arrLength; i++) { if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i; if (i - foundIndex + 1 === valLength) return foundIndex * indexSize } else { if (foundIndex !== -1) i -= i - foundIndex; foundIndex = -1; } } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; for (i = byteOffset; i >= 0; i--) { var found = true; for (var j = 0; j < valLength; j++) { if (read(arr, i + j) !== read(val, j)) { found = false; break } } if (found) return i } } return -1 } Buffer.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 }; Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) }; Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) }; function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0; var remaining = buf.length - offset; if (!length) { length = remaining; } else { length = Number(length); if (length > remaining) { length = remaining; } } // must be an even number of digits var strLen = string.length; if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') if (length > strLen / 2) { length = strLen / 2; } for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16); if (isNaN(parsed)) return i buf[offset + i] = parsed; } return i } function utf8Write (buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } function latin1Write (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length) } function ucs2Write (buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } Buffer.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8'; length = this.length; offset = 0; // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset; length = this.length; offset = 0; // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset | 0; if (isFinite(length)) { length = length | 0; if (encoding === undefined) encoding = 'utf8'; } else { encoding = length; length = undefined; } // legacy write(string, encoding, offset, length) - remove in v0.13 } else { throw new Error( 'Buffer.write(string, encoding, offset[, length]) is no longer supported' ) } var remaining = this.length - offset; if (length === undefined || length > remaining) length = remaining; if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { throw new RangeError('Attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8'; var loweredCase = false; for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length) case 'ascii': return asciiWrite(this, string, offset, length) case 'latin1': case 'binary': return latin1Write(this, string, offset, length) case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = ('' + encoding).toLowerCase(); loweredCase = true; } } }; Buffer.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } }; function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return fromByteArray(buf) } else { return fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { end = Math.min(buf.length, end); var res = []; var i = start; while (i < end) { var firstByte = buf[i]; var codePoint = null; var bytesPerSequence = (firstByte > 0xEF) ? 4 : (firstByte > 0xDF) ? 3 : (firstByte > 0xBF) ? 2 : 1; if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint; switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte; } break case 2: secondByte = buf[i + 1]; if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); if (tempCodePoint > 0x7F) { codePoint = tempCodePoint; } } break case 3: secondByte = buf[i + 1]; thirdByte = buf[i + 2]; if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint; } } break case 4: secondByte = buf[i + 1]; thirdByte = buf[i + 2]; fourthByte = buf[i + 3]; if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint; } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD; bytesPerSequence = 1; } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000; res.push(codePoint >>> 10 & 0x3FF | 0xD800); codePoint = 0xDC00 | codePoint & 0x3FF; } res.push(codePoint); i += bytesPerSequence; } return decodeCodePointsArray(res) } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000; function decodeCodePointsArray (codePoints) { var len = codePoints.length; if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = ''; var i = 0; while (i < len) { res += String.fromCharCode.apply( String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) ); } return res } function asciiSlice (buf, start, end) { var ret = ''; end = Math.min(buf.length, end); for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7F); } return ret } function latin1Slice (buf, start, end) { var ret = ''; end = Math.min(buf.length, end); for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]); } return ret } function hexSlice (buf, start, end) { var len = buf.length; if (!start || start < 0) start = 0; if (!end || end < 0 || end > len) end = len; var out = ''; for (var i = start; i < end; ++i) { out += toHex(buf[i]); } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end); var res = ''; for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); } return res } Buffer.prototype.slice = function slice (start, end) { var len = this.length; start = ~~start; end = end === undefined ? len : ~~end; if (start < 0) { start += len; if (start < 0) start = 0; } else if (start > len) { start = len; } if (end < 0) { end += len; if (end < 0) end = 0; } else if (end > len) { end = len; } if (end < start) end = start; var newBuf; if (Buffer.TYPED_ARRAY_SUPPORT) { newBuf = this.subarray(start, end); newBuf.__proto__ = Buffer.prototype; } else { var sliceLen = end - start; newBuf = new Buffer(sliceLen, undefined); for (var i = 0; i < sliceLen; ++i) { newBuf[i] = this[i + start]; } } return newBuf }; /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); var val = this[offset]; var mul = 1; var i = 0; while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul; } return val }; Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) { checkOffset(offset, byteLength, this.length); } var val = this[offset + --byteLength]; var mul = 1; while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul; } return val }; Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); return this[offset] }; Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] | (this[offset + 1] << 8) }; Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return (this[offset] << 8) | this[offset + 1] }; Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) }; Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) }; Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); var val = this[offset]; var mul = 1; var i = 0; while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul; } mul *= 0x80; if (val >= mul) val -= Math.pow(2, 8 * byteLength); return val }; Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); var i = byteLength; var mul = 1; var val = this[offset + --i]; while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul; } mul *= 0x80; if (val >= mul) val -= Math.pow(2, 8 * byteLength); return val }; Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) }; Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset] | (this[offset + 1] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset + 1] | (this[offset] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) }; Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) }; Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, true, 23, 4) }; Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, false, 23, 4) }; Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, true, 52, 8) }; Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, false, 52, 8) }; function checkInt (buf, value, offset, ext, max, min) { if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') if (offset + ext > buf.length) throw new RangeError('Index out of range') } Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1; checkInt(this, value, offset, byteLength, maxBytes, 0); } var mul = 1; var i = 0; this[offset] = value & 0xFF; while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF; } return offset + byteLength }; Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1; checkInt(this, value, offset, byteLength, maxBytes, 0); } var i = byteLength - 1; var mul = 1; this[offset + i] = value & 0xFF; while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF; } return offset + byteLength }; Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); this[offset] = (value & 0xff); return offset + 1 }; function objectWriteUInt16 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffff + value + 1; for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> (littleEndian ? i : 1 - i) * 8; } } Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { objectWriteUInt16(this, value, offset, true); } return offset + 2 }; Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { objectWriteUInt16(this, value, offset, false); } return offset + 2 }; function objectWriteUInt32 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffffffff + value + 1; for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; } } Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24); this[offset + 2] = (value >>> 16); this[offset + 1] = (value >>> 8); this[offset] = (value & 0xff); } else { objectWriteUInt32(this, value, offset, true); } return offset + 4 }; Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); this[offset + 3] = (value & 0xff); } else { objectWriteUInt32(this, value, offset, false); } return offset + 4 }; Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1); checkInt(this, value, offset, byteLength, limit - 1, -limit); } var i = 0; var mul = 1; var sub = 0; this[offset] = value & 0xFF; while (++i < byteLength && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { sub = 1; } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; } return offset + byteLength }; Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1); checkInt(this, value, offset, byteLength, limit - 1, -limit); } var i = byteLength - 1; var mul = 1; var sub = 0; this[offset + i] = value & 0xFF; while (--i >= 0 && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { sub = 1; } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; } return offset + byteLength }; Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); if (value < 0) value = 0xff + value + 1; this[offset] = (value & 0xff); return offset + 1 }; Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { objectWriteUInt16(this, value, offset, true); } return offset + 2 }; Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { objectWriteUInt16(this, value, offset, false); } return offset + 2 }; Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); this[offset + 2] = (value >>> 16); this[offset + 3] = (value >>> 24); } else { objectWriteUInt32(this, value, offset, true); } return offset + 4 }; Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); if (value < 0) value = 0xffffffff + value + 1; if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); this[offset + 3] = (value & 0xff); } else { objectWriteUInt32(this, value, offset, false); } return offset + 4 }; function checkIEEE754 (buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError('Index out of range') if (offset < 0) throw new RangeError('Index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 4); } write(buf, value, offset, littleEndian, 23, 4); return offset + 4 } Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) }; Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) }; function writeDouble (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 8); } write(buf, value, offset, littleEndian, 52, 8); return offset + 8 } Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) }; Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0; if (!end && end !== 0) end = this.length; if (targetStart >= target.length) targetStart = target.length; if (!targetStart) targetStart = 0; if (end > 0 && end < start) end = start; // Copy 0 bytes; we're done if (end === start) return 0 if (target.length === 0 || this.length === 0) return 0 // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds') } if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') if (end < 0) throw new RangeError('sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length; if (target.length - targetStart < end - start) { end = target.length - targetStart + start; } var len = end - start; var i; if (this === target && start < targetStart && targetStart < end) { // descending copy from end for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start]; } } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { // ascending copy from start for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start]; } } else { Uint8Array.prototype.set.call( target, this.subarray(start, start + len), targetStart ); } return len }; // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) Buffer.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { encoding = start; start = 0; end = this.length; } else if (typeof end === 'string') { encoding = end; end = this.length; } if (val.length === 1) { var code = val.charCodeAt(0); if (code < 256) { val = code; } } if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } } else if (typeof val === 'number') { val = val & 255; } // Invalid ranges are not set to a default, so can range check early. if (start < 0 || this.length < start || this.length < end) { throw new RangeError('Out of range index') } if (end <= start) { return this } start = start >>> 0; end = end === undefined ? this.length : end >>> 0; if (!val) val = 0; var i; if (typeof val === 'number') { for (i = start; i < end; ++i) { this[i] = val; } } else { var bytes = internalIsBuffer(val) ? val : utf8ToBytes(new Buffer(val, encoding).toString()); var len = bytes.length; for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len]; } } return this }; // HELPER FUNCTIONS // ================ var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; function base64clean (str) { // Node strips out invalid characters like \n and \t from the string, base64-js does not str = stringtrim(str).replace(INVALID_BASE64_RE, ''); // Node converts strings with length < 2 to '' if (str.length < 2) return '' // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '='; } return str } function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (string, units) { units = units || Infinity; var codePoint; var length = string.length; var leadSurrogate = null; var bytes = []; for (var i = 0; i < length; ++i) { codePoint = string.charCodeAt(i); // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); continue } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); continue } // valid lead leadSurrogate = codePoint; continue } // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); leadSurrogate = codePoint; continue } // valid surrogate pair codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); } leadSurrogate = null; // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break bytes.push(codePoint); } else if (codePoint < 0x800) { if ((units -= 2) < 0) break bytes.push( codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80 ); } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break bytes.push( codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ); } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break bytes.push( codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ); } else { throw new Error('Invalid code point') } } return bytes } function asciiToBytes (str) { var byteArray = []; for (var i = 0; i < str.length; ++i) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF); } return byteArray } function utf16leToBytes (str, units) { var c, hi, lo; var byteArray = []; for (var i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break c = str.charCodeAt(i); hi = c >> 8; lo = c % 256; byteArray.push(lo); byteArray.push(hi); } return byteArray } function base64ToBytes (str) { return toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; ++i) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i]; } return i } function isnan (val) { return val !== val // eslint-disable-line no-self-compare } // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence // The _isBuffer check is for Safari 5-7 support, because it's missing // Object.prototype.constructor. Remove this eventually function isBuffer(obj) { return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) } function isFastBuffer (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' && isFastBuffer(obj.slice(0, 0)) } var bufferEs6 = /*#__PURE__*/Object.freeze({ __proto__: null, INSPECT_MAX_BYTES: INSPECT_MAX_BYTES, kMaxLength: _kMaxLength, Buffer: Buffer, SlowBuffer: SlowBuffer, isBuffer: isBuffer }); var inherits; if (typeof Object.create === 'function'){ inherits = function inherits(ctor, superCtor) { // implementation from standard node.js 'util' module ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { inherits = function inherits(ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; }; } var inherits$1 = inherits; var formatRegExp = /%[sdj%]/g; function format(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$1(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. function deprecate(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(global$1.process)) { return function() { return 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; function debuglog(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 = 0; debugs[set] = function() { var msg = format.apply(null, 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 _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); } // 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$1(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== 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$1(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp$1(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$2(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction$1(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp$1(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$1(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$b(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$b(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 length = output.reduce(function(prev, cur) { if (cur.indexOf('\n') >= 0) ; 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$2(ar) { return Array.isArray(ar); } function isBoolean(arg) { return typeof arg === 'boolean'; } function isNull(arg) { return arg === null; } function isNullOrUndefined(arg) { return arg == null; } function isNumber(arg) { return typeof arg === 'number'; } function isString(arg) { return typeof arg === 'string'; } function isSymbol(arg) { return typeof arg === 'symbol'; } function isUndefined(arg) { return arg === void 0; } function isRegExp$1(re) { return isObject$1(re) && objectToString$1(re) === '[object RegExp]'; } function isObject$1(arg) { return typeof arg === 'object' && arg !== null; } function isDate(d) { return isObject$1(d) && objectToString$1(d) === '[object Date]'; } function isError(e) { return isObject$1(e) && (objectToString$1(e) === '[object Error]' || e instanceof Error); } function isFunction$1(arg) { return typeof arg === 'function'; } function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } function isBuffer$1(maybeBuf) { return isBuffer(maybeBuf); } function objectToString$1(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 function log() { console.log('%s - %s', timestamp(), format.apply(null, arguments)); } function _extend(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject$1(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; } function hasOwnProperty$b(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } var util = { inherits: inherits$1, _extend: _extend, log: log, isBuffer: isBuffer$1, isPrimitive: isPrimitive, isFunction: isFunction$1, isError: isError, isDate: isDate, isObject: isObject$1, isRegExp: isRegExp$1, isUndefined: isUndefined, isSymbol: isSymbol, isString: isString, isNumber: isNumber, isNullOrUndefined: isNullOrUndefined, isNull: isNull, isBoolean: isBoolean, isArray: isArray$2, inspect: inspect, deprecate: deprecate, format: format, debuglog: debuglog }; var util$1 = /*#__PURE__*/Object.freeze({ __proto__: null, format: format, deprecate: deprecate, debuglog: debuglog, inspect: inspect, isArray: isArray$2, isBoolean: isBoolean, isNull: isNull, isNullOrUndefined: isNullOrUndefined, isNumber: isNumber, isString: isString, isSymbol: isSymbol, isUndefined: isUndefined, isRegExp: isRegExp$1, isObject: isObject$1, isDate: isDate, isError: isError, isFunction: isFunction$1, isPrimitive: isPrimitive, isBuffer: isBuffer$1, log: log, inherits: inherits$1, _extend: _extend, 'default': util }); /* The MIT License (MIT) Copyright (c) 2016 CoderPuppy 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 _endianness; function endianness() { if (typeof _endianness === 'undefined') { var a = new ArrayBuffer(2); var b = new Uint8Array(a); var c = new Uint16Array(a); b[0] = 1; b[1] = 2; if (c[0] === 258) { _endianness = 'BE'; } else if (c[0] === 513){ _endianness = 'LE'; } else { throw new Error('unable to figure out endianess'); } } return _endianness; } function hostname() { if (typeof global$1.location !== 'undefined') { return global$1.location.hostname } else return ''; } function loadavg() { return []; } function uptime$1() { return 0; } function freemem() { return Number.MAX_VALUE; } function totalmem() { return Number.MAX_VALUE; } function cpus() { return []; } function type() { return 'Browser'; } function release$1 () { if (typeof global$1.navigator !== 'undefined') { return global$1.navigator.appVersion; } return ''; } function networkInterfaces(){} function getNetworkInterfaces(){} function arch() { return 'javascript'; } function platform$1() { return 'browser'; } function tmpDir() { return '/tmp'; } var tmpdir = tmpDir; var EOL = '\n'; var os = { EOL: EOL, tmpdir: tmpdir, tmpDir: tmpDir, networkInterfaces:networkInterfaces, getNetworkInterfaces: getNetworkInterfaces, release: release$1, type: type, cpus: cpus, totalmem: totalmem, freemem: freemem, uptime: uptime$1, loadavg: loadavg, hostname: hostname, endianness: endianness, }; var os$1 = /*#__PURE__*/Object.freeze({ __proto__: null, endianness: endianness, hostname: hostname, loadavg: loadavg, uptime: uptime$1, freemem: freemem, totalmem: totalmem, cpus: cpus, type: type, release: release$1, networkInterfaces: networkInterfaces, getNetworkInterfaces: getNetworkInterfaces, arch: arch, platform: platform$1, tmpDir: tmpDir, tmpdir: tmpdir, EOL: EOL, 'default': os }); var hasFlag = (flag, argv) => { argv = argv || process.argv; const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); const pos = argv.indexOf(prefix + flag); const terminatorPos = argv.indexOf('--'); return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); }; var os$2 = getCjsExportFromNamespace(os$1); const env$1 = process.env; let forceColor; if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { forceColor = false; } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) { forceColor = true; } if ('FORCE_COLOR' in env$1) { forceColor = env$1.FORCE_COLOR.length === 0 || parseInt(env$1.FORCE_COLOR, 10) !== 0; } function translateLevel(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; } function supportsColor(stream) { if (forceColor === false) { return 0; } if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { return 3; } if (hasFlag('color=256')) { return 2; } if (stream && !stream.isTTY && forceColor !== true) { return 0; } const min = forceColor ? 1 : 0; if (process.platform === 'win32') { // Node.js 7.5.0 is the first version of Node.js to include a patch to // libuv that enables 256 color output on Windows. Anything earlier and it // won't work. However, here we target Node.js 8 at minimum as it is an LTS // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows // release that supports 256 colors. Windows 10 build 14931 is the first release // that supports 16m/TrueColor. const osRelease = os$2.release().split('.'); if ( Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586 ) { return Number(osRelease[2]) >= 14931 ? 3 : 2; } return 1; } if ('CI' in env$1) { if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$1) || env$1.CI_NAME === 'codeship') { return 1; } return min; } if ('TEAMCITY_VERSION' in env$1) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0; } if (env$1.COLORTERM === 'truecolor') { return 3; } if ('TERM_PROGRAM' in env$1) { const version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10); switch (env$1.TERM_PROGRAM) { case 'iTerm.app': return version >= 3 ? 3 : 2; case 'Apple_Terminal': return 2; // No default } } if (/-256(color)?$/i.test(env$1.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) { return 1; } if ('COLORTERM' in env$1) { return 1; } if (env$1.TERM === 'dumb') { return min; } return min; } function getSupportLevel(stream) { const level = supportsColor(stream); return translateLevel(level); } var supportsColor_1 = { supportsColor: getSupportLevel, stdout: getSupportLevel(process.stdout), stderr: getSupportLevel(process.stderr) }; var tty$2 = getCjsExportFromNamespace(tty$1); var util$2 = getCjsExportFromNamespace(util$1); var node = createCommonjsModule(function (module, exports) { /** * Module dependencies. */ /** * This is the Node.js implementation of `debug()`. */ exports.init = init; exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.destroy = util$2.deprecate( () => {}, 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' ); /** * Colors. */ exports.colors = [6, 2, 3, 4, 5, 1]; try { // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) // eslint-disable-next-line import/no-extraneous-dependencies const supportsColor = supportsColor_1; if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { exports.colors = [ 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 214, 215, 220, 221 ]; } } catch (error) { // Swallow - we only care if `supports-color` is available; it doesn't have to be. } /** * Build up the default `inspectOpts` object from the environment variables. * * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ exports.inspectOpts = Object.keys(process.env).filter(key => { return /^debug_/i.test(key); }).reduce((obj, key) => { // Camel-case const prop = key .substring(6) .toLowerCase() .replace(/_([a-z])/g, (_, k) => { return k.toUpperCase(); }); // Coerce string value into JS value let val = process.env[key]; if (/^(yes|on|true|enabled)$/i.test(val)) { val = true; } else if (/^(no|off|false|disabled)$/i.test(val)) { val = false; } else if (val === 'null') { val = null; } else { val = Number(val); } obj[prop] = val; return obj; }, {}); /** * Is stdout a TTY? Colored output is enabled when `true`. */ function useColors() { return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty$2.isatty(process.stderr.fd); } /** * Adds ANSI color escape codes if enabled. * * @api public */ function formatArgs(args) { const {namespace: name, useColors} = this; if (useColors) { const c = this.color; const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); const prefix = ` ${colorCode};1m${name} \u001B[0m`; args[0] = prefix + args[0].split('\n').join('\n' + prefix); args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); } else { args[0] = getDate() + name + ' ' + args[0]; } } function getDate() { if (exports.inspectOpts.hideDate) { return ''; } return new Date().toISOString() + ' '; } /** * Invokes `util.format()` with the specified arguments and writes to stderr. */ function log(...args) { return process.stderr.write(util$2.format(...args) + '\n'); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { if (namespaces) { process.env.DEBUG = namespaces; } else { // If you set a process.env field to null or undefined, it gets cast to the // string 'null' or 'undefined'. Just delete instead. delete process.env.DEBUG; } } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { return process.env.DEBUG; } /** * Init logic for `debug` instances. * * Create a new `inspectOpts` object in case `useColors` is set * differently for a particular `debug` instance. */ function init(debug) { debug.inspectOpts = {}; const keys = Object.keys(exports.inspectOpts); for (let i = 0; i < keys.length; i++) { debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; } } module.exports = common(exports); const {formatters} = module.exports; /** * Map %o to `util.inspect()`, all on a single line. */ formatters.o = function (v) { this.inspectOpts.colors = this.useColors; return util$2.inspect(v, this.inspectOpts) .split('\n') .map(str => str.trim()) .join(' '); }; /** * Map %O to `util.inspect()`, allowing multiple lines if needed. */ formatters.O = function (v) { this.inspectOpts.colors = this.useColors; return util$2.inspect(v, this.inspectOpts); }; }); var node_1 = node.init; var node_2 = node.log; var node_3 = node.formatArgs; var node_4 = node.save; var node_5 = node.load; var node_6 = node.useColors; var node_7 = node.destroy; var node_8 = node.colors; var node_9 = node.inspectOpts; var src = createCommonjsModule(function (module) { /** * Detect Electron renderer / nwjs process, which is node, but we should * treat as a browser. */ if (typeof process === 'undefined' || process.type === 'renderer' || browser$1 === true || process.__nwjs) { module.exports = browser$2; } else { module.exports = node; } }); var binding$1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; class Binding { constructor({ identifier, scope, path, kind }) { this.constantViolations = []; this.constant = true; this.referencePaths = []; this.referenced = false; this.references = 0; this.identifier = identifier; this.scope = scope; this.path = path; this.kind = kind; 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; }); unwrapExports(binding$1); var lib$2 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = splitExportDeclaration; var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function splitExportDeclaration(exportDeclaration) { if (!exportDeclaration.isExportDeclaration()) { throw new Error("Only export declarations can be split."); } 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; } }); unwrapExports(lib$2); var renamer = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _binding = _interopRequireDefault(binding$1); var _helperSplitExportDeclaration = _interopRequireDefault(lib$2); var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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|VariableDeclarator"(path, state) { if (path.isVariableDeclaration()) return; 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; } maybeConvertFromClassFunctionExpression(path) { return; } 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; }); unwrapExports(renamer); var 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 }; var 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 }; var 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 }; var 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 }; var browser$3 = { 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 }; var 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 }; var node$1 = { __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 }; var commonjs = { exports: true, global: false, module: false, require: false }; var amd = { define: false, require: false }; var 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 }; var 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 }; var 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 }; var 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 }; var phantomjs = { console: true, exports: true, phantom: true, require: true, WebPage: true }; var couch = { emit: false, exports: false, getRow: false, log: false, module: false, provides: false, require: false, respond: false, send: false, start: false, sum: false }; var 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 }; var 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 }; var wsh = { ActiveXObject: true, Enumerator: true, GetObject: true, ScriptEngine: true, ScriptEngineBuildVersion: true, ScriptEngineMajorVersion: true, ScriptEngineMinorVersion: true, VBArray: true, WScript: true, WSH: true, XDomainRequest: true }; var jquery = { $: false, jQuery: false }; var yui = { YAHOO: false, YAHOO_config: false, YUI: false, YUI_config: false }; var 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 }; var 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 }; var 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 }; var 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 }; var applescript = { $: false, Application: false, Automation: false, console: false, delay: false, Library: false, ObjC: false, ObjectSpecifier: false, Path: false, Progress: false, Ref: false }; var 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 }; var atomtest = { advanceClock: false, fakeClearInterval: false, fakeClearTimeout: false, fakeSetInterval: false, fakeSetTimeout: false, resetTimeouts: false, waitsForPromise: false }; var 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 }; var protractor = { $: false, $$: false, browser: false, by: false, By: false, DartObject: false, element: false, protractor: false }; var webextensions = { browser: false, chrome: false, opr: false }; var 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 }; var 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 }; var globals = { builtin: builtin, es5: es5, es2015: es2015, es2017: es2017, browser: browser$3, worker: worker, node: node$1, commonjs: commonjs, amd: amd, mocha: mocha, jasmine: jasmine, jest: jest, qunit: qunit, phantomjs: phantomjs, couch: couch, rhino: rhino, nashorn: nashorn, wsh: wsh, jquery: jquery, yui: yui, shelljs: shelljs, prototypejs: prototypejs, meteor: meteor, mongo: mongo, applescript: applescript, serviceworker: serviceworker, atomtest: atomtest, embertest: embertest, protractor: protractor, "shared-node-browser": { clearInterval: false, clearTimeout: false, console: false, setInterval: false, setTimeout: false, URL: false, URLSearchParams: false }, webextensions: webextensions, greasemonkey: greasemonkey, devtools: devtools }; var globals$1 = /*#__PURE__*/Object.freeze({ __proto__: null, builtin: builtin, es5: es5, es2015: es2015, es2017: es2017, browser: browser$3, worker: worker, node: node$1, commonjs: commonjs, amd: amd, mocha: mocha, jasmine: jasmine, jest: jest, qunit: qunit, phantomjs: phantomjs, couch: couch, rhino: rhino, nashorn: nashorn, wsh: wsh, jquery: jquery, yui: yui, shelljs: shelljs, prototypejs: prototypejs, meteor: meteor, mongo: mongo, applescript: applescript, serviceworker: serviceworker, atomtest: atomtest, embertest: embertest, protractor: protractor, webextensions: webextensions, greasemonkey: greasemonkey, devtools: devtools, 'default': globals }); var require$$0 = getCjsExportFromNamespace(globals$1); var globals$2 = require$$0; var cache = createCommonjsModule(function (module, exports) { 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(); } }); unwrapExports(cache); var cache_1 = cache.clear; var cache_2 = cache.clearPath; var cache_3 = cache.clearScope; var cache_4 = cache.scope; var cache_5 = cache.path; var scope = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _renamer = _interopRequireDefault(renamer); var _index = _interopRequireDefault(lib$a); var _binding = _interopRequireDefault(binding$1); var _globals = _interopRequireDefault(globals$2); var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function gatherNodeParts(node, parts) { switch (node == null ? void 0 : node.type) { default: if (t.isModuleDeclaration(node)) { if (node.source) { gatherNodeParts(node.source, parts); } else if (node.specifiers && node.specifiers.length) { for (const e of node.specifiers) gatherNodeParts(e, parts); } else if (node.declaration) { gatherNodeParts(node.declaration, parts); } } else if (t.isModuleSpecifier(node)) { gatherNodeParts(node.local, parts); } else if (t.isLiteral(node)) { parts.push(node.value); } break; case "MemberExpression": case "OptionalMemberExpression": case "JSXMemberExpression": gatherNodeParts(node.object, parts); gatherNodeParts(node.property, parts); break; case "Identifier": case "JSXIdentifier": parts.push(node.name); break; case "CallExpression": case "OptionalCallExpression": case "NewExpression": gatherNodeParts(node.callee, parts); break; case "ObjectExpression": case "ObjectPattern": for (const e of node.properties) { gatherNodeParts(e, parts); } break; case "SpreadElement": case "RestElement": gatherNodeParts(node.argument, parts); break; case "ObjectProperty": case "ObjectMethod": case "ClassProperty": case "ClassMethod": case "ClassPrivateProperty": case "ClassPrivateMethod": gatherNodeParts(node.key, parts); break; case "ThisExpression": parts.push("this"); break; case "Super": parts.push("super"); break; case "Import": parts.push("import"); break; case "DoExpression": parts.push("do"); break; case "YieldExpression": parts.push("yield"); gatherNodeParts(node.argument, parts); break; case "AwaitExpression": parts.push("await"); gatherNodeParts(node.argument, parts); break; case "AssignmentExpression": gatherNodeParts(node.left, parts); break; case "VariableDeclarator": gatherNodeParts(node.id, parts); break; case "FunctionExpression": case "FunctionDeclaration": case "ClassExpression": case "ClassDeclaration": gatherNodeParts(node.id, parts); break; case "PrivateName": gatherNodeParts(node.id, parts); break; case "ParenthesizedExpression": gatherNodeParts(node.expression, parts); break; case "UnaryExpression": case "UpdateExpression": gatherNodeParts(node.argument, parts); break; case "MetaProperty": gatherNodeParts(node.meta, parts); gatherNodeParts(node.property, parts); break; case "JSXElement": gatherNodeParts(node.openingElement, parts); break; case "JSXOpeningElement": parts.push(node.name); break; case "JSXFragment": gatherNodeParts(node.openingFragment, parts); break; case "JSXOpeningFragment": parts.push("Fragment"); break; case "JSXNamespacedName": gatherNodeParts(node.namespace, parts); gatherNodeParts(node.name, parts); break; } } 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; const parent = scope.getBlockParent(); parent.registerDeclaration(path); if (path.isClassDeclaration() && path.node.id) { const id = path.node.id; const name = id.name; path.scope.bindings[name] = path.scope.parent.getBinding(name); } }, Block(path) { const paths = path.get("body"); for (const bodyPath of paths) { if (bodyPath.isFunctionDeclaration()) { path.scope.getBlockParent().registerDeclaration(bodyPath); } } }, CatchClause(path) { path.scope.registerBinding("let", path); }, Function(path) { if (path.isFunctionExpression() && path.has("id") && !path.get("id").node[t.NOT_LOCAL_BINDING]) { path.scope.registerBinding("local", path.get("id"), path); } const params = path.get("params"); for (const param of params) { path.scope.registerBinding("param", param); } }, ClassExpression(path) { if (path.has("id") && !path.get("id").node[t.NOT_LOCAL_BINDING]) { path.scope.registerBinding("local", path); } } }; let uid = 0; class Scope { constructor(path) { const { node } = path; const cached = cache.scope.get(node); if ((cached == null ? void 0 : cached.path) === path) { return cached; } cache.scope.set(node, this); this.uid = uid++; this.block = node; this.path = path; this.labels = new Map(); this.inited = false; } get parent() { const parent = this.path.findParent(p => p.isScope()); return parent == null ? void 0 : 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 = 1; 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(node, defaultName) { const parts = []; gatherNodeParts(node, parts); let id = parts.join("$"); id = id.replace(/^_/, "") || defaultName || "ref"; return this.generateUid(id.slice(0, 20)); } generateUidIdentifierBasedOnNode(node, defaultName) { return t.identifier(this.generateUidBasedOnNode(node, 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 = "-".repeat(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, allowArrayLike) { if (t.isIdentifier(node)) { const binding = this.getBinding(node.name); if ((binding == null ? void 0 : 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"; } if (allowArrayLike) { args.unshift(this.hub.addHelper(helperName)); helperName = "maybeArrayLike"; } 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() { return t.unaryExpression("void", t.numericLiteral(0), true); } 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)) { parent.references[name] = true; for (const id of ids[name]) { const local = this.getOwnBinding(name); if (local) { if (local.identifier === id) continue; this.checkBlockScopedCollisions(local, kind, name, id); } 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) { return !!this.getProgramParent().references[name]; } 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.isMethod(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.inited) { this.inited = true; 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.isFunction()) { if (path.isFunctionExpression() && path.has("id") && !path.get("id").node[t.NOT_LOCAL_BINDING]) { this.registerBinding("local", path.get("id"), path); } const params = path.get("params"); for (const param of params) { this.registerBinding("param", param); } } const programParent = this.getProgramParent(); if (programParent.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(); for (const name of Object.keys(ids)) { if (path.scope.getBinding(name)) continue; 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 { programParent.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 { for (const key of Object.keys(scope.bindings)) { if (key in ids === false) { ids[key] = scope.bindings[key]; } } 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; let previousPath; do { const binding = scope.getOwnBinding(name); if (binding) { var _previousPath; if (((_previousPath = previousPath) == null ? void 0 : _previousPath.isPattern()) && binding.kind !== "param") ; else { return binding; } } previousPath = scope.path; } while (scope = scope.parent); } getOwnBinding(name) { return this.bindings[name]; } getBindingIdentifier(name) { var _this$getBinding; return (_this$getBinding = this.getBinding(name)) == null ? void 0 : _this$getBinding.identifier; } getOwnBindingIdentifier(name) { const binding = this.bindings[name]; return binding == null ? void 0 : 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 && Scope.globals.includes(name)) return true; if (!noGlobals && Scope.contextVariables.includes(name)) return true; return false; } parentHasBinding(name, noGlobals) { var _this$parent; return (_this$parent = this.parent) == null ? void 0 : _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) { var _this$getBinding2; (_this$getBinding2 = this.getBinding(name)) == null ? void 0 : _this$getBinding2.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"]; }); unwrapExports(scope); /* -*- 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. */ var 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. */ var 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; }; var base64 = { encode: encode, decode: decode }; /* -*- 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. */ // 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. */ var encode$1 = 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. */ var decode$1 = 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; }; var base64Vlq = { encode: encode$1, decode: decode$1 }; var util$3 = createCommonjsModule(function (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; }); var util_1 = util$3.getArg; var util_2 = util$3.urlParse; var util_3 = util$3.urlGenerate; var util_4 = util$3.normalize; var util_5 = util$3.join; var util_6 = util$3.isAbsolute; var util_7 = util$3.relative; var util_8 = util$3.toSetString; var util_9 = util$3.fromSetString; var util_10 = util$3.compareByOriginalPositions; var util_11 = util$3.compareByGeneratedPositionsDeflated; var util_12 = util$3.compareByGeneratedPositionsInflated; /* -*- 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 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$3.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$3.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$3.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(); }; var ArraySet_1 = ArraySet; var arraySet = { ArraySet: ArraySet_1 }; /* -*- 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 */ /** * 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$3.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$3.compareByGeneratedPositionsInflated); this._sorted = true; } return this._array; }; var MappingList_1 = MappingList; var mappingList = { MappingList: MappingList_1 }; /* -*- 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 ArraySet$1 = arraySet.ArraySet; var MappingList$1 = mappingList.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$3.getArg(aArgs, 'file', null); this._sourceRoot = util$3.getArg(aArgs, 'sourceRoot', null); this._skipValidation = util$3.getArg(aArgs, 'skipValidation', false); this._sources = new ArraySet$1(); this._names = new ArraySet$1(); this._mappings = new MappingList$1(); 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$3.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$3.getArg(aArgs, 'generated'); var original = util$3.getArg(aArgs, 'original', null); var source = util$3.getArg(aArgs, 'source', null); var name = util$3.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$3.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$3.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$3.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$3.relative(sourceRoot, sourceFile); } // Applying the SourceMap can add and remove items from the sources and // the names array. var newSources = new ArraySet$1(); var newNames = new ArraySet$1(); // 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$3.join(aSourceMapPath, mapping.source); } if (sourceRoot != null) { mapping.source = util$3.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$3.join(aSourceMapPath, sourceFile); } if (sourceRoot != null) { sourceFile = util$3.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$3.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$3.relative(aSourceRoot, source); } var key = util$3.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()); }; var SourceMapGenerator_1 = SourceMapGenerator; var sourceMapGenerator = { SourceMapGenerator: SourceMapGenerator_1 }; var binarySearch = createCommonjsModule(function (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; }; }); var binarySearch_1 = binarySearch.GREATEST_LOWER_BOUND; var binarySearch_2 = binarySearch.LEAST_UPPER_BOUND; var binarySearch_3 = binarySearch.search; /* -*- 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$1(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$1(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$1(ary, i, j); } } swap$1(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. */ var quickSort_1 = function (ary, comparator) { doQuickSort(ary, comparator, 0, ary.length - 1); }; var quickSort = { quickSort: quickSort_1 }; /* -*- 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 ArraySet$2 = arraySet.ArraySet; var quickSort$1 = quickSort.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$3.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$3.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$3.getArg(aArgs, 'source'), originalLine: line, originalColumn: util$3.getArg(aArgs, 'column', 0) }; if (this.sourceRoot != null) { needle.source = util$3.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$3.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$3.getArg(mapping, 'generatedLine', null), column: util$3.getArg(mapping, 'generatedColumn', null), lastColumn: util$3.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$3.getArg(mapping, 'generatedLine', null), column: util$3.getArg(mapping, 'generatedColumn', null), lastColumn: util$3.getArg(mapping, 'lastGeneratedColumn', null) }); mapping = this._originalMappings[++index]; } } } return mappings; }; var SourceMapConsumer_1 = 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$3.getArg(sourceMap, 'version'); var sources = util$3.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$3.getArg(sourceMap, 'names', []); var sourceRoot = util$3.getArg(sourceMap, 'sourceRoot', null); var sourcesContent = util$3.getArg(sourceMap, 'sourcesContent', null); var mappings = util$3.getArg(sourceMap, 'mappings'); var file = util$3.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$3.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$3.isAbsolute(sourceRoot) && util$3.isAbsolute(source) ? util$3.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$2.fromArray(names.map(String), true); this._sources = ArraySet$2.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$2.fromArray(aSourceMap._names.toArray(), true); var sources = smc._sources = ArraySet$2.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$1(smc.__originalMappings, util$3.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$3.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$1(generatedMappings, util$3.compareByGeneratedPositionsDeflated); this.__generatedMappings = generatedMappings; quickSort$1(originalMappings, util$3.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$3.getArg(aArgs, 'line'), generatedColumn: util$3.getArg(aArgs, 'column') }; var index = this._findMapping( needle, this._generatedMappings, "generatedLine", "generatedColumn", util$3.compareByGeneratedPositionsDeflated, util$3.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) ); if (index >= 0) { var mapping = this._generatedMappings[index]; if (mapping.generatedLine === needle.generatedLine) { var source = util$3.getArg(mapping, 'source', null); if (source !== null) { source = this._sources.at(source); if (this.sourceRoot != null) { source = util$3.join(this.sourceRoot, source); } } var name = util$3.getArg(mapping, 'name', null); if (name !== null) { name = this._names.at(name); } return { source: source, line: util$3.getArg(mapping, 'originalLine', null), column: util$3.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$3.relative(this.sourceRoot, aSource); } if (this._sources.has(aSource)) { return this.sourcesContent[this._sources.indexOf(aSource)]; } var url; if (this.sourceRoot != null && (url = util$3.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$3.getArg(aArgs, 'source'); if (this.sourceRoot != null) { source = util$3.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$3.getArg(aArgs, 'line'), originalColumn: util$3.getArg(aArgs, 'column') }; var index = this._findMapping( needle, this._originalMappings, "originalLine", "originalColumn", util$3.compareByOriginalPositions, util$3.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) ); if (index >= 0) { var mapping = this._originalMappings[index]; if (mapping.source === needle.source) { return { line: util$3.getArg(mapping, 'generatedLine', null), column: util$3.getArg(mapping, 'generatedColumn', null), lastColumn: util$3.getArg(mapping, 'lastGeneratedColumn', null) }; } } return { line: null, column: null, lastColumn: null }; }; var BasicSourceMapConsumer_1 = 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$3.getArg(sourceMap, 'version'); var sections = util$3.getArg(sourceMap, 'sections'); if (version != this._version) { throw new Error('Unsupported version: ' + version); } this._sources = new ArraySet$2(); this._names = new ArraySet$2(); 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$3.getArg(s, 'offset'); var offsetLine = util$3.getArg(offset, 'line'); var offsetColumn = util$3.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$3.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$3.getArg(aArgs, 'line'), generatedColumn: util$3.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$3.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$3.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$1(this.__generatedMappings, util$3.compareByGeneratedPositionsDeflated); quickSort$1(this.__originalMappings, util$3.compareByOriginalPositions); }; var IndexedSourceMapConsumer_1 = IndexedSourceMapConsumer; var sourceMapConsumer = { SourceMapConsumer: SourceMapConsumer_1, BasicSourceMapConsumer: BasicSourceMapConsumer_1, IndexedSourceMapConsumer: IndexedSourceMapConsumer_1 }; /* -*- 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$1 = sourceMapGenerator.SourceMapGenerator; // 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$3.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$3.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$3.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$3.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$1(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 }; }; var SourceNode_1 = SourceNode; var sourceNode = { SourceNode: SourceNode_1 }; /* * Copyright 2009-2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE.txt or: * http://opensource.org/licenses/BSD-3-Clause */ var SourceMapGenerator$2 = sourceMapGenerator.SourceMapGenerator; var SourceMapConsumer$1 = sourceMapConsumer.SourceMapConsumer; var SourceNode$1 = sourceNode.SourceNode; var sourceMap = { SourceMapGenerator: SourceMapGenerator$2, SourceMapConsumer: SourceMapConsumer$1, SourceNode: SourceNode$1 }; var sourceMap$1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _sourceMap = _interopRequireDefault(sourceMap); 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.replace(/\\/g, "/"), code); } else if (typeof code === "object") { Object.keys(code).forEach(sourceFileName => { map.setSourceContent(sourceFileName.replace(/\\/g, "/"), code[sourceFileName]); }); } this._rawMappings.forEach(mapping => map.addMapping(mapping), 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).replace(/\\/g, "/"), original: line == null ? undefined : { line: line, column: column } }); } } exports.default = SourceMap; }); unwrapExports(sourceMap$1); var buffer = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; 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: this._buf.join("").trimRight(), map: null, rawMappings: map == null ? void 0 : 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) { this._buf.push(str); this._last = str[str.length - 1]; let i = str.indexOf("\n"); let last = 0; if (i !== 0) { this._mark(line, column, identifierName, filename, force); } while (i !== -1) { this._position.line++; this._position.column = 0; last = i + 1; if (last < str.length) { this._mark(++line, 0, identifierName, filename, force); } i = str.indexOf("\n", last); } this._position.column += str.length - last; } _mark(line, column, identifierName, filename, force) { var _this$_map; (_this$_map = this._map) == null ? void 0 : _this$_map.mark(this._position.line, this._position.column, line, column, identifierName, filename, force); } 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 == null ? void 0 : loc.identifierName) || null; targetObj.line = pos == null ? void 0 : pos.line; targetObj.column = pos == null ? void 0 : pos.column; targetObj.filename = loc == null ? void 0 : loc.filename; 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; }); unwrapExports(buffer); var whitespace = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.list = exports.nodes = void 0; var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function crawl(node, state = {}) { if (t.isMemberExpression(node) || t.isOptionalMemberExpression(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) || t.isOptionalCallExpression(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 }; } }, OptionalCallExpression(node) { if (t.isFunction(node.callee)) { 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) { var _parent$properties; if (parent.callProperties[0] === node && !((_parent$properties = parent.properties) == null ? void 0 : _parent$properties.length)) { return { before: true }; } }; nodes.ObjectTypeIndexer = function (node, parent) { var _parent$properties2, _parent$callPropertie; if (parent.indexers[0] === node && !((_parent$properties2 = parent.properties) == null ? void 0 : _parent$properties2.length) && !((_parent$callPropertie = parent.callProperties) == null ? void 0 : _parent$callPropertie.length)) { return { before: true }; } }; nodes.ObjectTypeInternalSlot = function (node, parent) { var _parent$properties3, _parent$callPropertie2, _parent$indexers; if (parent.internalSlots[0] === node && !((_parent$properties3 = parent.properties) == null ? void 0 : _parent$properties3.length) && !((_parent$callPropertie2 = parent.callProperties) == null ? void 0 : _parent$callPropertie2.length) && !((_parent$indexers = parent.indexers) == null ? void 0 : _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; }; }); }); }); unwrapExports(whitespace); var whitespace_1 = whitespace.list; var whitespace_2 = whitespace.nodes; var parentheses = createCommonjsModule(function (module, exports) { 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.TSInferType = TSInferType; 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.OptionalCallExpression = exports.OptionalMemberExpression = OptionalMemberExpression; exports.AssignmentExpression = AssignmentExpression; exports.LogicalExpression = LogicalExpression; var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } const PRECEDENCE = { "||": 0, "??": 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; const hasPostfixPart = (node, parent) => (t.isMemberExpression(parent) || t.isOptionalMemberExpression(parent)) && parent.object === node || (t.isCallExpression(parent) || t.isOptionalCallExpression(parent) || t.isNewExpression(parent)) && parent.callee === node || t.isTaggedTemplateExpression(parent) && parent.tag === node || t.isTSNonNullExpression(parent); function NullableTypeAnnotation(node, parent) { return t.isArrayTypeAnnotation(parent); } function FunctionTypeAnnotation(node, parent, printStack) { return t.isUnionTypeAnnotation(parent) || t.isIntersectionTypeAnnotation(parent) || t.isArrayTypeAnnotation(parent) || t.isTypeAnnotation(parent) && t.isArrowFunctionExpression(printStack[printStack.length - 3]); } function UpdateExpression(node, parent) { return hasPostfixPart(node, parent) || 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 (hasPostfixPart(node, parent) || t.isUnaryLike(parent) || 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; } } } 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 TSInferType(node, parent) { return t.isTSArrayType(parent) || t.isTSOptionalType(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) || hasPostfixPart(node, 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 hasPostfixPart(node, parent) || 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.isTSTypeAssertion(parent) || t.isTSAsExpression(parent)) { return true; } return UnaryLike(node, parent); } function OptionalMemberExpression(node, parent) { return t.isCallExpression(parent, { callee: node }) || t.isMemberExpression(parent, { object: node }); } function AssignmentExpression(node, parent, printStack) { if (t.isObjectPattern(node.left)) { return true; } else { return ConditionalExpression(node, parent); } } function LogicalExpression(node, parent) { switch (node.operator) { case "||": if (!t.isLogicalExpression(parent)) return false; return parent.operator === "??" || parent.operator === "&&"; case "&&": return t.isLogicalExpression(parent, { operator: "??" }); case "??": return t.isLogicalExpression(parent) && parent.operator !== "??"; } } 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 }) || considerDefaultExports && t.isExportDefaultDeclaration(parent, { declaration: node }) || considerArrow && t.isArrowFunctionExpression(parent, { body: node })) { return true; } if (hasPostfixPart(node, parent) && !t.isNewExpression(parent) || t.isSequenceExpression(parent) && parent.expressions[0] === 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; } }); unwrapExports(parentheses); var parentheses_1 = parentheses.NullableTypeAnnotation; var parentheses_2 = parentheses.FunctionTypeAnnotation; var parentheses_3 = parentheses.UpdateExpression; var parentheses_4 = parentheses.ObjectExpression; var parentheses_5 = parentheses.DoExpression; var parentheses_6 = parentheses.Binary; var parentheses_7 = parentheses.IntersectionTypeAnnotation; var parentheses_8 = parentheses.UnionTypeAnnotation; var parentheses_9 = parentheses.TSAsExpression; var parentheses_10 = parentheses.TSTypeAssertion; var parentheses_11 = parentheses.TSIntersectionType; var parentheses_12 = parentheses.TSUnionType; var parentheses_13 = parentheses.TSInferType; var parentheses_14 = parentheses.BinaryExpression; var parentheses_15 = parentheses.SequenceExpression; var parentheses_16 = parentheses.AwaitExpression; var parentheses_17 = parentheses.YieldExpression; var parentheses_18 = parentheses.ClassExpression; var parentheses_19 = parentheses.UnaryLike; var parentheses_20 = parentheses.FunctionExpression; var parentheses_21 = parentheses.ArrowFunctionExpression; var parentheses_22 = parentheses.ConditionalExpression; var parentheses_23 = parentheses.OptionalCallExpression; var parentheses_24 = parentheses.OptionalMemberExpression; var parentheses_25 = parentheses.AssignmentExpression; var parentheses_26 = parentheses.LogicalExpression; var node$2 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.needsWhitespace = needsWhitespace; exports.needsWhitespaceBefore = needsWhitespaceBefore; exports.needsWhitespaceAfter = needsWhitespaceAfter; exports.needsParens = needsParens; var whitespace$1 = _interopRequireWildcard(whitespace); var parens = _interopRequireWildcard(parentheses); var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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$1.nodes); const expandedWhitespaceList = expandAliases(whitespace$1.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; } return t.isMemberExpression(node) && isOrHasCallExpression(node.object); } 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); } }); unwrapExports(node$2); var node_1$1 = node$2.needsWhitespace; var node_2$1 = node$2.needsWhitespaceBefore; var node_3$1 = node$2.needsWhitespaceAfter; var node_4$1 = node$2.needsParens; var templateLiterals = createCommonjsModule(function (module, exports) { 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); } } } }); unwrapExports(templateLiterals); var templateLiterals_1 = templateLiterals.TaggedTemplateExpression; var templateLiterals_2 = templateLiterals.TemplateElement; var templateLiterals_3 = templateLiterals.TemplateLiteral; var expressions = createCommonjsModule(function (module, exports) { 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.V8IntrinsicIdentifier = V8IntrinsicIdentifier; exports.AwaitExpression = exports.YieldExpression = void 0; var t = _interopRequireWildcard(lib$1); var n = _interopRequireWildcard(node$2); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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); } function V8IntrinsicIdentifier(node) { this.token("%"); this.word(node.name); } }); unwrapExports(expressions); var expressions_1 = expressions.UnaryExpression; var expressions_2 = expressions.DoExpression; var expressions_3 = expressions.ParenthesizedExpression; var expressions_4 = expressions.UpdateExpression; var expressions_5 = expressions.ConditionalExpression; var expressions_6 = expressions.NewExpression; var expressions_7 = expressions.SequenceExpression; var expressions_8 = expressions.ThisExpression; var expressions_9 = expressions.Super; var expressions_10 = expressions.Decorator; var expressions_11 = expressions.OptionalMemberExpression; var expressions_12 = expressions.OptionalCallExpression; var expressions_13 = expressions.CallExpression; var expressions_14 = expressions.Import; var expressions_15 = expressions.EmptyStatement; var expressions_16 = expressions.ExpressionStatement; var expressions_17 = expressions.AssignmentPattern; var expressions_18 = expressions.LogicalExpression; var expressions_19 = expressions.BinaryExpression; var expressions_20 = expressions.AssignmentExpression; var expressions_21 = expressions.BindExpression; var expressions_22 = expressions.MemberExpression; var expressions_23 = expressions.MetaProperty; var expressions_24 = expressions.PrivateName; var expressions_25 = expressions.V8IntrinsicIdentifier; var expressions_26 = expressions.AwaitExpression; var expressions_27 = expressions.YieldExpression; var statements = createCommonjsModule(function (module, exports) { 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; var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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.print(node.param.typeAnnotation, 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); } } }); unwrapExports(statements); var statements_1 = statements.WithStatement; var statements_2 = statements.IfStatement; var statements_3 = statements.ForStatement; var statements_4 = statements.WhileStatement; var statements_5 = statements.DoWhileStatement; var statements_6 = statements.LabeledStatement; var statements_7 = statements.TryStatement; var statements_8 = statements.CatchClause; var statements_9 = statements.SwitchStatement; var statements_10 = statements.SwitchCase; var statements_11 = statements.DebuggerStatement; var statements_12 = statements.VariableDeclaration; var statements_13 = statements.VariableDeclarator; var statements_14 = statements.ThrowStatement; var statements_15 = statements.BreakStatement; var statements_16 = statements.ReturnStatement; var statements_17 = statements.ContinueStatement; var statements_18 = statements.ForOfStatement; var statements_19 = statements.ForInStatement; var classes = createCommonjsModule(function (module, exports) { 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; exports.StaticBlock = StaticBlock; var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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); this.tsPrintClassMemberModifiers(node, true); 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) { this.printJoin(node.decorators, 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); this.tsPrintClassMemberModifiers(node, false); this._methodHead(node); } function StaticBlock(node) { this.word("static"); this.space(); this.token("{"); if (node.body.length === 0) { this.token("}"); } else { this.newline(); this.printSequence(node.body, node, { indent: true }); this.rightBrace(); } } }); unwrapExports(classes); var classes_1 = classes.ClassExpression; var classes_2 = classes.ClassDeclaration; var classes_3 = classes.ClassBody; var classes_4 = classes.ClassProperty; var classes_5 = classes.ClassPrivateProperty; var classes_6 = classes.ClassMethod; var classes_7 = classes.ClassPrivateMethod; var classes_8 = classes._classMethodHead; var classes_9 = classes.StaticBlock; var methods = createCommonjsModule(function (module, exports) { 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; var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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._catchUp("start", key.loc); 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.async) && 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; } }); unwrapExports(methods); var methods_1 = methods._params; var methods_2 = methods._parameters; var methods_3 = methods._param; var methods_4 = methods._methodHead; var methods_5 = methods._predicate; var methods_6 = methods._functionHead; var methods_7 = methods.FunctionDeclaration; var methods_8 = methods.FunctionExpression; var methods_9 = methods.ArrowFunctionExpression; var modules = createCommonjsModule(function (module, exports) { 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.ImportAttribute = ImportAttribute; exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier; var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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.printAssertions(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; for (;;) { 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.printAssertions(node); } this.semicolon(); } } function ImportDeclaration(node) { var _node$attributes; 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 == null ? void 0 : specifiers.length) { for (;;) { 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.printAssertions(node); if ((_node$attributes = node.attributes) == null ? void 0 : _node$attributes.length) { this.space(); this.word("with"); this.space(); this.printList(node.attributes, node); } this.semicolon(); } function ImportAttribute(node) { this.print(node.key); this.token(":"); this.space(); this.print(node.value); } function ImportNamespaceSpecifier(node) { this.token("*"); this.space(); this.word("as"); this.space(); this.print(node.local, node); } }); unwrapExports(modules); var modules_1 = modules.ImportSpecifier; var modules_2 = modules.ImportDefaultSpecifier; var modules_3 = modules.ExportDefaultSpecifier; var modules_4 = modules.ExportSpecifier; var modules_5 = modules.ExportNamespaceSpecifier; var modules_6 = modules.ExportAllDeclaration; var modules_7 = modules.ExportNamedDeclaration; var modules_8 = modules.ExportDefaultDeclaration; var modules_9 = modules.ImportDeclaration; var modules_10 = modules.ImportAttribute; var modules_11 = modules.ImportNamespaceSpecifier; const object = {}; const hasOwnProperty$c = object.hasOwnProperty; const forOwn = (object, callback) => { for (const key in object) { if (hasOwnProperty$c.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$1 = object.toString; const isArray$3 = Array.isArray; const isBuffer$2 = isBuffer; const isObject$2 = (value) => { // This is a very simple check, but it’s good enough for what we need. return toString$1.call(value) == '[object Object]'; }; const isString$1 = (value) => { return typeof value == 'string' || toString$1.call(value) == '[object String]'; }; const isNumber$1 = (value) => { return typeof value == 'number' || toString$1.call(value) == '[object Number]'; }; const isFunction$2 = (value) => { return typeof value == 'function'; }; const isMap$1 = (value) => { return toString$1.call(value) == '[object Map]'; }; const isSet$1 = (value) => { return toString$1.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$2(argument.toJSON)) { argument = argument.toJSON(); } if (!isString$1(argument)) { if (isMap$1(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$1(argument)) { if (argument.size == 0) { return 'new Set()'; } return 'new Set(' + jsesc(Array.from(argument), options) + ')'; } if (isBuffer$2(argument)) { if (argument.length == 0) { return 'Buffer.from([])'; } return 'Buffer.from(' + jsesc(Array.from(argument), options) + ')'; } if (isArray$3(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$1(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$2(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(/<!--/g, json ? '\\u003C!--' : '\\x3C!--'); } return result; }; jsesc.version = '2.5.2'; var jsesc_1 = jsesc; var types = createCommonjsModule(function (module, exports) { 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.RecordExpression = RecordExpression; exports.TupleExpression = TupleExpression; exports.RegExpLiteral = RegExpLiteral; exports.BooleanLiteral = BooleanLiteral; exports.NullLiteral = NullLiteral; exports.NumericLiteral = NumericLiteral; exports.StringLiteral = StringLiteral; exports.BigIntLiteral = BigIntLiteral; exports.DecimalLiteral = DecimalLiteral; exports.PipelineTopicExpression = PipelineTopicExpression; exports.PipelineBareFunction = PipelineBareFunction; exports.PipelinePrimaryTopicReference = PipelinePrimaryTopicReference; var t = _interopRequireWildcard(lib$1); var _jsesc = _interopRequireDefault(jsesc_1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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 RecordExpression(node) { const props = node.properties; let startToken; let endToken; if (this.format.recordAndTupleSyntaxType === "bar") { startToken = "{|"; endToken = "|}"; } else if (this.format.recordAndTupleSyntaxType === "hash") { startToken = "#{"; endToken = "}"; } else { throw new Error(`The "recordAndTupleSyntaxType" generator option must be "bar" or "hash" (${JSON.stringify(this.format.recordAndTupleSyntaxType)} received).`); } this.token(startToken); this.printInnerComments(node); if (props.length) { this.space(); this.printList(props, node, { indent: true, statement: true }); this.space(); } this.token(endToken); } function TupleExpression(node) { const elems = node.elements; const len = elems.length; let startToken; let endToken; if (this.format.recordAndTupleSyntaxType === "bar") { startToken = "[|"; endToken = "|]"; } else if (this.format.recordAndTupleSyntaxType === "hash") { startToken = "#["; endToken = "]"; } else { throw new Error(`${this.format.recordAndTupleSyntaxType} is not a valid recordAndTuple syntax type`); } this.token(startToken); 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(","); } } this.token(endToken); } 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 opts = this.format.jsescOption; const value = node.value + ""; if (opts.numbers) { this.number((0, _jsesc.default)(node.value, opts)); } else 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 + "n"); } function DecimalLiteral(node) { const raw = this.getPossibleRaw(node); if (!this.format.minified && raw != null) { this.token(raw); return; } this.token(node.value + "m"); } function PipelineTopicExpression(node) { this.print(node.expression, node); } function PipelineBareFunction(node) { this.print(node.callee, node); } function PipelinePrimaryTopicReference() { this.token("#"); } }); unwrapExports(types); var types_1 = types.Identifier; var types_2 = types.ArgumentPlaceholder; var types_3 = types.SpreadElement; var types_4 = types.RestElement; var types_5 = types.ObjectPattern; var types_6 = types.ObjectExpression; var types_7 = types.ObjectMethod; var types_8 = types.ObjectProperty; var types_9 = types.ArrayPattern; var types_10 = types.ArrayExpression; var types_11 = types.RecordExpression; var types_12 = types.TupleExpression; var types_13 = types.RegExpLiteral; var types_14 = types.BooleanLiteral; var types_15 = types.NullLiteral; var types_16 = types.NumericLiteral; var types_17 = types.StringLiteral; var types_18 = types.BigIntLiteral; var types_19 = types.DecimalLiteral; var types_20 = types.PipelineTopicExpression; var types_21 = types.PipelineBareFunction; var types_22 = types.PipelinePrimaryTopicReference; var flow$1 = createCommonjsModule(function (module, exports) { 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.EnumDeclaration = EnumDeclaration; exports.EnumBooleanBody = EnumBooleanBody; exports.EnumNumberBody = EnumNumberBody; exports.EnumStringBody = EnumStringBody; exports.EnumSymbolBody = EnumSymbolBody; exports.EnumDefaultedMember = EnumDefaultedMember; exports.EnumBooleanMember = EnumBooleanMember; exports.EnumNumberMember = EnumNumberMember; exports.EnumStringMember = EnumStringMember; 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.SymbolTypeAnnotation = SymbolTypeAnnotation; exports.UnionTypeAnnotation = UnionTypeAnnotation; exports.TypeCastExpression = TypeCastExpression; exports.Variance = Variance; exports.VoidTypeAnnotation = VoidTypeAnnotation; Object.defineProperty(exports, "NumberLiteralTypeAnnotation", { enumerable: true, get: function () { return types.NumericLiteral; } }); Object.defineProperty(exports, "StringLiteralTypeAnnotation", { enumerable: true, get: function () { return types.StringLiteral; } }); var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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 EnumDeclaration(node) { const { id, body } = node; this.word("enum"); this.space(); this.print(id, node); this.print(body, node); } function enumExplicitType(context, name, hasExplicitType) { if (hasExplicitType) { context.space(); context.word("of"); context.space(); context.word(name); } context.space(); } function enumBody(context, node) { const { members } = node; context.token("{"); context.indent(); context.newline(); for (const member of members) { context.print(member, node); context.newline(); } context.dedent(); context.token("}"); } function EnumBooleanBody(node) { const { explicitType } = node; enumExplicitType(this, "boolean", explicitType); enumBody(this, node); } function EnumNumberBody(node) { const { explicitType } = node; enumExplicitType(this, "number", explicitType); enumBody(this, node); } function EnumStringBody(node) { const { explicitType } = node; enumExplicitType(this, "string", explicitType); enumBody(this, node); } function EnumSymbolBody(node) { enumExplicitType(this, "symbol", true); enumBody(this, node); } function EnumDefaultedMember(node) { const { id } = node; this.print(id, node); this.token(","); } function enumInitializedMember(context, node) { const { id, init } = node; context.print(id, node); context.space(); context.token("="); context.space(); context.print(init, node); context.token(","); } function EnumBooleanMember(node) { enumInitializedMember(this, node); } function EnumNumberMember(node) { enumInitializedMember(this, node); } function EnumStringMember(node) { enumInitializedMember(this, node); } 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 || node.inexact) { this.token(","); this.space(); } } }); this.space(); } if (node.inexact) { this.indent(); this.token("..."); if (props.length) { this.newline(); } this.dedent(); } 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(); } if (node.kind === "get" || node.kind === "set") { this.word(node.kind); 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 SymbolTypeAnnotation() { this.word("symbol"); } 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"); } }); unwrapExports(flow$1); var flow_1 = flow$1.AnyTypeAnnotation; var flow_2 = flow$1.ArrayTypeAnnotation; var flow_3 = flow$1.BooleanTypeAnnotation; var flow_4 = flow$1.BooleanLiteralTypeAnnotation; var flow_5 = flow$1.NullLiteralTypeAnnotation; var flow_6 = flow$1.DeclareClass; var flow_7 = flow$1.DeclareFunction; var flow_8 = flow$1.InferredPredicate; var flow_9 = flow$1.DeclaredPredicate; var flow_10 = flow$1.DeclareInterface; var flow_11 = flow$1.DeclareModule; var flow_12 = flow$1.DeclareModuleExports; var flow_13 = flow$1.DeclareTypeAlias; var flow_14 = flow$1.DeclareOpaqueType; var flow_15 = flow$1.DeclareVariable; var flow_16 = flow$1.DeclareExportDeclaration; var flow_17 = flow$1.DeclareExportAllDeclaration; var flow_18 = flow$1.EnumDeclaration; var flow_19 = flow$1.EnumBooleanBody; var flow_20 = flow$1.EnumNumberBody; var flow_21 = flow$1.EnumStringBody; var flow_22 = flow$1.EnumSymbolBody; var flow_23 = flow$1.EnumDefaultedMember; var flow_24 = flow$1.EnumBooleanMember; var flow_25 = flow$1.EnumNumberMember; var flow_26 = flow$1.EnumStringMember; var flow_27 = flow$1.ExistsTypeAnnotation; var flow_28 = flow$1.FunctionTypeAnnotation; var flow_29 = flow$1.FunctionTypeParam; var flow_30 = flow$1.GenericTypeAnnotation; var flow_31 = flow$1.ClassImplements; var flow_32 = flow$1.InterfaceExtends; var flow_33 = flow$1._interfaceish; var flow_34 = flow$1._variance; var flow_35 = flow$1.InterfaceDeclaration; var flow_36 = flow$1.InterfaceTypeAnnotation; var flow_37 = flow$1.IntersectionTypeAnnotation; var flow_38 = flow$1.MixedTypeAnnotation; var flow_39 = flow$1.EmptyTypeAnnotation; var flow_40 = flow$1.NullableTypeAnnotation; var flow_41 = flow$1.NumberTypeAnnotation; var flow_42 = flow$1.StringTypeAnnotation; var flow_43 = flow$1.ThisTypeAnnotation; var flow_44 = flow$1.TupleTypeAnnotation; var flow_45 = flow$1.TypeofTypeAnnotation; var flow_46 = flow$1.TypeAlias; var flow_47 = flow$1.TypeAnnotation; var flow_48 = flow$1.TypeParameterDeclaration; var flow_49 = flow$1.TypeParameterInstantiation; var flow_50 = flow$1.TypeParameter; var flow_51 = flow$1.OpaqueType; var flow_52 = flow$1.ObjectTypeAnnotation; var flow_53 = flow$1.ObjectTypeInternalSlot; var flow_54 = flow$1.ObjectTypeCallProperty; var flow_55 = flow$1.ObjectTypeIndexer; var flow_56 = flow$1.ObjectTypeProperty; var flow_57 = flow$1.ObjectTypeSpreadProperty; var flow_58 = flow$1.QualifiedTypeIdentifier; var flow_59 = flow$1.SymbolTypeAnnotation; var flow_60 = flow$1.UnionTypeAnnotation; var flow_61 = flow$1.TypeCastExpression; var flow_62 = flow$1.Variance; var flow_63 = flow$1.VoidTypeAnnotation; var base = createCommonjsModule(function (module, exports) { 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) { var _node$directives; this.token("{"); this.printInnerComments(node); const hasDirectives = (_node$directives = node.directives) == null ? void 0 : _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(); } } }); unwrapExports(base); var base_1 = base.File; var base_2 = base.Program; var base_3 = base.BlockStatement; var base_4 = base.Noop; var base_5 = base.Directive; var base_6 = base.DirectiveLiteral; var base_7 = base.InterpreterDirective; var base_8 = base.Placeholder; var jsx$1 = createCommonjsModule(function (module, exports) { 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("</"); this.print(node.name, 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("</"); this.token(">"); } }); unwrapExports(jsx$1); var jsx_1 = jsx$1.JSXAttribute; var jsx_2 = jsx$1.JSXIdentifier; var jsx_3 = jsx$1.JSXNamespacedName; var jsx_4 = jsx$1.JSXMemberExpression; var jsx_5 = jsx$1.JSXSpreadAttribute; var jsx_6 = jsx$1.JSXExpressionContainer; var jsx_7 = jsx$1.JSXSpreadChild; var jsx_8 = jsx$1.JSXText; var jsx_9 = jsx$1.JSXElement; var jsx_10 = jsx$1.JSXOpeningElement; var jsx_11 = jsx$1.JSXClosingElement; var jsx_12 = jsx$1.JSXEmptyExpression; var jsx_13 = jsx$1.JSXFragment; var jsx_14 = jsx$1.JSXOpeningFragment; var jsx_15 = jsx$1.JSXClosingFragment; var typescript$1 = createCommonjsModule(function (module, exports) { 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.TSBigIntKeyword = TSBigIntKeyword; 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.TSIntrinsicKeyword = TSIntrinsicKeyword; 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.TSNamedTupleMember = TSNamedTupleMember; 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; exports.tsPrintClassMemberModifiers = tsPrintClassMemberModifiers; 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); this.token(";"); } function TSConstructSignatureDeclaration(node) { this.word("new"); this.space(); this.tsPrintSignatureDeclarationBase(node); this.token(";"); } 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 TSBigIntKeyword() { this.word("bigint"); } 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 TSIntrinsicKeyword() { this.word("intrinsic"); } 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) { if (node.asserts) { this.word("asserts"); this.space(); } this.print(node.parameterName); if (node.typeAnnotation) { 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 TSNamedTupleMember(node) { this.print(node.label, node); if (node.optional) this.token("?"); this.token(":"); this.space(); this.print(node.elementType, 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.word(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 { nameType, optional, readonly, typeParameter } = 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); if (nameType) { this.space(); this.word("as"); this.space(); this.print(nameType, node); } 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); } function tsPrintClassMemberModifiers(node, isField) { if (isField && node.declare) { this.word("declare"); this.space(); } 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 (isField && node.readonly) { this.word("readonly"); this.space(); } } }); unwrapExports(typescript$1); var typescript_1 = typescript$1.TSTypeAnnotation; var typescript_2 = typescript$1.TSTypeParameterDeclaration; var typescript_3 = typescript$1.TSTypeParameterInstantiation; var typescript_4 = typescript$1.TSTypeParameter; var typescript_5 = typescript$1.TSParameterProperty; var typescript_6 = typescript$1.TSDeclareFunction; var typescript_7 = typescript$1.TSDeclareMethod; var typescript_8 = typescript$1.TSQualifiedName; var typescript_9 = typescript$1.TSCallSignatureDeclaration; var typescript_10 = typescript$1.TSConstructSignatureDeclaration; var typescript_11 = typescript$1.TSPropertySignature; var typescript_12 = typescript$1.tsPrintPropertyOrMethodName; var typescript_13 = typescript$1.TSMethodSignature; var typescript_14 = typescript$1.TSIndexSignature; var typescript_15 = typescript$1.TSAnyKeyword; var typescript_16 = typescript$1.TSBigIntKeyword; var typescript_17 = typescript$1.TSUnknownKeyword; var typescript_18 = typescript$1.TSNumberKeyword; var typescript_19 = typescript$1.TSObjectKeyword; var typescript_20 = typescript$1.TSBooleanKeyword; var typescript_21 = typescript$1.TSStringKeyword; var typescript_22 = typescript$1.TSSymbolKeyword; var typescript_23 = typescript$1.TSVoidKeyword; var typescript_24 = typescript$1.TSUndefinedKeyword; var typescript_25 = typescript$1.TSNullKeyword; var typescript_26 = typescript$1.TSNeverKeyword; var typescript_27 = typescript$1.TSIntrinsicKeyword; var typescript_28 = typescript$1.TSThisType; var typescript_29 = typescript$1.TSFunctionType; var typescript_30 = typescript$1.TSConstructorType; var typescript_31 = typescript$1.tsPrintFunctionOrConstructorType; var typescript_32 = typescript$1.TSTypeReference; var typescript_33 = typescript$1.TSTypePredicate; var typescript_34 = typescript$1.TSTypeQuery; var typescript_35 = typescript$1.TSTypeLiteral; var typescript_36 = typescript$1.tsPrintTypeLiteralOrInterfaceBody; var typescript_37 = typescript$1.tsPrintBraced; var typescript_38 = typescript$1.TSArrayType; var typescript_39 = typescript$1.TSTupleType; var typescript_40 = typescript$1.TSOptionalType; var typescript_41 = typescript$1.TSRestType; var typescript_42 = typescript$1.TSNamedTupleMember; var typescript_43 = typescript$1.TSUnionType; var typescript_44 = typescript$1.TSIntersectionType; var typescript_45 = typescript$1.tsPrintUnionOrIntersectionType; var typescript_46 = typescript$1.TSConditionalType; var typescript_47 = typescript$1.TSInferType; var typescript_48 = typescript$1.TSParenthesizedType; var typescript_49 = typescript$1.TSTypeOperator; var typescript_50 = typescript$1.TSIndexedAccessType; var typescript_51 = typescript$1.TSMappedType; var typescript_52 = typescript$1.TSLiteralType; var typescript_53 = typescript$1.TSExpressionWithTypeArguments; var typescript_54 = typescript$1.TSInterfaceDeclaration; var typescript_55 = typescript$1.TSInterfaceBody; var typescript_56 = typescript$1.TSTypeAliasDeclaration; var typescript_57 = typescript$1.TSAsExpression; var typescript_58 = typescript$1.TSTypeAssertion; var typescript_59 = typescript$1.TSEnumDeclaration; var typescript_60 = typescript$1.TSEnumMember; var typescript_61 = typescript$1.TSModuleDeclaration; var typescript_62 = typescript$1.TSModuleBlock; var typescript_63 = typescript$1.TSImportType; var typescript_64 = typescript$1.TSImportEqualsDeclaration; var typescript_65 = typescript$1.TSExternalModuleReference; var typescript_66 = typescript$1.TSNonNullExpression; var typescript_67 = typescript$1.TSExportAssignment; var typescript_68 = typescript$1.TSNamespaceExportDeclaration; var typescript_69 = typescript$1.tsPrintSignatureDeclarationBase; var typescript_70 = typescript$1.tsPrintClassMemberModifiers; var generators = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); Object.keys(templateLiterals).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (key in exports && exports[key] === templateLiterals[key]) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return templateLiterals[key]; } }); }); Object.keys(expressions).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (key in exports && exports[key] === expressions[key]) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return expressions[key]; } }); }); Object.keys(statements).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (key in exports && exports[key] === statements[key]) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return statements[key]; } }); }); Object.keys(classes).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (key in exports && exports[key] === classes[key]) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return classes[key]; } }); }); Object.keys(methods).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (key in exports && exports[key] === methods[key]) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return methods[key]; } }); }); Object.keys(modules).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (key in exports && exports[key] === modules[key]) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return modules[key]; } }); }); Object.keys(types).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (key in exports && exports[key] === types[key]) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return types[key]; } }); }); Object.keys(flow$1).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (key in exports && exports[key] === flow$1[key]) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return flow$1[key]; } }); }); Object.keys(base).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (key in exports && exports[key] === base[key]) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return base[key]; } }); }); Object.keys(jsx$1).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (key in exports && exports[key] === jsx$1[key]) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return jsx$1[key]; } }); }); Object.keys(typescript$1).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (key in exports && exports[key] === typescript$1[key]) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return typescript$1[key]; } }); }); }); unwrapExports(generators); var printer = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _buffer = _interopRequireDefault(buffer); var n = _interopRequireWildcard(node$2); var t = _interopRequireWildcard(lib$1); var generatorFunctions = _interopRequireWildcard(generators); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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]/; const PURE_ANNOTATION_RE = /^\s*[@#]__PURE__\s*$/; 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 = Number.isInteger(+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; 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 !== "/" || i + 1 === str.length) { this._parenPushNewlineState = null; return; } const chaPost = str[i + 1]; if (chaPost === "*") { if (PURE_ANNOTATION_RE.test(str.slice(i + 2, str.length - 2))) { return; } } else if (chaPost !== "/") { this._parenPushNewlineState = null; return; } } this.token("("); this.indent(); parenPushNewlineState.printed = true; } _catchUp(prop, loc) { if (!this.format.retainLines) return; const pos = loc ? loc[prop] : null; if ((pos == null ? void 0 : pos.line) != null) { const count = pos.line - this._buf.getCurrentLine(); for (let i = 0; i < count; i++) { this._newline(); } } } _getIndent() { return this.format.indent.style.repeat(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 == null ? void 0 : 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 == null ? void 0 : 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 == null ? void 0 : 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), true); } printInnerComments(node, indent = true) { var _node$innerComments; if (!((_node$innerComments = node.innerComments) == null ? void 0 : _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, skipNewLines) { 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"; const printNewLines = isBlockComment && !skipNewLines && !this._noLineTerminator; if (printNewLines && this._buf.hasContent()) this.newline(1); if (!this.endsWith("[") && !this.endsWith("{")) this.space(); let val = !isBlockComment && !this._noLineTerminator ? `//${comment.value}\n` : `/*${comment.value}*/`; if (isBlockComment && this.format.indent.adjustMultilineComment) { var _comment$loc; const offset = (_comment$loc = comment.loc) == null ? void 0 : _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.format.retainLines ? 0 : this._buf.getCurrentColumn()); val = val.replace(/\n(?!$)/g, `\n${" ".repeat(indentSize)}`); } if (this.endsWith("/")) this._space(); this.withSource("start", comment.loc, () => { this._append(val); }); if (printNewLines) this.newline(1); } _printComments(comments, inlinePureAnnotation) { if (!(comments == null ? void 0 : comments.length)) return; if (inlinePureAnnotation && comments.length === 1 && PURE_ANNOTATION_RE.test(comments[0].value)) { this._printComment(comments[0], this._buf.hasContent() && !this.endsWith("\n")); } else { for (const comment of comments) { this._printComment(comment); } } } printAssertions(node) { var _node$assertions; if ((_node$assertions = node.assertions) == null ? void 0 : _node$assertions.length) { this.space(); this.word("assert"); this.space(); this.token("{"); this.space(); this.printList(node.assertions, node); this.space(); this.token("}"); } } } exports.default = Printer; Object.assign(Printer.prototype, generatorFunctions); function commaSeparator() { this.token(","); this.space(); } }); unwrapExports(printer); var lib$3 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = _default; exports.CodeGenerator = void 0; var _sourceMap = _interopRequireDefault(sourceMap$1); var _printer = _interopRequireDefault(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 = void 0; 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), recordAndTupleSyntaxType: opts.recordAndTupleSyntaxType }; 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(); } }); unwrapExports(lib$3); var lib_1$1 = lib$3.CodeGenerator; var ancestry = createCommonjsModule(function (module, exports) { 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; var t = _interopRequireWildcard(lib$1); var _index = _interopRequireDefault(path); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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; } }); unwrapExports(ancestry); var ancestry_1 = ancestry.findParent; var ancestry_2 = ancestry.find; var ancestry_3 = ancestry.getFunctionParent; var ancestry_4 = ancestry.getStatementParent; var ancestry_5 = ancestry.getEarliestCommonAncestorFrom; var ancestry_6 = ancestry.getDeepestCommonAncestorFrom; var ancestry_7 = ancestry.getAncestry; var ancestry_8 = ancestry.isAncestor; var ancestry_9 = ancestry.isDescendant; var ancestry_10 = ancestry.inType; var infererReference = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = _default; var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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; } if (t.isTSTypeAnnotation(types[0]) && t.createTSUnionType) { return t.createTSUnionType(types); } if (t.createFlowUnionType) { return t.createFlowUnionType(types); } 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 === "unknown") 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) { if (t.isTSTypeAnnotation(types[0]) && t.createTSUnionType) { return { typeAnnotation: t.createTSUnionType(types), ifStatement }; } if (t.createFlowUnionType) { return { typeAnnotation: t.createFlowUnionType(types), ifStatement }; } return { typeAnnotation: t.createUnionTypeAnnotation(types), ifStatement }; } return getConditionalAnnotation(ifStatement, name); } }); unwrapExports(infererReference); var inferers = createCommonjsModule(function (module, exports) { 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; } }); var t = _interopRequireWildcard(lib$1); var _infererReference = _interopRequireDefault(infererReference); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function VariableDeclarator() { var _type; const id = this.get("id"); if (!id.isIdentifier()) return; const init = this.get("init"); let type = init.getTypeAnnotation(); if (((_type = type) == null ? void 0 : _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() { const argumentTypes = [this.get("left").getTypeAnnotation(), this.get("right").getTypeAnnotation()]; if (t.isTSTypeAnnotation(argumentTypes[0]) && t.createTSUnionType) { return t.createTSUnionType(argumentTypes); } if (t.createFlowUnionType) { return t.createFlowUnionType(argumentTypes); } return t.createUnionTypeAnnotation(argumentTypes); } function ConditionalExpression() { const argumentTypes = [this.get("consequent").getTypeAnnotation(), this.get("alternate").getTypeAnnotation()]; if (t.isTSTypeAnnotation(argumentTypes[0]) && t.createTSUnionType) { return t.createTSUnionType(argumentTypes); } if (t.createFlowUnionType) { return t.createFlowUnionType(argumentTypes); } return t.createUnionTypeAnnotation(argumentTypes); } 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; } } } } }); unwrapExports(inferers); var inferers_1 = inferers.VariableDeclarator; var inferers_2 = inferers.TypeCastExpression; var inferers_3 = inferers.NewExpression; var inferers_4 = inferers.TemplateLiteral; var inferers_5 = inferers.UnaryExpression; var inferers_6 = inferers.BinaryExpression; var inferers_7 = inferers.LogicalExpression; var inferers_8 = inferers.ConditionalExpression; var inferers_9 = inferers.SequenceExpression; var inferers_10 = inferers.ParenthesizedExpression; var inferers_11 = inferers.AssignmentExpression; var inferers_12 = inferers.UpdateExpression; var inferers_13 = inferers.StringLiteral; var inferers_14 = inferers.NumericLiteral; var inferers_15 = inferers.BooleanLiteral; var inferers_16 = inferers.NullLiteral; var inferers_17 = inferers.RegExpLiteral; var inferers_18 = inferers.ObjectExpression; var inferers_19 = inferers.ArrayExpression; var inferers_20 = inferers.RestElement; var inferers_21 = inferers.ClassDeclaration; var inferers_22 = inferers.ClassExpression; var inferers_23 = inferers.FunctionDeclaration; var inferers_24 = inferers.ArrowFunctionExpression; var inferers_25 = inferers.FunctionExpression; var inferers_26 = inferers.CallExpression; var inferers_27 = inferers.TaggedTemplateExpression; var inference = createCommonjsModule(function (module, exports) { 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$1 = _interopRequireWildcard(inferers); var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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() { var _inferer; 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$1[node.type]; if (inferer) { return inferer.call(this, node); } inferer = inferers$1[this.parentPath.type]; if ((_inferer = inferer) == null ? void 0 : _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 }); } }); unwrapExports(inference); var inference_1 = inference.getTypeAnnotation; var inference_2 = inference._getTypeAnnotation; var inference_3 = inference.isBaseType; var inference_4 = inference.couldBeBaseType; var inference_5 = inference.baseTypeStrictlyMatches; var inference_6 = inference.isGenericType; var jsTokens = createCommonjsModule(function (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 }; }); unwrapExports(jsTokens); var jsTokens_1 = jsTokens.matchToToken; var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; var escapeStringRegexp = function (str) { if (typeof str !== 'string') { throw new TypeError('Expected a string'); } return str.replace(matchOperatorsRe, '\\$&'); }; var colorName = { "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] }; var conversions = createCommonjsModule(function (module) { /* MIT license */ // 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 colorName) { if (colorName.hasOwnProperty(key)) { reverseKeywords[colorName[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 colorName) { if (colorName.hasOwnProperty(keyword)) { var value = colorName[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 colorName[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]; }; }); var conversions_1 = conversions.rgb; var conversions_2 = conversions.hsl; var conversions_3 = conversions.hsv; var conversions_4 = conversions.hwb; var conversions_5 = conversions.cmyk; var conversions_6 = conversions.xyz; var conversions_7 = conversions.lab; var conversions_8 = conversions.lch; var conversions_9 = conversions.hex; var conversions_10 = conversions.keyword; var conversions_11 = conversions.ansi16; var conversions_12 = conversions.ansi256; var conversions_13 = conversions.hcg; var conversions_14 = conversions.apple; var conversions_15 = conversions.gray; /* 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; } var route = 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; }; 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); }); }); var colorConvert = convert; var ansiStyles = createCommonjsModule(function (module) { 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 }); }); 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; } var templates = (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(''); }; var chalk = createCommonjsModule(function (module) { const stdoutColor = supportsColor_1.stdout; 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 templates(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 }); var chalk_1 = chalk.supportsColor; var lib$4 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.shouldHighlight = shouldHighlight; exports.getChalk = getChalk; exports.default = highlight; var _jsTokens = _interopRequireWildcard(jsTokens); var _chalk = _interopRequireDefault(chalk); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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 ((0, lib.isKeyword)(token.value) || (0, lib.isReservedWord)(token.value)) { return "keyword"; } if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == "</")) { return "jsx_tag"; } if (token.value[0] !== token.value[0].toLowerCase()) { return "capitalized"; } } if (token.type === "punctuator" && BRACKET.test(token.value)) { return "bracket"; } if (token.type === "invalid" && (token.value === "@" || token.value === "#")) { return "punctuator"; } return token.type; } function highlightTokens(defs, text) { return text.replace(_jsTokens.default, function (...args) { const type = getTokenType(args); const colorize = defs[type]; if (colorize) { return args[0].split(NEWLINE).map(str => 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; } } }); unwrapExports(lib$4); var lib_1$2 = lib$4.shouldHighlight; var lib_2 = lib$4.getChalk; var lib$5 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.codeFrameColumns = codeFrameColumns; exports.default = _default; var _highlight = _interopRequireWildcard(lib$4); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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 + 1]; } 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; }; 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; const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines; let frame = highlightedLines.split(NEWLINE).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); } }); unwrapExports(lib$5); var lib_1$3 = lib$5.codeFrameColumns; var lib$6 = createCommonjsModule(function (module, exports) { 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 = void 0; this.keyword = void 0; this.beforeExpr = void 0; this.startsExpr = void 0; this.rightAssociative = void 0; this.isLoop = void 0; this.isAssign = void 0; this.prefix = void 0; this.postfix = void 0; this.binop = void 0; this.updateContext = void 0; 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 }), decimal: new TokenType("decimal", { 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 }), bracketHashL: new TokenType("#[", { beforeExpr, startsExpr }), bracketBarL: new TokenType("[|", { beforeExpr, startsExpr }), bracketR: new TokenType("]"), bracketBarR: new TokenType("|]"), braceL: new TokenType("{", { beforeExpr, startsExpr }), braceBarL: new TokenType("{|", { beforeExpr, startsExpr }), braceHashL: 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: new TokenType("%", { beforeExpr, binop: 10, startsExpr }), star: new TokenType("*", { binop: 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 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 Position { constructor(line, col) { this.line = void 0; this.column = void 0; this.line = line; this.column = col; } } class SourceLocation { constructor(start, end) { this.start = void 0; this.end = void 0; this.filename = void 0; this.identifierName = void 0; 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; this.ambiguousScriptDifferentAst = 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); } adjustCommentsAfterTrailingComma(node, elements, takeAllComments) { if (this.state.leadingComments.length === 0) { return; } let lastElement = null; let i = elements.length; while (lastElement === null && i > 0) { lastElement = elements[--i]; } if (lastElement === null) { return; } for (let 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--; } } const newTrailingComments = []; for (let i = 0; i < this.state.leadingComments.length; i++) { const leadingComment = this.state.leadingComments[i]; if (leadingComment.end < node.end) { newTrailingComments.push(leadingComment); if (!takeAllComments) { this.state.leadingComments.splice(i, 1); i--; } } else { if (node.trailingComments === undefined) { node.trailingComments = []; } node.trailingComments.push(leadingComment); } } if (takeAllComments) this.state.leadingComments = []; if (newTrailingComments.length > 0) { lastElement.trailingComments = newTrailingComments; } else if (lastElement.trailingComments !== undefined) { lastElement.trailingComments = []; } } 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) { switch (node.type) { case "ObjectExpression": this.adjustCommentsAfterTrailingComma(node, node.properties); break; case "ObjectPattern": this.adjustCommentsAfterTrailingComma(node, node.properties, true); break; case "CallExpression": this.adjustCommentsAfterTrailingComma(node, node.arguments); break; case "ArrayExpression": this.adjustCommentsAfterTrailingComma(node, node.elements); break; case "ArrayPattern": this.adjustCommentsAfterTrailingComma(node, node.elements, true); break; } } else if (this.state.commentPreviousNode && (this.state.commentPreviousNode.type === "ImportSpecifier" && node.type !== "ImportSpecifier" || this.state.commentPreviousNode.type === "ExportSpecifier" && node.type !== "ExportSpecifier")) { this.adjustCommentsAfterTrailingComma(node, [this.state.commentPreviousNode]); } 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 { const firstTrailingCommentIndex = trailingComments.findIndex(comment => comment.end >= node.end); if (firstTrailingCommentIndex > 0) { node.innerComments = trailingComments.slice(0, firstTrailingCommentIndex); node.trailingComments = trailingComments.slice(firstTrailingCommentIndex); } else { node.trailingComments = trailingComments; } } } stack.push(node); } } const ErrorMessages = Object.freeze({ AccessorIsGenerator: "A %0ter cannot be a generator", ArgumentsInClass: "'arguments' is only allowed in functions and class methods", AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block", AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function", AwaitExpressionFormalParameter: "await is not allowed in async function parameters", AwaitNotInAsyncContext: "'await' is only allowed within async functions and at the top levels of modules", AwaitNotInAsyncFunction: "'await' is only allowed within async functions", BadGetterArity: "getter must not have any formal parameters", BadSetterArity: "setter must have exactly one formal parameter", BadSetterRestParameter: "setter function argument must not be a rest parameter", ConstructorClassField: "Classes may not have a field named 'constructor'", ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'", ConstructorIsAccessor: "Class constructor may not be an accessor", ConstructorIsAsync: "Constructor can't be an async function", ConstructorIsGenerator: "Constructor can't be a generator", DeclarationMissingInitializer: "%0 require an initialization value", DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. You can set the 'decoratorsBeforeExport' option to false to use the 'export @decorator class {}' syntax", DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?", DecoratorExportClass: "Using the export keyword between a decorator and a class is not allowed. Please use `export @dec class` instead.", DecoratorSemicolon: "Decorators must not be followed by a semicolon", DecoratorStaticBlock: "Decorators can't be used with a static block", DeletePrivateField: "Deleting a private field is not allowed", DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.", DuplicateConstructor: "Duplicate constructor in the same class", DuplicateDefaultExport: "Only one default export allowed per module.", DuplicateExport: "`%0` has already been exported. Exported identifiers must be unique.", DuplicateProto: "Redefinition of __proto__ property", DuplicateRegExpFlags: "Duplicate regular expression flag", DuplicateStaticBlock: "Duplicate static block in the same class", ElementAfterRest: "Rest element must be last element", EscapedCharNotAnIdentifier: "Invalid Unicode escape", ExportBindingIsString: "A string literal cannot be used as an exported binding without `from`.\n- Did you mean `export { %0 as '%1' } from 'some-module'`?", ExportDefaultFromAsIdentifier: "'from' is not allowed as an identifier after 'export default'", ForInOfLoopInitializer: "%0 loop variable declaration may not have an initializer", GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block", IllegalBreakContinue: "Unsyntactic %0", IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list", IllegalReturn: "'return' outside of function", ImportBindingIsString: 'A string literal cannot be used as an imported binding.\n- Did you mean `import { "%0" as foo }`?', ImportCallArgumentTrailingComma: "Trailing comma is disallowed inside import(...) arguments", ImportCallArity: "import() requires exactly %0", ImportCallNotNewExpression: "Cannot use new with import(...)", ImportCallSpreadArgument: "... is not allowed in import()", ImportMetaOutsideModule: `import.meta may appear only with 'sourceType: "module"'`, ImportOutsideModule: `'import' and 'export' may appear only with 'sourceType: "module"'`, InvalidBigIntLiteral: "Invalid BigIntLiteral", InvalidCodePoint: "Code point out of bounds", InvalidDecimal: "Invalid decimal", InvalidDigit: "Expected number in radix %0", InvalidEscapeSequence: "Bad character escape sequence", InvalidEscapeSequenceTemplate: "Invalid escape sequence in template", InvalidEscapedReservedWord: "Escape sequence in keyword %0", InvalidIdentifier: "Invalid identifier %0", InvalidLhs: "Invalid left-hand side in %0", InvalidLhsBinding: "Binding invalid left-hand side in %0", InvalidNumber: "Invalid number", InvalidOrMissingExponent: "Floating-point numbers require a valid exponent after the 'e'", InvalidOrUnexpectedToken: "Unexpected character '%0'", InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern", InvalidPrivateFieldResolution: "Private name #%0 is not defined", InvalidPropertyBindingPattern: "Binding member expression", InvalidRecordProperty: "Only properties and spread elements are allowed in record definitions", InvalidRestAssignmentPattern: "Invalid rest operator's argument", LabelRedeclaration: "Label '%0' is already declared", LetInLexicalBinding: "'let' is not allowed to be used as a name in 'let' or 'const' declarations.", LineTerminatorBeforeArrow: "No line break is allowed before '=>'", MalformedRegExpFlags: "Invalid regular expression flag", MissingClassName: "A class name is required", MissingEqInAssignment: "Only '=' operator can be used for specifying default value.", MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX", MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators", ModuleAttributeDifferentFromType: "The only accepted module attribute is `type`", ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values", ModuleAttributesWithDuplicateKeys: 'Duplicate key "%0" is not allowed in module attributes', ModuleExportNameHasLoneSurrogate: "An export name cannot include a lone surrogate, found '\\u%0'", ModuleExportUndefined: "Export '%0' is not defined", MultipleDefaultsInSwitch: "Multiple default clauses", NewlineAfterThrow: "Illegal newline after throw", NoCatchOrFinally: "Missing catch or finally clause", NumberIdentifier: "Identifier directly after number", NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences", ObsoleteAwaitStar: "await* has been removed from the async functions proposal. Use Promise.all() instead.", OptionalChainingNoNew: "constructors in/after an Optional Chain are not allowed", OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain", ParamDupe: "Argument name clash", PatternHasAccessor: "Object pattern can't contain getter or setter", PatternHasMethod: "Object pattern can't contain methods", PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized', PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression", PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression", PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference", PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding", PrimaryTopicRequiresSmartPipeline: "Primary Topic Reference found but pipelineOperator not passed 'smart' for 'proposal' option.", PrivateInExpectedIn: "Private names are only allowed in property accesses (`obj.#%0`) or in `in` expressions (`#%0 in obj`)", PrivateNameRedeclaration: "Duplicate private name #%0", RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'", RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'", RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'", RecordNoProto: "'__proto__' is not allowed in Record expressions", RestTrailingComma: "Unexpected trailing comma after rest element", SloppyFunction: "In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement", StaticPrototype: "Classes may not have static property named prototype", StrictDelete: "Deleting local variable in strict mode", StrictEvalArguments: "Assigning to '%0' in strict mode", StrictEvalArgumentsBinding: "Binding '%0' in strict mode", StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block", StrictNumericEscape: "The only valid numeric escape in strict mode is '\\0'", StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode", StrictWith: "'with' in strict mode", SuperNotAllowed: "super() is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?", SuperPrivateField: "Private fields can't be accessed on super", TrailingDecorator: "Decorators must be attached to a class element", TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'", TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'", TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'", UnexpectedArgumentPlaceholder: "Unexpected argument placeholder", UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal', UnexpectedDigitAfterHash: "Unexpected digit after hash token", UnexpectedImportExport: "'import' and 'export' may only appear at the top level", UnexpectedKeyword: "Unexpected keyword '%0'", UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration", UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context", UnexpectedNewTarget: "new.target can only be used in functions", UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits", UnexpectedPrivateField: "Private names can only be used as the name of a class element (i.e. class C { #p = 42; #m() {} } )\n or a property of member expression (i.e. this.#p).", UnexpectedReservedWord: "Unexpected reserved word '%0'", UnexpectedSuper: "super is only allowed in object methods and classes", UnexpectedToken: "Unexpected token '%0'", UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.", UnsupportedBind: "Binding should be performed on object property.", UnsupportedDecoratorExport: "A decorated export must export a class declaration", UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.", UnsupportedImport: "import can only be used in import() or import.meta", UnsupportedMetaProperty: "The only valid meta property for %0 is %0.%1", UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters", UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties", UnsupportedSuper: "super can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop])", UnterminatedComment: "Unterminated comment", UnterminatedRegExp: "Unterminated regular expression", UnterminatedString: "Unterminated string constant", UnterminatedTemplate: "Unterminated template", VarRedeclaration: "Identifier '%0' has already been declared", YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator", YieldInParameter: "Yield expression is not allowed in formal parameters", ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0" }); class ParserError 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, errorTemplate, ...params) { return this.raiseWithData(pos, undefined, errorTemplate, ...params); } raiseWithData(pos, data, errorTemplate, ...params) { const loc = this.getLocationForPosition(pos); const message = errorTemplate.replace(/%(\d+)/g, (_, i) => params[i]) + ` (${loc.line}:${loc.column})`; return this._raise(Object.assign({ loc, pos }, data), message); } _raise(errorContext, message) { const err = new SyntaxError(message); Object.assign(err, errorContext); if (this.options.errorRecovery) { if (!this.isLookahead) this.state.errors.push(err); return err; } else { throw err; } } } 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; } estreeParseBigIntLiteral(value) { const bigInt = typeof BigInt !== "undefined" ? BigInt(value) : null; const node = this.estreeParseLiteral(bigInt); node.bigint = String(node.value || value); return node; } estreeParseDecimalLiteral(value) { const decimal = null; const node = this.estreeParseLiteral(decimal); node.decimal = String(node.value || value); 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); } } getObjectOrClassMethodParams(method) { return method.value.params; } checkLVal(expr, contextDescription, ...args) { switch (expr.type) { case "ObjectPattern": expr.properties.forEach(prop => { this.checkLVal(prop.type === "Property" ? prop.value : prop, "object destructuring pattern", ...args); }); break; default: super.checkLVal(expr, contextDescription, ...args); } } checkProto(prop, isRecord, protoRef, refExpressionErrors) { if (prop.method) { return; } super.checkProto(prop, isRecord, protoRef, refExpressionErrors); } isValidDirective(stmt) { var _stmt$expression$extr; return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && !((_stmt$expression$extr = stmt.expression.extra) == null ? void 0 : _stmt$expression$extr.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(refExpressionErrors) { switch (this.state.type) { case types.num: case types.string: return this.estreeParseLiteral(this.state.value); case types.regexp: return this.estreeParseRegExpLiteral(this.state.value); case types.bigint: return this.estreeParseBigIntLiteral(this.state.value); case types.decimal: return this.estreeParseDecimalLiteral(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(refExpressionErrors); } } 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, isAccessor) { const node = super.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor); if (node) { node.type = "Property"; if (node.kind === "method") node.kind = "init"; node.shorthand = false; } return node; } parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) { const node = super.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors); if (node) { node.kind = "init"; node.type = "Property"; } return node; } toAssignable(node, isLHS = false) { if (isSimpleProperty(node)) { this.toAssignable(node.value); return node; } return super.toAssignable(node, isLHS); } toAssignableObjectExpressionProp(prop, ...args) { if (prop.kind === "get" || prop.kind === "set") { throw this.raise(prop.key.start, ErrorMessages.PatternHasAccessor); } else if (prop.method) { throw this.raise(prop.key.start, ErrorMessages.PatternHasMethod); } else { super.toAssignableObjectExpressionProp(prop, ...args); } } finishCallExpression(node, optional) { super.finishCallExpression(node, optional); if (node.callee.type === "Import") { node.type = "ImportExpression"; node.source = node.arguments[0]; delete node.arguments; delete node.callee; } return node; } toReferencedArguments(node) { if (node.type === "ImportExpression") { return; } super.toReferencedArguments(node); } parseExport(node) { super.parseExport(node); switch (node.type) { case "ExportAllDeclaration": node.exported = null; break; case "ExportNamedDeclaration": if (node.specifiers.length === 1 && node.specifiers[0].type === "ExportNamespaceSpecifier") { node.type = "ExportAllDeclaration"; node.exported = node.specifiers[0].exported; delete node.specifiers; } break; } return node; } parseSubscript(base, startPos, startLoc, noCalls, state) { const node = super.parseSubscript(base, startPos, startLoc, noCalls, state); if (state.optionalChainMember) { if (node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression") { node.type = node.type.substring(8); } if (state.stop) { const chain = this.startNodeAtNode(node); chain.expression = node; return this.finishNode(chain, "ChainExpression"); } } else if (node.type === "MemberExpression" || node.type === "CallExpression") { node.optional = false; } return node; } }); class TokContext { constructor(token, isExpr, preserveSpace, override) { this.token = void 0; this.isExpr = void 0; this.preserveSpace = void 0; this.override = void 0; this.token = token; this.isExpr = !!isExpr; this.preserveSpace = !!preserveSpace; this.override = override; } } const types$1 = { braceStatement: new TokContext("{", false), braceExpression: new TokContext("{", true), recordExpression: 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 && prevType !== types._function && prevType !== types._class) { 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 && this.hasPrecedingLineBreak()) && !((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; }; types.braceHashL.updateContext = function () { this.state.context.push(types$1.recordExpression); this.state.exprAllowed = true; }; 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-\u08c7\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\u0d04-\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-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\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-\uab69\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\u0b55-\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\u0d81-\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\u1abf\u1ac0\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\ua82c\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, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 107, 20, 28, 22, 13, 52, 76, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 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, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 230, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 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, 190, 0, 80, 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, 1237, 43, 8, 8952, 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, 42717, 35, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938]; 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, 370, 1, 154, 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, 2, 11, 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, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 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, 82, 0, 12, 1, 19628, 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, 4759, 9, 787719, 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 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 reservedWords = { keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"], strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"], strictBind: ["eval", "arguments"] }; const keywords$1 = new Set(reservedWords.keyword); const reservedWordsStrictSet = new Set(reservedWords.strict); const reservedWordsStrictBindSet = new Set(reservedWords.strictBind); function isReservedWord(word, inModule) { return inModule && word === "await" || word === "enum"; } function isStrictReservedWord(word, inModule) { return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word); } function isStrictBindOnlyReservedWord(word) { return reservedWordsStrictBindSet.has(word); } function isStrictBindReservedWord(word, inModule) { return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word); } function isKeyword(word) { return keywords$1.has(word); } const keywordRelationalOperator = /^in(stanceof)?$/; function isIteratorStart(current, next) { return current === 64 && next === 64; } const SCOPE_OTHER = 0b00000000, SCOPE_PROGRAM = 0b00000001, SCOPE_FUNCTION = 0b00000010, SCOPE_ARROW = 0b00000100, SCOPE_SIMPLE_CATCH = 0b00001000, SCOPE_SUPER = 0b00010000, SCOPE_DIRECT_SUPER = 0b00100000, SCOPE_CLASS = 0b01000000, SCOPE_TS_MODULE = 0b10000000, SCOPE_VAR = SCOPE_PROGRAM | SCOPE_FUNCTION | SCOPE_TS_MODULE; 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_AMBIENT = 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 = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY; const CLASS_ELEMENT_FLAG_STATIC = 0b100, CLASS_ELEMENT_KIND_GETTER = 0b010, CLASS_ELEMENT_KIND_SETTER = 0b001, CLASS_ELEMENT_KIND_ACCESSOR = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_KIND_SETTER; const CLASS_ELEMENT_STATIC_GETTER = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_FLAG_STATIC, CLASS_ELEMENT_STATIC_SETTER = CLASS_ELEMENT_KIND_SETTER | CLASS_ELEMENT_FLAG_STATIC, CLASS_ELEMENT_INSTANCE_GETTER = CLASS_ELEMENT_KIND_GETTER, CLASS_ELEMENT_INSTANCE_SETTER = CLASS_ELEMENT_KIND_SETTER, CLASS_ELEMENT_OTHER = 0; const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]); const FlowErrors = Object.freeze({ AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.", AmbiguousDeclareModuleKind: "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", AssignReservedType: "Cannot overwrite reserved type %0", DeclareClassElement: "The `declare` modifier can only appear on class fields.", DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.", DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement", EnumBooleanMemberNotInitialized: "Boolean enum members need to be initialized. Use either `%0 = true,` or `%0 = false,` in enum `%1`.", EnumDuplicateMemberName: "Enum member names need to be unique, but the name `%0` has already been used before in enum `%1`.", EnumInconsistentMemberValues: "Enum `%0` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.", EnumInvalidExplicitType: "Enum type `%1` is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.", EnumInvalidExplicitTypeUnknownSupplied: "Supplied enum type is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.", EnumInvalidMemberInitializerPrimaryType: "Enum `%0` has type `%2`, so the initializer of `%1` needs to be a %2 literal.", EnumInvalidMemberInitializerSymbolType: "Symbol enum members cannot be initialized. Use `%1,` in enum `%0`.", EnumInvalidMemberInitializerUnknownType: "The enum member initializer for `%1` needs to be a literal (either a boolean, number, or string) in enum `%0`.", EnumInvalidMemberName: "Enum member names cannot start with lowercase 'a' through 'z'. Instead of using `%0`, consider using `%1`, in enum `%2`.", EnumNumberMemberNotInitialized: "Number enum members need to be initialized, e.g. `%1 = 1` in enum `%0`.", EnumStringMemberInconsistentlyInitailized: "String enum members need to consistently either all use initializers, or use no initializers, in enum `%0`.", ImportTypeShorthandOnlyInPureImport: "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", InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type", InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions", InexactVariance: "Explicit inexact syntax cannot have variance", InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`", MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.", NestedDeclareModule: "`declare module` cannot be used inside another `declare module`", NestedFlowComment: "Cannot have a flow comment inside another flow comment", OptionalBindingPattern: "A binding pattern parameter cannot be optional in an implementation signature.", SpreadVariance: "Spread properties cannot have variance", TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`", TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis", UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object", UnexpectedReservedType: "Unexpected reserved type %0", UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new", UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.", UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions", UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint"', UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration", UnexpectedTypeParameterBeforeAsyncArrowFunction: "Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`", UnsupportedDeclareExportKind: "`declare export %0` is not supported. Use `%1` instead", UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module", UnterminatedFlowComment: "Unterminated flow-comment" }); 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 => { var _temp; return _temp = class extends superClass { constructor(options, input) { super(options, input); this.flowPragma = void 0; this.flowPragma = undefined; } shouldParseTypes() { return this.getPluginOption("flow", "all") || this.flowPragma === "flow"; } shouldParseEnums() { return !!this.getPluginOption("flow", "enums"); } 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, FlowErrors.UnexpectedSpaceBetweenModuloChecks); } 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.raise(this.state.lastTokStart, FlowErrors.NestedDeclareModule); } 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.scope.declareName(node.id.name, BIND_VAR, node.id.start); 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.match(types._typeof)) { this.raise(this.state.lastTokStart, FlowErrors.InvalidNonTypeImportInDeclareModule); } this.parseImport(bodyNode); } else { this.expectContextual("declare", FlowErrors.UnsupportedStatementInDeclareModule); 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; body.forEach(bodyElement => { if (isEsModuleType(bodyElement)) { if (kind === "CommonJS") { this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind); } kind = "ES"; } else if (bodyElement.type === "DeclareModuleExports") { if (hasModuleExport) { this.raise(bodyElement.start, FlowErrors.DuplicateDeclareModuleExports); } if (kind === "ES") { this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind); } 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]; throw this.raise(this.state.start, FlowErrors.UnsupportedDeclareExportKind, label, suggestion); } 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, true); this.scope.declareName(node.id.name, isClass ? BIND_FUNCTION : BIND_LEXICAL, node.id.start); 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 === "_") { this.raise(this.state.start, FlowErrors.UnexpectedReservedUnderscore); } } checkReservedType(word, startLoc, declaration) { if (!reservedTypes.has(word)) return; this.raise(startLoc, declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, word); } flowParseRestrictedIdentifier(liberal, declaration) { this.checkReservedType(this.state.value, this.state.start, declaration); return this.parseIdentifier(liberal); } flowParseTypeAlias(node) { node.id = this.flowParseRestrictedIdentifier(false, true); 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, 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(requireDefault = false) { 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)) { this.eat(types.eq); node.default = this.flowParseType(); } else { if (requireDefault) { this.raise(nodeStart, FlowErrors.MissingTypeParamDefault); } } return this.finishNode(node, "TypeParameter"); } flowParseTypeParameterDeclaration() { 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(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(); } 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; let inexactStart = 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 != null ? allowInexact : !exact); if (propOrInexact === null) { inexact = true; inexactStart = this.state.lastTokStart; } else { nodeStart.properties.push(propOrInexact); } } this.flowObjectTypeSemicolon(); if (inexactStart && !this.match(types.braceR) && !this.match(types.braceBarR)) { this.raise(inexactStart, FlowErrors.UnexpectedExplicitInexactInObject); } } 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.eat(types.ellipsis)) { const isInexactToken = this.match(types.comma) || this.match(types.semi) || this.match(types.braceR) || this.match(types.braceBarR); if (isInexactToken) { if (!allowSpread) { this.raise(this.state.lastTokStart, FlowErrors.InexactInsideNonObject); } else if (!allowInexact) { this.raise(this.state.lastTokStart, FlowErrors.InexactInsideExact); } if (variance) { this.raise(variance.start, FlowErrors.InexactVariance); } return null; } if (!allowSpread) { this.raise(this.state.lastTokStart, FlowErrors.UnexpectedSpreadType); } if (protoStart != null) { this.unexpected(protoStart); } if (variance) { this.raise(variance.start, FlowErrors.SpreadVariance); } 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, ErrorMessages.BadGetterArity); } else { this.raise(start, ErrorMessages.BadSetterArity); } } if (property.kind === "set" && property.value.rest) { this.raise(start, ErrorMessages.BadSetterRestParameter); } } 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.flowParseRestrictedIdentifier(true); while (this.eat(types.dot)) { const node2 = this.startNodeAt(startPos, startLoc); node2.qualification = node; node2.id = this.flowParseRestrictedIdentifier(true); 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"); case "symbol": return this.finishNode(node, "SymbolTypeAnnotation"); 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: this.state.noAnonFunctionType = false; type = this.flowParseTupleType(); this.state.noAnonFunctionType = oldNoAnonFunctionType; return type; case types.relational: if (this.state.value === "<") { node.typeParameters = this.flowParseTypeParameterDeclaration(); 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)) { return this.parseLiteral(-this.state.value, "NumberLiteralTypeAnnotation", node.start, node.loc.start); } if (this.match(types.bigint)) { return this.parseLiteral(-this.state.value, "BigIntLiteralTypeAnnotation", node.start, node.loc.start); } throw this.raise(this.state.start, FlowErrors.UnexpectedSubtractionOperand); } throw this.unexpected(); case types.num: return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation"); case types.bigint: return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation"); 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 lookahead = this.lookahead(); if (lookahead.type === types.name || isKeyword(lookahead.value)) { const node = this.startNode(); this.next(); return this.flowParseInterface(node); } } else if (this.shouldParseEnums() && this.isContextual("enum")) { const node = this.startNode(); this.next(); return this.flowParseEnumDeclaration(node); } 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") || this.shouldParseEnums() && this.isContextual("enum") || super.shouldParseExportDeclaration(); } isExportDefaultSpecifier() { if (this.match(types.name) && (this.state.value === "type" || this.state.value === "interface" || this.state.value === "opaque" || this.shouldParseEnums() && this.state.value === "enum")) { return false; } return super.isExportDefaultSpecifier(); } parseExportDefaultExpression() { if (this.shouldParseEnums() && this.isContextual("enum")) { const node = this.startNode(); this.next(); return this.flowParseEnumDeclaration(node); } return super.parseExportDefaultExpression(); } parseConditional(expr, startPos, startLoc, refNeedsArrowPos) { if (!this.match(types.question)) return expr; if (refNeedsArrowPos) { const result = this.tryParse(() => super.parseConditional(expr, startPos, startLoc)); if (!result.node) { refNeedsArrowPos.start = result.error.pos || this.state.start; return expr; } if (result.error) this.state = result.failState; return result.node; } 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, FlowErrors.AmbiguousConditionalArrow); } 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(undefined, undefined, undefined)); return this.finishNode(node, "ConditionalExpression"); } tryParseConditionalConsequent() { this.state.noArrowParamsConversionAt.push(this.state.start); const consequent = this.parseMaybeAssignAllowIn(); 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.finishArrowValidation(node); } else { arrows.push(node); } stack.push(node.body); } else if (node.type === "ConditionalExpression") { stack.push(node.consequent); stack.push(node.alternate); } } if (disallowInvalid) { arrows.forEach(node => this.finishArrowValidation(node)); return [arrows, []]; } return partition(arrows, node => node.params.every(param => this.isAssignable(param, true))); } finishArrowValidation(node) { var _node$extra; this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingComma, false); this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW); super.checkParams(node, false, true); this.scope.exit(); } 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 if (this.shouldParseEnums() && this.isContextual("enum")) { node.exportKind = "value"; const declarationNode = this.startNode(); this.next(); return this.flowParseEnumDeclaration(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(); } } parseClassMember(classBody, member, state) { const pos = this.state.start; if (this.isContextual("declare")) { if (this.parseClassMemberFromModifier(classBody, member)) { return; } member.declare = true; } super.parseClassMember(classBody, member, state); if (member.declare) { if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty") { this.raise(pos, FlowErrors.DeclareClassElement); } else if (member.value) { this.raise(member.value.start, FlowErrors.DeclareClassFieldInitializer); } } } 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 (this.state.inType && code === 63) { return this.finishOp(types.question, 1); } else if (isIteratorStart(code, next)) { this.state.isIterator = true; return super.readWord(); } else { return super.getTokenFromCode(code); } } isAssignable(node, isBinding) { switch (node.type) { case "Identifier": case "ObjectPattern": case "ArrayPattern": case "AssignmentPattern": return true; case "ObjectExpression": { const last = node.properties.length - 1; return node.properties.every((prop, i) => { return prop.type !== "ObjectMethod" && (i === last || prop.type === "SpreadElement") && this.isAssignable(prop); }); } case "ObjectProperty": return this.isAssignable(node.value); case "SpreadElement": return this.isAssignable(node.argument); case "ArrayExpression": return node.elements.every(element => this.isAssignable(element)); case "AssignmentExpression": return node.operator === "="; case "ParenthesizedExpression": case "TypeCastExpression": return this.isAssignable(node.expression); case "MemberExpression": case "OptionalMemberExpression": return !isBinding; default: return false; } } toAssignable(node, isLHS = false) { if (node.type === "TypeCastExpression") { return super.toAssignable(this.typeCastToParameter(node), isLHS); } else { return super.toAssignable(node, isLHS); } } toAssignableList(exprList, trailingCommaPos, isLHS) { for (let i = 0; i < exprList.length; i++) { const expr = exprList[i]; if ((expr == null ? void 0 : expr.type) === "TypeCastExpression") { exprList[i] = this.typeCastToParameter(expr); } } return super.toAssignableList(exprList, trailingCommaPos, isLHS); } toReferencedList(exprList, isParenthesizedExpr) { for (let i = 0; i < exprList.length; i++) { var _expr$extra; const expr = exprList[i]; if (expr && expr.type === "TypeCastExpression" && !((_expr$extra = expr.extra) == null ? void 0 : _expr$extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) { this.raise(expr.typeAnnotation.start, FlowErrors.TypeCastInPattern); } } return exprList; } parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) { const node = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors); if (canBePattern && !this.state.maybeInArrowParameters) { this.toReferencedList(node.elements); } return node; } checkLVal(expr, ...args) { if (expr.type !== "TypeCastExpression") { return super.checkLVal(expr, ...args); } } 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(); } 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, isPrivateNameAllowed) { const variance = this.flowParseVariance(); const key = super.parsePropertyName(node, isPrivateNameAllowed); node.variance = variance; return key; } parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) { if (prop.variance) { this.unexpected(prop.variance.start); } delete prop.variance; let typeParameters; if (this.isRelational("<") && !isAccessor) { typeParameters = this.flowParseTypeParameterDeclaration(); if (!this.match(types.parenL)) this.unexpected(); } super.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors); if (typeParameters) { (prop.value || prop).typeParameters = typeParameters; } } parseAssignableListItemTypes(param) { if (this.eat(types.question)) { if (param.type !== "Identifier") { this.raise(param.start, FlowErrors.OptionalBindingPattern); } 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, FlowErrors.TypeBeforeInitializer); } 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, true) : this.parseIdentifier(); this.checkLVal(specifier.local, contextDescription, BIND_LEXICAL); 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.parseModuleExportName(); let specifierTypeKind = null; if (firstIdent.type === "Identifier") { 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 { if (firstIdent.type === "StringLiteral") { throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, firstIdent.value); } 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, FlowErrors.ImportTypeShorthandOnlyInPureImport); } if (nodeIsTypeImport || specifierIsTypeImport) { this.checkReservedType(specifier.local.name, specifier.local.start, true); } if (isBinding && !nodeIsTypeImport && !specifierIsTypeImport) { this.checkReservedWord(specifier.local.name, specifier.start, true, true); } this.checkLVal(specifier.local, "import specifier", BIND_LEXICAL); 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(); } 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(refExpressionErrors, afterLeftParse, refNeedsArrowPos) { var _jsx; let state = null; let jsx; if (this.hasPlugin("jsx") && (this.match(types.jsxTagStart) || this.isRelational("<"))) { state = this.state.clone(); jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos), state); if (!jsx.error) return jsx.node; const { context } = this.state; if (context[context.length - 1] === types$1.j_oTag) { context.length -= 2; } else if (context[context.length - 1] === types$1.j_expr) { context.length -= 1; } } if (((_jsx = jsx) == null ? void 0 : _jsx.error) || this.isRelational("<")) { var _jsx2, _jsx3; state = state || this.state.clone(); let typeParameters; const arrow = this.tryParse(abort => { var _arrowExpression$extr; typeParameters = this.flowParseTypeParameterDeclaration(); const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => { const result = super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos); this.resetStartLocationFromNode(result, typeParameters); return result; }); if (arrowExpression.type !== "ArrowFunctionExpression" && ((_arrowExpression$extr = arrowExpression.extra) == null ? void 0 : _arrowExpression$extr.parenthesized)) { abort(); } const expr = this.maybeUnwrapTypeCastExpression(arrowExpression); expr.typeParameters = typeParameters; this.resetStartLocationFromNode(expr, typeParameters); return arrowExpression; }, state); let arrowExpression = null; if (arrow.node && this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") { if (!arrow.error && !arrow.aborted) { if (arrow.node.async) { this.raise(typeParameters.start, FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction); } return arrow.node; } arrowExpression = arrow.node; } if ((_jsx2 = jsx) == null ? void 0 : _jsx2.node) { this.state = jsx.failState; return jsx.node; } if (arrowExpression) { this.state = arrow.failState; return arrowExpression; } if ((_jsx3 = jsx) == null ? void 0 : _jsx3.thrown) throw jsx.error; if (arrow.thrown) throw arrow.error; throw this.raise(typeParameters.start, FlowErrors.UnexpectedTokenAfterTypeParameter); } return super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos); } parseArrow(node) { if (this.match(types.colon)) { const result = this.tryParse(() => { 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(); return typeNode; }); if (result.thrown) return null; if (result.error) this.state = result.failState; node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null; } 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(...arguments); } 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(); const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startPos, startLoc) || abort(), state); if (!arrow.error && !arrow.aborted) return arrow.node; const result = this.tryParse(() => super.parseSubscripts(base, startPos, startLoc, noCalls), state); if (result.node && !result.error) return result.node; if (arrow.node) { this.state = arrow.failState; return arrow.node; } if (result.node) { this.state = result.failState; return result.node; } throw arrow.error || result.error; } return super.parseSubscripts(base, startPos, startLoc, noCalls); } parseSubscript(base, startPos, startLoc, noCalls, subscriptState) { if (this.match(types.questionDot) && this.isLookaheadToken_lt()) { 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.finishCallExpression(node, true); } else if (!noCalls && this.shouldParseTypes() && this.isRelational("<")) { const node = this.startNodeAt(startPos, startLoc); node.callee = base; const result = this.tryParse(() => { node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew(); this.expect(types.parenL); node.arguments = this.parseCallExpressionArguments(types.parenR, false); if (subscriptState.optionalChainMember) node.optional = false; return this.finishCallExpression(node, subscriptState.optionalChainMember); }); if (result.node) { if (result.error) this.state = result.failState; return result.node; } } return super.parseSubscript(base, startPos, startLoc, noCalls, subscriptState); } parseNewArguments(node) { let targs = null; if (this.shouldParseTypes() && this.isRelational("<")) { targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node; } 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.raise(this.state.pos, FlowErrors.UnterminatedFlowComment); } return fileNode; } skipBlockComment() { if (this.hasPlugin("flowComments") && this.skipFlowComment()) { if (this.state.hasFlowComment) { this.unexpected(null, FlowErrors.NestedFlowComment); } 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) { throw this.raise(this.state.pos - 2, ErrorMessages.UnterminatedComment); } 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) { throw this.raise(this.state.pos, ErrorMessages.UnterminatedComment); } } flowEnumErrorBooleanMemberNotInitialized(pos, { enumName, memberName }) { this.raise(pos, FlowErrors.EnumBooleanMemberNotInitialized, memberName, enumName); } flowEnumErrorInvalidMemberName(pos, { enumName, memberName }) { const suggestion = memberName[0].toUpperCase() + memberName.slice(1); this.raise(pos, FlowErrors.EnumInvalidMemberName, memberName, suggestion, enumName); } flowEnumErrorDuplicateMemberName(pos, { enumName, memberName }) { this.raise(pos, FlowErrors.EnumDuplicateMemberName, memberName, enumName); } flowEnumErrorInconsistentMemberValues(pos, { enumName }) { this.raise(pos, FlowErrors.EnumInconsistentMemberValues, enumName); } flowEnumErrorInvalidExplicitType(pos, { enumName, suppliedType }) { return this.raise(pos, suppliedType === null ? FlowErrors.EnumInvalidExplicitTypeUnknownSupplied : FlowErrors.EnumInvalidExplicitType, enumName, suppliedType); } flowEnumErrorInvalidMemberInitializer(pos, { enumName, explicitType, memberName }) { let message = null; switch (explicitType) { case "boolean": case "number": case "string": message = FlowErrors.EnumInvalidMemberInitializerPrimaryType; break; case "symbol": message = FlowErrors.EnumInvalidMemberInitializerSymbolType; break; default: message = FlowErrors.EnumInvalidMemberInitializerUnknownType; } return this.raise(pos, message, enumName, memberName, explicitType); } flowEnumErrorNumberMemberNotInitialized(pos, { enumName, memberName }) { this.raise(pos, FlowErrors.EnumNumberMemberNotInitialized, enumName, memberName); } flowEnumErrorStringMemberInconsistentlyInitailized(pos, { enumName }) { this.raise(pos, FlowErrors.EnumStringMemberInconsistentlyInitailized, enumName); } flowEnumMemberInit() { const startPos = this.state.start; const endOfInit = () => this.match(types.comma) || this.match(types.braceR); switch (this.state.type) { case types.num: { const literal = this.parseLiteral(this.state.value, "NumericLiteral"); if (endOfInit()) { return { type: "number", pos: literal.start, value: literal }; } return { type: "invalid", pos: startPos }; } case types.string: { const literal = this.parseLiteral(this.state.value, "StringLiteral"); if (endOfInit()) { return { type: "string", pos: literal.start, value: literal }; } return { type: "invalid", pos: startPos }; } case types._true: case types._false: { const literal = this.parseBooleanLiteral(); if (endOfInit()) { return { type: "boolean", pos: literal.start, value: literal }; } return { type: "invalid", pos: startPos }; } default: return { type: "invalid", pos: startPos }; } } flowEnumMemberRaw() { const pos = this.state.start; const id = this.parseIdentifier(true); const init = this.eat(types.eq) ? this.flowEnumMemberInit() : { type: "none", pos }; return { id, init }; } flowEnumCheckExplicitTypeMismatch(pos, context, expectedType) { const { explicitType } = context; if (explicitType === null) { return; } if (explicitType !== expectedType) { this.flowEnumErrorInvalidMemberInitializer(pos, context); } } flowEnumMembers({ enumName, explicitType }) { const seenNames = new Set(); const members = { booleanMembers: [], numberMembers: [], stringMembers: [], defaultedMembers: [] }; while (!this.match(types.braceR)) { const memberNode = this.startNode(); const { id, init } = this.flowEnumMemberRaw(); const memberName = id.name; if (memberName === "") { continue; } if (/^[a-z]/.test(memberName)) { this.flowEnumErrorInvalidMemberName(id.start, { enumName, memberName }); } if (seenNames.has(memberName)) { this.flowEnumErrorDuplicateMemberName(id.start, { enumName, memberName }); } seenNames.add(memberName); const context = { enumName, explicitType, memberName }; memberNode.id = id; switch (init.type) { case "boolean": { this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "boolean"); memberNode.init = init.value; members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember")); break; } case "number": { this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "number"); memberNode.init = init.value; members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember")); break; } case "string": { this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "string"); memberNode.init = init.value; members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember")); break; } case "invalid": { throw this.flowEnumErrorInvalidMemberInitializer(init.pos, context); } case "none": { switch (explicitType) { case "boolean": this.flowEnumErrorBooleanMemberNotInitialized(init.pos, context); break; case "number": this.flowEnumErrorNumberMemberNotInitialized(init.pos, context); break; default: members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember")); } } } if (!this.match(types.braceR)) { this.expect(types.comma); } } return members; } flowEnumStringMembers(initializedMembers, defaultedMembers, { enumName }) { if (initializedMembers.length === 0) { return defaultedMembers; } else if (defaultedMembers.length === 0) { return initializedMembers; } else if (defaultedMembers.length > initializedMembers.length) { for (let _i = 0; _i < initializedMembers.length; _i++) { const member = initializedMembers[_i]; this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, { enumName }); } return defaultedMembers; } else { for (let _i2 = 0; _i2 < defaultedMembers.length; _i2++) { const member = defaultedMembers[_i2]; this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, { enumName }); } return initializedMembers; } } flowEnumParseExplicitType({ enumName }) { if (this.eatContextual("of")) { if (!this.match(types.name)) { throw this.flowEnumErrorInvalidExplicitType(this.state.start, { enumName, suppliedType: null }); } const { value } = this.state; this.next(); if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") { this.flowEnumErrorInvalidExplicitType(this.state.start, { enumName, suppliedType: value }); } return value; } return null; } flowEnumBody(node, { enumName, nameLoc }) { const explicitType = this.flowEnumParseExplicitType({ enumName }); this.expect(types.braceL); const members = this.flowEnumMembers({ enumName, explicitType }); switch (explicitType) { case "boolean": node.explicitType = true; node.members = members.booleanMembers; this.expect(types.braceR); return this.finishNode(node, "EnumBooleanBody"); case "number": node.explicitType = true; node.members = members.numberMembers; this.expect(types.braceR); return this.finishNode(node, "EnumNumberBody"); case "string": node.explicitType = true; node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, { enumName }); this.expect(types.braceR); return this.finishNode(node, "EnumStringBody"); case "symbol": node.members = members.defaultedMembers; this.expect(types.braceR); return this.finishNode(node, "EnumSymbolBody"); default: { const empty = () => { node.members = []; this.expect(types.braceR); return this.finishNode(node, "EnumStringBody"); }; node.explicitType = false; const boolsLen = members.booleanMembers.length; const numsLen = members.numberMembers.length; const strsLen = members.stringMembers.length; const defaultedLen = members.defaultedMembers.length; if (!boolsLen && !numsLen && !strsLen && !defaultedLen) { return empty(); } else if (!boolsLen && !numsLen) { node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, { enumName }); this.expect(types.braceR); return this.finishNode(node, "EnumStringBody"); } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) { for (let _i3 = 0, _members$defaultedMem = members.defaultedMembers; _i3 < _members$defaultedMem.length; _i3++) { const member = _members$defaultedMem[_i3]; this.flowEnumErrorBooleanMemberNotInitialized(member.start, { enumName, memberName: member.id.name }); } node.members = members.booleanMembers; this.expect(types.braceR); return this.finishNode(node, "EnumBooleanBody"); } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) { for (let _i4 = 0, _members$defaultedMem2 = members.defaultedMembers; _i4 < _members$defaultedMem2.length; _i4++) { const member = _members$defaultedMem2[_i4]; this.flowEnumErrorNumberMemberNotInitialized(member.start, { enumName, memberName: member.id.name }); } node.members = members.numberMembers; this.expect(types.braceR); return this.finishNode(node, "EnumNumberBody"); } else { this.flowEnumErrorInconsistentMemberValues(nameLoc, { enumName }); return empty(); } } } } flowParseEnumDeclaration(node) { const id = this.parseIdentifier(); node.id = id; node.body = this.flowEnumBody(this.startNode(), { enumName: id.name, nameLoc: id.start }); return this.finishNode(node, "EnumDeclaration"); } updateContext(prevType) { if (this.match(types.name) && this.state.value === "of" && prevType === types.name && this.input.slice(this.state.lastTokStart, this.state.lastTokEnd) === "interface") { this.state.exprAllowed = false; } else { super.updateContext(prevType); } } isLookaheadToken_lt() { const next = this.nextTokenStart(); if (this.input.charCodeAt(next) === 60) { const afterNext = this.input.charCodeAt(next + 1); return afterNext !== 60 && afterNext !== 61; } return false; } maybeUnwrapTypeCastExpression(node) { return node.type === "TypeCastExpression" ? node.expression : node; } }, _temp; }); 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+$/; const JsxErrors = Object.freeze({ AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression", MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>", MissingClosingTagElement: "Expected corresponding JSX closing tag for <%0>", UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text", UnterminatedJsxContent: "Unterminated JSX contents", UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?" }); types$1.j_oTag = new TokContext("<tag", false); types$1.j_cTag = new TokContext("</tag", false); types$1.j_expr = new TokContext("<tag>...</tag>", 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) { throw this.raise(this.state.start, JsxErrors.UnterminatedJsxContent); } 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) { throw this.raise(this.state.start, ErrorMessages.UnterminatedString); } 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(); if (node.type === "JSXNamespacedName") { return node; } 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") { this.raise(node.start, JsxErrors.AttributeIsEmpty); } return node; case types.jsxTagStart: case types.string: return this.parseExprAtom(); default: throw this.raise(this.state.start, JsxErrors.UnsupportedJsxValue); } } 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.parseMaybeAssignAllowIn(); 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, JsxErrors.MissingClosingTagFragment); } else if (!isFragment(openingElement) && isFragment(closingElement)) { this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name)); } else if (!isFragment(openingElement) && !isFragment(closingElement)) { if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) { this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name)); } } } if (isFragment(openingElement)) { node.openingFragment = openingElement; node.closingFragment = closingElement; } else { node.openingElement = openingElement; node.closingElement = closingElement; } node.children = children; if (this.isRelational("<")) { throw this.raise(this.state.start, JsxErrors.UnwrappedAdjacentJSXElements); } 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(refExpressionErrors) { 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(refExpressionErrors); } } 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.flags = void 0; this.var = []; this.lexical = []; this.functions = []; this.flags = flags; } } class ScopeHandler { constructor(raise, inModule) { this.scopeStack = []; this.undefinedExports = new Map(); this.undefinedPrivateNames = new Map(); this.raise = raise; this.inModule = inModule; } get inFunction() { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0; } get allowSuper() { return (this.currentThisScope().flags & SCOPE_SUPER) > 0; } get allowDirectSuper() { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0; } get inClass() { return (this.currentThisScope().flags & SCOPE_CLASS) > 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, ErrorMessages.VarRedeclaration, name); } } 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); } } } const PARAM = 0b0000, PARAM_YIELD = 0b0001, PARAM_AWAIT = 0b0010, PARAM_RETURN = 0b0100, PARAM_IN = 0b1000; class ProductionParameterHandler { constructor() { this.stacks = []; } enter(flags) { this.stacks.push(flags); } exit() { this.stacks.pop(); } currentFlags() { return this.stacks[this.stacks.length - 1]; } get hasAwait() { return (this.currentFlags() & PARAM_AWAIT) > 0; } get hasYield() { return (this.currentFlags() & PARAM_YIELD) > 0; } get hasReturn() { return (this.currentFlags() & PARAM_RETURN) > 0; } get hasIn() { return (this.currentFlags() & PARAM_IN) > 0; } } function functionFlags(isAsync, isGenerator) { return (isAsync ? PARAM_AWAIT : 0) | (isGenerator ? PARAM_YIELD : 0); } function nonNull(x) { if (x == null) { throw new Error(`Unexpected ${x} value.`); } return x; } function assert(x) { if (!x) { throw new Error("Assert fail"); } } const TSErrors = Object.freeze({ ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier", ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier", ConstructorHasTypeParameters: "Type parameters cannot appear on a constructor declaration.", DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.", DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.", DuplicateModifier: "Duplicate modifier: '%0'", EmptyHeritageClauseType: "'%0' list cannot be empty.", EmptyTypeArguments: "Type argument list cannot be empty.", EmptyTypeParameters: "Type parameter list cannot be empty.", IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier", IndexSignatureHasAccessibility: "Index signatures cannot have an accessibility modifier ('%0')", IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier", IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier", InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.", MixedLabeledAndUnlabeledElements: "Tuple members must all have names or all not have names.", OptionalTypeBeforeRequired: "A required element cannot follow an optional element.", PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.", PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.", PrivateElementHasAccessibility: "Private elements cannot have an accessibility modifier ('%0')", TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`", UnexpectedParameterModifier: "A parameter property is only allowed in a constructor implementation.", UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.", UnexpectedTypeAnnotation: "Did not expect a type annotation here.", UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.", UnsupportedImportTypeArgument: "Argument in a type import must be a string literal", UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.", UnsupportedSignatureParameterKind: "Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got %0" }); 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.match(types.bracketL) || this.match(types.braceL) || this.match(types.star) || this.match(types.ellipsis) || this.match(types.hash) || this.isLiteralPropertyName()) && !this.hasPrecedingLineBreak(); } 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; } tsParseModifiers(modified, allowedModifiers) { for (;;) { const startPos = this.state.start; const modifier = this.tsParseModifier(allowedModifiers); if (!modifier) break; if (Object.hasOwnProperty.call(modified, modifier)) { this.raise(startPos, TSErrors.DuplicateModifier, modifier); } modified[modifier] = true; } } 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)); } tsParseDelimitedListWorker(kind, parseElement, expectSuccess) { const result = []; for (;;) { 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)) { this.raise(this.state.start, TSErrors.UnsupportedImportTypeArgument); } 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); node.asserts = 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); if (node.params.length === 0) { this.raise(node.start, TSErrors.EmptyTypeParameters); } 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, 41).map(pattern => { if (pattern.type !== "Identifier" && pattern.type !== "RestElement" && pattern.type !== "ObjectPattern" && pattern.type !== "ArrayPattern") { this.raise(pattern.start, TSErrors.UnsupportedSignatureParameterKind, 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, false); 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(); node.nameType = this.eatContextual("as") ? this.tsParseType() : null; 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; let labeledElements = null; node.elementTypes.forEach(elementNode => { var _labeledElements; let { type } = elementNode; if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode.optional)) { this.raise(elementNode.start, TSErrors.OptionalTypeBeforeRequired); } seenOptionalElement = seenOptionalElement || type === "TSNamedTupleMember" && elementNode.optional || type === "TSOptionalType"; if (type === "TSRestType") { elementNode = elementNode.typeAnnotation; type = elementNode.type; } const isLabeled = type === "TSNamedTupleMember"; labeledElements = (_labeledElements = labeledElements) != null ? _labeledElements : isLabeled; if (labeledElements !== isLabeled) { this.raise(elementNode.start, TSErrors.MixedLabeledAndUnlabeledElements); } }); return this.finishNode(node, "TSTupleType"); } tsParseTupleElementType() { const { start: startPos, startLoc } = this.state; const rest = this.eat(types.ellipsis); let type = this.tsParseType(); const optional = this.eat(types.question); const labeled = this.eat(types.colon); if (labeled) { const labeledNode = this.startNodeAtNode(type); labeledNode.optional = optional; if (type.type === "TSTypeReference" && !type.typeParameters && type.typeName.type === "Identifier") { labeledNode.label = type.typeName; } else { this.raise(type.start, TSErrors.InvalidTupleMemberLabel); labeledNode.label = type; } labeledNode.elementType = this.tsParseType(); type = this.finishNode(labeledNode, "TSNamedTupleMember"); } else if (optional) { const optionalTypeNode = this.startNodeAtNode(type); optionalTypeNode.typeAnnotation = type; type = this.finishNode(optionalTypeNode, "TSOptionalType"); } if (rest) { const restNode = this.startNodeAt(startPos, startLoc); restNode.typeAnnotation = type; type = this.finishNode(restNode, "TSRestType"); } 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.bigint: 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(); node.literal = this.parseTemplate(false); return this.finishNode(node, "TSLiteralType"); } parseTemplateSubstitution() { if (this.state.inType) return this.tsParseType(); return super.parseTemplateSubstitution(); } tsParseThisTypeOrThisTypePredicate() { const thisKeyword = this.tsParseThisTypeNode(); if (this.isContextual("is") && !this.hasPrecedingLineBreak()) { return this.tsParseThisTypePredicate(thisKeyword); } else { return thisKeyword; } } 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.lookaheadCharCode() !== 46) { const node = this.startNode(); this.next(); return this.finishNode(node, type); } return this.tsParseTypeReference(); } case types.string: case types.num: case types.bigint: case types._true: case types._false: return this.tsParseLiteralTypeNode(); case types.plusMin: if (this.state.value === "-") { const node = this.startNode(); const nextToken = this.lookahead(); if (nextToken.type !== types.num && nextToken.type !== types.bigint) { throw this.unexpected(); } node.literal = this.parseMaybeUnary(); return this.finishNode(node, "TSLiteralType"); } break; case types._this: return this.tsParseThisTypeOrThisTypePredicate(); 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, TSErrors.UnexpectedReadonly); } } 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 asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this)); if (asserts && this.match(types._this)) { let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate(); if (thisTypePredicate.type === "TSThisType") { const node = this.startNodeAtNode(t); node.parameterName = thisTypePredicate; node.asserts = true; thisTypePredicate = this.finishNode(node, "TSTypePredicate"); } else { thisTypePredicate.asserts = true; } t.typeAnnotation = thisTypePredicate; return this.finishNode(t, "TSTypeAnnotation"); } const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this)); if (!typePredicateVariable) { if (!asserts) { return this.tsParseTypeAnnotation(false, t); } const node = this.startNodeAtNode(t); node.parameterName = this.parseIdentifier(); node.asserts = asserts; t.typeAnnotation = this.finishNode(node, "TSTypePredicate"); return this.finishNode(t, "TSTypeAnnotation"); } const type = this.tsParseTypeAnnotation(false); const node = this.startNodeAtNode(t); node.parameterName = typePredicateVariable; node.typeAnnotation = type; node.asserts = asserts; 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; } } tsParseTypePredicateAsserts() { if (!this.match(types.name) || this.state.value !== "asserts" || this.hasPrecedingLineBreak()) { return false; } const containsEsc = this.state.containsEsc; this.next(); if (!this.match(types.name) && !this.match(types._this)) { return false; } if (containsEsc) { this.raise(this.state.lastTokStart, ErrorMessages.InvalidEscapedReservedWord, "asserts"); } return true; } 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, TSErrors.EmptyHeritageClauseType, descriptor); } 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, "typescript interface declaration", BIND_TS_INTERFACE); 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, "typescript type alias", BIND_TS_TYPE); node.typeParameters = this.tsTryParseTypeParameters(); node.typeAnnotation = this.tsInType(() => { this.expect(types.eq); if (this.isContextual("intrinsic") && this.lookahead().type !== types.dot) { const node = this.startNode(); this.next(); return this.finishNode(node, "TSIntrinsicKeyword"); } return this.tsParseType(); }); 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.parseMaybeAssignAllowIn(); } return this.finishNode(node, "TSEnumMember"); } tsParseEnumDeclaration(node, isConst) { if (isConst) node.const = true; node.id = this.parseIdentifier(); this.checkLVal(node.id, "typescript enum declaration", isConst ? BIND_TS_CONST_ENUM : BIND_TS_ENUM); 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, "module or namespace declaration", BIND_TS_NAMESPACE); } if (this.eat(types.dot)) { const inner = this.startNode(); this.tsParseModuleOrNamespaceDeclaration(inner, true); node.body = inner; } else { this.scope.enter(SCOPE_TS_MODULE); this.prodParam.enter(PARAM); node.body = this.tsParseModuleBlock(); this.prodParam.exit(); this.scope.exit(); } 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)) { this.scope.enter(SCOPE_TS_MODULE); this.prodParam.enter(PARAM); node.body = this.tsParseModuleBlock(); this.prodParam.exit(); this.scope.exit(); } else { this.semicolon(); } return this.finishNode(node, "TSModuleDeclaration"); } tsParseImportEqualsDeclaration(node, isExport) { node.isExport = isExport || false; node.id = this.parseIdentifier(); this.checkLVal(node.id, "import equals declaration", BIND_LEXICAL); this.expect(types.eq); node.moduleReference = this.tsParseModuleReference(); this.semicolon(); return this.finishNode(node, "TSImportEqualsDeclaration"); } tsIsExternalModuleReference() { return this.isContextual("require") && this.lookaheadCharCode() === 40; } 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 result = this.tryParse(abort => f() || abort()); if (result.aborted || !result.node) return undefined; if (result.error) this.state = result.failState; return result.node; } tsTryParse(f) { const state = this.state.clone(); const result = f(); if (result !== undefined && result !== false) { return result; } else { this.state = state; return undefined; } } tsTryParseDeclare(nany) { if (this.isLineTerminator()) { return; } let starttype = this.state.type; let kind; if (this.isContextual("let")) { starttype = types._var; kind = "let"; } return this.tsInDeclareContext(() => { switch (starttype) { case types._function: nany.declare = true; return this.parseFunctionStatement(nany, false, true); case types._class: nany.declare = true; 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)) { this.scope.enter(SCOPE_TS_MODULE); this.prodParam.enter(PARAM); const mod = node; mod.global = true; mod.id = expr; mod.body = this.tsParseModuleBlock(); this.scope.exit(); this.prodParam.exit(); 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 oldMaybeInArrowParameters = this.state.maybeInArrowParameters; this.state.maybeInArrowParameters = true; 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; }); this.state.maybeInArrowParameters = oldMaybeInArrowParameters; 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)); })); if (node.params.length === 0) { this.raise(node.start, TSErrors.EmptyTypeArguments); } 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 !== undefined) { accessibility = this.parseAccessModifier(); readonly = !!this.tsParseModifier(["readonly"]); if (allowModifiers === false && (accessibility || readonly)) { this.raise(startPos, TSErrors.UnexpectedParameterModifier); } } 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") { this.raise(pp.start, TSErrors.UnsupportedParameterPropertyKind); } 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; } if (bodilessType === "TSDeclareFunction" && this.state.isDeclareContext) { this.raise(node.start, TSErrors.DeclareFunctionHasImplementation); if (node.declare) { super.parseFunctionBodyAndFinish(node, bodilessType, isMethod); return; } } super.parseFunctionBodyAndFinish(node, type, isMethod); } registerFunctionStatementId(node) { if (!node.body && node.id) { this.checkLVal(node.id, "function name", BIND_TS_AMBIENT); } else { super.registerFunctionStatementId(...arguments); } } tsCheckForInvalidTypeCasts(items) { items.forEach(node => { if ((node == null ? void 0 : node.type) === "TSTypeCastExpression") { this.raise(node.typeAnnotation.start, TSErrors.UnexpectedTypeAnnotation); } }); } toReferencedList(exprList, isInParens) { this.tsCheckForInvalidTypeCasts(exprList); return exprList; } parseArrayLike(...args) { const node = super.parseArrayLike(...args); if (node.type === "ArrayExpression") { this.tsCheckForInvalidTypeCasts(node.elements); } return node; } parseSubscript(base, startPos, startLoc, noCalls, state) { 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.atPossibleAsyncArrow(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); this.tsCheckForInvalidTypeCasts(node.arguments); node.typeParameters = typeArguments; return this.finishCallExpression(node, state.optionalChainMember); } else if (this.match(types.backQuote)) { const result = this.parseTaggedTemplateExpression(base, startPos, startLoc, state); result.typeParameters = typeArguments; return result; } } this.unexpected(); }); if (result) return result; } return super.parseSubscript(base, startPos, startLoc, noCalls, state); } 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) { 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"); this.reScan_lt_gt(); return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec); } return super.parseExprOp(left, leftStartPos, leftStartLoc, minPrec); } checkReservedWord(word, startLoc, checkKeywords, isBinding) {} checkDuplicateExports() {} parseImport(node) { if (this.match(types.name) || this.match(types.star) || this.match(types.braceL)) { const ahead = this.lookahead(); if (this.match(types.name) && ahead.type === types.eq) { return this.tsParseImportEqualsDeclaration(node); } if (this.isContextual("type") && ahead.type !== types.comma && !(ahead.type === types.name && ahead.value === "from")) { node.importKind = "type"; this.next(); } } if (!node.importKind) { node.importKind = "value"; } const importNode = super.parseImport(node); if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") { this.raise(importNode.start, "A type-only import can specify a default import or named bindings, but not both."); } return importNode; } 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 { if (this.isContextual("type") && this.lookahead().type === types.braceL) { this.next(); node.exportKind = "type"; } else { node.exportKind = "value"; } 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) { this.tsParseModifiers(member, ["declare"]); const accessibility = this.parseAccessModifier(); if (accessibility) member.accessibility = accessibility; this.tsParseModifiers(member, ["declare"]); const callParseClassMember = () => { super.parseClassMember(classBody, member, state); }; if (member.declare) { this.tsInDeclareContext(callParseClassMember); } else { callParseClassMember(); } } parseClassMemberWithIsStatic(classBody, member, state, isStatic) { this.tsParseModifiers(member, ["abstract", "readonly", "declare"]); const idx = this.tsTryParseIndexSignature(member); if (idx) { classBody.body.push(idx); if (member.abstract) { this.raise(member.start, TSErrors.IndexSignatureHasAbstract); } if (isStatic) { this.raise(member.start, TSErrors.IndexSignatureHasStatic); } if (member.accessibility) { this.raise(member.start, TSErrors.IndexSignatureHasAccessibility, member.accessibility); } if (member.declare) { this.raise(member.start, TSErrors.IndexSignatureHasDeclare); } return; } super.parseClassMemberWithIsStatic(classBody, member, state, isStatic); } parsePostMemberNameModifiers(methodOrProp) { const optional = this.eat(types.question); if (optional) methodOrProp.optional = true; if (methodOrProp.readonly && this.match(types.parenL)) { this.raise(methodOrProp.start, TSErrors.ClassMethodHasReadonly); } if (methodOrProp.declare && this.match(types.parenL)) { this.raise(methodOrProp.start, TSErrors.ClassMethodHasDeclare); } } 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, startPos, startLoc, refNeedsArrowPos) { if (!refNeedsArrowPos || !this.match(types.question)) { return super.parseConditional(expr, startPos, startLoc, refNeedsArrowPos); } const result = this.tryParse(() => super.parseConditional(expr, startPos, startLoc)); if (!result.node) { refNeedsArrowPos.start = result.error.pos || this.state.start; return expr; } if (result.error) this.state = result.failState; return result.node; } 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 && (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare)) { node.exportKind = "type"; } 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(node, isStatement, optionalId, node.declare ? BIND_TS_AMBIENT : BIND_CLASS); const typeParameters = this.tsTryParseTypeParameters(); if (typeParameters) node.typeParameters = typeParameters; } parseClassPropertyAnnotation(node) { if (!node.optional && this.eat(types.bang)) { node.definite = true; } const type = this.tsTryParseTypeAnnotation(); if (type) node.typeAnnotation = type; } parseClassProperty(node) { this.parseClassPropertyAnnotation(node); if (this.state.isDeclareContext && this.match(types.eq)) { this.raise(this.state.start, TSErrors.DeclareClassFieldHasInitializer); } return super.parseClassProperty(node); } parseClassPrivateProperty(node) { if (node.abstract) { this.raise(node.start, TSErrors.PrivateElementHasAbstract); } if (node.accessibility) { this.raise(node.start, TSErrors.PrivateElementHasAccessibility, node.accessibility); } this.parseClassPropertyAnnotation(node); return super.parseClassPrivateProperty(node); } pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) { const typeParameters = this.tsTryParseTypeParameters(); if (typeParameters && isConstructor) { this.raise(typeParameters.start, TSErrors.ConstructorHasTypeParameters); } 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) { var _jsx, _jsx2, _typeCast, _jsx3, _typeCast2, _jsx4, _typeCast3; let state; let jsx; let typeCast; if (this.match(types.jsxTagStart)) { state = this.state.clone(); jsx = this.tryParse(() => super.parseMaybeAssign(...args), state); if (!jsx.error) return jsx.node; const { context } = this.state; if (context[context.length - 1] === types$1.j_oTag) { context.length -= 2; } else if (context[context.length - 1] === types$1.j_expr) { context.length -= 1; } } if (!((_jsx = jsx) == null ? void 0 : _jsx.error) && !this.isRelational("<")) { return super.parseMaybeAssign(...args); } let typeParameters; state = state || this.state.clone(); const arrow = this.tryParse(abort => { var _typeParameters; typeParameters = this.tsParseTypeParameters(); const expr = super.parseMaybeAssign(...args); if (expr.type !== "ArrowFunctionExpression" || expr.extra && expr.extra.parenthesized) { abort(); } if (((_typeParameters = typeParameters) == null ? void 0 : _typeParameters.params.length) !== 0) { this.resetStartLocationFromNode(expr, typeParameters); } expr.typeParameters = typeParameters; return expr; }, state); if (!arrow.error && !arrow.aborted) return arrow.node; if (!jsx) { assert(!this.hasPlugin("jsx")); typeCast = this.tryParse(() => super.parseMaybeAssign(...args), state); if (!typeCast.error) return typeCast.node; } if ((_jsx2 = jsx) == null ? void 0 : _jsx2.node) { this.state = jsx.failState; return jsx.node; } if (arrow.node) { this.state = arrow.failState; return arrow.node; } if ((_typeCast = typeCast) == null ? void 0 : _typeCast.node) { this.state = typeCast.failState; return typeCast.node; } if ((_jsx3 = jsx) == null ? void 0 : _jsx3.thrown) throw jsx.error; if (arrow.thrown) throw arrow.error; if ((_typeCast2 = typeCast) == null ? void 0 : _typeCast2.thrown) throw typeCast.error; throw ((_jsx4 = jsx) == null ? void 0 : _jsx4.error) || arrow.error || ((_typeCast3 = typeCast) == null ? void 0 : _typeCast3.error); } parseMaybeUnary(refExpressionErrors) { if (!this.hasPlugin("jsx") && this.isRelational("<")) { return this.tsParseTypeAssertion(); } else { return super.parseMaybeUnary(refExpressionErrors); } } parseArrow(node) { if (this.match(types.colon)) { const result = this.tryParse(abort => { const returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon); if (this.canInsertSemicolon() || !this.match(types.arrow)) abort(); return returnType; }); if (result.aborted) return; if (!result.thrown) { if (result.error) this.state = result.failState; node.returnType = result.node; } } return super.parseArrow(node); } parseAssignableListItemTypes(param) { if (this.eat(types.question)) { if (param.type !== "Identifier" && !this.state.isDeclareContext && !this.state.inType) { this.raise(param.start, TSErrors.PatternIsOptional); } param.optional = true; } const type = this.tsTryParseTypeAnnotation(); if (type) param.typeAnnotation = type; this.resetEndLocation(param); return param; } toAssignable(node, isLHS = false) { switch (node.type) { case "TSTypeCastExpression": return super.toAssignable(this.typeCastToParameter(node), isLHS); case "TSParameterProperty": return super.toAssignable(node, isLHS); case "TSAsExpression": case "TSNonNullExpression": case "TSTypeAssertion": node.expression = this.toAssignable(node.expression, isLHS); return node; default: return super.toAssignable(node, isLHS); } } checkLVal(expr, contextDescription, ...args) { switch (expr.type) { case "TSTypeCastExpression": return; case "TSParameterProperty": this.checkLVal(expr.parameter, "parameter property", ...args); return; case "TSAsExpression": case "TSNonNullExpression": case "TSTypeAssertion": this.checkLVal(expr.expression, contextDescription, ...args); return; default: super.checkLVal(expr, contextDescription, ...args); 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, TSErrors.TypeAnnotationAfterAssign); } return node; } getTokenFromCode(code) { if (this.state.inType && (code === 62 || code === 60)) { return this.finishOp(types.relational, 1); } else { return super.getTokenFromCode(code); } } reScan_lt_gt() { if (this.match(types.relational)) { const code = this.input.charCodeAt(this.state.start); if (code === 60 || code === 62) { this.state.pos -= 1; this.readToken_lt_gt(code); } } } toAssignableList(exprList) { 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": if (!this.state.maybeInArrowParameters) { exprList[i] = this.typeCastToParameter(expr); } else { this.raise(expr.start, TSErrors.UnexpectedTypeCastInParameter); } break; } } return super.toAssignableList(...arguments); } typeCastToParameter(node) { node.expression.typeAnnotation = node.typeAnnotation; this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end); return node.expression; } 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 params = this.getObjectOrClassMethodParams(method); const firstParam = params[0]; const hasContextParam = firstParam && firstParam.type === "Identifier" && firstParam.name === "this"; return hasContextParam ? baseCount + 1 : baseCount; } parseCatchClauseParam() { const param = super.parseCatchClauseParam(); const type = this.tsTryParseTypeAnnotation(); if (type) { param.typeAnnotation = type; this.resetEndLocation(param); } return param; } tsInDeclareContext(cb) { const oldIsDeclareContext = this.state.isDeclareContext; this.state.isDeclareContext = true; try { return cb(); } finally { this.state.isDeclareContext = oldIsDeclareContext; } } }); 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 oldStrict = this.state.strict; 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, oldStrict); 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); } isExportDefaultSpecifier() { if (this.match(types._default)) { const next = this.nextTokenStart(); if (this.isUnparsedContextual(next, "from")) { if (this.input.startsWith(types.placeholder.label, this.nextTokenStartSince(next + 4))) { return true; } } } return super.isExportDefaultSpecifier(); } maybeParseExportDefaultSpecifier(node) { if (node.specifiers && node.specifiers.length > 0) { return true; } return super.maybeParseExportDefaultSpecifier(...arguments); } checkExport(node) { const { specifiers } = node; if (specifiers == null ? void 0 : 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); } }); var v8intrinsic = (superClass => class extends superClass { parseV8Intrinsic() { if (this.match(types.modulo)) { const v8IntrinsicStart = this.state.start; const node = this.startNode(); this.eat(types.modulo); if (this.match(types.name)) { const name = this.parseIdentifierName(this.state.start); const identifier = this.createIdentifier(node, name); identifier.type = "V8IntrinsicIdentifier"; if (this.match(types.parenL)) { return identifier; } } this.unexpected(v8IntrinsicStart); } } parseExprAtom() { return this.parseV8Intrinsic() || super.parseExprAtom(...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", "fsharp"]; const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"]; 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, "placeholders") && hasPlugin(plugins, "v8intrinsic")) { throw new Error("Cannot combine placeholders and v8intrinsic 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(", ")); } if (hasPlugin(plugins, "moduleAttributes")) { if (hasPlugin(plugins, "importAssertions")) { throw new Error("Cannot combine importAssertions and moduleAttributes plugins."); } const moduleAttributesVerionPluginOption = getPluginOption(plugins, "moduleAttributes", "version"); if (moduleAttributesVerionPluginOption !== "may-2020") { throw new Error("The 'moduleAttributes' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is 'may-2020'."); } } if (hasPlugin(plugins, "recordAndTuple") && !RECORD_AND_TUPLE_SYNTAX_TYPES.includes(getPluginOption(plugins, "recordAndTuple", "syntaxType"))) { throw new Error("'recordAndTuple' requires 'syntaxType' option whose value should be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(", ")); } } const mixinPlugins = { estree, jsx, flow, typescript, v8intrinsic, placeholders }; const mixinPluginNames = Object.keys(mixinPlugins); const defaultOptions = { sourceType: "script", sourceFilename: undefined, startLine: 1, allowAwaitOutsideFunction: false, allowReturnOutsideFunction: false, allowImportExportEverywhere: false, allowSuperOutsideMethod: false, allowUndeclaredExports: false, plugins: [], strictMode: null, ranges: false, tokens: false, createParenthesizedExpressions: false, errorRecovery: 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 State { constructor() { this.strict = void 0; this.curLine = void 0; this.startLoc = void 0; this.endLoc = void 0; this.errors = []; this.potentialArrowAt = -1; this.noArrowAt = []; this.noArrowParamsConversionAt = []; this.maybeInArrowParameters = false; this.inPipeline = false; this.inType = false; this.noAnonFunctionType = false; this.inPropertyName = false; this.hasFlowComment = false; this.isIterator = false; this.isDeclareContext = false; this.topicContext = { maxNumOfResolvableTopics: 0, maxTopicIndex: null }; this.soloAwait = false; this.inFSharpPipelineDirectBody = false; this.labels = []; this.decoratorStack = [[]]; 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.octalPositions = []; this.exportedIdentifiers = []; this.tokensLength = 0; } 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 ParserError { constructor(options, input) { super(); this.isLookahead = void 0; this.tokens = []; this.state = new State(); this.state.init(options); this.input = input; this.length = input.length; this.isLookahead = false; } pushToken(token) { this.tokens.length = this.state.tokensLength; this.tokens.push(token); ++this.state.tokensLength; } next() { if (!this.isLookahead) { this.checkKeywordEscapes(); if (this.options.tokens) { this.pushToken(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; } nextTokenStart() { return this.nextTokenStartSince(this.state.pos); } nextTokenStartSince(pos) { skipWhiteSpace.lastIndex = pos; const skip = skipWhiteSpace.exec(this.input); return pos + skip[0].length; } lookaheadCharCode() { return this.input.charCodeAt(this.nextTokenStart()); } 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 == null ? void 0 : curContext.preserveSpace)) this.skipSpace(); this.state.octalPositions = []; this.state.start = this.state.pos; this.state.startLoc = this.state.curPosition(); if (this.state.pos >= this.length) { this.finishToken(types.eof); return; } const override = curContext == null ? void 0 : curContext.override; if (override) { 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.pushToken(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) throw this.raise(start, ErrorMessages.UnterminatedComment); 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 (!isNewLine(ch) && ++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) { throw this.raise(this.state.pos, ErrorMessages.UnexpectedDigitAfterHash); } if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) { this.expectPlugin("recordAndTuple"); if (this.getPluginOption("recordAndTuple", "syntaxType") !== "hash") { throw this.raise(this.state.pos, next === 123 ? ErrorMessages.RecordExpressionHashIncorrectStartSyntaxType : ErrorMessages.TupleExpressionHashIncorrectStartSyntaxType); } if (next === 123) { this.finishToken(types.braceHashL); } else { this.finishToken(types.bracketHashL); } this.state.pos += 2; } else { this.finishOp(types.hash, 1); } } readToken_dot() { const next = this.input.charCodeAt(this.state.pos + 1); if (next >= 48 && next <= 57) { this.readNumber(true); return; } if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 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; let ch = this.input.charCodeAt(this.state.pos + 1); if (ch !== 33) return false; const start = this.state.pos; this.state.pos += 1; while (!isNewLine(ch) && ++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 (this.hasPlugin("recordAndTuple") && next === 125) { if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectEndSyntaxType); } this.finishOp(types.braceBarR, 2); return; } if (this.hasPlugin("recordAndTuple") && next === 93) { if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectEndSyntaxType); } this.finishOp(types.bracketBarR, 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 || this.hasPrecedingLineBreak())) { 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) { 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: if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) { if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectStartSyntaxType); } this.finishToken(types.bracketBarL); this.state.pos += 2; } else { ++this.state.pos; this.finishToken(types.bracketL); } return; case 93: ++this.state.pos; this.finishToken(types.bracketR); return; case 123: if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) { if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectStartSyntaxType); } this.finishToken(types.braceBarL); this.state.pos += 2; } else { ++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; } } throw this.raise(this.state.pos, ErrorMessages.InvalidOrUnexpectedToken, 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) { throw this.raise(start, ErrorMessages.UnterminatedRegExp); } const ch = this.input.charAt(this.state.pos); if (lineBreak.test(ch)) { throw this.raise(start, ErrorMessages.UnterminatedRegExp); } 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, ErrorMessages.DuplicateRegExpFlags); } } else if (isIdentifierChar(charCode) || charCode === 92) { this.raise(this.state.pos + 1, ErrorMessages.MalformedRegExpFlags); } else { break; } ++this.state.pos; mods += char; } this.finishToken(types.regexp, { pattern: content, flags: mods }); } readInt(radix, len, forceLen, allowNumSeparator = true) { 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 invalid = false; 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 (code === 95) { const prev = this.input.charCodeAt(this.state.pos - 1); const next = this.input.charCodeAt(this.state.pos + 1); if (allowedSiblings.indexOf(next) === -1) { this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator); } else if (forbiddenSiblings.indexOf(prev) > -1 || forbiddenSiblings.indexOf(next) > -1 || Number.isNaN(next)) { this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator); } if (!allowNumSeparator) { this.raise(this.state.pos, ErrorMessages.NumericSeparatorInEscapeSequence); } ++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) { if (this.options.errorRecovery && val <= 9) { val = 0; this.raise(this.state.start + i + 2, ErrorMessages.InvalidDigit, radix); } else if (forceLen) { val = 0; invalid = true; } else { break; } } ++this.state.pos; total = total * radix + val; } if (this.state.pos === start || len != null && this.state.pos - start !== len || invalid) { 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, ErrorMessages.InvalidDigit, radix); } const next = this.input.charCodeAt(this.state.pos); if (next === 110) { ++this.state.pos; isBigInt = true; } else if (next === 109) { throw this.raise(start, ErrorMessages.InvalidDecimal); } if (isIdentifierStart(this.input.codePointAt(this.state.pos))) { throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier); } 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; let isDecimal = false; let hasExponent = false; let isOctal = false; if (!startsWithDot && this.readInt(10) === null) { this.raise(start, ErrorMessages.InvalidNumber); } const hasLeadingZero = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48; if (hasLeadingZero) { const integer = this.input.slice(start, this.state.pos); if (this.state.strict) { this.raise(start, ErrorMessages.StrictOctalLiteral); } else { const underscorePos = integer.indexOf("_"); if (underscorePos > 0) { this.raise(underscorePos + start, ErrorMessages.ZeroDigitNumericSeparator); } } isOctal = hasLeadingZero && !/[89]/.test(integer); } let next = this.input.charCodeAt(this.state.pos); if (next === 46 && !isOctal) { ++this.state.pos; this.readInt(10); isFloat = true; next = this.input.charCodeAt(this.state.pos); } if ((next === 69 || next === 101) && !isOctal) { next = this.input.charCodeAt(++this.state.pos); if (next === 43 || next === 45) { ++this.state.pos; } if (this.readInt(10) === null) { this.raise(start, ErrorMessages.InvalidOrMissingExponent); } isFloat = true; hasExponent = true; next = this.input.charCodeAt(this.state.pos); } if (next === 110) { if (isFloat || hasLeadingZero) { this.raise(start, ErrorMessages.InvalidBigIntLiteral); } ++this.state.pos; isBigInt = true; } if (next === 109) { this.expectPlugin("decimal", this.state.pos); if (hasExponent || hasLeadingZero) { this.raise(start, ErrorMessages.InvalidDecimal); } ++this.state.pos; isDecimal = true; } if (isIdentifierStart(this.input.codePointAt(this.state.pos))) { throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier); } const str = this.input.slice(start, this.state.pos).replace(/[_mn]/g, ""); if (isBigInt) { this.finishToken(types.bigint, str); return; } if (isDecimal) { this.finishToken(types.decimal, str); return; } const val = isOctal ? 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, true, throwOnInvalid); ++this.state.pos; if (code !== null && code > 0x10ffff) { if (throwOnInvalid) { this.raise(codePos, ErrorMessages.InvalidCodePoint); } else { return null; } } } else { code = this.readHexChar(4, false, throwOnInvalid); } return code; } readString(quote) { let out = "", chunkStart = ++this.state.pos; for (;;) { if (this.state.pos >= this.length) { throw this.raise(this.state.start, ErrorMessages.UnterminatedString); } 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; this.state.lineStart = this.state.pos; } else if (isNewLine(ch)) { throw this.raise(this.state.start, ErrorMessages.UnterminatedString); } 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) { throw this.raise(this.state.start, ErrorMessages.UnterminatedTemplate); } 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, false, 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 ""; case 56: case 57: if (inTemplate) { return null; } else if (this.state.strict) { this.raise(this.state.pos - 1, ErrorMessages.StrictNumericEscape); } default: if (ch >= 48 && ch <= 55) { const codePos = this.state.pos - 1; const match = this.input.substr(this.state.pos - 1, 3).match(/^[0-7]+/); let octalStr = match[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) { return null; } else if (this.state.strict) { this.raise(codePos, ErrorMessages.StrictNumericEscape); } else { this.state.octalPositions.push(codePos); } } return String.fromCharCode(octal); } return String.fromCharCode(ch); } } readHexChar(len, forceLen, throwOnInvalid) { const codePos = this.state.pos; const n = this.readInt(16, len, forceLen, false); if (n === null) { if (throwOnInvalid) { this.raise(codePos, ErrorMessages.InvalidEscapeSequence); } else { this.state.pos = 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, ErrorMessages.MissingUnicodeEscape); continue; } ++this.state.pos; const esc = this.readCodePoint(true); if (esc !== null) { if (!identifierCheck(esc)) { this.raise(escStart, ErrorMessages.EscapedCharNotAnIdentifier); } 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 (this.state.isIterator && (!this.isIterator(word) || !this.state.inType)) { this.raise(this.state.pos, ErrorMessages.InvalidIdentifier, word); } this.finishToken(type, word); } checkKeywordEscapes() { const kw = this.state.type.keyword; if (kw && this.state.containsEsc) { this.raise(this.state.start, ErrorMessages.InvalidEscapedReservedWord, kw); } } 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 this.hasPrecedingLineBreak(); } 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; } } } 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; } expectRelational(op) { if (this.isRelational(op)) { this.next(); } else { this.unexpected(null, types.relational); } } isContextual(name) { return this.match(types.name) && this.state.value === name && !this.state.containsEsc; } isUnparsedContextual(nameStart, name) { const nameEnd = nameStart + name.length; return this.input.slice(nameStart, nameEnd) === name && (nameEnd === this.input.length || !isIdentifierChar(this.input.charCodeAt(nameEnd))); } isLookaheadContextual(name) { const next = this.nextTokenStart(); return this.isUnparsedContextual(next, 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.raiseWithData(pos != null ? pos : this.state.start, { missingPlugin: [name] }, `This experimental syntax requires enabling the parser plugin: '${name}'`); } return true; } expectOnePlugin(names, pos) { if (!names.some(n => this.hasPlugin(n))) { throw this.raiseWithData(pos != null ? pos : this.state.start, { missingPlugin: names }, `This experimental syntax requires enabling one of the following parser plugin(s): '${names.join(", ")}'`); } } tryParse(fn, oldState = this.state.clone()) { const abortSignal = { node: null }; try { const node = fn((node = null) => { abortSignal.node = node; throw abortSignal; }); if (this.state.errors.length > oldState.errors.length) { const failState = this.state; this.state = oldState; return { node, error: failState.errors[oldState.errors.length], thrown: false, aborted: false, failState }; } return { node, error: null, thrown: false, aborted: false, failState: null }; } catch (error) { const failState = this.state; this.state = oldState; if (error instanceof SyntaxError) { return { node: null, error, thrown: true, aborted: false, failState }; } if (error === abortSignal) { return { node: abortSignal.node, error: null, thrown: false, aborted: true, failState }; } throw error; } } checkExpressionErrors(refExpressionErrors, andThrow) { if (!refExpressionErrors) return false; const { shorthandAssign, doubleProto } = refExpressionErrors; if (!andThrow) return shorthandAssign >= 0 || doubleProto >= 0; if (shorthandAssign >= 0) { this.unexpected(shorthandAssign); } if (doubleProto >= 0) { this.raise(doubleProto, ErrorMessages.DuplicateProto); } } isLiteralPropertyName() { return this.match(types.name) || !!this.state.type.keyword || this.match(types.string) || this.match(types.num) || this.match(types.bigint) || this.match(types.decimal); } } class ExpressionErrors { constructor() { this.shorthandAssign = -1; this.doubleProto = -1; } } class Node { constructor(parser, pos, loc) { this.type = void 0; this.start = void 0; this.end = void 0; this.loc = void 0; this.range = void 0; this.leadingComments = void 0; this.trailingComments = void 0; this.innerComments = void 0; this.extra = void 0; this.type = ""; this.start = pos; this.end = 0; this.loc = new SourceLocation(loc); if (parser == null ? void 0 : parser.options.ranges) this.range = [pos, 0]; if (parser == null ? void 0 : 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); } } const unwrapParenthesizedExpression = node => { return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node; }; class LValParser extends NodeUtils { toAssignable(node, isLHS = false) { var _node$extra, _node$extra3; let parenthesized = undefined; if (node.type === "ParenthesizedExpression" || ((_node$extra = node.extra) == null ? void 0 : _node$extra.parenthesized)) { parenthesized = unwrapParenthesizedExpression(node); if (isLHS) { if (parenthesized.type === "Identifier") { this.expressionScope.recordParenthesizedIdentifierError(node.start, ErrorMessages.InvalidParenthesizedAssignment); } else if (parenthesized.type !== "MemberExpression") { this.raise(node.start, ErrorMessages.InvalidParenthesizedAssignment); } } else { this.raise(node.start, ErrorMessages.InvalidParenthesizedAssignment); } } 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++) { var _node$extra2; const prop = node.properties[i]; const isLast = i === last; this.toAssignableObjectExpressionProp(prop, isLast, isLHS); if (isLast && prop.type === "RestElement" && ((_node$extra2 = node.extra) == null ? void 0 : _node$extra2.trailingComma)) { this.raiseRestNotLast(node.extra.trailingComma); } } break; case "ObjectProperty": this.toAssignable(node.value, isLHS); break; case "SpreadElement": { this.checkToRestConversion(node); node.type = "RestElement"; const arg = node.argument; this.toAssignable(arg, isLHS); break; } case "ArrayExpression": node.type = "ArrayPattern"; this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingComma, isLHS); break; case "AssignmentExpression": if (node.operator !== "=") { this.raise(node.left.end, ErrorMessages.MissingEqInAssignment); } node.type = "AssignmentPattern"; delete node.operator; this.toAssignable(node.left, isLHS); break; case "ParenthesizedExpression": this.toAssignable(parenthesized, isLHS); break; } return node; } toAssignableObjectExpressionProp(prop, isLast, isLHS) { if (prop.type === "ObjectMethod") { const error = prop.kind === "get" || prop.kind === "set" ? ErrorMessages.PatternHasAccessor : ErrorMessages.PatternHasMethod; this.raise(prop.key.start, error); } else if (prop.type === "SpreadElement" && !isLast) { this.raiseRestNotLast(prop.start); } else { this.toAssignable(prop, isLHS); } } toAssignableList(exprList, trailingCommaPos, isLHS) { let end = exprList.length; if (end) { const last = exprList[end - 1]; if ((last == null ? void 0 : last.type) === "RestElement") { --end; } else if ((last == null ? void 0 : last.type) === "SpreadElement") { last.type = "RestElement"; let arg = last.argument; this.toAssignable(arg, isLHS); arg = unwrapParenthesizedExpression(arg); if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern" && arg.type !== "ObjectPattern") { this.unexpected(arg.start); } if (trailingCommaPos) { this.raiseTrailingCommaAfterRest(trailingCommaPos); } --end; } } for (let i = 0; i < end; i++) { const elt = exprList[i]; if (elt) { this.toAssignable(elt, isLHS); 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 == null ? void 0 : expr.type) === "ArrayExpression") { this.toReferencedListDeep(expr.elements); } } } parseSpread(refExpressionErrors, refNeedsArrowPos) { const node = this.startNode(); this.next(); node.argument = this.parseMaybeAssignAllowIn(refExpressionErrors, undefined, refNeedsArrowPos); 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, 93, true); return this.finishNode(node, "ArrayPattern"); } case types.braceL: return this.parseObjectLike(types.braceR, true); } return this.parseIdentifier(); } parseBindingList(close, closeCharCode, 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(closeCharCode); this.expect(close); break; } else { const decorators = []; if (this.match(types.at) && this.hasPlugin("decorators")) { this.raise(this.state.start, ErrorMessages.UnsupportedParameterDecorator); } 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) { var _startLoc, _startPos, _left; startLoc = (_startLoc = startLoc) != null ? _startLoc : this.state.startLoc; startPos = (_startPos = startPos) != null ? _startPos : this.state.start; left = (_left = left) != null ? _left : this.parseBindingAtom(); if (!this.eat(types.eq)) return left; const node = this.startNodeAt(startPos, startLoc); node.left = left; node.right = this.parseMaybeAssignAllowIn(); return this.finishNode(node, "AssignmentPattern"); } checkLVal(expr, contextDescription, bindingType = BIND_NONE, checkClashes, disallowLetBinding, strictModeChanged = false) { switch (expr.type) { case "Identifier": { const { name } = expr; if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(name, this.inModule) : isStrictBindOnlyReservedWord(name))) { this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.StrictEvalArguments : ErrorMessages.StrictEvalArgumentsBinding, name); } if (checkClashes) { if (checkClashes.has(name)) { this.raise(expr.start, ErrorMessages.ParamDupe); } else { checkClashes.add(name); } } if (disallowLetBinding && name === "let") { this.raise(expr.start, ErrorMessages.LetInLexicalBinding); } if (!(bindingType & BIND_NONE)) { this.scope.declareName(name, bindingType, expr.start); } break; } case "MemberExpression": if (bindingType !== BIND_NONE) { this.raise(expr.start, ErrorMessages.InvalidPropertyBindingPattern); } 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;else if (prop.type === "ObjectMethod") continue; this.checkLVal(prop, "object destructuring pattern", bindingType, checkClashes, disallowLetBinding); } 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, "array destructuring pattern", bindingType, checkClashes, disallowLetBinding); } } break; case "AssignmentPattern": this.checkLVal(expr.left, "assignment pattern", bindingType, checkClashes); break; case "RestElement": this.checkLVal(expr.argument, "rest element", bindingType, checkClashes); break; case "ParenthesizedExpression": this.checkLVal(expr.expression, "parenthesized expression", bindingType, checkClashes); break; default: { this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.InvalidLhs : ErrorMessages.InvalidLhsBinding, contextDescription); } } } checkToRestConversion(node) { if (node.argument.type !== "Identifier" && node.argument.type !== "MemberExpression") { this.raise(node.argument.start, ErrorMessages.InvalidRestAssignmentPattern); } } checkCommaAfterRest(close) { if (this.match(types.comma)) { if (this.lookaheadCharCode() === close) { this.raiseTrailingCommaAfterRest(this.state.start); } else { this.raiseRestNotLast(this.state.start); } } } raiseRestNotLast(pos) { throw this.raise(pos, ErrorMessages.ElementAfterRest); } raiseTrailingCommaAfterRest(pos) { this.raise(pos, ErrorMessages.RestTrailingComma); } } const kExpression = 0, kMaybeArrowParameterDeclaration = 1, kMaybeAsyncArrowParameterDeclaration = 2, kParameterDeclaration = 3; class ExpressionScope { constructor(type = kExpression) { this.type = void 0; this.type = type; } canBeArrowParameterDeclaration() { return this.type === kMaybeAsyncArrowParameterDeclaration || this.type === kMaybeArrowParameterDeclaration; } isCertainlyParameterDeclaration() { return this.type === kParameterDeclaration; } } class ArrowHeadParsingScope extends ExpressionScope { constructor(type) { super(type); this.errors = new Map(); } recordDeclarationError(pos, message) { this.errors.set(pos, message); } clearDeclarationError(pos) { this.errors.delete(pos); } iterateErrors(iterator) { this.errors.forEach(iterator); } } class ExpressionScopeHandler { constructor(raise) { this.stack = [new ExpressionScope()]; this.raise = raise; } enter(scope) { this.stack.push(scope); } exit() { this.stack.pop(); } recordParameterInitializerError(pos, message) { const { stack } = this; let i = stack.length - 1; let scope = stack[i]; while (!scope.isCertainlyParameterDeclaration()) { if (scope.canBeArrowParameterDeclaration()) { scope.recordDeclarationError(pos, message); } else { return; } scope = stack[--i]; } this.raise(pos, message); } recordParenthesizedIdentifierError(pos, message) { const { stack } = this; const scope = stack[stack.length - 1]; if (scope.isCertainlyParameterDeclaration()) { this.raise(pos, message); } else if (scope.canBeArrowParameterDeclaration()) { scope.recordDeclarationError(pos, message); } else { return; } } recordAsyncArrowParametersError(pos, message) { const { stack } = this; let i = stack.length - 1; let scope = stack[i]; while (scope.canBeArrowParameterDeclaration()) { if (scope.type === kMaybeAsyncArrowParameterDeclaration) { scope.recordDeclarationError(pos, message); } scope = stack[--i]; } } validateAsPattern() { const { stack } = this; const currentScope = stack[stack.length - 1]; if (!currentScope.canBeArrowParameterDeclaration()) return; currentScope.iterateErrors((message, pos) => { this.raise(pos, message); let i = stack.length - 2; let scope = stack[i]; while (scope.canBeArrowParameterDeclaration()) { scope.clearDeclarationError(pos); scope = stack[--i]; } }); } } function newParameterDeclarationScope() { return new ExpressionScope(kParameterDeclaration); } function newArrowHeadScope() { return new ArrowHeadParsingScope(kMaybeArrowParameterDeclaration); } function newAsyncArrowScope() { return new ArrowHeadParsingScope(kMaybeAsyncArrowParameterDeclaration); } function newExpressionScope() { return new ExpressionScope(); } class ExpressionParser extends LValParser { checkProto(prop, isRecord, protoRef, refExpressionErrors) { if (prop.type === "SpreadElement" || prop.type === "ObjectMethod" || prop.computed || prop.shorthand) { return; } const key = prop.key; const name = key.type === "Identifier" ? key.name : key.value; if (name === "__proto__") { if (isRecord) { this.raise(key.start, ErrorMessages.RecordNoProto); return; } if (protoRef.used) { if (refExpressionErrors) { if (refExpressionErrors.doubleProto === -1) { refExpressionErrors.doubleProto = key.start; } } else { this.raise(key.start, ErrorMessages.DuplicateProto); } } protoRef.used = true; } } shouldExitDescending(expr, potentialArrowAt) { return expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt; } getExpression() { let paramFlags = PARAM; if (this.hasPlugin("topLevelAwait") && this.inModule) { paramFlags |= PARAM_AWAIT; } this.scope.enter(SCOPE_PROGRAM); this.prodParam.enter(paramFlags); this.nextToken(); const expr = this.parseExpression(); if (!this.match(types.eof)) { this.unexpected(); } expr.comments = this.state.comments; expr.errors = this.state.errors; return expr; } parseExpression(disallowIn, refExpressionErrors) { if (disallowIn) { return this.disallowInAnd(() => this.parseExpressionBase(refExpressionErrors)); } return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors)); } parseExpressionBase(refExpressionErrors) { const startPos = this.state.start; const startLoc = this.state.startLoc; const expr = this.parseMaybeAssign(refExpressionErrors); if (this.match(types.comma)) { const node = this.startNodeAt(startPos, startLoc); node.expressions = [expr]; while (this.eat(types.comma)) { node.expressions.push(this.parseMaybeAssign(refExpressionErrors)); } this.toReferencedList(node.expressions); return this.finishNode(node, "SequenceExpression"); } return expr; } parseMaybeAssignDisallowIn(refExpressionErrors, afterLeftParse, refNeedsArrowPos) { return this.disallowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos)); } parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse, refNeedsArrowPos) { return this.allowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos)); } parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos) { const startPos = this.state.start; const startLoc = this.state.startLoc; if (this.isContextual("yield")) { if (this.prodParam.hasYield) { this.state.exprAllowed = true; let left = this.parseYield(); if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); } return left; } } let ownExpressionErrors; if (refExpressionErrors) { ownExpressionErrors = false; } else { refExpressionErrors = new ExpressionErrors(); ownExpressionErrors = true; } if (this.match(types.parenL) || this.match(types.name)) { this.state.potentialArrowAt = this.state.start; } let left = this.parseMaybeConditional(refExpressionErrors, 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 (this.match(types.eq)) { node.left = this.toAssignable(left, true); refExpressionErrors.doubleProto = -1; } else { node.left = left; } if (refExpressionErrors.shorthandAssign >= node.left.start) { refExpressionErrors.shorthandAssign = -1; } this.checkLVal(left, "assignment expression"); this.next(); node.right = this.parseMaybeAssign(); return this.finishNode(node, "AssignmentExpression"); } else if (ownExpressionErrors) { this.checkExpressionErrors(refExpressionErrors, true); } return left; } parseMaybeConditional(refExpressionErrors, refNeedsArrowPos) { const startPos = this.state.start; const startLoc = this.state.startLoc; const potentialArrowAt = this.state.potentialArrowAt; const expr = this.parseExprOps(refExpressionErrors); if (this.shouldExitDescending(expr, potentialArrowAt)) { return expr; } return this.parseConditional(expr, startPos, startLoc, refNeedsArrowPos); } parseConditional(expr, startPos, startLoc, refNeedsArrowPos) { if (this.eat(types.question)) { const node = this.startNodeAt(startPos, startLoc); node.test = expr; node.consequent = this.parseMaybeAssignAllowIn(); this.expect(types.colon); node.alternate = this.parseMaybeAssign(); return this.finishNode(node, "ConditionalExpression"); } return expr; } parseExprOps(refExpressionErrors) { const startPos = this.state.start; const startLoc = this.state.startLoc; const potentialArrowAt = this.state.potentialArrowAt; const expr = this.parseMaybeUnary(refExpressionErrors); if (this.shouldExitDescending(expr, potentialArrowAt)) { return expr; } return this.parseExprOp(expr, startPos, startLoc, -1); } parseExprOp(left, leftStartPos, leftStartLoc, minPrec) { let prec = this.state.type.binop; if (prec != null && (this.prodParam.hasIn || !this.match(types._in))) { if (prec > minPrec) { const op = this.state.type; if (op === types.pipeline) { this.expectPlugin("pipelineOperator"); if (this.state.inFSharpPipelineDirectBody) { return left; } this.state.inPipeline = true; this.checkPipelineAtInfixOperator(left, leftStartPos); } const node = this.startNodeAt(leftStartPos, leftStartLoc); node.left = left; node.operator = this.state.value; if (op === types.exponent && left.type === "UnaryExpression" && (this.options.createParenthesizedExpressions || !(left.extra && left.extra.parenthesized))) { this.raise(left.argument.start, ErrorMessages.UnexpectedTokenUnaryExponentiation); } const logical = op === types.logicalOR || op === types.logicalAND; const coalesce = op === types.nullishCoalescing; if (coalesce) { prec = types.logicalAND.binop; } this.next(); if (op === types.pipeline && this.getPluginOption("pipelineOperator", "proposal") === "minimal") { if (this.match(types.name) && this.state.value === "await" && this.prodParam.hasAwait) { throw this.raise(this.state.start, ErrorMessages.UnexpectedAwaitAfterPipelineBody); } } node.right = this.parseExprOpRightExpr(op, prec); this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression"); const nextOp = this.state.type; if (coalesce && (nextOp === types.logicalOR || nextOp === types.logicalAND) || logical && nextOp === types.nullishCoalescing) { throw this.raise(this.state.start, ErrorMessages.MixingCoalesceWithLogical); } return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec); } } return left; } parseExprOpRightExpr(op, prec) { const startPos = this.state.start; const startLoc = this.state.startLoc; switch (op) { case types.pipeline: switch (this.getPluginOption("pipelineOperator", "proposal")) { case "smart": return this.withTopicPermittingContext(() => { return this.parseSmartPipelineBody(this.parseExprOpBaseRightExpr(op, prec), startPos, startLoc); }); case "fsharp": return this.withSoloAwaitPermittingContext(() => { return this.parseFSharpPipelineBody(prec); }); } default: return this.parseExprOpBaseRightExpr(op, prec); } } parseExprOpBaseRightExpr(op, prec) { const startPos = this.state.start; const startLoc = this.state.startLoc; return this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, op.rightAssociative ? prec - 1 : prec); } parseMaybeUnary(refExpressionErrors) { if (this.isContextual("await") && this.isAwaitAllowed()) { return this.parseAwait(); } const update = this.match(types.incDec); const node = this.startNode(); if (this.state.type.prefix) { node.operator = this.state.value; node.prefix = true; if (this.match(types._throw)) { this.expectPlugin("throwExpressions"); } const isDelete = this.match(types._delete); this.next(); node.argument = this.parseMaybeUnary(); this.checkExpressionErrors(refExpressionErrors, true); if (this.state.strict && isDelete) { const arg = node.argument; if (arg.type === "Identifier") { this.raise(node.start, ErrorMessages.StrictDelete); } else if ((arg.type === "MemberExpression" || arg.type === "OptionalMemberExpression") && arg.property.type === "PrivateName") { this.raise(node.start, ErrorMessages.DeletePrivateField); } } if (!update) { return this.finishNode(node, "UnaryExpression"); } } return this.parseUpdate(node, update, refExpressionErrors); } parseUpdate(node, update, refExpressionErrors) { if (update) { this.checkLVal(node.argument, "prefix operation"); return this.finishNode(node, "UpdateExpression"); } const startPos = this.state.start; const startLoc = this.state.startLoc; let expr = this.parseExprSubscripts(refExpressionErrors); if (this.checkExpressionErrors(refExpressionErrors, false)) 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, "postfix operation"); this.next(); expr = this.finishNode(node, "UpdateExpression"); } return expr; } parseExprSubscripts(refExpressionErrors) { const startPos = this.state.start; const startLoc = this.state.startLoc; const potentialArrowAt = this.state.potentialArrowAt; const expr = this.parseExprAtom(refExpressionErrors); if (this.shouldExitDescending(expr, potentialArrowAt)) { return expr; } return this.parseSubscripts(expr, startPos, startLoc); } parseSubscripts(base, startPos, startLoc, noCalls) { const state = { optionalChainMember: false, maybeAsyncArrow: this.atPossibleAsyncArrow(base), stop: false }; do { base = this.parseSubscript(base, startPos, startLoc, noCalls, state); state.maybeAsyncArrow = false; } while (!state.stop); return base; } parseSubscript(base, startPos, startLoc, noCalls, state) { if (!noCalls && this.eat(types.doubleColon)) { return this.parseBind(base, startPos, startLoc, noCalls, state); } else if (this.match(types.backQuote)) { return this.parseTaggedTemplateExpression(base, startPos, startLoc, state); } let optional = false; if (this.match(types.questionDot)) { state.optionalChainMember = optional = true; if (noCalls && this.lookaheadCharCode() === 40) { state.stop = true; return base; } this.next(); } if (!noCalls && this.match(types.parenL)) { return this.parseCoverCallAndAsyncArrowHead(base, startPos, startLoc, state, optional); } else if (optional || this.match(types.bracketL) || this.eat(types.dot)) { return this.parseMember(base, startPos, startLoc, state, optional); } else { state.stop = true; return base; } } parseMember(base, startPos, startLoc, state, optional) { const node = this.startNodeAt(startPos, startLoc); const computed = this.eat(types.bracketL); node.object = base; node.computed = computed; const property = computed ? this.parseExpression() : this.parseMaybePrivateName(true); if (property.type === "PrivateName") { if (node.object.type === "Super") { this.raise(startPos, ErrorMessages.SuperPrivateField); } this.classScope.usePrivateName(property.id.name, property.start); } node.property = property; if (computed) { this.expect(types.bracketR); } if (state.optionalChainMember) { node.optional = optional; return this.finishNode(node, "OptionalMemberExpression"); } else { return this.finishNode(node, "MemberExpression"); } } parseBind(base, startPos, startLoc, noCalls, state) { 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); } parseCoverCallAndAsyncArrowHead(base, startPos, startLoc, state, optional) { const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; this.state.maybeInArrowParameters = true; this.next(); let node = this.startNodeAt(startPos, startLoc); node.callee = base; if (state.maybeAsyncArrow) { this.expressionScope.enter(newAsyncArrowScope()); } if (state.optionalChainMember) { node.optional = optional; } if (optional) { node.arguments = this.parseCallExpressionArguments(types.parenR, false); } else { node.arguments = this.parseCallExpressionArguments(types.parenR, state.maybeAsyncArrow, base.type === "Import", base.type !== "Super", node); } this.finishCallExpression(node, state.optionalChainMember); if (state.maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) { state.stop = true; this.expressionScope.validateAsPattern(); this.expressionScope.exit(); node = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startPos, startLoc), node); } else { if (state.maybeAsyncArrow) { this.expressionScope.exit(); } this.toReferencedArguments(node); } this.state.maybeInArrowParameters = oldMaybeInArrowParameters; return node; } toReferencedArguments(node, isParenthesizedExpr) { this.toReferencedListDeep(node.arguments, isParenthesizedExpr); } parseTaggedTemplateExpression(base, startPos, startLoc, state) { const node = this.startNodeAt(startPos, startLoc); node.tag = base; node.quasi = this.parseTemplate(true); if (state.optionalChainMember) { this.raise(startPos, ErrorMessages.OptionalChainingNoTemplate); } return this.finishNode(node, "TaggedTemplateExpression"); } atPossibleAsyncArrow(base) { return base.type === "Identifier" && base.name === "async" && this.state.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && base.start === this.state.potentialArrowAt; } finishCallExpression(node, optional) { if (node.callee.type === "Import") { if (node.arguments.length === 2) { if (!this.hasPlugin("moduleAttributes")) { this.expectPlugin("importAssertions"); } } if (node.arguments.length === 0 || node.arguments.length > 2) { this.raise(node.start, ErrorMessages.ImportCallArity, this.hasPlugin("importAssertions") || this.hasPlugin("moduleAttributes") ? "one or two arguments" : "one argument"); } else { for (let _i = 0, _node$arguments = node.arguments; _i < _node$arguments.length; _i++) { const arg = _node$arguments[_i]; if (arg.type === "SpreadElement") { this.raise(arg.start, ErrorMessages.ImportCallSpreadArgument); } } } } return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression"); } parseCallExpressionArguments(close, possibleAsyncArrow, dynamicImport, allowPlaceholder, nodeForExtra) { const elts = []; let first = true; const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; this.state.inFSharpPipelineDirectBody = false; while (!this.eat(close)) { if (first) { first = false; } else { this.expect(types.comma); if (this.match(close)) { if (dynamicImport && !this.hasPlugin("importAssertions") && !this.hasPlugin("moduleAttributes")) { this.raise(this.state.lastTokStart, ErrorMessages.ImportCallArgumentTrailingComma); } if (nodeForExtra) { this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart); } this.next(); break; } } elts.push(this.parseExprListItem(false, possibleAsyncArrow ? new ExpressionErrors() : undefined, possibleAsyncArrow ? { start: 0 } : undefined, allowPlaceholder)); } this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; return elts; } shouldParseAsyncArrow() { return this.match(types.arrow) && !this.canInsertSemicolon(); } parseAsyncArrowFromCallExpression(node, call) { var _call$extra; this.expect(types.arrow); this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingComma); return node; } parseNoCallExpr() { const startPos = this.state.start; const startLoc = this.state.startLoc; return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true); } parseExprAtom(refExpressionErrors) { 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: return this.parseSuper(); case types._import: node = this.startNode(); this.next(); if (this.match(types.dot)) { return this.parseImportMetaProperty(node); } if (!this.match(types.parenL)) { this.raise(this.state.lastTokStart, ErrorMessages.UnsupportedImport); } return this.finishNode(node, "Import"); case types._this: node = this.startNode(); this.next(); return this.finishNode(node, "ThisExpression"); case types.name: { const containsEsc = this.state.containsEsc; const id = this.parseIdentifier(); if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) { if (this.match(types._function)) { const last = this.state.context.length - 1; if (this.state.context[last] !== types$1.functionStatement) { throw new Error("Internal error"); } this.state.context[last] = types$1.functionExpression; this.next(); return this.parseFunction(this.startNodeAtNode(id), undefined, true); } else if (this.match(types.name)) { return this.parseAsyncArrowUnaryFunction(id); } } if (canBeArrow && this.match(types.arrow) && !this.canInsertSemicolon()) { this.next(); return this.parseArrowExpression(this.startNodeAtNode(id), [id], false); } return id; } case types._do: { return this.parseDo(); } 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.decimal: return this.parseLiteral(this.state.value, "DecimalLiteral"); 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.bracketBarL: case types.bracketHashL: { return this.parseArrayLike(this.state.type === types.bracketBarL ? types.bracketBarR : types.bracketR, false, true, refExpressionErrors); } case types.bracketL: { return this.parseArrayLike(types.bracketR, true, false, refExpressionErrors); } case types.braceBarL: case types.braceHashL: { return this.parseObjectLike(this.state.type === types.braceBarL ? types.braceBarR : types.braceR, false, true, refExpressionErrors); } case types.braceL: { return this.parseObjectLike(types.braceR, false, false, refExpressionErrors); } case types._function: return this.parseFunctionOrFunctionSent(); case types.at: this.parseDecorators(); case types._class: node = this.startNode(); this.takeDecorators(node); return this.parseClass(node, false); case types._new: return this.parseNewOrNewTarget(); 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, ErrorMessages.UnsupportedBind); } } case types.hash: { if (this.state.inPipeline) { node = this.startNode(); if (this.getPluginOption("pipelineOperator", "proposal") !== "smart") { this.raise(node.start, ErrorMessages.PrimaryTopicRequiresSmartPipeline); } this.next(); if (!this.primaryTopicReferenceIsAllowedInCurrentTopicContext()) { this.raise(node.start, ErrorMessages.PrimaryTopicNotAllowed); } this.registerTopicReference(); return this.finishNode(node, "PipelinePrimaryTopicReference"); } const nextCh = this.input.codePointAt(this.state.end); if (isIdentifierStart(nextCh) || nextCh === 92) { const start = this.state.start; node = this.parseMaybePrivateName(true); if (this.match(types._in)) { this.expectPlugin("privateIn"); this.classScope.usePrivateName(node.id.name, node.start); } else if (this.hasPlugin("privateIn")) { this.raise(this.state.start, ErrorMessages.PrivateInExpectedIn, node.id.name); } else { throw this.unexpected(start); } return node; } } case types.relational: { if (this.state.value === "<") { const lookaheadCh = this.input.codePointAt(this.nextTokenStart()); if (isIdentifierStart(lookaheadCh) || lookaheadCh === 62) { this.expectOnePlugin(["jsx", "flow", "typescript"]); } } } default: throw this.unexpected(); } } parseAsyncArrowUnaryFunction(id) { const node = this.startNodeAtNode(id); this.prodParam.enter(functionFlags(true, this.prodParam.hasYield)); const params = [this.parseIdentifier()]; this.prodParam.exit(); if (this.hasPrecedingLineBreak()) { this.raise(this.state.pos, ErrorMessages.LineTerminatorBeforeArrow); } this.expect(types.arrow); this.parseArrowExpression(node, params, true); return node; } parseDo() { 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"); } parseSuper() { const node = this.startNode(); this.next(); if (this.match(types.parenL) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) { this.raise(node.start, ErrorMessages.SuperNotAllowed); } else if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) { this.raise(node.start, ErrorMessages.UnexpectedSuper); } if (!this.match(types.parenL) && !this.match(types.bracketL) && !this.match(types.dot)) { this.raise(node.start, ErrorMessages.UnsupportedSuper); } return this.finishNode(node, "Super"); } parseBooleanLiteral() { const node = this.startNode(); node.value = this.match(types._true); this.next(); return this.finishNode(node, "BooleanLiteral"); } parseMaybePrivateName(isPrivateNameAllowed) { const isPrivate = this.match(types.hash); if (isPrivate) { this.expectOnePlugin(["classPrivateProperties", "classPrivateMethods"]); if (!isPrivateNameAllowed) { this.raise(this.state.pos, ErrorMessages.UnexpectedPrivateField); } 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); } } parseFunctionOrFunctionSent() { const node = this.startNode(); this.next(); if (this.prodParam.hasYield && this.match(types.dot)) { const meta = this.createIdentifier(this.startNodeAtNode(node), "function"); this.next(); 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, ErrorMessages.UnsupportedMetaProperty, meta.name, propertyName); } return this.finishNode(node, "MetaProperty"); } parseImportMetaProperty(node) { const id = this.createIdentifier(this.startNodeAtNode(node), "import"); this.next(); if (this.isContextual("meta")) { if (!this.inModule) { this.raiseWithData(id.start, { code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED" }, ErrorMessages.ImportMetaOutsideModule); } 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.next(); this.expressionScope.enter(newArrowHeadScope()); const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; this.state.maybeInArrowParameters = true; this.state.inFSharpPipelineDirectBody = false; const innerStartPos = this.state.start; const innerStartLoc = this.state.startLoc; const exprList = []; const refExpressionErrors = new ExpressionErrors(); 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(41); break; } else { exprList.push(this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem, refNeedsArrowPos)); } } const innerEndPos = this.state.lastTokEnd; const innerEndLoc = this.state.lastTokEndLoc; this.expect(types.parenR); this.state.maybeInArrowParameters = oldMaybeInArrowParameters; this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; let arrowNode = this.startNodeAt(startPos, startLoc); if (canBeArrow && this.shouldParseArrow() && (arrowNode = this.parseArrow(arrowNode))) { this.expressionScope.validateAsPattern(); this.expressionScope.exit(); this.parseArrowExpression(arrowNode, exprList, false); return arrowNode; } this.expressionScope.exit(); if (!exprList.length) { this.unexpected(this.state.lastTokStart); } if (optionalCommaStart) this.unexpected(optionalCommaStart); if (spreadStart) this.unexpected(spreadStart); this.checkExpressionErrors(refExpressionErrors, true); 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; } parseNewOrNewTarget() { const node = this.startNode(); this.next(); if (this.match(types.dot)) { const meta = this.createIdentifier(this.startNodeAtNode(node), "new"); this.next(); const metaProp = this.parseMetaProperty(node, meta, "target"); if (!this.scope.inNonArrowFunction && !this.scope.inClass) { let error = ErrorMessages.UnexpectedNewTarget; if (this.hasPlugin("classProperties")) { error += " or class properties"; } this.raise(metaProp.start, error); } return metaProp; } return this.parseNew(node); } parseNew(node) { node.callee = this.parseNoCallExpr(); if (node.callee.type === "Import") { this.raise(node.callee.start, ErrorMessages.ImportCallNotNewExpression); } else if (node.callee.type === "OptionalMemberExpression" || node.callee.type === "OptionalCallExpression") { this.raise(this.state.lastTokEnd, ErrorMessages.OptionalChainingNoNew); } else if (this.eat(types.questionDot)) { this.raise(this.state.start, ErrorMessages.OptionalChainingNoNew); } 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.start + 1, ErrorMessages.InvalidEscapeSequenceTemplate); } } 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.parseTemplateSubstitution()); this.expect(types.braceR); node.quasis.push(curElt = this.parseTemplateElement(isTagged)); } this.next(); return this.finishNode(node, "TemplateLiteral"); } parseTemplateSubstitution() { return this.parseExpression(); } parseObjectLike(close, isPattern, isRecord, refExpressionErrors) { if (isRecord) { this.expectPlugin("recordAndTuple"); } const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; this.state.inFSharpPipelineDirectBody = false; const propHash = Object.create(null); let first = true; const node = this.startNode(); node.properties = []; this.next(); while (!this.match(close)) { if (first) { first = false; } else { this.expect(types.comma); if (this.match(close)) { this.addExtra(node, "trailingComma", this.state.lastTokStart); break; } } const prop = this.parsePropertyDefinition(isPattern, refExpressionErrors); if (!isPattern) { this.checkProto(prop, isRecord, propHash, refExpressionErrors); } if (isRecord && prop.type !== "ObjectProperty" && prop.type !== "SpreadElement") { this.raise(prop.start, ErrorMessages.InvalidRecordProperty); } if (prop.shorthand) { this.addExtra(prop, "shorthand", true); } node.properties.push(prop); } this.state.exprAllowed = false; this.next(); this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; let type = "ObjectExpression"; if (isPattern) { type = "ObjectPattern"; } else if (isRecord) { type = "RecordExpression"; } return this.finishNode(node, type); } maybeAsyncOrAccessorProp(prop) { return !prop.computed && prop.key.type === "Identifier" && (this.isLiteralPropertyName() || this.match(types.bracketL) || this.match(types.star)); } parsePropertyDefinition(isPattern, refExpressionErrors) { let decorators = []; if (this.match(types.at)) { if (this.hasPlugin("decorators")) { this.raise(this.state.start, ErrorMessages.UnsupportedPropertyDecorator); } while (this.match(types.at)) { decorators.push(this.parseDecorator()); } } const prop = this.startNode(); let isGenerator = false; let isAsync = false; let isAccessor = 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(125); return this.finishNode(prop, "RestElement"); } return this.parseSpread(); } if (decorators.length) { prop.decorators = decorators; decorators = []; } prop.method = false; if (isPattern || refExpressionErrors) { startPos = this.state.start; startLoc = this.state.startLoc; } if (!isPattern) { isGenerator = this.eat(types.star); } const containsEsc = this.state.containsEsc; const key = this.parsePropertyName(prop, false); if (!isPattern && !isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) { const keyName = key.name; if (keyName === "async" && !this.hasPrecedingLineBreak()) { isAsync = true; isGenerator = this.eat(types.star); this.parsePropertyName(prop, false); } if (keyName === "get" || keyName === "set") { isAccessor = true; prop.kind = keyName; if (this.match(types.star)) { isGenerator = true; this.raise(this.state.pos, ErrorMessages.AccessorIsGenerator, keyName); this.next(); } this.parsePropertyName(prop, false); } } this.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors); return prop; } getGetterSetterExpectedParamCount(method) { return method.kind === "get" ? 0 : 1; } getObjectOrClassMethodParams(method) { return method.params; } checkGetterSetterParams(method) { var _params; const paramCount = this.getGetterSetterExpectedParamCount(method); const params = this.getObjectOrClassMethodParams(method); const start = method.start; if (params.length !== paramCount) { if (method.kind === "get") { this.raise(start, ErrorMessages.BadGetterArity); } else { this.raise(start, ErrorMessages.BadSetterArity); } } if (method.kind === "set" && ((_params = params[params.length - 1]) == null ? void 0 : _params.type) === "RestElement") { this.raise(start, ErrorMessages.BadSetterRestParameter); } } parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) { if (isAccessor) { this.parseMethod(prop, isGenerator, false, false, false, "ObjectMethod"); this.checkGetterSetterParams(prop); return prop; } 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"); } } parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) { prop.shorthand = false; if (this.eat(types.colon)) { prop.value = isPattern ? this.parseMaybeDefault(this.state.start, this.state.startLoc) : this.parseMaybeAssignAllowIn(refExpressionErrors); return this.finishNode(prop, "ObjectProperty"); } if (!prop.computed && prop.key.type === "Identifier") { this.checkReservedWord(prop.key.name, prop.key.start, true, false); if (isPattern) { prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone()); } else if (this.match(types.eq) && refExpressionErrors) { if (refExpressionErrors.shorthandAssign === -1) { refExpressionErrors.shorthandAssign = 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, isAccessor, refExpressionErrors) { const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) || this.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors); if (!node) this.unexpected(); return node; } parsePropertyName(prop, isPrivateNameAllowed) { if (this.eat(types.bracketL)) { prop.computed = true; prop.key = this.parseMaybeAssignAllowIn(); 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.match(types.bigint) || this.match(types.decimal) ? this.parseExprAtom() : this.parseMaybePrivateName(isPrivateNameAllowed); 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) { this.initFunction(node, isAsync); node.generator = !!isGenerator; const allowModifiers = isConstructor; this.scope.enter(SCOPE_FUNCTION | SCOPE_SUPER | (inClassScope ? SCOPE_CLASS : 0) | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); this.prodParam.enter(functionFlags(isAsync, node.generator)); this.parseFunctionParams(node, allowModifiers); this.parseFunctionBodyAndFinish(node, type, true); this.prodParam.exit(); this.scope.exit(); return node; } parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) { if (isTuple) { this.expectPlugin("recordAndTuple"); } const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; this.state.inFSharpPipelineDirectBody = false; const node = this.startNode(); this.next(); node.elements = this.parseExprList(close, !isTuple, refExpressionErrors, node); this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; return this.finishNode(node, isTuple ? "TupleExpression" : "ArrayExpression"); } parseArrowExpression(node, params, isAsync, trailingCommaPos) { this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW); let flags = functionFlags(isAsync, false); if (!this.match(types.bracketL) && this.prodParam.hasIn) { flags |= PARAM_IN; } this.prodParam.enter(flags); this.initFunction(node, isAsync); const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; if (params) { this.state.maybeInArrowParameters = true; this.setArrowFunctionParameters(node, params, trailingCommaPos); } this.state.maybeInArrowParameters = false; this.parseFunctionBody(node, true); this.prodParam.exit(); this.scope.exit(); this.state.maybeInArrowParameters = oldMaybeInArrowParameters; return this.finishNode(node, "ArrowFunctionExpression"); } setArrowFunctionParameters(node, params, trailingCommaPos) { node.params = this.toAssignableList(params, trailingCommaPos, 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); this.expressionScope.enter(newExpressionScope()); if (isExpression) { node.body = this.parseMaybeAssign(); this.checkParams(node, false, allowExpression, false); } else { const oldStrict = this.state.strict; const oldLabels = this.state.labels; this.state.labels = []; this.prodParam.enter(this.prodParam.currentFlags() | PARAM_RETURN); node.body = this.parseBlock(true, false, hasStrictModeDirective => { const nonSimple = !this.isSimpleParamList(node.params); if (hasStrictModeDirective && nonSimple) { const errorPos = (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.end : node.start; this.raise(errorPos, ErrorMessages.IllegalLanguageModeDirective); } const strictModeChanged = !oldStrict && this.state.strict; this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged); if (this.state.strict && node.id) { this.checkLVal(node.id, "function name", BIND_OUTSIDE, undefined, undefined, strictModeChanged); } }); this.prodParam.exit(); this.expressionScope.exit(); this.state.labels = oldLabels; } } 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, strictModeChanged = true) { const checkClashes = new Set(); for (let _i2 = 0, _node$params = node.params; _i2 < _node$params.length; _i2++) { const param = _node$params[_i2]; this.checkLVal(param, "function parameter list", BIND_VAR, allowDuplicates ? null : checkClashes, undefined, strictModeChanged); } } parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) { const elts = []; let first = true; while (!this.eat(close)) { if (first) { first = false; } else { this.expect(types.comma); if (this.match(close)) { if (nodeForExtra) { this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart); } this.next(); break; } } elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors)); } return elts; } parseExprListItem(allowEmpty, refExpressionErrors, refNeedsArrowPos, allowPlaceholder) { let elt; if (this.match(types.comma)) { if (!allowEmpty) { this.raise(this.state.pos, ErrorMessages.UnexpectedToken, ","); } elt = null; } else if (this.match(types.ellipsis)) { const spreadNodeStartPos = this.state.start; const spreadNodeStartLoc = this.state.startLoc; elt = this.parseParenItem(this.parseSpread(refExpressionErrors, refNeedsArrowPos), spreadNodeStartPos, spreadNodeStartLoc); } else if (this.match(types.question)) { this.expectPlugin("partialApplication"); if (!allowPlaceholder) { this.raise(this.state.start, ErrorMessages.UnexpectedArgumentPlaceholder); } const node = this.startNode(); this.next(); elt = this.finishNode(node, "ArgumentPlaceholder"); } else { elt = this.parseMaybeAssignAllowIn(refExpressionErrors, 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; const { start, type } = this.state; if (type === types.name) { name = this.state.value; } else if (type.keyword) { name = type.keyword; const curContext = this.curContext(); if ((type === types._class || type === types._function) && (curContext === types$1.functionStatement || curContext === types$1.functionExpression)) { this.state.context.pop(); } } else { throw this.unexpected(); } if (liberal) { this.state.type = types.name; } else { this.checkReservedWord(name, start, !!type.keyword, false); } this.next(); return name; } checkReservedWord(word, startLoc, checkKeywords, isBinding) { if (this.prodParam.hasYield && word === "yield") { this.raise(startLoc, ErrorMessages.YieldBindingIdentifier); return; } if (word === "await") { if (this.prodParam.hasAwait) { this.raise(startLoc, ErrorMessages.AwaitBindingIdentifier); return; } else { this.expressionScope.recordAsyncArrowParametersError(startLoc, ErrorMessages.AwaitBindingIdentifier); } } if (this.scope.inClass && !this.scope.inNonArrowFunction && word === "arguments") { this.raise(startLoc, ErrorMessages.ArgumentsInClass); return; } if (checkKeywords && isKeyword(word)) { this.raise(startLoc, ErrorMessages.UnexpectedKeyword, word); return; } const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord; if (reservedTest(word, this.inModule)) { if (!this.prodParam.hasAwait && word === "await") { this.raise(startLoc, this.hasPlugin("topLevelAwait") ? ErrorMessages.AwaitNotInAsyncContext : ErrorMessages.AwaitNotInAsyncFunction); } else { this.raise(startLoc, ErrorMessages.UnexpectedReservedWord, word); } } } isAwaitAllowed() { if (this.scope.inFunction) return this.prodParam.hasAwait; if (this.options.allowAwaitOutsideFunction) return true; if (this.hasPlugin("topLevelAwait")) { return this.inModule && this.prodParam.hasAwait; } return false; } parseAwait() { const node = this.startNode(); this.next(); this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.AwaitExpressionFormalParameter); if (this.eat(types.star)) { this.raise(node.start, ErrorMessages.ObsoleteAwaitStar); } if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) { if (this.hasPrecedingLineBreak() || this.match(types.plusMin) || this.match(types.parenL) || this.match(types.bracketL) || this.match(types.backQuote) || this.match(types.regexp) || this.match(types.slash) || this.hasPlugin("v8intrinsic") && this.match(types.modulo)) { this.ambiguousScriptDifferentAst = true; } else { this.sawUnambiguousESM = true; } } if (!this.state.soloAwait) { node.argument = this.parseMaybeUnary(); } return this.finishNode(node, "AwaitExpression"); } parseYield() { const node = this.startNode(); this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.YieldInParameter); this.next(); if (this.match(types.semi) || !this.match(types.star) && !this.state.type.startsExpr || this.hasPrecedingLineBreak()) { node.delegate = false; node.argument = null; } else { node.delegate = this.eat(types.star); node.argument = this.parseMaybeAssign(); } return this.finishNode(node, "YieldExpression"); } checkPipelineAtInfixOperator(left, leftStartPos) { if (this.getPluginOption("pipelineOperator", "proposal") === "smart") { if (left.type === "SequenceExpression") { this.raise(leftStartPos, ErrorMessages.PipelineHeadSequenceExpression); } } } parseSmartPipelineBody(childExpression, startPos, startLoc) { this.checkSmartPipelineBodyEarlyErrors(childExpression, startPos); return this.parseSmartPipelineBodyInStyle(childExpression, startPos, startLoc); } checkSmartPipelineBodyEarlyErrors(childExpression, startPos) { if (this.match(types.arrow)) { throw this.raise(this.state.start, ErrorMessages.PipelineBodyNoArrow); } else if (childExpression.type === "SequenceExpression") { this.raise(startPos, ErrorMessages.PipelineBodySequenceExpression); } } parseSmartPipelineBodyInStyle(childExpression, startPos, startLoc) { const bodyNode = this.startNodeAt(startPos, startLoc); const isSimpleReference = this.isSimpleReference(childExpression); if (isSimpleReference) { bodyNode.callee = childExpression; } else { if (!this.topicReferenceWasUsedInCurrentTopicContext()) { this.raise(startPos, ErrorMessages.PipelineTopicUnused); } bodyNode.expression = childExpression; } return this.finishNode(bodyNode, isSimpleReference ? "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; } } withSoloAwaitPermittingContext(callback) { const outerContextSoloAwaitState = this.state.soloAwait; this.state.soloAwait = true; try { return callback(); } finally { this.state.soloAwait = outerContextSoloAwaitState; } } allowInAnd(callback) { const flags = this.prodParam.currentFlags(); const prodParamToSet = PARAM_IN & ~flags; if (prodParamToSet) { this.prodParam.enter(flags | PARAM_IN); try { return callback(); } finally { this.prodParam.exit(); } } return callback(); } disallowInAnd(callback) { const flags = this.prodParam.currentFlags(); const prodParamToClear = PARAM_IN & flags; if (prodParamToClear) { this.prodParam.enter(flags & ~PARAM_IN); try { return callback(); } finally { this.prodParam.exit(); } } return callback(); } 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; } parseFSharpPipelineBody(prec) { const startPos = this.state.start; const startLoc = this.state.startLoc; this.state.potentialArrowAt = this.state.start; const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; this.state.inFSharpPipelineDirectBody = true; const ret = this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, prec); this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; return ret; } } const loopLabel = { kind: "loop" }, switchLabel = { kind: "switch" }; const FUNC_NO_FLAGS = 0b000, FUNC_STATEMENT = 0b001, FUNC_HANGING_STATEMENT = 0b010, FUNC_NULLABLE_ID = 0b100; const loneSurrogate = /[\uD800-\uDFFF]/u; 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.options.allowUndeclaredExports && 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, ErrorMessages.ModuleExportUndefined, name); } } file.program = this.finishNode(program, "Program"); file.comments = this.state.comments; if (this.options.tokens) file.tokens = this.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; } const next = this.nextTokenStart(); 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.lookaheadCharCode() === 46) break; if (context) { if (this.state.strict) { this.raise(this.state.start, ErrorMessages.StrictFunction); } else if (context !== "if" && context !== "label") { this.raise(this.state.start, ErrorMessages.SloppyFunction); } } 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.raise(this.state.start, ErrorMessages.UnexpectedLexicalDeclaration); } 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._import: { const nextTokenCharCode = this.lookaheadCharCode(); if (nextTokenCharCode === 40 || nextTokenCharCode === 46) { break; } } case types._export: { if (!this.options.allowImportExportEverywhere && !topLevel) { this.raise(this.state.start, ErrorMessages.UnexpectedImportExport); } 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.raise(this.state.start, ErrorMessages.AsyncFunctionInSingleStatementContext); } 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.raiseWithData(node.start, { code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED" }, ErrorMessages.ImportOutsideModule); } } 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, ErrorMessages.DecoratorExportClass); } } else if (!this.canHaveLeadingDecorator()) { throw this.raise(this.state.start, ErrorMessages.UnexpectedLeadingDecorator); } } 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.parseExprSubscripts(); } 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, ErrorMessages.IllegalBreakContinue, 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.isAwaitAllowed() && 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 refExpressionErrors = new ExpressionErrors(); const init = this.parseExpression(true, refExpressionErrors); if (this.match(types._in) || this.isContextual("of")) { this.toAssignable(init, true); const description = this.isContextual("of") ? "for-of statement" : "for-in statement"; this.checkLVal(init, description); return this.parseForIn(node, init, awaitAt); } else { this.checkExpressionErrors(refExpressionErrors, true); } 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.prodParam.hasReturn && !this.options.allowReturnOutsideFunction) { this.raise(this.state.start, ErrorMessages.IllegalReturn); } 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, ErrorMessages.MultipleDefaultsInSwitch); } 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 (this.hasPrecedingLineBreak()) { this.raise(this.state.lastTokEnd, ErrorMessages.NewlineAfterThrow); } node.argument = this.parseExpression(); this.semicolon(); return this.finishNode(node, "ThrowStatement"); } parseCatchClauseParam() { const param = this.parseBindingAtom(); const simple = param.type === "Identifier"; this.scope.enter(simple ? SCOPE_SIMPLE_CATCH : 0); this.checkLVal(param, "catch clause", BIND_LEXICAL); return param; } 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.parseCatchClauseParam(); 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, ErrorMessages.NoCatchOrFinally); } 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, ErrorMessages.StrictWith); } 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, ErrorMessages.LabelRedeclaration, maybeName); } } 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, afterBlockParse) { const node = this.startNode(); this.expect(types.braceL); if (createNewLexicalScope) { this.scope.enter(SCOPE_OTHER); } this.parseBlockBody(node, allowDirectives, false, types.braceR, afterBlockParse); 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, afterBlockParse) { const body = node.body = []; const directives = node.directives = []; this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end, afterBlockParse); } parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) { const octalPositions = []; const oldStrict = this.state.strict; let hasStrictModeDirective = false; let parsedNonDirective = false; while (!this.match(end)) { if (!parsedNonDirective && this.state.octalPositions.length) { octalPositions.push(...this.state.octalPositions); } const stmt = this.parseStatement(null, topLevel); if (directives && !parsedNonDirective && this.isValidDirective(stmt)) { const directive = this.stmtToDirective(stmt); directives.push(directive); if (!hasStrictModeDirective && directive.value.value === "use strict") { hasStrictModeDirective = true; this.setStrict(true); } continue; } parsedNonDirective = true; body.push(stmt); } if (this.state.strict && octalPositions.length) { for (let _i3 = 0; _i3 < octalPositions.length; _i3++) { const pos = octalPositions[_i3]; this.raise(pos, ErrorMessages.StrictOctalLiteral); } } if (afterBlockParse) { afterBlockParse.call(this, hasStrictModeDirective); } if (!oldStrict) { this.setStrict(false); } this.next(); } 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, ErrorMessages.ForInOfLoopInitializer, isForIn ? "for-in" : "for-of"); } else if (init.type === "AssignmentPattern") { this.raise(init.start, ErrorMessages.InvalidLhs, "for-loop"); } node.left = init; node.right = isForIn ? this.parseExpression() : this.parseMaybeAssignAllowIn(); 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 = isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn(); } else { if (kind === "const" && !(this.match(types._in) || this.isContextual("of"))) { if (!isTypescript) { this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Const declarations"); } } else if (decl.id.type !== "Identifier" && !(isFor && (this.match(types._in) || this.isContextual("of")))) { this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Complex binding patterns"); } decl.init = null; } declarations.push(this.finishNode(decl, "VariableDeclarator")); if (!this.eat(types.comma)) break; } return node; } parseVarId(decl, kind) { decl.id = this.parseBindingAtom(); this.checkLVal(decl.id, "variable declaration", kind === "var" ? BIND_VAR : BIND_LEXICAL, undefined, kind !== "var"); } 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.raise(this.state.start, ErrorMessages.GeneratorInSingleStatementContext); } node.generator = this.eat(types.star); if (isStatement) { node.id = this.parseFunctionId(requireId); } const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; this.state.maybeInArrowParameters = false; this.scope.enter(SCOPE_FUNCTION); this.prodParam.enter(functionFlags(isAsync, node.generator)); if (!isStatement) { node.id = this.parseFunctionId(); } this.parseFunctionParams(node, false); this.withTopicForbiddingContext(() => { this.parseFunctionBodyAndFinish(node, isStatement ? "FunctionDeclaration" : "FunctionExpression"); }); this.prodParam.exit(); this.scope.exit(); if (isStatement && !isHangingStatement) { this.registerFunctionStatementId(node); } this.state.maybeInArrowParameters = oldMaybeInArrowParameters; return node; } parseFunctionId(requireId) { return requireId || this.match(types.name) ? this.parseIdentifier() : null; } parseFunctionParams(node, allowModifiers) { this.expect(types.parenL); this.expressionScope.enter(newParameterDeclarationScope()); node.params = this.parseBindingList(types.parenR, 41, false, allowModifiers); this.expressionScope.exit(); } registerFunctionStatementId(node) { if (!node.id) return; this.scope.declareName(node.id.name, this.state.strict || node.generator || node.async ? this.scope.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION, node.id.start); } 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, 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, oldStrict) { this.classScope.enter(); const state = { constructorAllowsSuper, hadConstructor: false, hadStaticBlock: false }; let decorators = []; const classBody = this.startNode(); classBody.body = []; this.expect(types.braceL); this.withTopicForbiddingContext(() => { while (!this.match(types.braceR)) { if (this.eat(types.semi)) { if (decorators.length > 0) { throw this.raise(this.state.lastTokEnd, ErrorMessages.DecoratorSemicolon); } 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); if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) { this.raise(member.start, ErrorMessages.DecoratorConstructor); } } }); this.state.strict = oldStrict; this.next(); if (decorators.length) { throw this.raise(this.state.start, ErrorMessages.TrailingDecorator); } this.classScope.exit(); return this.finishNode(classBody, "ClassBody"); } parseClassMemberFromModifier(classBody, member) { 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 true; } else if (this.isClassProperty()) { const prop = member; prop.computed = false; prop.key = key; prop.static = false; classBody.body.push(this.parseClassProperty(prop)); return true; } return false; } parseClassMember(classBody, member, state) { const isStatic = this.isContextual("static"); if (isStatic) { if (this.parseClassMemberFromModifier(classBody, member)) { return; } if (this.eat(types.braceL)) { this.parseClassStaticBlock(classBody, member, state); return; } } this.parseClassMemberWithIsStatic(classBody, member, state, isStatic); } parseClassMemberWithIsStatic(classBody, member, state, isStatic) { 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.parseClassElementName(method); if (method.key.type === "PrivateName") { this.pushClassPrivateMethod(classBody, privateMethod, true, false); return; } if (this.isNonstaticConstructor(publicMethod)) { this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsGenerator); } this.pushClassMethod(classBody, publicMethod, true, false, false, false); return; } const containsEsc = this.state.containsEsc; const key = this.parseClassElementName(member); const isPrivate = key.type === "PrivateName"; const isSimple = key.type === "Identifier"; const maybeQuestionTokenStart = this.state.start; 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 (state.hadConstructor && !this.hasPlugin("typescript")) { this.raise(key.start, ErrorMessages.DuplicateConstructor); } state.hadConstructor = true; allowsDirectSuper = state.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); if (publicMember.optional) { this.unexpected(maybeQuestionTokenStart); } method.kind = "method"; this.parseClassElementName(method); this.parsePostMemberNameModifiers(publicMember); if (method.key.type === "PrivateName") { this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true); } else { if (this.isNonstaticConstructor(publicMethod)) { this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAsync); } 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.parseClassElementName(publicMethod); if (method.key.type === "PrivateName") { this.pushClassPrivateMethod(classBody, privateMethod, false, false); } else { if (this.isNonstaticConstructor(publicMethod)) { this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAccessor); } 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(); } } parseClassElementName(member) { const key = this.parsePropertyName(member, true); if (!member.computed && member.static && (key.name === "prototype" || key.value === "prototype")) { this.raise(key.start, ErrorMessages.StaticPrototype); } if (key.type === "PrivateName" && key.id.name === "constructor") { this.raise(key.start, ErrorMessages.ConstructorClassPrivateField); } return key; } parseClassStaticBlock(classBody, member, state) { var _member$decorators; this.expectPlugin("classStaticBlock", member.start); this.scope.enter(SCOPE_CLASS | SCOPE_SUPER); this.expressionScope.enter(newExpressionScope()); const oldLabels = this.state.labels; this.state.labels = []; this.prodParam.enter(PARAM); const body = member.body = []; this.parseBlockOrModuleBlockBody(body, undefined, false, types.braceR); this.prodParam.exit(); this.expressionScope.exit(); this.scope.exit(); this.state.labels = oldLabels; classBody.body.push(this.finishNode(member, "StaticBlock")); if (state.hadStaticBlock) { this.raise(member.start, ErrorMessages.DuplicateStaticBlock); } if ((_member$decorators = member.decorators) == null ? void 0 : _member$decorators.length) { this.raise(member.start, ErrorMessages.DecoratorStaticBlock); } state.hadStaticBlock = true; } pushClassProperty(classBody, prop) { if (!prop.computed && (prop.key.name === "constructor" || prop.key.value === "constructor")) { this.raise(prop.key.start, ErrorMessages.ConstructorClassField); } classBody.body.push(this.parseClassProperty(prop)); } pushClassPrivateProperty(classBody, prop) { this.expectPlugin("classPrivateProperties", prop.key.start); const node = this.parseClassPrivateProperty(prop); classBody.body.push(node); this.classScope.declarePrivateName(node.key.id.name, CLASS_ELEMENT_OTHER, node.key.start); } 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); const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true); classBody.body.push(node); const kind = node.kind === "get" ? node.static ? CLASS_ELEMENT_STATIC_GETTER : CLASS_ELEMENT_INSTANCE_GETTER : node.kind === "set" ? node.static ? CLASS_ELEMENT_STATIC_SETTER : CLASS_ELEMENT_INSTANCE_SETTER : CLASS_ELEMENT_OTHER; this.classScope.declarePrivateName(node.key.id.name, kind, node.key.start); } parsePostMemberNameModifiers(methodOrProp) {} parseClassPrivateProperty(node) { this.parseInitializer(node); this.semicolon(); return this.finishNode(node, "ClassPrivateProperty"); } parseClassProperty(node) { if (!node.typeAnnotation || this.match(types.eq)) { this.expectPlugin("classProperties"); } this.parseInitializer(node); this.semicolon(); return this.finishNode(node, "ClassProperty"); } parseInitializer(node) { this.scope.enter(SCOPE_CLASS | SCOPE_SUPER); this.expressionScope.enter(newExpressionScope()); this.prodParam.enter(PARAM); node.value = this.eat(types.eq) ? this.parseMaybeAssignAllowIn() : null; this.expressionScope.exit(); this.prodParam.exit(); this.scope.exit(); } parseClassId(node, isStatement, optionalId, bindingType = BIND_CLASS) { if (this.match(types.name)) { node.id = this.parseIdentifier(); if (isStatement) { this.checkLVal(node.id, "class name", bindingType); } } else { if (optionalId || !isStatement) { node.id = null; } else { this.unexpected(null, ErrorMessages.MissingClassName); } } } 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 = []; const specifier = this.startNodeAt(this.state.lastTokStart, this.state.lastTokStartLoc); this.next(); specifier.exported = this.parseModuleExportName(); 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()) { node.specifiers = []; node.source = null; node.declaration = this.parseExportDeclaration(node); return true; } return false; } isAsyncFunction() { if (!this.isContextual("async")) return false; const next = this.nextTokenStart(); return !lineBreak.test(this.input.slice(this.state.pos, next)) && this.isUnparsedContextual(next, "function"); } 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.raise(this.state.start, ErrorMessages.DecoratorBeforeExport); } this.parseDecorators(false); return this.parseClass(expr, true, true); } else if (this.match(types._const) || this.match(types._var) || this.isLet()) { throw this.raise(this.state.start, ErrorMessages.UnsupportedDefaultExport); } else { const res = this.parseMaybeAssignAllowIn(); this.semicolon(); return res; } } parseExportDeclaration(node) { return this.parseStatement(null); } isExportDefaultSpecifier() { if (this.match(types.name)) { const value = this.state.value; if (value === "async" && !this.state.containsEsc || value === "let") { return false; } if ((value === "type" || value === "interface") && !this.state.containsEsc) { const l = this.lookahead(); if (l.type === types.name && l.value !== "from" || l.type === types.braceL) { this.expectOnePlugin(["flow", "typescript"]); return false; } } } else if (!this.match(types._default)) { return false; } const next = this.nextTokenStart(); const hasFrom = this.isUnparsedContextual(next, "from"); if (this.input.charCodeAt(next) === 44 || this.match(types.name) && hasFrom) { return true; } if (this.match(types._default) && hasFrom) { const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next + 4)); return nextAfterFrom === 34 || nextAfterFrom === 39; } return false; } parseExportFrom(node, expect) { if (this.eatContextual("from")) { node.source = this.parseImportSource(); this.checkExport(node); const assertions = this.maybeParseImportAssertions(); if (assertions) { node.assertions = assertions; } } 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, ErrorMessages.DecoratorBeforeExport); } 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"); if (this.hasPlugin("exportDefaultFrom")) { var _declaration$extra; const declaration = node.declaration; if (declaration.type === "Identifier" && declaration.name === "from" && declaration.end - declaration.start === 4 && !((_declaration$extra = declaration.extra) == null ? void 0 : _declaration$extra.parenthesized)) { this.raise(declaration.start, ErrorMessages.ExportDefaultFromAsIdentifier); } } } else if (node.specifiers && node.specifiers.length) { for (let _i4 = 0, _node$specifiers = node.specifiers; _i4 < _node$specifiers.length; _i4++) { const specifier = _node$specifiers[_i4]; const { exported } = specifier; const exportedName = exported.type === "Identifier" ? exported.name : exported.value; this.checkDuplicateExports(specifier, exportedName); if (!isFrom && specifier.local) { const { local } = specifier; if (local.type === "StringLiteral") { this.raise(specifier.start, ErrorMessages.ExportBindingIsString, local.extra.raw, exportedName); } else { this.checkReservedWord(local.name, local.start, true, false); this.scope.checkLocalExport(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 _i5 = 0, _node$declaration$dec = node.declaration.declarations; _i5 < _node$declaration$dec.length; _i5++) { const declaration = _node$declaration$dec[_i5]; this.checkDeclaration(declaration.id); } } } } const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1]; if (currentContextDecorators.length) { throw this.raise(node.start, ErrorMessages.UnsupportedDecoratorExport); } } checkDeclaration(node) { if (node.type === "Identifier") { this.checkDuplicateExports(node, node.name); } else if (node.type === "ObjectPattern") { for (let _i6 = 0, _node$properties = node.properties; _i6 < _node$properties.length; _i6++) { const prop = _node$properties[_i6]; this.checkDeclaration(prop); } } else if (node.type === "ArrayPattern") { for (let _i7 = 0, _node$elements = node.elements; _i7 < _node$elements.length; _i7++) { const elem = _node$elements[_i7]; 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) { this.raise(node.start, name === "default" ? ErrorMessages.DuplicateDefaultExport : ErrorMessages.DuplicateExport, name); } 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.parseModuleExportName(); node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local.__clone(); nodes.push(this.finishNode(node, "ExportSpecifier")); } return nodes; } parseModuleExportName() { if (this.match(types.string)) { this.expectPlugin("moduleStringNames"); const result = this.parseLiteral(this.state.value, "StringLiteral"); const surrogate = result.value.match(loneSurrogate); if (surrogate) { this.raise(result.start, ErrorMessages.ModuleExportNameHasLoneSurrogate, surrogate[0].charCodeAt(0).toString(16)); } return result; } return this.parseIdentifier(true); } 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(); const assertions = this.maybeParseImportAssertions(); if (assertions) { node.assertions = assertions; } else { const attributes = this.maybeParseModuleAttributes(); if (attributes) { node.attributes = attributes; } } 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, contextDescription, BIND_LEXICAL); node.specifiers.push(this.finishNode(specifier, type)); } parseAssertEntries() { const attrs = []; const attrNames = new Set(); do { if (this.match(types.braceR)) { break; } const node = this.startNode(); const keyName = this.state.value; if (this.match(types.string)) { node.key = this.parseLiteral(keyName, "StringLiteral"); } else { node.key = this.parseIdentifier(true); } this.expect(types.colon); if (keyName !== "type") { this.raise(node.key.start, ErrorMessages.ModuleAttributeDifferentFromType, keyName); } if (attrNames.has(keyName)) { this.raise(node.key.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, keyName); } attrNames.add(keyName); if (!this.match(types.string)) { throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue); } node.value = this.parseLiteral(this.state.value, "StringLiteral"); this.finishNode(node, "ImportAttribute"); attrs.push(node); } while (this.eat(types.comma)); return attrs; } maybeParseModuleAttributes() { if (this.match(types._with) && !this.hasPrecedingLineBreak()) { this.expectPlugin("moduleAttributes"); this.next(); } else { if (this.hasPlugin("moduleAttributes")) return []; return null; } const attrs = []; const attributes = new Set(); do { const node = this.startNode(); node.key = this.parseIdentifier(true); if (node.key.name !== "type") { this.raise(node.key.start, ErrorMessages.ModuleAttributeDifferentFromType, node.key.name); } if (attributes.has(node.key.name)) { this.raise(node.key.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, node.key.name); } attributes.add(node.key.name); this.expect(types.colon); if (!this.match(types.string)) { throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue); } node.value = this.parseLiteral(this.state.value, "StringLiteral"); this.finishNode(node, "ImportAttribute"); attrs.push(node); } while (this.eat(types.comma)); return attrs; } maybeParseImportAssertions() { if (this.isContextual("assert") && !this.hasPrecedingLineBreak()) { this.expectPlugin("importAssertions"); this.next(); } else { if (this.hasPlugin("importAssertions")) return []; return null; } this.eat(types.braceL); const attrs = this.parseAssertEntries(); this.eat(types.braceR); return attrs; } 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)) { throw this.raise(this.state.start, ErrorMessages.DestructureNamedImport); } this.expect(types.comma); if (this.eat(types.braceR)) break; } this.parseImportSpecifier(node); } } parseImportSpecifier(node) { const specifier = this.startNode(); specifier.imported = this.parseModuleExportName(); if (this.eatContextual("as")) { specifier.local = this.parseIdentifier(); } else { const { imported } = specifier; if (imported.type === "StringLiteral") { throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, imported.value); } this.checkReservedWord(imported.name, specifier.start, true, true); specifier.local = imported.__clone(); } this.checkLVal(specifier.local, "import specifier", BIND_LEXICAL); node.specifiers.push(this.finishNode(specifier, "ImportSpecifier")); } } class ClassScope { constructor() { this.privateNames = new Set(); this.loneAccessors = new Map(); this.undefinedPrivateNames = new Map(); } } class ClassScopeHandler { constructor(raise) { this.stack = []; this.undefinedPrivateNames = new Map(); this.raise = raise; } current() { return this.stack[this.stack.length - 1]; } enter() { this.stack.push(new ClassScope()); } exit() { const oldClassScope = this.stack.pop(); const current = this.current(); for (let _i = 0, _Array$from = Array.from(oldClassScope.undefinedPrivateNames); _i < _Array$from.length; _i++) { const [name, pos] = _Array$from[_i]; if (current) { if (!current.undefinedPrivateNames.has(name)) { current.undefinedPrivateNames.set(name, pos); } } else { this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name); } } } declarePrivateName(name, elementType, pos) { const classScope = this.current(); let redefined = classScope.privateNames.has(name); if (elementType & CLASS_ELEMENT_KIND_ACCESSOR) { const accessor = redefined && classScope.loneAccessors.get(name); if (accessor) { const oldStatic = accessor & CLASS_ELEMENT_FLAG_STATIC; const newStatic = elementType & CLASS_ELEMENT_FLAG_STATIC; const oldKind = accessor & CLASS_ELEMENT_KIND_ACCESSOR; const newKind = elementType & CLASS_ELEMENT_KIND_ACCESSOR; redefined = oldKind === newKind || oldStatic !== newStatic; if (!redefined) classScope.loneAccessors.delete(name); } else if (!redefined) { classScope.loneAccessors.set(name, elementType); } } if (redefined) { this.raise(pos, ErrorMessages.PrivateNameRedeclaration, name); } classScope.privateNames.add(name); classScope.undefinedPrivateNames.delete(name); } usePrivateName(name, pos) { let classScope; for (let _i2 = 0, _this$stack = this.stack; _i2 < _this$stack.length; _i2++) { classScope = _this$stack[_i2]; if (classScope.privateNames.has(name)) return; } if (classScope) { classScope.undefinedPrivateNames.set(name, pos); } else { this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name); } } } 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.prodParam = new ProductionParameterHandler(); this.classScope = new ClassScopeHandler(this.raise.bind(this)); this.expressionScope = new ExpressionScopeHandler(this.raise.bind(this)); this.plugins = pluginsMap(this.options.plugins); this.filename = options.sourceFilename; } getScopeHandler() { return ScopeHandler; } parse() { let paramFlags = PARAM; if (this.hasPlugin("topLevelAwait") && this.inModule) { paramFlags |= PARAM_AWAIT; } this.scope.enter(SCOPE_PROGRAM); this.prodParam.enter(paramFlags); const file = this.startNode(); const program = this.startNode(); this.nextToken(); file.errors = null; this.parseTopLevel(file, program); file.errors = this.state.errors; return file; } } 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) { var _options; if (((_options = options) == null ? void 0 : _options.sourceType) === "unambiguous") { options = Object.assign({}, options); try { options.sourceType = "module"; const parser = getParser(options, input); const ast = parser.parse(); if (parser.sawUnambiguousESM) { return ast; } if (parser.ambiguousScriptDifferentAst) { try { options.sourceType = "script"; return getParser(options, input).parse(); } catch (_unused) {} } else { ast.program.sourceType = "script"; } return ast; } catch (moduleError) { try { options.sourceType = "script"; return getParser(options, input).parse(); } catch (_unused2) {} 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 == null ? void 0 : 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; }); unwrapExports(lib$6); var lib_1$4 = lib$6.parse; var lib_2$1 = lib$6.parseExpression; var lib_3 = lib$6.tokTypes; var replacement = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.replaceWithMultiple = replaceWithMultiple; exports.replaceWithSourceString = replaceWithSourceString; exports.replaceWith = replaceWith; exports._replaceWith = _replaceWith; exports.replaceExpressionWithStatements = replaceExpressionWithStatements; exports.replaceInline = replaceInline; var _index = _interopRequireDefault(lib$a); var _index2 = _interopRequireDefault(path); var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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); cache.path.get(this.parent).delete(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, lib$6.parse)(replacement); } catch (err) { const loc = err.loc; if (loc) { err.message += " - make sure this is an expression.\n" + (0, lib$5.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 == null ? void 0 : 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 functionParent = this.getFunctionParent(); const isParentAsync = functionParent == null ? void 0 : functionParent.is("async"); 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(); if (isParentAsync && _index.default.hasType(this.get("callee.body").node, "AwaitExpression", t.FUNCTION_TYPES)) { callee.set("async", true); this.replaceWith(t.awaitExpression(this.node)); } 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); } } }); unwrapExports(replacement); var replacement_1 = replacement.replaceWithMultiple; var replacement_2 = replacement.replaceWithSourceString; var replacement_3 = replacement.replaceWith; var replacement_4 = replacement._replaceWith; var replacement_5 = replacement.replaceExpressionWithStatements; var replacement_6 = replacement.replaceInline; var evaluation = createCommonjsModule(function (module, exports) { 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 == null ? void 0 : 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(elemValue.deopt, 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(key.deopt, 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(value.deopt, 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 = commonjsGlobal[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 = commonjsGlobal[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 }; } }); unwrapExports(evaluation); var evaluation_1 = evaluation.evaluateTruthy; var evaluation_2 = evaluation.evaluate; var lib$7 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = _default; var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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; } }); unwrapExports(lib$7); var formatters = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.program = exports.expression = exports.statement = exports.statements = exports.smart = void 0; var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } 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: ast => { if (ast.program.body.length > 1) { throw new Error("Found multiple statements but wanted one"); } if (expression.unwrap(ast).start === 0) { throw new Error("Parse result included parens."); } }, unwrap: ({ program }) => { const [stmt] = program.body; t.assertExpressionStatement(stmt); return stmt.expression; } }; exports.expression = expression; const program = { code: str => str, validate: () => {}, unwrap: ast => ast.program }; exports.program = program; }); unwrapExports(formatters); var formatters_1 = formatters.program; var formatters_2 = formatters.expression; var formatters_3 = formatters.statement; var formatters_4 = formatters.statements; var formatters_5 = formatters.smart; var options = createCommonjsModule(function (module, exports) { 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 ? undefined : 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"); } }); unwrapExports(options); var options_1 = options.merge; var options_2 = options.validate; var options_3 = options.normalizeReplacements; var parse$1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = parseAndBuildMetadata; var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } const PATTERN = /^[_$A-Z0-9]+$/; function parseAndBuildMetadata(formatter, code, opts) { const { placeholderWhitelist, placeholderPattern, preserveComments, syntacticPlaceholders } = opts; const ast = parseWithCodeFrame(code, opts.parser, syntacticPlaceholders); 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) { var _state$placeholderWhi; 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$placeholderWhi = state.placeholderWhitelist) == null ? void 0 : _state$placeholderWhi.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, syntacticPlaceholders) { const plugins = (parserOpts.plugins || []).slice(); if (syntacticPlaceholders !== false) { plugins.push("placeholders"); } parserOpts = Object.assign({ allowReturnOutsideFunction: true, allowSuperOutsideMethod: true, sourceType: "module" }, parserOpts, { plugins }); try { return (0, lib$6.parse)(code, parserOpts); } catch (err) { const loc = err.loc; if (loc) { err.message += "\n" + (0, lib$5.codeFrameColumns)(code, { start: loc }); err.code = "BABEL_TEMPLATE_PARSE_ERROR"; } throw err; } } }); unwrapExports(parse$1); var populate = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = populatePlaceholders; var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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; } } }); unwrapExports(populate); var string = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = stringTemplate; var _parse = _interopRequireDefault(parse$1); var _populate = _interopRequireDefault(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)); }; } }); unwrapExports(string); var literal = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = literalTemplate; var _parse = _interopRequireDefault(parse$1); var _populate = _interopRequireDefault(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.forEach((replacement, i) => { defaultReplacements[names[i]] = replacement; }); 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 }; } }); unwrapExports(literal); var builder = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = createTemplateBuilder; var _string = _interopRequireDefault(string); var _literal = _interopRequireDefault(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; } }; } }); unwrapExports(builder); var lib$8 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = exports.program = exports.expression = exports.statements = exports.statement = exports.smart = void 0; var formatters$1 = _interopRequireWildcard(formatters); var _builder = _interopRequireDefault(builder); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } const smart = (0, _builder.default)(formatters$1.smart); exports.smart = smart; const statement = (0, _builder.default)(formatters$1.statement); exports.statement = statement; const statements = (0, _builder.default)(formatters$1.statements); exports.statements = statements; const expression = (0, _builder.default)(formatters$1.expression); exports.expression = expression; const program = (0, _builder.default)(formatters$1.program); exports.program = program; var _default = Object.assign(smart.bind(undefined), { smart, statement, statements, expression, program, ast: smart.ast }); exports.default = _default; }); unwrapExports(lib$8); var lib_1$5 = lib$8.program; var lib_2$2 = lib$8.expression; var lib_3$1 = lib$8.statements; var lib_4 = lib$8.statement; var lib_5 = lib$8.smart; var lib$9 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = _default; var _helperGetFunctionArity = _interopRequireDefault(lib$7); var _template = _interopRequireDefault(lib$8); var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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 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, { operator: "=" })) { 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; } }); unwrapExports(lib$9); var conversion = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.toComputedKey = toComputedKey; exports.ensureBlock = ensureBlock; exports.arrowFunctionToShadowed = arrowFunctionToShadowed; exports.unwrapFunctionEnvironment = unwrapFunctionEnvironment; exports.arrowFunctionToExpression = arrowFunctionToExpression; var t = _interopRequireWildcard(lib$1); var _helperFunctionName = _interopRequireDefault(lib$9); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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 == null ? void 0 : 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); }); } 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; const isAssignment = superProp.parentPath.isAssignmentExpression({ left: superProp.node }); const isCall = superProp.parentPath.isCallExpression({ callee: 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); } const call = t.callExpression(t.identifier(superBinding), args); if (isCall) { superProp.parentPath.unshiftContainer("arguments", t.thisExpression()); superProp.replaceWith(t.memberExpression(call, t.identifier("call"))); thisPaths.push(superProp.parentPath.get("arguments.0")); } else if (isAssignment) { superProp.parentPath.replaceWith(call); } else { superProp.replaceWith(call); } }); } 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; } } 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 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 }; } }); unwrapExports(conversion); var conversion_1 = conversion.toComputedKey; var conversion_2 = conversion.ensureBlock; var conversion_3 = conversion.arrowFunctionToShadowed; var conversion_4 = conversion.unwrapFunctionEnvironment; var conversion_5 = conversion.arrowFunctionToExpression; var introspection = createCommonjsModule(function (module, exports) { 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; var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } 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 t.STATEMENT_OR_BLOCK_KEYS.includes(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 getOuterFunction(path) { return (path.scope.getFunctionParent() || path.scope.getProgramParent()).path; } function isExecutionUncertain(type, key) { switch (type) { case "LogicalExpression": return key === "right"; case "ConditionalExpression": case "IfStatement": return key === "consequent" || key === "alternate"; case "WhileStatement": case "DoWhileStatement": case "ForInStatement": case "ForOfStatement": return key === "body"; case "ForStatement": return key === "body" || key === "update"; case "SwitchStatement": return key === "cases"; case "TryStatement": return key === "handler"; case "AssignmentPattern": return key === "right"; case "OptionalMemberExpression": return key === "property"; case "OptionalCallExpression": return key === "arguments"; default: return false; } } function isExecutionUncertainInList(paths, maxIndex) { for (let i = 0; i < maxIndex; i++) { const path = paths[i]; if (isExecutionUncertain(path.parent.type, path.parentKey)) { return true; } } return false; } function _guessExecutionStatusRelativeTo(target) { const funcParent = { this: getOuterFunction(this), target: getOuterFunction(target) }; if (funcParent.target.node !== funcParent.this.node) { return this._guessExecutionStatusRelativeToDifferentFunctions(funcParent.target); } const paths = { target: target.getAncestry(), this: this.getAncestry() }; if (paths.target.indexOf(this) >= 0) return "after"; if (paths.this.indexOf(target) >= 0) return "before"; let commonPath; const commonIndex = { target: 0, this: 0 }; while (!commonPath && commonIndex.this < paths.this.length) { const path = paths.this[commonIndex.this]; commonIndex.target = paths.target.indexOf(path); if (commonIndex.target >= 0) { commonPath = path; } else { commonIndex.this++; } } if (!commonPath) { throw new Error("Internal Babel error - The two compared nodes" + " don't appear to belong to the same program."); } if (isExecutionUncertainInList(paths.this, commonIndex.this - 1) || isExecutionUncertainInList(paths.target, commonIndex.target - 1)) { return "unknown"; } const divergence = { this: paths.this[commonIndex.this - 1], target: paths.target[commonIndex.target - 1] }; if (divergence.target.listKey && divergence.this.listKey && divergence.target.container === divergence.this.container) { return divergence.target.key > divergence.this.key ? "before" : "after"; } const keys = t.VISITOR_KEYS[commonPath.type]; const keyPosition = { this: keys.indexOf(divergence.this.parentKey), target: keys.indexOf(divergence.target.parentKey) }; return keyPosition.target > keyPosition.this ? "before" : "after"; } const executionOrderCheckedNodes = new WeakSet(); function _guessExecutionStatusRelativeToDifferentFunctions(target) { if (!target.isFunctionDeclaration() || target.parentPath.isExportDeclaration()) { return "unknown"; } const binding = target.scope.getBinding(target.node.id.name); if (!binding.references) return "before"; const referencePaths = binding.referencePaths; let allStatus; for (const path of referencePaths) { const childOfFunction = !!path.find(path => path.node === target.node); if (childOfFunction) continue; if (path.key !== "callee" || !path.parentPath.isCallExpression()) { return "unknown"; } if (executionOrderCheckedNodes.has(path.node)) continue; executionOrderCheckedNodes.add(path.node); const status = this._guessExecutionStatusRelativeTo(path); executionOrderCheckedNodes.delete(path.node); if (allStatus && allStatus !== status) { return "unknown"; } 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 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; } }); unwrapExports(introspection); var introspection_1 = introspection.matchesPattern; var introspection_2 = introspection.has; var introspection_3 = introspection.isStatic; var introspection_4 = introspection.isnt; var introspection_5 = introspection.equals; var introspection_6 = introspection.isNodeType; var introspection_7 = introspection.canHaveVariableDeclarationOrExpression; var introspection_8 = introspection.canSwapBetweenExpressionAndStatement; var introspection_9 = introspection.isCompletionRecord; var introspection_10 = introspection.isStatementOrBlock; var introspection_11 = introspection.referencesImport; var introspection_12 = introspection.getSource; var introspection_13 = introspection.willIMaybeExecuteBefore; var introspection_14 = introspection._guessExecutionStatusRelativeTo; var introspection_15 = introspection._guessExecutionStatusRelativeToDifferentFunctions; var introspection_16 = introspection.resolve; var introspection_17 = introspection._resolve; var introspection_18 = introspection.isConstantExpression; var introspection_19 = introspection.isInStrictMode; var introspection_20 = introspection.is; var context = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.call = call; exports._call = _call; exports.isBlacklisted = exports.isDenylisted = isDenylisted; 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(lib$a); 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._traverseFlags > 0) return true; } return false; } function isDenylisted() { var _this$opts$denylist; const denylist = (_this$opts$denylist = this.opts.denylist) != null ? _this$opts$denylist : this.opts.blacklist; return denylist && denylist.indexOf(this.node.type) > -1; } function visit() { if (!this.node) { return false; } if (this.isDenylisted()) { return false; } if (this.opts.shouldSkip && this.opts.shouldSkip(this)) { return false; } if (this.shouldSkip || 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) { if (this.skipKeys == null) { this.skipKeys = {}; } this.skipKeys[key] = true; } function stop() { this._traverseFlags |= path.SHOULD_SKIP | path.SHOULD_STOP; } 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) { if (this.skipKeys != null) { this.skipKeys = {}; } this._traverseFlags = 0; 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.listKey = listKey; this.container = container; this.parentPath = parentPath || this.parentPath; this.setKey(key); } function setKey(key) { var _this$node; this.key = key; this.node = this.container[this.key]; this.type = (_this$node = this.node) == null ? void 0 : _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; } }); unwrapExports(context); var context_1 = context.call; var context_2 = context._call; var context_3 = context.isBlacklisted; var context_4 = context.isDenylisted; var context_5 = context.visit; var context_6 = context.skip; var context_7 = context.skipKey; var context_8 = context.stop; var context_9 = context.setScope; var context_10 = context.setContext; var context_11 = context.resync; var context_12 = context._resyncParent; var context_13 = context._resyncKey; var context_14 = context._resyncList; var context_15 = context._resyncRemoved; var context_16 = context.popContext; var context_17 = context.pushContext; var context_18 = context.setup; var context_19 = context.setKey; var context_20 = context.requeue; var context_21 = context._getQueueContexts; var removalHooks = createCommonjsModule(function (module, exports) { 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; }); unwrapExports(removalHooks); var removalHooks_1 = removalHooks.hooks; var removal = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.remove = remove; exports._removeFromScope = _removeFromScope; exports._callRemovalHooks = _callRemovalHooks; exports._remove = _remove; exports._markRemoved = _markRemoved; exports._assertUnremoved = _assertUnremoved; function remove() { var _this$opts; this._assertUnremoved(); this.resync(); if (!((_this$opts = this.opts) == null ? void 0 : _this$opts.noScope)) { 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._traverseFlags |= path.SHOULD_SKIP | path.REMOVED; if (this.parent) cache.path.get(this.parent).delete(this.node); this.node = null; } function _assertUnremoved() { if (this.removed) { throw this.buildCodeFrameError("NodePath has been removed so is read-only."); } } }); unwrapExports(removal); var removal_1 = removal.remove; var removal_2 = removal._removeFromScope; var removal_3 = removal._callRemovalHooks; var removal_4 = removal._remove; var removal_5 = removal._markRemoved; var removal_6 = removal._assertUnremoved; var hoister = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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; for (const violation of binding.constantViolations) { if (violation.scope !== binding.path.scope) { state.mutableBinding = true; path.stop(); 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.mutableBinding = false; 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); if (this.mutableBinding) return; 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; }); unwrapExports(hoister); var modification = createCommonjsModule(function (module, exports) { 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 _hoister = _interopRequireDefault(hoister); var _index = _interopRequireDefault(path); var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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.isJSXElement() || 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.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 (const [, path] of paths) { 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._containerInsertBefore(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(); } }); unwrapExports(modification); var modification_1 = modification.insertBefore; var modification_2 = modification._containerInsert; var modification_3 = modification._containerInsertBefore; var modification_4 = modification._containerInsertAfter; var modification_5 = modification.insertAfter; var modification_6 = modification.updateSiblingKeys; var modification_7 = modification._verifyNodeList; var modification_8 = modification.unshiftContainer; var modification_9 = modification.pushContainer; var modification_10 = modification.hoist; var family = createCommonjsModule(function (module, exports) { 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(path); var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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 findBreak(statements) { let breakStatement; if (!Array.isArray(statements)) { statements = [statements]; } for (const statement of statements) { if (statement.isDoExpression() || statement.isProgram() || statement.isBlockStatement() || statement.isCatchClause() || statement.isLabeledStatement()) { breakStatement = findBreak(statement.get("body")); } else if (statement.isIfStatement()) { var _findBreak; breakStatement = (_findBreak = findBreak(statement.get("consequent"))) != null ? _findBreak : findBreak(statement.get("alternate")); } else if (statement.isTryStatement()) { var _findBreak2; breakStatement = (_findBreak2 = findBreak(statement.get("block"))) != null ? _findBreak2 : findBreak(statement.get("handler")); } else if (statement.isBreakStatement()) { breakStatement = statement; } if (breakStatement) { return breakStatement; } } return null; } function completionRecordForSwitch(cases, paths) { let isLastCaseWithConsequent = true; for (let i = cases.length - 1; i >= 0; i--) { const switchCase = cases[i]; const consequent = switchCase.get("consequent"); let breakStatement = findBreak(consequent); if (breakStatement) { while (breakStatement.key === 0 && breakStatement.parentPath.isBlockStatement()) { breakStatement = breakStatement.parentPath; } const prevSibling = breakStatement.getPrevSibling(); if (breakStatement.key > 0 && (prevSibling.isExpressionStatement() || prevSibling.isBlockStatement())) { paths = addCompletionRecords(prevSibling, paths); breakStatement.remove(); } else { breakStatement.replaceWith(breakStatement.scope.buildUndefinedNode()); paths = addCompletionRecords(breakStatement, paths); } } else if (isLastCaseWithConsequent) { const statementFinder = statement => !statement.isBlockStatement() || statement.get("body").some(statementFinder); const hasConsequent = consequent.some(statementFinder); if (hasConsequent) { paths = addCompletionRecords(consequent[consequent.length - 1], paths); isLastCaseWithConsequent = false; } } } 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); } else if (this.isCatchClause()) { paths = addCompletionRecords(this.get("body"), paths); } else if (this.isSwitchStatement()) { paths = completionRecordForSwitch(this.get("cases"), 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 = true) { 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); } }); unwrapExports(family); var family_1 = family.getOpposite; var family_2 = family.getCompletionRecords; var family_3 = family.getSibling; var family_4 = family.getPrevSibling; var family_5 = family.getNextSibling; var family_6 = family.getAllNextSiblings; var family_7 = family.getAllPrevSiblings; var family_8 = family.get; var family_9 = family._getKey; var family_10 = family._getPattern; var family_11 = family.getBindingIdentifiers; var family_12 = family.getOuterBindingIdentifiers; var family_13 = family.getBindingIdentifierPaths; var family_14 = family.getOuterBindingIdentifierPaths; var comments = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.shareCommentsWithSiblings = shareCommentsWithSiblings; exports.addComment = addComment; exports.addComments = addComments; var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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) { prev.addComments("trailing", trailing); } else if (hasNext && !hasPrev) { 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); } }); unwrapExports(comments); var comments_1 = comments.shareCommentsWithSiblings; var comments_2 = comments.addComment; var comments_3 = comments.addComments; var path = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = exports.SHOULD_SKIP = exports.SHOULD_STOP = exports.REMOVED = void 0; var virtualTypes$1 = _interopRequireWildcard(virtualTypes); var _debug = _interopRequireDefault(src); var _index = _interopRequireDefault(lib$a); var _scope = _interopRequireDefault(scope); var t = _interopRequireWildcard(lib$1); var _generator = _interopRequireDefault(lib$3); var NodePath_ancestry = _interopRequireWildcard(ancestry); var NodePath_inference = _interopRequireWildcard(inference); var NodePath_replacement = _interopRequireWildcard(replacement); var NodePath_evaluation = _interopRequireWildcard(evaluation); var NodePath_conversion = _interopRequireWildcard(conversion); var NodePath_introspection = _interopRequireWildcard(introspection); var NodePath_context = _interopRequireWildcard(context); var NodePath_removal = _interopRequireWildcard(removal); var NodePath_modification = _interopRequireWildcard(modification); var NodePath_family = _interopRequireWildcard(family); var NodePath_comments = _interopRequireWildcard(comments); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } const debug = (0, _debug.default)("babel"); const REMOVED = 1 << 0; exports.REMOVED = REMOVED; const SHOULD_STOP = 1 << 1; exports.SHOULD_STOP = SHOULD_STOP; const SHOULD_SKIP = 1 << 2; exports.SHOULD_SKIP = SHOULD_SKIP; class NodePath { constructor(hub, parent) { this.contexts = []; this.state = null; this.opts = null; this._traverseFlags = 0; this.skipKeys = null; this.parentPath = null; this.container = null; this.listKey = null; this.key = null; this.node = null; this.type = null; this.parent = parent; this.hub = hub; this.data = null; this.context = null; this.scope = 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]; let paths = cache.path.get(parent); if (!paths) { paths = new Map(); cache.path.set(parent, paths); } let path = paths.get(targetNode); if (!path) { path = new NodePath(hub, parent); if (targetNode) paths.set(targetNode, path); } path.setup(parentPath, container, listKey, key); return path; } getScope(scope) { return this.isScope() ? new _scope.default(this) : scope; } setData(key, val) { if (this.data == null) { this.data = Object.create(null); } return this.data[key] = val; } getData(key, def) { if (this.data == null) { this.data = Object.create(null); } 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; } get inList() { return !!this.listKey; } set inList(inList) { if (!inList) { this.listKey = null; } } get parentKey() { return this.listKey || this.key; } get shouldSkip() { return !!(this._traverseFlags & SHOULD_SKIP); } set shouldSkip(v) { if (v) { this._traverseFlags |= SHOULD_SKIP; } else { this._traverseFlags &= ~SHOULD_SKIP; } } get shouldStop() { return !!(this._traverseFlags & SHOULD_STOP); } set shouldStop(v) { if (v) { this._traverseFlags |= SHOULD_STOP; } else { this._traverseFlags &= ~SHOULD_STOP; } } get removed() { return !!(this._traverseFlags & REMOVED); } set removed(v) { if (v) { this._traverseFlags |= REMOVED; } else { this._traverseFlags &= ~REMOVED; } } } 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$1)) { if (type[0] === "_") continue; if (t.TYPES.indexOf(type) < 0) t.TYPES.push(type); const virtualType = virtualTypes$1[type]; NodePath.prototype[`is${type}`] = function (opts) { return virtualType.checkPath(this, opts); }; } }); unwrapExports(path); var path_1 = path.SHOULD_SKIP; var path_2 = path.SHOULD_STOP; var path_3 = path.REMOVED; var context$1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _path = _interopRequireDefault(path); var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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 == null ? void 0 : 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 = new WeakSet(); 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; } const { node } = path; if (visited.has(node)) continue; if (node) visited.add(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; }); unwrapExports(context$1); var visitors = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.explode = explode; exports.verify = verify; exports.merge = merge; var virtualTypes$1 = _interopRequireWildcard(virtualTypes); var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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$1[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] = Object.assign({}, 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); } if (newFn !== fn) { newFn.toString = () => fn.toString(); } 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 === "denylist" || key === "noScope" || key === "skipKeys" || key === "blacklist") { return true; } return false; } function mergePair(dest, src) { for (const key of Object.keys(src)) { dest[key] = [].concat(dest[key] || [], src[key]); } } }); unwrapExports(visitors); var visitors_1 = visitors.explode; var visitors_2 = visitors.verify; var visitors_3 = visitors.merge; var hub = createCommonjsModule(function (module, exports) { 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; }); unwrapExports(hub); var lib$a = createCommonjsModule(function (module, exports) { 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(context$1); var visitors$1 = _interopRequireWildcard(visitors); exports.visitors = visitors$1; var t = _interopRequireWildcard(lib$1); var cache$1 = _interopRequireWildcard(cache); var _path = _interopRequireDefault(path); var _scope = _interopRequireDefault(scope); var _hub = _interopRequireDefault(hub); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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."); } } if (!t.VISITOR_KEYS[parent.type]) { return; } visitors$1.explode(opts); traverse.node(parent, opts, scope, state, parentPath); } traverse.visitors = visitors$1; traverse.verify = visitors$1.verify; traverse.explode = visitors$1.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$1.path.delete(node); }; traverse.removeProperties = function (tree, opts) { t.traverseFast(tree, traverse.clearNode, opts); return tree; }; function hasDenylistedType(path, state) { if (path.node.type === state.type) { state.has = true; path.stop(); } } traverse.hasType = function (tree, type, denylistTypes) { if (denylistTypes == null ? void 0 : denylistTypes.includes(tree.type)) return false; if (tree.type === type) return true; const state = { has: false, type: type }; traverse(tree, { noScope: true, denylist: denylistTypes, enter: hasDenylistedType }, null, state); return state.has; }; traverse.cache = cache$1; }); unwrapExports(lib$a); var lib_1$6 = lib$a.visitors; var helpers_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _template = _interopRequireDefault(lib$8); 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) { "@babel/helpers - typeof"; 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 (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; } if (props && defaultProps) { for (var propName in defaultProps) { if (props[propName] === void 0) { props[propName] = defaultProps[propName]; } } } else if (!props) { props = defaultProps || {}; } 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(key === "return" ? "return" : "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) { if (waiting) { waiting = false; return 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) ? Object(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.objectSpread2 = helper("7.5.0")` import defineProperty from "defineProperty"; // This function is different to "Reflect.ownKeys". The enumerableOnly // filters on symbol properties only. Returned string properties are always // enumerable. It is good to use in objectSpread. function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } export default function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = (arguments[i] != null) ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty( target, key, Object.getOwnPropertyDescriptor(source, key) ); }); } } return target; } `; 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.isNativeReflectConstruct = helper("7.9.0")` export default 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; } } `; helpers.construct = helper("7.0.0-beta.0")` import setPrototypeOf from "setPrototypeOf"; import isNativeReflectConstruct from "isNativeReflectConstruct"; 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")` function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } export default function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || (typeof obj !== "object" && typeof obj !== "function")) { return { default: obj } } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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.createSuper = helper("7.9.0")` import getPrototypeOf from "getPrototypeOf"; import isNativeReflectConstruct from "isNativeReflectConstruct"; import possibleConstructorReturn from "possibleConstructorReturn"; export default function _createSuper(Derived) { var hasNativeReflectConstruct = isNativeReflectConstruct(); return function _createSuperInternal() { var Super = getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { // NOTE: This doesn't work if this.__proto__.constructor has been modified. var NewTarget = getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return possibleConstructorReturn(this, result); } } `; 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 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 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.readOnlyError = helper("7.0.0-beta.0")` export default function _readOnlyError(name) { throw new TypeError("\\"" + 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")` // This function isn't mean to be called, but to be used as a reference. // We can't use a normal object because it isn't hoisted. export default function _temporalUndefined() {} `; helpers.tdz = helper("7.5.5")` export default function _tdzError(name) { throw new ReferenceError(name + " is not defined - temporal dead zone"); } `; helpers.temporalRef = helper("7.0.0-beta.0")` import undef from "temporalUndefined"; import err from "tdz"; export default function _temporalRef(val, name) { return val === undef ? err(name) : val; } `; helpers.slicedToArray = helper("7.0.0-beta.0")` import arrayWithHoles from "arrayWithHoles"; import iterableToArrayLimit from "iterableToArrayLimit"; import unsupportedIterableToArray from "unsupportedIterableToArray"; import nonIterableRest from "nonIterableRest"; export default function _slicedToArray(arr, i) { return ( arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest() ); } `; helpers.slicedToArrayLoose = helper("7.0.0-beta.0")` import arrayWithHoles from "arrayWithHoles"; import iterableToArrayLimitLoose from "iterableToArrayLimitLoose"; import unsupportedIterableToArray from "unsupportedIterableToArray"; import nonIterableRest from "nonIterableRest"; export default function _slicedToArrayLoose(arr, i) { return ( arrayWithHoles(arr) || iterableToArrayLimitLoose(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest() ); } `; helpers.toArray = helper("7.0.0-beta.0")` import arrayWithHoles from "arrayWithHoles"; import iterableToArray from "iterableToArray"; import unsupportedIterableToArray from "unsupportedIterableToArray"; import nonIterableRest from "nonIterableRest"; export default function _toArray(arr) { return ( arrayWithHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableRest() ); } `; helpers.toConsumableArray = helper("7.0.0-beta.0")` import arrayWithoutHoles from "arrayWithoutHoles"; import iterableToArray from "iterableToArray"; import unsupportedIterableToArray from "unsupportedIterableToArray"; import nonIterableSpread from "nonIterableSpread"; export default function _toConsumableArray(arr) { return ( arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread() ); } `; helpers.arrayWithoutHoles = helper("7.0.0-beta.0")` import arrayLikeToArray from "arrayLikeToArray"; export default function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return arrayLikeToArray(arr); } `; helpers.arrayWithHoles = helper("7.0.0-beta.0")` export default function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } `; helpers.maybeArrayLike = helper("7.9.0")` import arrayLikeToArray from "arrayLikeToArray"; export default function _maybeArrayLike(next, arr, i) { if (arr && !Array.isArray(arr) && typeof arr.length === "number") { var len = arr.length; return arrayLikeToArray(arr, i !== void 0 && i < len ? i : len); } return next(arr, i); } `; helpers.iterableToArray = helper("7.0.0-beta.0")` export default function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) 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 compliance is annoying :( // // _n = _iteratorNormalCompletion // _d = _didIteratorError // _e = _iteratorError // _i = _iterator // _s = _step if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } `; helpers.iterableToArrayLimitLoose = helper("7.0.0-beta.0")` export default function _iterableToArrayLimitLoose(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; 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.unsupportedIterableToArray = helper("7.9.0")` import arrayLikeToArray from "arrayLikeToArray"; export default function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen); } `; helpers.arrayLikeToArray = helper("7.9.0")` export default function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } `; helpers.nonIterableSpread = helper("7.0.0-beta.0")` export default function _nonIterableSpread() { throw new TypeError( "Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method." ); } `; helpers.nonIterableRest = helper("7.0.0-beta.0")` export default function _nonIterableRest() { throw new TypeError( "Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method." ); } `; helpers.createForOfIteratorHelper = helper("7.9.0")` import unsupportedIterableToArray from "unsupportedIterableToArray"; // s: start (create the iterator) // n: next // e: error (called whenever something throws) // f: finish (always called at the end) export default function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { // Fallback for engines without symbol support if ( Array.isArray(o) || (it = unsupportedIterableToArray(o)) || (allowArrayLike && o && typeof o.length === "number") ) { if (it) o = it; var i = 0; var F = function(){}; return { s: F, n: function() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function(e) { throw e; }, f: F, }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function() { it = o[Symbol.iterator](); }, n: function() { var step = it.next(); normalCompletion = step.done; return step; }, e: function(e) { didErr = true; err = e; }, f: function() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } `; helpers.createForOfIteratorHelperLoose = helper("7.9.0")` import unsupportedIterableToArray from "unsupportedIterableToArray"; export default function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { // Fallback for engines without symbol support if ( Array.isArray(o) || (it = unsupportedIterableToArray(o)) || (allowArrayLike && o && typeof o.length === "number") ) { if (it) o = it; var i = 0; return function() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; } } throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } it = o[Symbol.iterator](); return it.next.bind(it); } `; 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 runs after the decorators transform.' ); } `; 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){ 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) { var descriptor = privateMap.get(receiver); if (!descriptor) { throw new TypeError("attempted to get private field on non-instance"); } 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) { var descriptor = privateMap.get(receiver); if (!descriptor) { throw new TypeError("attempted to set private field on non-instance"); } 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.classPrivateFieldDestructureSet = helper("7.4.4")` export default function _classPrivateFieldDestructureSet(receiver, privateMap) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to set private field on non-instance"); } var descriptor = privateMap.get(receiver); if (descriptor.set) { if (!("__destrObj" in descriptor)) { descriptor.__destrObj = { set value(v) { descriptor.set.call(receiver, v) }, }; } return descriptor.__destrObj; } 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"); } return descriptor; } } `; 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"); } if (descriptor.get) { return descriptor.get.call(receiver); } 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.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.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 = <A, B>(cl: Class<A>) => Class<B>; // 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<C>(initialize: (instance: C) => void): { F: Class<C>, 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<Function> */, ) /*: 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( /*::<C>*/ 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( /*::<C>*/ F /*: Class<C> */, 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( /*::<C>*/ receiver /*: C | Class<C> */, 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 /*::<T>*/( obj /*: T */, name /*: $Keys<T> */, ) /*: ?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, undefined, groups); }; var _RegExp = wrapNativeSuper(RegExp); var _super = RegExp.prototype; var _groups = new WeakMap(); function BabelRegExp(re, flags, groups) { var _this = _RegExp.call(this, re, flags); // if the regex is recreated with 'g' flag _groups.set(_this, groups || _groups.get(re)); 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); } `; }); unwrapExports(helpers_1); var lib$b = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.get = get; exports.minVersion = minVersion; exports.getDependencies = getDependencies; exports.ensure = ensure; exports.default = exports.list = void 0; var _traverse = _interopRequireDefault(lib$a); var t = _interopRequireWildcard(lib$1); var _helpers = _interopRequireDefault(helpers_1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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("."); } let fileClass = undefined; 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 = []; const dependencyVisitor = { 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(); } }; const referenceVisitor = { 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 == null ? void 0 : binding.scope.path.isProgram()) { exportBindingAssignments.push(makePath(child)); } } }; (0, _traverse.default)(file.ast, dependencyVisitor, file.scope); (0, _traverse.default)(file.ast, referenceVisitor, file.scope); 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; } const visitor = { 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(); } }; (0, _traverse.default)(file.ast, visitor, file.scope); } 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 = () => { const file = { ast: t.file(helper.ast()) }; if (fileClass) { return new fileClass({ filename: `babel-helper://${name}` }, file); } return file; }; const metadata = getHelperMetadata(fn()); helperData[name] = { build(getDependency, id, localBindings) { const file = fn(); permuteHelperAST(file, metadata, id, localBindings, getDependency); return { nodes: file.ast.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()); } function ensure(name, newFileClass) { if (!fileClass) { fileClass = newFileClass; } loadHelper(name); } const list = Object.keys(_helpers.default).map(name => name.replace(/^_/, "")).filter(name => name !== "__esModule"); exports.list = list; var _default = get; exports.default = _default; }); unwrapExports(lib$b); var lib_1$7 = lib$b.get; var lib_2$3 = lib$b.minVersion; var lib_3$2 = lib$b.getDependencies; var lib_4$1 = lib$b.ensure; var lib_5$1 = lib$b.list; function compare(a, b) { 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; } var hasOwn = Object.prototype.hasOwnProperty; var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { if (hasOwn.call(obj, key)) keys.push(key); } return keys; }; var pSlice = Array.prototype.slice; var _functionsHaveNames; function functionsHaveNames() { if (typeof _functionsHaveNames !== 'undefined') { return _functionsHaveNames; } return _functionsHaveNames = (function () { return function foo() {}.name === 'foo'; }()); } function pToString (obj) { return Object.prototype.toString.call(obj); } function isView(arrbuf) { if (isBuffer(arrbuf)) { return false; } if (typeof global$1.ArrayBuffer !== 'function') { return false; } if (typeof ArrayBuffer.isView === 'function') { return ArrayBuffer.isView(arrbuf); } if (!arrbuf) { return false; } if (arrbuf instanceof DataView) { return true; } if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { return true; } return false; } // 1. The assert module provides functions that throw // AssertionError's when particular conditions are not met. The // assert module must conform to the following interface. function assert(value, message) { if (!value) fail(value, true, message, '==', ok); } // 2. The AssertionError is defined in assert. // new assert.AssertionError({ message: message, // actual: actual, // expected: expected }) var regex = /\s*function\s+([^\(\s]*)\s*/; // based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js function getName(func) { if (!isFunction$1(func)) { return; } if (functionsHaveNames()) { return func.name; } var str = func.toString(); var match = str.match(regex); return match && match[1]; } assert.AssertionError = AssertionError; function AssertionError(options) { this.name = 'AssertionError'; this.actual = options.actual; this.expected = options.expected; this.operator = options.operator; if (options.message) { this.message = options.message; this.generatedMessage = false; } else { this.message = getMessage(this); this.generatedMessage = true; } var stackStartFunction = options.stackStartFunction || fail; if (Error.captureStackTrace) { Error.captureStackTrace(this, stackStartFunction); } else { // non v8 browsers so we can have a stacktrace var err = new Error(); if (err.stack) { var out = err.stack; // try to strip useless frames var fn_name = getName(stackStartFunction); var idx = out.indexOf('\n' + fn_name); if (idx >= 0) { // once we have located the function frame // we need to strip out everything before it (and its line) var next_line = out.indexOf('\n', idx + 1); out = out.substring(next_line + 1); } this.stack = out; } } } // assert.AssertionError instanceof Error inherits$1(AssertionError, Error); function truncate(s, n) { if (typeof s === 'string') { return s.length < n ? s : s.slice(0, n); } else { return s; } } function inspect$1(something) { if (functionsHaveNames() || !isFunction$1(something)) { return inspect(something); } var rawname = getName(something); var name = rawname ? ': ' + rawname : ''; return '[Function' + name + ']'; } function getMessage(self) { return truncate(inspect$1(self.actual), 128) + ' ' + self.operator + ' ' + truncate(inspect$1(self.expected), 128); } // At present only the three keys mentioned above are used and // understood by the spec. Implementations or sub modules can pass // other keys to the AssertionError's constructor - they will be // ignored. // 3. All of the following functions must throw an AssertionError // when a corresponding condition is not met, with a message that // may be undefined if not provided. All assertion methods provide // both the actual and expected values to the assertion error for // display purposes. function fail(actual, expected, message, operator, stackStartFunction) { throw new AssertionError({ message: message, actual: actual, expected: expected, operator: operator, stackStartFunction: stackStartFunction }); } // EXTENSION! allows for well behaved errors defined elsewhere. assert.fail = fail; // 4. Pure assertion tests whether a value is truthy, as determined // by !!guard. // assert.ok(guard, message_opt); // This statement is equivalent to assert.equal(true, !!guard, // message_opt);. To test strictly for the value true, use // assert.strictEqual(true, guard, message_opt);. function ok(value, message) { if (!value) fail(value, true, message, '==', ok); } assert.ok = ok; // 5. The equality assertion tests shallow, coercive equality with // ==. // assert.equal(actual, expected, message_opt); assert.equal = equal; function equal(actual, expected, message) { if (actual != expected) fail(actual, expected, message, '==', equal); } // 6. The non-equality assertion tests for whether two objects are not equal // with != assert.notEqual(actual, expected, message_opt); assert.notEqual = notEqual; function notEqual(actual, expected, message) { if (actual == expected) { fail(actual, expected, message, '!=', notEqual); } } // 7. The equivalence assertion tests a deep equality relation. // assert.deepEqual(actual, expected, message_opt); assert.deepEqual = deepEqual; function deepEqual(actual, expected, message) { if (!_deepEqual(actual, expected, false)) { fail(actual, expected, message, 'deepEqual', deepEqual); } } assert.deepStrictEqual = deepStrictEqual; function deepStrictEqual(actual, expected, message) { if (!_deepEqual(actual, expected, true)) { fail(actual, expected, message, 'deepStrictEqual', deepStrictEqual); } } function _deepEqual(actual, expected, strict, memos) { // 7.1. All identical values are equivalent, as determined by ===. if (actual === expected) { return true; } else if (isBuffer(actual) && isBuffer(expected)) { return compare(actual, expected) === 0; // 7.2. If the expected value is a Date object, the actual value is // equivalent if it is also a Date object that refers to the same time. } else if (isDate(actual) && isDate(expected)) { return actual.getTime() === expected.getTime(); // 7.3 If the expected value is a RegExp object, the actual value is // equivalent if it is also a RegExp object with the same source and // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). } else if (isRegExp$1(actual) && isRegExp$1(expected)) { return actual.source === expected.source && actual.global === expected.global && actual.multiline === expected.multiline && actual.lastIndex === expected.lastIndex && actual.ignoreCase === expected.ignoreCase; // 7.4. Other pairs that do not both pass typeof value == 'object', // equivalence is determined by ==. } else if ((actual === null || typeof actual !== 'object') && (expected === null || typeof expected !== 'object')) { return strict ? actual === expected : actual == expected; // If both values are instances of typed arrays, wrap their underlying // ArrayBuffers in a Buffer each to increase performance // This optimization requires the arrays to have the same type as checked by // Object.prototype.toString (aka pToString). Never perform binary // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their // bit patterns are not identical. } else if (isView(actual) && isView(expected) && pToString(actual) === pToString(expected) && !(actual instanceof Float32Array || actual instanceof Float64Array)) { return compare(new Uint8Array(actual.buffer), new Uint8Array(expected.buffer)) === 0; // 7.5 For all other Object pairs, including Array objects, equivalence is // determined by having the same number of owned properties (as verified // with Object.prototype.hasOwnProperty.call), the same set of keys // (although not necessarily the same order), equivalent values for every // corresponding key, and an identical 'prototype' property. Note: this // accounts for both named and indexed properties on Arrays. } else if (isBuffer(actual) !== isBuffer(expected)) { return false; } else { memos = memos || {actual: [], expected: []}; var actualIndex = memos.actual.indexOf(actual); if (actualIndex !== -1) { if (actualIndex === memos.expected.indexOf(expected)) { return true; } } memos.actual.push(actual); memos.expected.push(expected); return objEquiv(actual, expected, strict, memos); } } function isArguments$1(object) { return Object.prototype.toString.call(object) == '[object Arguments]'; } function objEquiv(a, b, strict, actualVisitedObjects) { if (a === null || a === undefined || b === null || b === undefined) return false; // if one is a primitive, the other must be same if (isPrimitive(a) || isPrimitive(b)) return a === b; if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false; var aIsArgs = isArguments$1(a); var bIsArgs = isArguments$1(b); if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) return false; if (aIsArgs) { a = pSlice.call(a); b = pSlice.call(b); return _deepEqual(a, b, strict); } var ka = objectKeys(a); var kb = objectKeys(b); var key, i; // having the same number of owned properties (keys incorporates // hasOwnProperty) if (ka.length !== kb.length) return false; //the same set of keys (although not necessarily the same order), ka.sort(); kb.sort(); //~~~cheap key test for (i = ka.length - 1; i >= 0; i--) { if (ka[i] !== kb[i]) return false; } //equivalent values for every corresponding key, and //~~~possibly expensive deep test for (i = ka.length - 1; i >= 0; i--) { key = ka[i]; if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) return false; } return true; } // 8. The non-equivalence assertion tests for any deep inequality. // assert.notDeepEqual(actual, expected, message_opt); assert.notDeepEqual = notDeepEqual; function notDeepEqual(actual, expected, message) { if (_deepEqual(actual, expected, false)) { fail(actual, expected, message, 'notDeepEqual', notDeepEqual); } } assert.notDeepStrictEqual = notDeepStrictEqual; function notDeepStrictEqual(actual, expected, message) { if (_deepEqual(actual, expected, true)) { fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); } } // 9. The strict equality assertion tests strict equality, as determined by ===. // assert.strictEqual(actual, expected, message_opt); assert.strictEqual = strictEqual; function strictEqual(actual, expected, message) { if (actual !== expected) { fail(actual, expected, message, '===', strictEqual); } } // 10. The strict non-equality assertion tests for strict inequality, as // determined by !==. assert.notStrictEqual(actual, expected, message_opt); assert.notStrictEqual = notStrictEqual; function notStrictEqual(actual, expected, message) { if (actual === expected) { fail(actual, expected, message, '!==', notStrictEqual); } } function expectedException(actual, expected) { if (!actual || !expected) { return false; } if (Object.prototype.toString.call(expected) == '[object RegExp]') { return expected.test(actual); } try { if (actual instanceof expected) { return true; } } catch (e) { // Ignore. The instanceof check doesn't work for arrow functions. } if (Error.isPrototypeOf(expected)) { return false; } return expected.call({}, actual) === true; } function _tryBlock(block) { var error; try { block(); } catch (e) { error = e; } return error; } function _throws(shouldThrow, block, expected, message) { var actual; if (typeof block !== 'function') { throw new TypeError('"block" argument must be a function'); } if (typeof expected === 'string') { message = expected; expected = null; } actual = _tryBlock(block); message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + (message ? ' ' + message : '.'); if (shouldThrow && !actual) { fail(actual, expected, 'Missing expected exception' + message); } var userProvidedMessage = typeof message === 'string'; var isUnwantedException = !shouldThrow && isError(actual); var isUnexpectedException = !shouldThrow && actual && !expected; if ((isUnwantedException && userProvidedMessage && expectedException(actual, expected)) || isUnexpectedException) { fail(actual, expected, 'Got unwanted exception' + message); } if ((shouldThrow && actual && expected && !expectedException(actual, expected)) || (!shouldThrow && actual)) { throw actual; } } // 11. Expected to throw an error: // assert.throws(block, Error_opt, message_opt); assert.throws = throws; function throws(block, /*optional*/error, /*optional*/message) { _throws(true, block, error, message); } // EXTENSION! This is annoying to write outside this module. assert.doesNotThrow = doesNotThrow; function doesNotThrow(block, /*optional*/error, /*optional*/message) { _throws(false, block, error, message); } assert.ifError = ifError; function ifError(err) { if (err) throw err; } /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : (length + start); } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } var _baseSlice = baseSlice; /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject_1(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike_1(object) && _isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq_1(object[index], value); } return false; } var _isIterateeCall = isIterateeCall; /** `Object#toString` result references. */ var symbolTag$2 = '[object Symbol]'; /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol$1(value) { return typeof value == 'symbol' || (isObjectLike_1(value) && _baseGetTag(value) == symbolTag$2); } var isSymbol_1 = isSymbol$1; /** Used as references for various `Number` constants. */ var NAN = 0 / 0; /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Built-in method references without a dependency on `root`. */ var freeParseInt = parseInt; /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol_1(value)) { return NAN; } if (isObject_1(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject_1(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } var toNumber_1 = toNumber; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_INTEGER = 1.7976931348623157e+308; /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber_1(value); if (value === INFINITY || value === -INFINITY) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } var toFinite_1 = toFinite; /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite_1(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } var toInteger_1 = toInteger; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeCeil = Math.ceil, nativeMax = Math.max; /** * Creates an array of elements split into groups the length of `size`. * If `array` can't be split evenly, the final chunk will be the remaining * elements. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to process. * @param {number} [size=1] The length of each chunk * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the new array of chunks. * @example * * _.chunk(['a', 'b', 'c', 'd'], 2); * // => [['a', 'b'], ['c', 'd']] * * _.chunk(['a', 'b', 'c', 'd'], 3); * // => [['a', 'b', 'c'], ['d']] */ function chunk(array, size, guard) { if ((guard ? _isIterateeCall(array, size, guard) : size === undefined)) { size = 1; } else { size = nativeMax(toInteger_1(size), 0); } var length = array == null ? 0 : array.length; if (!length || size < 1) { return []; } var index = 0, resIndex = 0, result = Array(nativeCeil(length / size)); while (index < length) { result[resIndex++] = _baseSlice(array, index, (index += size)); } return result; } var chunk_1 = chunk; var importBuilder = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _assert = _interopRequireDefault(assert); var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } class ImportBuilder { constructor(importedSource, scope, hub) { this._statements = []; this._resultName = null; this._scope = null; this._hub = null; this._scope = scope; this._hub = hub; this._importedSource = importedSource; } done() { return { statements: this._statements, resultName: this._resultName }; } import() { this._statements.push(t.importDeclaration([], t.stringLiteral(this._importedSource))); return this; } require() { this._statements.push(t.expressionStatement(t.callExpression(t.identifier("require"), [t.stringLiteral(this._importedSource)]))); return this; } namespace(name = "namespace") { name = this._scope.generateUidIdentifier(name); const statement = this._statements[this._statements.length - 1]; (0, _assert.default)(statement.type === "ImportDeclaration"); (0, _assert.default)(statement.specifiers.length === 0); statement.specifiers = [t.importNamespaceSpecifier(name)]; this._resultName = t.cloneNode(name); return this; } default(name) { name = this._scope.generateUidIdentifier(name); const statement = this._statements[this._statements.length - 1]; (0, _assert.default)(statement.type === "ImportDeclaration"); (0, _assert.default)(statement.specifiers.length === 0); statement.specifiers = [t.importDefaultSpecifier(name)]; this._resultName = t.cloneNode(name); return this; } named(name, importName) { if (importName === "default") return this.default(name); name = this._scope.generateUidIdentifier(name); const statement = this._statements[this._statements.length - 1]; (0, _assert.default)(statement.type === "ImportDeclaration"); (0, _assert.default)(statement.specifiers.length === 0); statement.specifiers = [t.importSpecifier(name, t.identifier(importName))]; this._resultName = t.cloneNode(name); return this; } var(name) { name = this._scope.generateUidIdentifier(name); let statement = this._statements[this._statements.length - 1]; if (statement.type !== "ExpressionStatement") { (0, _assert.default)(this._resultName); statement = t.expressionStatement(this._resultName); this._statements.push(statement); } this._statements[this._statements.length - 1] = t.variableDeclaration("var", [t.variableDeclarator(name, statement.expression)]); this._resultName = t.cloneNode(name); return this; } defaultInterop() { return this._interop(this._hub.addHelper("interopRequireDefault")); } wildcardInterop() { return this._interop(this._hub.addHelper("interopRequireWildcard")); } _interop(callee) { const statement = this._statements[this._statements.length - 1]; if (statement.type === "ExpressionStatement") { statement.expression = t.callExpression(callee, [statement.expression]); } else if (statement.type === "VariableDeclaration") { (0, _assert.default)(statement.declarations.length === 1); statement.declarations[0].init = t.callExpression(callee, [statement.declarations[0].init]); } else { _assert.default.fail("Unexpected type."); } return this; } prop(name) { const statement = this._statements[this._statements.length - 1]; if (statement.type === "ExpressionStatement") { statement.expression = t.memberExpression(statement.expression, t.identifier(name)); } else if (statement.type === "VariableDeclaration") { (0, _assert.default)(statement.declarations.length === 1); statement.declarations[0].init = t.memberExpression(statement.declarations[0].init, t.identifier(name)); } else { _assert.default.fail("Unexpected type:" + statement.type); } return this; } read(name) { this._resultName = t.memberExpression(this._resultName, t.identifier(name)); } } exports.default = ImportBuilder; }); unwrapExports(importBuilder); var isModule_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isModule; function isModule(path) { const { sourceType } = path.node; if (sourceType !== "module" && sourceType !== "script") { throw path.buildCodeFrameError(`Unknown sourceType "${sourceType}", cannot transform.`); } return path.node.sourceType === "module"; } }); unwrapExports(isModule_1); var importInjector = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _assert = _interopRequireDefault(assert); var t = _interopRequireWildcard(lib$1); var _importBuilder = _interopRequireDefault(importBuilder); var _isModule = _interopRequireDefault(isModule_1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } class ImportInjector { constructor(path, importedSource, opts) { this._defaultOpts = { importedSource: null, importedType: "commonjs", importedInterop: "babel", importingInterop: "babel", ensureLiveReference: false, ensureNoContext: false }; const programPath = path.find(p => p.isProgram()); this._programPath = programPath; this._programScope = programPath.scope; this._hub = programPath.hub; this._defaultOpts = this._applyDefaults(importedSource, opts, true); } addDefault(importedSourceIn, opts) { return this.addNamed("default", importedSourceIn, opts); } addNamed(importName, importedSourceIn, opts) { (0, _assert.default)(typeof importName === "string"); return this._generateImport(this._applyDefaults(importedSourceIn, opts), importName); } addNamespace(importedSourceIn, opts) { return this._generateImport(this._applyDefaults(importedSourceIn, opts), null); } addSideEffect(importedSourceIn, opts) { return this._generateImport(this._applyDefaults(importedSourceIn, opts), false); } _applyDefaults(importedSource, opts, isInit = false) { const optsList = []; if (typeof importedSource === "string") { optsList.push({ importedSource }); optsList.push(opts); } else { (0, _assert.default)(!opts, "Unexpected secondary arguments."); optsList.push(importedSource); } const newOpts = Object.assign({}, this._defaultOpts); for (const opts of optsList) { if (!opts) continue; Object.keys(newOpts).forEach(key => { if (opts[key] !== undefined) newOpts[key] = opts[key]; }); if (!isInit) { if (opts.nameHint !== undefined) newOpts.nameHint = opts.nameHint; if (opts.blockHoist !== undefined) newOpts.blockHoist = opts.blockHoist; } } return newOpts; } _generateImport(opts, importName) { const isDefault = importName === "default"; const isNamed = !!importName && !isDefault; const isNamespace = importName === null; const { importedSource, importedType, importedInterop, importingInterop, ensureLiveReference, ensureNoContext, nameHint, blockHoist } = opts; let name = nameHint || importName; const isMod = (0, _isModule.default)(this._programPath); const isModuleForNode = isMod && importingInterop === "node"; const isModuleForBabel = isMod && importingInterop === "babel"; const builder = new _importBuilder.default(importedSource, this._programScope, this._hub); if (importedType === "es6") { if (!isModuleForNode && !isModuleForBabel) { throw new Error("Cannot import an ES6 module from CommonJS"); } builder.import(); if (isNamespace) { builder.namespace(nameHint || importedSource); } else if (isDefault || isNamed) { builder.named(name, importName); } } else if (importedType !== "commonjs") { throw new Error(`Unexpected interopType "${importedType}"`); } else if (importedInterop === "babel") { if (isModuleForNode) { name = name !== "default" ? name : importedSource; const es6Default = `${importedSource}$es6Default`; builder.import(); if (isNamespace) { builder.default(es6Default).var(name || importedSource).wildcardInterop(); } else if (isDefault) { if (ensureLiveReference) { builder.default(es6Default).var(name || importedSource).defaultInterop().read("default"); } else { builder.default(es6Default).var(name).defaultInterop().prop(importName); } } else if (isNamed) { builder.default(es6Default).read(importName); } } else if (isModuleForBabel) { builder.import(); if (isNamespace) { builder.namespace(name || importedSource); } else if (isDefault || isNamed) { builder.named(name, importName); } } else { builder.require(); if (isNamespace) { builder.var(name || importedSource).wildcardInterop(); } else if ((isDefault || isNamed) && ensureLiveReference) { if (isDefault) { name = name !== "default" ? name : importedSource; builder.var(name).read(importName); builder.defaultInterop(); } else { builder.var(importedSource).read(importName); } } else if (isDefault) { builder.var(name).defaultInterop().prop(importName); } else if (isNamed) { builder.var(name).prop(importName); } } } else if (importedInterop === "compiled") { if (isModuleForNode) { builder.import(); if (isNamespace) { builder.default(name || importedSource); } else if (isDefault || isNamed) { builder.default(importedSource).read(name); } } else if (isModuleForBabel) { builder.import(); if (isNamespace) { builder.namespace(name || importedSource); } else if (isDefault || isNamed) { builder.named(name, importName); } } else { builder.require(); if (isNamespace) { builder.var(name || importedSource); } else if (isDefault || isNamed) { if (ensureLiveReference) { builder.var(importedSource).read(name); } else { builder.prop(importName).var(name); } } } } else if (importedInterop === "uncompiled") { if (isDefault && ensureLiveReference) { throw new Error("No live reference for commonjs default"); } if (isModuleForNode) { builder.import(); if (isNamespace) { builder.default(name || importedSource); } else if (isDefault) { builder.default(name); } else if (isNamed) { builder.default(importedSource).read(name); } } else if (isModuleForBabel) { builder.import(); if (isNamespace) { builder.default(name || importedSource); } else if (isDefault) { builder.default(name); } else if (isNamed) { builder.named(name, importName); } } else { builder.require(); if (isNamespace) { builder.var(name || importedSource); } else if (isDefault) { builder.var(name); } else if (isNamed) { if (ensureLiveReference) { builder.var(importedSource).read(name); } else { builder.var(name).prop(importName); } } } } else { throw new Error(`Unknown importedInterop "${importedInterop}".`); } const { statements, resultName } = builder.done(); this._insertStatements(statements, blockHoist); if ((isDefault || isNamed) && ensureNoContext && resultName.type !== "Identifier") { return t.sequenceExpression([t.numericLiteral(0), resultName]); } return resultName; } _insertStatements(statements, blockHoist = 3) { statements.forEach(node => { node._blockHoist = blockHoist; }); const targetPath = this._programPath.get("body").find(p => { const val = p.node._blockHoist; return Number.isFinite(val) && val < 4; }); if (targetPath) { targetPath.insertBefore(statements); } else { this._programPath.unshiftContainer("body", statements); } } } exports.default = ImportInjector; }); unwrapExports(importInjector); var lib$c = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.addDefault = addDefault; exports.addNamed = addNamed; exports.addNamespace = addNamespace; exports.addSideEffect = addSideEffect; Object.defineProperty(exports, "ImportInjector", { enumerable: true, get: function () { return _importInjector.default; } }); Object.defineProperty(exports, "isModule", { enumerable: true, get: function () { return _isModule.default; } }); var _importInjector = _interopRequireDefault(importInjector); var _isModule = _interopRequireDefault(isModule_1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function addDefault(path, importedSource, opts) { return new _importInjector.default(path).addDefault(importedSource, opts); } function addNamed(path, name, importedSource, opts) { return new _importInjector.default(path).addNamed(name, importedSource, opts); } function addNamespace(path, importedSource, opts) { return new _importInjector.default(path).addNamespace(importedSource, opts); } function addSideEffect(path, importedSource, opts) { return new _importInjector.default(path).addSideEffect(importedSource, opts); } }); unwrapExports(lib$c); var lib_1$8 = lib$c.addDefault; var lib_2$4 = lib$c.addNamed; var lib_3$3 = lib$c.addNamespace; var lib_4$2 = lib$c.addSideEffect; var lib$d = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, '__esModule', { value: true }); function willPathCastToBoolean(path) { const maybeWrapped = path; const { node, parentPath } = maybeWrapped; if (parentPath.isLogicalExpression()) { const { operator, right } = parentPath.node; if (operator === "&&" || operator === "||" || operator === "??" && node === right) { return willPathCastToBoolean(parentPath); } } if (parentPath.isSequenceExpression()) { const { expressions } = parentPath.node; if (expressions[expressions.length - 1] === node) { return willPathCastToBoolean(parentPath); } else { return true; } } return parentPath.isConditional({ test: node }) || parentPath.isUnaryExpression({ operator: "!" }) || parentPath.isLoop({ test: node }); } class AssignmentMemoiser { constructor() { this._map = new WeakMap(); } has(key) { return this._map.has(key); } get(key) { if (!this.has(key)) return; const record = this._map.get(key); const { value } = record; record.count--; if (record.count === 0) { return lib$1.assignmentExpression("=", value, key); } return value; } set(key, value, count) { return this._map.set(key, { count, value }); } } function toNonOptional(path, base) { const { node } = path; if (path.isOptionalMemberExpression()) { return lib$1.memberExpression(base, node.property, node.computed); } if (path.isOptionalCallExpression()) { const callee = path.get("callee"); if (path.node.optional && callee.isOptionalMemberExpression()) { const { object } = callee.node; const context = path.scope.maybeGenerateMemoised(object) || object; callee.get("object").replaceWith(lib$1.assignmentExpression("=", context, object)); return lib$1.callExpression(lib$1.memberExpression(base, lib$1.identifier("call")), [context, ...node.arguments]); } return lib$1.callExpression(base, node.arguments); } return path.node; } function isInDetachedTree(path) { while (path) { if (path.isProgram()) break; const { parentPath, container, listKey } = path; const parentNode = parentPath.node; if (listKey) { if (container !== parentNode[listKey]) return true; } else { if (container !== parentNode) return true; } path = parentPath; } return false; } const handle = { memoise() {}, handle(member) { const { node, parent, parentPath, scope } = member; if (member.isOptionalMemberExpression()) { if (isInDetachedTree(member)) return; const endPath = member.find(({ node, parent, parentPath }) => { if (parentPath.isOptionalMemberExpression()) { return parent.optional || parent.object !== node; } if (parentPath.isOptionalCallExpression()) { return node !== member.node && parent.optional || parent.callee !== node; } return true; }); if (scope.path.isPattern()) { endPath.replaceWith(lib$1.callExpression(lib$1.arrowFunctionExpression([], endPath.node), [])); return; } const willEndPathCastToBoolean = willPathCastToBoolean(endPath); const rootParentPath = endPath.parentPath; if (rootParentPath.isUpdateExpression({ argument: node }) || rootParentPath.isAssignmentExpression({ left: node })) { throw member.buildCodeFrameError(`can't handle assignment`); } const isDeleteOperation = rootParentPath.isUnaryExpression({ operator: "delete" }); if (isDeleteOperation && endPath.isOptionalMemberExpression() && endPath.get("property").isPrivateName()) { throw member.buildCodeFrameError(`can't delete a private class element`); } let startingOptional = member; for (;;) { if (startingOptional.isOptionalMemberExpression()) { if (startingOptional.node.optional) break; startingOptional = startingOptional.get("object"); continue; } else if (startingOptional.isOptionalCallExpression()) { if (startingOptional.node.optional) break; startingOptional = startingOptional.get("callee"); continue; } throw new Error(`Internal error: unexpected ${startingOptional.node.type}`); } const startingProp = startingOptional.isOptionalMemberExpression() ? "object" : "callee"; const startingNode = startingOptional.node[startingProp]; const baseNeedsMemoised = scope.maybeGenerateMemoised(startingNode); const baseRef = baseNeedsMemoised != null ? baseNeedsMemoised : startingNode; const parentIsOptionalCall = parentPath.isOptionalCallExpression({ callee: node }); const parentIsCall = parentPath.isCallExpression({ callee: node }); startingOptional.replaceWith(toNonOptional(startingOptional, baseRef)); if (parentIsOptionalCall) { if (parent.optional) { parentPath.replaceWith(this.optionalCall(member, parent.arguments)); } else { parentPath.replaceWith(this.call(member, parent.arguments)); } } else if (parentIsCall) { member.replaceWith(this.boundGet(member)); } else { member.replaceWith(this.get(member)); } let regular = member.node; for (let current = member; current !== endPath;) { const { parentPath } = current; if (parentPath === endPath && parentIsOptionalCall && parent.optional) { regular = parentPath.node; break; } regular = toNonOptional(parentPath, regular); current = parentPath; } let context; const endParentPath = endPath.parentPath; if (lib$1.isMemberExpression(regular) && endParentPath.isOptionalCallExpression({ callee: endPath.node, optional: true })) { const { object } = regular; context = member.scope.maybeGenerateMemoised(object); if (context) { regular.object = lib$1.assignmentExpression("=", context, object); } } let replacementPath = endPath; if (isDeleteOperation) { replacementPath = endParentPath; regular = endParentPath.node; } if (willEndPathCastToBoolean) { const nonNullishCheck = lib$1.logicalExpression("&&", lib$1.binaryExpression("!==", baseNeedsMemoised ? lib$1.assignmentExpression("=", lib$1.cloneNode(baseRef), lib$1.cloneNode(startingNode)) : lib$1.cloneNode(baseRef), lib$1.nullLiteral()), lib$1.binaryExpression("!==", lib$1.cloneNode(baseRef), scope.buildUndefinedNode())); replacementPath.replaceWith(lib$1.logicalExpression("&&", nonNullishCheck, regular)); } else { const nullishCheck = lib$1.logicalExpression("||", lib$1.binaryExpression("===", baseNeedsMemoised ? lib$1.assignmentExpression("=", lib$1.cloneNode(baseRef), lib$1.cloneNode(startingNode)) : lib$1.cloneNode(baseRef), lib$1.nullLiteral()), lib$1.binaryExpression("===", lib$1.cloneNode(baseRef), scope.buildUndefinedNode())); replacementPath.replaceWith(lib$1.conditionalExpression(nullishCheck, isDeleteOperation ? lib$1.booleanLiteral(true) : scope.buildUndefinedNode(), regular)); } if (context) { const endParent = endParentPath.node; endParentPath.replaceWith(lib$1.optionalCallExpression(lib$1.optionalMemberExpression(endParent.callee, lib$1.identifier("call"), false, true), [lib$1.cloneNode(context), ...endParent.arguments], false)); } return; } if (parentPath.isUpdateExpression({ argument: node })) { if (this.simpleSet) { member.replaceWith(this.simpleSet(member)); return; } const { operator, prefix } = parent; this.memoise(member, 2); const value = lib$1.binaryExpression(operator[0], lib$1.unaryExpression("+", this.get(member)), lib$1.numericLiteral(1)); if (prefix) { parentPath.replaceWith(this.set(member, value)); } else { const { scope } = member; const ref = scope.generateUidIdentifierBasedOnNode(node); scope.push({ id: ref }); value.left = lib$1.assignmentExpression("=", lib$1.cloneNode(ref), value.left); parentPath.replaceWith(lib$1.sequenceExpression([this.set(member, value), lib$1.cloneNode(ref)])); } return; } if (parentPath.isAssignmentExpression({ left: node })) { if (this.simpleSet) { member.replaceWith(this.simpleSet(member)); return; } const { operator, right: value } = parent; if (operator === "=") { parentPath.replaceWith(this.set(member, value)); } else { const operatorTrunc = operator.slice(0, -1); if (lib$1.LOGICAL_OPERATORS.includes(operatorTrunc)) { this.memoise(member, 1); parentPath.replaceWith(lib$1.logicalExpression(operatorTrunc, this.get(member), this.set(member, value))); } else { this.memoise(member, 2); parentPath.replaceWith(this.set(member, lib$1.binaryExpression(operatorTrunc, this.get(member), value))); } } return; } if (parentPath.isCallExpression({ callee: node })) { parentPath.replaceWith(this.call(member, parent.arguments)); return; } if (parentPath.isOptionalCallExpression({ callee: node })) { if (scope.path.isPattern()) { parentPath.replaceWith(lib$1.callExpression(lib$1.arrowFunctionExpression([], parentPath.node), [])); return; } parentPath.replaceWith(this.optionalCall(member, parent.arguments)); return; } if (parentPath.isForXStatement({ left: node }) || parentPath.isObjectProperty({ value: node }) && parentPath.parentPath.isObjectPattern() || parentPath.isAssignmentPattern({ left: node }) && parentPath.parentPath.isObjectProperty({ value: parent }) && parentPath.parentPath.parentPath.isObjectPattern() || parentPath.isArrayPattern() || parentPath.isAssignmentPattern({ left: node }) && parentPath.parentPath.isArrayPattern() || parentPath.isRestElement()) { member.replaceWith(this.destructureSet(member)); return; } member.replaceWith(this.get(member)); } }; function memberExpressionToFunctions(path, visitor, state) { path.traverse(visitor, Object.assign({}, handle, state, { memoiser: new AssignmentMemoiser() })); } exports.default = memberExpressionToFunctions; }); unwrapExports(lib$d); var lib$e = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = _default; var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _default(callee, thisNode, args, optional) { if (args.length === 1 && t.isSpreadElement(args[0]) && t.isIdentifier(args[0].argument, { name: "arguments" })) { if (optional) { return t.optionalCallExpression(t.optionalMemberExpression(callee, t.identifier("apply"), false, true), [thisNode, args[0].argument], false); } return t.callExpression(t.memberExpression(callee, t.identifier("apply")), [thisNode, args[0].argument]); } else { if (optional) { return t.optionalCallExpression(t.optionalMemberExpression(callee, t.identifier("call"), false, true), [thisNode, ...args], false); } return t.callExpression(t.memberExpression(callee, t.identifier("call")), [thisNode, ...args]); } } }); unwrapExports(lib$e); var lib$f = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.skipAllButComputedKey = skipAllButComputedKey; exports.default = exports.environmentVisitor = void 0; var _traverse = _interopRequireDefault(lib$a); var _helperMemberExpressionToFunctions = _interopRequireDefault(lib$d); var _helperOptimiseCallExpression = _interopRequireDefault(lib$e); var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function getPrototypeOfExpression(objectRef, isStatic, file, isPrivateMethod) { objectRef = t.cloneNode(objectRef); const targetRef = isStatic || isPrivateMethod ? objectRef : t.memberExpression(objectRef, t.identifier("prototype")); return t.callExpression(file.addHelper("getPrototypeOf"), [targetRef]); } function skipAllButComputedKey(path) { if (!path.node.computed) { path.skip(); return; } const keys = t.VISITOR_KEYS[path.type]; for (const key of keys) { if (key !== "key") path.skipKey(key); } } const environmentVisitor = { [`${t.StaticBlock ? "StaticBlock|" : ""}ClassPrivateProperty|TypeAnnotation`](path) { path.skip(); }, Function(path) { if (path.isMethod()) return; if (path.isArrowFunctionExpression()) return; path.skip(); }, "Method|ClassProperty"(path) { skipAllButComputedKey(path); } }; exports.environmentVisitor = environmentVisitor; const visitor = _traverse.default.visitors.merge([environmentVisitor, { Super(path, state) { const { node, parentPath } = path; if (!parentPath.isMemberExpression({ object: node })) return; state.handle(parentPath); } }]); const specHandlers = { memoise(superMember, count) { const { scope, node } = superMember; const { computed, property } = node; if (!computed) { return; } const memo = scope.maybeGenerateMemoised(property); if (!memo) { return; } this.memoiser.set(property, memo, count); }, prop(superMember) { const { computed, property } = superMember.node; if (this.memoiser.has(property)) { return t.cloneNode(this.memoiser.get(property)); } if (computed) { return t.cloneNode(property); } return t.stringLiteral(property.name); }, get(superMember) { return this._get(superMember, this._getThisRefs()); }, _get(superMember, thisRefs) { const proto = getPrototypeOfExpression(this.getObjectRef(), this.isStatic, this.file, this.isPrivateMethod); return t.callExpression(this.file.addHelper("get"), [thisRefs.memo ? t.sequenceExpression([thisRefs.memo, proto]) : proto, this.prop(superMember), thisRefs.this]); }, _getThisRefs() { if (!this.isDerivedConstructor) { return { this: t.thisExpression() }; } const thisRef = this.scope.generateDeclaredUidIdentifier("thisSuper"); return { memo: t.assignmentExpression("=", thisRef, t.thisExpression()), this: t.cloneNode(thisRef) }; }, set(superMember, value) { const thisRefs = this._getThisRefs(); const proto = getPrototypeOfExpression(this.getObjectRef(), this.isStatic, this.file, this.isPrivateMethod); return t.callExpression(this.file.addHelper("set"), [thisRefs.memo ? t.sequenceExpression([thisRefs.memo, proto]) : proto, this.prop(superMember), value, thisRefs.this, t.booleanLiteral(superMember.isInStrictMode())]); }, destructureSet(superMember) { throw superMember.buildCodeFrameError(`Destructuring to a super field is not supported yet.`); }, call(superMember, args) { const thisRefs = this._getThisRefs(); return (0, _helperOptimiseCallExpression.default)(this._get(superMember, thisRefs), t.cloneNode(thisRefs.this), args, false); }, optionalCall(superMember, args) { const thisRefs = this._getThisRefs(); return (0, _helperOptimiseCallExpression.default)(this._get(superMember, thisRefs), t.cloneNode(thisRefs.this), args, true); } }; const looseHandlers = Object.assign({}, specHandlers, { prop(superMember) { const { property } = superMember.node; if (this.memoiser.has(property)) { return t.cloneNode(this.memoiser.get(property)); } return t.cloneNode(property); }, get(superMember) { const { isStatic, superRef } = this; const { computed } = superMember.node; const prop = this.prop(superMember); let object; if (isStatic) { object = superRef ? t.cloneNode(superRef) : t.memberExpression(t.identifier("Function"), t.identifier("prototype")); } else { object = superRef ? t.memberExpression(t.cloneNode(superRef), t.identifier("prototype")) : t.memberExpression(t.identifier("Object"), t.identifier("prototype")); } return t.memberExpression(object, prop, computed); }, set(superMember, value) { const { computed } = superMember.node; const prop = this.prop(superMember); return t.assignmentExpression("=", t.memberExpression(t.thisExpression(), prop, computed), value); }, destructureSet(superMember) { const { computed } = superMember.node; const prop = this.prop(superMember); return t.memberExpression(t.thisExpression(), prop, computed); }, call(superMember, args) { return (0, _helperOptimiseCallExpression.default)(this.get(superMember), t.thisExpression(), args, false); }, optionalCall(superMember, args) { return (0, _helperOptimiseCallExpression.default)(this.get(superMember), t.thisExpression(), args, true); } }); class ReplaceSupers { constructor(opts) { const path = opts.methodPath; this.methodPath = path; this.isDerivedConstructor = path.isClassMethod({ kind: "constructor" }) && !!opts.superRef; this.isStatic = path.isObjectMethod() || path.node.static; this.isPrivateMethod = path.isPrivate() && path.isMethod(); this.file = opts.file; this.superRef = opts.superRef; this.isLoose = opts.isLoose; this.opts = opts; } getObjectRef() { return t.cloneNode(this.opts.objectRef || this.opts.getObjectRef()); } replace() { const handler = this.isLoose ? looseHandlers : specHandlers; (0, _helperMemberExpressionToFunctions.default)(this.methodPath, visitor, Object.assign({ file: this.file, scope: this.methodPath.scope, isDerivedConstructor: this.isDerivedConstructor, isStatic: this.isStatic, isPrivateMethod: this.isPrivateMethod, getObjectRef: this.getObjectRef.bind(this), superRef: this.superRef }, handler)); } } exports.default = ReplaceSupers; }); unwrapExports(lib$f); var lib_1$9 = lib$f.skipAllButComputedKey; var lib_2$5 = lib$f.environmentVisitor; var rewriteThis_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = rewriteThis; var _traverse = _interopRequireDefault(lib$a); var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function rewriteThis(programPath) { (0, _traverse.default)(programPath.node, Object.assign({}, rewriteThisVisitor, { noScope: true })); } const rewriteThisVisitor = _traverse.default.visitors.merge([lib$f.environmentVisitor, { ThisExpression(path) { path.replaceWith(t.unaryExpression("void", t.numericLiteral(0), true)); } }]); }); unwrapExports(rewriteThis_1); var lib$g = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = simplifyAccess; var t = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function simplifyAccess(path, bindingNames) { path.traverse(simpleAssignmentVisitor, { scope: path.scope, bindingNames, seen: new WeakSet() }); } const simpleAssignmentVisitor = { UpdateExpression: { exit(path) { const { scope, bindingNames } = this; const arg = path.get("argument"); if (!arg.isIdentifier()) return; const localName = arg.node.name; if (!bindingNames.has(localName)) return; if (scope.getBinding(localName) !== path.scope.getBinding(localName)) { return; } if (path.parentPath.isExpressionStatement() && !path.isCompletionRecord()) { const operator = path.node.operator == "++" ? "+=" : "-="; path.replaceWith(t.assignmentExpression(operator, arg.node, t.numericLiteral(1))); } else if (path.node.prefix) { path.replaceWith(t.assignmentExpression("=", t.identifier(localName), t.binaryExpression(path.node.operator[0], t.unaryExpression("+", arg.node), t.numericLiteral(1)))); } else { const old = path.scope.generateUidIdentifierBasedOnNode(arg.node, "old"); const varName = old.name; path.scope.push({ id: old }); const binary = t.binaryExpression(path.node.operator[0], t.identifier(varName), t.numericLiteral(1)); path.replaceWith(t.sequenceExpression([t.assignmentExpression("=", t.identifier(varName), t.unaryExpression("+", arg.node)), t.assignmentExpression("=", t.cloneNode(arg.node), binary), t.identifier(varName)])); } } }, AssignmentExpression: { exit(path) { const { scope, seen, bindingNames } = this; if (path.node.operator === "=") return; if (seen.has(path.node)) return; seen.add(path.node); const left = path.get("left"); if (!left.isIdentifier()) return; const localName = left.node.name; if (!bindingNames.has(localName)) return; if (scope.getBinding(localName) !== path.scope.getBinding(localName)) { return; } path.node.right = t.binaryExpression(path.node.operator.slice(0, -1), t.cloneNode(path.node.left), path.node.right); path.node.operator = "="; } } }; }); unwrapExports(lib$g); var rewriteLiveReferences_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = rewriteLiveReferences; var _assert = _interopRequireDefault(assert); var t = _interopRequireWildcard(lib$1); var _template = _interopRequireDefault(lib$8); var _helperSimpleAccess = _interopRequireDefault(lib$g); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function rewriteLiveReferences(programPath, metadata) { const imported = new Map(); const exported = new Map(); const requeueInParent = path => { programPath.requeue(path); }; for (const [source, data] of metadata.source) { for (const [localName, importName] of data.imports) { imported.set(localName, [source, importName, null]); } for (const localName of data.importsNamespace) { imported.set(localName, [source, null, localName]); } } for (const [local, data] of metadata.local) { let exportMeta = exported.get(local); if (!exportMeta) { exportMeta = []; exported.set(local, exportMeta); } exportMeta.push(...data.names); } programPath.traverse(rewriteBindingInitVisitor, { metadata, requeueInParent, scope: programPath.scope, exported }); (0, _helperSimpleAccess.default)(programPath, new Set([...Array.from(imported.keys()), ...Array.from(exported.keys())])); programPath.traverse(rewriteReferencesVisitor, { seen: new WeakSet(), metadata, requeueInParent, scope: programPath.scope, imported, exported, buildImportReference: ([source, importName, localName], identNode) => { const meta = metadata.source.get(source); if (localName) { if (meta.lazy) identNode = t.callExpression(identNode, []); return identNode; } let namespace = t.identifier(meta.name); if (meta.lazy) namespace = t.callExpression(namespace, []); const computed = metadata.stringSpecifiers.has(importName); return t.memberExpression(namespace, computed ? t.stringLiteral(importName) : t.identifier(importName), computed); } }); } const rewriteBindingInitVisitor = { Scope(path) { path.skip(); }, ClassDeclaration(path) { const { requeueInParent, exported, metadata } = this; const { id } = path.node; if (!id) throw new Error("Expected class to have a name"); const localName = id.name; const exportNames = exported.get(localName) || []; if (exportNames.length > 0) { const statement = t.expressionStatement(buildBindingExportAssignmentExpression(metadata, exportNames, t.identifier(localName))); statement._blockHoist = path.node._blockHoist; requeueInParent(path.insertAfter(statement)[0]); } }, VariableDeclaration(path) { const { requeueInParent, exported, metadata } = this; Object.keys(path.getOuterBindingIdentifiers()).forEach(localName => { const exportNames = exported.get(localName) || []; if (exportNames.length > 0) { const statement = t.expressionStatement(buildBindingExportAssignmentExpression(metadata, exportNames, t.identifier(localName))); statement._blockHoist = path.node._blockHoist; requeueInParent(path.insertAfter(statement)[0]); } }); } }; const buildBindingExportAssignmentExpression = (metadata, exportNames, localExpr) => { return (exportNames || []).reduce((expr, exportName) => { const { stringSpecifiers } = metadata; const computed = stringSpecifiers.has(exportName); return t.assignmentExpression("=", t.memberExpression(t.identifier(metadata.exportName), computed ? t.stringLiteral(exportName) : t.identifier(exportName), computed), expr); }, localExpr); }; const buildImportThrow = localName => { return _template.default.expression.ast` (function() { throw new Error('"' + '${localName}' + '" is read-only.'); })() `; }; const rewriteReferencesVisitor = { ReferencedIdentifier(path) { const { seen, buildImportReference, scope, imported, requeueInParent } = this; if (seen.has(path.node)) return; seen.add(path.node); const localName = path.node.name; const localBinding = path.scope.getBinding(localName); const rootBinding = scope.getBinding(localName); if (rootBinding !== localBinding) return; const importData = imported.get(localName); if (importData) { const ref = buildImportReference(importData, path.node); ref.loc = path.node.loc; if ((path.parentPath.isCallExpression({ callee: path.node }) || path.parentPath.isOptionalCallExpression({ callee: path.node }) || path.parentPath.isTaggedTemplateExpression({ tag: path.node })) && t.isMemberExpression(ref)) { path.replaceWith(t.sequenceExpression([t.numericLiteral(0), ref])); } else if (path.isJSXIdentifier() && t.isMemberExpression(ref)) { const { object, property } = ref; path.replaceWith(t.JSXMemberExpression(t.JSXIdentifier(object.name), t.JSXIdentifier(property.name))); } else { path.replaceWith(ref); } requeueInParent(path); path.skip(); } }, AssignmentExpression: { exit(path) { const { scope, seen, imported, exported, requeueInParent, buildImportReference } = this; if (seen.has(path.node)) return; seen.add(path.node); const left = path.get("left"); if (left.isMemberExpression()) return; if (left.isIdentifier()) { const localName = left.node.name; if (scope.getBinding(localName) !== path.scope.getBinding(localName)) { return; } const exportedNames = exported.get(localName); const importData = imported.get(localName); if ((exportedNames == null ? void 0 : exportedNames.length) > 0 || importData) { (0, _assert.default)(path.node.operator === "=", "Path was not simplified"); const assignment = path.node; if (importData) { assignment.left = buildImportReference(importData, assignment.left); assignment.right = t.sequenceExpression([assignment.right, buildImportThrow(localName)]); } path.replaceWith(buildBindingExportAssignmentExpression(this.metadata, exportedNames, assignment)); requeueInParent(path); } } else { const ids = left.getOuterBindingIdentifiers(); const programScopeIds = Object.keys(ids).filter(localName => scope.getBinding(localName) === path.scope.getBinding(localName)); const id = programScopeIds.find(localName => imported.has(localName)); if (id) { path.node.right = t.sequenceExpression([path.node.right, buildImportThrow(id)]); } const items = []; programScopeIds.forEach(localName => { const exportedNames = exported.get(localName) || []; if (exportedNames.length > 0) { items.push(buildBindingExportAssignmentExpression(this.metadata, exportedNames, t.identifier(localName))); } }); if (items.length > 0) { let node = t.sequenceExpression(items); if (path.parentPath.isExpressionStatement()) { node = t.expressionStatement(node); node._blockHoist = path.parentPath.node._blockHoist; } const statement = path.insertAfter(node)[0]; requeueInParent(statement); } } } }, "ForOfStatement|ForInStatement"(path) { const { scope, node } = path; const { left } = node; const { exported, scope: programScope } = this; if (!t.isVariableDeclaration(left)) { let didTransform = false; const bodyPath = path.get("body"); const loopBodyScope = bodyPath.scope; for (const name of Object.keys(t.getOuterBindingIdentifiers(left))) { if (exported.get(name) && programScope.getBinding(name) === scope.getBinding(name)) { didTransform = true; if (loopBodyScope.hasOwnBinding(name)) { loopBodyScope.rename(name); } } } if (!didTransform) { return; } const newLoopId = scope.generateUidIdentifierBasedOnNode(left); bodyPath.unshiftContainer("body", t.expressionStatement(t.assignmentExpression("=", left, newLoopId))); path.get("left").replaceWith(t.variableDeclaration("let", [t.variableDeclarator(t.cloneNode(newLoopId))])); scope.registerDeclaration(path.get("left")); } } }; }); unwrapExports(rewriteLiveReferences_1); // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // resolves . and .. elements in a path array with directory names there // must be no slashes, empty elements, or device names (c:\) in the array // (so also no leading and trailing slashes - it does not distinguish // relative and absolute paths) function normalizeArray(parts, allowAboveRoot) { // if the path tries to go above the root, `up` ends up > 0 var up = 0; for (var i = parts.length - 1; i >= 0; i--) { var last = parts[i]; if (last === '.') { parts.splice(i, 1); } else if (last === '..') { parts.splice(i, 1); up++; } else if (up) { parts.splice(i, 1); up--; } } // if the path is allowed to go above the root, restore leading ..s if (allowAboveRoot) { for (; up--; up) { parts.unshift('..'); } } return parts; } // Split a filename into [root, dir, basename, ext], unix version // 'root' is just a slash, or nothing. var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; var splitPath = function(filename) { return splitPathRe.exec(filename).slice(1); }; // path.resolve([from ...], to) // posix version function resolve() { var resolvedPath = '', resolvedAbsolute = false; for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { var path = (i >= 0) ? arguments[i] : '/'; // Skip empty and invalid entries if (typeof path !== 'string') { throw new TypeError('Arguments to path.resolve must be strings'); } else if (!path) { continue; } resolvedPath = path + '/' + resolvedPath; resolvedAbsolute = path.charAt(0) === '/'; } // At this point the path should be resolved to a full absolute path, but // handle relative paths to be safe (might happen when process.cwd() fails) // Normalize the path resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { return !!p; }), !resolvedAbsolute).join('/'); return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; } // path.normalize(path) // posix version function normalize(path) { var isPathAbsolute = isAbsolute(path), trailingSlash = substr(path, -1) === '/'; // Normalize the path path = normalizeArray(filter(path.split('/'), function(p) { return !!p; }), !isPathAbsolute).join('/'); if (!path && !isPathAbsolute) { path = '.'; } if (path && trailingSlash) { path += '/'; } return (isPathAbsolute ? '/' : '') + path; } // posix version function isAbsolute(path) { return path.charAt(0) === '/'; } // posix version function join() { var paths = Array.prototype.slice.call(arguments, 0); return normalize(filter(paths, function(p, index) { if (typeof p !== 'string') { throw new TypeError('Arguments to path.join must be strings'); } return p; }).join('/')); } // path.relative(from, to) // posix version function relative(from, to) { from = resolve(from).substr(1); to = resolve(to).substr(1); function trim(arr) { var start = 0; for (; start < arr.length; start++) { if (arr[start] !== '') break; } var end = arr.length - 1; for (; end >= 0; end--) { if (arr[end] !== '') break; } if (start > end) return []; return arr.slice(start, end - start + 1); } var fromParts = trim(from.split('/')); var toParts = trim(to.split('/')); var length = Math.min(fromParts.length, toParts.length); var samePartsLength = length; for (var i = 0; i < length; i++) { if (fromParts[i] !== toParts[i]) { samePartsLength = i; break; } } var outputParts = []; for (var i = samePartsLength; i < fromParts.length; i++) { outputParts.push('..'); } outputParts = outputParts.concat(toParts.slice(samePartsLength)); return outputParts.join('/'); } var sep = '/'; var delimiter = ':'; function dirname(path) { var result = splitPath(path), root = result[0], dir = result[1]; if (!root && !dir) { // No dirname whatsoever return '.'; } if (dir) { // It has a dirname, strip trailing slash dir = dir.substr(0, dir.length - 1); } return root + dir; } function basename(path, ext) { var f = splitPath(path)[2]; // TODO: make this comparison case-insensitive on windows? if (ext && f.substr(-1 * ext.length) === ext) { f = f.substr(0, f.length - ext.length); } return f; } function extname(path) { return splitPath(path)[3]; } var require$$1 = { extname: extname, basename: basename, dirname: dirname, sep: sep, delimiter: delimiter, relative: relative, join: join, isAbsolute: isAbsolute, normalize: normalize, resolve: resolve }; function filter (xs, f) { if (xs.filter) return xs.filter(f); var res = []; for (var i = 0; i < xs.length; i++) { if (f(xs[i], i, xs)) res.push(xs[i]); } return res; } // String.prototype.substr - negative index don't work in IE8 var substr = 'ab'.substr(-1) === 'b' ? function (str, start, len) { return str.substr(start, len) } : function (str, start, len) { if (start < 0) start = str.length + start; return str.substr(start, len); } ; var normalizeAndLoadMetadata = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.hasExports = hasExports; exports.isSideEffectImport = isSideEffectImport; exports.default = normalizeModuleAndLoadMetadata; var _helperSplitExportDeclaration = _interopRequireDefault(lib$2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function hasExports(metadata) { return metadata.hasExports; } function isSideEffectImport(source) { return source.imports.size === 0 && source.importsNamespace.size === 0 && source.reexports.size === 0 && source.reexportNamespace.size === 0 && !source.reexportAll; } function normalizeModuleAndLoadMetadata(programPath, exportName, { noInterop = false, loose = false, lazy = false, esNamespaceOnly = false } = {}) { if (!exportName) { exportName = programPath.scope.generateUidIdentifier("exports").name; } const stringSpecifiers = new Set(); nameAnonymousExports(programPath); const { local, source, hasExports } = getModuleMetadata(programPath, { loose, lazy }, stringSpecifiers); removeModuleDeclarations(programPath); for (const [, metadata] of source) { if (metadata.importsNamespace.size > 0) { metadata.name = metadata.importsNamespace.values().next().value; } if (noInterop) metadata.interop = "none";else if (esNamespaceOnly) { if (metadata.interop === "namespace") { metadata.interop = "default"; } } } return { exportName, exportNameListName: null, hasExports, local, source, stringSpecifiers }; } function getExportSpecifierName(path, stringSpecifiers) { if (path.isIdentifier()) { return path.node.name; } else if (path.isStringLiteral()) { const stringValue = path.node.value; if (!(0, lib.isIdentifierName)(stringValue)) { stringSpecifiers.add(stringValue); } return stringValue; } else { throw new Error(`Expected export specifier to be either Identifier or StringLiteral, got ${path.node.type}`); } } function getModuleMetadata(programPath, { loose, lazy }, stringSpecifiers) { const localData = getLocalExportMetadata(programPath, loose, stringSpecifiers); const sourceData = new Map(); const getData = sourceNode => { const source = sourceNode.value; let data = sourceData.get(source); if (!data) { data = { name: programPath.scope.generateUidIdentifier((0, require$$1.basename)(source, (0, require$$1.extname)(source))).name, interop: "none", loc: null, imports: new Map(), importsNamespace: new Set(), reexports: new Map(), reexportNamespace: new Set(), reexportAll: null, lazy: false }; sourceData.set(source, data); } return data; }; let hasExports = false; programPath.get("body").forEach(child => { if (child.isImportDeclaration()) { const data = getData(child.node.source); if (!data.loc) data.loc = child.node.loc; child.get("specifiers").forEach(spec => { if (spec.isImportDefaultSpecifier()) { const localName = spec.get("local").node.name; data.imports.set(localName, "default"); const reexport = localData.get(localName); if (reexport) { localData.delete(localName); reexport.names.forEach(name => { data.reexports.set(name, "default"); }); } } else if (spec.isImportNamespaceSpecifier()) { const localName = spec.get("local").node.name; data.importsNamespace.add(localName); const reexport = localData.get(localName); if (reexport) { localData.delete(localName); reexport.names.forEach(name => { data.reexportNamespace.add(name); }); } } else if (spec.isImportSpecifier()) { const importName = getExportSpecifierName(spec.get("imported"), stringSpecifiers); const localName = spec.get("local").node.name; data.imports.set(localName, importName); const reexport = localData.get(localName); if (reexport) { localData.delete(localName); reexport.names.forEach(name => { data.reexports.set(name, importName); }); } } }); } else if (child.isExportAllDeclaration()) { hasExports = true; const data = getData(child.node.source); if (!data.loc) data.loc = child.node.loc; data.reexportAll = { loc: child.node.loc }; } else if (child.isExportNamedDeclaration() && child.node.source) { hasExports = true; const data = getData(child.node.source); if (!data.loc) data.loc = child.node.loc; child.get("specifiers").forEach(spec => { if (!spec.isExportSpecifier()) { throw spec.buildCodeFrameError("Unexpected export specifier type"); } const importName = getExportSpecifierName(spec.get("local"), stringSpecifiers); const exportName = getExportSpecifierName(spec.get("exported"), stringSpecifiers); data.reexports.set(exportName, importName); if (exportName === "__esModule") { throw exportName.buildCodeFrameError('Illegal export "__esModule".'); } }); } else if (child.isExportNamedDeclaration() || child.isExportDefaultDeclaration()) { hasExports = true; } }); for (const metadata of sourceData.values()) { let needsDefault = false; let needsNamed = false; if (metadata.importsNamespace.size > 0) { needsDefault = true; needsNamed = true; } if (metadata.reexportAll) { needsNamed = true; } for (const importName of metadata.imports.values()) { if (importName === "default") needsDefault = true;else needsNamed = true; } for (const importName of metadata.reexports.values()) { if (importName === "default") needsDefault = true;else needsNamed = true; } if (needsDefault && needsNamed) { metadata.interop = "namespace"; } else if (needsDefault) { metadata.interop = "default"; } } for (const [source, metadata] of sourceData) { if (lazy !== false && !(isSideEffectImport(metadata) || metadata.reexportAll)) { if (lazy === true) { metadata.lazy = !/\./.test(source); } else if (Array.isArray(lazy)) { metadata.lazy = lazy.indexOf(source) !== -1; } else if (typeof lazy === "function") { metadata.lazy = lazy(source); } else { throw new Error(`.lazy must be a boolean, string array, or function`); } } } return { hasExports, local: localData, source: sourceData }; } function getLocalExportMetadata(programPath, loose, stringSpecifiers) { const bindingKindLookup = new Map(); programPath.get("body").forEach(child => { let kind; if (child.isImportDeclaration()) { kind = "import"; } else { if (child.isExportDefaultDeclaration()) child = child.get("declaration"); if (child.isExportNamedDeclaration()) { if (child.node.declaration) { child = child.get("declaration"); } else if (loose && child.node.source && child.get("source").isStringLiteral()) { child.node.specifiers.forEach(specifier => { bindingKindLookup.set(specifier.local.name, "block"); }); return; } } if (child.isFunctionDeclaration()) { kind = "hoisted"; } else if (child.isClassDeclaration()) { kind = "block"; } else if (child.isVariableDeclaration({ kind: "var" })) { kind = "var"; } else if (child.isVariableDeclaration()) { kind = "block"; } else { return; } } Object.keys(child.getOuterBindingIdentifiers()).forEach(name => { bindingKindLookup.set(name, kind); }); }); const localMetadata = new Map(); const getLocalMetadata = idPath => { const localName = idPath.node.name; let metadata = localMetadata.get(localName); if (!metadata) { const kind = bindingKindLookup.get(localName); if (kind === undefined) { throw idPath.buildCodeFrameError(`Exporting local "${localName}", which is not declared.`); } metadata = { names: [], kind }; localMetadata.set(localName, metadata); } return metadata; }; programPath.get("body").forEach(child => { if (child.isExportNamedDeclaration() && (loose || !child.node.source)) { if (child.node.declaration) { const declaration = child.get("declaration"); const ids = declaration.getOuterBindingIdentifierPaths(); Object.keys(ids).forEach(name => { if (name === "__esModule") { throw declaration.buildCodeFrameError('Illegal export "__esModule".'); } getLocalMetadata(ids[name]).names.push(name); }); } else { child.get("specifiers").forEach(spec => { const local = spec.get("local"); const exported = spec.get("exported"); const localMetadata = getLocalMetadata(local); const exportName = getExportSpecifierName(exported, stringSpecifiers); if (exportName === "__esModule") { throw exported.buildCodeFrameError('Illegal export "__esModule".'); } localMetadata.names.push(exportName); }); } } else if (child.isExportDefaultDeclaration()) { const declaration = child.get("declaration"); if (declaration.isFunctionDeclaration() || declaration.isClassDeclaration()) { getLocalMetadata(declaration.get("id")).names.push("default"); } else { throw declaration.buildCodeFrameError("Unexpected default expression export."); } } }); return localMetadata; } function nameAnonymousExports(programPath) { programPath.get("body").forEach(child => { if (!child.isExportDefaultDeclaration()) return; (0, _helperSplitExportDeclaration.default)(child); }); } function removeModuleDeclarations(programPath) { programPath.get("body").forEach(child => { if (child.isImportDeclaration()) { child.remove(); } else if (child.isExportNamedDeclaration()) { if (child.node.declaration) { child.node.declaration._blockHoist = child.node._blockHoist; child.replaceWith(child.node.declaration); } else { child.remove(); } } else if (child.isExportDefaultDeclaration()) { const declaration = child.get("declaration"); if (declaration.isFunctionDeclaration() || declaration.isClassDeclaration()) { declaration._blockHoist = child.node._blockHoist; child.replaceWith(declaration); } else { throw declaration.buildCodeFrameError("Unexpected default expression export."); } } else if (child.isExportAllDeclaration()) { child.remove(); } }); } }); unwrapExports(normalizeAndLoadMetadata); var normalizeAndLoadMetadata_1 = normalizeAndLoadMetadata.hasExports; var normalizeAndLoadMetadata_2 = normalizeAndLoadMetadata.isSideEffectImport; var getModuleName_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = getModuleName; function getModuleName(rootOpts, pluginOpts) { var _pluginOpts$moduleRoo, _rootOpts$moduleIds, _rootOpts$moduleRoot; const { filename, filenameRelative = filename, sourceRoot = (_pluginOpts$moduleRoo = pluginOpts.moduleRoot) != null ? _pluginOpts$moduleRoo : rootOpts.moduleRoot } = rootOpts; const { moduleId = rootOpts.moduleId, moduleIds = (_rootOpts$moduleIds = rootOpts.moduleIds) != null ? _rootOpts$moduleIds : !!moduleId, getModuleId = rootOpts.getModuleId, moduleRoot = (_rootOpts$moduleRoot = rootOpts.moduleRoot) != null ? _rootOpts$moduleRoot : sourceRoot } = pluginOpts; 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; } } }); unwrapExports(getModuleName_1); var lib$h = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.rewriteModuleStatementsAndPrepareHeader = rewriteModuleStatementsAndPrepareHeader; exports.ensureStatementsHoisted = ensureStatementsHoisted; exports.wrapInterop = wrapInterop; exports.buildNamespaceInitStatements = buildNamespaceInitStatements; Object.defineProperty(exports, "isModule", { enumerable: true, get: function () { return lib$c.isModule; } }); Object.defineProperty(exports, "rewriteThis", { enumerable: true, get: function () { return _rewriteThis.default; } }); Object.defineProperty(exports, "hasExports", { enumerable: true, get: function () { return _normalizeAndLoadMetadata.hasExports; } }); Object.defineProperty(exports, "isSideEffectImport", { enumerable: true, get: function () { return _normalizeAndLoadMetadata.isSideEffectImport; } }); Object.defineProperty(exports, "getModuleName", { enumerable: true, get: function () { return _getModuleName.default; } }); var _assert = _interopRequireDefault(assert); var t = _interopRequireWildcard(lib$1); var _template = _interopRequireDefault(lib$8); var _chunk = _interopRequireDefault(chunk_1); var _rewriteThis = _interopRequireDefault(rewriteThis_1); var _rewriteLiveReferences = _interopRequireDefault(rewriteLiveReferences_1); var _normalizeAndLoadMetadata = _interopRequireWildcard(normalizeAndLoadMetadata); var _getModuleName = _interopRequireDefault(getModuleName_1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function rewriteModuleStatementsAndPrepareHeader(path, { exportName, strict, allowTopLevelThis, strictMode, loose, noInterop, lazy, esNamespaceOnly }) { (0, _assert.default)((0, lib$c.isModule)(path), "Cannot process module statements in a script"); path.node.sourceType = "script"; const meta = (0, _normalizeAndLoadMetadata.default)(path, exportName, { noInterop, loose, lazy, esNamespaceOnly }); if (!allowTopLevelThis) { (0, _rewriteThis.default)(path); } (0, _rewriteLiveReferences.default)(path, meta); if (strictMode !== false) { const hasStrict = path.node.directives.some(directive => { return directive.value.value === "use strict"; }); if (!hasStrict) { path.unshiftContainer("directives", t.directive(t.directiveLiteral("use strict"))); } } const headers = []; if ((0, _normalizeAndLoadMetadata.hasExports)(meta) && !strict) { headers.push(buildESModuleHeader(meta, loose)); } const nameList = buildExportNameListDeclaration(path, meta); if (nameList) { meta.exportNameListName = nameList.name; headers.push(nameList.statement); } headers.push(...buildExportInitializationStatements(path, meta, loose)); return { meta, headers }; } function ensureStatementsHoisted(statements) { statements.forEach(header => { header._blockHoist = 3; }); } function wrapInterop(programPath, expr, type) { if (type === "none") { return null; } let helper; if (type === "default") { helper = "interopRequireDefault"; } else if (type === "namespace") { helper = "interopRequireWildcard"; } else { throw new Error(`Unknown interop: ${type}`); } return t.callExpression(programPath.hub.addHelper(helper), [expr]); } function buildNamespaceInitStatements(metadata, sourceMetadata, loose = false) { const statements = []; let srcNamespace = t.identifier(sourceMetadata.name); if (sourceMetadata.lazy) srcNamespace = t.callExpression(srcNamespace, []); for (const localName of sourceMetadata.importsNamespace) { if (localName === sourceMetadata.name) continue; statements.push(_template.default.statement`var NAME = SOURCE;`({ NAME: localName, SOURCE: t.cloneNode(srcNamespace) })); } if (loose) { statements.push(...buildReexportsFromMeta(metadata, sourceMetadata, loose)); } for (const exportName of sourceMetadata.reexportNamespace) { statements.push((sourceMetadata.lazy ? _template.default.statement` Object.defineProperty(EXPORTS, "NAME", { enumerable: true, get: function() { return NAMESPACE; } }); ` : _template.default.statement`EXPORTS.NAME = NAMESPACE;`)({ EXPORTS: metadata.exportName, NAME: exportName, NAMESPACE: t.cloneNode(srcNamespace) })); } if (sourceMetadata.reexportAll) { const statement = buildNamespaceReexport(metadata, t.cloneNode(srcNamespace), loose); statement.loc = sourceMetadata.reexportAll.loc; statements.push(statement); } return statements; } const ReexportTemplate = { loose: _template.default.statement`EXPORTS.EXPORT_NAME = NAMESPACE_IMPORT;`, looseComputed: _template.default.statement`EXPORTS["EXPORT_NAME"] = NAMESPACE_IMPORT;`, spec: (_template.default)` Object.defineProperty(EXPORTS, "EXPORT_NAME", { enumerable: true, get: function() { return NAMESPACE_IMPORT; }, }); ` }; const buildReexportsFromMeta = (meta, metadata, loose) => { const namespace = metadata.lazy ? t.callExpression(t.identifier(metadata.name), []) : t.identifier(metadata.name); const { stringSpecifiers } = meta; return Array.from(metadata.reexports, ([exportName, importName]) => { let NAMESPACE_IMPORT; if (stringSpecifiers.has(importName)) { NAMESPACE_IMPORT = t.memberExpression(t.cloneNode(namespace), t.stringLiteral(importName), true); } else { NAMESPACE_IMPORT = NAMESPACE_IMPORT = t.memberExpression(t.cloneNode(namespace), t.identifier(importName)); } const astNodes = { EXPORTS: meta.exportName, EXPORT_NAME: exportName, NAMESPACE_IMPORT }; if (loose) { if (stringSpecifiers.has(exportName)) { return ReexportTemplate.looseComputed(astNodes); } else { return ReexportTemplate.loose(astNodes); } } else { return ReexportTemplate.spec(astNodes); } }); }; function buildESModuleHeader(metadata, enumerable = false) { return (enumerable ? _template.default.statement` EXPORTS.__esModule = true; ` : _template.default.statement` Object.defineProperty(EXPORTS, "__esModule", { value: true, }); `)({ EXPORTS: metadata.exportName }); } function buildNamespaceReexport(metadata, namespace, loose) { return (loose ? _template.default.statement` Object.keys(NAMESPACE).forEach(function(key) { if (key === "default" || key === "__esModule") return; VERIFY_NAME_LIST; if (key in EXPORTS && EXPORTS[key] === NAMESPACE[key]) return; EXPORTS[key] = NAMESPACE[key]; }); ` : _template.default.statement` Object.keys(NAMESPACE).forEach(function(key) { if (key === "default" || key === "__esModule") return; VERIFY_NAME_LIST; if (key in EXPORTS && EXPORTS[key] === NAMESPACE[key]) return; Object.defineProperty(EXPORTS, key, { enumerable: true, get: function() { return NAMESPACE[key]; }, }); }); `)({ NAMESPACE: namespace, EXPORTS: metadata.exportName, VERIFY_NAME_LIST: metadata.exportNameListName ? (_template.default)` if (Object.prototype.hasOwnProperty.call(EXPORTS_LIST, key)) return; `({ EXPORTS_LIST: metadata.exportNameListName }) : null }); } function buildExportNameListDeclaration(programPath, metadata) { const exportedVars = Object.create(null); for (const data of metadata.local.values()) { for (const name of data.names) { exportedVars[name] = true; } } let hasReexport = false; for (const data of metadata.source.values()) { for (const exportName of data.reexports.keys()) { exportedVars[exportName] = true; } for (const exportName of data.reexportNamespace) { exportedVars[exportName] = true; } hasReexport = hasReexport || data.reexportAll; } if (!hasReexport || Object.keys(exportedVars).length === 0) return null; const name = programPath.scope.generateUidIdentifier("exportNames"); delete exportedVars.default; return { name: name.name, statement: t.variableDeclaration("var", [t.variableDeclarator(name, t.valueToNode(exportedVars))]) }; } function buildExportInitializationStatements(programPath, metadata, loose = false) { const initStatements = []; const exportNames = []; for (const [localName, data] of metadata.local) { if (data.kind === "import") ; else if (data.kind === "hoisted") { initStatements.push(buildInitStatement(metadata, data.names, t.identifier(localName))); } else { exportNames.push(...data.names); } } for (const data of metadata.source.values()) { if (!loose) { initStatements.push(...buildReexportsFromMeta(metadata, data, loose)); } for (const exportName of data.reexportNamespace) { exportNames.push(exportName); } } initStatements.push(...(0, _chunk.default)(exportNames, 100).map(members => { return buildInitStatement(metadata, members, programPath.scope.buildUndefinedNode()); })); return initStatements; } const InitTemplate = { computed: _template.default.expression`EXPORTS["NAME"] = VALUE`, default: _template.default.expression`EXPORTS.NAME = VALUE` }; function buildInitStatement(metadata, exportNames, initExpr) { const { stringSpecifiers, exportName: EXPORTS } = metadata; return t.expressionStatement(exportNames.reduce((acc, exportName) => { const params = { EXPORTS, NAME: exportName, VALUE: acc }; if (stringSpecifiers.has(exportName)) { return InitTemplate.computed(params); } else { return InitTemplate.default(params); } }, initExpr)); } }); unwrapExports(lib$h); var lib_1$a = lib$h.rewriteModuleStatementsAndPrepareHeader; var lib_2$6 = lib$h.ensureStatementsHoisted; var lib_3$4 = lib$h.wrapInterop; var lib_4$3 = lib$h.buildNamespaceInitStatements; var semver = createCommonjsModule(function (module, exports) { 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')) } }); var semver_1 = semver.SEMVER_SPEC_VERSION; var semver_2 = semver.re; var semver_3 = semver.src; var semver_4 = semver.parse; var semver_5 = semver.valid; var semver_6 = semver.clean; var semver_7 = semver.SemVer; var semver_8 = semver.inc; var semver_9 = semver.diff; var semver_10 = semver.compareIdentifiers; var semver_11 = semver.rcompareIdentifiers; var semver_12 = semver.major; var semver_13 = semver.minor; var semver_14 = semver.patch; var semver_15 = semver.compare; var semver_16 = semver.compareLoose; var semver_17 = semver.rcompare; var semver_18 = semver.sort; var semver_19 = semver.rsort; var semver_20 = semver.gt; var semver_21 = semver.lt; var semver_22 = semver.eq; var semver_23 = semver.neq; var semver_24 = semver.gte; var semver_25 = semver.lte; var semver_26 = semver.cmp; var semver_27 = semver.Comparator; var semver_28 = semver.Range; var semver_29 = semver.toComparators; var semver_30 = semver.satisfies; var semver_31 = semver.maxSatisfying; var semver_32 = semver.minSatisfying; var semver_33 = semver.minVersion; var semver_34 = semver.validRange; var semver_35 = semver.ltr; var semver_36 = semver.gtr; var semver_37 = semver.outside; var semver_38 = semver.prerelease; var semver_39 = semver.intersects; var semver_40 = semver.coerce; var file = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; function helpers() { const data = _interopRequireWildcard(lib$b); helpers = function () { return data; }; return data; } function _traverse() { const data = _interopRequireWildcard(lib$a); _traverse = function () { return data; }; return data; } function _codeFrame() { const data = lib$5; _codeFrame = function () { return data; }; return data; } function t() { const data = _interopRequireWildcard(lib$1); t = function () { return data; }; return data; } function _helperModuleTransforms() { const data = lib$h; _helperModuleTransforms = function () { return data; }; return data; } function _semver() { const data = _interopRequireDefault(semver); _semver = function () { return data; }; return data; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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.opts = void 0; this.declarations = {}; this.path = null; this.ast = {}; this.scope = void 0; 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() { return (0, _helperModuleTransforms().getModuleName)(this.opts, this.opts); } 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; } helpers().ensure(name, File); 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); 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 }, end: loc.end && loc.start.line === loc.end.line ? { line: loc.end.line, column: loc.end.column + 1 } : undefined }, { highlightCode }); } return new Error(msg); } } exports.default = File; }); unwrapExports(file); var buildExternalHelpers = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = _default; function helpers() { const data = _interopRequireWildcard(lib$b); helpers = function () { return data; }; return data; } function _generator() { const data = _interopRequireDefault(lib$3); _generator = function () { return data; }; return data; } function _template() { const data = _interopRequireDefault(lib$8); _template = function () { return data; }; return data; } function t() { const data = _interopRequireWildcard(lib$1); t = function () { return data; }; return data; } var _file = _interopRequireDefault(file); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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(allowlist) { 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, allowlist); return tree; } function buildModule(allowlist) { const body = []; const refs = buildHelpers(body, null, allowlist); 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(allowlist) { const namespace = t().identifier("babelHelpers"); const body = []; body.push(t().variableDeclaration("var", [t().variableDeclarator(namespace, t().identifier("global"))])); buildHelpers(body, namespace, allowlist); 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(allowlist) { 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, allowlist); body.push(t().expressionStatement(namespace)); return tree; } function buildHelpers(body, namespace, allowlist) { const getHelperReference = name => { return namespace ? t().memberExpression(namespace, t().identifier(name)) : t().identifier(`_${name}`); }; const refs = {}; helpers().list.forEach(function (name) { if (allowlist && allowlist.indexOf(name) < 0) return; const ref = refs[name] = getHelperReference(name); helpers().ensure(name, _file.default); const { nodes } = helpers().get(name, getHelperReference, ref); body.push(...nodes); }); return refs; } function _default(allowlist, outputType = "global") { let tree; const build = { global: buildGlobal, module: buildModule, umd: buildUmd, var: buildVar }[outputType]; if (build) { tree = build(allowlist); } else { throw new Error(`Unsupported output type ${outputType}`); } return (0, _generator().default)(tree).code; } }); unwrapExports(buildExternalHelpers); // These use the global symbol registry so that multiple copies of this // library can work together in case they are not deduped. const GENSYNC_START = Symbol.for("gensync:v1:start"); const GENSYNC_SUSPEND = Symbol.for("gensync:v1:suspend"); const GENSYNC_EXPECTED_START = "GENSYNC_EXPECTED_START"; const GENSYNC_EXPECTED_SUSPEND = "GENSYNC_EXPECTED_SUSPEND"; const GENSYNC_OPTIONS_ERROR = "GENSYNC_OPTIONS_ERROR"; const GENSYNC_RACE_NONEMPTY = "GENSYNC_RACE_NONEMPTY"; const GENSYNC_ERRBACK_NO_CALLBACK = "GENSYNC_ERRBACK_NO_CALLBACK"; var gensync = Object.assign( function gensync(optsOrFn) { let genFn = optsOrFn; if (typeof optsOrFn !== "function") { genFn = newGenerator(optsOrFn); } else { genFn = wrapGenerator(optsOrFn); } return Object.assign(genFn, makeFunctionAPI(genFn)); }, { all: buildOperation({ name: "all", arity: 1, sync: function(args) { const items = Array.from(args[0]); return items.map(item => evaluateSync(item)); }, async: function(args, resolve, reject) { const items = Array.from(args[0]); if (items.length === 0) { Promise.resolve().then(() => resolve([])); return; } let count = 0; const results = items.map(() => undefined); items.forEach((item, i) => { evaluateAsync( item, val => { results[i] = val; count += 1; if (count === results.length) resolve(results); }, reject ); }); }, }), race: buildOperation({ name: "race", arity: 1, sync: function(args) { const items = Array.from(args[0]); if (items.length === 0) { throw makeError("Must race at least 1 item", GENSYNC_RACE_NONEMPTY); } return evaluateSync(items[0]); }, async: function(args, resolve, reject) { const items = Array.from(args[0]); if (items.length === 0) { throw makeError("Must race at least 1 item", GENSYNC_RACE_NONEMPTY); } for (const item of items) { evaluateAsync(item, resolve, reject); } }, }), } ); /** * Given a generator function, return the standard API object that executes * the generator and calls the callbacks. */ function makeFunctionAPI(genFn) { const fns = { sync: function(...args) { return evaluateSync(genFn.apply(this, args)); }, async: function(...args) { return new Promise((resolve, reject) => { evaluateAsync(genFn.apply(this, args), resolve, reject); }); }, errback: function(...args) { const cb = args.pop(); if (typeof cb !== "function") { throw makeError( "Asynchronous function called without callback", GENSYNC_ERRBACK_NO_CALLBACK ); } let gen; try { gen = genFn.apply(this, args); } catch (err) { cb(err); return; } evaluateAsync(gen, val => cb(undefined, val), err => cb(err)); }, }; return fns; } function assertTypeof(type, name, value, allowUndefined) { if ( typeof value === type || (allowUndefined && typeof value === "undefined") ) { return; } let msg; if (allowUndefined) { msg = `Expected opts.${name} to be either a ${type}, or undefined.`; } else { msg = `Expected opts.${name} to be a ${type}.`; } throw makeError(msg, GENSYNC_OPTIONS_ERROR); } function makeError(msg, code) { return Object.assign(new Error(msg), { code }); } /** * Given an options object, return a new generator that dispatches the * correct handler based on sync or async execution. */ function newGenerator({ name, arity, sync, async, errback }) { assertTypeof("string", "name", name, true /* allowUndefined */); assertTypeof("number", "arity", arity, true /* allowUndefined */); assertTypeof("function", "sync", sync); assertTypeof("function", "async", async, true /* allowUndefined */); assertTypeof("function", "errback", errback, true /* allowUndefined */); if (async && errback) { throw makeError( "Expected one of either opts.async or opts.errback, but got _both_.", GENSYNC_OPTIONS_ERROR ); } if (typeof name !== "string") { let fnName; if (errback && errback.name && errback.name !== "errback") { fnName = errback.name; } if (async && async.name && async.name !== "async") { fnName = async.name.replace(/Async$/, ""); } if (sync && sync.name && sync.name !== "sync") { fnName = sync.name.replace(/Sync$/, ""); } if (typeof fnName === "string") { name = fnName; } } if (typeof arity !== "number") { arity = sync.length; } return buildOperation({ name, arity, sync: function(args) { return sync.apply(this, args); }, async: function(args, resolve, reject) { if (async) { async.apply(this, args).then(resolve, reject); } else if (errback) { errback.call(this, ...args, (err, value) => { if (err == null) resolve(value); else reject(err); }); } else { resolve(sync.apply(this, args)); } }, }); } function wrapGenerator(genFn) { return setFunctionMetadata(genFn.name, genFn.length, function(...args) { return genFn.apply(this, args); }); } function buildOperation({ name, arity, sync, async }) { return setFunctionMetadata(name, arity, function*(...args) { const resume = yield GENSYNC_START; if (!resume) { // Break the tail call to avoid a bug in V8 v6.X with --harmony enabled. const res = sync.call(this, args); return res; } let result; try { async.call( this, args, value => { if (result) return; result = { value }; resume(); }, err => { if (result) return; result = { err }; resume(); } ); } catch (err) { result = { err }; resume(); } // Suspend until the callbacks run. Will resume synchronously if the // callback was already called. yield GENSYNC_SUSPEND; if (result.hasOwnProperty("err")) { throw result.err; } return result.value; }); } function evaluateSync(gen) { let value; while (!({ value } = gen.next()).done) { assertStart(value, gen); } return value; } function evaluateAsync(gen, resolve, reject) { (function step() { try { let value; while (!({ value } = gen.next()).done) { assertStart(value, gen); // If this throws, it is considered to have broken the contract // established for async handlers. If these handlers are called // synchronously, it is also considered bad behavior. let sync = true; let didSyncResume = false; const out = gen.next(() => { if (sync) { didSyncResume = true; } else { step(); } }); sync = false; assertSuspend(out, gen); if (!didSyncResume) { // Callback wasn't called synchronously, so break out of the loop // and let it call 'step' later. return; } } return resolve(value); } catch (err) { return reject(err); } })(); } function assertStart(value, gen) { if (value === GENSYNC_START) return; throwError( gen, makeError( `Got unexpected yielded value in gensync generator: ${JSON.stringify( value )}. Did you perhaps mean to use 'yield*' instead of 'yield'?`, GENSYNC_EXPECTED_START ) ); } function assertSuspend({ value, done }, gen) { if (!done && value === GENSYNC_SUSPEND) return; throwError( gen, makeError( done ? "Unexpected generator completion. If you get this, it is probably a gensync bug." : `Expected GENSYNC_SUSPEND, got ${JSON.stringify( value )}. If you get this, it is probably a gensync bug.`, GENSYNC_EXPECTED_SUSPEND ) ); } function throwError(gen, err) { // Call `.throw` so that users can step in a debugger to easily see which // 'yield' passed an unexpected value. If the `.throw` call didn't throw // back to the generator, we explicitly do it to stop the error // from being swallowed by user code try/catches. if (gen.throw) gen.throw(err); throw err; } function setFunctionMetadata(name, arity, fn) { if (typeof name === "string") { // This should always work on the supported Node versions, but for the // sake of users that are compiling to older versions, we check for // configurability so we don't throw. const nameDesc = Object.getOwnPropertyDescriptor(fn, "name"); if (!nameDesc || nameDesc.configurable) { Object.defineProperty( fn, "name", Object.assign(nameDesc || {}, { configurable: true, value: name, }) ); } } if (typeof arity === "number") { const lengthDesc = Object.getOwnPropertyDescriptor(fn, "length"); if (!lengthDesc || lengthDesc.configurable) { Object.defineProperty( fn, "length", Object.assign(lengthDesc || {}, { configurable: true, value: arity, }) ); } } return fn; } var async = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.maybeAsync = maybeAsync; exports.forwardAsync = forwardAsync; exports.isThenable = isThenable; exports.waitFor = exports.onFirstPause = exports.isAsync = void 0; function _gensync() { const data = _interopRequireDefault(gensync); _gensync = function () { return data; }; return data; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const id = x => x; const runGenerator = (0, _gensync().default)(function* (item) { return yield* item; }); const isAsync = (0, _gensync().default)({ sync: () => false, errback: cb => cb(null, true) }); exports.isAsync = isAsync; function maybeAsync(fn, message) { return (0, _gensync().default)({ sync(...args) { const result = fn.apply(this, args); if (isThenable(result)) throw new Error(message); return result; }, async(...args) { return Promise.resolve(fn.apply(this, args)); } }); } const withKind = (0, _gensync().default)({ sync: cb => cb("sync"), async: cb => cb("async") }); function forwardAsync(action, cb) { const g = (0, _gensync().default)(action); return withKind(kind => { const adapted = g[kind]; return cb(adapted); }); } const onFirstPause = (0, _gensync().default)({ name: "onFirstPause", arity: 2, sync: function (item) { return runGenerator.sync(item); }, errback: function (item, firstPause, cb) { let completed = false; runGenerator.errback(item, (err, value) => { completed = true; cb(err, value); }); if (!completed) { firstPause(); } } }); exports.onFirstPause = onFirstPause; const waitFor = (0, _gensync().default)({ sync: id, async: id }); exports.waitFor = waitFor; function isThenable(val) { return !!val && (typeof val === "object" || typeof val === "function") && !!val.then && typeof val.then === "function"; } }); unwrapExports(async); var async_1 = async.maybeAsync; var async_2 = async.forwardAsync; var async_3 = async.isThenable; var async_4 = async.waitFor; var async_5 = async.onFirstPause; var async_6 = async.isAsync; var util$4 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.mergeOptions = mergeOptions; exports.isIterableIterator = isIterableIterator; 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; } } function isIterableIterator(value) { return !!value && typeof value.next === "function" && typeof value[Symbol.iterator] === "function"; } }); unwrapExports(util$4); var util_1$1 = util$4.mergeOptions; var util_2$1 = util$4.isIterableIterator; var caching = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.makeWeakCache = makeWeakCache; exports.makeWeakCacheSync = makeWeakCacheSync; exports.makeStrongCache = makeStrongCache; exports.makeStrongCacheSync = makeStrongCacheSync; exports.assertSimpleType = assertSimpleType; function _gensync() { const data = _interopRequireDefault(gensync); _gensync = function () { return data; }; return data; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const synchronize = gen => { return (0, _gensync().default)(gen).sync; }; function* genTrue(data) { return true; } function makeWeakCache(handler) { return makeCachedFunction(WeakMap, handler); } function makeWeakCacheSync(handler) { return synchronize(makeWeakCache(handler)); } function makeStrongCache(handler) { return makeCachedFunction(Map, handler); } function makeStrongCacheSync(handler) { return synchronize(makeStrongCache(handler)); } function makeCachedFunction(CallCache, handler) { const callCacheSync = new CallCache(); const callCacheAsync = new CallCache(); const futureCache = new CallCache(); return function* cachedFunction(arg, data) { const asyncContext = yield* (0, async.isAsync)(); const callCache = asyncContext ? callCacheAsync : callCacheSync; const cached = yield* getCachedValueOrWait(asyncContext, callCache, futureCache, arg, data); if (cached.valid) return cached.value; const cache = new CacheConfigurator(data); const handlerResult = handler(arg, cache); let finishLock; let value; if ((0, util$4.isIterableIterator)(handlerResult)) { const gen = handlerResult; value = yield* (0, async.onFirstPause)(gen, () => { finishLock = setupAsyncLocks(cache, futureCache, arg); }); } else { value = handlerResult; } updateFunctionCache(callCache, cache, arg, value); if (finishLock) { futureCache.delete(arg); finishLock.release(value); } return value; }; } function* getCachedValue(cache, arg, data) { const cachedValue = cache.get(arg); if (cachedValue) { for (const { value, valid } of cachedValue) { if (yield* valid(data)) return { valid: true, value }; } } return { valid: false, value: null }; } function* getCachedValueOrWait(asyncContext, callCache, futureCache, arg, data) { const cached = yield* getCachedValue(callCache, arg, data); if (cached.valid) { return cached; } if (asyncContext) { const cached = yield* getCachedValue(futureCache, arg, data); if (cached.valid) { const value = yield* (0, async.waitFor)(cached.value.promise); return { valid: true, value }; } } return { valid: false, value: null }; } function setupAsyncLocks(config, futureCache, arg) { const finishLock = new Lock(); updateFunctionCache(futureCache, config, arg, finishLock); return finishLock; } function updateFunctionCache(cache, config, arg, value) { if (!config.configured()) config.forever(); let cachedValue = cache.get(arg); config.deactivate(); switch (config.mode()) { case "forever": cachedValue = [{ value, valid: genTrue }]; cache.set(arg, cachedValue); break; case "invalidate": cachedValue = [{ value, valid: config.validator() }]; cache.set(arg, cachedValue); break; case "valid": if (cachedValue) { cachedValue.push({ value, valid: config.validator() }); } else { cachedValue = [{ value, valid: config.validator() }]; cache.set(arg, cachedValue); } } } class CacheConfigurator { constructor(data) { this._active = true; this._never = false; this._forever = false; this._invalidate = false; this._configured = false; this._pairs = []; this._data = void 0; 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); const fn = (0, async.maybeAsync)(handler, `You appear to be using an async cache handler, but Babel has been called synchronously`); if ((0, async.isThenable)(key)) { return key.then(key => { this._pairs.push([key, fn]); return key; }); } this._pairs.push([key, fn]); return key; } invalidate(handler) { this._invalidate = true; return this.using(handler); } validator() { const pairs = this._pairs; return function* (data) { for (const [key, fn] of pairs) { if (key !== (yield* fn(data))) return false; } return true; }; } 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 ((0, async.isThenable)(value)) { throw new Error(`You appear to be using an async cache handler, ` + `which your current version of Babel does not support. ` + `We may add support for this in the future, ` + `but if you're on the most recent version of @babel/core and still ` + `seeing this error, then you'll need to synchronously handle your caching logic.`); } 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; } class Lock { constructor() { this.released = false; this.promise = void 0; this._resolve = void 0; this.promise = new Promise(resolve => { this._resolve = resolve; }); } release(value) { this.released = true; this._resolve(value); } } }); unwrapExports(caching); var caching_1 = caching.makeWeakCache; var caching_2 = caching.makeWeakCacheSync; var caching_3 = caching.makeStrongCache; var caching_4 = caching.makeStrongCacheSync; var caching_5 = caching.assertSimpleType; var require$$0$1 = {}; var fs = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.stat = exports.exists = exports.readFile = void 0; function _fs() { const data = _interopRequireDefault(require$$0$1); _fs = function () { return data; }; return data; } function _gensync() { const data = _interopRequireDefault(gensync); _gensync = function () { return data; }; return data; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const readFile = (0, _gensync().default)({ sync: _fs().default.readFileSync, errback: _fs().default.readFile }); exports.readFile = readFile; const exists = (0, _gensync().default)({ sync(path) { try { _fs().default.accessSync(path); return true; } catch (_unused) { return false; } }, errback: (path, cb) => _fs().default.access(path, undefined, err => cb(null, !err)) }); exports.exists = exists; const stat = (0, _gensync().default)({ sync: _fs().default.statSync, errback: _fs().default.stat }); exports.stat = stat; }); unwrapExports(fs); var fs_1 = fs.stat; var fs_2 = fs.exists; var fs_3 = fs.readFile; var utils$1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.makeStaticFileCache = makeStaticFileCache; var fs$1 = _interopRequireWildcard(fs); function _fs2() { const data = _interopRequireDefault(require$$0$1); _fs2 = function () { return data; }; return data; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function makeStaticFileCache(fn) { return (0, caching.makeStrongCache)(function* (filepath, cache) { const cached = cache.invalidate(() => fileMtime(filepath)); if (cached === null) { return null; } return fn(filepath, yield* fs$1.readFile(filepath, "utf8")); }); } function fileMtime(filepath) { try { return +_fs2().default.statSync(filepath).mtime; } catch (e) { if (e.code !== "ENOENT" && e.code !== "ENOTDIR") throw e; } return null; } }); unwrapExports(utils$1); var utils_1$1 = utils$1.makeStaticFileCache; var _package = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.findPackageData = findPackageData; function _path() { const data = _interopRequireDefault(require$$1); _path = function () { return data; }; return data; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const PACKAGE_FILENAME = "package.json"; function* findPackageData(filepath) { let pkg = null; const directories = []; let isPackage = true; let dirname = _path().default.dirname(filepath); while (!pkg && _path().default.basename(dirname) !== "node_modules") { directories.push(dirname); pkg = yield* readConfigPackage(_path().default.join(dirname, PACKAGE_FILENAME)); const nextLoc = _path().default.dirname(dirname); if (dirname === nextLoc) { isPackage = false; break; } dirname = nextLoc; } return { filepath, directories, pkg, isPackage }; } const readConfigPackage = (0, utils$1.makeStaticFileCache)((filepath, content) => { let options; try { options = JSON.parse(content); } catch (err) { err.message = `${filepath}: Error while parsing JSON - ${err.message}`; throw err; } if (!options) throw new Error(`${filepath}: No config detected`); if (typeof options !== "object") { throw new Error(`${filepath}: Config returned typeof ${typeof options}`); } if (Array.isArray(options)) { throw new Error(`${filepath}: Expected config object but found array`); } return { filepath, dirname: _path().default.dirname(filepath), options }; }); }); unwrapExports(_package); var _package_1 = _package.findPackageData; // This is a generated file. Do not edit. var Space_Separator = /[\u1680\u2000-\u200A\u202F\u205F\u3000]/; var ID_Start = /[\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\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\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-\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-\u1877\u1880-\u1884\u1887-\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\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-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\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-\uAB65\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]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\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\uDCE0-\uDCF2\uDCF4\uDCF5\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\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\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\uDD00-\uDD43]|\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\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/; var ID_Continue = /[\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\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\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\u09FC\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\u0AF9-\u0AFF\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-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\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\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\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-\u13F5\u13F8-\u13FD\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\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\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\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-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\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-\uAB65\uAB70-\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-\uFE2F\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\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\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\uDCE0-\uDCF2\uDCF4\uDCF5\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\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\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\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\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]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\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\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/; var unicode = { Space_Separator: Space_Separator, ID_Start: ID_Start, ID_Continue: ID_Continue }; var util$5 = { isSpaceSeparator (c) { return typeof c === 'string' && unicode.Space_Separator.test(c) }, isIdStartChar (c) { return typeof c === 'string' && ( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c === '$') || (c === '_') || unicode.ID_Start.test(c) ) }, isIdContinueChar (c) { return typeof c === 'string' && ( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c === '$') || (c === '_') || (c === '\u200C') || (c === '\u200D') || unicode.ID_Continue.test(c) ) }, isDigit (c) { return typeof c === 'string' && /[0-9]/.test(c) }, isHexDigit (c) { return typeof c === 'string' && /[0-9A-Fa-f]/.test(c) }, }; let source; let parseState; let stack; let pos; let line; let column; let token; let key; let root$1; var parse$2 = function parse (text, reviver) { source = String(text); parseState = 'start'; stack = []; pos = 0; line = 1; column = 0; token = undefined; key = undefined; root$1 = undefined; do { token = lex(); // This code is unreachable. // if (!parseStates[parseState]) { // throw invalidParseState() // } parseStates[parseState](); } while (token.type !== 'eof') if (typeof reviver === 'function') { return internalize({'': root$1}, '', reviver) } return root$1 }; function internalize (holder, name, reviver) { const value = holder[name]; if (value != null && typeof value === 'object') { for (const key in value) { const replacement = internalize(value, key, reviver); if (replacement === undefined) { delete value[key]; } else { value[key] = replacement; } } } return reviver.call(holder, name, value) } let lexState; let buffer$1; let doubleQuote; let sign; let c; function lex () { lexState = 'default'; buffer$1 = ''; doubleQuote = false; sign = 1; for (;;) { c = peek(); // This code is unreachable. // if (!lexStates[lexState]) { // throw invalidLexState(lexState) // } const token = lexStates[lexState](); if (token) { return token } } } function peek () { if (source[pos]) { return String.fromCodePoint(source.codePointAt(pos)) } } function read$1 () { const c = peek(); if (c === '\n') { line++; column = 0; } else if (c) { column += c.length; } else { column++; } if (c) { pos += c.length; } return c } const lexStates = { default () { switch (c) { case '\t': case '\v': case '\f': case ' ': case '\u00A0': case '\uFEFF': case '\n': case '\r': case '\u2028': case '\u2029': read$1(); return case '/': read$1(); lexState = 'comment'; return case undefined: read$1(); return newToken('eof') } if (util$5.isSpaceSeparator(c)) { read$1(); return } // This code is unreachable. // if (!lexStates[parseState]) { // throw invalidLexState(parseState) // } return lexStates[parseState]() }, comment () { switch (c) { case '*': read$1(); lexState = 'multiLineComment'; return case '/': read$1(); lexState = 'singleLineComment'; return } throw invalidChar(read$1()) }, multiLineComment () { switch (c) { case '*': read$1(); lexState = 'multiLineCommentAsterisk'; return case undefined: throw invalidChar(read$1()) } read$1(); }, multiLineCommentAsterisk () { switch (c) { case '*': read$1(); return case '/': read$1(); lexState = 'default'; return case undefined: throw invalidChar(read$1()) } read$1(); lexState = 'multiLineComment'; }, singleLineComment () { switch (c) { case '\n': case '\r': case '\u2028': case '\u2029': read$1(); lexState = 'default'; return case undefined: read$1(); return newToken('eof') } read$1(); }, value () { switch (c) { case '{': case '[': return newToken('punctuator', read$1()) case 'n': read$1(); literal$1('ull'); return newToken('null', null) case 't': read$1(); literal$1('rue'); return newToken('boolean', true) case 'f': read$1(); literal$1('alse'); return newToken('boolean', false) case '-': case '+': if (read$1() === '-') { sign = -1; } lexState = 'sign'; return case '.': buffer$1 = read$1(); lexState = 'decimalPointLeading'; return case '0': buffer$1 = read$1(); lexState = 'zero'; return case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': buffer$1 = read$1(); lexState = 'decimalInteger'; return case 'I': read$1(); literal$1('nfinity'); return newToken('numeric', Infinity) case 'N': read$1(); literal$1('aN'); return newToken('numeric', NaN) case '"': case "'": doubleQuote = (read$1() === '"'); buffer$1 = ''; lexState = 'string'; return } throw invalidChar(read$1()) }, identifierNameStartEscape () { if (c !== 'u') { throw invalidChar(read$1()) } read$1(); const u = unicodeEscape(); switch (u) { case '$': case '_': break default: if (!util$5.isIdStartChar(u)) { throw invalidIdentifier() } break } buffer$1 += u; lexState = 'identifierName'; }, identifierName () { switch (c) { case '$': case '_': case '\u200C': case '\u200D': buffer$1 += read$1(); return case '\\': read$1(); lexState = 'identifierNameEscape'; return } if (util$5.isIdContinueChar(c)) { buffer$1 += read$1(); return } return newToken('identifier', buffer$1) }, identifierNameEscape () { if (c !== 'u') { throw invalidChar(read$1()) } read$1(); const u = unicodeEscape(); switch (u) { case '$': case '_': case '\u200C': case '\u200D': break default: if (!util$5.isIdContinueChar(u)) { throw invalidIdentifier() } break } buffer$1 += u; lexState = 'identifierName'; }, sign () { switch (c) { case '.': buffer$1 = read$1(); lexState = 'decimalPointLeading'; return case '0': buffer$1 = read$1(); lexState = 'zero'; return case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': buffer$1 = read$1(); lexState = 'decimalInteger'; return case 'I': read$1(); literal$1('nfinity'); return newToken('numeric', sign * Infinity) case 'N': read$1(); literal$1('aN'); return newToken('numeric', NaN) } throw invalidChar(read$1()) }, zero () { switch (c) { case '.': buffer$1 += read$1(); lexState = 'decimalPoint'; return case 'e': case 'E': buffer$1 += read$1(); lexState = 'decimalExponent'; return case 'x': case 'X': buffer$1 += read$1(); lexState = 'hexadecimal'; return } return newToken('numeric', sign * 0) }, decimalInteger () { switch (c) { case '.': buffer$1 += read$1(); lexState = 'decimalPoint'; return case 'e': case 'E': buffer$1 += read$1(); lexState = 'decimalExponent'; return } if (util$5.isDigit(c)) { buffer$1 += read$1(); return } return newToken('numeric', sign * Number(buffer$1)) }, decimalPointLeading () { if (util$5.isDigit(c)) { buffer$1 += read$1(); lexState = 'decimalFraction'; return } throw invalidChar(read$1()) }, decimalPoint () { switch (c) { case 'e': case 'E': buffer$1 += read$1(); lexState = 'decimalExponent'; return } if (util$5.isDigit(c)) { buffer$1 += read$1(); lexState = 'decimalFraction'; return } return newToken('numeric', sign * Number(buffer$1)) }, decimalFraction () { switch (c) { case 'e': case 'E': buffer$1 += read$1(); lexState = 'decimalExponent'; return } if (util$5.isDigit(c)) { buffer$1 += read$1(); return } return newToken('numeric', sign * Number(buffer$1)) }, decimalExponent () { switch (c) { case '+': case '-': buffer$1 += read$1(); lexState = 'decimalExponentSign'; return } if (util$5.isDigit(c)) { buffer$1 += read$1(); lexState = 'decimalExponentInteger'; return } throw invalidChar(read$1()) }, decimalExponentSign () { if (util$5.isDigit(c)) { buffer$1 += read$1(); lexState = 'decimalExponentInteger'; return } throw invalidChar(read$1()) }, decimalExponentInteger () { if (util$5.isDigit(c)) { buffer$1 += read$1(); return } return newToken('numeric', sign * Number(buffer$1)) }, hexadecimal () { if (util$5.isHexDigit(c)) { buffer$1 += read$1(); lexState = 'hexadecimalInteger'; return } throw invalidChar(read$1()) }, hexadecimalInteger () { if (util$5.isHexDigit(c)) { buffer$1 += read$1(); return } return newToken('numeric', sign * Number(buffer$1)) }, string () { switch (c) { case '\\': read$1(); buffer$1 += escape$1(); return case '"': if (doubleQuote) { read$1(); return newToken('string', buffer$1) } buffer$1 += read$1(); return case "'": if (!doubleQuote) { read$1(); return newToken('string', buffer$1) } buffer$1 += read$1(); return case '\n': case '\r': throw invalidChar(read$1()) case '\u2028': case '\u2029': separatorChar(c); break case undefined: throw invalidChar(read$1()) } buffer$1 += read$1(); }, start () { switch (c) { case '{': case '[': return newToken('punctuator', read$1()) // This code is unreachable since the default lexState handles eof. // case undefined: // return newToken('eof') } lexState = 'value'; }, beforePropertyName () { switch (c) { case '$': case '_': buffer$1 = read$1(); lexState = 'identifierName'; return case '\\': read$1(); lexState = 'identifierNameStartEscape'; return case '}': return newToken('punctuator', read$1()) case '"': case "'": doubleQuote = (read$1() === '"'); lexState = 'string'; return } if (util$5.isIdStartChar(c)) { buffer$1 += read$1(); lexState = 'identifierName'; return } throw invalidChar(read$1()) }, afterPropertyName () { if (c === ':') { return newToken('punctuator', read$1()) } throw invalidChar(read$1()) }, beforePropertyValue () { lexState = 'value'; }, afterPropertyValue () { switch (c) { case ',': case '}': return newToken('punctuator', read$1()) } throw invalidChar(read$1()) }, beforeArrayValue () { if (c === ']') { return newToken('punctuator', read$1()) } lexState = 'value'; }, afterArrayValue () { switch (c) { case ',': case ']': return newToken('punctuator', read$1()) } throw invalidChar(read$1()) }, end () { // This code is unreachable since it's handled by the default lexState. // if (c === undefined) { // read() // return newToken('eof') // } throw invalidChar(read$1()) }, }; function newToken (type, value) { return { type, value, line, column, } } function literal$1 (s) { for (const c of s) { const p = peek(); if (p !== c) { throw invalidChar(read$1()) } read$1(); } } function escape$1 () { const c = peek(); switch (c) { case 'b': read$1(); return '\b' case 'f': read$1(); return '\f' case 'n': read$1(); return '\n' case 'r': read$1(); return '\r' case 't': read$1(); return '\t' case 'v': read$1(); return '\v' case '0': read$1(); if (util$5.isDigit(peek())) { throw invalidChar(read$1()) } return '\0' case 'x': read$1(); return hexEscape() case 'u': read$1(); return unicodeEscape() case '\n': case '\u2028': case '\u2029': read$1(); return '' case '\r': read$1(); if (peek() === '\n') { read$1(); } return '' case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': throw invalidChar(read$1()) case undefined: throw invalidChar(read$1()) } return read$1() } function hexEscape () { let buffer = ''; let c = peek(); if (!util$5.isHexDigit(c)) { throw invalidChar(read$1()) } buffer += read$1(); c = peek(); if (!util$5.isHexDigit(c)) { throw invalidChar(read$1()) } buffer += read$1(); return String.fromCodePoint(parseInt(buffer, 16)) } function unicodeEscape () { let buffer = ''; let count = 4; while (count-- > 0) { const c = peek(); if (!util$5.isHexDigit(c)) { throw invalidChar(read$1()) } buffer += read$1(); } return String.fromCodePoint(parseInt(buffer, 16)) } const parseStates = { start () { if (token.type === 'eof') { throw invalidEOF() } push(); }, beforePropertyName () { switch (token.type) { case 'identifier': case 'string': key = token.value; parseState = 'afterPropertyName'; return case 'punctuator': // This code is unreachable since it's handled by the lexState. // if (token.value !== '}') { // throw invalidToken() // } pop(); return case 'eof': throw invalidEOF() } // This code is unreachable since it's handled by the lexState. // throw invalidToken() }, afterPropertyName () { // This code is unreachable since it's handled by the lexState. // if (token.type !== 'punctuator' || token.value !== ':') { // throw invalidToken() // } if (token.type === 'eof') { throw invalidEOF() } parseState = 'beforePropertyValue'; }, beforePropertyValue () { if (token.type === 'eof') { throw invalidEOF() } push(); }, beforeArrayValue () { if (token.type === 'eof') { throw invalidEOF() } if (token.type === 'punctuator' && token.value === ']') { pop(); return } push(); }, afterPropertyValue () { // This code is unreachable since it's handled by the lexState. // if (token.type !== 'punctuator') { // throw invalidToken() // } if (token.type === 'eof') { throw invalidEOF() } switch (token.value) { case ',': parseState = 'beforePropertyName'; return case '}': pop(); } // This code is unreachable since it's handled by the lexState. // throw invalidToken() }, afterArrayValue () { // This code is unreachable since it's handled by the lexState. // if (token.type !== 'punctuator') { // throw invalidToken() // } if (token.type === 'eof') { throw invalidEOF() } switch (token.value) { case ',': parseState = 'beforeArrayValue'; return case ']': pop(); } // This code is unreachable since it's handled by the lexState. // throw invalidToken() }, end () { // This code is unreachable since it's handled by the lexState. // if (token.type !== 'eof') { // throw invalidToken() // } }, }; function push () { let value; switch (token.type) { case 'punctuator': switch (token.value) { case '{': value = {}; break case '[': value = []; break } break case 'null': case 'boolean': case 'numeric': case 'string': value = token.value; break // This code is unreachable. // default: // throw invalidToken() } if (root$1 === undefined) { root$1 = value; } else { const parent = stack[stack.length - 1]; if (Array.isArray(parent)) { parent.push(value); } else { parent[key] = value; } } if (value !== null && typeof value === 'object') { stack.push(value); if (Array.isArray(value)) { parseState = 'beforeArrayValue'; } else { parseState = 'beforePropertyName'; } } else { const current = stack[stack.length - 1]; if (current == null) { parseState = 'end'; } else if (Array.isArray(current)) { parseState = 'afterArrayValue'; } else { parseState = 'afterPropertyValue'; } } } function pop () { stack.pop(); const current = stack[stack.length - 1]; if (current == null) { parseState = 'end'; } else if (Array.isArray(current)) { parseState = 'afterArrayValue'; } else { parseState = 'afterPropertyValue'; } } // This code is unreachable. // function invalidParseState () { // return new Error(`JSON5: invalid parse state '${parseState}'`) // } // This code is unreachable. // function invalidLexState (state) { // return new Error(`JSON5: invalid lex state '${state}'`) // } function invalidChar (c) { if (c === undefined) { return syntaxError(`JSON5: invalid end of input at ${line}:${column}`) } return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`) } function invalidEOF () { return syntaxError(`JSON5: invalid end of input at ${line}:${column}`) } // This code is unreachable. // function invalidToken () { // if (token.type === 'eof') { // return syntaxError(`JSON5: invalid end of input at ${line}:${column}`) // } // const c = String.fromCodePoint(token.value.codePointAt(0)) // return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`) // } function invalidIdentifier () { column -= 5; return syntaxError(`JSON5: invalid identifier character at ${line}:${column}`) } function separatorChar (c) { console.warn(`JSON5: '${formatChar(c)}' in strings is not valid ECMAScript; consider escaping`); } function formatChar (c) { const replacements = { "'": "\\'", '"': '\\"', '\\': '\\\\', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t', '\v': '\\v', '\0': '\\0', '\u2028': '\\u2028', '\u2029': '\\u2029', }; if (replacements[c]) { return replacements[c] } if (c < ' ') { const hexString = c.charCodeAt(0).toString(16); return '\\x' + ('00' + hexString).substring(hexString.length) } return c } function syntaxError (message) { const err = new SyntaxError(message); err.lineNumber = line; err.columnNumber = column; return err } var stringify = function stringify (value, replacer, space) { const stack = []; let indent = ''; let propertyList; let replacerFunc; let gap = ''; let quote; if ( replacer != null && typeof replacer === 'object' && !Array.isArray(replacer) ) { space = replacer.space; quote = replacer.quote; replacer = replacer.replacer; } if (typeof replacer === 'function') { replacerFunc = replacer; } else if (Array.isArray(replacer)) { propertyList = []; for (const v of replacer) { let item; if (typeof v === 'string') { item = v; } else if ( typeof v === 'number' || v instanceof String || v instanceof Number ) { item = String(v); } if (item !== undefined && propertyList.indexOf(item) < 0) { propertyList.push(item); } } } if (space instanceof Number) { space = Number(space); } else if (space instanceof String) { space = String(space); } if (typeof space === 'number') { if (space > 0) { space = Math.min(10, Math.floor(space)); gap = ' '.substr(0, space); } } else if (typeof space === 'string') { gap = space.substr(0, 10); } return serializeProperty('', {'': value}) function serializeProperty (key, holder) { let value = holder[key]; if (value != null) { if (typeof value.toJSON5 === 'function') { value = value.toJSON5(key); } else if (typeof value.toJSON === 'function') { value = value.toJSON(key); } } if (replacerFunc) { value = replacerFunc.call(holder, key, value); } if (value instanceof Number) { value = Number(value); } else if (value instanceof String) { value = String(value); } else if (value instanceof Boolean) { value = value.valueOf(); } switch (value) { case null: return 'null' case true: return 'true' case false: return 'false' } if (typeof value === 'string') { return quoteString(value) } if (typeof value === 'number') { return String(value) } if (typeof value === 'object') { return Array.isArray(value) ? serializeArray(value) : serializeObject(value) } return undefined } function quoteString (value) { const quotes = { "'": 0.1, '"': 0.2, }; const replacements = { "'": "\\'", '"': '\\"', '\\': '\\\\', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t', '\v': '\\v', '\0': '\\0', '\u2028': '\\u2028', '\u2029': '\\u2029', }; let product = ''; for (let i = 0; i < value.length; i++) { const c = value[i]; switch (c) { case "'": case '"': quotes[c]++; product += c; continue case '\0': if (util$5.isDigit(value[i + 1])) { product += '\\x00'; continue } } if (replacements[c]) { product += replacements[c]; continue } if (c < ' ') { let hexString = c.charCodeAt(0).toString(16); product += '\\x' + ('00' + hexString).substring(hexString.length); continue } product += c; } const quoteChar = quote || Object.keys(quotes).reduce((a, b) => (quotes[a] < quotes[b]) ? a : b); product = product.replace(new RegExp(quoteChar, 'g'), replacements[quoteChar]); return quoteChar + product + quoteChar } function serializeObject (value) { if (stack.indexOf(value) >= 0) { throw TypeError('Converting circular structure to JSON5') } stack.push(value); let stepback = indent; indent = indent + gap; let keys = propertyList || Object.keys(value); let partial = []; for (const key of keys) { const propertyString = serializeProperty(key, value); if (propertyString !== undefined) { let member = serializeKey(key) + ':'; if (gap !== '') { member += ' '; } member += propertyString; partial.push(member); } } let final; if (partial.length === 0) { final = '{}'; } else { let properties; if (gap === '') { properties = partial.join(','); final = '{' + properties + '}'; } else { let separator = ',\n' + indent; properties = partial.join(separator); final = '{\n' + indent + properties + ',\n' + stepback + '}'; } } stack.pop(); indent = stepback; return final } function serializeKey (key) { if (key.length === 0) { return quoteString(key) } const firstChar = String.fromCodePoint(key.codePointAt(0)); if (!util$5.isIdStartChar(firstChar)) { return quoteString(key) } for (let i = firstChar.length; i < key.length; i++) { if (!util$5.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) { return quoteString(key) } } return key } function serializeArray (value) { if (stack.indexOf(value) >= 0) { throw TypeError('Converting circular structure to JSON5') } stack.push(value); let stepback = indent; indent = indent + gap; let partial = []; for (let i = 0; i < value.length; i++) { const propertyString = serializeProperty(String(i), value); partial.push((propertyString !== undefined) ? propertyString : 'null'); } let final; if (partial.length === 0) { final = '[]'; } else { if (gap === '') { let properties = partial.join(','); final = '[' + properties + ']'; } else { let separator = ',\n' + indent; let properties = partial.join(separator); final = '[\n' + indent + properties + ',\n' + stepback + ']'; } } stack.pop(); indent = stepback; return final } }; const JSON5 = { parse: parse$2, stringify, }; var lib$i = JSON5; var dist = /*#__PURE__*/Object.freeze({ __proto__: null, 'default': lib$i }); var configApi = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = makeAPI; function _semver() { const data = _interopRequireDefault(semver); _semver = function () { return data; }; return data; } 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: lib$j.version, cache: cache.simple(), env, async: () => false, caller, assertVersion }; } 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(lib$j.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 "${lib$j.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: lib$j.version, range }); } }); unwrapExports(configApi); /*! https://mths.be/punycode v1.4.1 by @mathias */ /** Highest positive signed 32-bit float value */ var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 /** Bootstring parameters */ var base$1 = 36; var tMin = 1; var tMax = 26; var skew = 38; var damp = 700; var initialBias = 72; var initialN = 128; // 0x80 var delimiter$1 = '-'; // '\x2D' var regexNonASCII = /[^\x20-\x7E]/; // unprintable ASCII chars + non-ASCII chars var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators /** Error messages */ var errors = { 'overflow': 'Overflow: input needs wider integers to process', 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', 'invalid-input': 'Invalid input' }; /** Convenience shortcuts */ var baseMinusTMin = base$1 - tMin; var floor = Math.floor; var stringFromCharCode = String.fromCharCode; /*--------------------------------------------------------------------------*/ /** * A generic error utility function. * @private * @param {String} type The error type. * @returns {Error} Throws a `RangeError` with the applicable error message. */ function error(type) { throw new RangeError(errors[type]); } /** * A generic `Array#map` utility function. * @private * @param {Array} array The array to iterate over. * @param {Function} callback The function that gets called for every array * item. * @returns {Array} A new array of values returned by the callback function. */ function map(array, fn) { var length = array.length; var result = []; while (length--) { result[length] = fn(array[length]); } return result; } /** * A simple `Array#map`-like wrapper to work with domain name strings or email * addresses. * @private * @param {String} domain The domain name or email address. * @param {Function} callback The function that gets called for every * character. * @returns {Array} A new string of characters returned by the callback * function. */ function mapDomain(string, fn) { var parts = string.split('@'); var result = ''; if (parts.length > 1) { // In email addresses, only the domain name should be punycoded. Leave // the local part (i.e. everything up to `@`) intact. result = parts[0] + '@'; string = parts[1]; } // Avoid `split(regex)` for IE8 compatibility. See #17. string = string.replace(regexSeparators, '\x2E'); var labels = string.split('.'); var encoded = map(labels, fn).join('.'); return result + encoded; } /** * Creates an array containing the numeric code points of each Unicode * character in the string. While JavaScript uses UCS-2 internally, * this function will convert a pair of surrogate halves (each of which * UCS-2 exposes as separate characters) into a single code point, * matching UTF-16. * @see `punycode.ucs2.encode` * @see <https://mathiasbynens.be/notes/javascript-encoding> * @memberOf punycode.ucs2 * @name decode * @param {String} string The Unicode input string (UCS-2). * @returns {Array} The new array of code points. */ function ucs2decode(string) { var output = [], counter = 0, length = string.length, value, extra; while (counter < length) { value = string.charCodeAt(counter++); if (value >= 0xD800 && value <= 0xDBFF && counter < length) { // high surrogate, and there is a next character extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // low surrogate output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { // unmatched surrogate; only append this code unit, in case the next // code unit is the high surrogate of a surrogate pair output.push(value); counter--; } } else { output.push(value); } } return output; } /** * Converts a digit/integer into a basic code point. * @see `basicToDigit()` * @private * @param {Number} digit The numeric value of a basic code point. * @returns {Number} The basic code point whose value (when used for * representing integers) is `digit`, which needs to be in the range * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is * used; else, the lowercase form is used. The behavior is undefined * if `flag` is non-zero and `digit` has no uppercase form. */ function digitToBasic(digit, flag) { // 0..25 map to ASCII a..z or A..Z // 26..35 map to ASCII 0..9 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); } /** * Bias adaptation function as per section 3.4 of RFC 3492. * https://tools.ietf.org/html/rfc3492#section-3.4 * @private */ function adapt(delta, numPoints, firstTime) { var k = 0; delta = firstTime ? floor(delta / damp) : delta >> 1; delta += floor(delta / numPoints); for ( /* no initialization */ ; delta > baseMinusTMin * tMax >> 1; k += base$1) { delta = floor(delta / baseMinusTMin); } return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); } /** * Converts a string of Unicode symbols (e.g. a domain name label) to a * Punycode string of ASCII-only symbols. * @memberOf punycode * @param {String} input The string of Unicode symbols. * @returns {String} The resulting Punycode string of ASCII-only symbols. */ function encode$2(input) { var n, delta, handledCPCount, basicLength, bias, j, m, q, k, t, currentValue, output = [], /** `inputLength` will hold the number of code points in `input`. */ inputLength, /** Cached calculation results */ handledCPCountPlusOne, baseMinusT, qMinusT; // Convert the input in UCS-2 to Unicode input = ucs2decode(input); // Cache the length inputLength = input.length; // Initialize the state n = initialN; delta = 0; bias = initialBias; // Handle the basic code points for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < 0x80) { output.push(stringFromCharCode(currentValue)); } } handledCPCount = basicLength = output.length; // `handledCPCount` is the number of code points that have been handled; // `basicLength` is the number of basic code points. // Finish the basic string - if it is not empty - with a delimiter if (basicLength) { output.push(delimiter$1); } // Main encoding loop: while (handledCPCount < inputLength) { // All non-basic code points < n have been handled already. Find the next // larger one: for (m = maxInt, j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue >= n && currentValue < m) { m = currentValue; } } // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>, // but guard against overflow handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { error('overflow'); } delta += (m - n) * handledCPCountPlusOne; n = m; for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < n && ++delta > maxInt) { error('overflow'); } if (currentValue == n) { // Represent delta as a generalized variable-length integer for (q = delta, k = base$1; /* no condition */ ; k += base$1) { t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (q < t) { break; } qMinusT = q - t; baseMinusT = base$1 - t; output.push( stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) ); q = floor(qMinusT / baseMinusT); } output.push(stringFromCharCode(digitToBasic(q, 0))); bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); delta = 0; ++handledCPCount; } } ++delta; ++n; } return output.join(''); } /** * Converts a Unicode string representing a domain name or an email address to * Punycode. Only the non-ASCII parts of the domain name will be converted, * i.e. it doesn't matter if you call it with a domain that's already in * ASCII. * @memberOf punycode * @param {String} input The domain name or email address to convert, as a * Unicode string. * @returns {String} The Punycode representation of the given domain name or * email address. */ function toASCII(input) { return mapDomain(input, function(string) { return regexNonASCII.test(string) ? 'xn--' + encode$2(string) : string; }); } // 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. // If obj.hasOwnProperty has been overridden, then calling // obj.hasOwnProperty(prop) will break. // See: https://github.com/joyent/node/issues/1707 function hasOwnProperty$d(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } var isArray$4 = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; function stringifyPrimitive(v) { switch (typeof v) { case 'string': return v; case 'boolean': return v ? 'true' : 'false'; case 'number': return isFinite(v) ? v : ''; default: return ''; } } function stringify$1 (obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (obj === null) { obj = undefined; } if (typeof obj === 'object') { return map$1(objectKeys$1(obj), function(k) { var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; if (isArray$4(obj[k])) { return map$1(obj[k], function(v) { return ks + encodeURIComponent(stringifyPrimitive(v)); }).join(sep); } else { return ks + encodeURIComponent(stringifyPrimitive(obj[k])); } }).join(sep); } if (!name) return ''; return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj)); } function map$1 (xs, f) { if (xs.map) return xs.map(f); var res = []; for (var i = 0; i < xs.length; i++) { res.push(f(xs[i], i)); } return res; } var objectKeys$1 = Object.keys || function (obj) { var res = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); } return res; }; function parse$3(qs, sep, eq, options) { sep = sep || '&'; eq = eq || '='; var obj = {}; if (typeof qs !== 'string' || qs.length === 0) { return obj; } var regexp = /\+/g; qs = qs.split(sep); var maxKeys = 1000; if (options && typeof options.maxKeys === 'number') { maxKeys = options.maxKeys; } var len = qs.length; // maxKeys <= 0 means that we should not limit keys count if (maxKeys > 0 && len > maxKeys) { len = maxKeys; } for (var i = 0; i < len; ++i) { var x = qs[i].replace(regexp, '%20'), idx = x.indexOf(eq), kstr, vstr, k, v; if (idx >= 0) { kstr = x.substr(0, idx); vstr = x.substr(idx + 1); } else { kstr = x; vstr = ''; } k = decodeURIComponent(kstr); v = decodeURIComponent(vstr); if (!hasOwnProperty$d(obj, k)) { obj[k] = v; } else if (isArray$4(obj[k])) { obj[k].push(v); } else { obj[k] = [obj[k], v]; } } return obj; }var qs = { encode: stringify$1, stringify: stringify$1, decode: parse$3, parse: parse$3 }; var qs$1 = /*#__PURE__*/Object.freeze({ __proto__: null, stringify: stringify$1, parse: parse$3, 'default': qs, encode: stringify$1, decode: parse$3 }); // Copyright Joyent, Inc. and other Node contributors. var url = { parse: urlParse, resolve: urlResolve, resolveObject: urlResolveObject, format: urlFormat, Url: Url }; function Url() { this.protocol = null; this.slashes = null; this.auth = null; this.host = null; this.port = null; this.hostname = null; this.hash = null; this.search = null; this.query = null; this.pathname = null; this.path = null; this.href = null; } // Reference: RFC 3986, RFC 1808, RFC 2396 // define these here so at least they only have to be // compiled once on the first module load. var protocolPattern = /^([a-z0-9.+-]+:)/i, portPattern = /:[0-9]*$/, // Special case for a simple path URL simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, // RFC 2396: characters reserved for delimiting URLs. // We actually just auto-escape these. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], // RFC 2396: characters not allowed for various reasons. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), // Allowed by RFCs, but cause of XSS attacks. Always escape these. autoEscape = ['\''].concat(unwise), // Characters that are never ever allowed in a hostname. // Note that any invalid chars are also handled, but these // are the ones that are *expected* to be seen, so we fast-path // them. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), hostEndingChars = ['/', '?', '#'], hostnameMaxLen = 255, hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, // protocols that can allow "unsafe" and "unwise" chars. unsafeProtocol = { 'javascript': true, 'javascript:': true }, // protocols that never have a hostname. hostlessProtocol = { 'javascript': true, 'javascript:': true }, // protocols that always contain a // bit. slashedProtocol = { 'http': true, 'https': true, 'ftp': true, 'gopher': true, 'file': true, 'http:': true, 'https:': true, 'ftp:': true, 'gopher:': true, 'file:': true }; function urlParse(url, parseQueryString, slashesDenoteHost) { if (url && isObject$1(url) && url instanceof Url) return url; var u = new Url; u.parse(url, parseQueryString, slashesDenoteHost); return u; } Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { return parse$4(this, url, parseQueryString, slashesDenoteHost); }; function parse$4(self, url, parseQueryString, slashesDenoteHost) { if (!isString(url)) { throw new TypeError('Parameter \'url\' must be a string, not ' + typeof url); } // Copy chrome, IE, opera backslash-handling behavior. // Back slashes before the query string get converted to forward slashes // See: https://code.google.com/p/chromium/issues/detail?id=25916 var queryIndex = url.indexOf('?'), splitter = (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', uSplit = url.split(splitter), slashRegex = /\\/g; uSplit[0] = uSplit[0].replace(slashRegex, '/'); url = uSplit.join(splitter); var rest = url; // trim before proceeding. // This is to support parse stuff like " http://foo.com \n" rest = rest.trim(); if (!slashesDenoteHost && url.split('#').length === 1) { // Try fast path regexp var simplePath = simplePathPattern.exec(rest); if (simplePath) { self.path = rest; self.href = rest; self.pathname = simplePath[1]; if (simplePath[2]) { self.search = simplePath[2]; if (parseQueryString) { self.query = parse$3(self.search.substr(1)); } else { self.query = self.search.substr(1); } } else if (parseQueryString) { self.search = ''; self.query = {}; } return self; } } var proto = protocolPattern.exec(rest); if (proto) { proto = proto[0]; var lowerProto = proto.toLowerCase(); self.protocol = lowerProto; rest = rest.substr(proto.length); } // figure out if it's got a host // user@server is *always* interpreted as a hostname, and url // resolution will treat //foo/bar as host=foo,path=bar because that's // how the browser resolves relative URLs. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { var slashes = rest.substr(0, 2) === '//'; if (slashes && !(proto && hostlessProtocol[proto])) { rest = rest.substr(2); self.slashes = true; } } var i, hec, l, p; if (!hostlessProtocol[proto] && (slashes || (proto && !slashedProtocol[proto]))) { // there's a hostname. // the first instance of /, ?, ;, or # ends the host. // // If there is an @ in the hostname, then non-host chars *are* allowed // to the left of the last @ sign, unless some host-ending character // comes *before* the @-sign. // URLs are obnoxious. // // ex: // http://a@b@c/ => user:a@b host:c // http://a@b?@c => user:a host:c path:/?@c // v0.12 TODO(isaacs): This is not quite how Chrome does things. // Review our test case against browsers more comprehensively. // find the first instance of any hostEndingChars var hostEnd = -1; for (i = 0; i < hostEndingChars.length; i++) { hec = rest.indexOf(hostEndingChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } // at this point, either we have an explicit point where the // auth portion cannot go past, or the last @ char is the decider. var auth, atSign; if (hostEnd === -1) { // atSign can be anywhere. atSign = rest.lastIndexOf('@'); } else { // atSign must be in auth portion. // http://a@b/c@d => host:b auth:a path:/c@d atSign = rest.lastIndexOf('@', hostEnd); } // Now we have a portion which is definitely the auth. // Pull that off. if (atSign !== -1) { auth = rest.slice(0, atSign); rest = rest.slice(atSign + 1); self.auth = decodeURIComponent(auth); } // the host is the remaining to the left of the first non-host char hostEnd = -1; for (i = 0; i < nonHostChars.length; i++) { hec = rest.indexOf(nonHostChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } // if we still have not hit it, then the entire thing is a host. if (hostEnd === -1) hostEnd = rest.length; self.host = rest.slice(0, hostEnd); rest = rest.slice(hostEnd); // pull out port. parseHost(self); // we've indicated that there is a hostname, // so even if it's empty, it has to be present. self.hostname = self.hostname || ''; // if hostname begins with [ and ends with ] // assume that it's an IPv6 address. var ipv6Hostname = self.hostname[0] === '[' && self.hostname[self.hostname.length - 1] === ']'; // validate a little. if (!ipv6Hostname) { var hostparts = self.hostname.split(/\./); for (i = 0, l = hostparts.length; i < l; i++) { var part = hostparts[i]; if (!part) continue; if (!part.match(hostnamePartPattern)) { var newpart = ''; for (var j = 0, k = part.length; j < k; j++) { if (part.charCodeAt(j) > 127) { // we replace non-ASCII char with a temporary placeholder // we need this to make sure size of hostname is not // broken by replacing non-ASCII by nothing newpart += 'x'; } else { newpart += part[j]; } } // we test again with ASCII char only if (!newpart.match(hostnamePartPattern)) { var validParts = hostparts.slice(0, i); var notHost = hostparts.slice(i + 1); var bit = part.match(hostnamePartStart); if (bit) { validParts.push(bit[1]); notHost.unshift(bit[2]); } if (notHost.length) { rest = '/' + notHost.join('.') + rest; } self.hostname = validParts.join('.'); break; } } } } if (self.hostname.length > hostnameMaxLen) { self.hostname = ''; } else { // hostnames are always lower case. self.hostname = self.hostname.toLowerCase(); } if (!ipv6Hostname) { // IDNA Support: Returns a punycoded representation of "domain". // It only converts parts of the domain name that // have non-ASCII characters, i.e. it doesn't matter if // you call it with a domain that already is ASCII-only. self.hostname = toASCII(self.hostname); } p = self.port ? ':' + self.port : ''; var h = self.hostname || ''; self.host = h + p; self.href += self.host; // strip [ and ] from the hostname // the host field still retains them, though if (ipv6Hostname) { self.hostname = self.hostname.substr(1, self.hostname.length - 2); if (rest[0] !== '/') { rest = '/' + rest; } } } // now rest is set to the post-host stuff. // chop off any delim chars. if (!unsafeProtocol[lowerProto]) { // First, make 100% sure that any "autoEscape" chars get // escaped, even if encodeURIComponent doesn't think they // need to be. for (i = 0, l = autoEscape.length; i < l; i++) { var ae = autoEscape[i]; if (rest.indexOf(ae) === -1) continue; var esc = encodeURIComponent(ae); if (esc === ae) { esc = escape(ae); } rest = rest.split(ae).join(esc); } } // chop off from the tail first. var hash = rest.indexOf('#'); if (hash !== -1) { // got a fragment string. self.hash = rest.substr(hash); rest = rest.slice(0, hash); } var qm = rest.indexOf('?'); if (qm !== -1) { self.search = rest.substr(qm); self.query = rest.substr(qm + 1); if (parseQueryString) { self.query = parse$3(self.query); } rest = rest.slice(0, qm); } else if (parseQueryString) { // no query string, but parseQueryString still requested self.search = ''; self.query = {}; } if (rest) self.pathname = rest; if (slashedProtocol[lowerProto] && self.hostname && !self.pathname) { self.pathname = '/'; } //to support http.request if (self.pathname || self.search) { p = self.pathname || ''; var s = self.search || ''; self.path = p + s; } // finally, reconstruct the href based on what has been validated. self.href = format$1(self); return self; } // format a parsed object into a url string function urlFormat(obj) { // ensure it's an object, and not a string url. // If it's an obj, this is a no-op. // this way, you can call url_format() on strings // to clean up potentially wonky urls. if (isString(obj)) obj = parse$4({}, obj); return format$1(obj); } function format$1(self) { var auth = self.auth || ''; if (auth) { auth = encodeURIComponent(auth); auth = auth.replace(/%3A/i, ':'); auth += '@'; } var protocol = self.protocol || '', pathname = self.pathname || '', hash = self.hash || '', host = false, query = ''; if (self.host) { host = auth + self.host; } else if (self.hostname) { host = auth + (self.hostname.indexOf(':') === -1 ? self.hostname : '[' + this.hostname + ']'); if (self.port) { host += ':' + self.port; } } if (self.query && isObject$1(self.query) && Object.keys(self.query).length) { query = stringify$1(self.query); } var search = self.search || (query && ('?' + query)) || ''; if (protocol && protocol.substr(-1) !== ':') protocol += ':'; // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. // unless they had them to begin with. if (self.slashes || (!protocol || slashedProtocol[protocol]) && host !== false) { host = '//' + (host || ''); if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; } else if (!host) { host = ''; } if (hash && hash.charAt(0) !== '#') hash = '#' + hash; if (search && search.charAt(0) !== '?') search = '?' + search; pathname = pathname.replace(/[?#]/g, function(match) { return encodeURIComponent(match); }); search = search.replace('#', '%23'); return protocol + host + pathname + search + hash; } Url.prototype.format = function() { return format$1(this); }; function urlResolve(source, relative) { return urlParse(source, false, true).resolve(relative); } Url.prototype.resolve = function(relative) { return this.resolveObject(urlParse(relative, false, true)).format(); }; function urlResolveObject(source, relative) { if (!source) return relative; return urlParse(source, false, true).resolveObject(relative); } Url.prototype.resolveObject = function(relative) { if (isString(relative)) { var rel = new Url(); rel.parse(relative, false, true); relative = rel; } var result = new Url(); var tkeys = Object.keys(this); for (var tk = 0; tk < tkeys.length; tk++) { var tkey = tkeys[tk]; result[tkey] = this[tkey]; } // hash is always overridden, no matter what. // even href="" will remove it. result.hash = relative.hash; // if the relative url is empty, then there's nothing left to do here. if (relative.href === '') { result.href = result.format(); return result; } // hrefs like //foo/bar always cut to the protocol. if (relative.slashes && !relative.protocol) { // take everything except the protocol from relative var rkeys = Object.keys(relative); for (var rk = 0; rk < rkeys.length; rk++) { var rkey = rkeys[rk]; if (rkey !== 'protocol') result[rkey] = relative[rkey]; } //urlParse appends trailing / to urls like http://www.example.com if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) { result.path = result.pathname = '/'; } result.href = result.format(); return result; } var relPath; if (relative.protocol && relative.protocol !== result.protocol) { // if it's a known url protocol, then changing // the protocol does weird things // first, if it's not file:, then we MUST have a host, // and if there was a path // to begin with, then we MUST have a path. // if it is file:, then the host is dropped, // because that's known to be hostless. // anything else is assumed to be absolute. if (!slashedProtocol[relative.protocol]) { var keys = Object.keys(relative); for (var v = 0; v < keys.length; v++) { var k = keys[v]; result[k] = relative[k]; } result.href = result.format(); return result; } result.protocol = relative.protocol; if (!relative.host && !hostlessProtocol[relative.protocol]) { relPath = (relative.pathname || '').split('/'); while (relPath.length && !(relative.host = relPath.shift())); if (!relative.host) relative.host = ''; if (!relative.hostname) relative.hostname = ''; if (relPath[0] !== '') relPath.unshift(''); if (relPath.length < 2) relPath.unshift(''); result.pathname = relPath.join('/'); } else { result.pathname = relative.pathname; } result.search = relative.search; result.query = relative.query; result.host = relative.host || ''; result.auth = relative.auth; result.hostname = relative.hostname || relative.host; result.port = relative.port; // to support http.request if (result.pathname || result.search) { var p = result.pathname || ''; var s = result.search || ''; result.path = p + s; } result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; } var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), isRelAbs = ( relative.host || relative.pathname && relative.pathname.charAt(0) === '/' ), mustEndAbs = (isRelAbs || isSourceAbs || (result.host && relative.pathname)), removeAllDots = mustEndAbs, srcPath = result.pathname && result.pathname.split('/') || [], psychotic = result.protocol && !slashedProtocol[result.protocol]; relPath = relative.pathname && relative.pathname.split('/') || []; // if the url is a non-slashed url, then relative // links like ../.. should be able // to crawl up to the hostname, as well. This is strange. // result.protocol has already been set by now. // Later on, put the first path part into the host field. if (psychotic) { result.hostname = ''; result.port = null; if (result.host) { if (srcPath[0] === '') srcPath[0] = result.host; else srcPath.unshift(result.host); } result.host = ''; if (relative.protocol) { relative.hostname = null; relative.port = null; if (relative.host) { if (relPath[0] === '') relPath[0] = relative.host; else relPath.unshift(relative.host); } relative.host = null; } mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); } var authInHost; if (isRelAbs) { // it's absolute. result.host = (relative.host || relative.host === '') ? relative.host : result.host; result.hostname = (relative.hostname || relative.hostname === '') ? relative.hostname : result.hostname; result.search = relative.search; result.query = relative.query; srcPath = relPath; // fall through to the dot-handling below. } else if (relPath.length) { // it's relative // throw away the existing file, and take the new path instead. if (!srcPath) srcPath = []; srcPath.pop(); srcPath = srcPath.concat(relPath); result.search = relative.search; result.query = relative.query; } else if (!isNullOrUndefined(relative.search)) { // just pull out the search. // like href='?foo'. // Put this after the other two cases because it simplifies the booleans if (psychotic) { result.hostname = result.host = srcPath.shift(); //occationaly the auth can get stuck only in host //this especially happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } result.search = relative.search; result.query = relative.query; //to support http.request if (!isNull(result.pathname) || !isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.href = result.format(); return result; } if (!srcPath.length) { // no path at all. easy. // we've already handled the other stuff above. result.pathname = null; //to support http.request if (result.search) { result.path = '/' + result.search; } else { result.path = null; } result.href = result.format(); return result; } // if a url ENDs in . or .., then it must get a trailing slash. // however, if it ends in anything else non-slashy, // then it must NOT get a trailing slash. var last = srcPath.slice(-1)[0]; var hasTrailingSlash = ( (result.host || relative.host || srcPath.length > 1) && (last === '.' || last === '..') || last === ''); // strip single dots, resolve double dots to parent dir // if the path tries to go above the root, `up` ends up > 0 var up = 0; for (var i = srcPath.length; i >= 0; i--) { last = srcPath[i]; if (last === '.') { srcPath.splice(i, 1); } else if (last === '..') { srcPath.splice(i, 1); up++; } else if (up) { srcPath.splice(i, 1); up--; } } // if the path is allowed to go above the root, restore leading ..s if (!mustEndAbs && !removeAllDots) { for (; up--; up) { srcPath.unshift('..'); } } if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { srcPath.unshift(''); } if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { srcPath.push(''); } var isAbsolute = srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/'); // put the host back if (psychotic) { result.hostname = result.host = isAbsolute ? '' : srcPath.length ? srcPath.shift() : ''; //occationaly the auth can get stuck only in host //this especially happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } mustEndAbs = mustEndAbs || (result.host && srcPath.length); if (mustEndAbs && !isAbsolute) { srcPath.unshift(''); } if (!srcPath.length) { result.pathname = null; result.path = null; } else { result.pathname = srcPath.join('/'); } //to support request.http if (!isNull(result.pathname) || !isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.auth = relative.auth || result.auth; result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; }; Url.prototype.parseHost = function() { return parseHost(this); }; function parseHost(self) { var host = self.host; var port = portPattern.exec(host); if (port) { port = port[0]; if (port !== ':') { self.port = port.substr(1); } host = host.substr(0, host.length - port.length); } if (host) self.hostname = host; } var url$1 = /*#__PURE__*/Object.freeze({ __proto__: null, parse: urlParse, resolve: urlResolve, resolveObject: urlResolveObject, format: urlFormat, 'default': url, Url: Url }); var _import = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = import_; function import_(filepath) { return import(filepath); } }); unwrapExports(_import); var require$$1$1 = getCjsExportFromNamespace(url$1); var moduleTypes = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = loadCjsOrMjsDefault; function _path() { const data = _interopRequireDefault(require$$1); _path = function () { return data; }; return data; } function _url() { const data = require$$1$1; _url = function () { return data; }; return data; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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); } } 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); }); }; } let import_; try { import_ = _import.default; } catch (_unused) {} function* loadCjsOrMjsDefault(filepath, asyncError) { switch (guessJSModuleType(filepath)) { case "cjs": return loadCjsDefault(); case "unknown": try { return loadCjsDefault(filepath); } catch (e) { if (e.code !== "ERR_REQUIRE_ESM") throw e; } case "mjs": if (yield* (0, async.isAsync)()) { return yield* (0, async.waitFor)(loadMjsDefault(filepath)); } throw new Error(asyncError); } } function guessJSModuleType(filename) { switch (_path().default.extname(filename)) { case ".cjs": return "cjs"; case ".mjs": return "mjs"; default: return "unknown"; } } function loadCjsDefault(filepath) { const module = commonjsRequire(); return (module == null ? void 0 : module.__esModule) ? module.default || undefined : module; } function loadMjsDefault(_x) { return _loadMjsDefault.apply(this, arguments); } function _loadMjsDefault() { _loadMjsDefault = _asyncToGenerator(function* (filepath) { if (!import_) { throw new Error("Internal error: Native ECMAScript modules aren't supported" + " by this platform.\n"); } const module = yield import_((0, _url().pathToFileURL)(filepath)); return module.default; }); return _loadMjsDefault.apply(this, arguments); } }); unwrapExports(moduleTypes); /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } var _arrayMap = arrayMap; /** Used as references for various `Number` constants. */ var INFINITY$1 = 1 / 0; /** Used to convert symbols to primitives and strings. */ var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined, symbolToString = symbolProto$1 ? symbolProto$1.toString : undefined; /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray_1(value)) { // Recursively convert values (susceptible to call stack limits). return _arrayMap(value, baseToString) + ''; } if (isSymbol_1(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result; } var _baseToString = baseToString; /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString$2(value) { return value == null ? '' : _baseToString(value); } var toString_1 = toString$2; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar$1 = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar$1.source); /** * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escapeRegExp('[lodash](https://lodash.com/)'); * // => '\[lodash\]\(https://lodash\.com/\)' */ function escapeRegExp(string) { string = toString_1(string); return (string && reHasRegExpChar.test(string)) ? string.replace(reRegExpChar$1, '\\$&') : string; } var escapeRegExp_1 = escapeRegExp; var patternToRegex = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = pathToPattern; function _path() { const data = _interopRequireDefault(require$$1); _path = function () { return data; }; return data; } function _escapeRegExp() { const data = _interopRequireDefault(escapeRegExp_1); _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("")); } }); unwrapExports(patternToRegex); var caller = function () { // see https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi var origPrepareStackTrace = Error.prepareStackTrace; Error.prepareStackTrace = function (_, stack) { return stack; }; var stack = (new Error()).stack; Error.prepareStackTrace = origPrepareStackTrace; return stack[2].getFileName(); }; var pathParse = createCommonjsModule(function (module) { var isWindows = process.platform === 'win32'; // Regex to split a windows path into three parts: [*, device, slash, // tail] windows-only var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; // Regex to split the tail part of the above into [*, dir, basename, ext] var splitTailRe = /^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/; var win32 = {}; // Function to split a filename into [root, dir, basename, ext] function win32SplitPath(filename) { // Separate device+slash from tail var result = splitDeviceRe.exec(filename), device = (result[1] || '') + (result[2] || ''), tail = result[3] || ''; // Split the tail into dir, basename and extension var result2 = splitTailRe.exec(tail), dir = result2[1], basename = result2[2], ext = result2[3]; return [device, dir, basename, ext]; } win32.parse = function(pathString) { if (typeof pathString !== 'string') { throw new TypeError( "Parameter 'pathString' must be a string, not " + typeof pathString ); } var allParts = win32SplitPath(pathString); if (!allParts || allParts.length !== 4) { throw new TypeError("Invalid path '" + pathString + "'"); } return { root: allParts[0], dir: allParts[0] + allParts[1].slice(0, -1), base: allParts[2], ext: allParts[3], name: allParts[2].slice(0, allParts[2].length - allParts[3].length) }; }; // Split a filename into [root, dir, basename, ext], unix version // 'root' is just a slash, or nothing. var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; var posix = {}; function posixSplitPath(filename) { return splitPathRe.exec(filename).slice(1); } posix.parse = function(pathString) { if (typeof pathString !== 'string') { throw new TypeError( "Parameter 'pathString' must be a string, not " + typeof pathString ); } var allParts = posixSplitPath(pathString); if (!allParts || allParts.length !== 4) { throw new TypeError("Invalid path '" + pathString + "'"); } allParts[1] = allParts[1] || ''; allParts[2] = allParts[2] || ''; allParts[3] = allParts[3] || ''; return { root: allParts[0], dir: allParts[0] + allParts[1].slice(0, -1), base: allParts[2], ext: allParts[3], name: allParts[2].slice(0, allParts[2].length - allParts[3].length) }; }; if (isWindows) module.exports = win32.parse; else /* posix */ module.exports = posix.parse; module.exports.posix = posix.parse; module.exports.win32 = win32.parse; }); var pathParse_1 = pathParse.posix; var pathParse_2 = pathParse.win32; var parse$5 = require$$1.parse || pathParse; var getNodeModulesDirs = function getNodeModulesDirs(absoluteStart, modules) { var prefix = '/'; if ((/^([A-Za-z]:)/).test(absoluteStart)) { prefix = ''; } else if ((/^\\\\/).test(absoluteStart)) { prefix = '\\\\'; } var paths = [absoluteStart]; var parsed = parse$5(absoluteStart); while (parsed.dir !== paths[paths.length - 1]) { paths.push(parsed.dir); parsed = parse$5(parsed.dir); } return paths.reduce(function (dirs, aPath) { return dirs.concat(modules.map(function (moduleDir) { return require$$1.resolve(prefix, aPath, moduleDir); })); }, []); }; var nodeModulesPaths = function nodeModulesPaths(start, opts, request) { var modules = opts && opts.moduleDirectory ? [].concat(opts.moduleDirectory) : ['node_modules']; if (opts && typeof opts.paths === 'function') { return opts.paths( request, start, function () { return getNodeModulesDirs(start, modules); }, opts ); } var dirs = getNodeModulesDirs(start, modules); return opts && opts.paths ? dirs.concat(opts.paths) : dirs; }; var normalizeOptions = function (x, opts) { /** * This file is purposefully a passthrough. It's expected that third-party * environments will override it at runtime in order to inject special logic * into `resolve` (by manipulating the options). One such example is the PnP * code path in Yarn. */ return opts || {}; }; /* eslint no-invalid-this: 1 */ var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; var slice = Array.prototype.slice; var toStr = Object.prototype.toString; var funcType = '[object Function]'; var implementation = function bind(that) { var target = this; if (typeof target !== 'function' || toStr.call(target) !== funcType) { throw new TypeError(ERROR_MESSAGE + target); } var args = slice.call(arguments, 1); var bound; var binder = function () { if (this instanceof bound) { var result = target.apply( this, args.concat(slice.call(arguments)) ); if (Object(result) === result) { return result; } return this; } else { return target.apply( that, args.concat(slice.call(arguments)) ); } }; var boundLength = Math.max(0, target.length - args.length); var boundArgs = []; for (var i = 0; i < boundLength; i++) { boundArgs.push('$' + i); } bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); if (target.prototype) { var Empty = function Empty() {}; Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; var functionBind = Function.prototype.bind || implementation; var src$1 = functionBind.call(Function.call, Object.prototype.hasOwnProperty); var assert$1 = true; var async_hooks = ">= 8"; var buffer_ieee754 = "< 0.9.7"; var buffer$2 = true; var child_process = true; var cluster = true; var console$1 = true; var constants$1 = true; var crypto = true; var _debug_agent = ">= 1 && < 8"; var _debugger = "< 8"; var dgram = true; var diagnostics_channel = ">= 15.1"; var dns = true; var domain = ">= 0.7.12"; var events = true; var freelist = "< 6"; var fs$1 = true; var _http_agent = ">= 0.11.1"; var _http_client = ">= 0.11.1"; var _http_common = ">= 0.11.1"; var _http_incoming = ">= 0.11.1"; var _http_outgoing = ">= 0.11.1"; var _http_server = ">= 0.11.1"; var http = true; var http2 = ">= 8.8"; var https = true; var inspector = ">= 8.0.0"; var _linklist = "< 8"; var module = true; var net = true; var os$3 = true; var path$1 = true; var perf_hooks = ">= 8.5"; var process$1 = ">= 1"; var punycode = true; var querystring = true; var readline = true; var repl = true; var smalloc = ">= 0.11.5 && < 3"; var _stream_duplex = ">= 0.9.4"; var _stream_transform = ">= 0.9.4"; var _stream_wrap = ">= 1.4.1"; var _stream_passthrough = ">= 0.9.4"; var _stream_readable = ">= 0.9.4"; var _stream_writable = ">= 0.9.4"; var stream = true; var string_decoder = true; var sys = [ ">= 0.6 && < 0.7", ">= 0.8" ]; var timers = true; var _tls_common = ">= 0.11.13"; var _tls_legacy = ">= 0.11.3 && < 10"; var _tls_wrap = ">= 0.11.3"; var tls = true; var trace_events = ">= 10"; var tty$3 = true; var url$2 = true; var util$6 = true; var v8 = ">= 1"; var vm = true; var wasi = ">= 13.4 && < 13.5"; var worker_threads = ">= 11.7"; var zlib = true; var core$1 = { assert: assert$1, "assert/strict": ">= 15", async_hooks: async_hooks, buffer_ieee754: buffer_ieee754, buffer: buffer$2, child_process: child_process, cluster: cluster, console: console$1, constants: constants$1, crypto: crypto, _debug_agent: _debug_agent, _debugger: _debugger, dgram: dgram, diagnostics_channel: diagnostics_channel, dns: dns, "dns/promises": ">= 15", domain: domain, events: events, freelist: freelist, fs: fs$1, "fs/promises": [ ">= 10 && < 10.1", ">= 14" ], _http_agent: _http_agent, _http_client: _http_client, _http_common: _http_common, _http_incoming: _http_incoming, _http_outgoing: _http_outgoing, _http_server: _http_server, http: http, http2: http2, https: https, inspector: inspector, _linklist: _linklist, module: module, net: net, "node-inspect/lib/_inspect": ">= 7.6.0 && < 12", "node-inspect/lib/internal/inspect_client": ">= 7.6.0 && < 12", "node-inspect/lib/internal/inspect_repl": ">= 7.6.0 && < 12", os: os$3, path: path$1, perf_hooks: perf_hooks, process: process$1, punycode: punycode, querystring: querystring, readline: readline, repl: repl, smalloc: smalloc, _stream_duplex: _stream_duplex, _stream_transform: _stream_transform, _stream_wrap: _stream_wrap, _stream_passthrough: _stream_passthrough, _stream_readable: _stream_readable, _stream_writable: _stream_writable, stream: stream, "stream/promises": ">= 15", string_decoder: string_decoder, sys: sys, timers: timers, "timers/promises": ">= 15", _tls_common: _tls_common, _tls_legacy: _tls_legacy, _tls_wrap: _tls_wrap, tls: tls, trace_events: trace_events, tty: tty$3, url: url$2, util: util$6, "v8/tools/arguments": ">= 10 && < 12", "v8/tools/codemap": [ ">= 4.4.0 && < 5", ">= 5.2.0 && < 12" ], "v8/tools/consarray": [ ">= 4.4.0 && < 5", ">= 5.2.0 && < 12" ], "v8/tools/csvparser": [ ">= 4.4.0 && < 5", ">= 5.2.0 && < 12" ], "v8/tools/logreader": [ ">= 4.4.0 && < 5", ">= 5.2.0 && < 12" ], "v8/tools/profile_view": [ ">= 4.4.0 && < 5", ">= 5.2.0 && < 12" ], "v8/tools/splaytree": [ ">= 4.4.0 && < 5", ">= 5.2.0 && < 12" ], v8: v8, vm: vm, wasi: wasi, worker_threads: worker_threads, zlib: zlib }; var core$2 = /*#__PURE__*/Object.freeze({ __proto__: null, assert: assert$1, async_hooks: async_hooks, buffer_ieee754: buffer_ieee754, buffer: buffer$2, child_process: child_process, cluster: cluster, console: console$1, constants: constants$1, crypto: crypto, _debug_agent: _debug_agent, _debugger: _debugger, dgram: dgram, diagnostics_channel: diagnostics_channel, dns: dns, domain: domain, events: events, freelist: freelist, fs: fs$1, _http_agent: _http_agent, _http_client: _http_client, _http_common: _http_common, _http_incoming: _http_incoming, _http_outgoing: _http_outgoing, _http_server: _http_server, http: http, http2: http2, https: https, inspector: inspector, _linklist: _linklist, module: module, net: net, os: os$3, path: path$1, perf_hooks: perf_hooks, process: process$1, punycode: punycode, querystring: querystring, readline: readline, repl: repl, smalloc: smalloc, _stream_duplex: _stream_duplex, _stream_transform: _stream_transform, _stream_wrap: _stream_wrap, _stream_passthrough: _stream_passthrough, _stream_readable: _stream_readable, _stream_writable: _stream_writable, stream: stream, string_decoder: string_decoder, sys: sys, timers: timers, _tls_common: _tls_common, _tls_legacy: _tls_legacy, _tls_wrap: _tls_wrap, tls: tls, trace_events: trace_events, tty: tty$3, url: url$2, util: util$6, v8: v8, vm: vm, wasi: wasi, worker_threads: worker_threads, zlib: zlib, 'default': core$1 }); var data = getCjsExportFromNamespace(core$2); function specifierIncluded(current, specifier) { var nodeParts = current.split('.'); var parts = specifier.split(' '); var op = parts.length > 1 ? parts[0] : '='; var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.'); for (var i = 0; i < 3; ++i) { var cur = parseInt(nodeParts[i] || 0, 10); var ver = parseInt(versionParts[i] || 0, 10); if (cur === ver) { continue; // eslint-disable-line no-restricted-syntax, no-continue } if (op === '<') { return cur < ver; } if (op === '>=') { return cur >= ver; } return false; } return op === '>='; } function matchesRange(current, range) { var specifiers = range.split(/ ?&& ?/); if (specifiers.length === 0) { return false; } for (var i = 0; i < specifiers.length; ++i) { if (!specifierIncluded(current, specifiers[i])) { return false; } } return true; } function versionIncluded(nodeVersion, specifierValue) { if (typeof specifierValue === 'boolean') { return specifierValue; } var current = typeof nodeVersion === 'undefined' ? process.versions && process.versions.node && process.versions.node : nodeVersion; if (typeof current !== 'string') { throw new TypeError(typeof nodeVersion === 'undefined' ? 'Unable to determine current node version' : 'If provided, a valid node version is required'); } if (specifierValue && typeof specifierValue === 'object') { for (var i = 0; i < specifierValue.length; ++i) { if (matchesRange(current, specifierValue[i])) { return true; } } return false; } return matchesRange(current, specifierValue); } var isCoreModule = function isCore(x, nodeVersion) { return src$1(data, x) && versionIncluded(nodeVersion, data[x]); }; var realpathFS = require$$0$1.realpath && typeof require$$0$1.realpath.native === 'function' ? require$$0$1.realpath.native : require$$0$1.realpath; var defaultIsFile = function isFile(file, cb) { require$$0$1.stat(file, function (err, stat) { if (!err) { return cb(null, stat.isFile() || stat.isFIFO()); } if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); return cb(err); }); }; var defaultIsDir = function isDirectory(dir, cb) { require$$0$1.stat(dir, function (err, stat) { if (!err) { return cb(null, stat.isDirectory()); } if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); return cb(err); }); }; var defaultRealpath = function realpath(x, cb) { realpathFS(x, function (realpathErr, realPath) { if (realpathErr && realpathErr.code !== 'ENOENT') cb(realpathErr); else cb(null, realpathErr ? x : realPath); }); }; var maybeRealpath = function maybeRealpath(realpath, x, opts, cb) { if (opts && opts.preserveSymlinks === false) { realpath(x, cb); } else { cb(null, x); } }; var getPackageCandidates = function getPackageCandidates(x, start, opts) { var dirs = nodeModulesPaths(start, opts, x); for (var i = 0; i < dirs.length; i++) { dirs[i] = require$$1.join(dirs[i], x); } return dirs; }; var async$1 = function resolve(x, options, callback) { var cb = callback; var opts = options; if (typeof options === 'function') { cb = opts; opts = {}; } if (typeof x !== 'string') { var err = new TypeError('Path must be a string.'); return nextTick(function () { cb(err); }); } opts = normalizeOptions(x, opts); var isFile = opts.isFile || defaultIsFile; var isDirectory = opts.isDirectory || defaultIsDir; var readFile = opts.readFile || require$$0$1.readFile; var realpath = opts.realpath || defaultRealpath; var packageIterator = opts.packageIterator; var extensions = opts.extensions || ['.js']; var includeCoreModules = opts.includeCoreModules !== false; var basedir = opts.basedir || require$$1.dirname(caller()); var parent = opts.filename || basedir; opts.paths = opts.paths || []; // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory var absoluteStart = require$$1.resolve(basedir); maybeRealpath( realpath, absoluteStart, opts, function (err, realStart) { if (err) cb(err); else init(realStart); } ); var res; function init(basedir) { if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) { res = require$$1.resolve(basedir, x); if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/'; if ((/\/$/).test(x) && res === basedir) { loadAsDirectory(res, opts.package, onfile); } else loadAsFile(res, opts.package, onfile); } else if (includeCoreModules && isCoreModule(x)) { return cb(null, x); } else loadNodeModules(x, basedir, function (err, n, pkg) { if (err) cb(err); else if (n) { return maybeRealpath(realpath, n, opts, function (err, realN) { if (err) { cb(err); } else { cb(null, realN, pkg); } }); } else { var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'"); moduleError.code = 'MODULE_NOT_FOUND'; cb(moduleError); } }); } function onfile(err, m, pkg) { if (err) cb(err); else if (m) cb(null, m, pkg); else loadAsDirectory(res, function (err, d, pkg) { if (err) cb(err); else if (d) { maybeRealpath(realpath, d, opts, function (err, realD) { if (err) { cb(err); } else { cb(null, realD, pkg); } }); } else { var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'"); moduleError.code = 'MODULE_NOT_FOUND'; cb(moduleError); } }); } function loadAsFile(x, thePackage, callback) { var loadAsFilePackage = thePackage; var cb = callback; if (typeof loadAsFilePackage === 'function') { cb = loadAsFilePackage; loadAsFilePackage = undefined; } var exts = [''].concat(extensions); load(exts, x, loadAsFilePackage); function load(exts, x, loadPackage) { if (exts.length === 0) return cb(null, undefined, loadPackage); var file = x + exts[0]; var pkg = loadPackage; if (pkg) onpkg(null, pkg); else loadpkg(require$$1.dirname(file), onpkg); function onpkg(err, pkg_, dir) { pkg = pkg_; if (err) return cb(err); if (dir && pkg && opts.pathFilter) { var rfile = require$$1.relative(dir, file); var rel = rfile.slice(0, rfile.length - exts[0].length); var r = opts.pathFilter(pkg, x, rel); if (r) return load( [''].concat(extensions.slice()), require$$1.resolve(dir, r), pkg ); } isFile(file, onex); } function onex(err, ex) { if (err) return cb(err); if (ex) return cb(null, file, pkg); load(exts.slice(1), x, pkg); } } } function loadpkg(dir, cb) { if (dir === '' || dir === '/') return cb(null); if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) { return cb(null); } if ((/[/\\]node_modules[/\\]*$/).test(dir)) return cb(null); maybeRealpath(realpath, dir, opts, function (unwrapErr, pkgdir) { if (unwrapErr) return loadpkg(require$$1.dirname(dir), cb); var pkgfile = require$$1.join(pkgdir, 'package.json'); isFile(pkgfile, function (err, ex) { // on err, ex is false if (!ex) return loadpkg(require$$1.dirname(dir), cb); readFile(pkgfile, function (err, body) { if (err) cb(err); try { var pkg = JSON.parse(body); } catch (jsonErr) {} if (pkg && opts.packageFilter) { pkg = opts.packageFilter(pkg, pkgfile); } cb(null, pkg, dir); }); }); }); } function loadAsDirectory(x, loadAsDirectoryPackage, callback) { var cb = callback; var fpkg = loadAsDirectoryPackage; if (typeof fpkg === 'function') { cb = fpkg; fpkg = opts.package; } maybeRealpath(realpath, x, opts, function (unwrapErr, pkgdir) { if (unwrapErr) return cb(unwrapErr); var pkgfile = require$$1.join(pkgdir, 'package.json'); isFile(pkgfile, function (err, ex) { if (err) return cb(err); if (!ex) return loadAsFile(require$$1.join(x, 'index'), fpkg, cb); readFile(pkgfile, function (err, body) { if (err) return cb(err); try { var pkg = JSON.parse(body); } catch (jsonErr) {} if (pkg && opts.packageFilter) { pkg = opts.packageFilter(pkg, pkgfile); } if (pkg && pkg.main) { if (typeof pkg.main !== 'string') { var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string'); mainError.code = 'INVALID_PACKAGE_MAIN'; return cb(mainError); } if (pkg.main === '.' || pkg.main === './') { pkg.main = 'index'; } loadAsFile(require$$1.resolve(x, pkg.main), pkg, function (err, m, pkg) { if (err) return cb(err); if (m) return cb(null, m, pkg); if (!pkg) return loadAsFile(require$$1.join(x, 'index'), pkg, cb); var dir = require$$1.resolve(x, pkg.main); loadAsDirectory(dir, pkg, function (err, n, pkg) { if (err) return cb(err); if (n) return cb(null, n, pkg); loadAsFile(require$$1.join(x, 'index'), pkg, cb); }); }); return; } loadAsFile(require$$1.join(x, '/index'), pkg, cb); }); }); }); } function processDirs(cb, dirs) { if (dirs.length === 0) return cb(null, undefined); var dir = dirs[0]; isDirectory(require$$1.dirname(dir), isdir); function isdir(err, isdir) { if (err) return cb(err); if (!isdir) return processDirs(cb, dirs.slice(1)); loadAsFile(dir, opts.package, onfile); } function onfile(err, m, pkg) { if (err) return cb(err); if (m) return cb(null, m, pkg); loadAsDirectory(dir, opts.package, ondir); } function ondir(err, n, pkg) { if (err) return cb(err); if (n) return cb(null, n, pkg); processDirs(cb, dirs.slice(1)); } } function loadNodeModules(x, start, cb) { var thunk = function () { return getPackageCandidates(x, start, opts); }; processDirs( cb, packageIterator ? packageIterator(x, start, thunk, opts) : thunk() ); } }; var assert$2 = true; var async_hooks$1 = ">= 8"; var buffer_ieee754$1 = "< 0.9.7"; var buffer$3 = true; var child_process$1 = true; var cluster$1 = true; var console$2 = true; var constants$2 = true; var crypto$1 = true; var _debug_agent$1 = ">= 1 && < 8"; var _debugger$1 = "< 8"; var dgram$1 = true; var diagnostics_channel$1 = ">= 15.1"; var dns$1 = true; var domain$1 = ">= 0.7.12"; var events$1 = true; var freelist$1 = "< 6"; var fs$2 = true; var _http_agent$1 = ">= 0.11.1"; var _http_client$1 = ">= 0.11.1"; var _http_common$1 = ">= 0.11.1"; var _http_incoming$1 = ">= 0.11.1"; var _http_outgoing$1 = ">= 0.11.1"; var _http_server$1 = ">= 0.11.1"; var http$1 = true; var http2$1 = ">= 8.8"; var https$1 = true; var inspector$1 = ">= 8.0.0"; var _linklist$1 = "< 8"; var module$1 = true; var net$1 = true; var os$4 = true; var path$2 = true; var perf_hooks$1 = ">= 8.5"; var process$2 = ">= 1"; var punycode$1 = true; var querystring$1 = true; var readline$1 = true; var repl$1 = true; var smalloc$1 = ">= 0.11.5 && < 3"; var _stream_duplex$1 = ">= 0.9.4"; var _stream_transform$1 = ">= 0.9.4"; var _stream_wrap$1 = ">= 1.4.1"; var _stream_passthrough$1 = ">= 0.9.4"; var _stream_readable$1 = ">= 0.9.4"; var _stream_writable$1 = ">= 0.9.4"; var stream$1 = true; var string_decoder$1 = true; var sys$1 = [ ">= 0.6 && < 0.7", ">= 0.8" ]; var timers$1 = true; var _tls_common$1 = ">= 0.11.13"; var _tls_legacy$1 = ">= 0.11.3 && < 10"; var _tls_wrap$1 = ">= 0.11.3"; var tls$1 = true; var trace_events$1 = ">= 10"; var tty$4 = true; var url$3 = true; var util$7 = true; var v8$1 = ">= 1"; var vm$1 = true; var wasi$1 = ">= 13.4 && < 13.5"; var worker_threads$1 = ">= 11.7"; var zlib$1 = true; var core$3 = { assert: assert$2, "assert/strict": ">= 15", async_hooks: async_hooks$1, buffer_ieee754: buffer_ieee754$1, buffer: buffer$3, child_process: child_process$1, cluster: cluster$1, console: console$2, constants: constants$2, crypto: crypto$1, _debug_agent: _debug_agent$1, _debugger: _debugger$1, dgram: dgram$1, diagnostics_channel: diagnostics_channel$1, dns: dns$1, "dns/promises": ">= 15", domain: domain$1, events: events$1, freelist: freelist$1, fs: fs$2, "fs/promises": [ ">= 10 && < 10.1", ">= 14" ], _http_agent: _http_agent$1, _http_client: _http_client$1, _http_common: _http_common$1, _http_incoming: _http_incoming$1, _http_outgoing: _http_outgoing$1, _http_server: _http_server$1, http: http$1, http2: http2$1, https: https$1, inspector: inspector$1, _linklist: _linklist$1, module: module$1, net: net$1, "node-inspect/lib/_inspect": ">= 7.6.0 && < 12", "node-inspect/lib/internal/inspect_client": ">= 7.6.0 && < 12", "node-inspect/lib/internal/inspect_repl": ">= 7.6.0 && < 12", os: os$4, path: path$2, perf_hooks: perf_hooks$1, process: process$2, punycode: punycode$1, querystring: querystring$1, readline: readline$1, repl: repl$1, smalloc: smalloc$1, _stream_duplex: _stream_duplex$1, _stream_transform: _stream_transform$1, _stream_wrap: _stream_wrap$1, _stream_passthrough: _stream_passthrough$1, _stream_readable: _stream_readable$1, _stream_writable: _stream_writable$1, stream: stream$1, "stream/promises": ">= 15", string_decoder: string_decoder$1, sys: sys$1, timers: timers$1, "timers/promises": ">= 15", _tls_common: _tls_common$1, _tls_legacy: _tls_legacy$1, _tls_wrap: _tls_wrap$1, tls: tls$1, trace_events: trace_events$1, tty: tty$4, url: url$3, util: util$7, "v8/tools/arguments": ">= 10 && < 12", "v8/tools/codemap": [ ">= 4.4.0 && < 5", ">= 5.2.0 && < 12" ], "v8/tools/consarray": [ ">= 4.4.0 && < 5", ">= 5.2.0 && < 12" ], "v8/tools/csvparser": [ ">= 4.4.0 && < 5", ">= 5.2.0 && < 12" ], "v8/tools/logreader": [ ">= 4.4.0 && < 5", ">= 5.2.0 && < 12" ], "v8/tools/profile_view": [ ">= 4.4.0 && < 5", ">= 5.2.0 && < 12" ], "v8/tools/splaytree": [ ">= 4.4.0 && < 5", ">= 5.2.0 && < 12" ], v8: v8$1, vm: vm$1, wasi: wasi$1, worker_threads: worker_threads$1, zlib: zlib$1 }; var core$4 = /*#__PURE__*/Object.freeze({ __proto__: null, assert: assert$2, async_hooks: async_hooks$1, buffer_ieee754: buffer_ieee754$1, buffer: buffer$3, child_process: child_process$1, cluster: cluster$1, console: console$2, constants: constants$2, crypto: crypto$1, _debug_agent: _debug_agent$1, _debugger: _debugger$1, dgram: dgram$1, diagnostics_channel: diagnostics_channel$1, dns: dns$1, domain: domain$1, events: events$1, freelist: freelist$1, fs: fs$2, _http_agent: _http_agent$1, _http_client: _http_client$1, _http_common: _http_common$1, _http_incoming: _http_incoming$1, _http_outgoing: _http_outgoing$1, _http_server: _http_server$1, http: http$1, http2: http2$1, https: https$1, inspector: inspector$1, _linklist: _linklist$1, module: module$1, net: net$1, os: os$4, path: path$2, perf_hooks: perf_hooks$1, process: process$2, punycode: punycode$1, querystring: querystring$1, readline: readline$1, repl: repl$1, smalloc: smalloc$1, _stream_duplex: _stream_duplex$1, _stream_transform: _stream_transform$1, _stream_wrap: _stream_wrap$1, _stream_passthrough: _stream_passthrough$1, _stream_readable: _stream_readable$1, _stream_writable: _stream_writable$1, stream: stream$1, string_decoder: string_decoder$1, sys: sys$1, timers: timers$1, _tls_common: _tls_common$1, _tls_legacy: _tls_legacy$1, _tls_wrap: _tls_wrap$1, tls: tls$1, trace_events: trace_events$1, tty: tty$4, url: url$3, util: util$7, v8: v8$1, vm: vm$1, wasi: wasi$1, worker_threads: worker_threads$1, zlib: zlib$1, 'default': core$3 }); var data$1 = getCjsExportFromNamespace(core$4); var current = (process.versions && process.versions.node && process.versions.node.split('.')) || []; function specifierIncluded$1(specifier) { var parts = specifier.split(' '); var op = parts.length > 1 ? parts[0] : '='; var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.'); for (var i = 0; i < 3; ++i) { var cur = parseInt(current[i] || 0, 10); var ver = parseInt(versionParts[i] || 0, 10); if (cur === ver) { continue; // eslint-disable-line no-restricted-syntax, no-continue } if (op === '<') { return cur < ver; } else if (op === '>=') { return cur >= ver; } else { return false; } } return op === '>='; } function matchesRange$1(range) { var specifiers = range.split(/ ?&& ?/); if (specifiers.length === 0) { return false; } for (var i = 0; i < specifiers.length; ++i) { if (!specifierIncluded$1(specifiers[i])) { return false; } } return true; } function versionIncluded$1(specifierValue) { if (typeof specifierValue === 'boolean') { return specifierValue; } if (specifierValue && typeof specifierValue === 'object') { for (var i = 0; i < specifierValue.length; ++i) { if (matchesRange$1(specifierValue[i])) { return true; } } return false; } return matchesRange$1(specifierValue); } var core$5 = {}; for (var mod in data$1) { // eslint-disable-line no-restricted-syntax if (Object.prototype.hasOwnProperty.call(data$1, mod)) { core$5[mod] = versionIncluded$1(data$1[mod]); } } var core_1$1 = core$5; var isCore = function isCore(x) { return isCoreModule(x); }; var realpathFS$1 = require$$0$1.realpathSync && typeof require$$0$1.realpathSync.native === 'function' ? require$$0$1.realpathSync.native : require$$0$1.realpathSync; var defaultIsFile$1 = function isFile(file) { try { var stat = require$$0$1.statSync(file); } catch (e) { if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; throw e; } return stat.isFile() || stat.isFIFO(); }; var defaultIsDir$1 = function isDirectory(dir) { try { var stat = require$$0$1.statSync(dir); } catch (e) { if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; throw e; } return stat.isDirectory(); }; var defaultRealpathSync = function realpathSync(x) { try { return realpathFS$1(x); } catch (realpathErr) { if (realpathErr.code !== 'ENOENT') { throw realpathErr; } } return x; }; var maybeRealpathSync = function maybeRealpathSync(realpathSync, x, opts) { if (opts && opts.preserveSymlinks === false) { return realpathSync(x); } return x; }; var getPackageCandidates$1 = function getPackageCandidates(x, start, opts) { var dirs = nodeModulesPaths(start, opts, x); for (var i = 0; i < dirs.length; i++) { dirs[i] = require$$1.join(dirs[i], x); } return dirs; }; var sync = function resolveSync(x, options) { if (typeof x !== 'string') { throw new TypeError('Path must be a string.'); } var opts = normalizeOptions(x, options); var isFile = opts.isFile || defaultIsFile$1; var readFileSync = opts.readFileSync || require$$0$1.readFileSync; var isDirectory = opts.isDirectory || defaultIsDir$1; var realpathSync = opts.realpathSync || defaultRealpathSync; var packageIterator = opts.packageIterator; var extensions = opts.extensions || ['.js']; var includeCoreModules = opts.includeCoreModules !== false; var basedir = opts.basedir || require$$1.dirname(caller()); var parent = opts.filename || basedir; opts.paths = opts.paths || []; // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory var absoluteStart = maybeRealpathSync(realpathSync, require$$1.resolve(basedir), opts); if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) { var res = require$$1.resolve(absoluteStart, x); if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/'; var m = loadAsFileSync(res) || loadAsDirectorySync(res); if (m) return maybeRealpathSync(realpathSync, m, opts); } else if (includeCoreModules && isCoreModule(x)) { return x; } else { var n = loadNodeModulesSync(x, absoluteStart); if (n) return maybeRealpathSync(realpathSync, n, opts); } var err = new Error("Cannot find module '" + x + "' from '" + parent + "'"); err.code = 'MODULE_NOT_FOUND'; throw err; function loadAsFileSync(x) { var pkg = loadpkg(require$$1.dirname(x)); if (pkg && pkg.dir && pkg.pkg && opts.pathFilter) { var rfile = require$$1.relative(pkg.dir, x); var r = opts.pathFilter(pkg.pkg, x, rfile); if (r) { x = require$$1.resolve(pkg.dir, r); // eslint-disable-line no-param-reassign } } if (isFile(x)) { return x; } for (var i = 0; i < extensions.length; i++) { var file = x + extensions[i]; if (isFile(file)) { return file; } } } function loadpkg(dir) { if (dir === '' || dir === '/') return; if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) { return; } if ((/[/\\]node_modules[/\\]*$/).test(dir)) return; var pkgfile = require$$1.join(maybeRealpathSync(realpathSync, dir, opts), 'package.json'); if (!isFile(pkgfile)) { return loadpkg(require$$1.dirname(dir)); } var body = readFileSync(pkgfile); try { var pkg = JSON.parse(body); } catch (jsonErr) {} if (pkg && opts.packageFilter) { // v2 will pass pkgfile pkg = opts.packageFilter(pkg, /*pkgfile,*/ dir); // eslint-disable-line spaced-comment } return { pkg: pkg, dir: dir }; } function loadAsDirectorySync(x) { var pkgfile = require$$1.join(maybeRealpathSync(realpathSync, x, opts), '/package.json'); if (isFile(pkgfile)) { try { var body = readFileSync(pkgfile, 'UTF8'); var pkg = JSON.parse(body); } catch (e) {} if (pkg && opts.packageFilter) { // v2 will pass pkgfile pkg = opts.packageFilter(pkg, /*pkgfile,*/ x); // eslint-disable-line spaced-comment } if (pkg && pkg.main) { if (typeof pkg.main !== 'string') { var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string'); mainError.code = 'INVALID_PACKAGE_MAIN'; throw mainError; } if (pkg.main === '.' || pkg.main === './') { pkg.main = 'index'; } try { var m = loadAsFileSync(require$$1.resolve(x, pkg.main)); if (m) return m; var n = loadAsDirectorySync(require$$1.resolve(x, pkg.main)); if (n) return n; } catch (e) {} } } return loadAsFileSync(require$$1.join(x, '/index')); } function loadNodeModulesSync(x, start) { var thunk = function () { return getPackageCandidates$1(x, start, opts); }; var dirs = packageIterator ? packageIterator(x, start, thunk, opts) : thunk(); for (var i = 0; i < dirs.length; i++) { var dir = dirs[i]; if (isDirectory(require$$1.dirname(dir))) { var m = loadAsFileSync(dir); if (m) return m; var n = loadAsDirectorySync(dir); if (n) return n; } } } }; async$1.core = core_1$1; async$1.isCore = isCore; async$1.sync = sync; var resolve$1 = async$1; var resolve$2 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; function _resolve() { const data = _interopRequireDefault(resolve$1); _resolve = function () { return data; }; return data; } function _gensync() { const data = _interopRequireDefault(gensync); _gensync = function () { return data; }; return data; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _default = (0, _gensync().default)({ sync: _resolve().default.sync, errback: _resolve().default }); exports.default = _default; }); unwrapExports(resolve$2); var require$$2 = getCjsExportFromNamespace(dist); var configuration = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.findConfigUpwards = findConfigUpwards; exports.findRelativeConfig = findRelativeConfig; exports.findRootConfig = findRootConfig; exports.loadConfig = loadConfig; exports.resolveShowConfigPath = resolveShowConfigPath; exports.ROOT_CONFIG_FILENAMES = void 0; function _debug() { const data = _interopRequireDefault(src); _debug = function () { return data; }; return data; } function _path() { const data = _interopRequireDefault(require$$1); _path = function () { return data; }; return data; } function _json() { const data = _interopRequireDefault(require$$2); _json = function () { return data; }; return data; } function _gensync() { const data = _interopRequireDefault(gensync); _gensync = function () { return data; }; return data; } var _configApi = _interopRequireDefault(configApi); var _moduleTypes = _interopRequireDefault(moduleTypes); var _patternToRegex = _interopRequireDefault(patternToRegex); var fs$1 = _interopRequireWildcard(fs); var _resolve = _interopRequireDefault(resolve$2); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug().default)("babel:config:loading:files:configuration"); const ROOT_CONFIG_FILENAMES = ["babel.config.js", "babel.config.cjs", "babel.config.mjs", "babel.config.json"]; exports.ROOT_CONFIG_FILENAMES = ROOT_CONFIG_FILENAMES; const RELATIVE_CONFIG_FILENAMES = [".babelrc", ".babelrc.js", ".babelrc.cjs", ".babelrc.mjs", ".babelrc.json"]; const BABELIGNORE_FILENAME = ".babelignore"; function* findConfigUpwards(rootDir) { let dirname = rootDir; while (true) { for (const filename of ROOT_CONFIG_FILENAMES) { if (yield* fs$1.exists(_path().default.join(dirname, filename))) { return dirname; } } const nextDir = _path().default.dirname(dirname); if (dirname === nextDir) break; dirname = nextDir; } return null; } function* findRelativeConfig(packageData, envName, caller) { let config = null; let ignore = null; const dirname = _path().default.dirname(packageData.filepath); for (const loc of packageData.directories) { if (!config) { var _packageData$pkg; config = yield* loadOneConfig(RELATIVE_CONFIG_FILENAMES, loc, envName, caller, ((_packageData$pkg = packageData.pkg) == null ? void 0 : _packageData$pkg.dirname) === loc ? packageToBabelConfig(packageData.pkg) : null); } if (!ignore) { const ignoreLoc = _path().default.join(loc, BABELIGNORE_FILENAME); ignore = yield* readIgnoreConfig(ignoreLoc); if (ignore) { debug("Found ignore %o from %o.", ignore.filepath, dirname); } } } return { config, ignore }; } function findRootConfig(dirname, envName, caller) { return loadOneConfig(ROOT_CONFIG_FILENAMES, dirname, envName, caller); } function* loadOneConfig(names, dirname, envName, caller, previousConfig = null) { const configs = yield* _gensync().default.all(names.map(filename => readConfig(_path().default.join(dirname, filename), envName, caller))); const config = configs.reduce((previousConfig, config) => { if (config && previousConfig) { throw new Error(`Multiple configuration files found. Please remove one:\n` + ` - ${_path().default.basename(previousConfig.filepath)}\n` + ` - ${config.filepath}\n` + `from ${dirname}`); } return config || previousConfig; }, previousConfig); if (config) { debug("Found configuration %o from %o.", config.filepath, dirname); } return config; } function* loadConfig(name, dirname, envName, caller) { const filepath = yield* (0, _resolve.default)(name, { basedir: dirname }); const conf = yield* readConfig(filepath, envName, caller); if (!conf) { throw new Error(`Config file ${filepath} contains no configuration data`); } debug("Loaded config %o from %o.", name, dirname); return conf; } function readConfig(filepath, envName, caller) { const ext = _path().default.extname(filepath); return ext === ".js" || ext === ".cjs" || ext === ".mjs" ? readConfigJS(filepath, { envName, caller }) : readConfigJSON5(filepath); } const LOADING_CONFIGS = new Set(); const readConfigJS = (0, caching.makeStrongCache)(function* readConfigJS(filepath, cache) { if (!fs$1.exists.sync(filepath)) { cache.forever(); return null; } if (LOADING_CONFIGS.has(filepath)) { cache.never(); debug("Auto-ignoring usage of config %o.", filepath); return { filepath, dirname: _path().default.dirname(filepath), options: {} }; } let options; try { LOADING_CONFIGS.add(filepath); options = yield* (0, _moduleTypes.default)(filepath, "You appear to be using a native ECMAScript module configuration " + "file, which is only supported when running Babel asynchronously."); } catch (err) { err.message = `${filepath}: Error while loading config - ${err.message}`; throw err; } finally { LOADING_CONFIGS.delete(filepath); } let assertCache = false; if (typeof options === "function") { yield* []; options = options((0, _configApi.default)(cache)); assertCache = true; } if (!options || typeof options !== "object" || Array.isArray(options)) { throw new Error(`${filepath}: Configuration should be an exported JavaScript object.`); } if (typeof options.then === "function") { throw new Error(`You appear to be using an async configuration, ` + `which your current version of Babel does not support. ` + `We may add support for this in the future, ` + `but if you're on the most recent version of @babel/core and still ` + `seeing this error, then you'll need to synchronously return your config.`); } if (assertCache && !cache.configured()) throwConfigError(); return { filepath, dirname: _path().default.dirname(filepath), options }; }); const packageToBabelConfig = (0, caching.makeWeakCacheSync)(file => { const babel = file.options["babel"]; if (typeof babel === "undefined") return null; if (typeof babel !== "object" || Array.isArray(babel) || babel === null) { throw new Error(`${file.filepath}: .babel property must be an object`); } return { filepath: file.filepath, dirname: file.dirname, options: babel }; }); const readConfigJSON5 = (0, utils$1.makeStaticFileCache)((filepath, content) => { let options; try { options = _json().default.parse(content); } catch (err) { err.message = `${filepath}: Error while parsing config - ${err.message}`; throw err; } if (!options) throw new Error(`${filepath}: No config detected`); if (typeof options !== "object") { throw new Error(`${filepath}: Config returned typeof ${typeof options}`); } if (Array.isArray(options)) { throw new Error(`${filepath}: Expected config object but found array`); } return { filepath, dirname: _path().default.dirname(filepath), options }; }); const readIgnoreConfig = (0, utils$1.makeStaticFileCache)((filepath, content) => { const ignoreDir = _path().default.dirname(filepath); const ignorePatterns = content.split("\n").map(line => line.replace(/#(.*?)$/, "").trim()).filter(line => !!line); for (const pattern of ignorePatterns) { if (pattern[0] === "!") { throw new Error(`Negation of file paths is not supported.`); } } return { filepath, dirname: _path().default.dirname(filepath), ignore: ignorePatterns.map(pattern => (0, _patternToRegex.default)(pattern, ignoreDir)) }; }); function* resolveShowConfigPath(dirname) { const targetPath = process.env.BABEL_SHOW_CONFIG_FOR; if (targetPath != null) { const absolutePath = _path().default.resolve(dirname, targetPath); const stats = yield* fs$1.stat(absolutePath); if (!stats.isFile()) { throw new Error(`${absolutePath}: BABEL_SHOW_CONFIG_FOR must refer to a regular file, directories are not supported.`); } return absolutePath; } return null; } function throwConfigError() { throw new Error(`\ Caching was left unconfigured. Babel's plugins, presets, and .babelrc.js files can be configured for various types of caching, using the first param of their handler functions: module.exports = function(api) { // The API exposes the following: // Cache the returned value forever and don't call this function again. api.cache(true); // Don't cache at all. Not recommended because it will be very slow. api.cache(false); // Cached based on the value of some function. If this function returns a value different from // a previously-encountered value, the plugins will re-evaluate. var env = api.cache(() => process.env.NODE_ENV); // If testing for a specific env, we recommend specifics to avoid instantiating a plugin for // any possible NODE_ENV value that might come up during plugin execution. var isProd = api.cache(() => process.env.NODE_ENV === "production"); // .cache(fn) will perform a linear search though instances to find the matching plugin based // based on previous instantiated plugins. If you want to recreate the plugin and discard the // previous instance whenever something changes, you may use: var isProd = api.cache.invalidate(() => process.env.NODE_ENV === "production"); // Note, we also expose the following more-verbose versions of the above examples: api.cache.forever(); // api.cache(true) api.cache.never(); // api.cache(false) api.cache.using(fn); // api.cache(fn) // Return the value that will be cached. return { }; };`); } }); unwrapExports(configuration); var configuration_1 = configuration.findConfigUpwards; var configuration_2 = configuration.findRelativeConfig; var configuration_3 = configuration.findRootConfig; var configuration_4 = configuration.loadConfig; var configuration_5 = configuration.resolveShowConfigPath; var configuration_6 = configuration.ROOT_CONFIG_FILENAMES; var plugins = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.resolvePlugin = resolvePlugin; exports.resolvePreset = resolvePreset; exports.loadPlugin = loadPlugin; exports.loadPreset = loadPreset; function _debug() { const data = _interopRequireDefault(src); _debug = function () { return data; }; return data; } function _resolve() { const data = _interopRequireDefault(resolve$1); _resolve = function () { return data; }; return data; } function _path() { const data = _interopRequireDefault(require$$1); _path = function () { return data; }; return data; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug().default)("babel:config:loading:files:plugins"); const EXACT_RE = /^module:/; const BABEL_PLUGIN_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-plugin-)/; const BABEL_PRESET_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-preset-)/; const BABEL_PLUGIN_ORG_RE = /^(@babel\/)(?!plugin-|[^/]+\/)/; const BABEL_PRESET_ORG_RE = /^(@babel\/)(?!preset-|[^/]+\/)/; const OTHER_PLUGIN_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-plugin(?:-|\/|$)|[^/]+\/)/; const OTHER_PRESET_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-preset(?:-|\/|$)|[^/]+\/)/; const OTHER_ORG_DEFAULT_RE = /^(@(?!babel$)[^/]+)$/; function resolvePlugin(name, dirname) { return resolveStandardizedName("plugin", name, dirname); } function resolvePreset(name, dirname) { return resolveStandardizedName("preset", name, dirname); } function loadPlugin(name, dirname) { const filepath = resolvePlugin(name, dirname); if (!filepath) { throw new Error(`Plugin ${name} not found relative to ${dirname}`); } const value = requireModule("plugin", filepath); debug("Loaded plugin %o from %o.", name, dirname); return { filepath, value }; } function loadPreset(name, dirname) { const filepath = resolvePreset(name, dirname); if (!filepath) { throw new Error(`Preset ${name} not found relative to ${dirname}`); } const value = requireModule("preset", filepath); debug("Loaded preset %o from %o.", name, dirname); return { filepath, value }; } function standardizeName(type, name) { if (_path().default.isAbsolute(name)) return name; const isPreset = type === "preset"; return name.replace(isPreset ? BABEL_PRESET_PREFIX_RE : BABEL_PLUGIN_PREFIX_RE, `babel-${type}-`).replace(isPreset ? BABEL_PRESET_ORG_RE : BABEL_PLUGIN_ORG_RE, `$1${type}-`).replace(isPreset ? OTHER_PRESET_ORG_RE : OTHER_PLUGIN_ORG_RE, `$1babel-${type}-`).replace(OTHER_ORG_DEFAULT_RE, `$1/babel-${type}`).replace(EXACT_RE, ""); } function resolveStandardizedName(type, name, dirname = process.cwd()) { const standardizedName = standardizeName(type, name); try { return _resolve().default.sync(standardizedName, { basedir: dirname }); } catch (e) { if (e.code !== "MODULE_NOT_FOUND") throw e; if (standardizedName !== name) { let resolvedOriginal = false; try { _resolve().default.sync(name, { basedir: dirname }); resolvedOriginal = true; } catch (_unused) {} if (resolvedOriginal) { e.message += `\n- If you want to resolve "${name}", use "module:${name}"`; } } let resolvedBabel = false; try { _resolve().default.sync(standardizeName(type, "@babel/" + name), { basedir: dirname }); resolvedBabel = true; } catch (_unused2) {} if (resolvedBabel) { e.message += `\n- Did you mean "@babel/${name}"?`; } let resolvedOppositeType = false; const oppositeType = type === "preset" ? "plugin" : "preset"; try { _resolve().default.sync(standardizeName(oppositeType, name), { basedir: dirname }); resolvedOppositeType = true; } catch (_unused3) {} if (resolvedOppositeType) { e.message += `\n- Did you accidentally pass a ${oppositeType} as a ${type}?`; } throw e; } } const LOADING_MODULES = new Set(); function requireModule(type, name) { if (LOADING_MODULES.has(name)) { throw new Error(`Reentrant ${type} detected trying to load "${name}". This module is not ignored ` + "and is trying to load itself while compiling itself, leading to a dependency cycle. " + 'We recommend adding it to your "ignore" list in your babelrc, or to a .babelignore.'); } try { LOADING_MODULES.add(name); return commonjsRequire(name); } finally { LOADING_MODULES.delete(name); } } }); unwrapExports(plugins); var plugins_1 = plugins.resolvePlugin; var plugins_2 = plugins.resolvePreset; var plugins_3 = plugins.loadPlugin; var plugins_4 = plugins.loadPreset; var files = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "findPackageData", { enumerable: true, get: function () { return _package.findPackageData; } }); Object.defineProperty(exports, "findConfigUpwards", { enumerable: true, get: function () { return configuration.findConfigUpwards; } }); Object.defineProperty(exports, "findRelativeConfig", { enumerable: true, get: function () { return configuration.findRelativeConfig; } }); Object.defineProperty(exports, "findRootConfig", { enumerable: true, get: function () { return configuration.findRootConfig; } }); Object.defineProperty(exports, "loadConfig", { enumerable: true, get: function () { return configuration.loadConfig; } }); Object.defineProperty(exports, "resolveShowConfigPath", { enumerable: true, get: function () { return configuration.resolveShowConfigPath; } }); Object.defineProperty(exports, "ROOT_CONFIG_FILENAMES", { enumerable: true, get: function () { return configuration.ROOT_CONFIG_FILENAMES; } }); Object.defineProperty(exports, "resolvePlugin", { enumerable: true, get: function () { return plugins.resolvePlugin; } }); Object.defineProperty(exports, "resolvePreset", { enumerable: true, get: function () { return plugins.resolvePreset; } }); Object.defineProperty(exports, "loadPlugin", { enumerable: true, get: function () { return plugins.loadPlugin; } }); Object.defineProperty(exports, "loadPreset", { enumerable: true, get: function () { return plugins.loadPreset; } }); }); unwrapExports(files); var _from = "@babel/core@^7.0.0"; var _id = "@babel/core@7.12.7"; var _inBundle = false; var _integrity = "sha512-tRKx9B53kJe8NCGGIxEQb2Bkr0riUIEuN7Sc1fxhs5H8lKlCWUvQCSNMVIB0Meva7hcbCRJ76de15KoLltdoqw=="; var _location = "/@babel/core"; var _phantomChildren = { }; var _requested = { type: "range", registry: true, raw: "@babel/core@^7.0.0", name: "@babel/core", escapedName: "@babel%2fcore", scope: "@babel", rawSpec: "^7.0.0", saveSpec: null, fetchSpec: "^7.0.0" }; var _requiredBy = [ "/" ]; var _resolved = "https://registry.npmjs.org/@babel/core/-/core-7.12.7.tgz"; var _shasum = "bf55363c08c8352a37691f7216ec30090bf7e3bf"; var _spec = "@babel/core@^7.0.0"; var _where = "/home/circleci/project"; var author = { name: "Sebastian McKenzie", email: "sebmck@gmail.com" }; var browser$4 = { "./lib/config/files/index.js": "./lib/config/files/index-browser.js", "./lib/transform-file.js": "./lib/transform-file-browser.js", "./src/config/files/index.js": "./src/config/files/index-browser.js", "./src/transform-file.js": "./src/transform-file-browser.js" }; var bugs = { url: "https://github.com/babel/babel/issues" }; var bundleDependencies = false; var dependencies = { "@babel/code-frame": "^7.10.4", "@babel/generator": "^7.12.5", "@babel/helper-module-transforms": "^7.12.1", "@babel/helpers": "^7.12.5", "@babel/parser": "^7.12.7", "@babel/template": "^7.12.7", "@babel/traverse": "^7.12.7", "@babel/types": "^7.12.7", "convert-source-map": "^1.7.0", debug: "^4.1.0", gensync: "^1.0.0-beta.1", json5: "^2.1.2", lodash: "^4.17.19", resolve: "^1.3.2", semver: "^5.4.1", "source-map": "^0.5.0" }; var deprecated = false; var description = "Babel compiler core."; var devDependencies = { "@babel/helper-transform-fixture-test-runner": "7.12.1" }; var engines = { node: ">=6.9.0" }; var funding = { type: "opencollective", url: "https://opencollective.com/babel" }; var homepage = "https://babeljs.io/"; var keywords = [ "6to5", "babel", "classes", "const", "es6", "harmony", "let", "modules", "transpile", "transpiler", "var", "babel-core", "compiler" ]; var license = "MIT"; var main = "lib/index.js"; var name = "@babel/core"; var publishConfig = { access: "public" }; var repository = { type: "git", url: "git+https://github.com/babel/babel.git", directory: "packages/babel-core" }; var version$1 = "7.12.7"; var _package$1 = { _from: _from, _id: _id, _inBundle: _inBundle, _integrity: _integrity, _location: _location, _phantomChildren: _phantomChildren, _requested: _requested, _requiredBy: _requiredBy, _resolved: _resolved, _shasum: _shasum, _spec: _spec, _where: _where, author: author, browser: browser$4, bugs: bugs, bundleDependencies: bundleDependencies, dependencies: dependencies, deprecated: deprecated, description: description, devDependencies: devDependencies, engines: engines, funding: funding, homepage: homepage, keywords: keywords, license: license, main: main, name: name, publishConfig: publishConfig, repository: repository, version: version$1 }; var _package$2 = /*#__PURE__*/Object.freeze({ __proto__: null, _from: _from, _id: _id, _inBundle: _inBundle, _integrity: _integrity, _location: _location, _phantomChildren: _phantomChildren, _requested: _requested, _requiredBy: _requiredBy, _resolved: _resolved, _shasum: _shasum, _spec: _spec, _where: _where, author: author, browser: browser$4, bugs: bugs, bundleDependencies: bundleDependencies, dependencies: dependencies, deprecated: deprecated, description: description, devDependencies: devDependencies, engines: engines, funding: funding, homepage: homepage, keywords: keywords, license: license, main: main, name: name, publishConfig: publishConfig, repository: repository, version: version$1, 'default': _package$1 }); var environment = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.getEnv = getEnv; function getEnv(defaultValue = "development") { return process.env.BABEL_ENV || process.env.NODE_ENV || defaultValue; } }); unwrapExports(environment); var environment_1 = environment.getEnv; var configDescriptors = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.createCachedDescriptors = createCachedDescriptors; exports.createUncachedDescriptors = createUncachedDescriptors; exports.createDescriptor = createDescriptor; 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.makeWeakCacheSync)((items, cache) => { const dirname = cache.using(dir => dir); return (0, caching.makeStrongCacheSync)(alias => (0, caching.makeStrongCacheSync)(passPerPreset => createPresetDescriptors(items, dirname, alias, passPerPreset).map(desc => loadCachedDescriptor(PRESET_DESCRIPTOR_CACHE, desc)))); }); const PLUGIN_DESCRIPTOR_CACHE = new WeakMap(); const createCachedPluginDescriptors = (0, caching.makeWeakCacheSync)((items, cache) => { const dirname = cache.using(dir => dir); return (0, caching.makeStrongCacheSync)(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)) { const conflicts = items.filter(i => i.value === item.value); 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'],`, ` ]`, ``, `Duplicates detected are:`, `${JSON.stringify(conflicts, null, 2)}`].join("\n")); } nameMap.add(item.name); } } }); unwrapExports(configDescriptors); var configDescriptors_1 = configDescriptors.createCachedDescriptors; var configDescriptors_2 = configDescriptors.createUncachedDescriptors; var configDescriptors_3 = configDescriptors.createDescriptor; var item = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.createItemFromDescriptor = createItemFromDescriptor; exports.createConfigItem = createConfigItem; exports.getItemDescriptor = getItemDescriptor; function _path() { const data = _interopRequireDefault(require$$1); _path = function () { return data; }; return data; } 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 == null ? void 0 : item[CONFIG_ITEM_BRAND]) { return item._descriptor; } return undefined; } const CONFIG_ITEM_BRAND = Symbol.for("@babel/core@7 - ConfigItem"); class ConfigItem { constructor(descriptor) { this._descriptor = void 0; this[CONFIG_ITEM_BRAND] = true; this.value = void 0; this.options = void 0; this.dirname = void 0; this.name = void 0; this.file = void 0; this._descriptor = descriptor; Object.defineProperty(this, "_descriptor", { enumerable: false }); Object.defineProperty(this, CONFIG_ITEM_BRAND, { 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); }); unwrapExports(item); var item_1 = item.createItemFromDescriptor; var item_2 = item.createConfigItem; var item_3 = item.getItemDescriptor; var plugin = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; class Plugin { constructor(plugin, options, key) { this.key = void 0; this.manipulateOptions = void 0; this.post = void 0; this.pre = void 0; this.visitor = void 0; this.parserOverride = void 0; this.generatorOverride = void 0; this.options = void 0; 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; }); unwrapExports(plugin); var removed = createCommonjsModule(function (module, exports) { 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; }); unwrapExports(removed); var optionAssertions = createCommonjsModule(function (module, exports) { 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/Function/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; } }); unwrapExports(optionAssertions); var optionAssertions_1 = optionAssertions.msg; var optionAssertions_2 = optionAssertions.access; var optionAssertions_3 = optionAssertions.assertRootMode; var optionAssertions_4 = optionAssertions.assertSourceMaps; var optionAssertions_5 = optionAssertions.assertCompact; var optionAssertions_6 = optionAssertions.assertSourceType; var optionAssertions_7 = optionAssertions.assertCallerMetadata; var optionAssertions_8 = optionAssertions.assertInputSourceMap; var optionAssertions_9 = optionAssertions.assertString; var optionAssertions_10 = optionAssertions.assertFunction; var optionAssertions_11 = optionAssertions.assertBoolean; var optionAssertions_12 = optionAssertions.assertObject; var optionAssertions_13 = optionAssertions.assertArray; var optionAssertions_14 = optionAssertions.assertIgnoreList; var optionAssertions_15 = optionAssertions.assertConfigApplicableTest; var optionAssertions_16 = optionAssertions.assertConfigFileSearch; var optionAssertions_17 = optionAssertions.assertBabelrcSearch; var optionAssertions_18 = optionAssertions.assertPluginList; var options$1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.validate = validate; exports.checkNoUnwrappedItemOptionPairs = checkNoUnwrappedItemOptionPairs; var _plugin = _interopRequireDefault(plugin); var _removed = _interopRequireDefault(removed); 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, cloneInputAst: 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 Error(`Using removed Babel ${version} option: ${(0, optionAssertions.msg)(loc)} - ${message}`); } else { const unknownOptErr = new Error(`Unknown option: ${(0, optionAssertions.msg)(loc)}. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.`); unknownOptErr.code = "BABEL_UNKNOWN_OPTION"; throw 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; } function checkNoUnwrappedItemOptionPairs(items, index, type, e) { if (index === 0) return; const lastItem = items[index - 1]; const thisItem = items[index]; if (lastItem.file && lastItem.options === undefined && typeof thisItem.value === "object") { e.message += `\n- Maybe you meant to use\n` + `"${type}": [\n ["${lastItem.file.request}", ${JSON.stringify(thisItem.value, undefined, 2)}]\n]\n` + `To be a valid ${type}, its name and options should be wrapped in a pair of brackets`; } } }); unwrapExports(options$1); var options_1$1 = options$1.validate; var options_2$1 = options$1.checkNoUnwrappedItemOptionPairs; var printer$1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.ConfigPrinter = exports.ChainFormatter = void 0; const ChainFormatter = { Programmatic: 0, Config: 1 }; exports.ChainFormatter = ChainFormatter; const Formatter = { title(type, callerName, filepath) { let title = ""; if (type === ChainFormatter.Programmatic) { title = "programmatic options"; if (callerName) { title += " from " + callerName; } } else { title = "config " + filepath; } return title; }, loc(index, envName) { let loc = ""; if (index != null) { loc += `.overrides[${index}]`; } if (envName != null) { loc += `.env["${envName}"]`; } return loc; }, optionsAndDescriptors(opt) { const content = Object.assign({}, opt.options); delete content.overrides; delete content.env; const pluginDescriptors = [...opt.plugins()]; if (pluginDescriptors.length) { content.plugins = pluginDescriptors.map(d => descriptorToConfig(d)); } const presetDescriptors = [...opt.presets()]; if (presetDescriptors.length) { content.presets = [...presetDescriptors].map(d => descriptorToConfig(d)); } return JSON.stringify(content, undefined, 2); } }; function descriptorToConfig(d) { var _d$file; let name = (_d$file = d.file) == null ? void 0 : _d$file.request; if (name == null) { if (typeof d.value === "object") { name = d.value; } else if (typeof d.value === "function") { name = `[Function: ${d.value.toString().substr(0, 50)} ... ]`; } } if (name == null) { name = "[Unknown]"; } if (d.options === undefined) { return name; } else if (d.name == null) { return [name, d.options]; } else { return [name, d.options, d.name]; } } class ConfigPrinter { constructor() { this._stack = []; } configure(enabled, type, { callerName, filepath }) { if (!enabled) return () => {}; return (content, index, envName) => { this._stack.push({ type, callerName, filepath, content, index, envName }); }; } static format(config) { let title = Formatter.title(config.type, config.callerName, config.filepath); const loc = Formatter.loc(config.index, config.envName); if (loc) title += ` ${loc}`; const content = Formatter.optionsAndDescriptors(config.content); return `${title}\n${content}`; } output() { if (this._stack.length === 0) return ""; return this._stack.map(s => ConfigPrinter.format(s)).join("\n\n"); } } exports.ConfigPrinter = ConfigPrinter; }); unwrapExports(printer$1); var printer_1 = printer$1.ConfigPrinter; var printer_2 = printer$1.ChainFormatter; var configChain = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.buildPresetChain = buildPresetChain; exports.buildRootChain = buildRootChain; exports.buildPresetChainWalker = void 0; function _path() { const data = _interopRequireDefault(require$$1); _path = function () { return data; }; return data; } function _debug() { const data = _interopRequireDefault(src); _debug = function () { return data; }; return data; } var _patternToRegex = _interopRequireDefault(patternToRegex); 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 = yield* buildPresetChainWalker(arg, context); if (!chain) return null; return { plugins: dedupDescriptors(chain.plugins), presets: dedupDescriptors(chain.presets), options: chain.options.map(o => normalizeOptions(o)), files: new Set() }; } const buildPresetChainWalker = makeChainWalker({ root: preset => loadPresetDescriptors(preset), env: (preset, envName) => loadPresetEnvDescriptors(preset)(envName), overrides: (preset, index) => loadPresetOverridesDescriptors(preset)(index), overridesEnv: (preset, index, envName) => loadPresetOverridesEnvDescriptors(preset)(index)(envName), createLogger: () => () => {} }); exports.buildPresetChainWalker = buildPresetChainWalker; const loadPresetDescriptors = (0, caching.makeWeakCacheSync)(preset => buildRootDescriptors(preset, preset.alias, configDescriptors.createUncachedDescriptors)); const loadPresetEnvDescriptors = (0, caching.makeWeakCacheSync)(preset => (0, caching.makeStrongCacheSync)(envName => buildEnvDescriptors(preset, preset.alias, configDescriptors.createUncachedDescriptors, envName))); const loadPresetOverridesDescriptors = (0, caching.makeWeakCacheSync)(preset => (0, caching.makeStrongCacheSync)(index => buildOverrideDescriptors(preset, preset.alias, configDescriptors.createUncachedDescriptors, index))); const loadPresetOverridesEnvDescriptors = (0, caching.makeWeakCacheSync)(preset => (0, caching.makeStrongCacheSync)(index => (0, caching.makeStrongCacheSync)(envName => buildOverrideEnvDescriptors(preset, preset.alias, configDescriptors.createUncachedDescriptors, index, envName)))); function* buildRootChain(opts, context) { let configReport, babelRcReport; const programmaticLogger = new printer$1.ConfigPrinter(); const programmaticChain = yield* loadProgrammaticChain({ options: opts, dirname: context.cwd }, context, undefined, programmaticLogger); if (!programmaticChain) return null; const programmaticReport = programmaticLogger.output(); let configFile; if (typeof opts.configFile === "string") { configFile = yield* (0, files.loadConfig)(opts.configFile, context.cwd, context.envName, context.caller); } else if (opts.configFile !== false) { configFile = yield* (0, files.findRootConfig)(context.root, context.envName, context.caller); } let { babelrc, babelrcRoots } = opts; let babelrcRootsDirectory = context.cwd; const configFileChain = emptyChain(); const configFileLogger = new printer$1.ConfigPrinter(); if (configFile) { const validatedFile = validateConfigFile(configFile); const result = yield* loadFileChain(validatedFile, context, undefined, configFileLogger); if (!result) return null; configReport = configFileLogger.output(); 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" ? yield* (0, files.findPackageData)(context.filename) : null; let ignoreFile, babelrcFile; let isIgnored = false; const fileChain = emptyChain(); if ((babelrc === true || babelrc === undefined) && pkgData && babelrcLoadEnabled(context, pkgData, babelrcRoots, babelrcRootsDirectory)) { ({ ignore: ignoreFile, config: babelrcFile } = yield* (0, files.findRelativeConfig)(pkgData, context.envName, context.caller)); if (ignoreFile) { fileChain.files.add(ignoreFile.filepath); } if (ignoreFile && shouldIgnore(context, ignoreFile.ignore, null, ignoreFile.dirname)) { isIgnored = true; } if (babelrcFile && !isIgnored) { const validatedFile = validateBabelrcFile(babelrcFile); const babelrcLogger = new printer$1.ConfigPrinter(); const result = yield* loadFileChain(validatedFile, context, undefined, babelrcLogger); if (!result) { isIgnored = true; } else { babelRcReport = babelrcLogger.output(); mergeChain(fileChain, result); } } if (babelrcFile && isIgnored) { fileChain.files.add(babelrcFile.filepath); } } if (context.showConfig) { console.log(`Babel configs on "${context.filename}" (ascending priority):\n` + [configReport, babelRcReport, programmaticReport].filter(x => !!x).join("\n\n")); return null; } const chain = mergeChain(mergeChain(mergeChain(emptyChain(), configFileChain), fileChain), programmaticChain); return { plugins: isIgnored ? [] : dedupDescriptors(chain.plugins), presets: isIgnored ? [] : dedupDescriptors(chain.presets), options: isIgnored ? [] : chain.options.map(o => normalizeOptions(o)), fileHandling: isIgnored ? "ignored" : "transpile", ignore: ignoreFile || undefined, babelrc: babelrcFile || undefined, config: configFile || undefined, files: chain.files }; } 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.makeWeakCacheSync)(file => ({ filepath: file.filepath, dirname: file.dirname, options: (0, options$1.validate)("configfile", file.options) })); const validateBabelrcFile = (0, caching.makeWeakCacheSync)(file => ({ filepath: file.filepath, dirname: file.dirname, options: (0, options$1.validate)("babelrcfile", file.options) })); const validateExtendFile = (0, caching.makeWeakCacheSync)(file => ({ filepath: file.filepath, dirname: file.dirname, options: (0, options$1.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), createLogger: (input, context, baseLogger) => buildProgrammaticLogger(input, context, baseLogger) }); const loadFileChainWalker = 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), createLogger: (file, context, baseLogger) => buildFileLogger(file.filepath, context, baseLogger) }); function* loadFileChain(input, context, files, baseLogger) { const chain = yield* loadFileChainWalker(input, context, files, baseLogger); if (chain) { chain.files.add(input.filepath); } return chain; } const loadFileDescriptors = (0, caching.makeWeakCacheSync)(file => buildRootDescriptors(file, file.filepath, configDescriptors.createUncachedDescriptors)); const loadFileEnvDescriptors = (0, caching.makeWeakCacheSync)(file => (0, caching.makeStrongCacheSync)(envName => buildEnvDescriptors(file, file.filepath, configDescriptors.createUncachedDescriptors, envName))); const loadFileOverridesDescriptors = (0, caching.makeWeakCacheSync)(file => (0, caching.makeStrongCacheSync)(index => buildOverrideDescriptors(file, file.filepath, configDescriptors.createUncachedDescriptors, index))); const loadFileOverridesEnvDescriptors = (0, caching.makeWeakCacheSync)(file => (0, caching.makeStrongCacheSync)(index => (0, caching.makeStrongCacheSync)(envName => buildOverrideEnvDescriptors(file, file.filepath, configDescriptors.createUncachedDescriptors, index, envName)))); function buildFileLogger(filepath, context, baseLogger) { if (!baseLogger) { return () => {}; } return baseLogger.configure(context.showConfig, printer$1.ChainFormatter.Config, { filepath }); } function buildRootDescriptors({ dirname, options }, alias, descriptors) { return descriptors(dirname, options, alias); } function buildProgrammaticLogger(_, context, baseLogger) { var _context$caller; if (!baseLogger) { return () => {}; } return baseLogger.configure(context.showConfig, printer$1.ChainFormatter.Programmatic, { callerName: (_context$caller = context.caller) == null ? void 0 : _context$caller.name }); } 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, createLogger }) { return function* (input, context, files = new Set(), baseLogger) { const { dirname } = input; const flattenedConfigs = []; const rootOpts = root(input); if (configIsApplicable(rootOpts, dirname, context)) { flattenedConfigs.push({ config: rootOpts, envName: undefined, index: undefined }); const envOpts = env(input, context.envName); if (envOpts && configIsApplicable(envOpts, dirname, context)) { flattenedConfigs.push({ config: envOpts, envName: context.envName, index: undefined }); } (rootOpts.options.overrides || []).forEach((_, index) => { const overrideOps = overrides(input, index); if (configIsApplicable(overrideOps, dirname, context)) { flattenedConfigs.push({ config: overrideOps, index, envName: undefined }); const overrideEnvOpts = overridesEnv(input, index, context.envName); if (overrideEnvOpts && configIsApplicable(overrideEnvOpts, dirname, context)) { flattenedConfigs.push({ config: overrideEnvOpts, index, envName: context.envName }); } } }); } if (flattenedConfigs.some(({ config: { options: { ignore, only } } }) => shouldIgnore(context, ignore, only, dirname))) { return null; } const chain = emptyChain(); const logger = createLogger(input, context, baseLogger); for (const { config, index, envName } of flattenedConfigs) { if (!(yield* mergeExtendsChain(chain, config.options, dirname, context, files, baseLogger))) { return null; } logger(config, index, envName); mergeChainOpts(chain, config); } return chain; }; } function* mergeExtendsChain(chain, opts, dirname, context, files$1, baseLogger) { if (opts.extends === undefined) return true; const file = yield* (0, files.loadConfig)(opts.extends, dirname, context.envName, context.caller); if (files$1.has(file)) { throw new Error(`Configuration cycle detected loading ${file.filepath}.\n` + `File already loaded following the config chain:\n` + Array.from(files$1, file => ` - ${file.filepath}`).join("\n")); } files$1.add(file); const fileChain = yield* loadFileChain(validateExtendFile(file), context, files$1, baseLogger); files$1.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); for (const file of source.files) { target.files.add(file); } 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: [], files: new Set() }; } 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 (Object.prototype.hasOwnProperty.call(options, "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)) { var _context$filename; const message = `No config is applied to "${(_context$filename = context.filename) != null ? _context$filename : "(unknown)"}" because it matches one of \`ignore: ${JSON.stringify(ignore)}\` from "${dirname}"`; debug(message); if (context.showConfig) { console.log(message); } return true; } if (only && !matchesPatterns(context, only, dirname)) { var _context$filename2; const message = `No config is applied to "${(_context$filename2 = context.filename) != null ? _context$filename2 : "(unknown)"}" because it fails to match one of \`only: ${JSON.stringify(only)}\` from "${dirname}"`; debug(message); if (context.showConfig) { console.log(message); } 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); } }); unwrapExports(configChain); var configChain_1 = configChain.buildPresetChain; var configChain_2 = configChain.buildRootChain; var configChain_3 = configChain.buildPresetChainWalker; var plugins$1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.validatePluginObject = validatePluginObject; 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(loc, value) { const obj = (0, optionAssertions.assertObject)(loc, value); if (obj) { Object.keys(obj).forEach(prop => assertVisitorHandler(prop, obj[prop])); if (obj.enter || obj.exit) { throw new Error(`${(0, optionAssertions.msg)(loc)} 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) { const rootPath = { type: "root", source: "plugin" }; Object.keys(obj).forEach(key => { const validator = VALIDATORS[key]; if (validator) { const optLoc = { type: "option", name: key, parent: rootPath }; validator(optLoc, obj[key]); } else { const invalidPluginPropertyError = new Error(`.${key} is not a valid Plugin property`); invalidPluginPropertyError.code = "BABEL_UNKNOWN_PLUGIN_PROPERTY"; throw invalidPluginPropertyError; } }); return obj; } }); unwrapExports(plugins$1); var plugins_1$1 = plugins$1.validatePluginObject; var partial = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = loadPrivatePartialConfig; exports.loadPartialConfig = void 0; function _path() { const data = _interopRequireDefault(require$$1); _path = function () { return data; }; return data; } function _gensync() { const data = _interopRequireDefault(gensync); _gensync = function () { return data; }; return data; } var _plugin = _interopRequireDefault(plugin); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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* resolveRootMode(rootDir, rootMode) { switch (rootMode) { case "root": return rootDir; case "upward-optional": { const upwardRootDir = yield* (0, files.findConfigUpwards)(rootDir); return upwardRootDir === null ? rootDir : upwardRootDir; } case "upward": { const upwardRootDir = yield* (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}".\n` + `One of the following config files must be in the directory tree: ` + `"${files.ROOT_CONFIG_FILENAMES.join(", ")}".`), { 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$1.validate)("arguments", inputOpts) : {}; const { envName = (0, environment.getEnv)(), cwd = ".", root: rootDir = ".", rootMode = "root", caller, cloneInputAst = true } = args; const absoluteCwd = _path().default.resolve(cwd); const absoluteRootDir = yield* resolveRootMode(_path().default.resolve(absoluteCwd, rootDir), rootMode); const filename = typeof args.filename === "string" ? _path().default.resolve(cwd, args.filename) : undefined; const showConfigPath = yield* (0, files.resolveShowConfigPath)(absoluteCwd); const context = { filename, cwd: absoluteCwd, root: absoluteRootDir, envName, caller, showConfig: showConfigPath === filename }; const configChain$1 = yield* (0, configChain.buildRootChain)(args, context); if (!configChain$1) return null; const options = {}; configChain$1.options.forEach(opts => { (0, util$4.mergeOptions)(options, opts); }); options.cloneInputAst = cloneInputAst; 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$1.plugins.map(descriptor => (0, item.createItemFromDescriptor)(descriptor)); options.presets = configChain$1.presets.map(descriptor => (0, item.createItemFromDescriptor)(descriptor)); return { options, context, fileHandling: configChain$1.fileHandling, ignore: configChain$1.ignore, babelrc: configChain$1.babelrc, config: configChain$1.config, files: configChain$1.files }; } const loadPartialConfig = (0, _gensync().default)(function* (opts) { let showIgnoredFiles = false; if (typeof opts === "object" && opts !== null && !Array.isArray(opts)) { var _opts = opts; ({ showIgnoredFiles } = _opts); opts = _objectWithoutPropertiesLoose(_opts, ["showIgnoredFiles"]); } const result = yield* loadPrivatePartialConfig(opts); if (!result) return null; const { options, babelrc, ignore, config, fileHandling, files } = result; if (fileHandling === "ignored" && !showIgnoredFiles) { return null; } (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, fileHandling, files); }); exports.loadPartialConfig = loadPartialConfig; class PartialConfig { constructor(options, babelrc, ignore, config, fileHandling, files) { this.options = void 0; this.babelrc = void 0; this.babelignore = void 0; this.config = void 0; this.fileHandling = void 0; this.files = void 0; this.options = options; this.babelignore = ignore; this.babelrc = babelrc; this.config = config; this.fileHandling = fileHandling; this.files = files; Object.freeze(this); } hasFilesystemConfig() { return this.babelrc !== undefined || this.config !== undefined; } } Object.freeze(PartialConfig.prototype); }); unwrapExports(partial); var partial_1 = partial.loadPartialConfig; var full = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; function _gensync() { const data = _interopRequireDefault(gensync); _gensync = function () { return data; }; return data; } var context = _interopRequireWildcard(lib$j); var _plugin = _interopRequireDefault(plugin); function _traverse() { const data = _interopRequireDefault(lib$a); _traverse = function () { return data; }; return data; } var _configApi = _interopRequireDefault(configApi); var _partial = _interopRequireDefault(partial); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _default = (0, _gensync().default)(function* loadFullConfig(inputOpts) { const result = yield* (0, _partial.default)(inputOpts); if (!result) { return null; } const { options, context, fileHandling } = result; if (fileHandling === "ignored") { return null; } const optionDefaults = {}; const { plugins, presets } = options; if (!plugins || !presets) { throw new Error("Assertion failure - plugins and presets exist"); } const toDescriptor = item$1 => { const desc = (0, item.getItemDescriptor)(item$1); if (!desc) { throw new Error("Assertion failure - must be config item"); } return desc; }; const presetsDescriptors = presets.map(toDescriptor); const initialPluginsDescriptors = plugins.map(toDescriptor); const pluginDescriptorsByPass = [[]]; const passes = []; const ignored = yield* enhanceError(context, function* recursePresetDescriptors(rawPresets, pluginDescriptorsPass) { const presets = []; for (let i = 0; i < rawPresets.length; i++) { const descriptor = rawPresets[i]; if (descriptor.options !== false) { try { if (descriptor.ownPass) { presets.push({ preset: yield* loadPresetDescriptor(descriptor, context), pass: [] }); } else { presets.unshift({ preset: yield* loadPresetDescriptor(descriptor, context), pass: pluginDescriptorsPass }); } } catch (e) { if (e.code === "BABEL_UNKNOWN_OPTION") { (0, options$1.checkNoUnwrappedItemOptionPairs)(rawPresets, i, "preset", e); } throw e; } } } if (presets.length > 0) { pluginDescriptorsByPass.splice(1, 0, ...presets.map(o => o.pass).filter(p => p !== pluginDescriptorsPass)); for (const { preset, pass } of presets) { if (!preset) return true; pass.push(...preset.plugins); const ignored = yield* recursePresetDescriptors(preset.presets, pass); if (ignored) return true; preset.options.forEach(opts => { (0, util$4.mergeOptions)(optionDefaults, opts); }); } } })(presetsDescriptors, pluginDescriptorsByPass[0]); if (ignored) return null; const opts = optionDefaults; (0, util$4.mergeOptions)(opts, options); yield* enhanceError(context, function* loadPluginDescriptors() { pluginDescriptorsByPass[0].unshift(...initialPluginsDescriptors); for (const descs of pluginDescriptorsByPass) { const pass = []; passes.push(pass); for (let i = 0; i < descs.length; i++) { const descriptor = descs[i]; if (descriptor.options !== false) { try { pass.push(yield* loadPluginDescriptor(descriptor, context)); } catch (e) { if (e.code === "BABEL_UNKNOWN_PLUGIN_PROPERTY") { (0, options$1.checkNoUnwrappedItemOptionPairs)(descs, i, "plugin", e); } throw e; } } } } })(); 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 }; }); exports.default = _default; function enhanceError(context, fn) { return function* (arg1, arg2) { try { return yield* fn(arg1, arg2); } catch (e) { if (!/^\[BABEL\]/.test(e.message)) { e.message = `[BABEL] ${context.filename || "unknown"}: ${e.message}`; } throw e; } }; } const loadDescriptor = (0, caching.makeWeakCache)(function* ({ 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") { yield* []; 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 yield* instantiatePlugin(yield* loadDescriptor(descriptor, context), context); } const instantiatePlugin = (0, caching.makeWeakCache)(function* ({ value, options, dirname, alias }, cache) { const pluginObj = (0, plugins$1.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 = yield* (0, async.forwardAsync)(loadPluginDescriptor, run => { return cache.invalidate(data => run(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 validateIfOptionNeedsFilename = (options, descriptor) => { if (options.test || options.include || options.exclude) { const formattedPresetName = descriptor.name ? `"${descriptor.name}"` : "/* your preset */"; throw new Error([`Preset ${formattedPresetName} requires a filename to be set when babel is called directly,`, `\`\`\``, `babel.transform(code, { filename: 'file.ts', presets: [${formattedPresetName}] });`, `\`\`\``, `See https://babeljs.io/docs/en/options#filename for more information.`].join("\n")); } }; const validatePreset = (preset, context, descriptor) => { if (!context.filename) { const { options } = preset; validateIfOptionNeedsFilename(options, descriptor); if (options.overrides) { options.overrides.forEach(overrideOptions => validateIfOptionNeedsFilename(overrideOptions, descriptor)); } } }; function* loadPresetDescriptor(descriptor, context) { const preset = instantiatePreset(yield* loadDescriptor(descriptor, context)); validatePreset(preset, context, descriptor); return yield* (0, configChain.buildPresetChain)(preset, context); } const instantiatePreset = (0, caching.makeWeakCacheSync)(({ value, dirname, alias }) => { return { options: (0, options$1.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); } }; } }); unwrapExports(full); var config$1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "default", { enumerable: true, get: function () { return _full.default; } }); exports.loadOptionsAsync = exports.loadOptionsSync = exports.loadOptions = exports.loadPartialConfigAsync = exports.loadPartialConfigSync = exports.loadPartialConfig = void 0; function _gensync() { const data = _interopRequireDefault(gensync); _gensync = function () { return data; }; return data; } var _full = _interopRequireDefault(full); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const loadOptionsRunner = (0, _gensync().default)(function* (opts) { var _config$options; const config = yield* (0, _full.default)(opts); return (_config$options = config == null ? void 0 : config.options) != null ? _config$options : null; }); const maybeErrback = runner => (opts, callback) => { if (callback === undefined && typeof opts === "function") { callback = opts; opts = undefined; } return callback ? runner.errback(opts, callback) : runner.sync(opts); }; const loadPartialConfig = maybeErrback(partial.loadPartialConfig); exports.loadPartialConfig = loadPartialConfig; const loadPartialConfigSync = partial.loadPartialConfig.sync; exports.loadPartialConfigSync = loadPartialConfigSync; const loadPartialConfigAsync = partial.loadPartialConfig.async; exports.loadPartialConfigAsync = loadPartialConfigAsync; const loadOptions = maybeErrback(loadOptionsRunner); exports.loadOptions = loadOptions; const loadOptionsSync = loadOptionsRunner.sync; exports.loadOptionsSync = loadOptionsSync; const loadOptionsAsync = loadOptionsRunner.async; exports.loadOptionsAsync = loadOptionsAsync; }); unwrapExports(config$1); var config_1 = config$1.loadOptionsAsync; var config_2 = config$1.loadOptionsSync; var config_3 = config$1.loadOptions; var config_4 = config$1.loadPartialConfigAsync; var config_5 = config$1.loadPartialConfigSync; var config_6 = config$1.loadPartialConfig; var pluginPass = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; class PluginPass { constructor(file, key, options) { this._map = new Map(); this.key = void 0; this.file = void 0; this.opts = void 0; this.cwd = void 0; this.filename = void 0; 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; }); unwrapExports(pluginPass); /** Built-in value references. */ var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined; /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray_1(value) || isArguments_1(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } var _isFlattenable = isFlattenable; /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = _isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { _arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } var _baseFlatten = baseFlatten; /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/; /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray_1(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol_1(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } var _isKey = isKey; /** Error message constants. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || _MapCache); return memoized; } // Expose `MapCache`. memoize.Cache = _MapCache; var memoize_1 = memoize; /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize_1(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } var _memoizeCapped = memoizeCapped; /** Used to match property names within property paths. */ var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = _memoizeCapped(function(string) { var result = []; if (string.charCodeAt(0) === 46 /* . */) { result.push(''); } string.replace(rePropName, function(match, number, quote, subString) { result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); var _stringToPath = stringToPath; /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray_1(value)) { return value; } return _isKey(value, object) ? [value] : _stringToPath(toString_1(value)); } var _castPath = castPath; /** Used as references for various `Number` constants. */ var INFINITY$2 = 1 / 0; /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol_1(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY$2) ? '-0' : result; } var _toKey = toKey; /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = _castPath(path, object); var index = 0, length = path.length; while (object != null && index < length) { object = object[_toKey(path[index++])]; } return (index && index == length) ? object : undefined; } var _baseGet = baseGet; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED$2); return this; } var _setCacheAdd = setCacheAdd; /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } var _setCacheHas = setCacheHas; /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new _MapCache; while (++index < length) { this.add(values[index]); } } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd; SetCache.prototype.has = _setCacheHas; var _SetCache = SetCache; /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } var _arraySome = arraySome; /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } var _cacheHas = cacheHas; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Check that cyclic values are equal. var arrStacked = stack.get(array); var othStacked = stack.get(other); if (arrStacked && othStacked) { return arrStacked == other && othStacked == array; } var index = -1, result = true, seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new _SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!_arraySome(other, function(othValue, othIndex) { if (!_cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } var _equalArrays = equalArrays; /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } var _mapToArray = mapToArray; /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } var _setToArray = setToArray; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$1 = 1, COMPARE_UNORDERED_FLAG$1 = 2; /** `Object#toString` result references. */ var boolTag$3 = '[object Boolean]', dateTag$3 = '[object Date]', errorTag$2 = '[object Error]', mapTag$5 = '[object Map]', numberTag$3 = '[object Number]', regexpTag$4 = '[object RegExp]', setTag$5 = '[object Set]', stringTag$3 = '[object String]', symbolTag$3 = '[object Symbol]'; var arrayBufferTag$3 = '[object ArrayBuffer]', dataViewTag$4 = '[object DataView]'; /** Used to convert symbols to primitives and strings. */ var symbolProto$2 = _Symbol ? _Symbol.prototype : undefined, symbolValueOf$1 = symbolProto$2 ? symbolProto$2.valueOf : undefined; /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag$4: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag$3: if ((object.byteLength != other.byteLength) || !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) { return false; } return true; case boolTag$3: case dateTag$3: case numberTag$3: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq_1(+object, +other); case errorTag$2: return object.name == other.name && object.message == other.message; case regexpTag$4: case stringTag$3: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag$5: var convert = _mapToArray; case setTag$5: var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1; convert || (convert = _setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG$1; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag$3: if (symbolValueOf$1) { return symbolValueOf$1.call(object) == symbolValueOf$1.call(other); } } return false; } var _equalByTag = equalByTag; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$2 = 1; /** Used for built-in method references. */ var objectProto$e = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$e = objectProto$e.hasOwnProperty; /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2, objProps = _getAllKeys(object), objLength = objProps.length, othProps = _getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty$e.call(other, key))) { return false; } } // Check that cyclic values are equal. var objStacked = stack.get(object); var othStacked = stack.get(other); if (objStacked && othStacked) { return objStacked == other && othStacked == object; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } var _equalObjects = equalObjects; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$3 = 1; /** `Object#toString` result references. */ var argsTag$3 = '[object Arguments]', arrayTag$2 = '[object Array]', objectTag$4 = '[object Object]'; /** Used for built-in method references. */ var objectProto$f = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$f = objectProto$f.hasOwnProperty; /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray_1(object), othIsArr = isArray_1(other), objTag = objIsArr ? arrayTag$2 : _getTag(object), othTag = othIsArr ? arrayTag$2 : _getTag(other); objTag = objTag == argsTag$3 ? objectTag$4 : objTag; othTag = othTag == argsTag$3 ? objectTag$4 : othTag; var objIsObj = objTag == objectTag$4, othIsObj = othTag == objectTag$4, isSameTag = objTag == othTag; if (isSameTag && isBuffer_1(object)) { if (!isBuffer_1(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new _Stack); return (objIsArr || isTypedArray_1(object)) ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack) : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) { var objIsWrapped = objIsObj && hasOwnProperty$f.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty$f.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new _Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new _Stack); return _equalObjects(object, other, bitmask, customizer, equalFunc, stack); } var _baseIsEqualDeep = baseIsEqualDeep; /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike_1(value) && !isObjectLike_1(other))) { return value !== value && other !== other; } return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } var _baseIsEqual = baseIsEqual; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$4 = 1, COMPARE_UNORDERED_FLAG$2 = 2; /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new _Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) : result )) { return false; } } } return true; } var _baseIsMatch = baseIsMatch; /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject_1(value); } var _isStrictComparable = isStrictComparable; /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys_1(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, _isStrictComparable(value)]; } return result; } var _getMatchData = getMatchData; /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || (key in Object(object))); }; } var _matchesStrictComparable = matchesStrictComparable; /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = _getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return _matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || _baseIsMatch(object, source, matchData); }; } var _baseMatches = baseMatches; /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : _baseGet(object, path); return result === undefined ? defaultValue : result; } var get_1 = get; /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } var _baseHasIn = baseHasIn; /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = _castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = _toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength_1(length) && _isIndex(key, length) && (isArray_1(object) || isArguments_1(object)); } var _hasPath = hasPath; /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && _hasPath(object, path, _baseHasIn); } var hasIn_1 = hasIn; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$5 = 1, COMPARE_UNORDERED_FLAG$3 = 2; /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (_isKey(path) && _isStrictComparable(srcValue)) { return _matchesStrictComparable(_toKey(path), srcValue); } return function(object) { var objValue = get_1(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn_1(object, path) : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3); }; } var _baseMatchesProperty = baseMatchesProperty; /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } var identity_1 = identity; /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } var _baseProperty = baseProperty; /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return _baseGet(object, path); }; } var _basePropertyDeep = basePropertyDeep; /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. * @example * * var objects = [ * { 'a': { 'b': 2 } }, * { 'a': { 'b': 1 } } * ]; * * _.map(objects, _.property('a.b')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); * // => [1, 2] */ function property(path) { return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path); } var property_1 = property; /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity_1; } if (typeof value == 'object') { return isArray_1(value) ? _baseMatchesProperty(value[0], value[1]) : _baseMatches(value); } return property_1(value); } var _baseIteratee = baseIteratee; /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } var _createBaseFor = createBaseFor; /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = _createBaseFor(); var _baseFor = baseFor; /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && _baseFor(object, iteratee, keys_1); } var _baseForOwn = baseForOwn; /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike_1(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } var _createBaseEach = createBaseEach; /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = _createBaseEach(_baseForOwn); var _baseEach = baseEach; /** * The base implementation of `_.map` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike_1(collection) ? Array(collection.length) : []; _baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } var _baseMap = baseMap; /** * The base implementation of `_.sortBy` which uses `comparer` to define the * sort order of `array` and replaces criteria objects with their corresponding * values. * * @private * @param {Array} array The array to sort. * @param {Function} comparer The function to define sort order. * @returns {Array} Returns `array`. */ function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value; } return array; } var _baseSortBy = baseSortBy; /** * Compares values to sort them in ascending order. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {number} Returns the sort order indicator for `value`. */ function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol_1(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol_1(other); if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; } var _compareAscending = compareAscending; /** * Used by `_.orderBy` to compare multiple properties of a value to another * and stable sort them. * * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, * specify an order of "desc" for descending or "asc" for ascending sort order * of corresponding values. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {boolean[]|string[]} orders The order to sort by for each property. * @returns {number} Returns the sort order indicator for `object`. */ function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = _compareAscending(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result; } var order = orders[index]; return result * (order == 'desc' ? -1 : 1); } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to provide the same value for // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 // for more details. // // This also ensures a stable sort in V8 and other engines. // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. return object.index - other.index; } var _compareMultiple = compareMultiple; /** * The base implementation of `_.orderBy` without param guards. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {string[]} orders The sort orders of `iteratees`. * @returns {Array} Returns the new sorted array. */ function baseOrderBy(collection, iteratees, orders) { if (iteratees.length) { iteratees = _arrayMap(iteratees, function(iteratee) { if (isArray_1(iteratee)) { return function(value) { return _baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee); } } return iteratee; }); } else { iteratees = [identity_1]; } var index = -1; iteratees = _arrayMap(iteratees, _baseUnary(_baseIteratee)); var result = _baseMap(collection, function(value, key, collection) { var criteria = _arrayMap(iteratees, function(iteratee) { return iteratee(value); }); return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return _baseSortBy(result, function(object, other) { return _compareMultiple(object, other, orders); }); } var _baseOrderBy = baseOrderBy; /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } var _apply = apply; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$1 = Math.max; /** * A specialized version of `baseRest` which transforms the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @param {Function} transform The rest array transform. * @returns {Function} Returns the new function. */ function overRest(func, start, transform) { start = nativeMax$1(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax$1(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = transform(array); return _apply(func, this, otherArgs); }; } var _overRest = overRest; /** * Creates a function that returns `value`. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {*} value The value to return from the new function. * @returns {Function} Returns the new constant function. * @example * * var objects = _.times(2, _.constant({ 'a': 1 })); * * console.log(objects); * // => [{ 'a': 1 }, { 'a': 1 }] * * console.log(objects[0] === objects[1]); * // => true */ function constant(value) { return function() { return value; }; } var constant_1 = constant; /** * The base implementation of `setToString` without support for hot loop shorting. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var baseSetToString = !_defineProperty ? identity_1 : function(func, string) { return _defineProperty(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant_1(string), 'writable': true }); }; var _baseSetToString = baseSetToString; /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 800, HOT_SPAN = 16; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeNow = Date.now; /** * Creates a function that'll short out and invoke `identity` instead * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` * milliseconds. * * @private * @param {Function} func The function to restrict. * @returns {Function} Returns the new shortable function. */ function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(undefined, arguments); }; } var _shortOut = shortOut; /** * Sets the `toString` method of `func` to return `string`. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var setToString = _shortOut(_baseSetToString); var _setToString = setToString; /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { return _setToString(_overRest(func, start, identity_1), func + ''); } var _baseRest = baseRest; /** * Creates an array of elements, sorted in ascending order by the results of * running each element in a collection thru each iteratee. This method * performs a stable sort, that is, it preserves the original sort order of * equal elements. The iteratees are invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {...(Function|Function[])} [iteratees=[_.identity]] * The iteratees to sort by. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 30 }, * { 'user': 'barney', 'age': 34 } * ]; * * _.sortBy(users, [function(o) { return o.user; }]); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]] * * _.sortBy(users, ['user', 'age']); * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]] */ var sortBy = _baseRest(function(collection, iteratees) { if (collection == null) { return []; } var length = iteratees.length; if (length > 1 && _isIterateeCall(collection, iteratees[0], iteratees[1])) { iteratees = []; } else if (length > 2 && _isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { iteratees = [iteratees[0]]; } return _baseOrderBy(collection, _baseFlatten(iteratees, 1), []); }); var sortBy_1 = sortBy; var blockHoistPlugin_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = loadBlockHoistPlugin; function _sortBy() { const data = _interopRequireDefault(sortBy_1); _sortBy = function () { return data; }; return data; } var _config = _interopRequireDefault(config$1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } let LOADED_PLUGIN; function loadBlockHoistPlugin() { if (!LOADED_PLUGIN) { const config = _config.default.sync({ 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 == null ? void 0 : bodyNode._blockHoist) != null) { hasChange = true; break; } } if (!hasChange) return; node.body = (0, _sortBy().default)(node.body, function (bodyNode) { let priority = bodyNode == null ? void 0 : bodyNode._blockHoist; if (priority == null) priority = 1; if (priority === true) priority = 2; return -1 * priority; }); } } } }; }); unwrapExports(blockHoistPlugin_1); var normalizeOpts = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = normalizeOptions; function _path() { const data = _interopRequireDefault(require$$1); _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; } }); unwrapExports(normalizeOpts); /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG$1 = 1, CLONE_SYMBOLS_FLAG$2 = 4; /** * This method is like `_.clone` except that it recursively clones `value`. * * @static * @memberOf _ * @since 1.0.0 * @category Lang * @param {*} value The value to recursively clone. * @returns {*} Returns the deep cloned value. * @see _.clone * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var deep = _.cloneDeep(objects); * console.log(deep[0] === objects[0]); * // => false */ function cloneDeep(value) { return _baseClone(value, CLONE_DEEP_FLAG$1 | CLONE_SYMBOLS_FLAG$2); } var cloneDeep_1$1 = cloneDeep; var safeBuffer = createCommonjsModule(function (module, exports) { /* eslint-disable node/no-deprecated-api */ var Buffer = bufferEs6.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 = bufferEs6; } else { // Copy properties from require('buffer') copyProps(bufferEs6, 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 bufferEs6.SlowBuffer(size) }; }); var safeBuffer_1 = safeBuffer.Buffer; var convertSourceMap = createCommonjsModule(function (module, exports) { 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 = require$$1.resolve(dir, filename); try { return require$$0$1.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; }; }); var convertSourceMap_1 = convertSourceMap.fromObject; var convertSourceMap_2 = convertSourceMap.fromJSON; var convertSourceMap_3 = convertSourceMap.fromBase64; var convertSourceMap_4 = convertSourceMap.fromComment; var convertSourceMap_5 = convertSourceMap.fromMapFileComment; var convertSourceMap_6 = convertSourceMap.fromSource; var convertSourceMap_7 = convertSourceMap.fromMapFileSource; var convertSourceMap_8 = convertSourceMap.removeComments; var convertSourceMap_9 = convertSourceMap.removeMapFileComments; var convertSourceMap_10 = convertSourceMap.generateMapFileComment; var missingPluginHelper = createCommonjsModule(function (module, exports) { 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" } }, classPrivateProperties: { syntax: { name: "@babel/plugin-syntax-class-properties", url: "https://git.io/vb4yQ" }, transform: { name: "@babel/plugin-proposal-class-properties", url: "https://git.io/vb4SL" } }, classPrivateMethods: { syntax: { name: "@babel/plugin-syntax-class-properties", url: "https://git.io/vb4yQ" }, transform: { name: "@babel/plugin-proposal-private-methods", url: "https://git.io/JvpRG" } }, classStaticBlock: { syntax: { name: "@babel/plugin-syntax-class-static-block", url: "https://git.io/JTLB6" }, transform: { name: "@babel/plugin-proposal-class-static-block", url: "https://git.io/JTLBP" } }, decimal: { syntax: { name: "@babel/plugin-syntax-decimal", url: "https://git.io/JfKOH" } }, 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/preset-flow", url: "https://git.io/JfeDn" } }, 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/preset-react", url: "https://git.io/JfeDR" } }, importAssertions: { syntax: { name: "@babel/plugin-syntax-import-assertions", url: "https://git.io/JUbkv" } }, moduleStringNames: { syntax: { name: "@babel/plugin-syntax-module-string-names", url: "https://git.io/JTL8G" } }, 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" } }, privateIn: { syntax: { name: "@babel/plugin-syntax-private-property-in-object", url: "https://git.io/JfK3q" }, transform: { name: "@babel/plugin-proposal-private-property-in-object", url: "https://git.io/JfK3O" } }, recordAndTuple: { syntax: { name: "@babel/plugin-syntax-record-and-tuple", url: "https://git.io/JvKp3" } }, 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/preset-typescript", url: "https://git.io/JfeDz" } }, 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" } }, 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" } }, 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" } } }; pluginNameMap.privateIn.syntax = pluginNameMap.privateIn.transform; 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) { const syntaxPluginInfo = getNameURLCombination(syntaxPlugin); if (transformPlugin) { const transformPluginInfo = getNameURLCombination(transformPlugin); const sectionType = transformPlugin.name.startsWith("@babel/plugin") ? "plugins" : "presets"; helpMessage += `\n\nAdd ${transformPluginInfo} to the '${sectionType}' section of your Babel config to enable transformation. If you want to leave it as-is, add ${syntaxPluginInfo} to the 'plugins' section to enable parsing.`; } else { helpMessage += `\n\nAdd ${syntaxPluginInfo} to the 'plugins' section of your Babel config ` + `to enable parsing.`; } } } return helpMessage; } }); unwrapExports(missingPluginHelper); var parser_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = parser; function _parser() { const data = lib$6; _parser = function () { return data; }; return data; } function _codeFrame() { const data = lib$5; _codeFrame = function () { return data; }; return data; } var _missingPluginHelper = _interopRequireDefault(missingPluginHelper); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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) { yield* []; if (typeof results[0].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.`); } 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; } } }); unwrapExports(parser_1); var normalizeFile_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = normalizeFile; function _fs() { const data = _interopRequireDefault(require$$0$1); _fs = function () { return data; }; return data; } function _path() { const data = _interopRequireDefault(require$$1); _path = function () { return data; }; return data; } function _debug() { const data = _interopRequireDefault(src); _debug = function () { return data; }; return data; } function _cloneDeep() { const data = _interopRequireDefault(cloneDeep_1$1); _cloneDeep = function () { return data; }; return data; } function t() { const data = _interopRequireWildcard(lib$1); t = function () { return data; }; return data; } function _convertSourceMap() { const data = _interopRequireDefault(convertSourceMap); _convertSourceMap = function () { return data; }; return data; } var _file = _interopRequireDefault(file); var _parser = _interopRequireDefault(parser_1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const debug = (0, _debug().default)("babel:transform:file"); const LARGE_INPUT_SOURCEMAP_THRESHOLD = 1000000; function* normalizeFile(pluginPasses, options, code, ast) { code = `${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"); } const { cloneInputAst } = options; if (cloneInputAst) { ast = (0, _cloneDeep().default)(ast); } } else { ast = yield* (0, _parser.default)(pluginPasses, options, code); } let inputMap = null; if (options.inputSourceMap !== false) { if (typeof options.inputSourceMap === "object") { inputMap = _convertSourceMap().default.fromObject(options.inputSourceMap); } if (!inputMap) { const lastComment = extractComments(INLINE_SOURCEMAP_REGEX, ast); if (lastComment) { try { inputMap = _convertSourceMap().default.fromComment(lastComment); } catch (err) { debug("discarding unknown inline input sourcemap", err); } } } if (!inputMap) { const lastComment = extractComments(EXTERNAL_SOURCEMAP_REGEX, ast); if (typeof options.filename === "string" && lastComment) { try { const match = EXTERNAL_SOURCEMAP_REGEX.exec(lastComment); const inputMapContent = _fs().default.readFileSync(_path().default.resolve(_path().default.dirname(options.filename), match[1])); if (inputMapContent.length > LARGE_INPUT_SOURCEMAP_THRESHOLD) { debug("skip merging input map > 1 MB"); } else { inputMap = _convertSourceMap().default.fromJSON(inputMapContent); } } catch (err) { debug("discarding unknown file input sourcemap", err); } } else if (lastComment) { debug("discarding un-loadable file input sourcemap"); } } } return new _file.default(options, { code, ast, inputMap }); } const INLINE_SOURCEMAP_REGEX = /^[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,(?:.*)$/; const EXTERNAL_SOURCEMAP_REGEX = /^[@#][ \t]+sourceMappingURL=([^\s'"`]+)[ \t]*$/; function extractCommentsFromList(regex, comments, lastComment) { if (comments) { comments = comments.filter(({ value }) => { if (regex.test(value)) { lastComment = value; return false; } return true; }); } return [comments, lastComment]; } function extractComments(regex, ast) { let lastComment = null; t().traverseFast(ast, node => { [node.leadingComments, lastComment] = extractCommentsFromList(regex, node.leadingComments, lastComment); [node.innerComments, lastComment] = extractCommentsFromList(regex, node.innerComments, lastComment); [node.trailingComments, lastComment] = extractCommentsFromList(regex, node.trailingComments, lastComment); }); return lastComment; } }); unwrapExports(normalizeFile_1); var mergeMap = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = mergeSourceMap; function _sourceMap() { const data = _interopRequireDefault(sourceMap); _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 { source } of input.sources) { 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 { generated } of overlappingOriginal) { 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 { source, mappings } of map.sources) { for (const { original, generated } of mappings) { 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; } }); unwrapExports(mergeMap); var generate = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.default = generateCode; function _convertSourceMap() { const data = _interopRequireDefault(convertSourceMap); _convertSourceMap = function () { return data; }; return data; } function _generator() { const data = _interopRequireDefault(lib$3); _generator = function () { return data; }; return data; } var _mergeMap = _interopRequireDefault(mergeMap); 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 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.`); } } 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 }; } }); unwrapExports(generate); var transformation = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.run = run; function _traverse() { const data = _interopRequireDefault(lib$a); _traverse = function () { return data; }; return data; } var _pluginPass = _interopRequireDefault(pluginPass); var _blockHoistPlugin = _interopRequireDefault(blockHoistPlugin_1); var _normalizeOpts = _interopRequireDefault(normalizeOpts); var _normalizeFile = _interopRequireDefault(normalizeFile_1); var _generate = _interopRequireDefault(generate); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function* run(config, code, ast) { const file = yield* (0, _normalizeFile.default)(config.passes, (0, _normalizeOpts.default)(config), code, ast); const opts = file.opts; try { yield* transformFile(file, config.passes); } catch (e) { var _opts$filename; e.message = `${(_opts$filename = opts.filename) != null ? _opts$filename : "unknown"}: ${e.message}`; if (!e.code) { e.code = "BABEL_TRANSFORM_ERROR"; } throw e; } let outputCode, outputMap; try { if (opts.code !== false) { ({ outputCode, outputMap } = (0, _generate.default)(config.passes, file)); } } catch (e) { var _opts$filename2; e.message = `${(_opts$filename2 = opts.filename) != null ? _opts$filename2 : "unknown"}: ${e.message}`; if (!e.code) { e.code = "BABEL_GENERATE_ERROR"; } throw e; } 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); yield* []; 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); yield* []; 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"; } }); unwrapExports(transformation); var transformation_1 = transformation.run; var transform_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.transformAsync = exports.transformSync = exports.transform = void 0; function _gensync() { const data = _interopRequireDefault(gensync); _gensync = function () { return data; }; return data; } var _config = _interopRequireDefault(config$1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const transformRunner = (0, _gensync().default)(function* transform(code, opts) { const config = yield* (0, _config.default)(opts); if (config === null) return null; return yield* (0, transformation.run)(config, code); }); const transform = function transform(code, opts, callback) { if (typeof opts === "function") { callback = opts; opts = undefined; } if (callback === undefined) return transformRunner.sync(code, opts); transformRunner.errback(code, opts, callback); }; exports.transform = transform; const transformSync = transformRunner.sync; exports.transformSync = transformSync; const transformAsync = transformRunner.async; exports.transformAsync = transformAsync; }); unwrapExports(transform_1); var transform_2 = transform_1.transformAsync; var transform_3 = transform_1.transformSync; var transform_4 = transform_1.transform; var transformFile_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.transformFileAsync = exports.transformFileSync = exports.transformFile = void 0; function _gensync() { const data = _interopRequireDefault(gensync); _gensync = function () { return data; }; return data; } var _config = _interopRequireDefault(config$1); var fs$1 = _interopRequireWildcard(fs); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const transformFileRunner = (0, _gensync().default)(function* (filename, opts) { const options = Object.assign({}, opts, { filename }); const config = yield* (0, _config.default)(options); if (config === null) return null; const code = yield* fs$1.readFile(filename, "utf8"); return yield* (0, transformation.run)(config, code); }); const transformFile = transformFileRunner.errback; exports.transformFile = transformFile; const transformFileSync = transformFileRunner.sync; exports.transformFileSync = transformFileSync; const transformFileAsync = transformFileRunner.async; exports.transformFileAsync = transformFileAsync; }); unwrapExports(transformFile_1); var transformFile_2 = transformFile_1.transformFileAsync; var transformFile_3 = transformFile_1.transformFileSync; var transformFile_4 = transformFile_1.transformFile; var transformAst = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.transformFromAstAsync = exports.transformFromAstSync = exports.transformFromAst = void 0; function _gensync() { const data = _interopRequireDefault(gensync); _gensync = function () { return data; }; return data; } var _config = _interopRequireDefault(config$1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const transformFromAstRunner = (0, _gensync().default)(function* (ast, code, opts) { const config = yield* (0, _config.default)(opts); if (config === null) return null; if (!ast) throw new Error("No AST given"); return yield* (0, transformation.run)(config, code, ast); }); const transformFromAst = function transformFromAst(ast, code, opts, callback) { if (typeof opts === "function") { callback = opts; opts = undefined; } if (callback === undefined) { return transformFromAstRunner.sync(ast, code, opts); } transformFromAstRunner.errback(ast, code, opts, callback); }; exports.transformFromAst = transformFromAst; const transformFromAstSync = transformFromAstRunner.sync; exports.transformFromAstSync = transformFromAstSync; const transformFromAstAsync = transformFromAstRunner.async; exports.transformFromAstAsync = transformFromAstAsync; }); unwrapExports(transformAst); var transformAst_1 = transformAst.transformFromAstAsync; var transformAst_2 = transformAst.transformFromAstSync; var transformAst_3 = transformAst.transformFromAst; var parse_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.parseAsync = exports.parseSync = exports.parse = void 0; function _gensync() { const data = _interopRequireDefault(gensync); _gensync = function () { return data; }; return data; } var _config = _interopRequireDefault(config$1); var _parser = _interopRequireDefault(parser_1); var _normalizeOpts = _interopRequireDefault(normalizeOpts); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const parseRunner = (0, _gensync().default)(function* parse(code, opts) { const config = yield* (0, _config.default)(opts); if (config === null) { return null; } return yield* (0, _parser.default)(config.passes, (0, _normalizeOpts.default)(config), code); }); const parse = function parse(code, opts, callback) { if (typeof opts === "function") { callback = opts; opts = undefined; } if (callback === undefined) return parseRunner.sync(code, opts); parseRunner.errback(code, opts, callback); }; exports.parse = parse; const parseSync = parseRunner.sync; exports.parseSync = parseSync; const parseAsync = parseRunner.async; exports.parseAsync = parseAsync; }); unwrapExports(parse_1); var parse_2 = parse_1.parseAsync; var parse_3 = parse_1.parseSync; var parse_4 = parse_1.parse; var _package$3 = getCjsExportFromNamespace(_package$2); var lib$j = createCommonjsModule(function (module, exports) { 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$3.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$1.loadPartialConfig; } }); Object.defineProperty(exports, "loadPartialConfigSync", { enumerable: true, get: function () { return config$1.loadPartialConfigSync; } }); Object.defineProperty(exports, "loadPartialConfigAsync", { enumerable: true, get: function () { return config$1.loadPartialConfigAsync; } }); Object.defineProperty(exports, "loadOptions", { enumerable: true, get: function () { return config$1.loadOptions; } }); Object.defineProperty(exports, "loadOptionsSync", { enumerable: true, get: function () { return config$1.loadOptionsSync; } }); Object.defineProperty(exports, "loadOptionsAsync", { enumerable: true, get: function () { return config$1.loadOptionsAsync; } }); Object.defineProperty(exports, "transform", { enumerable: true, get: function () { return transform_1.transform; } }); Object.defineProperty(exports, "transformSync", { enumerable: true, get: function () { return transform_1.transformSync; } }); Object.defineProperty(exports, "transformAsync", { enumerable: true, get: function () { return transform_1.transformAsync; } }); Object.defineProperty(exports, "transformFile", { enumerable: true, get: function () { return transformFile_1.transformFile; } }); Object.defineProperty(exports, "transformFileSync", { enumerable: true, get: function () { return transformFile_1.transformFileSync; } }); Object.defineProperty(exports, "transformFileAsync", { enumerable: true, get: function () { return transformFile_1.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_1.parse; } }); Object.defineProperty(exports, "parseSync", { enumerable: true, get: function () { return parse_1.parseSync; } }); Object.defineProperty(exports, "parseAsync", { enumerable: true, get: function () { return parse_1.parseAsync; } }); exports.types = exports.OptionManager = exports.DEFAULT_EXTENSIONS = void 0; var _file = _interopRequireDefault(file); var _buildExternalHelpers = _interopRequireDefault(buildExternalHelpers); function _types() { const data = _interopRequireWildcard(lib$1); _types = function () { return data; }; return data; } Object.defineProperty(exports, "types", { enumerable: true, get: function () { return _types(); } }); function _parser() { const data = lib$6; _parser = function () { return data; }; return data; } function _traverse() { const data = _interopRequireDefault(lib$a); _traverse = function () { return data; }; return data; } function _template() { const data = _interopRequireDefault(lib$8); _template = function () { return data; }; return data; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } 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$1.loadOptions)(opts); } } exports.OptionManager = OptionManager; function Plugin(alias) { throw new Error(`The (${alias}) Babel 5 plugin is being run with an unsupported Babel version.`); } }); unwrapExports(lib$j); var lib_1$b = lib$j.Plugin; var lib_2$7 = lib$j.types; var lib_3$5 = lib$j.OptionManager; var lib_4$4 = lib$j.DEFAULT_EXTENSIONS; var debugFunc; var phase = 'default'; var namespace = ''; var newDebug = function newDebug() { debugFunc = namespace ? src("fetch-mock:".concat(phase, ":").concat(namespace)) : src("fetch-mock:".concat(phase)); }; var newDebugSandbox = function newDebugSandbox(ns) { return src("fetch-mock:".concat(phase, ":").concat(ns)); }; newDebug(); var debug_1 = { debug: function debug() { debugFunc.apply(void 0, arguments); }, setDebugNamespace: function setDebugNamespace(str) { namespace = str; newDebug(); }, setDebugPhase: function setDebugPhase(str) { phase = str || 'default'; newDebug(); }, getDebug: function getDebug(namespace) { return newDebugSandbox(namespace); } }; var debug = debug_1.debug, setDebugPhase = debug_1.setDebugPhase; var FetchMock = {}; FetchMock.mock = function () { setDebugPhase('setup'); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (args.length) { this.addRoute(args); } return this._mock(); }; FetchMock.addRoute = function (uncompiledRoute) { var _this = this; debug('Adding route', uncompiledRoute); var route = this.compileRoute(uncompiledRoute); var clashes = this.routes.filter(function (_ref) { var identifier = _ref.identifier, method = _ref.method; var isMatch = typeof identifier === 'function' ? identifier === route.identifier : String(identifier) === String(route.identifier); return isMatch && (!method || !route.method || method === route.method); }); if (this.getOption('overwriteRoutes', route) === false || !clashes.length) { this._uncompiledRoutes.push(uncompiledRoute); return this.routes.push(route); } if (this.getOption('overwriteRoutes', route) === true) { clashes.forEach(function (clash) { var index = _this.routes.indexOf(clash); _this._uncompiledRoutes.splice(index, 1, uncompiledRoute); _this.routes.splice(index, 1, route); }); return this.routes; } if (clashes.length) { throw new Error('fetch-mock: Adding route with same name or matcher as existing route. See `overwriteRoutes` option.'); } this._uncompiledRoutes.push(uncompiledRoute); this.routes.push(route); }; FetchMock._mock = function () { if (!this.isSandbox) { // Do this here rather than in the constructor to ensure it's scoped to the test this.realFetch = this.realFetch || this.global.fetch; this.global.fetch = this.fetchHandler; } setDebugPhase(); return this; }; FetchMock["catch"] = function (response) { if (this.fallbackResponse) { console.warn('calling fetchMock.catch() twice - are you sure you want to overwrite the previous fallback response'); // eslint-disable-line } this.fallbackResponse = response || 'ok'; return this._mock(); }; FetchMock.spy = function (route) { // even though ._mock() is called by .mock() and .catch() we still need to // call it here otherwise .getNativeFetch() won't be able to use the reference // to .realFetch that ._mock() sets up this._mock(); return route ? this.mock(route, this.getNativeFetch()) : this["catch"](this.getNativeFetch()); }; var defineShorthand = function defineShorthand(methodName, underlyingMethod, shorthandOptions) { FetchMock[methodName] = function (matcher, response, options) { return this[underlyingMethod](matcher, response, Object.assign(options || {}, shorthandOptions)); }; }; var defineGreedyShorthand = function defineGreedyShorthand(methodName, underlyingMethod) { FetchMock[methodName] = function (response, options) { return this[underlyingMethod]({}, response, options); }; }; defineShorthand('sticky', 'mock', { sticky: true }); defineShorthand('once', 'mock', { repeat: 1 }); defineGreedyShorthand('any', 'mock'); defineGreedyShorthand('anyOnce', 'once'); ['get', 'post', 'put', 'delete', 'head', 'patch'].forEach(function (method) { defineShorthand(method, 'mock', { method: method }); defineShorthand("".concat(method, "Once"), 'once', { method: method }); defineGreedyShorthand("".concat(method, "Any"), method); defineGreedyShorthand("".concat(method, "AnyOnce"), "".concat(method, "Once")); }); var mochaAsyncHookWorkaround = function mochaAsyncHookWorkaround(options) { // HACK workaround for this https://github.com/mochajs/mocha/issues/4280 // Note that it doesn't matter that we call it _before_ carrying out all // the things resetBehavior does as everything in there is synchronous if (typeof options === 'function') { console.warn("Deprecated: Passing fetch-mock reset methods\ndirectly in as handlers for before/after test runner hooks.\nWrap in an arrow function instead e.g. `() => fetchMock.restore()`"); options(); } }; var getRouteRemover = function getRouteRemover(_ref2) { var removeStickyRoutes = _ref2.sticky; return function (routes) { return removeStickyRoutes ? [] : routes.filter(function (_ref3) { var sticky = _ref3.sticky; return sticky; }); }; }; FetchMock.resetBehavior = function () { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; mochaAsyncHookWorkaround(options); var removeRoutes = getRouteRemover(options); this.routes = removeRoutes(this.routes); this._uncompiledRoutes = removeRoutes(this._uncompiledRoutes); if (this.realFetch && !this.routes.length) { this.global.fetch = this.realFetch; this.realFetch = undefined; } this.fallbackResponse = undefined; return this; }; FetchMock.resetHistory = function () { this._calls = []; this._holdingPromises = []; this.routes.forEach(function (route) { return route.reset && route.reset(); }); return this; }; FetchMock.restore = FetchMock.reset = function (options) { this.resetBehavior(options); this.resetHistory(); return this; }; var setUpAndTearDown = FetchMock; var interopRequireDefault = createCommonjsModule(function (module) { function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } module.exports = _interopRequireDefault; }); unwrapExports(interopRequireDefault); function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } var arrayWithHoles = _arrayWithHoles; function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } var iterableToArrayLimit = _iterableToArrayLimit; function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var arrayLikeToArray = _arrayLikeToArray; function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen); } var unsupportedIterableToArray = _unsupportedIterableToArray; function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var nonIterableRest = _nonIterableRest; function _slicedToArray(arr, i) { return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest(); } var slicedToArray = _slicedToArray; var runtime_1 = createCommonjsModule(function (module) { /** * Copyright (c) 2014-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var runtime = (function (exports) { var Op = Object.prototype; var hasOwn = Op.hasOwnProperty; var undefined$1; // More compressible than void 0. var $Symbol = typeof Symbol === "function" ? Symbol : {}; var iteratorSymbol = $Symbol.iterator || "@@iterator"; var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); return obj[key]; } try { // IE 8 has a broken Object.defineProperty that only works on DOM objects. define({}, ""); } catch (err) { define = function(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; var generator = Object.create(protoGenerator.prototype); var context = new Context(tryLocsList || []); // The ._invoke method unifies the implementations of the .next, // .throw, and .return methods. generator._invoke = makeInvokeMethod(innerFn, self, context); return generator; } exports.wrap = wrap; // Try/catch helper to minimize deoptimizations. Returns a completion // record like context.tryEntries[i].completion. This interface could // have been (and was previously) designed to take a closure to be // invoked without arguments, but in all the cases we care about we // already have an existing method we want to call, so there's no need // to create a new function object. We can even get away with assuming // the method takes exactly one argument, since that happens to be true // in every case, so we don't have to touch the arguments object. The // only additional allocation required is the completion record, which // has a stable shape and so hopefully should be cheap to allocate. function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } var GenStateSuspendedStart = "suspendedStart"; var GenStateSuspendedYield = "suspendedYield"; var GenStateExecuting = "executing"; var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as // breaking out of the dispatch switch statement. var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and // .constructor.prototype properties for functions that return Generator // objects. For full spec compliance, you may wish to configure your // minifier not to mangle the names of these two functions. function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} // This is a polyfill for %IteratorPrototype% for environments that // don't natively support it. var IteratorPrototype = {}; IteratorPrototype[iteratorSymbol] = function () { return this; }; var getProto = Object.getPrototypeOf; var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { // This environment has a native %IteratorPrototype%; use it instead // of the polyfill. IteratorPrototype = NativeIteratorPrototype; } var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; GeneratorFunctionPrototype.constructor = GeneratorFunction; GeneratorFunction.displayName = define( GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction" ); // Helper for defining the .next, .throw, and .return methods of the // Iterator interface in terms of a single ._invoke method. function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function(method) { define(prototype, method, function(arg) { return this._invoke(method, arg); }); }); } exports.isGeneratorFunction = function(genFun) { var ctor = typeof genFun === "function" && genFun.constructor; return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can // do is to check its .name property. (ctor.displayName || ctor.name) === "GeneratorFunction" : false; }; exports.mark = function(genFun) { if (Object.setPrototypeOf) { Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); } else { genFun.__proto__ = GeneratorFunctionPrototype; define(genFun, toStringTagSymbol, "GeneratorFunction"); } genFun.prototype = Object.create(Gp); return genFun; }; // Within the body of any async function, `await x` is transformed to // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test // `hasOwn.call(value, "__await")` to determine if the yielded value is // meant to be awaited. exports.awrap = function(arg) { return { __await: arg }; }; function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (record.type === "throw") { reject(record.arg); } else { var result = record.arg; var value = result.value; if (value && typeof value === "object" && hasOwn.call(value, "__await")) { return PromiseImpl.resolve(value.__await).then(function(value) { invoke("next", value, resolve, reject); }, function(err) { invoke("throw", err, resolve, reject); }); } return PromiseImpl.resolve(value).then(function(unwrapped) { // When a yielded Promise is resolved, its final value becomes // the .value of the Promise<{value,done}> result for the // current iteration. result.value = unwrapped; resolve(result); }, function(error) { // If a rejected Promise was yielded, throw the rejection back // into the async generator function so it can be handled there. return invoke("throw", error, resolve, reject); }); } } var previousPromise; function enqueue(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function(resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = // If enqueue has been called before, then we want to wait until // all previous Promises have been resolved before calling invoke, // so that results are always delivered in the correct order. If // enqueue has not been called before, then it is important to // call invoke immediately, without waiting on a callback to fire, // so that the async generator function has the opportunity to do // any necessary setup in a predictable way. This predictability // is why the Promise constructor synchronously invokes its // executor callback, and why async functions synchronously // execute code before the first await. Since we implement simple // async functions in terms of async generators, it is especially // important to get this right, even though it requires care. previousPromise ? previousPromise.then( callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later // invocations of the iterator. callInvokeWithMethodAndArg ) : callInvokeWithMethodAndArg(); } // Define the unified helper method that is used to implement .next, // .throw, and .return (see defineIteratorMethods). this._invoke = enqueue; } defineIteratorMethods(AsyncIterator.prototype); AsyncIterator.prototype[asyncIteratorSymbol] = function () { return this; }; exports.AsyncIterator = AsyncIterator; // Note that simple async functions are implemented on top of // AsyncIterator objects; they just return a Promise for the value of // the final result produced by the iterator. exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) { if (PromiseImpl === void 0) PromiseImpl = Promise; var iter = new AsyncIterator( wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl ); return exports.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator. : iter.next().then(function(result) { return result.done ? result.value : iter.next(); }); }; function makeInvokeMethod(innerFn, self, context) { var state = GenStateSuspendedStart; return function invoke(method, arg) { if (state === GenStateExecuting) { throw new Error("Generator is already running"); } if (state === GenStateCompleted) { if (method === "throw") { throw arg; } // Be forgiving, per 25.3.3.3.3 of the spec: // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume return doneResult(); } context.method = method; context.arg = arg; while (true) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if (context.method === "next") { // Setting context._sent for legacy support of Babel's // function.sent implementation. context.sent = context._sent = context.arg; } else if (context.method === "throw") { if (state === GenStateSuspendedStart) { state = GenStateCompleted; throw context.arg; } context.dispatchException(context.arg); } else if (context.method === "return") { context.abrupt("return", context.arg); } state = GenStateExecuting; var record = tryCatch(innerFn, self, context); if (record.type === "normal") { // If an exception is thrown from innerFn, we leave state === // GenStateExecuting and loop back for another invocation. state = context.done ? GenStateCompleted : GenStateSuspendedYield; if (record.arg === ContinueSentinel) { continue; } return { value: record.arg, done: context.done }; } else if (record.type === "throw") { state = GenStateCompleted; // Dispatch the exception by looping back around to the // context.dispatchException(context.arg) call above. context.method = "throw"; context.arg = record.arg; } } }; } // Call delegate.iterator[context.method](context.arg) and handle the // result, either by returning a { value, done } result from the // delegate iterator, or by modifying context.method and context.arg, // setting context.delegate to null, and returning the ContinueSentinel. function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (method === undefined$1) { // A .throw or .return when the delegate iterator has no .throw // method always terminates the yield* loop. context.delegate = null; if (context.method === "throw") { // Note: ["return"] must be used for ES3 parsing compatibility. if (delegate.iterator["return"]) { // If the delegate iterator has a return method, give it a // chance to clean up. context.method = "return"; context.arg = undefined$1; maybeInvokeDelegate(delegate, context); if (context.method === "throw") { // If maybeInvokeDelegate(context) changed context.method from // "return" to "throw", let that override the TypeError below. return ContinueSentinel; } } context.method = "throw"; context.arg = new TypeError( "The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if (record.type === "throw") { context.method = "throw"; context.arg = record.arg; context.delegate = null; return ContinueSentinel; } var info = record.arg; if (! info) { context.method = "throw"; context.arg = new TypeError("iterator result is not an object"); context.delegate = null; return ContinueSentinel; } if (info.done) { // Assign the result of the finished delegate to the temporary // variable specified by delegate.resultName (see delegateYield). context[delegate.resultName] = info.value; // Resume execution at the desired location (see delegateYield). context.next = delegate.nextLoc; // If context.method was "throw" but the delegate handled the // exception, let the outer generator proceed normally. If // context.method was "next", forget context.arg since it has been // "consumed" by the delegate iterator. If context.method was // "return", allow the original .return call to continue in the // outer generator. if (context.method !== "return") { context.method = "next"; context.arg = undefined$1; } } else { // Re-yield the result returned by the delegate method. return info; } // The delegate iterator is finished, so forget it and continue with // the outer generator. context.delegate = null; return ContinueSentinel; } // Define Generator.prototype.{next,throw,return} in terms of the // unified ._invoke helper method. defineIteratorMethods(Gp); define(Gp, toStringTagSymbol, "Generator"); // A Generator should always return itself as the iterator object when the // @@iterator function is called on it. Some browsers' implementations of the // iterator prototype chain incorrectly implement this, causing the Generator // object to not be returned from this call. This ensures that doesn't happen. // See https://github.com/facebook/regenerator/issues/274 for more details. Gp[iteratorSymbol] = function() { return this; }; Gp.toString = function() { return "[object Generator]"; }; function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; if (1 in locs) { entry.catchLoc = locs[1]; } if (2 in locs) { entry.finallyLoc = locs[2]; entry.afterLoc = locs[3]; } this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal"; delete record.arg; entry.completion = record; } function Context(tryLocsList) { // The root entry object (effectively a try statement without a catch // or a finally block) gives us a place to store values thrown from // locations where there is no enclosing try statement. this.tryEntries = [{ tryLoc: "root" }]; tryLocsList.forEach(pushTryEntry, this); this.reset(true); } exports.keys = function(object) { var keys = []; for (var key in object) { keys.push(key); } keys.reverse(); // Rather than returning an object with a next method, we keep // things simple and return the next function itself. return function next() { while (keys.length) { var key = keys.pop(); if (key in object) { next.value = key; next.done = false; return next; } } // To avoid creating an additional object, we just hang the .value // and .done properties off the next function object itself. This // also ensures that the minifier will not anonymize the function. next.done = true; return next; }; }; function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) { return iteratorMethod.call(iterable); } if (typeof iterable.next === "function") { return iterable; } if (!isNaN(iterable.length)) { var i = -1, next = function next() { while (++i < iterable.length) { if (hasOwn.call(iterable, i)) { next.value = iterable[i]; next.done = false; return next; } } next.value = undefined$1; next.done = true; return next; }; return next.next = next; } } // Return an iterator with no values. return { next: doneResult }; } exports.values = values; function doneResult() { return { value: undefined$1, done: true }; } Context.prototype = { constructor: Context, reset: function(skipTempReset) { this.prev = 0; this.next = 0; // Resetting context._sent for legacy support of Babel's // function.sent implementation. this.sent = this._sent = undefined$1; this.done = false; this.delegate = null; this.method = "next"; this.arg = undefined$1; this.tryEntries.forEach(resetTryEntry); if (!skipTempReset) { for (var name in this) { // Not sure about the optimal order of these conditions: if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) { this[name] = undefined$1; } } } }, stop: function() { this.done = true; var rootEntry = this.tryEntries[0]; var rootRecord = rootEntry.completion; if (rootRecord.type === "throw") { throw rootRecord.arg; } return this.rval; }, dispatchException: function(exception) { if (this.done) { throw exception; } var context = this; function handle(loc, caught) { record.type = "throw"; record.arg = exception; context.next = loc; if (caught) { // If the dispatched exception was caught by a catch block, // then let that catch block handle the exception normally. context.method = "next"; context.arg = undefined$1; } return !! caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; var record = entry.completion; if (entry.tryLoc === "root") { // Exception thrown outside of any try block that could handle // it, so set the completion value of the entire function to // throw the exception. return handle("end"); } if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"); var hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } else if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else if (hasCatch) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } } else if (hasFinally) { if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else { throw new Error("try statement without catch or finally"); } } } }, abrupt: function(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { // Ignore the finally entry if control is not jumping to a // location outside the try/catch block. finallyEntry = null; } var record = finallyEntry ? finallyEntry.completion : {}; record.type = type; record.arg = arg; if (finallyEntry) { this.method = "next"; this.next = finallyEntry.finallyLoc; return ContinueSentinel; } return this.complete(record); }, complete: function(record, afterLoc) { if (record.type === "throw") { throw record.arg; } if (record.type === "break" || record.type === "continue") { this.next = record.arg; } else if (record.type === "return") { this.rval = this.arg = record.arg; this.method = "return"; this.next = "end"; } else if (record.type === "normal" && afterLoc) { this.next = afterLoc; } return ContinueSentinel; }, finish: function(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) { this.complete(entry.completion, entry.afterLoc); resetTryEntry(entry); return ContinueSentinel; } } }, "catch": function(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if (record.type === "throw") { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } // The context.catch method must only be called with a location // argument that corresponds to a known catch block. throw new Error("illegal catch attempt"); }, delegateYield: function(iterable, resultName, nextLoc) { this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }; if (this.method === "next") { // Deliberately forget the last sent value so that we don't // accidentally pass it on to the delegate. this.arg = undefined$1; } return ContinueSentinel; } }; // Regardless of whether this script is executing as a CommonJS module // or not, return the runtime object so that we can declare the variable // regeneratorRuntime in the outer scope, which allows this module to be // injected easily by `bin/regenerator --include-runtime script.js`. return exports; }( // If this script is executing as a CommonJS module, use module.exports // as the regeneratorRuntime namespace. Otherwise create a new empty // object. Either way, the resulting object will be used to initialize // the regeneratorRuntime variable at the top of this file. module.exports )); try { regeneratorRuntime = runtime; } catch (accidentalStrictMode) { // This module should not be running in strict mode, so the above // assignment should always work unless something is misconfigured. Just // in case runtime.js accidentally runs in strict mode, we can escape // strict mode using a global Function call. This could conceivably fail // if a Content Security Policy forbids using Function, but in that case // the proper solution is to fix the accidental strict mode problem. If // you've misconfigured your bundler to force strict mode and applied a // CSP to forbid Function, and you're not willing to fix either of those // problems, please detail your unique predicament in a GitHub issue. Function("r", "regeneratorRuntime = r")(runtime); } }); var regenerator = runtime_1; 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); } } 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); }); }; } var asyncToGenerator = _asyncToGenerator; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var classCallCheck = _classCallCheck; function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } var assertThisInitialized = _assertThisInitialized; var setPrototypeOf = createCommonjsModule(function (module) { function _setPrototypeOf(o, p) { module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } module.exports = _setPrototypeOf; }); 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); } var inherits$2 = _inherits; var _typeof_1 = createCommonjsModule(function (module) { function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { module.exports = _typeof = function _typeof(obj) { return typeof obj; }; } else { module.exports = _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } module.exports = _typeof; }); function _possibleConstructorReturn(self, call) { if (call && (_typeof_1(call) === "object" || typeof call === "function")) { return call; } return assertThisInitialized(self); } var possibleConstructorReturn = _possibleConstructorReturn; var getPrototypeOf = createCommonjsModule(function (module) { function _getPrototypeOf(o) { module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } module.exports = _getPrototypeOf; }); function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } var isNativeFunction = _isNativeFunction; function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } var isNativeReflectConstruct = _isNativeReflectConstruct; var construct = createCommonjsModule(function (module) { function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { module.exports = _construct = Reflect.construct; } else { module.exports = _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } module.exports = _construct; }); var wrapNativeSuper = createCommonjsModule(function (module) { function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; module.exports = _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); } module.exports = _wrapNativeSuper; }); 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 createClass = _createClass; var _typeof2 = interopRequireDefault(_typeof_1); var _classCallCheck2 = interopRequireDefault(classCallCheck); var _createClass2 = interopRequireDefault(createClass); var getDebug = debug_1.getDebug; var responseConfigProps = ['body', 'headers', 'throws', 'status', 'redirectUrl']; var ResponseBuilder = /*#__PURE__*/function () { function ResponseBuilder(options) { (0, _classCallCheck2["default"])(this, ResponseBuilder); this.debug = getDebug('ResponseBuilder()'); this.debug('Response builder created with options', options); Object.assign(this, options); } (0, _createClass2["default"])(ResponseBuilder, [{ key: "exec", value: function exec() { this.debug('building response'); this.normalizeResponseConfig(); this.constructFetchOpts(); this.constructResponseBody(); var realResponse = new this.fetchMock.config.Response(this.body, this.options); var proxyResponse = this.buildObservableResponse(realResponse); return [realResponse, proxyResponse]; } }, { key: "sendAsObject", value: function sendAsObject() { var _this = this; if (responseConfigProps.some(function (prop) { return _this.responseConfig[prop]; })) { if (Object.keys(this.responseConfig).every(function (key) { return responseConfigProps.includes(key); })) { return false; } else { return true; } } else { return true; } } }, { key: "normalizeResponseConfig", value: function normalizeResponseConfig() { // If the response config looks like a status, start to generate a simple response if (typeof this.responseConfig === 'number') { this.debug('building response using status', this.responseConfig); this.responseConfig = { status: this.responseConfig }; // If the response config is not an object, or is an object that doesn't use // any reserved properties, assume it is meant to be the body of the response } else if (typeof this.responseConfig === 'string' || this.sendAsObject()) { this.debug('building text response from', this.responseConfig); this.responseConfig = { body: this.responseConfig }; } } }, { key: "validateStatus", value: function validateStatus(status) { if (!status) { this.debug('No status provided. Defaulting to 200'); return 200; } if (typeof status === 'number' && parseInt(status, 10) !== status && status >= 200 || status < 600) { this.debug('Valid status provided', status); return status; } throw new TypeError("fetch-mock: Invalid status ".concat(status, " passed on response object.\nTo respond with a JSON object that has status as a property assign the object to body\ne.g. {\"body\": {\"status: \"registered\"}}")); } }, { key: "constructFetchOpts", value: function constructFetchOpts() { this.options = this.responseConfig.options || {}; this.options.url = this.responseConfig.redirectUrl || this.url; this.options.status = this.validateStatus(this.responseConfig.status); this.options.statusText = this.fetchMock.statusTextMap[String(this.options.status)]; // Set up response headers. The empty object is to cope with // new Headers(undefined) throwing in Chrome // https://code.google.com/p/chromium/issues/detail?id=335871 this.options.headers = new this.fetchMock.config.Headers(this.responseConfig.headers || {}); } }, { key: "getOption", value: function getOption(name) { return this.fetchMock.getOption(name, this.route); } }, { key: "convertToJson", value: function convertToJson() { // convert to json if we need to if (this.getOption('sendAsJson') && this.responseConfig.body != null && //eslint-disable-line (0, _typeof2["default"])(this.body) === 'object') { this.debug('Stringifying JSON response body'); this.body = JSON.stringify(this.body); if (!this.options.headers.has('Content-Type')) { this.options.headers.set('Content-Type', 'application/json'); } } } }, { key: "setContentLength", value: function setContentLength() { // add a Content-Length header if we need to if (this.getOption('includeContentLength') && typeof this.body === 'string' && !this.options.headers.has('Content-Length')) { this.debug('Setting content-length header:', this.body.length.toString()); this.options.headers.set('Content-Length', this.body.length.toString()); } } }, { key: "constructResponseBody", value: function constructResponseBody() { // start to construct the body this.body = this.responseConfig.body; this.convertToJson(); this.setContentLength(); // On the server we need to manually construct the readable stream for the // Response object (on the client this done automatically) if (this.Stream) { this.debug('Creating response stream'); var stream = new this.Stream.Readable(); if (this.body != null) { //eslint-disable-line stream.push(this.body, 'utf-8'); } stream.push(null); this.body = stream; } this.body = this.body; } }, { key: "buildObservableResponse", value: function buildObservableResponse(response) { var _this2 = this; var fetchMock = this.fetchMock; response._fmResults = {}; // Using a proxy means we can set properties that may not be writable on // the original Response. It also means we can track the resolution of // promises returned by res.json(), res.text() etc this.debug('Wrapping Response in ES proxy for observability'); return new Proxy(response, { get: function get(originalResponse, name) { if (_this2.responseConfig.redirectUrl) { if (name === 'url') { _this2.debug('Retrieving redirect url', _this2.responseConfig.redirectUrl); return _this2.responseConfig.redirectUrl; } if (name === 'redirected') { _this2.debug('Retrieving redirected status', true); return true; } } if (typeof originalResponse[name] === 'function') { _this2.debug('Wrapping body promises in ES proxies for observability'); return new Proxy(originalResponse[name], { apply: function apply(func, thisArg, args) { _this2.debug("Calling res.".concat(name)); var result = func.apply(response, args); if (result.then) { fetchMock._holdingPromises.push(result["catch"](function () { return null; })); originalResponse._fmResults[name] = result; } return result; } }); } return originalResponse[name]; } }); } }]); return ResponseBuilder; }(); var responseBuilder = function (options) { return new ResponseBuilder(options).exec(); }; function _defineProperty$1(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var defineProperty$1 = _defineProperty$1; function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return arrayLikeToArray(arr); } var arrayWithoutHoles = _arrayWithoutHoles; function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } var iterableToArray = _iterableToArray; function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var nonIterableSpread = _nonIterableSpread; function _toConsumableArray(arr) { return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread(); } var toConsumableArray = _toConsumableArray; var _typeof2$1 = interopRequireDefault(_typeof_1); var _regenerator = interopRequireDefault(regenerator); var _asyncToGenerator2 = interopRequireDefault(asyncToGenerator); var _defineProperty2 = interopRequireDefault(defineProperty$1); var _slicedToArray2 = interopRequireDefault(slicedToArray); var _toConsumableArray2 = interopRequireDefault(toConsumableArray); var URL; // https://stackoverflow.com/a/19709846/308237 // split, URL constructor does not support protocol-relative urls var absoluteUrlRX = new RegExp('^[a-z]+://', 'i'); var protocolRelativeUrlRX = new RegExp('^//', 'i'); var headersToArray = function headersToArray(headers) { // node-fetch 1 Headers if (typeof headers.raw === 'function') { return Object.entries(headers.raw()); } else if (headers[Symbol.iterator]) { return (0, _toConsumableArray2["default"])(headers); } else { return Object.entries(headers); } }; var zipObject = function zipObject(entries) { return entries.reduce(function (obj, _ref) { var _ref2 = (0, _slicedToArray2["default"])(_ref, 2), key = _ref2[0], val = _ref2[1]; return Object.assign(obj, (0, _defineProperty2["default"])({}, key, val)); }, {}); }; var normalizeUrl = function normalizeUrl(url) { if (typeof url === 'function' || url instanceof RegExp || /^(begin|end|glob|express|path)\:/.test(url)) { return url; } if (absoluteUrlRX.test(url)) { var u = new URL(url); return u.href; } else if (protocolRelativeUrlRX.test(url)) { var _u = new URL(url, 'http://dummy'); return _u.href; } else { var _u2 = new URL(url, 'http://dummy'); return _u2.pathname + _u2.search; } }; var extractBody = /*#__PURE__*/function () { var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(request) { return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.prev = 0; if (!('body' in request)) { _context.next = 3; break; } return _context.abrupt("return", request.body.toString()); case 3: return _context.abrupt("return", request.clone().text()); case 6: _context.prev = 6; _context.t0 = _context["catch"](0); case 8: case "end": return _context.stop(); } } }, _callee, null, [[0, 6]]); })); return function extractBody(_x) { return _ref3.apply(this, arguments); }; }(); var requestUtils = { setUrlImplementation: function setUrlImplementation(it) { URL = it; }, normalizeRequest: function normalizeRequest(url, options, Request) { if (Request.prototype.isPrototypeOf(url)) { var derivedOptions = { method: url.method }; var body = extractBody(url); if (typeof body !== 'undefined') { derivedOptions.body = body; } var normalizedRequestObject = { url: normalizeUrl(url.url), options: Object.assign(derivedOptions, options), request: url, signal: options && options.signal || url.signal }; var headers = headersToArray(url.headers); if (headers.length) { normalizedRequestObject.options.headers = zipObject(headers); } return normalizedRequestObject; } else if (typeof url === 'string' || // horrible URL object duck-typing (0, _typeof2$1["default"])(url) === 'object' && 'href' in url) { return { url: normalizeUrl(url), options: options, signal: options && options.signal }; } else if ((0, _typeof2$1["default"])(url) === 'object') { throw new TypeError('fetch-mock: Unrecognised Request object. Read the Config and Installation sections of the docs'); } else { throw new TypeError('fetch-mock: Invalid arguments passed to fetch'); } }, normalizeUrl: normalizeUrl, getPath: function getPath(url) { var u = absoluteUrlRX.test(url) ? new URL(url) : new URL(url, 'http://dummy'); return u.pathname; }, getQuery: function getQuery(url) { var u = absoluteUrlRX.test(url) ? new URL(url) : new URL(url, 'http://dummy'); return u.search ? u.search.substr(1) : ''; }, headers: { normalize: function normalize(headers) { return zipObject(headersToArray(headers)); }, toLowerCase: function toLowerCase(headers) { return Object.keys(headers).reduce(function (obj, k) { obj[k.toLowerCase()] = headers[k]; return obj; }, {}); }, equal: function equal(actualHeader, expectedHeader) { actualHeader = Array.isArray(actualHeader) ? actualHeader : [actualHeader]; expectedHeader = Array.isArray(expectedHeader) ? expectedHeader : [expectedHeader]; if (actualHeader.length !== expectedHeader.length) { return false; } return actualHeader.every(function (val, i) { return val === expectedHeader[i]; }); } } }; var _slicedToArray2$1 = interopRequireDefault(slicedToArray); var _regenerator$1 = interopRequireDefault(regenerator); var _asyncToGenerator2$1 = interopRequireDefault(asyncToGenerator); var _classCallCheck2$1 = interopRequireDefault(classCallCheck); var _assertThisInitialized2 = interopRequireDefault(assertThisInitialized); var _inherits2 = interopRequireDefault(inherits$2); var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); var _wrapNativeSuper2 = interopRequireDefault(wrapNativeSuper); function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } var debug$1 = debug_1.debug, setDebugPhase$1 = debug_1.setDebugPhase, getDebug$1 = debug_1.getDebug; var FetchMock$1 = {}; // see https://heycam.github.io/webidl/#aborterror for the standardised interface // Note that this differs slightly from node-fetch var AbortError = /*#__PURE__*/function (_Error) { (0, _inherits2["default"])(AbortError, _Error); var _super = _createSuper(AbortError); function AbortError() { var _this; (0, _classCallCheck2$1["default"])(this, AbortError); _this = _super.apply(this, arguments); _this.name = 'AbortError'; _this.message = 'The operation was aborted.'; // Do not include this class in the stacktrace if (Error.captureStackTrace) { Error.captureStackTrace((0, _assertThisInitialized2["default"])(_this), _this.constructor); } return _this; } return AbortError; }( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(Error)); // Patch native fetch to avoid "NotSupportedError:ReadableStream uploading is not supported" in Safari. // See also https://github.com/wheresrhys/fetch-mock/issues/584 // See also https://stackoverflow.com/a/50952018/1273406 var patchNativeFetchForSafari = function patchNativeFetchForSafari(nativeFetch) { // Try to patch fetch only on Safari if (typeof navigator === 'undefined' || !navigator.vendor || navigator.vendor !== 'Apple Computer, Inc.') { return nativeFetch; } // It seems the code is working on Safari thus patch native fetch to avoid the error. return /*#__PURE__*/function () { var _ref = (0, _asyncToGenerator2$1["default"])( /*#__PURE__*/_regenerator$1["default"].mark(function _callee(request) { var method, body, cache, credentials, headers, integrity, mode, redirect, referrer, init; return _regenerator$1["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: method = request.method; if (['POST', 'PUT', 'PATCH'].includes(method)) { _context.next = 3; break; } return _context.abrupt("return", nativeFetch(request)); case 3: _context.next = 5; return request.clone().text(); case 5: body = _context.sent; cache = request.cache, credentials = request.credentials, headers = request.headers, integrity = request.integrity, mode = request.mode, redirect = request.redirect, referrer = request.referrer; init = { body: body, cache: cache, credentials: credentials, headers: headers, integrity: integrity, mode: mode, redirect: redirect, referrer: referrer, method: method }; return _context.abrupt("return", nativeFetch(request.url, init)); case 9: case "end": return _context.stop(); } } }, _callee); })); return function (_x) { return _ref.apply(this, arguments); }; }(); }; var resolve$3 = /*#__PURE__*/function () { var _ref2 = (0, _asyncToGenerator2$1["default"])( /*#__PURE__*/_regenerator$1["default"].mark(function _callee2(_ref3, url, options, request) { var response, _ref3$responseIsFetch, responseIsFetch, debug; return _regenerator$1["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: response = _ref3.response, _ref3$responseIsFetch = _ref3.responseIsFetch, responseIsFetch = _ref3$responseIsFetch === void 0 ? false : _ref3$responseIsFetch; debug = getDebug$1('resolve()'); debug('Recursively resolving function and promise responses'); // We want to allow things like // - function returning a Promise for a response // - delaying (using a timeout Promise) a function's execution to generate // a response // Because of this we can't safely check for function before Promisey-ness, // or vice versa. So to keep it DRY, and flexible, we keep trying until we // have something that looks like neither Promise nor function case 3: if (!(typeof response === 'function')) { _context2.next = 18; break; } debug(' Response is a function'); // in the case of falling back to the network we need to make sure we're using // the original Request instance, not our normalised url + options if (!responseIsFetch) { _context2.next = 14; break; } if (!request) { _context2.next = 10; break; } debug(' -> Calling fetch with Request instance'); return _context2.abrupt("return", response(request)); case 10: debug(' -> Calling fetch with url and options'); return _context2.abrupt("return", response(url, options)); case 14: debug(' -> Calling response function'); response = response(url, options, request); case 16: _context2.next = 29; break; case 18: if (!(typeof response.then === 'function')) { _context2.next = 26; break; } debug(' Response is a promise'); debug(' -> Resolving promise'); _context2.next = 23; return response; case 23: response = _context2.sent; _context2.next = 29; break; case 26: debug(' Response is not a function or a promise'); debug(' -> Exiting response resolution recursion'); return _context2.abrupt("return", response); case 29: _context2.next = 3; break; case 31: case "end": return _context2.stop(); } } }, _callee2); })); return function resolve(_x2, _x3, _x4, _x5) { return _ref2.apply(this, arguments); }; }(); FetchMock$1.needsAsyncBodyExtraction = function (_ref4) { var request = _ref4.request; return request && this.routes.some(function (_ref5) { var usesBody = _ref5.usesBody; return usesBody; }); }; FetchMock$1.fetchHandler = function (url, options) { setDebugPhase$1('handle'); var debug = getDebug$1('fetchHandler()'); debug('fetch called with:', url, options); var normalizedRequest = requestUtils.normalizeRequest(url, options, this.config.Request); debug('Request normalised'); debug(' url', normalizedRequest.url); debug(' options', normalizedRequest.options); debug(' request', normalizedRequest.request); debug(' signal', normalizedRequest.signal); if (this.needsAsyncBodyExtraction(normalizedRequest)) { debug('Need to wait for Body to be streamed before calling router: switching to async mode'); return this._extractBodyThenHandle(normalizedRequest); } return this._fetchHandler(normalizedRequest); }; FetchMock$1._extractBodyThenHandle = /*#__PURE__*/function () { var _ref6 = (0, _asyncToGenerator2$1["default"])( /*#__PURE__*/_regenerator$1["default"].mark(function _callee3(normalizedRequest) { return _regenerator$1["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return normalizedRequest.options.body; case 2: normalizedRequest.options.body = _context3.sent; return _context3.abrupt("return", this._fetchHandler(normalizedRequest)); case 4: case "end": return _context3.stop(); } } }, _callee3, this); })); return function (_x6) { return _ref6.apply(this, arguments); }; }(); FetchMock$1._fetchHandler = function (_ref7) { var _this2 = this; var url = _ref7.url, options = _ref7.options, request = _ref7.request, signal = _ref7.signal; var _this$executeRouter = this.executeRouter(url, options, request), route = _this$executeRouter.route, callLog = _this$executeRouter.callLog; this.recordCall(callLog); // this is used to power the .flush() method var done; this._holdingPromises.push(new this.config.Promise(function (res) { return done = res; })); // wrapped in this promise to make sure we respect custom Promise // constructors defined by the user return new this.config.Promise(function (res, rej) { if (signal) { debug$1('signal exists - enabling fetch abort'); var abort = function abort() { debug$1('aborting fetch'); // note that DOMException is not available in node.js; // even node-fetch uses a custom error class: // https://github.com/bitinn/node-fetch/blob/master/src/abort-error.js rej(typeof DOMException !== 'undefined' ? new DOMException('The operation was aborted.', 'AbortError') : new AbortError()); done(); }; if (signal.aborted) { debug$1('signal is already aborted - aborting the fetch'); abort(); } signal.addEventListener('abort', abort); } _this2.generateResponse({ route: route, url: url, options: options, request: request, callLog: callLog }).then(res, rej).then(done, done).then(function () { setDebugPhase$1(); }); }); }; FetchMock$1.fetchHandler.isMock = true; FetchMock$1.executeRouter = function (url, options, request) { var debug = getDebug$1('executeRouter()'); var callLog = { url: url, options: options, request: request, isUnmatched: true }; debug("Attempting to match request to a route"); if (this.getOption('fallbackToNetwork') === 'always') { debug(' Configured with fallbackToNetwork=always - passing through to fetch'); return { route: { response: this.getNativeFetch(), responseIsFetch: true } // BUG - this callLog never used to get sent. Discovered the bug // but can't fix outside a major release as it will potentially // cause too much disruption // // callLog, }; } var route = this.router(url, options, request); if (route) { debug(' Matching route found'); return { route: route, callLog: { url: url, options: options, request: request, identifier: route.identifier } }; } if (this.getOption('warnOnFallback')) { console.warn("Unmatched ".concat(options && options.method || 'GET', " to ").concat(url)); // eslint-disable-line } if (this.fallbackResponse) { debug(' No matching route found - using fallbackResponse'); return { route: { response: this.fallbackResponse }, callLog: callLog }; } if (!this.getOption('fallbackToNetwork')) { throw new Error("fetch-mock: No fallback response defined for ".concat(options && options.method || 'GET', " to ").concat(url)); } debug(' Configured to fallbackToNetwork - passing through to fetch'); return { route: { response: this.getNativeFetch(), responseIsFetch: true }, callLog: callLog }; }; FetchMock$1.generateResponse = /*#__PURE__*/function () { var _ref8 = (0, _asyncToGenerator2$1["default"])( /*#__PURE__*/_regenerator$1["default"].mark(function _callee4(_ref9) { var route, url, options, request, _ref9$callLog, callLog, debug, response, _responseBuilder, _responseBuilder2, realResponse, finalResponse; return _regenerator$1["default"].wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: route = _ref9.route, url = _ref9.url, options = _ref9.options, request = _ref9.request, _ref9$callLog = _ref9.callLog, callLog = _ref9$callLog === void 0 ? {} : _ref9$callLog; debug = getDebug$1('generateResponse()'); _context4.next = 4; return resolve$3(route, url, options, request); case 4: response = _context4.sent; if (!(response["throws"] && typeof response !== 'function')) { _context4.next = 8; break; } debug('response.throws is defined - throwing an error'); throw response["throws"]; case 8: if (!this.config.Response.prototype.isPrototypeOf(response)) { _context4.next = 12; break; } debug('response is already a Response instance - returning it'); callLog.response = response; return _context4.abrupt("return", response); case 12: // finally, if we need to convert config into a response, we do it _responseBuilder = responseBuilder({ url: url, responseConfig: response, fetchMock: this, route: route }), _responseBuilder2 = (0, _slicedToArray2$1["default"])(_responseBuilder, 2), realResponse = _responseBuilder2[0], finalResponse = _responseBuilder2[1]; callLog.response = realResponse; return _context4.abrupt("return", finalResponse); case 15: case "end": return _context4.stop(); } } }, _callee4, this); })); return function (_x7) { return _ref8.apply(this, arguments); }; }(); FetchMock$1.router = function (url, options, request) { var route = this.routes.find(function (route, i) { debug$1("Trying to match route ".concat(i)); return route.matcher(url, options, request); }); if (route) { return route; } }; FetchMock$1.getNativeFetch = function () { var func = this.realFetch || this.isSandbox && this.config.fetch; if (!func) { throw new Error('fetch-mock: Falling back to network only available on global fetch-mock, or by setting config.fetch on sandboxed fetch-mock'); } return patchNativeFetchForSafari(func); }; FetchMock$1.recordCall = function (obj) { debug$1('Recording fetch call', obj); if (obj) { this._calls.push(obj); } }; var fetchHandler = FetchMock$1; var globToRegexp = function (glob, opts) { if (typeof glob !== 'string') { throw new TypeError('Expected a string'); } var str = String(glob); // The regexp we are building, as a string. var reStr = ""; // Whether we are matching so called "extended" globs (like bash) and should // support single character matching, matching ranges of characters, group // matching, etc. var extended = opts ? !!opts.extended : false; // When globstar is _false_ (default), '/foo/*' is translated a regexp like // '^\/foo\/.*$' which will match any string beginning with '/foo/' // When globstar is _true_, '/foo/*' is translated to regexp like // '^\/foo\/[^/]*$' which will match any string beginning with '/foo/' BUT // which does not have a '/' to the right of it. // E.g. with '/foo/*' these will match: '/foo/bar', '/foo/bar.txt' but // these will not '/foo/bar/baz', '/foo/bar/baz.txt' // Lastely, when globstar is _true_, '/foo/**' is equivelant to '/foo/*' when // globstar is _false_ var globstar = opts ? !!opts.globstar : false; // If we are doing extended matching, this boolean is true when we are inside // a group (eg {*.html,*.js}), and false otherwise. var inGroup = false; // RegExp flags (eg "i" ) to pass in to RegExp constructor. var flags = opts && typeof( opts.flags ) === "string" ? opts.flags : ""; var c; for (var i = 0, len = str.length; i < len; i++) { c = str[i]; switch (c) { case "/": case "$": case "^": case "+": case ".": case "(": case ")": case "=": case "!": case "|": reStr += "\\" + c; break; case "?": if (extended) { reStr += "."; break; } case "[": case "]": if (extended) { reStr += c; break; } case "{": if (extended) { inGroup = true; reStr += "("; break; } case "}": if (extended) { inGroup = false; reStr += ")"; break; } case ",": if (inGroup) { reStr += "|"; break; } reStr += "\\" + c; break; case "*": // Move over all consecutive "*"'s. // Also store the previous and next characters var prevChar = str[i - 1]; var starCount = 1; while(str[i + 1] === "*") { starCount++; i++; } var nextChar = str[i + 1]; if (!globstar) { // globstar is disabled, so treat any number of "*" as one reStr += ".*"; } else { // globstar is enabled, so determine if this is a globstar segment var isGlobstar = starCount > 1 // multiple "*"'s && (prevChar === "/" || prevChar === undefined) // from the start of the segment && (nextChar === "/" || nextChar === undefined); // to the end of the segment if (isGlobstar) { // it's a globstar, so match zero or more path segments reStr += "((?:[^/]*(?:\/|$))*)"; i++; // move over the "/" } else { // it's not a globstar, so only match one path segment reStr += "([^/]*)"; } } break; default: reStr += c; } } // When regexp 'g' flag is specified don't // constrain the regular expression with ^ & $ if (!flags || !~flags.indexOf('g')) { reStr = "^" + reStr + "$"; } return new RegExp(reStr, flags); }; /** * Expose `pathToRegexp`. */ var pathToRegexp_1 = pathToRegexp; var parse_1$1 = parse$6; var compile_1 = compile; var tokensToFunction_1 = tokensToFunction; var tokensToRegExp_1 = tokensToRegExp; /** * Default configs. */ var DEFAULT_DELIMITER = '/'; var DEFAULT_DELIMITERS = './'; /** * The main path matching regexp utility. * * @type {RegExp} */ var PATH_REGEXP = new RegExp([ // Match escaped characters that would otherwise appear in future matches. // This allows the user to escape special characters that won't transform. '(\\\\.)', // Match Express-style parameters and un-named parameters with a prefix // and optional suffixes. Matches appear as: // // ":test(\\d+)?" => ["test", "\d+", undefined, "?"] // "(\\d+)" => [undefined, undefined, "\d+", undefined] '(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?' ].join('|'), 'g'); /** * Parse a string for the raw tokens. * * @param {string} str * @param {Object=} options * @return {!Array} */ function parse$6 (str, options) { var tokens = []; var key = 0; var index = 0; var path = ''; var defaultDelimiter = (options && options.delimiter) || DEFAULT_DELIMITER; var delimiters = (options && options.delimiters) || DEFAULT_DELIMITERS; var pathEscaped = false; var res; while ((res = PATH_REGEXP.exec(str)) !== null) { var m = res[0]; var escaped = res[1]; var offset = res.index; path += str.slice(index, offset); index = offset + m.length; // Ignore already escaped sequences. if (escaped) { path += escaped[1]; pathEscaped = true; continue } var prev = ''; var next = str[index]; var name = res[2]; var capture = res[3]; var group = res[4]; var modifier = res[5]; if (!pathEscaped && path.length) { var k = path.length - 1; if (delimiters.indexOf(path[k]) > -1) { prev = path[k]; path = path.slice(0, k); } } // Push the current path onto the tokens. if (path) { tokens.push(path); path = ''; pathEscaped = false; } var partial = prev !== '' && next !== undefined && next !== prev; var repeat = modifier === '+' || modifier === '*'; var optional = modifier === '?' || modifier === '*'; var delimiter = prev || defaultDelimiter; var pattern = capture || group; tokens.push({ name: name || key++, prefix: prev, delimiter: delimiter, optional: optional, repeat: repeat, partial: partial, pattern: pattern ? escapeGroup(pattern) : '[^' + escapeString(delimiter) + ']+?' }); } // Push any remaining characters. if (path || index < str.length) { tokens.push(path + str.substr(index)); } return tokens } /** * Compile a string to a template function for the path. * * @param {string} str * @param {Object=} options * @return {!function(Object=, Object=)} */ function compile (str, options) { return tokensToFunction(parse$6(str, options)) } /** * Expose a method for transforming tokens into the path function. */ function tokensToFunction (tokens) { // Compile all the tokens into regexps. var matches = new Array(tokens.length); // Compile all the patterns before compilation. for (var i = 0; i < tokens.length; i++) { if (typeof tokens[i] === 'object') { matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$'); } } return function (data, options) { var path = ''; var encode = (options && options.encode) || encodeURIComponent; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (typeof token === 'string') { path += token; continue } var value = data ? data[token.name] : undefined; var segment; if (Array.isArray(value)) { if (!token.repeat) { throw new TypeError('Expected "' + token.name + '" to not repeat, but got array') } if (value.length === 0) { if (token.optional) continue throw new TypeError('Expected "' + token.name + '" to not be empty') } for (var j = 0; j < value.length; j++) { segment = encode(value[j], token); if (!matches[i].test(segment)) { throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '"') } path += (j === 0 ? token.prefix : token.delimiter) + segment; } continue } if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { segment = encode(String(value), token); if (!matches[i].test(segment)) { throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but got "' + segment + '"') } path += token.prefix + segment; continue } if (token.optional) { // Prepend partial segment prefixes. if (token.partial) path += token.prefix; continue } throw new TypeError('Expected "' + token.name + '" to be ' + (token.repeat ? 'an array' : 'a string')) } return path } } /** * Escape a regular expression string. * * @param {string} str * @return {string} */ function escapeString (str) { return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, '\\$1') } /** * Escape the capturing group by escaping special characters and meaning. * * @param {string} group * @return {string} */ function escapeGroup (group) { return group.replace(/([=!:$/()])/g, '\\$1') } /** * Get the flags for a regexp from the options. * * @param {Object} options * @return {string} */ function flags (options) { return options && options.sensitive ? '' : 'i' } /** * Pull out keys from a regexp. * * @param {!RegExp} path * @param {Array=} keys * @return {!RegExp} */ function regexpToRegexp (path, keys) { if (!keys) return path // Use a negative lookahead to match only capturing groups. var groups = path.source.match(/\((?!\?)/g); if (groups) { for (var i = 0; i < groups.length; i++) { keys.push({ name: i, prefix: null, delimiter: null, optional: false, repeat: false, partial: false, pattern: null }); } } return path } /** * Transform an array into a regexp. * * @param {!Array} path * @param {Array=} keys * @param {Object=} options * @return {!RegExp} */ function arrayToRegexp (path, keys, options) { var parts = []; for (var i = 0; i < path.length; i++) { parts.push(pathToRegexp(path[i], keys, options).source); } return new RegExp('(?:' + parts.join('|') + ')', flags(options)) } /** * Create a path regexp from string input. * * @param {string} path * @param {Array=} keys * @param {Object=} options * @return {!RegExp} */ function stringToRegexp (path, keys, options) { return tokensToRegExp(parse$6(path, options), keys, options) } /** * Expose a function for taking tokens and returning a RegExp. * * @param {!Array} tokens * @param {Array=} keys * @param {Object=} options * @return {!RegExp} */ function tokensToRegExp (tokens, keys, options) { options = options || {}; var strict = options.strict; var start = options.start !== false; var end = options.end !== false; var delimiter = escapeString(options.delimiter || DEFAULT_DELIMITER); var delimiters = options.delimiters || DEFAULT_DELIMITERS; var endsWith = [].concat(options.endsWith || []).map(escapeString).concat('$').join('|'); var route = start ? '^' : ''; var isEndDelimited = tokens.length === 0; // Iterate over the tokens and create our regexp string. for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (typeof token === 'string') { route += escapeString(token); isEndDelimited = i === tokens.length - 1 && delimiters.indexOf(token[token.length - 1]) > -1; } else { var capture = token.repeat ? '(?:' + token.pattern + ')(?:' + escapeString(token.delimiter) + '(?:' + token.pattern + '))*' : token.pattern; if (keys) keys.push(token); if (token.optional) { if (token.partial) { route += escapeString(token.prefix) + '(' + capture + ')?'; } else { route += '(?:' + escapeString(token.prefix) + '(' + capture + '))?'; } } else { route += escapeString(token.prefix) + '(' + capture + ')'; } } } if (end) { if (!strict) route += '(?:' + delimiter + ')?'; route += endsWith === '$' ? '$' : '(?=' + endsWith + ')'; } else { if (!strict) route += '(?:' + delimiter + '(?=' + endsWith + '))?'; if (!isEndDelimited) route += '(?=' + delimiter + '|' + endsWith + ')'; } return new RegExp(route, flags(options)) } /** * Normalize the given path string, returning a regular expression. * * An empty array can be passed in for the keys, which will hold the * placeholder key descriptions. For example, using `/user/:id`, `keys` will * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`. * * @param {(string|RegExp|Array)} path * @param {Array=} keys * @param {Object=} options * @return {!RegExp} */ function pathToRegexp (path, keys, options) { if (path instanceof RegExp) { return regexpToRegexp(path, keys) } if (Array.isArray(path)) { return arrayToRegexp(/** @type {!Array} */ (path), keys, options) } return stringToRegexp(/** @type {string} */ (path), keys, options) } pathToRegexp_1.parse = parse_1$1; pathToRegexp_1.compile = compile_1; pathToRegexp_1.tokensToFunction = tokensToFunction_1; pathToRegexp_1.tokensToRegExp = tokensToRegExp_1; var isSubset_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, '__esModule', { value: true }); /** * Check if an object is contained within another object. * * Returns `true` if: * - all enumerable keys of *subset* are also enumerable in *superset*, and * - every value assigned to an enumerable key of *subset* strictly equals * the value assigned to the same key of *superset* – or is a subset of it. * * @param {Object} superset * @param {Object} subset * * @returns {Boolean} * * @module is-subset * @function default * @alias isSubset */ var isSubset = (function (_isSubset) { function isSubset(_x, _x2) { return _isSubset.apply(this, arguments); } isSubset.toString = function () { return _isSubset.toString(); }; return isSubset; })(function (superset, subset) { if (typeof superset !== 'object' || superset === null || (typeof subset !== 'object' || subset === null)) return false; return Object.keys(subset).every(function (key) { if (!superset.propertyIsEnumerable(key)) return false; var subsetItem = subset[key]; var supersetItem = superset[key]; if (typeof subsetItem === 'object' && subsetItem !== null ? !isSubset(supersetItem, subsetItem) : supersetItem !== subsetItem) return false; return true; }); }); exports['default'] = isSubset; module.exports = exports['default']; }); unwrapExports(isSubset_1); var lodash_isequal = createCommonjsModule(function (module, exports) { /** * Lodash (Custom Build) <https://lodash.com/> * Build: `lodash modularize exports="npm" -o ./` * Copyright JS Foundation and other contributors <https://js.foundation/> * Released under MIT license <https://lodash.com/license> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', asyncTag = '[object AsyncFunction]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', nullTag = '[object Null]', objectTag = '[object Object]', promiseTag = '[object Promise]', proxyTag = '[object Proxy]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', undefinedTag = '[object Undefined]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** Detect free variable `exports`. */ var freeExports = exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); /* Node.js helper references. */ var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } /** Used for built-in method references. */ var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; /** Used to detect overreaching core-js shims. */ var coreJsData = root['__core-js_shared__']; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** Built-in value references. */ var Buffer = moduleExports ? root.Buffer : undefined, Symbol = root.Symbol, Uint8Array = root.Uint8Array, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, symToStringTag = Symbol ? Symbol.toStringTag : undefined; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols, nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, nativeKeys = overArg(Object.keys, Object); /* Built-in method references that are verified to be native. */ var DataView = getNative(root, 'DataView'), Map = getNative(root, 'Map'), Promise = getNative(root, 'Promise'), Set = getNative(root, 'Set'), WeakMap = getNative(root, 'WeakMap'), nativeCreate = getNative(Object, 'create'); /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; this.size = 0; } /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); } /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new MapCache; while (++index < length) { this.add(values[index]); } } /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; this.size = 0; } /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. isIndex(key, length) ))) { result.push(key); } } return result; } /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); objTag = objTag == argsTag ? objectTag : objTag; othTag = othTag == argsTag ? objectTag : othTag; var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && isBuffer(object)) { if (!isBuffer(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new Stack); return (objIsArr || isTypedArray(object)) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index = -1, result = true, seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!arraySome(other, function(othValue, othIndex) { if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray : function(object) { if (object == null) { return []; } object = Object(object); return arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable.call(object, symbol); }); }; /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (typeof value == 'number' || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse; /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are compared by strict equality, i.e. `===`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return baseIsEqual(value, other); } /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } module.exports = isEqual; }); var querystring$2 = getCjsExportFromNamespace(qs$1); var _defineProperty2$1 = interopRequireDefault(defineProperty$1); var debug$2 = debug_1.debug; var headerUtils = requestUtils.headers, getPath = requestUtils.getPath, getQuery = requestUtils.getQuery, normalizeUrl$1 = requestUtils.normalizeUrl; var debuggableUrlFunc = function debuggableUrlFunc(func) { return function (url) { debug$2('Actual url:', url); return func(url); }; }; var stringMatchers = { begin: function begin(targetString) { return debuggableUrlFunc(function (url) { return url.indexOf(targetString) === 0; }); }, end: function end(targetString) { return debuggableUrlFunc(function (url) { return url.substr(-targetString.length) === targetString; }); }, glob: function glob(targetString) { var urlRX = globToRegexp(targetString); return debuggableUrlFunc(function (url) { return urlRX.test(url); }); }, express: function express(targetString) { var urlRX = pathToRegexp_1(targetString); return debuggableUrlFunc(function (url) { return urlRX.test(getPath(url)); }); }, path: function path(targetString) { return debuggableUrlFunc(function (url) { return getPath(url) === targetString; }); } }; var getHeaderMatcher = function getHeaderMatcher(_ref) { var expectedHeaders = _ref.headers; debug$2('Generating header matcher'); if (!expectedHeaders) { debug$2(' No header expectations defined - skipping'); return; } var expectation = headerUtils.toLowerCase(expectedHeaders); debug$2(' Expected headers:', expectation); return function (url, _ref2) { var _ref2$headers = _ref2.headers, headers = _ref2$headers === void 0 ? {} : _ref2$headers; debug$2('Attempting to match headers'); var lowerCaseHeaders = headerUtils.toLowerCase(headerUtils.normalize(headers)); debug$2(' Expected headers:', expectation); debug$2(' Actual headers:', lowerCaseHeaders); return Object.keys(expectation).every(function (headerName) { return headerUtils.equal(lowerCaseHeaders[headerName], expectation[headerName]); }); }; }; var getMethodMatcher = function getMethodMatcher(_ref3) { var expectedMethod = _ref3.method; debug$2('Generating method matcher'); if (!expectedMethod) { debug$2(' No method expectations defined - skipping'); return; } debug$2(' Expected method:', expectedMethod); return function (url, _ref4) { var method = _ref4.method; debug$2('Attempting to match method'); var actualMethod = method ? method.toLowerCase() : 'get'; debug$2(' Expected method:', expectedMethod); debug$2(' Actual method:', actualMethod); return expectedMethod === actualMethod; }; }; var getQueryStringMatcher = function getQueryStringMatcher(_ref5) { var passedQuery = _ref5.query; debug$2('Generating query parameters matcher'); if (!passedQuery) { debug$2(' No query parameters expectations defined - skipping'); return; } var expectedQuery = querystring$2.parse(querystring$2.stringify(passedQuery)); debug$2(' Expected query parameters:', passedQuery); var keys = Object.keys(expectedQuery); return function (url) { debug$2('Attempting to match query parameters'); var query = querystring$2.parse(getQuery(url)); debug$2(' Expected query parameters:', expectedQuery); debug$2(' Actual query parameters:', query); return keys.every(function (key) { if (Array.isArray(query[key])) { if (!Array.isArray(expectedQuery[key])) { return false; } else { return lodash_isequal(query[key].sort(), expectedQuery[key].sort()); } } return query[key] === expectedQuery[key]; }); }; }; var getParamsMatcher = function getParamsMatcher(_ref6) { var expectedParams = _ref6.params, matcherUrl = _ref6.url; debug$2('Generating path parameters matcher'); if (!expectedParams) { debug$2(' No path parameters expectations defined - skipping'); return; } if (!/express:/.test(matcherUrl)) { throw new Error('fetch-mock: matching on params is only possible when using an express: matcher'); } debug$2(' Expected path parameters:', expectedParams); var expectedKeys = Object.keys(expectedParams); var keys = []; var re = pathToRegexp_1(matcherUrl.replace(/^express:/, ''), keys); return function (url) { debug$2('Attempting to match path parameters'); var vals = re.exec(getPath(url)) || []; vals.shift(); var params = keys.reduce(function (map, _ref7, i) { var name = _ref7.name; return vals[i] ? Object.assign(map, (0, _defineProperty2$1["default"])({}, name, vals[i])) : map; }, {}); debug$2(' Expected path parameters:', expectedParams); debug$2(' Actual path parameters:', params); return expectedKeys.every(function (key) { return params[key] === expectedParams[key]; }); }; }; var getBodyMatcher = function getBodyMatcher(route, fetchMock) { var matchPartialBody = fetchMock.getOption('matchPartialBody', route); var expectedBody = route.body; debug$2('Generating body matcher'); return function (url, _ref8) { var body = _ref8.body, _ref8$method = _ref8.method, method = _ref8$method === void 0 ? 'get' : _ref8$method; debug$2('Attempting to match body'); if (method.toLowerCase() === 'get') { debug$2(' GET request - skip matching body'); // GET requests don’t send a body so the body matcher should be ignored for them return true; } var sentBody; try { debug$2(' Parsing request body as JSON'); sentBody = JSON.parse(body); } catch (err) { debug$2(' Failed to parse request body as JSON', err); } debug$2('Expected body:', expectedBody); debug$2('Actual body:', sentBody); if (matchPartialBody) { debug$2('matchPartialBody is true - checking for partial match only'); } return sentBody && (matchPartialBody ? isSubset_1(sentBody, expectedBody) : lodash_isequal(sentBody, expectedBody)); }; }; var getFullUrlMatcher = function getFullUrlMatcher(route, matcherUrl, query) { // if none of the special syntaxes apply, it's just a simple string match // but we have to be careful to normalize the url we check and the name // of the route to allow for e.g. http://it.at.there being indistinguishable // from http://it.at.there/ once we start generating Request/Url objects debug$2(' Matching using full url', matcherUrl); var expectedUrl = normalizeUrl$1(matcherUrl); debug$2(' Normalised url to:', matcherUrl); if (route.identifier === matcherUrl) { debug$2(' Updating route identifier to match normalized url:', matcherUrl); route.identifier = expectedUrl; } return function (matcherUrl) { debug$2('Expected url:', expectedUrl); debug$2('Actual url:', matcherUrl); if (query && expectedUrl.indexOf('?')) { debug$2('Ignoring query string when matching url'); return matcherUrl.indexOf(expectedUrl) === 0; } return normalizeUrl$1(matcherUrl) === expectedUrl; }; }; var getFunctionMatcher = function getFunctionMatcher(_ref9) { var functionMatcher = _ref9.functionMatcher; debug$2('Detected user defined function matcher', functionMatcher); return function () { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } debug$2('Calling function matcher with arguments', args); return functionMatcher.apply(void 0, args); }; }; var getUrlMatcher = function getUrlMatcher(route) { debug$2('Generating url matcher'); var matcherUrl = route.url, query = route.query; if (matcherUrl === '*') { debug$2(' Using universal * rule to match any url'); return function () { return true; }; } if (matcherUrl instanceof RegExp) { debug$2(' Using regular expression to match url:', matcherUrl); return function (url) { return matcherUrl.test(url); }; } if (matcherUrl.href) { debug$2(" Using URL object to match url", matcherUrl); return getFullUrlMatcher(route, matcherUrl.href, query); } for (var shorthand in stringMatchers) { if (matcherUrl.indexOf(shorthand + ':') === 0) { debug$2(" Using ".concat(shorthand, ": pattern to match url"), matcherUrl); var urlFragment = matcherUrl.replace(new RegExp("^".concat(shorthand, ":")), ''); return stringMatchers[shorthand](urlFragment); } } return getFullUrlMatcher(route, matcherUrl, query); }; var matchers = [{ name: 'query', matcher: getQueryStringMatcher }, { name: 'method', matcher: getMethodMatcher }, { name: 'headers', matcher: getHeaderMatcher }, { name: 'params', matcher: getParamsMatcher }, { name: 'body', matcher: getBodyMatcher, usesBody: true }, { name: 'functionMatcher', matcher: getFunctionMatcher }, { name: 'url', matcher: getUrlMatcher }]; var _slicedToArray2$2 = interopRequireDefault(slicedToArray); var _classCallCheck2$2 = interopRequireDefault(classCallCheck); var _createClass2$1 = interopRequireDefault(createClass); var _typeof2$2 = interopRequireDefault(_typeof_1); var debug$3 = debug_1.debug, setDebugNamespace = debug_1.setDebugNamespace, getDebug$2 = debug_1.getDebug; var isUrlMatcher = function isUrlMatcher(matcher) { return matcher instanceof RegExp || typeof matcher === 'string' || (0, _typeof2$2["default"])(matcher) === 'object' && 'href' in matcher; }; var isFunctionMatcher = function isFunctionMatcher(matcher) { return typeof matcher === 'function'; }; var Route = /*#__PURE__*/function () { function Route(args, fetchMock) { (0, _classCallCheck2$2["default"])(this, Route); this.fetchMock = fetchMock; var debug = getDebug$2('compileRoute()'); debug('Compiling route'); this.init(args); this.sanitize(); this.validate(); this.generateMatcher(); this.limit(); this.delayResponse(); } (0, _createClass2$1["default"])(Route, [{ key: "validate", value: function validate() { var _this = this; if (!('response' in this)) { throw new Error('fetch-mock: Each route must define a response'); } if (!Route.registeredMatchers.some(function (_ref) { var name = _ref.name; return name in _this; })) { throw new Error("fetch-mock: Each route must specify some criteria for matching calls to fetch. To match all calls use '*'"); } } }, { key: "init", value: function init(args) { var _args = (0, _slicedToArray2$2["default"])(args, 3), matcher = _args[0], response = _args[1], _args$ = _args[2], options = _args$ === void 0 ? {} : _args$; var routeConfig = {}; if (isUrlMatcher(matcher) || isFunctionMatcher(matcher)) { routeConfig.matcher = matcher; } else { Object.assign(routeConfig, matcher); } if (typeof response !== 'undefined') { routeConfig.response = response; } Object.assign(routeConfig, options); Object.assign(this, routeConfig); } }, { key: "sanitize", value: function sanitize() { var debug = getDebug$2('sanitize()'); debug('Sanitizing route properties'); if (this.method) { debug("Converting method ".concat(this.method, " to lower case")); this.method = this.method.toLowerCase(); } if (isUrlMatcher(this.matcher)) { debug('Mock uses a url matcher', this.matcher); this.url = this.matcher; delete this.matcher; } this.functionMatcher = this.matcher || this.functionMatcher; debug('Setting route.identifier...'); debug(" route.name is ".concat(this.name)); debug(" route.url is ".concat(this.url)); debug(" route.functionMatcher is ".concat(this.functionMatcher)); this.identifier = this.name || this.url || this.functionMatcher; debug(" -> route.identifier set to ".concat(this.identifier)); } }, { key: "generateMatcher", value: function generateMatcher() { var _this2 = this; setDebugNamespace('generateMatcher()'); debug$3('Compiling matcher for route'); var activeMatchers = Route.registeredMatchers.map(function (_ref2) { var name = _ref2.name, matcher = _ref2.matcher, usesBody = _ref2.usesBody; return _this2[name] && { matcher: matcher(_this2, _this2.fetchMock), usesBody: usesBody }; }).filter(function (matcher) { return Boolean(matcher); }); this.usesBody = activeMatchers.some(function (_ref3) { var usesBody = _ref3.usesBody; return usesBody; }); debug$3('Compiled matcher for route'); setDebugNamespace(); this.matcher = function (url) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var request = arguments.length > 2 ? arguments[2] : undefined; return activeMatchers.every(function (_ref4) { var matcher = _ref4.matcher; return matcher(url, options, request); }); }; } }, { key: "limit", value: function limit() { var _this3 = this; var debug = getDebug$2('limit()'); debug('Limiting number of requests to handle by route'); if (!this.repeat) { debug(' No `repeat` value set on route. Will match any number of requests'); return; } debug(" Route set to repeat ".concat(this.repeat, " times")); var matcher = this.matcher; var timesLeft = this.repeat; this.matcher = function (url, options) { var match = timesLeft && matcher(url, options); if (match) { timesLeft--; return true; } }; this.reset = function () { return timesLeft = _this3.repeat; }; } }, { key: "delayResponse", value: function delayResponse() { var _this4 = this; var debug = getDebug$2('delayResponse()'); debug("Applying response delay settings"); if (this.delay) { debug(" Wrapping response in delay of ".concat(this.delay, " miliseconds")); var response = this.response; this.response = function () { debug("Delaying response by ".concat(_this4.delay, " miliseconds")); return new Promise(function (res) { return setTimeout(function () { return res(response); }, _this4.delay); }); }; } else { debug(" No delay set on route. Will respond 'immediately' (but asynchronously)"); } } }], [{ key: "addMatcher", value: function addMatcher(matcher) { Route.registeredMatchers.push(matcher); } }]); return Route; }(); Route.registeredMatchers = []; matchers.forEach(Route.addMatcher); var Route_1 = Route; var _regenerator$2 = interopRequireDefault(regenerator); var _asyncToGenerator2$2 = interopRequireDefault(asyncToGenerator); var _slicedToArray2$3 = interopRequireDefault(slicedToArray); var _toConsumableArray2$1 = interopRequireDefault(toConsumableArray); var setDebugPhase$2 = debug_1.setDebugPhase, setDebugNamespace$1 = debug_1.setDebugNamespace, debug$4 = debug_1.debug; var normalizeUrl$2 = requestUtils.normalizeUrl; var FetchMock$2 = {}; var isName = function isName(nameOrMatcher) { return typeof nameOrMatcher === 'string' && /^[\da-zA-Z\-]+$/.test(nameOrMatcher); }; var filterCallsWithMatcher = function filterCallsWithMatcher(matcher) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var calls = arguments.length > 2 ? arguments[2] : undefined; var _Route = new Route_1([Object.assign({ matcher: matcher, response: 'ok' }, options)], this); matcher = _Route.matcher; return calls.filter(function (_ref) { var url = _ref.url, options = _ref.options; return matcher(normalizeUrl$2(url), options); }); }; var formatDebug = function formatDebug(func) { return function () { setDebugPhase$2('inspect'); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var result = func.call.apply(func, [this].concat(args)); setDebugPhase$2(); return result; }; }; var callObjToArray = function callObjToArray(obj) { if (!obj) { return undefined; } var url = obj.url, options = obj.options, request = obj.request, identifier = obj.identifier, isUnmatched = obj.isUnmatched, response = obj.response; var arr = [url, options]; arr.request = request; arr.identifier = identifier; arr.isUnmatched = isUnmatched; arr.response = response; return arr; }; FetchMock$2.filterCalls = function (nameOrMatcher, options) { debug$4('Filtering fetch calls'); var calls = this._calls; var matcher = '*'; if ([true, 'matched'].includes(nameOrMatcher)) { debug$4("Filter provided is ".concat(nameOrMatcher, ". Returning matched calls only")); calls = calls.filter(function (_ref2) { var isUnmatched = _ref2.isUnmatched; return !isUnmatched; }); } else if ([false, 'unmatched'].includes(nameOrMatcher)) { debug$4("Filter provided is ".concat(nameOrMatcher, ". Returning unmatched calls only")); calls = calls.filter(function (_ref3) { var isUnmatched = _ref3.isUnmatched; return isUnmatched; }); } else if (typeof nameOrMatcher === 'undefined') { debug$4("Filter provided is undefined. Returning all calls"); calls = calls; } else if (isName(nameOrMatcher)) { debug$4("Filter provided, looks like the name of a named route. Returning only calls handled by that route"); calls = calls.filter(function (_ref4) { var identifier = _ref4.identifier; return identifier === nameOrMatcher; }); } else { matcher = nameOrMatcher === '*' ? '*' : normalizeUrl$2(nameOrMatcher); if (this.routes.some(function (_ref5) { var identifier = _ref5.identifier; return identifier === matcher; })) { debug$4("Filter provided, ".concat(nameOrMatcher, ", identifies a route. Returning only calls handled by that route")); calls = calls.filter(function (call) { return call.identifier === matcher; }); } } if ((options || matcher !== '*') && calls.length) { if (typeof options === 'string') { options = { method: options }; } debug$4('Compiling filter and options to route in order to filter all calls', nameOrMatcher); calls = filterCallsWithMatcher.call(this, matcher, options, calls); } debug$4("Retrieved ".concat(calls.length, " calls")); return calls.map(callObjToArray); }; FetchMock$2.calls = formatDebug(function (nameOrMatcher, options) { debug$4('retrieving matching calls'); return this.filterCalls(nameOrMatcher, options); }); FetchMock$2.lastCall = formatDebug(function (nameOrMatcher, options) { debug$4('retrieving last matching call'); return (0, _toConsumableArray2$1["default"])(this.filterCalls(nameOrMatcher, options)).pop(); }); FetchMock$2.lastUrl = formatDebug(function (nameOrMatcher, options) { debug$4('retrieving url of last matching call'); return (this.lastCall(nameOrMatcher, options) || [])[0]; }); FetchMock$2.lastOptions = formatDebug(function (nameOrMatcher, options) { debug$4('retrieving options of last matching call'); return (this.lastCall(nameOrMatcher, options) || [])[1]; }); FetchMock$2.lastResponse = formatDebug(function (nameOrMatcher, options) { debug$4('retrieving respose of last matching call'); console.warn("When doing all the following:\n- using node-fetch\n- responding with a real network response (using spy() or fallbackToNetwork)\n- using `fetchMock.LastResponse()`\n- awaiting the body content\n... the response will hang unless your source code also awaits the response body.\nThis is an unavoidable consequence of the nodejs implementation of streams.\n"); var response = (this.lastCall(nameOrMatcher, options) || []).response; try { var clonedResponse = response.clone(); return clonedResponse; } catch (err) { Object.entries(response._fmResults).forEach(function (_ref6) { var _ref7 = (0, _slicedToArray2$3["default"])(_ref6, 2), name = _ref7[0], result = _ref7[1]; response[name] = function () { return result; }; }); return response; } }); FetchMock$2.called = formatDebug(function (nameOrMatcher, options) { debug$4('checking if matching call was made'); return Boolean(this.filterCalls(nameOrMatcher, options).length); }); FetchMock$2.flush = formatDebug( /*#__PURE__*/function () { var _ref8 = (0, _asyncToGenerator2$2["default"])( /*#__PURE__*/_regenerator$2["default"].mark(function _callee(waitForResponseMethods) { var queuedPromises; return _regenerator$2["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: setDebugNamespace$1('flush'); debug$4("flushing all fetch calls. ".concat(waitForResponseMethods ? '' : 'Not ', "waiting for response bodies to complete download")); queuedPromises = this._holdingPromises; this._holdingPromises = []; debug$4("".concat(queuedPromises.length, " fetch calls to be awaited")); _context.next = 7; return Promise.all(queuedPromises); case 7: debug$4("All fetch calls have completed"); if (!(waitForResponseMethods && this._holdingPromises.length)) { _context.next = 13; break; } debug$4("Awaiting all fetch bodies to download"); _context.next = 12; return this.flush(waitForResponseMethods); case 12: debug$4("All fetch bodies have completed downloading"); case 13: setDebugNamespace$1(); case 14: case "end": return _context.stop(); } } }, _callee, this); })); return function (_x) { return _ref8.apply(this, arguments); }; }()); FetchMock$2.done = formatDebug(function (nameOrMatcher) { var _this = this; setDebugPhase$2('inspect'); setDebugNamespace$1('done'); debug$4('Checking to see if expected calls have been made'); var routesToCheck; if (nameOrMatcher && typeof nameOrMatcher !== 'boolean') { debug$4('Checking to see if expected calls have been made for single route:', nameOrMatcher); routesToCheck = [{ identifier: nameOrMatcher }]; } else { debug$4('Checking to see if expected calls have been made for all routes'); routesToCheck = this.routes; } // Can't use array.every because would exit after first failure, which would // break the logging var result = routesToCheck.map(function (_ref9) { var identifier = _ref9.identifier; if (!_this.called(identifier)) { debug$4('No calls made for route:', identifier); console.warn("Warning: ".concat(identifier, " not called")); // eslint-disable-line return false; } var expectedTimes = (_this.routes.find(function (r) { return r.identifier === identifier; }) || {}).repeat; if (!expectedTimes) { debug$4('Route has been called at least once, and no expectation of more set:', identifier); return true; } var actualTimes = _this.filterCalls(identifier).length; debug$4("Route called ".concat(actualTimes, " times:"), identifier); if (expectedTimes > actualTimes) { debug$4("Route called ".concat(actualTimes, " times, but expected ").concat(expectedTimes, ":"), identifier); console.warn("Warning: ".concat(identifier, " only called ").concat(actualTimes, " times, but ").concat(expectedTimes, " expected")); // eslint-disable-line return false; } else { return true; } }).every(function (isDone) { return isDone; }); setDebugNamespace$1(); setDebugPhase$2(); return result; }); var inspecting = FetchMock$2; var debug$5 = debug_1.debug; var FetchMock$3 = Object.assign({}, fetchHandler, setUpAndTearDown, inspecting); FetchMock$3.addMatcher = function (matcher) { Route_1.addMatcher(matcher); }; FetchMock$3.config = { fallbackToNetwork: false, includeContentLength: true, sendAsJson: true, warnOnFallback: true, overwriteRoutes: undefined }; FetchMock$3.createInstance = function () { var _this = this; debug$5('Creating fetch-mock instance'); var instance = Object.create(FetchMock$3); instance._uncompiledRoutes = (this._uncompiledRoutes || []).slice(); instance.routes = instance._uncompiledRoutes.map(function (config) { return _this.compileRoute(config); }); instance.fallbackResponse = this.fallbackResponse || undefined; instance.config = Object.assign({}, this.config || FetchMock$3.config); instance._calls = []; instance._holdingPromises = []; instance.bindMethods(); return instance; }; FetchMock$3.compileRoute = function (config) { return new Route_1(config, this); }; FetchMock$3.bindMethods = function () { this.fetchHandler = FetchMock$3.fetchHandler.bind(this); this.reset = this.restore = FetchMock$3.reset.bind(this); this.resetHistory = FetchMock$3.resetHistory.bind(this); this.resetBehavior = FetchMock$3.resetBehavior.bind(this); }; FetchMock$3.sandbox = function () { debug$5('Creating sandboxed fetch-mock instance'); // this construct allows us to create a fetch-mock instance which is also // a callable function, while circumventing circularity when defining the // object that this function should be bound to var fetchMockProxy = function fetchMockProxy(url, options) { return sandbox.fetchHandler(url, options); }; var sandbox = Object.assign(fetchMockProxy, // Ensures that the entire returned object is a callable function FetchMock$3, // prototype methods this.createInstance(), // instance data { Headers: this.config.Headers, Request: this.config.Request, Response: this.config.Response }); sandbox.bindMethods(); sandbox.isSandbox = true; sandbox["default"] = sandbox; return sandbox; }; FetchMock$3.getOption = function (name) { var route = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return name in route ? route[name] : this.config[name]; }; var lib$k = FetchMock$3; var statusTextMap = { 100: 'Continue', 101: 'Switching Protocols', 102: 'Processing', 200: 'OK', 201: 'Created', 202: 'Accepted', 203: 'Non-Authoritative Information', 204: 'No Content', 205: 'Reset Content', 206: 'Partial Content', 207: 'Multi-Status', 208: 'Already Reported', 226: 'IM Used', 300: 'Multiple Choices', 301: 'Moved Permanently', 302: 'Found', 303: 'See Other', 304: 'Not Modified', 305: 'Use Proxy', 307: 'Temporary Redirect', 308: 'Permanent Redirect', 400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Required', 403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed', 406: 'Not Acceptable', 407: 'Proxy Authentication Required', 408: 'Request Timeout', 409: 'Conflict', 410: 'Gone', 411: 'Length Required', 412: 'Precondition Failed', 413: 'Payload Too Large', 414: 'URI Too Long', 415: 'Unsupported Media Type', 416: 'Range Not Satisfiable', 417: 'Expectation Failed', 418: "I'm a teapot", 421: 'Misdirected Request', 422: 'Unprocessable Entity', 423: 'Locked', 424: 'Failed Dependency', 425: 'Unordered Collection', 426: 'Upgrade Required', 428: 'Precondition Required', 429: 'Too Many Requests', 431: 'Request Header Fields Too Large', 451: 'Unavailable For Legal Reasons', 500: 'Internal Server Error', 501: 'Not Implemented', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Gateway Timeout', 505: 'HTTP Version Not Supported', 506: 'Variant Also Negotiates', 507: 'Insufficient Storage', 508: 'Loop Detected', 509: 'Bandwidth Limit Exceeded', 510: 'Not Extended', 511: 'Network Authentication Required' }; var statusText = statusTextMap; var theGlobal = typeof window !== 'undefined' ? window : self; var setUrlImplementation = requestUtils.setUrlImplementation; setUrlImplementation(theGlobal.URL); lib$k.global = theGlobal; lib$k.statusTextMap = statusText; lib$k.config = Object.assign(lib$k.config, { Promise: theGlobal.Promise, Request: theGlobal.Request, Response: theGlobal.Response, Headers: theGlobal.Headers }); var client = lib$k.createInstance(); lib$j.transform('code', { plugins: ['transform-runtime'] }); var clientLegacy = client; return clientLegacy; })));
Save File
Cancel